ncd.c 42 KB

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