ncd.c 44 KB

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