ncd.c 44 KB

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