ncd.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545
  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 <limits.h>
  34. #include <misc/version.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/open_standard_streams.h>
  40. #include <misc/expstring.h>
  41. #include <structure/LinkedList1.h>
  42. #include <base/BLog.h>
  43. #include <base/BLog_syslog.h>
  44. #include <system/BReactor.h>
  45. #include <system/BSignal.h>
  46. #include <system/BProcess.h>
  47. #include <udevmonitor/NCDUdevManager.h>
  48. #include <random/BRandom2.h>
  49. #include <ncd/NCDConfigParser.h>
  50. #include <ncd/NCDStringIndex.h>
  51. #include <ncd/NCDModule.h>
  52. #include <ncd/NCDModuleIndex.h>
  53. #include <ncd/NCDSugar.h>
  54. #include <ncd/NCDInterpProg.h>
  55. #include <ncd/modules/modules.h>
  56. #include "ncd.h"
  57. #include <generated/blog_channel_ncd.h>
  58. #define LOGGER_STDOUT 1
  59. #define LOGGER_STDERR 2
  60. #define LOGGER_SYSLOG 3
  61. #define SSTATE_CHILD 1
  62. #define SSTATE_ADULT 2
  63. #define SSTATE_DYING 3
  64. #define SSTATE_FORGOTTEN 4
  65. #define PSTATE_WORKING 0
  66. #define PSTATE_UP 1
  67. #define PSTATE_WAITING 2
  68. #define PSTATE_TERMINATING 3
  69. #define PROCESS_STATE_MASK 0x3
  70. #define PROCESS_ERROR_MASK 0x4
  71. #define PROCESS_STATE_SHIFT 0
  72. #define PROCESS_ERROR_SHIFT 2
  73. struct statement {
  74. NCDModuleInst inst;
  75. NCDValMem args_mem;
  76. char *mem;
  77. int mem_size;
  78. int i;
  79. int state;
  80. };
  81. struct process {
  82. NCDInterpProcess *iprocess;
  83. NCDModuleProcess *module_process;
  84. BSmallTimer wait_timer;
  85. BSmallPending work_job;
  86. LinkedList1Node list_node; // node in processes
  87. int ap;
  88. int fp;
  89. int num_statements;
  90. int state2_error1;
  91. struct statement statements[];
  92. };
  93. // command-line options
  94. static struct {
  95. int help;
  96. int version;
  97. int logger;
  98. char *logger_syslog_facility;
  99. char *logger_syslog_ident;
  100. int loglevel;
  101. int loglevels[BLOG_NUM_CHANNELS];
  102. char *config_file;
  103. int retry_time;
  104. int no_udev;
  105. char **extra_args;
  106. int num_extra_args;
  107. } options;
  108. // reactor
  109. static BReactor reactor;
  110. // are we terminating
  111. static int terminating;
  112. static int main_exit_code;
  113. // process manager
  114. static BProcessManager manager;
  115. // udev manager
  116. static NCDUdevManager umanager;
  117. // random number generator
  118. static BRandom2 random2;
  119. // string index
  120. static NCDStringIndex string_index;
  121. // method index
  122. static NCDMethodIndex method_index;
  123. // module index
  124. static NCDModuleIndex mindex;
  125. // program AST
  126. static NCDProgram program;
  127. // placeholder database
  128. static NCDPlaceholderDb placeholder_db;
  129. // structure for efficient interpretation
  130. static NCDInterpProg iprogram;
  131. // common module parameters
  132. static struct NCDModuleInst_params module_params;
  133. static struct NCDModuleInst_iparams module_iparams;
  134. // processes
  135. static LinkedList1 processes;
  136. static void print_help (const char *name);
  137. static void print_version (void);
  138. static int parse_arguments (int argc, char *argv[]);
  139. static void signal_handler (void *unused);
  140. static void start_terminate (int exit_code);
  141. static char * implode_id_strings (const NCD_string_id_t *names, size_t num_names, char del);
  142. static int alloc_base_type_strings (const struct NCDModuleGroup *g);
  143. static int process_new (NCDInterpProcess *iprocess, NCDModuleProcess *module_process);
  144. static void process_free (struct process *p, NCDModuleProcess **out_mp);
  145. static int process_state (struct process *p);
  146. static void process_set_state (struct process *p, int state);
  147. static int process_error (struct process *p);
  148. static void process_set_error (struct process *p, int error);
  149. static void process_start_terminating (struct process *p);
  150. static int process_have_child (struct process *p);
  151. static void process_assert_pointers (struct process *p);
  152. static void process_logfunc (struct process *p);
  153. static void process_log (struct process *p, int level, const char *fmt, ...);
  154. static void process_schedule_work (struct process *p);
  155. static void process_work_job_handler (struct process *p);
  156. static int replace_placeholders_callback (void *arg, int plid, NCDValMem *mem, NCDValRef *out);
  157. static void process_advance (struct process *p);
  158. static void process_wait_timer_handler (BSmallTimer *timer);
  159. static int process_find_object (struct process *p, int pos, NCD_string_id_t name, NCDObject *out_object);
  160. static int process_resolve_object_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDObject *out_object);
  161. static int process_resolve_variable_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDValMem *mem, NCDValRef *out_value);
  162. static void statement_logfunc (struct statement *ps);
  163. static void statement_log (struct statement *ps, int level, const char *fmt, ...);
  164. static struct process * statement_process (struct statement *ps);
  165. static int statement_mem_is_allocated (struct statement *ps);
  166. static int statement_mem_size (struct statement *ps);
  167. static int statement_allocate_memory (struct statement *ps, int alloc_size);
  168. static void statement_instance_func_event (NCDModuleInst *inst, int event);
  169. static int statement_instance_func_getobj (NCDModuleInst *inst, NCD_string_id_t objname, NCDObject *out_object);
  170. static int statement_instance_func_initprocess (NCDModuleProcess *mp, NCD_string_id_t template_name);
  171. static void statement_instance_logfunc (NCDModuleInst *inst);
  172. static void statement_instance_func_interp_exit (int exit_code);
  173. static int statement_instance_func_interp_getargs (NCDValMem *mem, NCDValRef *out_value);
  174. static btime_t statement_instance_func_interp_getretrytime (void);
  175. static void process_moduleprocess_func_event (struct process *p, int event);
  176. static int process_moduleprocess_func_getobj (struct process *p, NCD_string_id_t name, NCDObject *out_object);
  177. int main (int argc, char **argv)
  178. {
  179. if (argc <= 0) {
  180. return 1;
  181. }
  182. // set exit code
  183. main_exit_code = 1;
  184. // open standard streams
  185. open_standard_streams();
  186. // parse command-line arguments
  187. if (!parse_arguments(argc, argv)) {
  188. fprintf(stderr, "Failed to parse arguments\n");
  189. print_help(argv[0]);
  190. goto fail0;
  191. }
  192. // handle --help and --version
  193. if (options.help) {
  194. print_version();
  195. print_help(argv[0]);
  196. return 0;
  197. }
  198. if (options.version) {
  199. print_version();
  200. return 0;
  201. }
  202. // initialize logger
  203. switch (options.logger) {
  204. case LOGGER_STDOUT:
  205. BLog_InitStdout();
  206. break;
  207. case LOGGER_STDERR:
  208. BLog_InitStderr();
  209. break;
  210. case LOGGER_SYSLOG:
  211. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  212. fprintf(stderr, "Failed to initialize syslog logger\n");
  213. goto fail0;
  214. }
  215. break;
  216. default:
  217. ASSERT(0);
  218. }
  219. // configure logger channels
  220. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  221. if (options.loglevels[i] >= 0) {
  222. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  223. }
  224. else if (options.loglevel >= 0) {
  225. BLog_SetChannelLoglevel(i, options.loglevel);
  226. }
  227. }
  228. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  229. // initialize network
  230. if (!BNetwork_GlobalInit()) {
  231. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  232. goto fail1;
  233. }
  234. // init time
  235. BTime_Init();
  236. // init reactor
  237. if (!BReactor_Init(&reactor)) {
  238. BLog(BLOG_ERROR, "BReactor_Init failed");
  239. goto fail1;
  240. }
  241. // set not terminating
  242. terminating = 0;
  243. // init process manager
  244. if (!BProcessManager_Init(&manager, &reactor)) {
  245. BLog(BLOG_ERROR, "BProcessManager_Init failed");
  246. goto fail1a;
  247. }
  248. // init udev manager
  249. NCDUdevManager_Init(&umanager, options.no_udev, &reactor, &manager);
  250. // init random number generator
  251. if (!BRandom2_Init(&random2, BRANDOM2_INIT_LAZY)) {
  252. BLog(BLOG_ERROR, "BRandom2_Init failed");
  253. goto fail1aa;
  254. }
  255. // init string index
  256. if (!NCDStringIndex_Init(&string_index)) {
  257. BLog(BLOG_ERROR, "NCDStringIndex_Init failed");
  258. goto fail1aaa;
  259. }
  260. // init method index
  261. if (!NCDMethodIndex_Init(&method_index, &string_index)) {
  262. BLog(BLOG_ERROR, "NCDMethodIndex_Init failed");
  263. goto fail1b;
  264. }
  265. // init module index
  266. if (!NCDModuleIndex_Init(&mindex)) {
  267. BLog(BLOG_ERROR, "NCDModuleIndex_Init failed");
  268. goto fail1c;
  269. }
  270. // add module groups to index and allocate string id's for base_type's
  271. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  272. if (!NCDModuleIndex_AddGroup(&mindex, *g, &method_index)) {
  273. BLog(BLOG_ERROR, "NCDModuleIndex_AddGroup failed");
  274. goto fail2;
  275. }
  276. if (!alloc_base_type_strings(*g)) {
  277. goto fail2;
  278. }
  279. }
  280. // setup signal handler
  281. if (!BSignal_Init(&reactor, signal_handler, NULL)) {
  282. BLog(BLOG_ERROR, "BSignal_Init failed");
  283. goto fail2;
  284. }
  285. // read config file
  286. uint8_t *file;
  287. size_t file_len;
  288. if (!read_file(options.config_file, &file, &file_len)) {
  289. BLog(BLOG_ERROR, "failed to read config file");
  290. goto fail3;
  291. }
  292. // parse config file
  293. if (!NCDConfigParser_Parse((char *)file, file_len, &program)) {
  294. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  295. free(file);
  296. goto fail3;
  297. }
  298. // fee config file memory
  299. free(file);
  300. // desugar
  301. if (!NCDSugar_Desugar(&program)) {
  302. BLog(BLOG_ERROR, "NCDSugar_Desugar failed");
  303. goto fail4;
  304. }
  305. // init placeholder database
  306. if (!NCDPlaceholderDb_Init(&placeholder_db, &string_index)) {
  307. BLog(BLOG_ERROR, "NCDPlaceholderDb_Init failed");
  308. goto fail4;
  309. }
  310. // init interp program
  311. if (!NCDInterpProg_Init(&iprogram, &program, &string_index, &placeholder_db, &mindex, &method_index)) {
  312. BLog(BLOG_ERROR, "NCDInterpProg_Init failed");
  313. goto fail4a;
  314. }
  315. // init pointers to global resources in out struct NCDModuleInst_iparams.
  316. // Don't initialize any callback at this point as these must not be called
  317. // from globalinit functions of modules.
  318. module_iparams.reactor = &reactor;
  319. module_iparams.manager = &manager;
  320. module_iparams.umanager = &umanager;
  321. module_iparams.random2 = &random2;
  322. module_iparams.string_index = &string_index;
  323. // init modules
  324. size_t num_inited_modules = 0;
  325. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  326. // map strings
  327. if ((*g)->strings && !NCDStringIndex_GetRequests(&string_index, (*g)->strings)) {
  328. BLog(BLOG_ERROR, "NCDStringIndex_GetRequests failed for some module");
  329. goto fail5;
  330. }
  331. // call func_globalinit
  332. if ((*g)->func_globalinit && !(*g)->func_globalinit(&module_iparams)) {
  333. BLog(BLOG_ERROR, "globalinit failed for some module");
  334. goto fail5;
  335. }
  336. num_inited_modules++;
  337. }
  338. // init the rest of the module parameters structures
  339. module_params.func_event = statement_instance_func_event;
  340. module_params.func_getobj = statement_instance_func_getobj;
  341. module_params.logfunc = (BLog_logfunc)statement_instance_logfunc;
  342. module_params.iparams = &module_iparams;
  343. module_iparams.func_initprocess = statement_instance_func_initprocess;
  344. module_iparams.func_interp_exit = statement_instance_func_interp_exit;
  345. module_iparams.func_interp_getargs = statement_instance_func_interp_getargs;
  346. module_iparams.func_interp_getretrytime = statement_instance_func_interp_getretrytime;
  347. // init processes list
  348. LinkedList1_Init(&processes);
  349. // init processes
  350. for (NCDProcess *p = NCDProgram_FirstProcess(&program); p; p = NCDProgram_NextProcess(&program, p)) {
  351. if (NCDProcess_IsTemplate(p)) {
  352. continue;
  353. }
  354. // get string id for process name
  355. NCD_string_id_t name_id = NCDStringIndex_Lookup(&string_index, NCDProcess_Name(p));
  356. ASSERT(name_id >= 0)
  357. // find iprocess
  358. NCDInterpProcess *iprocess = NCDInterpProg_FindProcess(&iprogram, name_id);
  359. ASSERT(iprocess)
  360. if (!process_new(iprocess, NULL)) {
  361. BLog(BLOG_ERROR, "failed to initialize process, exiting");
  362. goto fail6;
  363. }
  364. }
  365. // enter event loop
  366. BLog(BLOG_NOTICE, "entering event loop");
  367. BReactor_Exec(&reactor);
  368. ASSERT(LinkedList1_IsEmpty(&processes))
  369. fail6:;
  370. LinkedList1Node *ln;
  371. while (ln = LinkedList1_GetFirst(&processes)) {
  372. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  373. NCDModuleProcess *mp;
  374. process_free(p, &mp);
  375. ASSERT(!mp)
  376. }
  377. fail5:
  378. // free modules
  379. while (num_inited_modules > 0) {
  380. const struct NCDModuleGroup **g = &ncd_modules[num_inited_modules - 1];
  381. if ((*g)->func_globalfree) {
  382. (*g)->func_globalfree();
  383. }
  384. num_inited_modules--;
  385. }
  386. // free interp program
  387. NCDInterpProg_Free(&iprogram);
  388. fail4a:
  389. // free placeholder database
  390. NCDPlaceholderDb_Free(&placeholder_db);
  391. fail4:
  392. // free program AST
  393. NCDProgram_Free(&program);
  394. fail3:
  395. // remove signal handler
  396. BSignal_Finish();
  397. fail2:
  398. // free module index
  399. NCDModuleIndex_Free(&mindex);
  400. fail1c:
  401. // free method index
  402. NCDMethodIndex_Free(&method_index);
  403. fail1b:
  404. // free string index
  405. NCDStringIndex_Free(&string_index);
  406. fail1aaa:
  407. // free random number generator
  408. BRandom2_Free(&random2);
  409. fail1aa:
  410. // free udev manager
  411. NCDUdevManager_Free(&umanager);
  412. // free process manager
  413. BProcessManager_Free(&manager);
  414. fail1a:
  415. // free reactor
  416. BReactor_Free(&reactor);
  417. fail1:
  418. // free logger
  419. BLog(BLOG_NOTICE, "exiting");
  420. BLog_Free();
  421. fail0:
  422. // finish objects
  423. DebugObjectGlobal_Finish();
  424. return main_exit_code;
  425. }
  426. void print_help (const char *name)
  427. {
  428. printf(
  429. "Usage:\n"
  430. " %s\n"
  431. " [--help]\n"
  432. " [--version]\n"
  433. " [--logger <stdout/stderr/syslog>]\n"
  434. " (logger=syslog?\n"
  435. " [--syslog-facility <string>]\n"
  436. " [--syslog-ident <string>]\n"
  437. " )\n"
  438. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  439. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  440. " --config-file <file>\n"
  441. " [--retry-time <ms>]\n"
  442. " [--no-udev]\n"
  443. " [-- [<extra_arg>] ...]\n",
  444. name
  445. );
  446. }
  447. void print_version (void)
  448. {
  449. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  450. }
  451. int parse_arguments (int argc, char *argv[])
  452. {
  453. if (argc <= 0) {
  454. return 0;
  455. }
  456. options.help = 0;
  457. options.version = 0;
  458. options.logger = LOGGER_STDERR;
  459. options.logger_syslog_facility = "daemon";
  460. options.logger_syslog_ident = argv[0];
  461. options.loglevel = -1;
  462. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  463. options.loglevels[i] = -1;
  464. }
  465. options.config_file = NULL;
  466. options.retry_time = DEFAULT_RETRY_TIME;
  467. options.no_udev = 0;
  468. options.extra_args = NULL;
  469. options.num_extra_args = 0;
  470. for (int i = 1; i < argc; i++) {
  471. char *arg = argv[i];
  472. if (!strcmp(arg, "--help")) {
  473. options.help = 1;
  474. }
  475. else if (!strcmp(arg, "--version")) {
  476. options.version = 1;
  477. }
  478. else if (!strcmp(arg, "--logger")) {
  479. if (1 >= argc - i) {
  480. fprintf(stderr, "%s: requires an argument\n", arg);
  481. return 0;
  482. }
  483. char *arg2 = argv[i + 1];
  484. if (!strcmp(arg2, "stdout")) {
  485. options.logger = LOGGER_STDOUT;
  486. }
  487. else if (!strcmp(arg2, "stderr")) {
  488. options.logger = LOGGER_STDERR;
  489. }
  490. else if (!strcmp(arg2, "syslog")) {
  491. options.logger = LOGGER_SYSLOG;
  492. }
  493. else {
  494. fprintf(stderr, "%s: wrong argument\n", arg);
  495. return 0;
  496. }
  497. i++;
  498. }
  499. else if (!strcmp(arg, "--syslog-facility")) {
  500. if (1 >= argc - i) {
  501. fprintf(stderr, "%s: requires an argument\n", arg);
  502. return 0;
  503. }
  504. options.logger_syslog_facility = argv[i + 1];
  505. i++;
  506. }
  507. else if (!strcmp(arg, "--syslog-ident")) {
  508. if (1 >= argc - i) {
  509. fprintf(stderr, "%s: requires an argument\n", arg);
  510. return 0;
  511. }
  512. options.logger_syslog_ident = argv[i + 1];
  513. i++;
  514. }
  515. else if (!strcmp(arg, "--loglevel")) {
  516. if (1 >= argc - i) {
  517. fprintf(stderr, "%s: requires an argument\n", arg);
  518. return 0;
  519. }
  520. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  521. fprintf(stderr, "%s: wrong argument\n", arg);
  522. return 0;
  523. }
  524. i++;
  525. }
  526. else if (!strcmp(arg, "--channel-loglevel")) {
  527. if (2 >= argc - i) {
  528. fprintf(stderr, "%s: requires two arguments\n", arg);
  529. return 0;
  530. }
  531. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  532. if (channel < 0) {
  533. fprintf(stderr, "%s: wrong channel argument\n", arg);
  534. return 0;
  535. }
  536. int loglevel = parse_loglevel(argv[i + 2]);
  537. if (loglevel < 0) {
  538. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  539. return 0;
  540. }
  541. options.loglevels[channel] = loglevel;
  542. i += 2;
  543. }
  544. else if (!strcmp(arg, "--config-file")) {
  545. if (1 >= argc - i) {
  546. fprintf(stderr, "%s: requires an argument\n", arg);
  547. return 0;
  548. }
  549. options.config_file = argv[i + 1];
  550. i++;
  551. }
  552. else if (!strcmp(arg, "--retry-time")) {
  553. if (1 >= argc - i) {
  554. fprintf(stderr, "%s: requires an argument\n", arg);
  555. return 0;
  556. }
  557. if ((options.retry_time = atoi(argv[i + 1])) < 0) {
  558. fprintf(stderr, "%s: wrong argument\n", arg);
  559. return 0;
  560. }
  561. i++;
  562. }
  563. else if (!strcmp(arg, "--no-udev")) {
  564. options.no_udev = 1;
  565. }
  566. else if (!strcmp(arg, "--")) {
  567. options.extra_args = &argv[i + 1];
  568. options.num_extra_args = argc - i - 1;
  569. i += options.num_extra_args;
  570. }
  571. else {
  572. fprintf(stderr, "unknown option: %s\n", arg);
  573. return 0;
  574. }
  575. }
  576. if (options.help || options.version) {
  577. return 1;
  578. }
  579. if (!options.config_file) {
  580. fprintf(stderr, "--config-file is required\n");
  581. return 0;
  582. }
  583. return 1;
  584. }
  585. void signal_handler (void *unused)
  586. {
  587. BLog(BLOG_NOTICE, "termination requested");
  588. start_terminate(1);
  589. }
  590. void start_terminate (int exit_code)
  591. {
  592. main_exit_code = exit_code;
  593. if (terminating) {
  594. return;
  595. }
  596. terminating = 1;
  597. if (LinkedList1_IsEmpty(&processes)) {
  598. BReactor_Quit(&reactor, 0);
  599. return;
  600. }
  601. // start terminating non-template processes
  602. for (LinkedList1Node *ln = LinkedList1_GetFirst(&processes); ln; ln = LinkedList1Node_Next(ln)) {
  603. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  604. if (p->module_process) {
  605. continue;
  606. }
  607. if (process_state(p) != PSTATE_TERMINATING) {
  608. process_start_terminating(p);
  609. }
  610. }
  611. }
  612. char * implode_id_strings (const NCD_string_id_t *names, size_t num_names, char del)
  613. {
  614. ExpString str;
  615. if (!ExpString_Init(&str)) {
  616. goto fail0;
  617. }
  618. int is_first = 1;
  619. while (num_names > 0) {
  620. if (!is_first && !ExpString_AppendChar(&str, del)) {
  621. goto fail1;
  622. }
  623. const char *name_str = NCDStringIndex_Value(&string_index, *names);
  624. if (!ExpString_Append(&str, name_str)) {
  625. goto fail1;
  626. }
  627. names++;
  628. num_names--;
  629. is_first = 0;
  630. }
  631. return ExpString_Get(&str);
  632. fail1:
  633. ExpString_Free(&str);
  634. fail0:
  635. return NULL;
  636. }
  637. int alloc_base_type_strings (const struct NCDModuleGroup *g)
  638. {
  639. for (struct NCDModule *m = g->modules; m->type; m++) {
  640. const char *type = (m->base_type ? m->base_type : m->type);
  641. ASSERT(type)
  642. m->base_type_id = NCDStringIndex_Get(&string_index, type);
  643. if (m->base_type_id < 0) {
  644. BLog(BLOG_ERROR, "NCDStringIndex_Get failed");
  645. return 0;
  646. }
  647. }
  648. return 1;
  649. }
  650. int process_new (NCDInterpProcess *iprocess, NCDModuleProcess *module_process)
  651. {
  652. ASSERT(iprocess)
  653. // get number of statements
  654. int num_statements = NCDInterpProcess_NumStatements(iprocess);
  655. // get size of preallocated memory
  656. int mem_size = NCDInterpProcess_PreallocSize(iprocess);
  657. if (mem_size < 0) {
  658. goto fail0;
  659. }
  660. // start with size of process structure
  661. size_t alloc_size = sizeof(struct process);
  662. // add size of statements array
  663. if (num_statements > SIZE_MAX / sizeof(struct statement)) {
  664. goto fail0;
  665. }
  666. if (!BSizeAdd(&alloc_size, num_statements * sizeof(struct statement))) {
  667. goto fail0;
  668. }
  669. // align for preallocated memory
  670. if (!BSizeAlign(&alloc_size, BMAX_ALIGN)) {
  671. goto fail0;
  672. }
  673. size_t mem_off = alloc_size;
  674. // add size of preallocated memory
  675. if (mem_size > SIZE_MAX || !BSizeAdd(&alloc_size, mem_size)) {
  676. goto fail0;
  677. }
  678. // allocate memory
  679. struct process *p = BAlloc(alloc_size);
  680. if (!p) {
  681. goto fail0;
  682. }
  683. // set variables
  684. p->iprocess = iprocess;
  685. p->module_process = module_process;
  686. p->ap = 0;
  687. p->fp = 0;
  688. p->num_statements = num_statements;
  689. p->state2_error1 = PSTATE_WORKING << PROCESS_STATE_SHIFT;
  690. // set module process handlers
  691. if (p->module_process) {
  692. NCDModuleProcess_Interp_SetHandlers(p->module_process, p,
  693. (NCDModuleProcess_interp_func_event)process_moduleprocess_func_event,
  694. (NCDModuleProcess_interp_func_getobj)process_moduleprocess_func_getobj);
  695. }
  696. // init statements
  697. char *mem = (char *)p + mem_off;
  698. for (int i = 0; i < num_statements; i++) {
  699. struct statement *ps = &p->statements[i];
  700. ps->i = i;
  701. ps->state = SSTATE_FORGOTTEN;
  702. ps->mem_size = NCDInterpProcess_StatementPreallocSize(iprocess, i);
  703. ps->mem = (ps->mem_size == 0 ? NULL : mem + NCDInterpProcess_StatementPreallocOffset(iprocess, i));
  704. }
  705. // init timer
  706. BSmallTimer_Init(&p->wait_timer, process_wait_timer_handler);
  707. // init work job
  708. BSmallPending_Init(&p->work_job, BReactor_PendingGroup(&reactor), (BSmallPending_handler)process_work_job_handler, p);
  709. // insert to processes list
  710. LinkedList1_Append(&processes, &p->list_node);
  711. // schedule work
  712. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(&reactor));
  713. return 1;
  714. fail0:
  715. BLog(BLOG_ERROR, "failed to allocate memory for process %s", NCDInterpProcess_Name(iprocess));
  716. return 0;
  717. }
  718. void process_free (struct process *p, NCDModuleProcess **out_mp)
  719. {
  720. ASSERT(p->ap == 0)
  721. ASSERT(p->fp == 0)
  722. ASSERT(out_mp)
  723. // give module process to caller so it can inform the process creator that the process has terminated
  724. *out_mp = p->module_process;
  725. // free statement memory
  726. for (int i = 0; i < p->num_statements; i++) {
  727. struct statement *ps = &p->statements[i];
  728. if (statement_mem_is_allocated(ps)) {
  729. free(ps->mem);
  730. }
  731. }
  732. // remove from processes list
  733. LinkedList1_Remove(&processes, &p->list_node);
  734. // free work job
  735. BSmallPending_Free(&p->work_job, BReactor_PendingGroup(&reactor));
  736. // free timer
  737. BReactor_RemoveSmallTimer(&reactor, &p->wait_timer);
  738. // free strucure
  739. BFree(p);
  740. }
  741. int process_state (struct process *p)
  742. {
  743. return (p->state2_error1 & PROCESS_STATE_MASK) >> PROCESS_STATE_SHIFT;
  744. }
  745. void process_set_state (struct process *p, int state)
  746. {
  747. p->state2_error1 = (p->state2_error1 & ~PROCESS_STATE_MASK) | (state << PROCESS_STATE_SHIFT);
  748. }
  749. int process_error (struct process *p)
  750. {
  751. return (p->state2_error1 & PROCESS_ERROR_MASK) >> PROCESS_ERROR_SHIFT;
  752. }
  753. void process_set_error (struct process *p, int error)
  754. {
  755. p->state2_error1 = (p->state2_error1 & ~PROCESS_ERROR_MASK) | (error << PROCESS_ERROR_SHIFT);
  756. }
  757. void process_start_terminating (struct process *p)
  758. {
  759. ASSERT(process_state(p) != PSTATE_TERMINATING)
  760. // set terminating
  761. process_set_state(p, PSTATE_TERMINATING);
  762. // schedule work
  763. process_schedule_work(p);
  764. }
  765. int process_have_child (struct process *p)
  766. {
  767. return (p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD);
  768. }
  769. void process_assert_pointers (struct process *p)
  770. {
  771. ASSERT(p->ap <= p->num_statements)
  772. ASSERT(p->fp >= p->ap)
  773. ASSERT(p->fp <= p->num_statements)
  774. #ifndef NDEBUG
  775. // check AP
  776. for (int i = 0; i < p->ap; i++) {
  777. if (i == p->ap - 1) {
  778. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  779. } else {
  780. ASSERT(p->statements[i].state == SSTATE_ADULT)
  781. }
  782. }
  783. // check FP
  784. int fp = p->num_statements;
  785. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  786. fp--;
  787. }
  788. ASSERT(p->fp == fp)
  789. #endif
  790. }
  791. void process_logfunc (struct process *p)
  792. {
  793. BLog_Append("process %s: ", NCDInterpProcess_Name(p->iprocess));
  794. }
  795. void process_log (struct process *p, int level, const char *fmt, ...)
  796. {
  797. va_list vl;
  798. va_start(vl, fmt);
  799. BLog_LogViaFuncVarArg((BLog_logfunc)process_logfunc, p, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  800. va_end(vl);
  801. }
  802. void process_schedule_work (struct process *p)
  803. {
  804. process_assert_pointers(p);
  805. // stop timer
  806. BReactor_RemoveSmallTimer(&reactor, &p->wait_timer);
  807. // schedule work
  808. BSmallPending_Set(&p->work_job, BReactor_PendingGroup(&reactor));
  809. }
  810. void process_work_job_handler (struct process *p)
  811. {
  812. process_assert_pointers(p);
  813. ASSERT(!BSmallTimer_IsRunning(&p->wait_timer))
  814. int pstate = process_state(p);
  815. if (pstate == PSTATE_WAITING) {
  816. return;
  817. }
  818. if (pstate == PSTATE_TERMINATING) {
  819. if (p->fp == 0) {
  820. // free process
  821. NCDModuleProcess *mp;
  822. process_free(p, &mp);
  823. // if program is terminating amd there are no more processes, exit program
  824. if (terminating && LinkedList1_IsEmpty(&processes)) {
  825. ASSERT(!mp)
  826. BReactor_Quit(&reactor, 0);
  827. return;
  828. }
  829. // inform the process creator that the process has terminated
  830. if (mp) {
  831. NCDModuleProcess_Interp_Terminated(mp);
  832. return;
  833. }
  834. return;
  835. }
  836. // order the last living statement to die, if needed
  837. struct statement *ps = &p->statements[p->fp - 1];
  838. ASSERT(ps->state != SSTATE_FORGOTTEN)
  839. if (ps->state != SSTATE_DYING) {
  840. statement_log(ps, BLOG_INFO, "killing");
  841. // set statement state DYING
  842. ps->state = SSTATE_DYING;
  843. // update AP
  844. if (p->ap > ps->i) {
  845. p->ap = ps->i;
  846. }
  847. // order it to die
  848. NCDModuleInst_Die(&ps->inst);
  849. return;
  850. }
  851. return;
  852. }
  853. // process was up but is no longer?
  854. if (pstate == PSTATE_UP && !(!process_have_child(p) && p->ap == p->num_statements)) {
  855. // if we have module process, wait for its permission to continue
  856. if (p->module_process) {
  857. // set state waiting
  858. process_set_state(p, PSTATE_WAITING);
  859. // set module process down
  860. NCDModuleProcess_Interp_Down(p->module_process);
  861. return;
  862. }
  863. // set state working
  864. process_set_state(p, PSTATE_WORKING);
  865. pstate = PSTATE_WORKING;
  866. }
  867. // cleaning up?
  868. if (p->ap < p->fp) {
  869. // order the last living statement to die, if needed
  870. struct statement *ps = &p->statements[p->fp - 1];
  871. if (ps->state != SSTATE_DYING) {
  872. statement_log(ps, BLOG_INFO, "killing");
  873. // set statement state DYING
  874. ps->state = SSTATE_DYING;
  875. // order it to die
  876. NCDModuleInst_Die(&ps->inst);
  877. return;
  878. }
  879. return;
  880. }
  881. // clean?
  882. if (process_have_child(p)) {
  883. ASSERT(p->ap > 0)
  884. ASSERT(p->ap <= p->num_statements)
  885. struct statement *ps = &p->statements[p->ap - 1];
  886. ASSERT(ps->state == SSTATE_CHILD)
  887. statement_log(ps, BLOG_INFO, "clean");
  888. // report clean
  889. NCDModuleInst_Clean(&ps->inst);
  890. return;
  891. }
  892. // advancing?
  893. if (p->ap < p->num_statements) {
  894. ASSERT(process_state(p) == PSTATE_WORKING)
  895. struct statement *ps = &p->statements[p->ap];
  896. ASSERT(ps->state == SSTATE_FORGOTTEN)
  897. if (process_error(p)) {
  898. statement_log(ps, BLOG_INFO, "waiting after error");
  899. // clear error
  900. process_set_error(p, 0);
  901. // set wait timer
  902. BReactor_SetSmallTimer(&reactor, &p->wait_timer, BTIMER_SET_RELATIVE, options.retry_time);
  903. } else {
  904. // advance
  905. process_advance(p);
  906. }
  907. return;
  908. }
  909. // have we just finished?
  910. if (pstate == PSTATE_WORKING) {
  911. process_log(p, BLOG_INFO, "victory");
  912. // set state up
  913. process_set_state(p, PSTATE_UP);
  914. // set module process up
  915. if (p->module_process) {
  916. NCDModuleProcess_Interp_Up(p->module_process);
  917. return;
  918. }
  919. }
  920. }
  921. int replace_placeholders_callback (void *arg, int plid, NCDValMem *mem, NCDValRef *out)
  922. {
  923. struct statement *ps = arg;
  924. ASSERT(plid >= 0)
  925. ASSERT(mem)
  926. ASSERT(out)
  927. const NCD_string_id_t *varnames;
  928. size_t num_names;
  929. NCDPlaceholderDb_GetVariable(&placeholder_db, plid, &varnames, &num_names);
  930. return process_resolve_variable_expr(statement_process(ps), ps->i, varnames, num_names, mem, out);
  931. }
  932. void process_advance (struct process *p)
  933. {
  934. process_assert_pointers(p);
  935. ASSERT(p->ap == p->fp)
  936. ASSERT(!process_have_child(p))
  937. ASSERT(p->ap < p->num_statements)
  938. ASSERT(!process_error(p))
  939. ASSERT(!BSmallPending_IsSet(&p->work_job))
  940. ASSERT(!BSmallTimer_IsRunning(&p->wait_timer))
  941. ASSERT(process_state(p) == PSTATE_WORKING)
  942. struct statement *ps = &p->statements[p->ap];
  943. ASSERT(ps->state == SSTATE_FORGOTTEN)
  944. statement_log(ps, BLOG_INFO, "initializing");
  945. // need to determine the module and object to use it on (if it's a method)
  946. const struct NCDModule *module;
  947. NCDObject object;
  948. NCDObject *object_ptr = NULL;
  949. // get object names, e.g. "my.cat" in "my.cat->meow();"
  950. // (or NULL if this is not a method statement)
  951. const NCD_string_id_t *objnames;
  952. size_t num_objnames;
  953. NCDInterpProcess_StatementObjNames(p->iprocess, p->ap, &objnames, &num_objnames);
  954. if (!objnames) {
  955. // not a method; module is already known by NCDInterpProcess
  956. module = NCDInterpProcess_StatementGetSimpleModule(p->iprocess, p->ap);
  957. if (!module) {
  958. statement_log(ps, BLOG_ERROR, "unknown simple statement: %s", NCDInterpProcess_StatementCmdName(p->iprocess, p->ap));
  959. goto fail0;
  960. }
  961. } else {
  962. // get object
  963. if (!process_resolve_object_expr(p, p->ap, objnames, num_objnames, &object)) {
  964. goto fail0;
  965. }
  966. object_ptr = &object;
  967. // get object type
  968. NCD_string_id_t object_type = NCDObject_Type(&object);
  969. if (object_type < 0) {
  970. statement_log(ps, BLOG_ERROR, "cannot call method on object with no type");
  971. goto fail0;
  972. }
  973. // find module based on type of object
  974. module = NCDInterpProcess_StatementGetMethodModule(p->iprocess, p->ap, object_type, &method_index);
  975. if (!module) {
  976. const char *type_str = NCDStringIndex_Value(&string_index, object_type);
  977. statement_log(ps, BLOG_ERROR, "unknown method statement: %s::%s", type_str, NCDInterpProcess_StatementCmdName(p->iprocess, p->ap));
  978. goto fail0;
  979. }
  980. }
  981. // register alloc size for future preallocations
  982. NCDInterpProcess_StatementBumpAllocSize(p->iprocess, p->ap, module->alloc_size);
  983. // copy arguments
  984. NCDValRef args;
  985. NCDValReplaceProg prog;
  986. if (!NCDInterpProcess_CopyStatementArgs(p->iprocess, ps->i, &ps->args_mem, &args, &prog)) {
  987. statement_log(ps, BLOG_ERROR, "NCDInterpProcess_CopyStatementArgs failed");
  988. goto fail0;
  989. }
  990. // replace placeholders with values of variables
  991. if (!NCDValReplaceProg_Execute(prog, &ps->args_mem, replace_placeholders_callback, ps)) {
  992. statement_log(ps, BLOG_ERROR, "failed to replace variables in arguments with values");
  993. goto fail1;
  994. }
  995. // allocate memory
  996. if (!statement_allocate_memory(ps, module->alloc_size)) {
  997. statement_log(ps, BLOG_ERROR, "failed to allocate memory");
  998. goto fail1;
  999. }
  1000. char *mem = (module->alloc_size == 0 ? NULL : ps->mem);
  1001. // set statement state CHILD
  1002. ps->state = SSTATE_CHILD;
  1003. // increment AP
  1004. p->ap++;
  1005. // increment FP
  1006. p->fp++;
  1007. process_assert_pointers(p);
  1008. // initialize module instance
  1009. NCDModuleInst_Init(&ps->inst, module, mem, object_ptr, args, &module_params);
  1010. return;
  1011. fail1:
  1012. NCDValMem_Free(&ps->args_mem);
  1013. fail0:
  1014. // set error
  1015. process_set_error(p, 1);
  1016. // schedule work to start the timer
  1017. process_schedule_work(p);
  1018. }
  1019. void process_wait_timer_handler (BSmallTimer *timer)
  1020. {
  1021. struct process *p = UPPER_OBJECT(timer, struct process, wait_timer);
  1022. process_assert_pointers(p);
  1023. ASSERT(p->ap == p->fp)
  1024. ASSERT(!process_have_child(p))
  1025. ASSERT(p->ap < p->num_statements)
  1026. ASSERT(!process_error(p))
  1027. ASSERT(!BSmallPending_IsSet(&p->work_job))
  1028. ASSERT(process_state(p) == PSTATE_WORKING)
  1029. process_log(p, BLOG_INFO, "retrying");
  1030. // advance
  1031. process_advance(p);
  1032. }
  1033. int process_find_object (struct process *p, int pos, NCD_string_id_t name, NCDObject *out_object)
  1034. {
  1035. ASSERT(pos >= 0)
  1036. ASSERT(pos <= p->num_statements)
  1037. ASSERT(out_object)
  1038. int i = NCDInterpProcess_FindStatement(p->iprocess, pos, name);
  1039. if (i >= 0) {
  1040. struct statement *ps = &p->statements[i];
  1041. ASSERT(i < p->num_statements)
  1042. if (ps->state == SSTATE_FORGOTTEN) {
  1043. process_log(p, BLOG_ERROR, "statement (%d) is uninitialized", i);
  1044. return 0;
  1045. }
  1046. *out_object = NCDModuleInst_Object(&ps->inst);
  1047. return 1;
  1048. }
  1049. if (p->module_process && NCDModuleProcess_Interp_GetSpecialObj(p->module_process, name, out_object)) {
  1050. return 1;
  1051. }
  1052. return 0;
  1053. }
  1054. int process_resolve_object_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDObject *out_object)
  1055. {
  1056. ASSERT(pos >= 0)
  1057. ASSERT(pos <= p->num_statements)
  1058. ASSERT(names)
  1059. ASSERT(num_names > 0)
  1060. ASSERT(out_object)
  1061. NCDObject object;
  1062. if (!process_find_object(p, pos, names[0], &object)) {
  1063. goto fail;
  1064. }
  1065. if (!NCDObject_ResolveObjExprCompact(&object, names + 1, num_names - 1, out_object)) {
  1066. goto fail;
  1067. }
  1068. return 1;
  1069. fail:;
  1070. char *name = implode_id_strings(names, num_names, '.');
  1071. process_log(p, BLOG_ERROR, "failed to resolve object (%s) from position %zu", (name ? name : ""), pos);
  1072. free(name);
  1073. return 0;
  1074. }
  1075. int process_resolve_variable_expr (struct process *p, int pos, const NCD_string_id_t *names, size_t num_names, NCDValMem *mem, NCDValRef *out_value)
  1076. {
  1077. ASSERT(pos >= 0)
  1078. ASSERT(pos <= p->num_statements)
  1079. ASSERT(names)
  1080. ASSERT(num_names > 0)
  1081. ASSERT(mem)
  1082. ASSERT(out_value)
  1083. NCDObject object;
  1084. if (!process_find_object(p, pos, names[0], &object)) {
  1085. goto fail;
  1086. }
  1087. if (!NCDObject_ResolveVarExprCompact(&object, names + 1, num_names - 1, mem, out_value)) {
  1088. goto fail;
  1089. }
  1090. return 1;
  1091. fail:;
  1092. char *name = implode_id_strings(names, num_names, '.');
  1093. process_log(p, BLOG_ERROR, "failed to resolve variable (%s) from position %zu", (name ? name : ""), pos);
  1094. free(name);
  1095. return 0;
  1096. }
  1097. void statement_logfunc (struct statement *ps)
  1098. {
  1099. process_logfunc(statement_process(ps));
  1100. BLog_Append("statement %zu: ", ps->i);
  1101. }
  1102. void statement_log (struct statement *ps, int level, const char *fmt, ...)
  1103. {
  1104. if (!BLog_WouldLog(BLOG_CURRENT_CHANNEL, level)) {
  1105. return;
  1106. }
  1107. va_list vl;
  1108. va_start(vl, fmt);
  1109. BLog_LogViaFuncVarArg((BLog_logfunc)statement_logfunc, ps, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1110. va_end(vl);
  1111. }
  1112. struct process * statement_process (struct statement *ps)
  1113. {
  1114. return UPPER_OBJECT(ps - ps->i, struct process, statements);
  1115. }
  1116. int statement_mem_is_allocated (struct statement *ps)
  1117. {
  1118. return (ps->mem_size < 0);
  1119. }
  1120. int statement_mem_size (struct statement *ps)
  1121. {
  1122. return (ps->mem_size >= 0 ? ps->mem_size : -ps->mem_size);
  1123. }
  1124. int statement_allocate_memory (struct statement *ps, int alloc_size)
  1125. {
  1126. ASSERT(alloc_size >= 0)
  1127. if (alloc_size > statement_mem_size(ps)) {
  1128. if (statement_mem_is_allocated(ps)) {
  1129. free(ps->mem);
  1130. }
  1131. if (!(ps->mem = malloc(alloc_size))) {
  1132. statement_log(ps, BLOG_ERROR, "malloc failed");
  1133. ps->mem_size = 0;
  1134. return 0;
  1135. }
  1136. ps->mem_size = -alloc_size;
  1137. }
  1138. return 1;
  1139. }
  1140. void statement_instance_func_event (NCDModuleInst *inst, int event)
  1141. {
  1142. struct statement *ps = UPPER_OBJECT(inst, struct statement, inst);
  1143. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  1144. struct process *p = statement_process(ps);
  1145. process_assert_pointers(p);
  1146. // schedule work
  1147. process_schedule_work(p);
  1148. switch (event) {
  1149. case NCDMODULE_EVENT_UP: {
  1150. ASSERT(ps->state == SSTATE_CHILD)
  1151. statement_log(ps, BLOG_INFO, "up");
  1152. // set state ADULT
  1153. ps->state = SSTATE_ADULT;
  1154. } break;
  1155. case NCDMODULE_EVENT_DOWN: {
  1156. ASSERT(ps->state == SSTATE_ADULT)
  1157. statement_log(ps, BLOG_INFO, "down");
  1158. // set state CHILD
  1159. ps->state = SSTATE_CHILD;
  1160. // clear error
  1161. if (ps->i < p->ap) {
  1162. process_set_error(p, 0);
  1163. }
  1164. // update AP
  1165. if (p->ap > ps->i + 1) {
  1166. p->ap = ps->i + 1;
  1167. }
  1168. } break;
  1169. case NCDMODULE_EVENT_DEAD: {
  1170. int is_error = NCDModuleInst_HaveError(&ps->inst);
  1171. if (is_error) {
  1172. statement_log(ps, BLOG_ERROR, "died with error");
  1173. } else {
  1174. statement_log(ps, BLOG_INFO, "died");
  1175. }
  1176. // free instance
  1177. NCDModuleInst_Free(&ps->inst);
  1178. // free arguments memory
  1179. NCDValMem_Free(&ps->args_mem);
  1180. // set state FORGOTTEN
  1181. ps->state = SSTATE_FORGOTTEN;
  1182. // set error
  1183. if (is_error && ps->i < p->ap) {
  1184. process_set_error(p, 1);
  1185. }
  1186. // update AP
  1187. if (p->ap > ps->i) {
  1188. p->ap = ps->i;
  1189. }
  1190. // update FP
  1191. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  1192. p->fp--;
  1193. }
  1194. } break;
  1195. }
  1196. }
  1197. int statement_instance_func_getobj (NCDModuleInst *inst, NCD_string_id_t objname, NCDObject *out_object)
  1198. {
  1199. struct statement *ps = UPPER_OBJECT(inst, struct statement, inst);
  1200. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1201. return process_find_object(statement_process(ps), ps->i, objname, out_object);
  1202. }
  1203. int statement_instance_func_initprocess (NCDModuleProcess* mp, NCD_string_id_t template_name)
  1204. {
  1205. // find process
  1206. NCDInterpProcess *iprocess = NCDInterpProg_FindProcess(&iprogram, template_name);
  1207. if (!iprocess) {
  1208. const char *str = NCDStringIndex_Value(&string_index, template_name);
  1209. BLog(BLOG_ERROR, "no template named %s", str);
  1210. return 0;
  1211. }
  1212. // make sure it's a template
  1213. if (!NCDInterpProcess_IsTemplate(iprocess)) {
  1214. const char *str = NCDStringIndex_Value(&string_index, template_name);
  1215. BLog(BLOG_ERROR, "need template to create a process, but %s is a process", str);
  1216. return 0;
  1217. }
  1218. // create process
  1219. if (!process_new(iprocess, mp)) {
  1220. const char *str = NCDStringIndex_Value(&string_index, template_name);
  1221. BLog(BLOG_ERROR, "failed to create process from template %s", str);
  1222. return 0;
  1223. }
  1224. if (BLog_WouldLog(BLOG_INFO, BLOG_CURRENT_CHANNEL)) {
  1225. const char *str = NCDStringIndex_Value(&string_index, template_name);
  1226. BLog(BLOG_INFO, "created process from template %s", str);
  1227. }
  1228. return 1;
  1229. }
  1230. void statement_instance_logfunc (NCDModuleInst *inst)
  1231. {
  1232. struct statement *ps = UPPER_OBJECT(inst, struct statement, inst);
  1233. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1234. statement_logfunc(ps);
  1235. BLog_Append("module: ");
  1236. }
  1237. void statement_instance_func_interp_exit (int exit_code)
  1238. {
  1239. start_terminate(exit_code);
  1240. }
  1241. int statement_instance_func_interp_getargs (NCDValMem *mem, NCDValRef *out_value)
  1242. {
  1243. *out_value = NCDVal_NewList(mem, options.num_extra_args);
  1244. if (NCDVal_IsInvalid(*out_value)) {
  1245. BLog(BLOG_ERROR, "NCDVal_NewList failed");
  1246. goto fail;
  1247. }
  1248. for (int i = 0; i < options.num_extra_args; i++) {
  1249. NCDValRef arg = NCDVal_NewString(mem, options.extra_args[i]);
  1250. if (NCDVal_IsInvalid(arg)) {
  1251. BLog(BLOG_ERROR, "NCDVal_NewString failed");
  1252. goto fail;
  1253. }
  1254. NCDVal_ListAppend(*out_value, arg);
  1255. }
  1256. return 1;
  1257. fail:
  1258. *out_value = NCDVal_NewInvalid();
  1259. return 1;
  1260. }
  1261. btime_t statement_instance_func_interp_getretrytime (void)
  1262. {
  1263. return options.retry_time;
  1264. }
  1265. void process_moduleprocess_func_event (struct process *p, int event)
  1266. {
  1267. ASSERT(p->module_process)
  1268. switch (event) {
  1269. case NCDMODULEPROCESS_INTERP_EVENT_CONTINUE: {
  1270. ASSERT(process_state(p) == PSTATE_WAITING)
  1271. // set state working
  1272. process_set_state(p, PSTATE_WORKING);
  1273. // schedule work
  1274. process_schedule_work(p);
  1275. } break;
  1276. case NCDMODULEPROCESS_INTERP_EVENT_TERMINATE: {
  1277. ASSERT(process_state(p) != PSTATE_TERMINATING)
  1278. process_log(p, BLOG_INFO, "process termination requested");
  1279. // start terminating
  1280. process_start_terminating(p);
  1281. } break;
  1282. default: ASSERT(0);
  1283. }
  1284. }
  1285. int process_moduleprocess_func_getobj (struct process *p, NCD_string_id_t name, NCDObject *out_object)
  1286. {
  1287. ASSERT(p->module_process)
  1288. return process_find_object(p, p->num_statements, name, out_object);
  1289. }