ncd.c 47 KB

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