ncd.c 49 KB

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