ncd.c 49 KB

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