ncd.c 49 KB

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