ncd.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  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 <structure/LinkedList1.h>
  44. #include <structure/LinkedList2.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/modules/modules.h>
  56. #include <ncd/ncd.h>
  57. #include <generated/blog_channel_ncd.h>
  58. #define LOGGER_STDOUT 1
  59. #define LOGGER_STDERR 2
  60. #define LOGGER_SYSLOG 3
  61. #define ARG_VALUE_TYPE_STRING 1
  62. #define ARG_VALUE_TYPE_VARIABLE 2
  63. #define ARG_VALUE_TYPE_LIST 3
  64. #define ARG_VALUE_TYPE_MAP 4
  65. #define SSTATE_CHILD 1
  66. #define SSTATE_ADULT 2
  67. #define SSTATE_DYING 3
  68. #define SSTATE_FORGOTTEN 4
  69. #define PSTATE_WORKING 1
  70. #define PSTATE_UP 2
  71. #define PSTATE_WAITING 3
  72. #define PSTATE_TERMINATING 4
  73. struct arg_value {
  74. int type;
  75. union {
  76. struct {
  77. char *string;
  78. size_t string_len;
  79. };
  80. char **variable_names;
  81. LinkedList1 list;
  82. LinkedList1 maplist;
  83. };
  84. };
  85. struct arg_list_elem {
  86. LinkedList1Node list_node;
  87. struct arg_value value;
  88. };
  89. struct arg_map_elem {
  90. LinkedList1Node maplist_node;
  91. struct arg_value key;
  92. struct arg_value val;
  93. };
  94. struct statement {
  95. char **object_names;
  96. char *method_name;
  97. struct arg_value args;
  98. char *name;
  99. };
  100. struct process {
  101. NCDModuleProcess *module_process;
  102. char *name;
  103. size_t num_statements;
  104. struct process_statement *statements;
  105. int state;
  106. size_t ap;
  107. size_t fp;
  108. BTimer wait_timer;
  109. BPending advance_job;
  110. BPending work_job;
  111. LinkedList2Node list_node; // node in processes
  112. };
  113. struct process_statement {
  114. struct process *p;
  115. size_t i;
  116. struct statement s;
  117. int state;
  118. const struct NCDModule *module;
  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. // config AST
  151. struct NCDConfig_processes *config_ast;
  152. // common module parameters
  153. struct NCDModuleInst_params module_params;
  154. // processes
  155. LinkedList2 processes;
  156. static void print_help (const char *name);
  157. static void print_version (void);
  158. static int parse_arguments (int argc, char *argv[]);
  159. static void signal_handler (void *unused);
  160. static void start_terminate (int exit_code);
  161. static int arg_value_init_string (struct arg_value *o, const char *string, size_t len);
  162. static int arg_value_init_variable (struct arg_value *o, struct NCDConfig_strings *ast_names);
  163. static void arg_value_init_list (struct arg_value *o);
  164. static int arg_value_list_append (struct arg_value *o, struct arg_value v);
  165. static void arg_value_init_map (struct arg_value *o);
  166. static int arg_value_map_append (struct arg_value *o, struct arg_value key, struct arg_value val);
  167. static void arg_value_free (struct arg_value *o);
  168. static int build_arg_from_ast (struct arg_value *o, struct NCDConfig_list *ast);
  169. static int build_arg_list_from_ast_list (struct arg_value *o, struct NCDConfig_list *list);
  170. static int build_arg_map_from_ast_list (struct arg_value *o, struct NCDConfig_list *list);
  171. static char ** names_new (struct NCDConfig_strings *ast_names);
  172. static size_t names_count (char **names);
  173. static char * names_tostring (char **names);
  174. static void names_free (char **names);
  175. static int statement_init (struct statement *s, struct NCDConfig_statements *conf);
  176. static void statement_free (struct statement *s);
  177. static int process_new (struct NCDConfig_processes *conf, NCDModuleProcess *module_process);
  178. static void process_free (struct process *p);
  179. static void process_start_terminating (struct process *p);
  180. static void process_free_statements (struct process *p);
  181. static size_t process_rap (struct process *p);
  182. static void process_assert_pointers (struct process *p);
  183. static void process_logfunc (struct process *p);
  184. static void process_log (struct process *p, int level, const char *fmt, ...);
  185. static void process_schedule_work (struct process *p);
  186. static void process_work_job_handler (struct process *p);
  187. static void process_advance_job_handler (struct process *p);
  188. static void process_wait_timer_handler (struct process *p);
  189. static int process_find_object (struct process *p, size_t pos, const char *name, NCDObject *out_object);
  190. static int process_resolve_object_expr (struct process *p, size_t pos, char **names, NCDObject *out_object);
  191. static int process_resolve_variable_expr (struct process *p, size_t pos, char **names, NCDValue *out_value);
  192. static void process_statement_logfunc (struct process_statement *ps);
  193. static void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...);
  194. static void process_statement_set_error (struct process_statement *ps);
  195. static int process_statement_resolve_argument (struct process_statement *ps, struct arg_value *arg, NCDValue *out);
  196. static void process_statement_instance_func_event (struct process_statement *ps, int event);
  197. static int process_statement_instance_func_getobj (struct process_statement *ps, const char *objname, NCDObject *out_object);
  198. static int process_statement_instance_func_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name);
  199. static void process_statement_instance_logfunc (struct process_statement *ps);
  200. static void process_statement_instance_func_interp_exit (struct process_statement *ps, int exit_code);
  201. static int process_statement_instance_func_interp_getargs (struct process_statement *ps, NCDValue *out_value);
  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, &config_ast)) {
  300. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  301. free(file);
  302. goto fail3;
  303. }
  304. // fee config file memory
  305. free(file);
  306. // init module params
  307. struct NCDModuleInitParams params;
  308. params.reactor = &ss;
  309. params.manager = &manager;
  310. params.umanager = &umanager;
  311. // init modules
  312. size_t num_inited_modules = 0;
  313. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  314. if ((*g)->func_globalinit && !(*g)->func_globalinit(params)) {
  315. BLog(BLOG_ERROR, "globalinit failed for some module");
  316. goto fail5;
  317. }
  318. num_inited_modules++;
  319. }
  320. // init common module params
  321. module_params.reactor = &ss;
  322. module_params.manager = &manager;
  323. module_params.umanager = &umanager;
  324. module_params.func_event = (NCDModuleInst_func_event)process_statement_instance_func_event;
  325. module_params.func_getobj = (NCDModuleInst_func_getobj)process_statement_instance_func_getobj;
  326. module_params.func_initprocess = (NCDModuleInst_func_initprocess)process_statement_instance_func_initprocess;
  327. module_params.logfunc = (BLog_logfunc)process_statement_instance_logfunc;
  328. module_params.func_interp_exit = (NCDModuleInst_func_interp_exit)process_statement_instance_func_interp_exit;
  329. module_params.func_interp_getargs = (NCDModuleInst_func_interp_getargs)process_statement_instance_func_interp_getargs;
  330. // init processes list
  331. LinkedList2_Init(&processes);
  332. // init processes
  333. struct NCDConfig_processes *conf = config_ast;
  334. while (conf) {
  335. if (!conf->is_template) {
  336. process_new(conf, NULL);
  337. }
  338. conf = conf->next;
  339. }
  340. // enter event loop
  341. BLog(BLOG_NOTICE, "entering event loop");
  342. BReactor_Exec(&ss);
  343. ASSERT(LinkedList2_IsEmpty(&processes))
  344. fail5:
  345. // free modules
  346. while (num_inited_modules > 0) {
  347. const struct NCDModuleGroup **g = &ncd_modules[num_inited_modules - 1];
  348. if ((*g)->func_globalfree) {
  349. (*g)->func_globalfree();
  350. }
  351. num_inited_modules--;
  352. }
  353. // free configuration
  354. NCDConfig_free_processes(config_ast);
  355. fail3:
  356. // remove signal handler
  357. BSignal_Finish();
  358. fail2:
  359. // free module index
  360. NCDModuleIndex_Free(&mindex);
  361. // free udev manager
  362. NCDUdevManager_Free(&umanager);
  363. // free process manager
  364. BProcessManager_Free(&manager);
  365. fail1a:
  366. // free reactor
  367. BReactor_Free(&ss);
  368. fail1:
  369. // free logger
  370. BLog(BLOG_NOTICE, "exiting");
  371. BLog_Free();
  372. fail0:
  373. // finish objects
  374. DebugObjectGlobal_Finish();
  375. return main_exit_code;
  376. }
  377. void print_help (const char *name)
  378. {
  379. printf(
  380. "Usage:\n"
  381. " %s\n"
  382. " [--help]\n"
  383. " [--version]\n"
  384. " [--logger <stdout/stderr/syslog>]\n"
  385. " (logger=syslog?\n"
  386. " [--syslog-facility <string>]\n"
  387. " [--syslog-ident <string>]\n"
  388. " )\n"
  389. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  390. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  391. " --config-file <file>\n"
  392. " [--retry-time <ms>]\n"
  393. " [--no-udev]\n"
  394. " [-- [<extra_arg>] ...]\n",
  395. name
  396. );
  397. }
  398. void print_version (void)
  399. {
  400. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  401. }
  402. int parse_arguments (int argc, char *argv[])
  403. {
  404. if (argc <= 0) {
  405. return 0;
  406. }
  407. options.help = 0;
  408. options.version = 0;
  409. options.logger = LOGGER_STDERR;
  410. options.logger_syslog_facility = "daemon";
  411. options.logger_syslog_ident = argv[0];
  412. options.loglevel = -1;
  413. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  414. options.loglevels[i] = -1;
  415. }
  416. options.config_file = NULL;
  417. options.retry_time = DEFAULT_RETRY_TIME;
  418. options.no_udev = 0;
  419. options.extra_args = NULL;
  420. options.num_extra_args = 0;
  421. for (int i = 1; i < argc; i++) {
  422. char *arg = argv[i];
  423. if (!strcmp(arg, "--help")) {
  424. options.help = 1;
  425. }
  426. else if (!strcmp(arg, "--version")) {
  427. options.version = 1;
  428. }
  429. else if (!strcmp(arg, "--logger")) {
  430. if (1 >= argc - i) {
  431. fprintf(stderr, "%s: requires an argument\n", arg);
  432. return 0;
  433. }
  434. char *arg2 = argv[i + 1];
  435. if (!strcmp(arg2, "stdout")) {
  436. options.logger = LOGGER_STDOUT;
  437. }
  438. else if (!strcmp(arg2, "stderr")) {
  439. options.logger = LOGGER_STDERR;
  440. }
  441. else if (!strcmp(arg2, "syslog")) {
  442. options.logger = LOGGER_SYSLOG;
  443. }
  444. else {
  445. fprintf(stderr, "%s: wrong argument\n", arg);
  446. return 0;
  447. }
  448. i++;
  449. }
  450. else if (!strcmp(arg, "--syslog-facility")) {
  451. if (1 >= argc - i) {
  452. fprintf(stderr, "%s: requires an argument\n", arg);
  453. return 0;
  454. }
  455. options.logger_syslog_facility = argv[i + 1];
  456. i++;
  457. }
  458. else if (!strcmp(arg, "--syslog-ident")) {
  459. if (1 >= argc - i) {
  460. fprintf(stderr, "%s: requires an argument\n", arg);
  461. return 0;
  462. }
  463. options.logger_syslog_ident = argv[i + 1];
  464. i++;
  465. }
  466. else if (!strcmp(arg, "--loglevel")) {
  467. if (1 >= argc - i) {
  468. fprintf(stderr, "%s: requires an argument\n", arg);
  469. return 0;
  470. }
  471. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  472. fprintf(stderr, "%s: wrong argument\n", arg);
  473. return 0;
  474. }
  475. i++;
  476. }
  477. else if (!strcmp(arg, "--channel-loglevel")) {
  478. if (2 >= argc - i) {
  479. fprintf(stderr, "%s: requires two arguments\n", arg);
  480. return 0;
  481. }
  482. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  483. if (channel < 0) {
  484. fprintf(stderr, "%s: wrong channel argument\n", arg);
  485. return 0;
  486. }
  487. int loglevel = parse_loglevel(argv[i + 2]);
  488. if (loglevel < 0) {
  489. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  490. return 0;
  491. }
  492. options.loglevels[channel] = loglevel;
  493. i += 2;
  494. }
  495. else if (!strcmp(arg, "--config-file")) {
  496. if (1 >= argc - i) {
  497. fprintf(stderr, "%s: requires an argument\n", arg);
  498. return 0;
  499. }
  500. options.config_file = argv[i + 1];
  501. i++;
  502. }
  503. else if (!strcmp(arg, "--retry-time")) {
  504. if (1 >= argc - i) {
  505. fprintf(stderr, "%s: requires an argument\n", arg);
  506. return 0;
  507. }
  508. if ((options.retry_time = atoi(argv[i + 1])) < 0) {
  509. fprintf(stderr, "%s: wrong argument\n", arg);
  510. return 0;
  511. }
  512. i++;
  513. }
  514. else if (!strcmp(arg, "--no-udev")) {
  515. options.no_udev = 1;
  516. }
  517. else if (!strcmp(arg, "--")) {
  518. options.extra_args = &argv[i + 1];
  519. options.num_extra_args = argc - i - 1;
  520. i += options.num_extra_args;
  521. }
  522. else {
  523. fprintf(stderr, "unknown option: %s\n", arg);
  524. return 0;
  525. }
  526. }
  527. if (options.help || options.version) {
  528. return 1;
  529. }
  530. if (!options.config_file) {
  531. fprintf(stderr, "--config-file is required\n");
  532. return 0;
  533. }
  534. return 1;
  535. }
  536. void signal_handler (void *unused)
  537. {
  538. BLog(BLOG_NOTICE, "termination requested");
  539. start_terminate(1);
  540. }
  541. void start_terminate (int exit_code)
  542. {
  543. main_exit_code = exit_code;
  544. if (terminating) {
  545. return;
  546. }
  547. terminating = 1;
  548. if (LinkedList2_IsEmpty(&processes)) {
  549. BReactor_Quit(&ss, 0);
  550. return;
  551. }
  552. // start terminating non-template processes
  553. LinkedList2Iterator it;
  554. LinkedList2Iterator_InitForward(&it, &processes);
  555. LinkedList2Node *n;
  556. while (n = LinkedList2Iterator_Next(&it)) {
  557. struct process *p = UPPER_OBJECT(n, struct process, list_node);
  558. if (p->module_process) {
  559. continue;
  560. }
  561. if (p->state != PSTATE_TERMINATING) {
  562. process_start_terminating(p);
  563. }
  564. }
  565. }
  566. int arg_value_init_string (struct arg_value *o, const char *string, size_t len)
  567. {
  568. o->type = ARG_VALUE_TYPE_STRING;
  569. if (!(o->string = malloc(len))) {
  570. BLog(BLOG_ERROR, "malloc failed");
  571. return 0;
  572. }
  573. memcpy(o->string, string, len);
  574. o->string_len = len;
  575. return 1;
  576. }
  577. int arg_value_init_variable (struct arg_value *o, struct NCDConfig_strings *ast_names)
  578. {
  579. ASSERT(ast_names)
  580. o->type = ARG_VALUE_TYPE_VARIABLE;
  581. if (!(o->variable_names = names_new(ast_names))) {
  582. return 0;
  583. }
  584. return 1;
  585. }
  586. void arg_value_init_list (struct arg_value *o)
  587. {
  588. o->type = ARG_VALUE_TYPE_LIST;
  589. LinkedList1_Init(&o->list);
  590. }
  591. int arg_value_list_append (struct arg_value *o, struct arg_value v)
  592. {
  593. ASSERT(o->type == ARG_VALUE_TYPE_LIST)
  594. struct arg_list_elem *elem = malloc(sizeof(*elem));
  595. if (!elem) {
  596. BLog(BLOG_ERROR, "malloc failed");
  597. return 0;
  598. }
  599. LinkedList1_Append(&o->list, &elem->list_node);
  600. elem->value = v;
  601. return 1;
  602. }
  603. void arg_value_init_map (struct arg_value *o)
  604. {
  605. o->type = ARG_VALUE_TYPE_MAP;
  606. LinkedList1_Init(&o->maplist);
  607. }
  608. int arg_value_map_append (struct arg_value *o, struct arg_value key, struct arg_value val)
  609. {
  610. ASSERT(o->type == ARG_VALUE_TYPE_MAP)
  611. struct arg_map_elem *elem = malloc(sizeof(*elem));
  612. if (!elem) {
  613. BLog(BLOG_ERROR, "malloc failed");
  614. return 0;
  615. }
  616. LinkedList1_Append(&o->maplist, &elem->maplist_node);
  617. elem->key = key;
  618. elem->val = val;
  619. return 1;
  620. }
  621. void arg_value_free (struct arg_value *o)
  622. {
  623. switch (o->type) {
  624. case ARG_VALUE_TYPE_STRING: {
  625. free(o->string);
  626. } break;
  627. case ARG_VALUE_TYPE_VARIABLE: {
  628. names_free(o->variable_names);
  629. } break;
  630. case ARG_VALUE_TYPE_LIST: {
  631. while (!LinkedList1_IsEmpty(&o->list)) {
  632. struct arg_list_elem *elem = UPPER_OBJECT(LinkedList1_GetFirst(&o->list), struct arg_list_elem, list_node);
  633. arg_value_free(&elem->value);
  634. LinkedList1_Remove(&o->list, &elem->list_node);
  635. free(elem);
  636. }
  637. } break;
  638. case ARG_VALUE_TYPE_MAP: {
  639. while (!LinkedList1_IsEmpty(&o->maplist)) {
  640. struct arg_map_elem *elem = UPPER_OBJECT(LinkedList1_GetFirst(&o->maplist), struct arg_map_elem, maplist_node);
  641. arg_value_free(&elem->key);
  642. arg_value_free(&elem->val);
  643. LinkedList1_Remove(&o->maplist, &elem->maplist_node);
  644. free(elem);
  645. }
  646. } break;
  647. default: ASSERT(0);
  648. }
  649. }
  650. int build_arg_from_ast (struct arg_value *o, struct NCDConfig_list *ast)
  651. {
  652. switch (ast->type) {
  653. case NCDCONFIG_ARG_STRING: {
  654. if (!arg_value_init_string(o, ast->string, ast->string_len)) {
  655. return 0;
  656. }
  657. } break;
  658. case NCDCONFIG_ARG_VAR: {
  659. if (!arg_value_init_variable(o, ast->var)) {
  660. return 0;
  661. }
  662. } break;
  663. case NCDCONFIG_ARG_LIST: {
  664. if (!build_arg_list_from_ast_list(o, ast->list)) {
  665. return 0;
  666. }
  667. } break;
  668. case NCDCONFIG_ARG_MAPLIST: {
  669. if (!build_arg_map_from_ast_list(o, ast->list)) {
  670. return 0;
  671. }
  672. } break;
  673. default: ASSERT(0);
  674. }
  675. return 1;
  676. }
  677. int build_arg_list_from_ast_list (struct arg_value *o, struct NCDConfig_list *list)
  678. {
  679. arg_value_init_list(o);
  680. for (struct NCDConfig_list *c = list; c; c = c->next) {
  681. struct arg_value e;
  682. if (!build_arg_from_ast(&e, c)) {
  683. goto fail;
  684. }
  685. if (!arg_value_list_append(o, e)) {
  686. arg_value_free(&e);
  687. goto fail;
  688. }
  689. }
  690. return 1;
  691. fail:
  692. arg_value_free(o);
  693. return 0;
  694. }
  695. int build_arg_map_from_ast_list (struct arg_value *o, struct NCDConfig_list *list)
  696. {
  697. arg_value_init_map(o);
  698. for (struct NCDConfig_list *c = list; c; c = c->next->next) {
  699. ASSERT(c->next)
  700. struct arg_value key;
  701. struct arg_value val;
  702. if (!build_arg_from_ast(&key, c)) {
  703. goto fail;
  704. }
  705. if (!build_arg_from_ast(&val, c->next)) {
  706. arg_value_free(&key);
  707. goto fail;
  708. }
  709. if (!arg_value_map_append(o, key, val)) {
  710. arg_value_free(&key);
  711. arg_value_free(&val);
  712. goto fail;
  713. }
  714. }
  715. return 1;
  716. fail:
  717. arg_value_free(o);
  718. return 0;
  719. }
  720. static char ** names_new (struct NCDConfig_strings *ast_names)
  721. {
  722. ASSERT(ast_names)
  723. bsize_t size = bsize_fromsize(1);
  724. for (struct NCDConfig_strings *n = ast_names; n; n = n->next) {
  725. size = bsize_add(size, bsize_fromsize(1));
  726. }
  727. char **names;
  728. if (size.is_overflow || !(names = BAllocArray(size.value, sizeof(names[0])))) {
  729. BLog(BLOG_ERROR, "BAllocArray failed");
  730. goto fail0;
  731. }
  732. size_t i = 0;
  733. for (struct NCDConfig_strings *n = ast_names; n; n = n->next) {
  734. if (!(names[i] = strdup(n->value))) {
  735. BLog(BLOG_ERROR, "strdup failed");
  736. goto fail1;
  737. }
  738. i++;
  739. }
  740. names[i] = NULL;
  741. return names;
  742. fail1:
  743. while (i-- > 0) {
  744. free(names[i]);
  745. }
  746. BFree(names);
  747. fail0:
  748. return NULL;
  749. }
  750. static size_t names_count (char **names)
  751. {
  752. ASSERT(names)
  753. size_t i;
  754. for (i = 0; names[i]; i++);
  755. return i;
  756. }
  757. static char * names_tostring (char **names)
  758. {
  759. ASSERT(names)
  760. ExpString str;
  761. if (!ExpString_Init(&str)) {
  762. goto fail0;
  763. }
  764. for (size_t i = 0; names[i]; i++) {
  765. if (i > 0 && !ExpString_AppendChar(&str, '.')) {
  766. goto fail1;
  767. }
  768. if (!ExpString_Append(&str, names[i])) {
  769. goto fail1;
  770. }
  771. }
  772. return ExpString_Get(&str);
  773. fail1:
  774. ExpString_Free(&str);
  775. fail0:
  776. return NULL;
  777. }
  778. static void names_free (char **names)
  779. {
  780. ASSERT(names)
  781. size_t i = names_count(names);
  782. while (i-- > 0) {
  783. free(names[i]);
  784. }
  785. BFree(names);
  786. }
  787. int statement_init (struct statement *s, struct NCDConfig_statements *conf)
  788. {
  789. // set object names
  790. if (conf->objname) {
  791. if (!(s->object_names = names_new(conf->objname))) {
  792. goto fail0;
  793. }
  794. } else {
  795. s->object_names = NULL;
  796. }
  797. // set method name
  798. if (!(s->method_name = NCDConfig_concat_strings(conf->names))) {
  799. BLog(BLOG_ERROR, "NCDConfig_concat_strings failed");
  800. goto fail1;
  801. }
  802. // init name
  803. if (conf->name) {
  804. if (!(s->name = strdup(conf->name))) {
  805. BLog(BLOG_ERROR, "strdup failed");
  806. goto fail2;
  807. }
  808. } else {
  809. s->name = NULL;
  810. }
  811. // init arguments
  812. if (!build_arg_list_from_ast_list(&s->args, conf->args)) {
  813. BLog(BLOG_ERROR, "build_arg_list_from_ast_list failed");
  814. goto fail3;
  815. }
  816. return 1;
  817. fail3:
  818. free(s->name);
  819. fail2:
  820. free(s->method_name);
  821. fail1:
  822. if (s->object_names) {
  823. names_free(s->object_names);
  824. }
  825. fail0:
  826. return 0;
  827. }
  828. void statement_free (struct statement *s)
  829. {
  830. // free arguments
  831. arg_value_free(&s->args);
  832. // free name
  833. free(s->name);
  834. // free method name
  835. free(s->method_name);
  836. // free object names
  837. if (s->object_names) {
  838. names_free(s->object_names);
  839. }
  840. }
  841. int process_new (struct NCDConfig_processes *conf, NCDModuleProcess *module_process)
  842. {
  843. // allocate strucure
  844. struct process *p = malloc(sizeof(*p));
  845. if (!p) {
  846. BLog(BLOG_ERROR, "malloc failed");
  847. goto fail0;
  848. }
  849. // set module process
  850. p->module_process = module_process;
  851. // set module process handlers
  852. if (p->module_process) {
  853. NCDModuleProcess_Interp_SetHandlers(p->module_process, p,
  854. (NCDModuleProcess_interp_func_event)process_moduleprocess_func_event,
  855. (NCDModuleProcess_interp_func_getobj)process_moduleprocess_func_getobj);
  856. }
  857. // init name
  858. if (!(p->name = strdup(conf->name))) {
  859. BLog(BLOG_ERROR, "strdup failed");
  860. goto fail1;
  861. }
  862. // count statements
  863. size_t num_st = 0;
  864. struct NCDConfig_statements *st = conf->statements;
  865. while (st) {
  866. if (num_st == SIZE_MAX) {
  867. BLog(BLOG_ERROR, "too many statements");
  868. goto fail2;
  869. }
  870. num_st++;
  871. st = st->next;
  872. }
  873. // allocate statements array
  874. if (!(p->statements = BAllocArray(num_st, sizeof(p->statements[0])))) {
  875. goto fail2;
  876. }
  877. p->num_statements = 0;
  878. // init statements
  879. st = conf->statements;
  880. while (st) {
  881. struct process_statement *ps = &p->statements[p->num_statements];
  882. ps->p = p;
  883. ps->i = p->num_statements;
  884. if (!statement_init(&ps->s, st)) {
  885. goto fail3;
  886. }
  887. ps->state = SSTATE_FORGOTTEN;
  888. ps->have_error = 0;
  889. p->num_statements++;
  890. st = st->next;
  891. }
  892. // set state working
  893. p->state = PSTATE_WORKING;
  894. // set AP=0
  895. p->ap = 0;
  896. // set FP=0
  897. p->fp = 0;
  898. // init timer
  899. BTimer_Init(&p->wait_timer, 0, (BTimer_handler)process_wait_timer_handler, p);
  900. // init advance job
  901. BPending_Init(&p->advance_job, BReactor_PendingGroup(&ss), (BPending_handler)process_advance_job_handler, p);
  902. // init work job
  903. BPending_Init(&p->work_job, BReactor_PendingGroup(&ss), (BPending_handler)process_work_job_handler, p);
  904. // insert to processes list
  905. LinkedList2_Append(&processes, &p->list_node);
  906. // schedule work
  907. BPending_Set(&p->work_job);
  908. return 1;
  909. fail3:
  910. process_free_statements(p);
  911. fail2:
  912. free(p->name);
  913. fail1:
  914. free(p);
  915. fail0:
  916. BLog(BLOG_ERROR, "failed to initialize process %s", conf->name);
  917. return 0;
  918. }
  919. void process_free (struct process *p)
  920. {
  921. ASSERT(p->ap == 0)
  922. ASSERT(p->fp == 0)
  923. ASSERT(p->state == PSTATE_TERMINATING)
  924. // inform module process that the process is terminated
  925. if (p->module_process) {
  926. NCDModuleProcess_Interp_Terminated(p->module_process);
  927. }
  928. // remove from processes list
  929. LinkedList2_Remove(&processes, &p->list_node);
  930. // free work job
  931. BPending_Free(&p->work_job);
  932. // free advance job
  933. BPending_Free(&p->advance_job);
  934. // free timer
  935. BReactor_RemoveTimer(&ss, &p->wait_timer);
  936. // free statements
  937. process_free_statements(p);
  938. // free name
  939. free(p->name);
  940. // free strucure
  941. free(p);
  942. }
  943. void process_start_terminating (struct process *p)
  944. {
  945. ASSERT(p->state != PSTATE_TERMINATING)
  946. // set terminating
  947. p->state = PSTATE_TERMINATING;
  948. // schedule work
  949. process_schedule_work(p);
  950. }
  951. size_t process_rap (struct process *p)
  952. {
  953. if (p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD) {
  954. return (p->ap - 1);
  955. } else {
  956. return p->ap;
  957. }
  958. }
  959. void process_free_statements (struct process *p)
  960. {
  961. // free statments
  962. while (p->num_statements > 0) {
  963. statement_free(&p->statements[p->num_statements - 1].s);
  964. p->num_statements--;
  965. }
  966. // free stataments array
  967. free(p->statements);
  968. }
  969. void process_assert_pointers (struct process *p)
  970. {
  971. ASSERT(p->ap <= p->num_statements)
  972. ASSERT(p->fp >= p->ap)
  973. ASSERT(p->fp <= p->num_statements)
  974. #ifndef NDEBUG
  975. // check AP
  976. for (size_t i = 0; i < p->ap; i++) {
  977. if (i == p->ap - 1) {
  978. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  979. } else {
  980. ASSERT(p->statements[i].state == SSTATE_ADULT)
  981. }
  982. }
  983. // check FP
  984. size_t fp = p->num_statements;
  985. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  986. fp--;
  987. }
  988. ASSERT(p->fp == fp)
  989. #endif
  990. }
  991. void process_logfunc (struct process *p)
  992. {
  993. BLog_Append("process %s: ", p->name);
  994. }
  995. void process_log (struct process *p, int level, const char *fmt, ...)
  996. {
  997. va_list vl;
  998. va_start(vl, fmt);
  999. BLog_LogViaFuncVarArg((BLog_logfunc)process_logfunc, p, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1000. va_end(vl);
  1001. }
  1002. void process_schedule_work (struct process *p)
  1003. {
  1004. process_assert_pointers(p);
  1005. // stop timer
  1006. BReactor_RemoveTimer(&ss, &p->wait_timer);
  1007. // stop advance job
  1008. BPending_Unset(&p->advance_job);
  1009. // schedule work
  1010. BPending_Set(&p->work_job);
  1011. }
  1012. void process_work_job_handler (struct process *p)
  1013. {
  1014. process_assert_pointers(p);
  1015. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  1016. ASSERT(!BPending_IsSet(&p->advance_job))
  1017. if (p->state == PSTATE_WAITING) {
  1018. return;
  1019. }
  1020. if (p->state == PSTATE_TERMINATING) {
  1021. if (p->fp == 0) {
  1022. // finished retreating
  1023. process_free(p);
  1024. // if program is terminating amd there are no more processes, exit program
  1025. if (terminating && LinkedList2_IsEmpty(&processes)) {
  1026. BReactor_Quit(&ss, 0);
  1027. }
  1028. return;
  1029. }
  1030. // order the last living statement to die, if needed
  1031. struct process_statement *ps = &p->statements[p->fp - 1];
  1032. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1033. if (ps->state != SSTATE_DYING) {
  1034. process_statement_log(ps, BLOG_INFO, "killing");
  1035. // order it to die
  1036. NCDModuleInst_Die(&ps->inst);
  1037. // set statement state DYING
  1038. ps->state = SSTATE_DYING;
  1039. // update AP
  1040. if (p->ap > ps->i) {
  1041. p->ap = ps->i;
  1042. }
  1043. }
  1044. return;
  1045. }
  1046. // process was up but is no longer?
  1047. if (p->state == PSTATE_UP && !(p->ap == process_rap(p) && p->ap == p->num_statements)) {
  1048. // if we have module process, wait for its permission to continue
  1049. if (p->module_process) {
  1050. // set module process down
  1051. NCDModuleProcess_Interp_Down(p->module_process);
  1052. // set state waiting
  1053. p->state = PSTATE_WAITING;
  1054. return;
  1055. }
  1056. // set state working
  1057. p->state = PSTATE_WORKING;
  1058. }
  1059. // cleaning up?
  1060. if (p->ap < p->fp) {
  1061. // order the last living statement to die, if needed
  1062. struct process_statement *ps = &p->statements[p->fp - 1];
  1063. if (ps->state != SSTATE_DYING) {
  1064. process_statement_log(ps, BLOG_INFO, "killing");
  1065. // order it to die
  1066. NCDModuleInst_Die(&ps->inst);
  1067. // set statement state DYING
  1068. ps->state = SSTATE_DYING;
  1069. }
  1070. return;
  1071. }
  1072. // clean?
  1073. if (p->ap > process_rap(p)) {
  1074. ASSERT(p->ap > 0)
  1075. ASSERT(p->ap <= p->num_statements)
  1076. struct process_statement *ps = &p->statements[p->ap - 1];
  1077. ASSERT(ps->state == SSTATE_CHILD)
  1078. process_statement_log(ps, BLOG_INFO, "clean");
  1079. // report clean
  1080. NCDModuleInst_Clean(&ps->inst);
  1081. return;
  1082. }
  1083. // advancing?
  1084. if (p->ap < p->num_statements) {
  1085. ASSERT(p->state == PSTATE_WORKING)
  1086. struct process_statement *ps = &p->statements[p->ap];
  1087. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1088. // clear expired error
  1089. if (ps->have_error && ps->error_until <= btime_gettime()) {
  1090. ps->have_error = 0;
  1091. }
  1092. if (ps->have_error) {
  1093. process_statement_log(ps, BLOG_INFO, "waiting after error");
  1094. // set wait timer
  1095. BReactor_SetTimerAbsolute(&ss, &p->wait_timer, ps->error_until);
  1096. } else {
  1097. // schedule advance
  1098. BPending_Set(&p->advance_job);
  1099. }
  1100. return;
  1101. }
  1102. // have we just finished?
  1103. if (p->state == PSTATE_WORKING) {
  1104. process_log(p, BLOG_INFO, "victory");
  1105. // set module process up
  1106. if (p->module_process) {
  1107. NCDModuleProcess_Interp_Up(p->module_process);
  1108. }
  1109. // set state up
  1110. p->state = PSTATE_UP;
  1111. }
  1112. }
  1113. void process_advance_job_handler (struct process *p)
  1114. {
  1115. process_assert_pointers(p);
  1116. ASSERT(p->ap == p->fp)
  1117. ASSERT(p->ap == process_rap(p))
  1118. ASSERT(p->ap < p->num_statements)
  1119. ASSERT(!p->statements[p->ap].have_error)
  1120. ASSERT(!BPending_IsSet(&p->work_job))
  1121. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  1122. ASSERT(p->state == PSTATE_WORKING)
  1123. struct process_statement *ps = &p->statements[p->ap];
  1124. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1125. process_statement_log(ps, BLOG_INFO, "initializing");
  1126. NCDObject object;
  1127. NCDObject *object_ptr = NULL;
  1128. char *type;
  1129. int free_type = 0;
  1130. if (!ps->s.object_names) {
  1131. // this is a function_call(); type is "function_call"
  1132. type = ps->s.method_name;
  1133. } else {
  1134. // this is a some.object.somewhere->method_call(); type is "base_type(some.object.somewhere)::method_call"
  1135. // get object
  1136. if (!process_resolve_object_expr(p, p->ap, ps->s.object_names, &object)) {
  1137. goto fail;
  1138. }
  1139. object_ptr = &object;
  1140. // get object type
  1141. const char *object_type = NCDObject_Type(&object);
  1142. if (!object_type) {
  1143. process_statement_log(ps, BLOG_ERROR, "cannot call method on object with no type");
  1144. goto fail;
  1145. }
  1146. // build type string
  1147. if (!(type = concat_strings(3, object_type, "::", ps->s.method_name))) {
  1148. process_statement_log(ps, BLOG_ERROR, "concat_strings failed");
  1149. goto fail;
  1150. }
  1151. free_type = 1;
  1152. }
  1153. // find module to instantiate
  1154. if (!(ps->module = NCDModuleIndex_FindModule(&mindex, type))) {
  1155. process_statement_log(ps, BLOG_ERROR, "failed to find module: %s", type);
  1156. goto fail;
  1157. }
  1158. // resolve arguments
  1159. if (!process_statement_resolve_argument(ps, &ps->s.args, &ps->inst_args)) {
  1160. process_statement_log(ps, BLOG_ERROR, "failed to resolve arguments");
  1161. goto fail;
  1162. }
  1163. // initialize module instance
  1164. NCDModuleInst_Init(&ps->inst, ps->module, object_ptr, &ps->inst_args, ps, &module_params);
  1165. // set statement state CHILD
  1166. ps->state = SSTATE_CHILD;
  1167. // increment AP
  1168. p->ap++;
  1169. // increment FP
  1170. p->fp++;
  1171. if (free_type) {
  1172. free(type);
  1173. }
  1174. process_assert_pointers(p);
  1175. return;
  1176. fail:
  1177. if (free_type) {
  1178. free(type);
  1179. }
  1180. // mark error
  1181. process_statement_set_error(ps);
  1182. // schedule work to start the timer
  1183. process_schedule_work(p);
  1184. }
  1185. void process_wait_timer_handler (struct process *p)
  1186. {
  1187. process_assert_pointers(p);
  1188. ASSERT(p->ap == p->fp)
  1189. ASSERT(p->ap == process_rap(p))
  1190. ASSERT(p->ap < p->num_statements)
  1191. ASSERT(p->statements[p->ap].have_error)
  1192. ASSERT(!BPending_IsSet(&p->work_job))
  1193. ASSERT(!BPending_IsSet(&p->advance_job))
  1194. ASSERT(p->state == PSTATE_WORKING)
  1195. process_log(p, BLOG_INFO, "retrying");
  1196. // clear error
  1197. p->statements[p->ap].have_error = 0;
  1198. // schedule work
  1199. BPending_Set(&p->work_job);
  1200. }
  1201. int process_find_object (struct process *p, size_t pos, const char *name, NCDObject *out_object)
  1202. {
  1203. ASSERT(pos <= p->num_statements)
  1204. ASSERT(name)
  1205. ASSERT(out_object)
  1206. for (size_t i = pos; i > 0; i--) {
  1207. struct process_statement *ps = &p->statements[i - 1];
  1208. if (ps->s.name && !strcmp(ps->s.name, name)) {
  1209. if (ps->state == SSTATE_FORGOTTEN) {
  1210. process_log(p, BLOG_ERROR, "statement (%zu) is uninitialized", i - 1);
  1211. goto fail;
  1212. }
  1213. *out_object = NCDModuleInst_Object(&ps->inst);
  1214. return 1;
  1215. }
  1216. }
  1217. if (p->module_process && NCDModuleProcess_Interp_GetSpecialObj(p->module_process, name, out_object)) {
  1218. return 1;
  1219. }
  1220. fail:
  1221. return 0;
  1222. }
  1223. int process_resolve_object_expr (struct process *p, size_t pos, char **names, NCDObject *out_object)
  1224. {
  1225. ASSERT(pos <= p->num_statements)
  1226. ASSERT(names)
  1227. ASSERT(names_count(names) > 0)
  1228. ASSERT(out_object)
  1229. NCDObject object;
  1230. if (!process_find_object(p, pos, names[0], &object)) {
  1231. goto fail;
  1232. }
  1233. if (!NCDObject_ResolveObjExpr(&object, names + 1, out_object)) {
  1234. goto fail;
  1235. }
  1236. return 1;
  1237. fail:;
  1238. char *name = names_tostring(names);
  1239. process_log(p, BLOG_ERROR, "failed to resolve object (%s) from position %zu", (name ? name : ""), pos);
  1240. free(name);
  1241. return 0;
  1242. }
  1243. int process_resolve_variable_expr (struct process *p, size_t pos, char **names, NCDValue *out_value)
  1244. {
  1245. ASSERT(pos <= p->num_statements)
  1246. ASSERT(names)
  1247. ASSERT(names_count(names) > 0)
  1248. ASSERT(out_value)
  1249. NCDObject object;
  1250. if (!process_find_object(p, pos, names[0], &object)) {
  1251. goto fail;
  1252. }
  1253. if (!NCDObject_ResolveVarExpr(&object, names + 1, out_value)) {
  1254. goto fail;
  1255. }
  1256. return 1;
  1257. fail:;
  1258. char *name = names_tostring(names);
  1259. process_log(p, BLOG_ERROR, "failed to resolve variable (%s) from position %zu", (name ? name : ""), pos);
  1260. free(name);
  1261. return 0;
  1262. }
  1263. void process_statement_logfunc (struct process_statement *ps)
  1264. {
  1265. process_logfunc(ps->p);
  1266. BLog_Append("statement %zu: ", ps->i);
  1267. }
  1268. void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...)
  1269. {
  1270. va_list vl;
  1271. va_start(vl, fmt);
  1272. BLog_LogViaFuncVarArg((BLog_logfunc)process_statement_logfunc, ps, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1273. va_end(vl);
  1274. }
  1275. void process_statement_set_error (struct process_statement *ps)
  1276. {
  1277. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1278. ps->have_error = 1;
  1279. ps->error_until = btime_add(btime_gettime(), options.retry_time);
  1280. }
  1281. int process_statement_resolve_argument (struct process_statement *ps, struct arg_value *arg, NCDValue *out)
  1282. {
  1283. ASSERT(ps->i <= process_rap(ps->p))
  1284. ASSERT(arg)
  1285. ASSERT(out)
  1286. switch (arg->type) {
  1287. case ARG_VALUE_TYPE_STRING: {
  1288. if (!NCDValue_InitStringBin(out, arg->string, arg->string_len)) {
  1289. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitStringBin failed");
  1290. return 0;
  1291. }
  1292. } break;
  1293. case ARG_VALUE_TYPE_VARIABLE: {
  1294. if (!process_resolve_variable_expr(ps->p, ps->i, arg->variable_names, out)) {
  1295. return 0;
  1296. }
  1297. } break;
  1298. case ARG_VALUE_TYPE_LIST: do {
  1299. NCDValue_InitList(out);
  1300. for (LinkedList1Node *n = LinkedList1_GetFirst(&arg->list); n; n = LinkedList1Node_Next(n)) {
  1301. struct arg_list_elem *elem = UPPER_OBJECT(n, struct arg_list_elem, list_node);
  1302. NCDValue v;
  1303. if (!process_statement_resolve_argument(ps, &elem->value, &v)) {
  1304. goto list_fail1;
  1305. }
  1306. if (!NCDValue_ListAppend(out, v)) {
  1307. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  1308. NCDValue_Free(&v);
  1309. goto list_fail1;
  1310. }
  1311. }
  1312. break;
  1313. list_fail1:
  1314. NCDValue_Free(out);
  1315. return 0;
  1316. } while (0); break;
  1317. case ARG_VALUE_TYPE_MAP: do {
  1318. NCDValue_InitMap(out);
  1319. for (LinkedList1Node *n = LinkedList1_GetFirst(&arg->maplist); n; n = LinkedList1Node_Next(n)) {
  1320. struct arg_map_elem *elem = UPPER_OBJECT(n, struct arg_map_elem, maplist_node);
  1321. NCDValue key;
  1322. NCDValue val;
  1323. if (!process_statement_resolve_argument(ps, &elem->key, &key)) {
  1324. goto map_fail;
  1325. }
  1326. if (!process_statement_resolve_argument(ps, &elem->val, &val)) {
  1327. NCDValue_Free(&key);
  1328. goto map_fail;
  1329. }
  1330. if (NCDValue_MapFindKey(out, &key)) {
  1331. process_statement_log(ps, BLOG_ERROR, "duplicate map keys");
  1332. NCDValue_Free(&key);
  1333. NCDValue_Free(&val);
  1334. goto map_fail;
  1335. }
  1336. if (!NCDValue_MapInsert(out, key, val)) {
  1337. process_statement_log(ps, BLOG_ERROR, "NCDValue_MapInsert failed");
  1338. NCDValue_Free(&key);
  1339. NCDValue_Free(&val);
  1340. goto map_fail;
  1341. }
  1342. }
  1343. break;
  1344. map_fail:
  1345. NCDValue_Free(out);
  1346. return 0;
  1347. } while (0); break;
  1348. default: ASSERT(0);
  1349. }
  1350. return 1;
  1351. }
  1352. void process_statement_instance_func_event (struct process_statement *ps, int event)
  1353. {
  1354. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  1355. struct process *p = ps->p;
  1356. process_assert_pointers(p);
  1357. // schedule work
  1358. process_schedule_work(p);
  1359. switch (event) {
  1360. case NCDMODULE_EVENT_UP: {
  1361. ASSERT(ps->state == SSTATE_CHILD)
  1362. process_statement_log(ps, BLOG_INFO, "up");
  1363. // set state ADULT
  1364. ps->state = SSTATE_ADULT;
  1365. } break;
  1366. case NCDMODULE_EVENT_DOWN: {
  1367. ASSERT(ps->state == SSTATE_ADULT)
  1368. process_statement_log(ps, BLOG_INFO, "down");
  1369. // set state CHILD
  1370. ps->state = SSTATE_CHILD;
  1371. // update AP
  1372. if (p->ap > ps->i + 1) {
  1373. p->ap = ps->i + 1;
  1374. }
  1375. } break;
  1376. case NCDMODULE_EVENT_DEAD: {
  1377. int is_error = NCDModuleInst_HaveError(&ps->inst);
  1378. if (is_error) {
  1379. process_statement_log(ps, BLOG_ERROR, "died with error");
  1380. } else {
  1381. process_statement_log(ps, BLOG_INFO, "died");
  1382. }
  1383. // free instance
  1384. NCDModuleInst_Free(&ps->inst);
  1385. // free instance arguments
  1386. NCDValue_Free(&ps->inst_args);
  1387. // set state FORGOTTEN
  1388. ps->state = SSTATE_FORGOTTEN;
  1389. // set error
  1390. if (is_error) {
  1391. process_statement_set_error(ps);
  1392. }
  1393. // update AP
  1394. if (p->ap > ps->i) {
  1395. p->ap = ps->i;
  1396. }
  1397. // update FP
  1398. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  1399. p->fp--;
  1400. }
  1401. } break;
  1402. }
  1403. }
  1404. int process_statement_instance_func_getobj (struct process_statement *ps, const char *objname, NCDObject *out_object)
  1405. {
  1406. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1407. return process_find_object(ps->p, ps->i, objname, out_object);
  1408. }
  1409. int process_statement_instance_func_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name)
  1410. {
  1411. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1412. // find template
  1413. struct NCDConfig_processes *conf = config_ast;
  1414. while (conf) {
  1415. if (conf->is_template && !strcmp(conf->name, template_name)) {
  1416. break;
  1417. }
  1418. conf = conf->next;
  1419. }
  1420. if (!conf) {
  1421. process_statement_log(ps, BLOG_ERROR, "no template named %s", template_name);
  1422. return 0;
  1423. }
  1424. // create process
  1425. if (!process_new(conf, mp)) {
  1426. process_statement_log(ps, BLOG_ERROR, "failed to create process from template %s", template_name);
  1427. return 0;
  1428. }
  1429. process_statement_log(ps, BLOG_INFO, "created process from template %s", template_name);
  1430. return 1;
  1431. }
  1432. void process_statement_instance_logfunc (struct process_statement *ps)
  1433. {
  1434. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1435. process_statement_logfunc(ps);
  1436. BLog_Append("module: ");
  1437. }
  1438. void process_statement_instance_func_interp_exit (struct process_statement *ps, int exit_code)
  1439. {
  1440. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1441. start_terminate(exit_code);
  1442. }
  1443. int process_statement_instance_func_interp_getargs (struct process_statement *ps, NCDValue *out_value)
  1444. {
  1445. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1446. NCDValue_InitList(out_value);
  1447. for (int i = 0; i < options.num_extra_args; i++) {
  1448. NCDValue arg;
  1449. if (!NCDValue_InitString(&arg, options.extra_args[i])) {
  1450. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitString failed");
  1451. goto fail1;
  1452. }
  1453. if (!NCDValue_ListAppend(out_value, arg)) {
  1454. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  1455. NCDValue_Free(&arg);
  1456. goto fail1;
  1457. }
  1458. }
  1459. return 1;
  1460. fail1:
  1461. NCDValue_Free(out_value);
  1462. return 0;
  1463. }
  1464. void process_moduleprocess_func_event (struct process *p, int event)
  1465. {
  1466. ASSERT(p->module_process)
  1467. switch (event) {
  1468. case NCDMODULEPROCESS_INTERP_EVENT_CONTINUE: {
  1469. ASSERT(p->state == PSTATE_WAITING)
  1470. // set state working
  1471. p->state = PSTATE_WORKING;
  1472. // schedule work
  1473. process_schedule_work(p);
  1474. } break;
  1475. case NCDMODULEPROCESS_INTERP_EVENT_TERMINATE: {
  1476. ASSERT(p->state != PSTATE_TERMINATING)
  1477. process_log(p, BLOG_INFO, "process termination requested");
  1478. // start terminating
  1479. process_start_terminating(p);
  1480. } break;
  1481. default: ASSERT(0);
  1482. }
  1483. }
  1484. int process_moduleprocess_func_getobj (struct process *p, const char *name, NCDObject *out_object)
  1485. {
  1486. ASSERT(p->module_process)
  1487. return process_find_object(p, p->num_statements, name, out_object);
  1488. }