ncd.c 49 KB

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