ncd.c 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772
  1. /**
  2. * @file ncd.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * 3. Neither the name of the author nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. */
  29. #include <stdint.h>
  30. #include <stdio.h>
  31. #include <string.h>
  32. #include <stdlib.h>
  33. #include <misc/version.h>
  34. #include <misc/loglevel.h>
  35. #include <misc/offset.h>
  36. #include <misc/read_file.h>
  37. #include <misc/balloc.h>
  38. #include <misc/concat_strings.h>
  39. #include <misc/string_begins_with.h>
  40. #include <misc/parse_number.h>
  41. #include <misc/open_standard_streams.h>
  42. #include <misc/expstring.h>
  43. #include <misc/split_string.h>
  44. #include <structure/LinkedList1.h>
  45. #include <base/BLog.h>
  46. #include <base/BLog_syslog.h>
  47. #include <system/BReactor.h>
  48. #include <system/BSignal.h>
  49. #include <system/BConnection.h>
  50. #include <system/BProcess.h>
  51. #include <udevmonitor/NCDUdevManager.h>
  52. #include <ncd/NCDConfigParser.h>
  53. #include <ncd/NCDModule.h>
  54. #include <ncd/NCDModuleIndex.h>
  55. #include <ncd/NCDSugar.h>
  56. #include <ncd/modules/modules.h>
  57. #include <ncd/ncd.h>
  58. #include <generated/blog_channel_ncd.h>
  59. #define LOGGER_STDOUT 1
  60. #define LOGGER_STDERR 2
  61. #define LOGGER_SYSLOG 3
  62. #define ARG_VALUE_TYPE_STRING 1
  63. #define ARG_VALUE_TYPE_VARIABLE 2
  64. #define ARG_VALUE_TYPE_LIST 3
  65. #define ARG_VALUE_TYPE_MAP 4
  66. #define SSTATE_CHILD 1
  67. #define SSTATE_ADULT 2
  68. #define SSTATE_DYING 3
  69. #define SSTATE_FORGOTTEN 4
  70. #define PSTATE_WORKING 1
  71. #define PSTATE_UP 2
  72. #define PSTATE_WAITING 3
  73. #define PSTATE_TERMINATING 4
  74. struct arg_value {
  75. int type;
  76. union {
  77. struct {
  78. char *string;
  79. size_t string_len;
  80. };
  81. char **variable_names;
  82. LinkedList1 list;
  83. LinkedList1 maplist;
  84. };
  85. };
  86. struct arg_list_elem {
  87. LinkedList1Node list_node;
  88. struct arg_value value;
  89. };
  90. struct arg_map_elem {
  91. LinkedList1Node maplist_node;
  92. struct arg_value key;
  93. struct arg_value val;
  94. };
  95. struct statement {
  96. char **object_names;
  97. char *method_name;
  98. struct arg_value args;
  99. char *name;
  100. };
  101. struct process {
  102. NCDModuleProcess *module_process;
  103. char *name;
  104. size_t num_statements;
  105. struct process_statement *statements;
  106. int state;
  107. size_t ap;
  108. size_t fp;
  109. BTimer wait_timer;
  110. BPending advance_job;
  111. BPending work_job;
  112. LinkedList1Node list_node; // node in processes
  113. };
  114. struct process_statement {
  115. struct process *p;
  116. size_t i;
  117. struct statement s;
  118. int state;
  119. int have_error;
  120. btime_t error_until;
  121. NCDModuleInst inst;
  122. NCDValue inst_args;
  123. };
  124. // command-line options
  125. struct {
  126. int help;
  127. int version;
  128. int logger;
  129. char *logger_syslog_facility;
  130. char *logger_syslog_ident;
  131. int loglevel;
  132. int loglevels[BLOG_NUM_CHANNELS];
  133. char *config_file;
  134. int retry_time;
  135. int no_udev;
  136. char **extra_args;
  137. int num_extra_args;
  138. } options;
  139. // reactor
  140. BReactor ss;
  141. // are we terminating
  142. int terminating;
  143. int main_exit_code;
  144. // process manager
  145. BProcessManager manager;
  146. // udev manager
  147. NCDUdevManager umanager;
  148. // module index
  149. NCDModuleIndex mindex;
  150. // program AST
  151. NCDProgram program;
  152. // common module parameters
  153. struct NCDModuleInst_params module_params;
  154. struct NCDModuleInst_iparams module_iparams;
  155. // processes
  156. LinkedList1 processes;
  157. static void print_help (const char *name);
  158. static void print_version (void);
  159. static int parse_arguments (int argc, char *argv[]);
  160. static void signal_handler (void *unused);
  161. static void start_terminate (int exit_code);
  162. static int arg_value_init_string (struct arg_value *o, const char *string, size_t len);
  163. static int arg_value_init_variable (struct arg_value *o, const char *name);
  164. static void arg_value_init_list (struct arg_value *o);
  165. static int arg_value_list_append (struct arg_value *o, struct arg_value v);
  166. static void arg_value_init_map (struct arg_value *o);
  167. static int arg_value_map_append (struct arg_value *o, struct arg_value key, struct arg_value val);
  168. static void arg_value_free (struct arg_value *o);
  169. static int build_arg_from_ast (struct arg_value *o, NCDValue *val_ast);
  170. static char ** names_new (const char *name);
  171. static size_t names_count (char **names);
  172. static char * names_tostring (char **names);
  173. static void names_free (char **names);
  174. static int statement_init (struct statement *s, NCDStatement *stmt_ast);
  175. static void statement_free (struct statement *s);
  176. static int process_new (NCDProcess *proc_ast, NCDModuleProcess *module_process);
  177. static void process_free (struct process *p);
  178. static void process_start_terminating (struct process *p);
  179. static void process_free_statements (struct process *p);
  180. static size_t process_rap (struct process *p);
  181. static void process_assert_pointers (struct process *p);
  182. static void process_logfunc (struct process *p);
  183. static void process_log (struct process *p, int level, const char *fmt, ...);
  184. static void process_schedule_work (struct process *p);
  185. static void process_work_job_handler (struct process *p);
  186. static void process_advance_job_handler (struct process *p);
  187. static void process_wait_timer_handler (struct process *p);
  188. static int process_find_object (struct process *p, size_t pos, const char *name, NCDObject *out_object);
  189. static int process_resolve_object_expr (struct process *p, size_t pos, char **names, NCDObject *out_object);
  190. static int process_resolve_variable_expr (struct process *p, size_t pos, char **names, NCDValue *out_value);
  191. static void process_statement_logfunc (struct process_statement *ps);
  192. static void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...);
  193. static void process_statement_set_error (struct process_statement *ps);
  194. static int process_statement_resolve_argument (struct process_statement *ps, struct arg_value *arg, NCDValue *out);
  195. static void process_statement_instance_func_event (struct process_statement *ps, int event);
  196. static int process_statement_instance_func_getobj (struct process_statement *ps, const char *objname, NCDObject *out_object);
  197. static int process_statement_instance_func_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name);
  198. static void process_statement_instance_logfunc (struct process_statement *ps);
  199. static void process_statement_instance_func_interp_exit (struct process_statement *ps, int exit_code);
  200. static int process_statement_instance_func_interp_getargs (struct process_statement *ps, NCDValue *out_value);
  201. static btime_t process_statement_instance_func_interp_getretrytime (struct process_statement *ps);
  202. static void process_moduleprocess_func_event (struct process *p, int event);
  203. static int process_moduleprocess_func_getobj (struct process *p, const char *name, NCDObject *out_object);
  204. int main (int argc, char **argv)
  205. {
  206. if (argc <= 0) {
  207. return 1;
  208. }
  209. // set exit code
  210. main_exit_code = 1;
  211. // open standard streams
  212. open_standard_streams();
  213. // parse command-line arguments
  214. if (!parse_arguments(argc, argv)) {
  215. fprintf(stderr, "Failed to parse arguments\n");
  216. print_help(argv[0]);
  217. goto fail0;
  218. }
  219. // handle --help and --version
  220. if (options.help) {
  221. print_version();
  222. print_help(argv[0]);
  223. return 0;
  224. }
  225. if (options.version) {
  226. print_version();
  227. return 0;
  228. }
  229. // initialize logger
  230. switch (options.logger) {
  231. case LOGGER_STDOUT:
  232. BLog_InitStdout();
  233. break;
  234. case LOGGER_STDERR:
  235. BLog_InitStderr();
  236. break;
  237. case LOGGER_SYSLOG:
  238. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  239. fprintf(stderr, "Failed to initialize syslog logger\n");
  240. goto fail0;
  241. }
  242. break;
  243. default:
  244. ASSERT(0);
  245. }
  246. // configure logger channels
  247. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  248. if (options.loglevels[i] >= 0) {
  249. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  250. }
  251. else if (options.loglevel >= 0) {
  252. BLog_SetChannelLoglevel(i, options.loglevel);
  253. }
  254. }
  255. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  256. // initialize network
  257. if (!BNetwork_GlobalInit()) {
  258. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  259. goto fail1;
  260. }
  261. // init time
  262. BTime_Init();
  263. // init reactor
  264. if (!BReactor_Init(&ss)) {
  265. BLog(BLOG_ERROR, "BReactor_Init failed");
  266. goto fail1;
  267. }
  268. // set not terminating
  269. terminating = 0;
  270. // init process manager
  271. if (!BProcessManager_Init(&manager, &ss)) {
  272. BLog(BLOG_ERROR, "BProcessManager_Init failed");
  273. goto fail1a;
  274. }
  275. // init udev manager
  276. NCDUdevManager_Init(&umanager, options.no_udev, &ss, &manager);
  277. // init module index
  278. NCDModuleIndex_Init(&mindex);
  279. // add module groups to index
  280. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  281. if (!NCDModuleIndex_AddGroup(&mindex, *g)) {
  282. BLog(BLOG_ERROR, "NCDModuleIndex_AddGroup failed");
  283. goto fail2;
  284. }
  285. }
  286. // setup signal handler
  287. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  288. BLog(BLOG_ERROR, "BSignal_Init failed");
  289. goto fail2;
  290. }
  291. // read config file
  292. uint8_t *file;
  293. size_t file_len;
  294. if (!read_file(options.config_file, &file, &file_len)) {
  295. BLog(BLOG_ERROR, "failed to read config file");
  296. goto fail3;
  297. }
  298. // parse config file
  299. if (!NCDConfigParser_Parse((char *)file, file_len, &program)) {
  300. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  301. free(file);
  302. goto fail3;
  303. }
  304. // fee config file memory
  305. free(file);
  306. // desugar
  307. if (!NCDSugar_Desugar(&program)) {
  308. BLog(BLOG_ERROR, "NCDSugar_Desugar failed");
  309. goto fail4;
  310. }
  311. // init module params
  312. struct NCDModuleInitParams params;
  313. params.reactor = &ss;
  314. params.manager = &manager;
  315. params.umanager = &umanager;
  316. // init modules
  317. size_t num_inited_modules = 0;
  318. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  319. if ((*g)->func_globalinit && !(*g)->func_globalinit(params)) {
  320. BLog(BLOG_ERROR, "globalinit failed for some module");
  321. goto fail5;
  322. }
  323. num_inited_modules++;
  324. }
  325. // init common module params
  326. module_params.func_event = (NCDModuleInst_func_event)process_statement_instance_func_event;
  327. module_params.func_getobj = (NCDModuleInst_func_getobj)process_statement_instance_func_getobj;
  328. module_params.logfunc = (BLog_logfunc)process_statement_instance_logfunc;
  329. module_iparams.reactor = &ss;
  330. module_iparams.manager = &manager;
  331. module_iparams.umanager = &umanager;
  332. module_iparams.func_initprocess = (NCDModuleInst_func_initprocess)process_statement_instance_func_initprocess;
  333. module_iparams.func_interp_exit = (NCDModuleInst_func_interp_exit)process_statement_instance_func_interp_exit;
  334. module_iparams.func_interp_getargs = (NCDModuleInst_func_interp_getargs)process_statement_instance_func_interp_getargs;
  335. module_iparams.func_interp_getretrytime = (NCDModuleInst_func_interp_getretrytime)process_statement_instance_func_interp_getretrytime;
  336. // init processes list
  337. LinkedList1_Init(&processes);
  338. // init processes
  339. for (NCDProcess *p = NCDProgram_FirstProcess(&program); p; p = NCDProgram_NextProcess(&program, p)) {
  340. if (NCDProcess_IsTemplate(p)) {
  341. continue;
  342. }
  343. if (!process_new(p, NULL)) {
  344. BLog(BLOG_ERROR, "failed to initialize process, exiting");
  345. goto fail6;
  346. }
  347. }
  348. // enter event loop
  349. BLog(BLOG_NOTICE, "entering event loop");
  350. BReactor_Exec(&ss);
  351. ASSERT(LinkedList1_IsEmpty(&processes))
  352. fail6:;
  353. LinkedList1Node *ln;
  354. while (ln = LinkedList1_GetFirst(&processes)) {
  355. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  356. process_free(p);
  357. }
  358. fail5:
  359. // free modules
  360. while (num_inited_modules > 0) {
  361. const struct NCDModuleGroup **g = &ncd_modules[num_inited_modules - 1];
  362. if ((*g)->func_globalfree) {
  363. (*g)->func_globalfree();
  364. }
  365. num_inited_modules--;
  366. }
  367. fail4:
  368. // free program AST
  369. NCDProgram_Free(&program);
  370. fail3:
  371. // remove signal handler
  372. BSignal_Finish();
  373. fail2:
  374. // free module index
  375. NCDModuleIndex_Free(&mindex);
  376. // free udev manager
  377. NCDUdevManager_Free(&umanager);
  378. // free process manager
  379. BProcessManager_Free(&manager);
  380. fail1a:
  381. // free reactor
  382. BReactor_Free(&ss);
  383. fail1:
  384. // free logger
  385. BLog(BLOG_NOTICE, "exiting");
  386. BLog_Free();
  387. fail0:
  388. // finish objects
  389. DebugObjectGlobal_Finish();
  390. return main_exit_code;
  391. }
  392. void print_help (const char *name)
  393. {
  394. printf(
  395. "Usage:\n"
  396. " %s\n"
  397. " [--help]\n"
  398. " [--version]\n"
  399. " [--logger <stdout/stderr/syslog>]\n"
  400. " (logger=syslog?\n"
  401. " [--syslog-facility <string>]\n"
  402. " [--syslog-ident <string>]\n"
  403. " )\n"
  404. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  405. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  406. " --config-file <file>\n"
  407. " [--retry-time <ms>]\n"
  408. " [--no-udev]\n"
  409. " [-- [<extra_arg>] ...]\n",
  410. name
  411. );
  412. }
  413. void print_version (void)
  414. {
  415. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  416. }
  417. int parse_arguments (int argc, char *argv[])
  418. {
  419. if (argc <= 0) {
  420. return 0;
  421. }
  422. options.help = 0;
  423. options.version = 0;
  424. options.logger = LOGGER_STDERR;
  425. options.logger_syslog_facility = "daemon";
  426. options.logger_syslog_ident = argv[0];
  427. options.loglevel = -1;
  428. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  429. options.loglevels[i] = -1;
  430. }
  431. options.config_file = NULL;
  432. options.retry_time = DEFAULT_RETRY_TIME;
  433. options.no_udev = 0;
  434. options.extra_args = NULL;
  435. options.num_extra_args = 0;
  436. for (int i = 1; i < argc; i++) {
  437. char *arg = argv[i];
  438. if (!strcmp(arg, "--help")) {
  439. options.help = 1;
  440. }
  441. else if (!strcmp(arg, "--version")) {
  442. options.version = 1;
  443. }
  444. else if (!strcmp(arg, "--logger")) {
  445. if (1 >= argc - i) {
  446. fprintf(stderr, "%s: requires an argument\n", arg);
  447. return 0;
  448. }
  449. char *arg2 = argv[i + 1];
  450. if (!strcmp(arg2, "stdout")) {
  451. options.logger = LOGGER_STDOUT;
  452. }
  453. else if (!strcmp(arg2, "stderr")) {
  454. options.logger = LOGGER_STDERR;
  455. }
  456. else if (!strcmp(arg2, "syslog")) {
  457. options.logger = LOGGER_SYSLOG;
  458. }
  459. else {
  460. fprintf(stderr, "%s: wrong argument\n", arg);
  461. return 0;
  462. }
  463. i++;
  464. }
  465. else if (!strcmp(arg, "--syslog-facility")) {
  466. if (1 >= argc - i) {
  467. fprintf(stderr, "%s: requires an argument\n", arg);
  468. return 0;
  469. }
  470. options.logger_syslog_facility = argv[i + 1];
  471. i++;
  472. }
  473. else if (!strcmp(arg, "--syslog-ident")) {
  474. if (1 >= argc - i) {
  475. fprintf(stderr, "%s: requires an argument\n", arg);
  476. return 0;
  477. }
  478. options.logger_syslog_ident = argv[i + 1];
  479. i++;
  480. }
  481. else if (!strcmp(arg, "--loglevel")) {
  482. if (1 >= argc - i) {
  483. fprintf(stderr, "%s: requires an argument\n", arg);
  484. return 0;
  485. }
  486. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  487. fprintf(stderr, "%s: wrong argument\n", arg);
  488. return 0;
  489. }
  490. i++;
  491. }
  492. else if (!strcmp(arg, "--channel-loglevel")) {
  493. if (2 >= argc - i) {
  494. fprintf(stderr, "%s: requires two arguments\n", arg);
  495. return 0;
  496. }
  497. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  498. if (channel < 0) {
  499. fprintf(stderr, "%s: wrong channel argument\n", arg);
  500. return 0;
  501. }
  502. int loglevel = parse_loglevel(argv[i + 2]);
  503. if (loglevel < 0) {
  504. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  505. return 0;
  506. }
  507. options.loglevels[channel] = loglevel;
  508. i += 2;
  509. }
  510. else if (!strcmp(arg, "--config-file")) {
  511. if (1 >= argc - i) {
  512. fprintf(stderr, "%s: requires an argument\n", arg);
  513. return 0;
  514. }
  515. options.config_file = argv[i + 1];
  516. i++;
  517. }
  518. else if (!strcmp(arg, "--retry-time")) {
  519. if (1 >= argc - i) {
  520. fprintf(stderr, "%s: requires an argument\n", arg);
  521. return 0;
  522. }
  523. if ((options.retry_time = atoi(argv[i + 1])) < 0) {
  524. fprintf(stderr, "%s: wrong argument\n", arg);
  525. return 0;
  526. }
  527. i++;
  528. }
  529. else if (!strcmp(arg, "--no-udev")) {
  530. options.no_udev = 1;
  531. }
  532. else if (!strcmp(arg, "--")) {
  533. options.extra_args = &argv[i + 1];
  534. options.num_extra_args = argc - i - 1;
  535. i += options.num_extra_args;
  536. }
  537. else {
  538. fprintf(stderr, "unknown option: %s\n", arg);
  539. return 0;
  540. }
  541. }
  542. if (options.help || options.version) {
  543. return 1;
  544. }
  545. if (!options.config_file) {
  546. fprintf(stderr, "--config-file is required\n");
  547. return 0;
  548. }
  549. return 1;
  550. }
  551. void signal_handler (void *unused)
  552. {
  553. BLog(BLOG_NOTICE, "termination requested");
  554. start_terminate(1);
  555. }
  556. void start_terminate (int exit_code)
  557. {
  558. main_exit_code = exit_code;
  559. if (terminating) {
  560. return;
  561. }
  562. terminating = 1;
  563. if (LinkedList1_IsEmpty(&processes)) {
  564. BReactor_Quit(&ss, 0);
  565. return;
  566. }
  567. // start terminating non-template processes
  568. for (LinkedList1Node *ln = LinkedList1_GetFirst(&processes); ln; ln = LinkedList1Node_Next(ln)) {
  569. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  570. if (p->module_process) {
  571. continue;
  572. }
  573. if (p->state != PSTATE_TERMINATING) {
  574. process_start_terminating(p);
  575. }
  576. }
  577. }
  578. int arg_value_init_string (struct arg_value *o, const char *string, size_t len)
  579. {
  580. o->type = ARG_VALUE_TYPE_STRING;
  581. if (!(o->string = malloc(len))) {
  582. BLog(BLOG_ERROR, "malloc failed");
  583. return 0;
  584. }
  585. memcpy(o->string, string, len);
  586. o->string_len = len;
  587. return 1;
  588. }
  589. int arg_value_init_variable (struct arg_value *o, const char *name)
  590. {
  591. ASSERT(name)
  592. o->type = ARG_VALUE_TYPE_VARIABLE;
  593. if (!(o->variable_names = names_new(name))) {
  594. return 0;
  595. }
  596. return 1;
  597. }
  598. void arg_value_init_list (struct arg_value *o)
  599. {
  600. o->type = ARG_VALUE_TYPE_LIST;
  601. LinkedList1_Init(&o->list);
  602. }
  603. int arg_value_list_append (struct arg_value *o, struct arg_value v)
  604. {
  605. ASSERT(o->type == ARG_VALUE_TYPE_LIST)
  606. struct arg_list_elem *elem = malloc(sizeof(*elem));
  607. if (!elem) {
  608. BLog(BLOG_ERROR, "malloc failed");
  609. return 0;
  610. }
  611. LinkedList1_Append(&o->list, &elem->list_node);
  612. elem->value = v;
  613. return 1;
  614. }
  615. void arg_value_init_map (struct arg_value *o)
  616. {
  617. o->type = ARG_VALUE_TYPE_MAP;
  618. LinkedList1_Init(&o->maplist);
  619. }
  620. int arg_value_map_append (struct arg_value *o, struct arg_value key, struct arg_value val)
  621. {
  622. ASSERT(o->type == ARG_VALUE_TYPE_MAP)
  623. struct arg_map_elem *elem = malloc(sizeof(*elem));
  624. if (!elem) {
  625. BLog(BLOG_ERROR, "malloc failed");
  626. return 0;
  627. }
  628. LinkedList1_Append(&o->maplist, &elem->maplist_node);
  629. elem->key = key;
  630. elem->val = val;
  631. return 1;
  632. }
  633. void arg_value_free (struct arg_value *o)
  634. {
  635. switch (o->type) {
  636. case ARG_VALUE_TYPE_STRING: {
  637. free(o->string);
  638. } break;
  639. case ARG_VALUE_TYPE_VARIABLE: {
  640. names_free(o->variable_names);
  641. } break;
  642. case ARG_VALUE_TYPE_LIST: {
  643. while (!LinkedList1_IsEmpty(&o->list)) {
  644. struct arg_list_elem *elem = UPPER_OBJECT(LinkedList1_GetFirst(&o->list), struct arg_list_elem, list_node);
  645. arg_value_free(&elem->value);
  646. LinkedList1_Remove(&o->list, &elem->list_node);
  647. free(elem);
  648. }
  649. } break;
  650. case ARG_VALUE_TYPE_MAP: {
  651. while (!LinkedList1_IsEmpty(&o->maplist)) {
  652. struct arg_map_elem *elem = UPPER_OBJECT(LinkedList1_GetFirst(&o->maplist), struct arg_map_elem, maplist_node);
  653. arg_value_free(&elem->key);
  654. arg_value_free(&elem->val);
  655. LinkedList1_Remove(&o->maplist, &elem->maplist_node);
  656. free(elem);
  657. }
  658. } break;
  659. default: ASSERT(0);
  660. }
  661. }
  662. int build_arg_from_ast (struct arg_value *o, NCDValue *val_ast)
  663. {
  664. switch (NCDValue_Type(val_ast)) {
  665. case NCDVALUE_STRING: {
  666. if (!arg_value_init_string(o, NCDValue_StringValue(val_ast), NCDValue_StringLength(val_ast))) {
  667. return 0;
  668. }
  669. } break;
  670. case NCDVALUE_VAR: {
  671. if (!arg_value_init_variable(o, NCDValue_VarName(val_ast))) {
  672. return 0;
  673. }
  674. } break;
  675. case NCDVALUE_LIST: {
  676. arg_value_init_list(o);
  677. for (NCDValue *ve = NCDValue_ListFirst(val_ast); ve; ve = NCDValue_ListNext(val_ast, ve)) {
  678. struct arg_value e;
  679. if (!build_arg_from_ast(&e, ve)) {
  680. goto fail_list;
  681. }
  682. if (!arg_value_list_append(o, e)) {
  683. arg_value_free(&e);
  684. goto fail_list;
  685. }
  686. }
  687. break;
  688. fail_list:
  689. arg_value_free(o);
  690. return 0;
  691. } break;
  692. case NCDVALUE_MAP: {
  693. arg_value_init_map(o);
  694. for (NCDValue *ekey = NCDValue_MapFirstKey(val_ast); ekey; ekey = NCDValue_MapNextKey(val_ast, ekey)) {
  695. NCDValue *eval = NCDValue_MapKeyValue(val_ast, ekey);
  696. struct arg_value key;
  697. struct arg_value val;
  698. if (!build_arg_from_ast(&key, ekey)) {
  699. goto fail_map;
  700. }
  701. if (!build_arg_from_ast(&val, eval)) {
  702. arg_value_free(&key);
  703. goto fail_map;
  704. }
  705. if (!arg_value_map_append(o, key, val)) {
  706. arg_value_free(&key);
  707. arg_value_free(&val);
  708. goto fail_map;
  709. }
  710. }
  711. break;
  712. fail_map:
  713. arg_value_free(o);
  714. return 0;
  715. } break;
  716. default: ASSERT(0);
  717. }
  718. return 1;
  719. }
  720. static char ** names_new (const char *name)
  721. {
  722. ASSERT(name)
  723. return split_string(name, '.');
  724. }
  725. static size_t names_count (char **names)
  726. {
  727. ASSERT(names)
  728. size_t i;
  729. for (i = 0; names[i]; i++);
  730. return i;
  731. }
  732. static char * names_tostring (char **names)
  733. {
  734. ASSERT(names)
  735. ExpString str;
  736. if (!ExpString_Init(&str)) {
  737. goto fail0;
  738. }
  739. for (size_t i = 0; names[i]; i++) {
  740. if (i > 0 && !ExpString_AppendChar(&str, '.')) {
  741. goto fail1;
  742. }
  743. if (!ExpString_Append(&str, names[i])) {
  744. goto fail1;
  745. }
  746. }
  747. return ExpString_Get(&str);
  748. fail1:
  749. ExpString_Free(&str);
  750. fail0:
  751. return NULL;
  752. }
  753. static void names_free (char **names)
  754. {
  755. ASSERT(names)
  756. size_t i = names_count(names);
  757. while (i-- > 0) {
  758. free(names[i]);
  759. }
  760. BFree(names);
  761. }
  762. int statement_init (struct statement *s, NCDStatement *stmt_ast)
  763. {
  764. ASSERT(NCDStatement_Type(stmt_ast) == NCDSTATEMENT_REG)
  765. // set object names
  766. if (NCDStatement_RegObjName(stmt_ast)) {
  767. if (!(s->object_names = names_new(NCDStatement_RegObjName(stmt_ast)))) {
  768. goto fail0;
  769. }
  770. } else {
  771. s->object_names = NULL;
  772. }
  773. // set method name
  774. if (!(s->method_name = strdup(NCDStatement_RegCmdName(stmt_ast)))) {
  775. BLog(BLOG_ERROR, "strdup failed");
  776. goto fail1;
  777. }
  778. // init name
  779. if (NCDStatement_Name(stmt_ast)) {
  780. if (!(s->name = strdup(NCDStatement_Name(stmt_ast)))) {
  781. BLog(BLOG_ERROR, "strdup failed");
  782. goto fail2;
  783. }
  784. } else {
  785. s->name = NULL;
  786. }
  787. // init arguments
  788. if (!build_arg_from_ast(&s->args, NCDStatement_RegArgs(stmt_ast))) {
  789. BLog(BLOG_ERROR, "build_arg_from_ast failed");
  790. goto fail3;
  791. }
  792. return 1;
  793. fail3:
  794. free(s->name);
  795. fail2:
  796. free(s->method_name);
  797. fail1:
  798. if (s->object_names) {
  799. names_free(s->object_names);
  800. }
  801. fail0:
  802. return 0;
  803. }
  804. void statement_free (struct statement *s)
  805. {
  806. // free arguments
  807. arg_value_free(&s->args);
  808. // free name
  809. free(s->name);
  810. // free method name
  811. free(s->method_name);
  812. // free object names
  813. if (s->object_names) {
  814. names_free(s->object_names);
  815. }
  816. }
  817. int process_new (NCDProcess *proc_ast, NCDModuleProcess *module_process)
  818. {
  819. // allocate strucure
  820. struct process *p = malloc(sizeof(*p));
  821. if (!p) {
  822. BLog(BLOG_ERROR, "malloc failed");
  823. goto fail0;
  824. }
  825. // set module process
  826. p->module_process = module_process;
  827. // set module process handlers
  828. if (p->module_process) {
  829. NCDModuleProcess_Interp_SetHandlers(p->module_process, p,
  830. (NCDModuleProcess_interp_func_event)process_moduleprocess_func_event,
  831. (NCDModuleProcess_interp_func_getobj)process_moduleprocess_func_getobj);
  832. }
  833. // init name
  834. if (!(p->name = strdup(NCDProcess_Name(proc_ast)))) {
  835. BLog(BLOG_ERROR, "strdup failed");
  836. goto fail1;
  837. }
  838. // get block
  839. NCDBlock *block = NCDProcess_Block(proc_ast);
  840. // allocate statements array
  841. if (!(p->statements = BAllocArray(NCDBlock_NumStatements(block), sizeof(p->statements[0])))) {
  842. goto fail2;
  843. }
  844. p->num_statements = 0;
  845. // init statements
  846. for (NCDStatement *st = NCDBlock_FirstStatement(block); st; st = NCDBlock_NextStatement(block, st)) {
  847. struct process_statement *ps = &p->statements[p->num_statements];
  848. ps->p = p;
  849. ps->i = p->num_statements;
  850. if (!statement_init(&ps->s, st)) {
  851. goto fail3;
  852. }
  853. ps->state = SSTATE_FORGOTTEN;
  854. ps->have_error = 0;
  855. p->num_statements++;
  856. }
  857. // set state working
  858. p->state = PSTATE_WORKING;
  859. // set AP=0
  860. p->ap = 0;
  861. // set FP=0
  862. p->fp = 0;
  863. // init timer
  864. BTimer_Init(&p->wait_timer, 0, (BTimer_handler)process_wait_timer_handler, p);
  865. // init advance job
  866. BPending_Init(&p->advance_job, BReactor_PendingGroup(&ss), (BPending_handler)process_advance_job_handler, p);
  867. // init work job
  868. BPending_Init(&p->work_job, BReactor_PendingGroup(&ss), (BPending_handler)process_work_job_handler, p);
  869. // insert to processes list
  870. LinkedList1_Append(&processes, &p->list_node);
  871. // schedule work
  872. BPending_Set(&p->work_job);
  873. return 1;
  874. fail3:
  875. process_free_statements(p);
  876. fail2:
  877. free(p->name);
  878. fail1:
  879. free(p);
  880. fail0:
  881. BLog(BLOG_ERROR, "failed to initialize process %s", NCDProcess_Name(proc_ast));
  882. return 0;
  883. }
  884. void process_free (struct process *p)
  885. {
  886. ASSERT(p->ap == 0)
  887. ASSERT(p->fp == 0)
  888. // inform module process that the process is terminated
  889. if (p->module_process) {
  890. NCDModuleProcess_Interp_Terminated(p->module_process);
  891. }
  892. // remove from processes list
  893. LinkedList1_Remove(&processes, &p->list_node);
  894. // free work job
  895. BPending_Free(&p->work_job);
  896. // free advance job
  897. BPending_Free(&p->advance_job);
  898. // free timer
  899. BReactor_RemoveTimer(&ss, &p->wait_timer);
  900. // free statements
  901. process_free_statements(p);
  902. // free name
  903. free(p->name);
  904. // free strucure
  905. free(p);
  906. }
  907. void process_start_terminating (struct process *p)
  908. {
  909. ASSERT(p->state != PSTATE_TERMINATING)
  910. // set terminating
  911. p->state = PSTATE_TERMINATING;
  912. // schedule work
  913. process_schedule_work(p);
  914. }
  915. size_t process_rap (struct process *p)
  916. {
  917. if (p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD) {
  918. return (p->ap - 1);
  919. } else {
  920. return p->ap;
  921. }
  922. }
  923. void process_free_statements (struct process *p)
  924. {
  925. // free statments
  926. while (p->num_statements > 0) {
  927. statement_free(&p->statements[p->num_statements - 1].s);
  928. p->num_statements--;
  929. }
  930. // free stataments array
  931. free(p->statements);
  932. }
  933. void process_assert_pointers (struct process *p)
  934. {
  935. ASSERT(p->ap <= p->num_statements)
  936. ASSERT(p->fp >= p->ap)
  937. ASSERT(p->fp <= p->num_statements)
  938. #ifndef NDEBUG
  939. // check AP
  940. for (size_t i = 0; i < p->ap; i++) {
  941. if (i == p->ap - 1) {
  942. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  943. } else {
  944. ASSERT(p->statements[i].state == SSTATE_ADULT)
  945. }
  946. }
  947. // check FP
  948. size_t fp = p->num_statements;
  949. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  950. fp--;
  951. }
  952. ASSERT(p->fp == fp)
  953. #endif
  954. }
  955. void process_logfunc (struct process *p)
  956. {
  957. BLog_Append("process %s: ", p->name);
  958. }
  959. void process_log (struct process *p, int level, const char *fmt, ...)
  960. {
  961. va_list vl;
  962. va_start(vl, fmt);
  963. BLog_LogViaFuncVarArg((BLog_logfunc)process_logfunc, p, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  964. va_end(vl);
  965. }
  966. void process_schedule_work (struct process *p)
  967. {
  968. process_assert_pointers(p);
  969. // stop timer
  970. BReactor_RemoveTimer(&ss, &p->wait_timer);
  971. // stop advance job
  972. BPending_Unset(&p->advance_job);
  973. // schedule work
  974. BPending_Set(&p->work_job);
  975. }
  976. void process_work_job_handler (struct process *p)
  977. {
  978. process_assert_pointers(p);
  979. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  980. ASSERT(!BPending_IsSet(&p->advance_job))
  981. if (p->state == PSTATE_WAITING) {
  982. return;
  983. }
  984. if (p->state == PSTATE_TERMINATING) {
  985. if (p->fp == 0) {
  986. // finished retreating
  987. process_free(p);
  988. // if program is terminating amd there are no more processes, exit program
  989. if (terminating && LinkedList1_IsEmpty(&processes)) {
  990. BReactor_Quit(&ss, 0);
  991. }
  992. return;
  993. }
  994. // order the last living statement to die, if needed
  995. struct process_statement *ps = &p->statements[p->fp - 1];
  996. ASSERT(ps->state != SSTATE_FORGOTTEN)
  997. if (ps->state != SSTATE_DYING) {
  998. process_statement_log(ps, BLOG_INFO, "killing");
  999. // order it to die
  1000. NCDModuleInst_Die(&ps->inst);
  1001. // set statement state DYING
  1002. ps->state = SSTATE_DYING;
  1003. // update AP
  1004. if (p->ap > ps->i) {
  1005. p->ap = ps->i;
  1006. }
  1007. }
  1008. return;
  1009. }
  1010. // process was up but is no longer?
  1011. if (p->state == PSTATE_UP && !(p->ap == process_rap(p) && p->ap == p->num_statements)) {
  1012. // if we have module process, wait for its permission to continue
  1013. if (p->module_process) {
  1014. // set module process down
  1015. NCDModuleProcess_Interp_Down(p->module_process);
  1016. // set state waiting
  1017. p->state = PSTATE_WAITING;
  1018. return;
  1019. }
  1020. // set state working
  1021. p->state = PSTATE_WORKING;
  1022. }
  1023. // cleaning up?
  1024. if (p->ap < p->fp) {
  1025. // order the last living statement to die, if needed
  1026. struct process_statement *ps = &p->statements[p->fp - 1];
  1027. if (ps->state != SSTATE_DYING) {
  1028. process_statement_log(ps, BLOG_INFO, "killing");
  1029. // order it to die
  1030. NCDModuleInst_Die(&ps->inst);
  1031. // set statement state DYING
  1032. ps->state = SSTATE_DYING;
  1033. }
  1034. return;
  1035. }
  1036. // clean?
  1037. if (p->ap > process_rap(p)) {
  1038. ASSERT(p->ap > 0)
  1039. ASSERT(p->ap <= p->num_statements)
  1040. struct process_statement *ps = &p->statements[p->ap - 1];
  1041. ASSERT(ps->state == SSTATE_CHILD)
  1042. process_statement_log(ps, BLOG_INFO, "clean");
  1043. // report clean
  1044. NCDModuleInst_Clean(&ps->inst);
  1045. return;
  1046. }
  1047. // advancing?
  1048. if (p->ap < p->num_statements) {
  1049. ASSERT(p->state == PSTATE_WORKING)
  1050. struct process_statement *ps = &p->statements[p->ap];
  1051. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1052. // clear expired error
  1053. if (ps->have_error && ps->error_until <= btime_gettime()) {
  1054. ps->have_error = 0;
  1055. }
  1056. if (ps->have_error) {
  1057. process_statement_log(ps, BLOG_INFO, "waiting after error");
  1058. // set wait timer
  1059. BReactor_SetTimerAbsolute(&ss, &p->wait_timer, ps->error_until);
  1060. } else {
  1061. // schedule advance
  1062. BPending_Set(&p->advance_job);
  1063. }
  1064. return;
  1065. }
  1066. // have we just finished?
  1067. if (p->state == PSTATE_WORKING) {
  1068. process_log(p, BLOG_INFO, "victory");
  1069. // set module process up
  1070. if (p->module_process) {
  1071. NCDModuleProcess_Interp_Up(p->module_process);
  1072. }
  1073. // set state up
  1074. p->state = PSTATE_UP;
  1075. }
  1076. }
  1077. void process_advance_job_handler (struct process *p)
  1078. {
  1079. process_assert_pointers(p);
  1080. ASSERT(p->ap == p->fp)
  1081. ASSERT(p->ap == process_rap(p))
  1082. ASSERT(p->ap < p->num_statements)
  1083. ASSERT(!p->statements[p->ap].have_error)
  1084. ASSERT(!BPending_IsSet(&p->work_job))
  1085. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  1086. ASSERT(p->state == PSTATE_WORKING)
  1087. struct process_statement *ps = &p->statements[p->ap];
  1088. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1089. process_statement_log(ps, BLOG_INFO, "initializing");
  1090. NCDObject object;
  1091. NCDObject *object_ptr = NULL;
  1092. char *type;
  1093. int free_type = 0;
  1094. if (!ps->s.object_names) {
  1095. // this is a function_call(); type is "function_call"
  1096. type = ps->s.method_name;
  1097. } else {
  1098. // this is a some.object.somewhere->method_call(); type is "base_type(some.object.somewhere)::method_call"
  1099. // get object
  1100. if (!process_resolve_object_expr(p, p->ap, ps->s.object_names, &object)) {
  1101. goto fail;
  1102. }
  1103. object_ptr = &object;
  1104. // get object type
  1105. const char *object_type = NCDObject_Type(&object);
  1106. if (!object_type) {
  1107. process_statement_log(ps, BLOG_ERROR, "cannot call method on object with no type");
  1108. goto fail;
  1109. }
  1110. // build type string
  1111. if (!(type = concat_strings(3, object_type, "::", ps->s.method_name))) {
  1112. process_statement_log(ps, BLOG_ERROR, "concat_strings failed");
  1113. goto fail;
  1114. }
  1115. free_type = 1;
  1116. }
  1117. // find module to instantiate
  1118. const struct NCDModule *module = NCDModuleIndex_FindModule(&mindex, type);
  1119. if (!module) {
  1120. process_statement_log(ps, BLOG_ERROR, "failed to find module: %s", type);
  1121. goto fail;
  1122. }
  1123. // resolve arguments
  1124. if (!process_statement_resolve_argument(ps, &ps->s.args, &ps->inst_args)) {
  1125. process_statement_log(ps, BLOG_ERROR, "failed to resolve arguments");
  1126. goto fail;
  1127. }
  1128. // initialize module instance
  1129. NCDModuleInst_Init(&ps->inst, module, object_ptr, &ps->inst_args, ps, &module_params, &module_iparams);
  1130. // set statement state CHILD
  1131. ps->state = SSTATE_CHILD;
  1132. // increment AP
  1133. p->ap++;
  1134. // increment FP
  1135. p->fp++;
  1136. if (free_type) {
  1137. free(type);
  1138. }
  1139. process_assert_pointers(p);
  1140. return;
  1141. fail:
  1142. if (free_type) {
  1143. free(type);
  1144. }
  1145. // mark error
  1146. process_statement_set_error(ps);
  1147. // schedule work to start the timer
  1148. process_schedule_work(p);
  1149. }
  1150. void process_wait_timer_handler (struct process *p)
  1151. {
  1152. process_assert_pointers(p);
  1153. ASSERT(p->ap == p->fp)
  1154. ASSERT(p->ap == process_rap(p))
  1155. ASSERT(p->ap < p->num_statements)
  1156. ASSERT(p->statements[p->ap].have_error)
  1157. ASSERT(!BPending_IsSet(&p->work_job))
  1158. ASSERT(!BPending_IsSet(&p->advance_job))
  1159. ASSERT(p->state == PSTATE_WORKING)
  1160. process_log(p, BLOG_INFO, "retrying");
  1161. // clear error
  1162. p->statements[p->ap].have_error = 0;
  1163. // schedule work
  1164. BPending_Set(&p->work_job);
  1165. }
  1166. int process_find_object (struct process *p, size_t pos, const char *name, NCDObject *out_object)
  1167. {
  1168. ASSERT(pos <= p->num_statements)
  1169. ASSERT(name)
  1170. ASSERT(out_object)
  1171. for (size_t i = pos; i > 0; i--) {
  1172. struct process_statement *ps = &p->statements[i - 1];
  1173. if (ps->s.name && !strcmp(ps->s.name, name)) {
  1174. if (ps->state == SSTATE_FORGOTTEN) {
  1175. process_log(p, BLOG_ERROR, "statement (%zu) is uninitialized", i - 1);
  1176. goto fail;
  1177. }
  1178. *out_object = NCDModuleInst_Object(&ps->inst);
  1179. return 1;
  1180. }
  1181. }
  1182. if (p->module_process && NCDModuleProcess_Interp_GetSpecialObj(p->module_process, name, out_object)) {
  1183. return 1;
  1184. }
  1185. fail:
  1186. return 0;
  1187. }
  1188. int process_resolve_object_expr (struct process *p, size_t pos, char **names, NCDObject *out_object)
  1189. {
  1190. ASSERT(pos <= p->num_statements)
  1191. ASSERT(names)
  1192. ASSERT(names_count(names) > 0)
  1193. ASSERT(out_object)
  1194. NCDObject object;
  1195. if (!process_find_object(p, pos, names[0], &object)) {
  1196. goto fail;
  1197. }
  1198. if (!NCDObject_ResolveObjExpr(&object, names + 1, out_object)) {
  1199. goto fail;
  1200. }
  1201. return 1;
  1202. fail:;
  1203. char *name = names_tostring(names);
  1204. process_log(p, BLOG_ERROR, "failed to resolve object (%s) from position %zu", (name ? name : ""), pos);
  1205. free(name);
  1206. return 0;
  1207. }
  1208. int process_resolve_variable_expr (struct process *p, size_t pos, char **names, NCDValue *out_value)
  1209. {
  1210. ASSERT(pos <= p->num_statements)
  1211. ASSERT(names)
  1212. ASSERT(names_count(names) > 0)
  1213. ASSERT(out_value)
  1214. NCDObject object;
  1215. if (!process_find_object(p, pos, names[0], &object)) {
  1216. goto fail;
  1217. }
  1218. if (!NCDObject_ResolveVarExpr(&object, names + 1, out_value)) {
  1219. goto fail;
  1220. }
  1221. return 1;
  1222. fail:;
  1223. char *name = names_tostring(names);
  1224. process_log(p, BLOG_ERROR, "failed to resolve variable (%s) from position %zu", (name ? name : ""), pos);
  1225. free(name);
  1226. return 0;
  1227. }
  1228. void process_statement_logfunc (struct process_statement *ps)
  1229. {
  1230. process_logfunc(ps->p);
  1231. BLog_Append("statement %zu: ", ps->i);
  1232. }
  1233. void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...)
  1234. {
  1235. va_list vl;
  1236. va_start(vl, fmt);
  1237. BLog_LogViaFuncVarArg((BLog_logfunc)process_statement_logfunc, ps, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1238. va_end(vl);
  1239. }
  1240. void process_statement_set_error (struct process_statement *ps)
  1241. {
  1242. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1243. ps->have_error = 1;
  1244. ps->error_until = btime_add(btime_gettime(), options.retry_time);
  1245. }
  1246. int process_statement_resolve_argument (struct process_statement *ps, struct arg_value *arg, NCDValue *out)
  1247. {
  1248. ASSERT(ps->i <= process_rap(ps->p))
  1249. ASSERT(arg)
  1250. ASSERT(out)
  1251. switch (arg->type) {
  1252. case ARG_VALUE_TYPE_STRING: {
  1253. if (!NCDValue_InitStringBin(out, (uint8_t *)arg->string, arg->string_len)) {
  1254. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitStringBin failed");
  1255. return 0;
  1256. }
  1257. } break;
  1258. case ARG_VALUE_TYPE_VARIABLE: {
  1259. if (!process_resolve_variable_expr(ps->p, ps->i, arg->variable_names, out)) {
  1260. return 0;
  1261. }
  1262. } break;
  1263. case ARG_VALUE_TYPE_LIST: do {
  1264. NCDValue_InitList(out);
  1265. for (LinkedList1Node *n = LinkedList1_GetFirst(&arg->list); n; n = LinkedList1Node_Next(n)) {
  1266. struct arg_list_elem *elem = UPPER_OBJECT(n, struct arg_list_elem, list_node);
  1267. NCDValue v;
  1268. if (!process_statement_resolve_argument(ps, &elem->value, &v)) {
  1269. goto list_fail1;
  1270. }
  1271. if (!NCDValue_ListAppend(out, v)) {
  1272. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  1273. NCDValue_Free(&v);
  1274. goto list_fail1;
  1275. }
  1276. }
  1277. break;
  1278. list_fail1:
  1279. NCDValue_Free(out);
  1280. return 0;
  1281. } while (0); break;
  1282. case ARG_VALUE_TYPE_MAP: do {
  1283. NCDValue_InitMap(out);
  1284. for (LinkedList1Node *n = LinkedList1_GetFirst(&arg->maplist); n; n = LinkedList1Node_Next(n)) {
  1285. struct arg_map_elem *elem = UPPER_OBJECT(n, struct arg_map_elem, maplist_node);
  1286. NCDValue key;
  1287. NCDValue val;
  1288. if (!process_statement_resolve_argument(ps, &elem->key, &key)) {
  1289. goto map_fail;
  1290. }
  1291. if (!process_statement_resolve_argument(ps, &elem->val, &val)) {
  1292. NCDValue_Free(&key);
  1293. goto map_fail;
  1294. }
  1295. if (NCDValue_MapFindKey(out, &key)) {
  1296. process_statement_log(ps, BLOG_ERROR, "duplicate map keys");
  1297. NCDValue_Free(&key);
  1298. NCDValue_Free(&val);
  1299. goto map_fail;
  1300. }
  1301. if (!NCDValue_MapInsert(out, key, val)) {
  1302. process_statement_log(ps, BLOG_ERROR, "NCDValue_MapInsert failed");
  1303. NCDValue_Free(&key);
  1304. NCDValue_Free(&val);
  1305. goto map_fail;
  1306. }
  1307. }
  1308. break;
  1309. map_fail:
  1310. NCDValue_Free(out);
  1311. return 0;
  1312. } while (0); break;
  1313. default: ASSERT(0);
  1314. }
  1315. return 1;
  1316. }
  1317. void process_statement_instance_func_event (struct process_statement *ps, int event)
  1318. {
  1319. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  1320. struct process *p = ps->p;
  1321. process_assert_pointers(p);
  1322. // schedule work
  1323. process_schedule_work(p);
  1324. switch (event) {
  1325. case NCDMODULE_EVENT_UP: {
  1326. ASSERT(ps->state == SSTATE_CHILD)
  1327. process_statement_log(ps, BLOG_INFO, "up");
  1328. // set state ADULT
  1329. ps->state = SSTATE_ADULT;
  1330. } break;
  1331. case NCDMODULE_EVENT_DOWN: {
  1332. ASSERT(ps->state == SSTATE_ADULT)
  1333. process_statement_log(ps, BLOG_INFO, "down");
  1334. // set state CHILD
  1335. ps->state = SSTATE_CHILD;
  1336. // update AP
  1337. if (p->ap > ps->i + 1) {
  1338. p->ap = ps->i + 1;
  1339. }
  1340. } break;
  1341. case NCDMODULE_EVENT_DEAD: {
  1342. int is_error = NCDModuleInst_HaveError(&ps->inst);
  1343. if (is_error) {
  1344. process_statement_log(ps, BLOG_ERROR, "died with error");
  1345. } else {
  1346. process_statement_log(ps, BLOG_INFO, "died");
  1347. }
  1348. // free instance
  1349. NCDModuleInst_Free(&ps->inst);
  1350. // free instance arguments
  1351. NCDValue_Free(&ps->inst_args);
  1352. // set state FORGOTTEN
  1353. ps->state = SSTATE_FORGOTTEN;
  1354. // set error
  1355. if (is_error) {
  1356. process_statement_set_error(ps);
  1357. }
  1358. // update AP
  1359. if (p->ap > ps->i) {
  1360. p->ap = ps->i;
  1361. }
  1362. // update FP
  1363. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  1364. p->fp--;
  1365. }
  1366. } break;
  1367. }
  1368. }
  1369. int process_statement_instance_func_getobj (struct process_statement *ps, const char *objname, NCDObject *out_object)
  1370. {
  1371. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1372. return process_find_object(ps->p, ps->i, objname, out_object);
  1373. }
  1374. int process_statement_instance_func_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name)
  1375. {
  1376. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1377. // find template
  1378. NCDProcess *p_ast;
  1379. for (p_ast = NCDProgram_FirstProcess(&program); p_ast; p_ast = NCDProgram_NextProcess(&program, p_ast)) {
  1380. if (NCDProcess_IsTemplate(p_ast) && !strcmp(NCDProcess_Name(p_ast), template_name)) {
  1381. break;
  1382. }
  1383. }
  1384. if (!p_ast) {
  1385. process_statement_log(ps, BLOG_ERROR, "no template named %s", template_name);
  1386. return 0;
  1387. }
  1388. // create process
  1389. if (!process_new(p_ast, mp)) {
  1390. process_statement_log(ps, BLOG_ERROR, "failed to create process from template %s", template_name);
  1391. return 0;
  1392. }
  1393. process_statement_log(ps, BLOG_INFO, "created process from template %s", template_name);
  1394. return 1;
  1395. }
  1396. void process_statement_instance_logfunc (struct process_statement *ps)
  1397. {
  1398. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1399. process_statement_logfunc(ps);
  1400. BLog_Append("module: ");
  1401. }
  1402. void process_statement_instance_func_interp_exit (struct process_statement *ps, int exit_code)
  1403. {
  1404. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1405. start_terminate(exit_code);
  1406. }
  1407. int process_statement_instance_func_interp_getargs (struct process_statement *ps, NCDValue *out_value)
  1408. {
  1409. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1410. NCDValue_InitList(out_value);
  1411. for (int i = 0; i < options.num_extra_args; i++) {
  1412. NCDValue arg;
  1413. if (!NCDValue_InitString(&arg, options.extra_args[i])) {
  1414. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitString failed");
  1415. goto fail1;
  1416. }
  1417. if (!NCDValue_ListAppend(out_value, arg)) {
  1418. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  1419. NCDValue_Free(&arg);
  1420. goto fail1;
  1421. }
  1422. }
  1423. return 1;
  1424. fail1:
  1425. NCDValue_Free(out_value);
  1426. return 0;
  1427. }
  1428. btime_t process_statement_instance_func_interp_getretrytime (struct process_statement *ps)
  1429. {
  1430. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1431. return options.retry_time;
  1432. }
  1433. void process_moduleprocess_func_event (struct process *p, int event)
  1434. {
  1435. ASSERT(p->module_process)
  1436. switch (event) {
  1437. case NCDMODULEPROCESS_INTERP_EVENT_CONTINUE: {
  1438. ASSERT(p->state == PSTATE_WAITING)
  1439. // set state working
  1440. p->state = PSTATE_WORKING;
  1441. // schedule work
  1442. process_schedule_work(p);
  1443. } break;
  1444. case NCDMODULEPROCESS_INTERP_EVENT_TERMINATE: {
  1445. ASSERT(p->state != PSTATE_TERMINATING)
  1446. process_log(p, BLOG_INFO, "process termination requested");
  1447. // start terminating
  1448. process_start_terminating(p);
  1449. } break;
  1450. default: ASSERT(0);
  1451. }
  1452. }
  1453. int process_moduleprocess_func_getobj (struct process *p, const char *name, NCDObject *out_object)
  1454. {
  1455. ASSERT(p->module_process)
  1456. return process_find_object(p, p->num_statements, name, out_object);
  1457. }