ncd.c 42 KB

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