ncd.c 43 KB

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