ncd.c 50 KB

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