ncd.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820
  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 <misc/version.h>
  34. #include <misc/loglevel.h>
  35. #include <misc/offset.h>
  36. #include <misc/read_file.h>
  37. #include <misc/balloc.h>
  38. #include <misc/concat_strings.h>
  39. #include <misc/string_begins_with.h>
  40. #include <misc/parse_number.h>
  41. #include <misc/open_standard_streams.h>
  42. #include <misc/expstring.h>
  43. #include <structure/LinkedList1.h>
  44. #include <base/BLog.h>
  45. #include <base/BLog_syslog.h>
  46. #include <system/BReactor.h>
  47. #include <system/BSignal.h>
  48. #include <system/BConnection.h>
  49. #include <system/BProcess.h>
  50. #include <udevmonitor/NCDUdevManager.h>
  51. #include <ncd/NCDConfigParser.h>
  52. #include <ncd/NCDModule.h>
  53. #include <ncd/NCDModuleIndex.h>
  54. #include <ncd/modules/modules.h>
  55. #include <ncd/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 ARG_VALUE_TYPE_STRING 1
  61. #define ARG_VALUE_TYPE_VARIABLE 2
  62. #define ARG_VALUE_TYPE_LIST 3
  63. #define ARG_VALUE_TYPE_MAP 4
  64. #define SSTATE_CHILD 1
  65. #define SSTATE_ADULT 2
  66. #define SSTATE_DYING 3
  67. #define SSTATE_FORGOTTEN 4
  68. #define PSTATE_WORKING 1
  69. #define PSTATE_UP 2
  70. #define PSTATE_WAITING 3
  71. #define PSTATE_TERMINATING 4
  72. struct arg_value {
  73. int type;
  74. union {
  75. struct {
  76. char *string;
  77. size_t string_len;
  78. };
  79. char **variable_names;
  80. LinkedList1 list;
  81. LinkedList1 maplist;
  82. };
  83. };
  84. struct arg_list_elem {
  85. LinkedList1Node list_node;
  86. struct arg_value value;
  87. };
  88. struct arg_map_elem {
  89. LinkedList1Node maplist_node;
  90. struct arg_value key;
  91. struct arg_value val;
  92. };
  93. struct statement {
  94. char **object_names;
  95. char *method_name;
  96. struct arg_value args;
  97. char *name;
  98. };
  99. struct process {
  100. NCDModuleProcess *module_process;
  101. char *name;
  102. size_t num_statements;
  103. struct process_statement *statements;
  104. int state;
  105. size_t ap;
  106. size_t fp;
  107. BTimer wait_timer;
  108. BPending advance_job;
  109. BPending work_job;
  110. LinkedList1Node list_node; // node in processes
  111. };
  112. struct process_statement {
  113. struct process *p;
  114. size_t i;
  115. struct statement s;
  116. int state;
  117. int have_error;
  118. btime_t error_until;
  119. NCDModuleInst inst;
  120. NCDValue inst_args;
  121. };
  122. // command-line options
  123. struct {
  124. int help;
  125. int version;
  126. int logger;
  127. char *logger_syslog_facility;
  128. char *logger_syslog_ident;
  129. int loglevel;
  130. int loglevels[BLOG_NUM_CHANNELS];
  131. char *config_file;
  132. int retry_time;
  133. int no_udev;
  134. char **extra_args;
  135. int num_extra_args;
  136. } options;
  137. // reactor
  138. BReactor ss;
  139. // are we terminating
  140. int terminating;
  141. int main_exit_code;
  142. // process manager
  143. BProcessManager manager;
  144. // udev manager
  145. NCDUdevManager umanager;
  146. // module index
  147. NCDModuleIndex mindex;
  148. // config AST
  149. struct NCDConfig_processes *config_ast;
  150. // common module parameters
  151. struct NCDModuleInst_params module_params;
  152. struct NCDModuleInst_iparams module_iparams;
  153. // processes
  154. LinkedList1 processes;
  155. static void print_help (const char *name);
  156. static void print_version (void);
  157. static int parse_arguments (int argc, char *argv[]);
  158. static void signal_handler (void *unused);
  159. static void start_terminate (int exit_code);
  160. static int arg_value_init_string (struct arg_value *o, const char *string, size_t len);
  161. static int arg_value_init_variable (struct arg_value *o, struct NCDConfig_strings *ast_names);
  162. static void arg_value_init_list (struct arg_value *o);
  163. static int arg_value_list_append (struct arg_value *o, struct arg_value v);
  164. static void arg_value_init_map (struct arg_value *o);
  165. static int arg_value_map_append (struct arg_value *o, struct arg_value key, struct arg_value val);
  166. static void arg_value_free (struct arg_value *o);
  167. static int build_arg_from_ast (struct arg_value *o, struct NCDConfig_list *ast);
  168. static int build_arg_list_from_ast_list (struct arg_value *o, struct NCDConfig_list *list);
  169. static int build_arg_map_from_ast_list (struct arg_value *o, struct NCDConfig_list *list);
  170. static char ** names_new (struct NCDConfig_strings *ast_names);
  171. static size_t names_count (char **names);
  172. static char * names_tostring (char **names);
  173. static void names_free (char **names);
  174. static int statement_init (struct statement *s, struct NCDConfig_statements *conf);
  175. static void statement_free (struct statement *s);
  176. static int process_new (struct NCDConfig_processes *conf, NCDModuleProcess *module_process);
  177. static void process_free (struct process *p);
  178. static void process_start_terminating (struct process *p);
  179. static void process_free_statements (struct process *p);
  180. static size_t process_rap (struct process *p);
  181. static void process_assert_pointers (struct process *p);
  182. static void process_logfunc (struct process *p);
  183. static void process_log (struct process *p, int level, const char *fmt, ...);
  184. static void process_schedule_work (struct process *p);
  185. static void process_work_job_handler (struct process *p);
  186. static void process_advance_job_handler (struct process *p);
  187. static void process_wait_timer_handler (struct process *p);
  188. static int process_find_object (struct process *p, size_t pos, const char *name, NCDObject *out_object);
  189. static int process_resolve_object_expr (struct process *p, size_t pos, char **names, NCDObject *out_object);
  190. static int process_resolve_variable_expr (struct process *p, size_t pos, char **names, NCDValue *out_value);
  191. static void process_statement_logfunc (struct process_statement *ps);
  192. static void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...);
  193. static void process_statement_set_error (struct process_statement *ps);
  194. static int process_statement_resolve_argument (struct process_statement *ps, struct arg_value *arg, NCDValue *out);
  195. static void process_statement_instance_func_event (struct process_statement *ps, int event);
  196. static int process_statement_instance_func_getobj (struct process_statement *ps, const char *objname, NCDObject *out_object);
  197. static int process_statement_instance_func_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name);
  198. static void process_statement_instance_logfunc (struct process_statement *ps);
  199. static void process_statement_instance_func_interp_exit (struct process_statement *ps, int exit_code);
  200. static int process_statement_instance_func_interp_getargs (struct process_statement *ps, NCDValue *out_value);
  201. static btime_t process_statement_instance_func_interp_getretrytime (struct process_statement *ps);
  202. static void process_moduleprocess_func_event (struct process *p, int event);
  203. static int process_moduleprocess_func_getobj (struct process *p, const char *name, NCDObject *out_object);
  204. int main (int argc, char **argv)
  205. {
  206. if (argc <= 0) {
  207. return 1;
  208. }
  209. // set exit code
  210. main_exit_code = 1;
  211. // open standard streams
  212. open_standard_streams();
  213. // parse command-line arguments
  214. if (!parse_arguments(argc, argv)) {
  215. fprintf(stderr, "Failed to parse arguments\n");
  216. print_help(argv[0]);
  217. goto fail0;
  218. }
  219. // handle --help and --version
  220. if (options.help) {
  221. print_version();
  222. print_help(argv[0]);
  223. return 0;
  224. }
  225. if (options.version) {
  226. print_version();
  227. return 0;
  228. }
  229. // initialize logger
  230. switch (options.logger) {
  231. case LOGGER_STDOUT:
  232. BLog_InitStdout();
  233. break;
  234. case LOGGER_STDERR:
  235. BLog_InitStderr();
  236. break;
  237. case LOGGER_SYSLOG:
  238. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  239. fprintf(stderr, "Failed to initialize syslog logger\n");
  240. goto fail0;
  241. }
  242. break;
  243. default:
  244. ASSERT(0);
  245. }
  246. // configure logger channels
  247. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  248. if (options.loglevels[i] >= 0) {
  249. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  250. }
  251. else if (options.loglevel >= 0) {
  252. BLog_SetChannelLoglevel(i, options.loglevel);
  253. }
  254. }
  255. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  256. // initialize network
  257. if (!BNetwork_GlobalInit()) {
  258. BLog(BLOG_ERROR, "BNetwork_GlobalInit failed");
  259. goto fail1;
  260. }
  261. // init time
  262. BTime_Init();
  263. // init reactor
  264. if (!BReactor_Init(&ss)) {
  265. BLog(BLOG_ERROR, "BReactor_Init failed");
  266. goto fail1;
  267. }
  268. // set not terminating
  269. terminating = 0;
  270. // init process manager
  271. if (!BProcessManager_Init(&manager, &ss)) {
  272. BLog(BLOG_ERROR, "BProcessManager_Init failed");
  273. goto fail1a;
  274. }
  275. // init udev manager
  276. NCDUdevManager_Init(&umanager, options.no_udev, &ss, &manager);
  277. // init module index
  278. NCDModuleIndex_Init(&mindex);
  279. // add module groups to index
  280. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  281. if (!NCDModuleIndex_AddGroup(&mindex, *g)) {
  282. BLog(BLOG_ERROR, "NCDModuleIndex_AddGroup failed");
  283. goto fail2;
  284. }
  285. }
  286. // setup signal handler
  287. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  288. BLog(BLOG_ERROR, "BSignal_Init failed");
  289. goto fail2;
  290. }
  291. // read config file
  292. uint8_t *file;
  293. size_t file_len;
  294. if (!read_file(options.config_file, &file, &file_len)) {
  295. BLog(BLOG_ERROR, "failed to read config file");
  296. goto fail3;
  297. }
  298. // parse config file
  299. if (!NCDConfigParser_Parse((char *)file, file_len, &config_ast)) {
  300. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  301. free(file);
  302. goto fail3;
  303. }
  304. // fee config file memory
  305. free(file);
  306. // init module params
  307. struct NCDModuleInitParams params;
  308. params.reactor = &ss;
  309. params.manager = &manager;
  310. params.umanager = &umanager;
  311. // init modules
  312. size_t num_inited_modules = 0;
  313. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  314. if ((*g)->func_globalinit && !(*g)->func_globalinit(params)) {
  315. BLog(BLOG_ERROR, "globalinit failed for some module");
  316. goto fail5;
  317. }
  318. num_inited_modules++;
  319. }
  320. // init common module params
  321. module_params.func_event = (NCDModuleInst_func_event)process_statement_instance_func_event;
  322. module_params.func_getobj = (NCDModuleInst_func_getobj)process_statement_instance_func_getobj;
  323. module_params.logfunc = (BLog_logfunc)process_statement_instance_logfunc;
  324. module_iparams.reactor = &ss;
  325. module_iparams.manager = &manager;
  326. module_iparams.umanager = &umanager;
  327. module_iparams.func_initprocess = (NCDModuleInst_func_initprocess)process_statement_instance_func_initprocess;
  328. module_iparams.func_interp_exit = (NCDModuleInst_func_interp_exit)process_statement_instance_func_interp_exit;
  329. module_iparams.func_interp_getargs = (NCDModuleInst_func_interp_getargs)process_statement_instance_func_interp_getargs;
  330. module_iparams.func_interp_getretrytime = (NCDModuleInst_func_interp_getretrytime)process_statement_instance_func_interp_getretrytime;
  331. // init processes list
  332. LinkedList1_Init(&processes);
  333. // init processes
  334. for (struct NCDConfig_processes *conf = config_ast; conf; conf = conf->next) {
  335. if (conf->is_template) {
  336. continue;
  337. }
  338. if (!process_new(conf, NULL)) {
  339. BLog(BLOG_ERROR, "failed to initialize process, exiting");
  340. goto fail6;
  341. }
  342. }
  343. // enter event loop
  344. BLog(BLOG_NOTICE, "entering event loop");
  345. BReactor_Exec(&ss);
  346. ASSERT(LinkedList1_IsEmpty(&processes))
  347. fail6:;
  348. LinkedList1Node *ln;
  349. while (ln = LinkedList1_GetFirst(&processes)) {
  350. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  351. process_free(p);
  352. }
  353. fail5:
  354. // free modules
  355. while (num_inited_modules > 0) {
  356. const struct NCDModuleGroup **g = &ncd_modules[num_inited_modules - 1];
  357. if ((*g)->func_globalfree) {
  358. (*g)->func_globalfree();
  359. }
  360. num_inited_modules--;
  361. }
  362. // free configuration
  363. NCDConfig_free_processes(config_ast);
  364. fail3:
  365. // remove signal handler
  366. BSignal_Finish();
  367. fail2:
  368. // free module index
  369. NCDModuleIndex_Free(&mindex);
  370. // free udev manager
  371. NCDUdevManager_Free(&umanager);
  372. // free process manager
  373. BProcessManager_Free(&manager);
  374. fail1a:
  375. // free reactor
  376. BReactor_Free(&ss);
  377. fail1:
  378. // free logger
  379. BLog(BLOG_NOTICE, "exiting");
  380. BLog_Free();
  381. fail0:
  382. // finish objects
  383. DebugObjectGlobal_Finish();
  384. return main_exit_code;
  385. }
  386. void print_help (const char *name)
  387. {
  388. printf(
  389. "Usage:\n"
  390. " %s\n"
  391. " [--help]\n"
  392. " [--version]\n"
  393. " [--logger <stdout/stderr/syslog>]\n"
  394. " (logger=syslog?\n"
  395. " [--syslog-facility <string>]\n"
  396. " [--syslog-ident <string>]\n"
  397. " )\n"
  398. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  399. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  400. " --config-file <file>\n"
  401. " [--retry-time <ms>]\n"
  402. " [--no-udev]\n"
  403. " [-- [<extra_arg>] ...]\n",
  404. name
  405. );
  406. }
  407. void print_version (void)
  408. {
  409. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  410. }
  411. int parse_arguments (int argc, char *argv[])
  412. {
  413. if (argc <= 0) {
  414. return 0;
  415. }
  416. options.help = 0;
  417. options.version = 0;
  418. options.logger = LOGGER_STDERR;
  419. options.logger_syslog_facility = "daemon";
  420. options.logger_syslog_ident = argv[0];
  421. options.loglevel = -1;
  422. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  423. options.loglevels[i] = -1;
  424. }
  425. options.config_file = NULL;
  426. options.retry_time = DEFAULT_RETRY_TIME;
  427. options.no_udev = 0;
  428. options.extra_args = NULL;
  429. options.num_extra_args = 0;
  430. for (int i = 1; i < argc; i++) {
  431. char *arg = argv[i];
  432. if (!strcmp(arg, "--help")) {
  433. options.help = 1;
  434. }
  435. else if (!strcmp(arg, "--version")) {
  436. options.version = 1;
  437. }
  438. else if (!strcmp(arg, "--logger")) {
  439. if (1 >= argc - i) {
  440. fprintf(stderr, "%s: requires an argument\n", arg);
  441. return 0;
  442. }
  443. char *arg2 = argv[i + 1];
  444. if (!strcmp(arg2, "stdout")) {
  445. options.logger = LOGGER_STDOUT;
  446. }
  447. else if (!strcmp(arg2, "stderr")) {
  448. options.logger = LOGGER_STDERR;
  449. }
  450. else if (!strcmp(arg2, "syslog")) {
  451. options.logger = LOGGER_SYSLOG;
  452. }
  453. else {
  454. fprintf(stderr, "%s: wrong argument\n", arg);
  455. return 0;
  456. }
  457. i++;
  458. }
  459. else if (!strcmp(arg, "--syslog-facility")) {
  460. if (1 >= argc - i) {
  461. fprintf(stderr, "%s: requires an argument\n", arg);
  462. return 0;
  463. }
  464. options.logger_syslog_facility = argv[i + 1];
  465. i++;
  466. }
  467. else if (!strcmp(arg, "--syslog-ident")) {
  468. if (1 >= argc - i) {
  469. fprintf(stderr, "%s: requires an argument\n", arg);
  470. return 0;
  471. }
  472. options.logger_syslog_ident = argv[i + 1];
  473. i++;
  474. }
  475. else if (!strcmp(arg, "--loglevel")) {
  476. if (1 >= argc - i) {
  477. fprintf(stderr, "%s: requires an argument\n", arg);
  478. return 0;
  479. }
  480. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  481. fprintf(stderr, "%s: wrong argument\n", arg);
  482. return 0;
  483. }
  484. i++;
  485. }
  486. else if (!strcmp(arg, "--channel-loglevel")) {
  487. if (2 >= argc - i) {
  488. fprintf(stderr, "%s: requires two arguments\n", arg);
  489. return 0;
  490. }
  491. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  492. if (channel < 0) {
  493. fprintf(stderr, "%s: wrong channel argument\n", arg);
  494. return 0;
  495. }
  496. int loglevel = parse_loglevel(argv[i + 2]);
  497. if (loglevel < 0) {
  498. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  499. return 0;
  500. }
  501. options.loglevels[channel] = loglevel;
  502. i += 2;
  503. }
  504. else if (!strcmp(arg, "--config-file")) {
  505. if (1 >= argc - i) {
  506. fprintf(stderr, "%s: requires an argument\n", arg);
  507. return 0;
  508. }
  509. options.config_file = argv[i + 1];
  510. i++;
  511. }
  512. else if (!strcmp(arg, "--retry-time")) {
  513. if (1 >= argc - i) {
  514. fprintf(stderr, "%s: requires an argument\n", arg);
  515. return 0;
  516. }
  517. if ((options.retry_time = atoi(argv[i + 1])) < 0) {
  518. fprintf(stderr, "%s: wrong argument\n", arg);
  519. return 0;
  520. }
  521. i++;
  522. }
  523. else if (!strcmp(arg, "--no-udev")) {
  524. options.no_udev = 1;
  525. }
  526. else if (!strcmp(arg, "--")) {
  527. options.extra_args = &argv[i + 1];
  528. options.num_extra_args = argc - i - 1;
  529. i += options.num_extra_args;
  530. }
  531. else {
  532. fprintf(stderr, "unknown option: %s\n", arg);
  533. return 0;
  534. }
  535. }
  536. if (options.help || options.version) {
  537. return 1;
  538. }
  539. if (!options.config_file) {
  540. fprintf(stderr, "--config-file is required\n");
  541. return 0;
  542. }
  543. return 1;
  544. }
  545. void signal_handler (void *unused)
  546. {
  547. BLog(BLOG_NOTICE, "termination requested");
  548. start_terminate(1);
  549. }
  550. void start_terminate (int exit_code)
  551. {
  552. main_exit_code = exit_code;
  553. if (terminating) {
  554. return;
  555. }
  556. terminating = 1;
  557. if (LinkedList1_IsEmpty(&processes)) {
  558. BReactor_Quit(&ss, 0);
  559. return;
  560. }
  561. // start terminating non-template processes
  562. for (LinkedList1Node *ln = LinkedList1_GetFirst(&processes); ln; ln = LinkedList1Node_Next(ln)) {
  563. struct process *p = UPPER_OBJECT(ln, struct process, list_node);
  564. if (p->module_process) {
  565. continue;
  566. }
  567. if (p->state != PSTATE_TERMINATING) {
  568. process_start_terminating(p);
  569. }
  570. }
  571. }
  572. int arg_value_init_string (struct arg_value *o, const char *string, size_t len)
  573. {
  574. o->type = ARG_VALUE_TYPE_STRING;
  575. if (!(o->string = malloc(len))) {
  576. BLog(BLOG_ERROR, "malloc failed");
  577. return 0;
  578. }
  579. memcpy(o->string, string, len);
  580. o->string_len = len;
  581. return 1;
  582. }
  583. int arg_value_init_variable (struct arg_value *o, struct NCDConfig_strings *ast_names)
  584. {
  585. ASSERT(ast_names)
  586. o->type = ARG_VALUE_TYPE_VARIABLE;
  587. if (!(o->variable_names = names_new(ast_names))) {
  588. return 0;
  589. }
  590. return 1;
  591. }
  592. void arg_value_init_list (struct arg_value *o)
  593. {
  594. o->type = ARG_VALUE_TYPE_LIST;
  595. LinkedList1_Init(&o->list);
  596. }
  597. int arg_value_list_append (struct arg_value *o, struct arg_value v)
  598. {
  599. ASSERT(o->type == ARG_VALUE_TYPE_LIST)
  600. struct arg_list_elem *elem = malloc(sizeof(*elem));
  601. if (!elem) {
  602. BLog(BLOG_ERROR, "malloc failed");
  603. return 0;
  604. }
  605. LinkedList1_Append(&o->list, &elem->list_node);
  606. elem->value = v;
  607. return 1;
  608. }
  609. void arg_value_init_map (struct arg_value *o)
  610. {
  611. o->type = ARG_VALUE_TYPE_MAP;
  612. LinkedList1_Init(&o->maplist);
  613. }
  614. int arg_value_map_append (struct arg_value *o, struct arg_value key, struct arg_value val)
  615. {
  616. ASSERT(o->type == ARG_VALUE_TYPE_MAP)
  617. struct arg_map_elem *elem = malloc(sizeof(*elem));
  618. if (!elem) {
  619. BLog(BLOG_ERROR, "malloc failed");
  620. return 0;
  621. }
  622. LinkedList1_Append(&o->maplist, &elem->maplist_node);
  623. elem->key = key;
  624. elem->val = val;
  625. return 1;
  626. }
  627. void arg_value_free (struct arg_value *o)
  628. {
  629. switch (o->type) {
  630. case ARG_VALUE_TYPE_STRING: {
  631. free(o->string);
  632. } break;
  633. case ARG_VALUE_TYPE_VARIABLE: {
  634. names_free(o->variable_names);
  635. } break;
  636. case ARG_VALUE_TYPE_LIST: {
  637. while (!LinkedList1_IsEmpty(&o->list)) {
  638. struct arg_list_elem *elem = UPPER_OBJECT(LinkedList1_GetFirst(&o->list), struct arg_list_elem, list_node);
  639. arg_value_free(&elem->value);
  640. LinkedList1_Remove(&o->list, &elem->list_node);
  641. free(elem);
  642. }
  643. } break;
  644. case ARG_VALUE_TYPE_MAP: {
  645. while (!LinkedList1_IsEmpty(&o->maplist)) {
  646. struct arg_map_elem *elem = UPPER_OBJECT(LinkedList1_GetFirst(&o->maplist), struct arg_map_elem, maplist_node);
  647. arg_value_free(&elem->key);
  648. arg_value_free(&elem->val);
  649. LinkedList1_Remove(&o->maplist, &elem->maplist_node);
  650. free(elem);
  651. }
  652. } break;
  653. default: ASSERT(0);
  654. }
  655. }
  656. int build_arg_from_ast (struct arg_value *o, struct NCDConfig_list *ast)
  657. {
  658. switch (ast->type) {
  659. case NCDCONFIG_ARG_STRING: {
  660. if (!arg_value_init_string(o, ast->string, ast->string_len)) {
  661. return 0;
  662. }
  663. } break;
  664. case NCDCONFIG_ARG_VAR: {
  665. if (!arg_value_init_variable(o, ast->var)) {
  666. return 0;
  667. }
  668. } break;
  669. case NCDCONFIG_ARG_LIST: {
  670. if (!build_arg_list_from_ast_list(o, ast->list)) {
  671. return 0;
  672. }
  673. } break;
  674. case NCDCONFIG_ARG_MAPLIST: {
  675. if (!build_arg_map_from_ast_list(o, ast->list)) {
  676. return 0;
  677. }
  678. } break;
  679. default: ASSERT(0);
  680. }
  681. return 1;
  682. }
  683. int build_arg_list_from_ast_list (struct arg_value *o, struct NCDConfig_list *list)
  684. {
  685. arg_value_init_list(o);
  686. for (struct NCDConfig_list *c = list; c; c = c->next) {
  687. struct arg_value e;
  688. if (!build_arg_from_ast(&e, c)) {
  689. goto fail;
  690. }
  691. if (!arg_value_list_append(o, e)) {
  692. arg_value_free(&e);
  693. goto fail;
  694. }
  695. }
  696. return 1;
  697. fail:
  698. arg_value_free(o);
  699. return 0;
  700. }
  701. int build_arg_map_from_ast_list (struct arg_value *o, struct NCDConfig_list *list)
  702. {
  703. arg_value_init_map(o);
  704. for (struct NCDConfig_list *c = list; c; c = c->next->next) {
  705. ASSERT(c->next)
  706. struct arg_value key;
  707. struct arg_value val;
  708. if (!build_arg_from_ast(&key, c)) {
  709. goto fail;
  710. }
  711. if (!build_arg_from_ast(&val, c->next)) {
  712. arg_value_free(&key);
  713. goto fail;
  714. }
  715. if (!arg_value_map_append(o, key, val)) {
  716. arg_value_free(&key);
  717. arg_value_free(&val);
  718. goto fail;
  719. }
  720. }
  721. return 1;
  722. fail:
  723. arg_value_free(o);
  724. return 0;
  725. }
  726. static char ** names_new (struct NCDConfig_strings *ast_names)
  727. {
  728. ASSERT(ast_names)
  729. bsize_t size = bsize_fromsize(1);
  730. for (struct NCDConfig_strings *n = ast_names; n; n = n->next) {
  731. size = bsize_add(size, bsize_fromsize(1));
  732. }
  733. char **names;
  734. if (size.is_overflow || !(names = BAllocArray(size.value, sizeof(names[0])))) {
  735. BLog(BLOG_ERROR, "BAllocArray failed");
  736. goto fail0;
  737. }
  738. size_t i = 0;
  739. for (struct NCDConfig_strings *n = ast_names; n; n = n->next) {
  740. if (!(names[i] = strdup(n->value))) {
  741. BLog(BLOG_ERROR, "strdup failed");
  742. goto fail1;
  743. }
  744. i++;
  745. }
  746. names[i] = NULL;
  747. return names;
  748. fail1:
  749. while (i-- > 0) {
  750. free(names[i]);
  751. }
  752. BFree(names);
  753. fail0:
  754. return NULL;
  755. }
  756. static size_t names_count (char **names)
  757. {
  758. ASSERT(names)
  759. size_t i;
  760. for (i = 0; names[i]; i++);
  761. return i;
  762. }
  763. static char * names_tostring (char **names)
  764. {
  765. ASSERT(names)
  766. ExpString str;
  767. if (!ExpString_Init(&str)) {
  768. goto fail0;
  769. }
  770. for (size_t i = 0; names[i]; i++) {
  771. if (i > 0 && !ExpString_AppendChar(&str, '.')) {
  772. goto fail1;
  773. }
  774. if (!ExpString_Append(&str, names[i])) {
  775. goto fail1;
  776. }
  777. }
  778. return ExpString_Get(&str);
  779. fail1:
  780. ExpString_Free(&str);
  781. fail0:
  782. return NULL;
  783. }
  784. static void names_free (char **names)
  785. {
  786. ASSERT(names)
  787. size_t i = names_count(names);
  788. while (i-- > 0) {
  789. free(names[i]);
  790. }
  791. BFree(names);
  792. }
  793. int statement_init (struct statement *s, struct NCDConfig_statements *conf)
  794. {
  795. // set object names
  796. if (conf->objname) {
  797. if (!(s->object_names = names_new(conf->objname))) {
  798. goto fail0;
  799. }
  800. } else {
  801. s->object_names = NULL;
  802. }
  803. // set method name
  804. if (!(s->method_name = NCDConfig_concat_strings(conf->names))) {
  805. BLog(BLOG_ERROR, "NCDConfig_concat_strings failed");
  806. goto fail1;
  807. }
  808. // init name
  809. if (conf->name) {
  810. if (!(s->name = strdup(conf->name))) {
  811. BLog(BLOG_ERROR, "strdup failed");
  812. goto fail2;
  813. }
  814. } else {
  815. s->name = NULL;
  816. }
  817. // init arguments
  818. if (!build_arg_list_from_ast_list(&s->args, conf->args)) {
  819. BLog(BLOG_ERROR, "build_arg_list_from_ast_list failed");
  820. goto fail3;
  821. }
  822. return 1;
  823. fail3:
  824. free(s->name);
  825. fail2:
  826. free(s->method_name);
  827. fail1:
  828. if (s->object_names) {
  829. names_free(s->object_names);
  830. }
  831. fail0:
  832. return 0;
  833. }
  834. void statement_free (struct statement *s)
  835. {
  836. // free arguments
  837. arg_value_free(&s->args);
  838. // free name
  839. free(s->name);
  840. // free method name
  841. free(s->method_name);
  842. // free object names
  843. if (s->object_names) {
  844. names_free(s->object_names);
  845. }
  846. }
  847. int process_new (struct NCDConfig_processes *conf, NCDModuleProcess *module_process)
  848. {
  849. // allocate strucure
  850. struct process *p = malloc(sizeof(*p));
  851. if (!p) {
  852. BLog(BLOG_ERROR, "malloc failed");
  853. goto fail0;
  854. }
  855. // set module process
  856. p->module_process = module_process;
  857. // set module process handlers
  858. if (p->module_process) {
  859. NCDModuleProcess_Interp_SetHandlers(p->module_process, p,
  860. (NCDModuleProcess_interp_func_event)process_moduleprocess_func_event,
  861. (NCDModuleProcess_interp_func_getobj)process_moduleprocess_func_getobj);
  862. }
  863. // init name
  864. if (!(p->name = strdup(conf->name))) {
  865. BLog(BLOG_ERROR, "strdup failed");
  866. goto fail1;
  867. }
  868. // count statements
  869. size_t num_st = 0;
  870. struct NCDConfig_statements *st = conf->statements;
  871. while (st) {
  872. if (num_st == SIZE_MAX) {
  873. BLog(BLOG_ERROR, "too many statements");
  874. goto fail2;
  875. }
  876. num_st++;
  877. st = st->next;
  878. }
  879. // allocate statements array
  880. if (!(p->statements = BAllocArray(num_st, sizeof(p->statements[0])))) {
  881. goto fail2;
  882. }
  883. p->num_statements = 0;
  884. // init statements
  885. st = conf->statements;
  886. while (st) {
  887. struct process_statement *ps = &p->statements[p->num_statements];
  888. ps->p = p;
  889. ps->i = p->num_statements;
  890. if (!statement_init(&ps->s, st)) {
  891. goto fail3;
  892. }
  893. ps->state = SSTATE_FORGOTTEN;
  894. ps->have_error = 0;
  895. p->num_statements++;
  896. st = st->next;
  897. }
  898. // set state working
  899. p->state = PSTATE_WORKING;
  900. // set AP=0
  901. p->ap = 0;
  902. // set FP=0
  903. p->fp = 0;
  904. // init timer
  905. BTimer_Init(&p->wait_timer, 0, (BTimer_handler)process_wait_timer_handler, p);
  906. // init advance job
  907. BPending_Init(&p->advance_job, BReactor_PendingGroup(&ss), (BPending_handler)process_advance_job_handler, p);
  908. // init work job
  909. BPending_Init(&p->work_job, BReactor_PendingGroup(&ss), (BPending_handler)process_work_job_handler, p);
  910. // insert to processes list
  911. LinkedList1_Append(&processes, &p->list_node);
  912. // schedule work
  913. BPending_Set(&p->work_job);
  914. return 1;
  915. fail3:
  916. process_free_statements(p);
  917. fail2:
  918. free(p->name);
  919. fail1:
  920. free(p);
  921. fail0:
  922. BLog(BLOG_ERROR, "failed to initialize process %s", conf->name);
  923. return 0;
  924. }
  925. void process_free (struct process *p)
  926. {
  927. ASSERT(p->ap == 0)
  928. ASSERT(p->fp == 0)
  929. // inform module process that the process is terminated
  930. if (p->module_process) {
  931. NCDModuleProcess_Interp_Terminated(p->module_process);
  932. }
  933. // remove from processes list
  934. LinkedList1_Remove(&processes, &p->list_node);
  935. // free work job
  936. BPending_Free(&p->work_job);
  937. // free advance job
  938. BPending_Free(&p->advance_job);
  939. // free timer
  940. BReactor_RemoveTimer(&ss, &p->wait_timer);
  941. // free statements
  942. process_free_statements(p);
  943. // free name
  944. free(p->name);
  945. // free strucure
  946. free(p);
  947. }
  948. void process_start_terminating (struct process *p)
  949. {
  950. ASSERT(p->state != PSTATE_TERMINATING)
  951. // set terminating
  952. p->state = PSTATE_TERMINATING;
  953. // schedule work
  954. process_schedule_work(p);
  955. }
  956. size_t process_rap (struct process *p)
  957. {
  958. if (p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD) {
  959. return (p->ap - 1);
  960. } else {
  961. return p->ap;
  962. }
  963. }
  964. void process_free_statements (struct process *p)
  965. {
  966. // free statments
  967. while (p->num_statements > 0) {
  968. statement_free(&p->statements[p->num_statements - 1].s);
  969. p->num_statements--;
  970. }
  971. // free stataments array
  972. free(p->statements);
  973. }
  974. void process_assert_pointers (struct process *p)
  975. {
  976. ASSERT(p->ap <= p->num_statements)
  977. ASSERT(p->fp >= p->ap)
  978. ASSERT(p->fp <= p->num_statements)
  979. #ifndef NDEBUG
  980. // check AP
  981. for (size_t i = 0; i < p->ap; i++) {
  982. if (i == p->ap - 1) {
  983. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  984. } else {
  985. ASSERT(p->statements[i].state == SSTATE_ADULT)
  986. }
  987. }
  988. // check FP
  989. size_t fp = p->num_statements;
  990. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  991. fp--;
  992. }
  993. ASSERT(p->fp == fp)
  994. #endif
  995. }
  996. void process_logfunc (struct process *p)
  997. {
  998. BLog_Append("process %s: ", p->name);
  999. }
  1000. void process_log (struct process *p, int level, const char *fmt, ...)
  1001. {
  1002. va_list vl;
  1003. va_start(vl, fmt);
  1004. BLog_LogViaFuncVarArg((BLog_logfunc)process_logfunc, p, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1005. va_end(vl);
  1006. }
  1007. void process_schedule_work (struct process *p)
  1008. {
  1009. process_assert_pointers(p);
  1010. // stop timer
  1011. BReactor_RemoveTimer(&ss, &p->wait_timer);
  1012. // stop advance job
  1013. BPending_Unset(&p->advance_job);
  1014. // schedule work
  1015. BPending_Set(&p->work_job);
  1016. }
  1017. void process_work_job_handler (struct process *p)
  1018. {
  1019. process_assert_pointers(p);
  1020. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  1021. ASSERT(!BPending_IsSet(&p->advance_job))
  1022. if (p->state == PSTATE_WAITING) {
  1023. return;
  1024. }
  1025. if (p->state == PSTATE_TERMINATING) {
  1026. if (p->fp == 0) {
  1027. // finished retreating
  1028. process_free(p);
  1029. // if program is terminating amd there are no more processes, exit program
  1030. if (terminating && LinkedList1_IsEmpty(&processes)) {
  1031. BReactor_Quit(&ss, 0);
  1032. }
  1033. return;
  1034. }
  1035. // order the last living statement to die, if needed
  1036. struct process_statement *ps = &p->statements[p->fp - 1];
  1037. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1038. if (ps->state != SSTATE_DYING) {
  1039. process_statement_log(ps, BLOG_INFO, "killing");
  1040. // order it to die
  1041. NCDModuleInst_Die(&ps->inst);
  1042. // set statement state DYING
  1043. ps->state = SSTATE_DYING;
  1044. // update AP
  1045. if (p->ap > ps->i) {
  1046. p->ap = ps->i;
  1047. }
  1048. }
  1049. return;
  1050. }
  1051. // process was up but is no longer?
  1052. if (p->state == PSTATE_UP && !(p->ap == process_rap(p) && p->ap == p->num_statements)) {
  1053. // if we have module process, wait for its permission to continue
  1054. if (p->module_process) {
  1055. // set module process down
  1056. NCDModuleProcess_Interp_Down(p->module_process);
  1057. // set state waiting
  1058. p->state = PSTATE_WAITING;
  1059. return;
  1060. }
  1061. // set state working
  1062. p->state = PSTATE_WORKING;
  1063. }
  1064. // cleaning up?
  1065. if (p->ap < p->fp) {
  1066. // order the last living statement to die, if needed
  1067. struct process_statement *ps = &p->statements[p->fp - 1];
  1068. if (ps->state != SSTATE_DYING) {
  1069. process_statement_log(ps, BLOG_INFO, "killing");
  1070. // order it to die
  1071. NCDModuleInst_Die(&ps->inst);
  1072. // set statement state DYING
  1073. ps->state = SSTATE_DYING;
  1074. }
  1075. return;
  1076. }
  1077. // clean?
  1078. if (p->ap > process_rap(p)) {
  1079. ASSERT(p->ap > 0)
  1080. ASSERT(p->ap <= p->num_statements)
  1081. struct process_statement *ps = &p->statements[p->ap - 1];
  1082. ASSERT(ps->state == SSTATE_CHILD)
  1083. process_statement_log(ps, BLOG_INFO, "clean");
  1084. // report clean
  1085. NCDModuleInst_Clean(&ps->inst);
  1086. return;
  1087. }
  1088. // advancing?
  1089. if (p->ap < p->num_statements) {
  1090. ASSERT(p->state == PSTATE_WORKING)
  1091. struct process_statement *ps = &p->statements[p->ap];
  1092. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1093. // clear expired error
  1094. if (ps->have_error && ps->error_until <= btime_gettime()) {
  1095. ps->have_error = 0;
  1096. }
  1097. if (ps->have_error) {
  1098. process_statement_log(ps, BLOG_INFO, "waiting after error");
  1099. // set wait timer
  1100. BReactor_SetTimerAbsolute(&ss, &p->wait_timer, ps->error_until);
  1101. } else {
  1102. // schedule advance
  1103. BPending_Set(&p->advance_job);
  1104. }
  1105. return;
  1106. }
  1107. // have we just finished?
  1108. if (p->state == PSTATE_WORKING) {
  1109. process_log(p, BLOG_INFO, "victory");
  1110. // set module process up
  1111. if (p->module_process) {
  1112. NCDModuleProcess_Interp_Up(p->module_process);
  1113. }
  1114. // set state up
  1115. p->state = PSTATE_UP;
  1116. }
  1117. }
  1118. void process_advance_job_handler (struct process *p)
  1119. {
  1120. process_assert_pointers(p);
  1121. ASSERT(p->ap == p->fp)
  1122. ASSERT(p->ap == process_rap(p))
  1123. ASSERT(p->ap < p->num_statements)
  1124. ASSERT(!p->statements[p->ap].have_error)
  1125. ASSERT(!BPending_IsSet(&p->work_job))
  1126. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  1127. ASSERT(p->state == PSTATE_WORKING)
  1128. struct process_statement *ps = &p->statements[p->ap];
  1129. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1130. process_statement_log(ps, BLOG_INFO, "initializing");
  1131. NCDObject object;
  1132. NCDObject *object_ptr = NULL;
  1133. char *type;
  1134. int free_type = 0;
  1135. if (!ps->s.object_names) {
  1136. // this is a function_call(); type is "function_call"
  1137. type = ps->s.method_name;
  1138. } else {
  1139. // this is a some.object.somewhere->method_call(); type is "base_type(some.object.somewhere)::method_call"
  1140. // get object
  1141. if (!process_resolve_object_expr(p, p->ap, ps->s.object_names, &object)) {
  1142. goto fail;
  1143. }
  1144. object_ptr = &object;
  1145. // get object type
  1146. const char *object_type = NCDObject_Type(&object);
  1147. if (!object_type) {
  1148. process_statement_log(ps, BLOG_ERROR, "cannot call method on object with no type");
  1149. goto fail;
  1150. }
  1151. // build type string
  1152. if (!(type = concat_strings(3, object_type, "::", ps->s.method_name))) {
  1153. process_statement_log(ps, BLOG_ERROR, "concat_strings failed");
  1154. goto fail;
  1155. }
  1156. free_type = 1;
  1157. }
  1158. // find module to instantiate
  1159. const struct NCDModule *module = NCDModuleIndex_FindModule(&mindex, type);
  1160. if (!module) {
  1161. process_statement_log(ps, BLOG_ERROR, "failed to find module: %s", type);
  1162. goto fail;
  1163. }
  1164. // resolve arguments
  1165. if (!process_statement_resolve_argument(ps, &ps->s.args, &ps->inst_args)) {
  1166. process_statement_log(ps, BLOG_ERROR, "failed to resolve arguments");
  1167. goto fail;
  1168. }
  1169. // initialize module instance
  1170. NCDModuleInst_Init(&ps->inst, module, object_ptr, &ps->inst_args, ps, &module_params, &module_iparams);
  1171. // set statement state CHILD
  1172. ps->state = SSTATE_CHILD;
  1173. // increment AP
  1174. p->ap++;
  1175. // increment FP
  1176. p->fp++;
  1177. if (free_type) {
  1178. free(type);
  1179. }
  1180. process_assert_pointers(p);
  1181. return;
  1182. fail:
  1183. if (free_type) {
  1184. free(type);
  1185. }
  1186. // mark error
  1187. process_statement_set_error(ps);
  1188. // schedule work to start the timer
  1189. process_schedule_work(p);
  1190. }
  1191. void process_wait_timer_handler (struct process *p)
  1192. {
  1193. process_assert_pointers(p);
  1194. ASSERT(p->ap == p->fp)
  1195. ASSERT(p->ap == process_rap(p))
  1196. ASSERT(p->ap < p->num_statements)
  1197. ASSERT(p->statements[p->ap].have_error)
  1198. ASSERT(!BPending_IsSet(&p->work_job))
  1199. ASSERT(!BPending_IsSet(&p->advance_job))
  1200. ASSERT(p->state == PSTATE_WORKING)
  1201. process_log(p, BLOG_INFO, "retrying");
  1202. // clear error
  1203. p->statements[p->ap].have_error = 0;
  1204. // schedule work
  1205. BPending_Set(&p->work_job);
  1206. }
  1207. int process_find_object (struct process *p, size_t pos, const char *name, NCDObject *out_object)
  1208. {
  1209. ASSERT(pos <= p->num_statements)
  1210. ASSERT(name)
  1211. ASSERT(out_object)
  1212. for (size_t i = pos; i > 0; i--) {
  1213. struct process_statement *ps = &p->statements[i - 1];
  1214. if (ps->s.name && !strcmp(ps->s.name, name)) {
  1215. if (ps->state == SSTATE_FORGOTTEN) {
  1216. process_log(p, BLOG_ERROR, "statement (%zu) is uninitialized", i - 1);
  1217. goto fail;
  1218. }
  1219. *out_object = NCDModuleInst_Object(&ps->inst);
  1220. return 1;
  1221. }
  1222. }
  1223. if (p->module_process && NCDModuleProcess_Interp_GetSpecialObj(p->module_process, name, out_object)) {
  1224. return 1;
  1225. }
  1226. fail:
  1227. return 0;
  1228. }
  1229. int process_resolve_object_expr (struct process *p, size_t pos, char **names, NCDObject *out_object)
  1230. {
  1231. ASSERT(pos <= p->num_statements)
  1232. ASSERT(names)
  1233. ASSERT(names_count(names) > 0)
  1234. ASSERT(out_object)
  1235. NCDObject object;
  1236. if (!process_find_object(p, pos, names[0], &object)) {
  1237. goto fail;
  1238. }
  1239. if (!NCDObject_ResolveObjExpr(&object, names + 1, out_object)) {
  1240. goto fail;
  1241. }
  1242. return 1;
  1243. fail:;
  1244. char *name = names_tostring(names);
  1245. process_log(p, BLOG_ERROR, "failed to resolve object (%s) from position %zu", (name ? name : ""), pos);
  1246. free(name);
  1247. return 0;
  1248. }
  1249. int process_resolve_variable_expr (struct process *p, size_t pos, char **names, NCDValue *out_value)
  1250. {
  1251. ASSERT(pos <= p->num_statements)
  1252. ASSERT(names)
  1253. ASSERT(names_count(names) > 0)
  1254. ASSERT(out_value)
  1255. NCDObject object;
  1256. if (!process_find_object(p, pos, names[0], &object)) {
  1257. goto fail;
  1258. }
  1259. if (!NCDObject_ResolveVarExpr(&object, names + 1, out_value)) {
  1260. goto fail;
  1261. }
  1262. return 1;
  1263. fail:;
  1264. char *name = names_tostring(names);
  1265. process_log(p, BLOG_ERROR, "failed to resolve variable (%s) from position %zu", (name ? name : ""), pos);
  1266. free(name);
  1267. return 0;
  1268. }
  1269. void process_statement_logfunc (struct process_statement *ps)
  1270. {
  1271. process_logfunc(ps->p);
  1272. BLog_Append("statement %zu: ", ps->i);
  1273. }
  1274. void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...)
  1275. {
  1276. va_list vl;
  1277. va_start(vl, fmt);
  1278. BLog_LogViaFuncVarArg((BLog_logfunc)process_statement_logfunc, ps, BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1279. va_end(vl);
  1280. }
  1281. void process_statement_set_error (struct process_statement *ps)
  1282. {
  1283. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1284. ps->have_error = 1;
  1285. ps->error_until = btime_add(btime_gettime(), options.retry_time);
  1286. }
  1287. int process_statement_resolve_argument (struct process_statement *ps, struct arg_value *arg, NCDValue *out)
  1288. {
  1289. ASSERT(ps->i <= process_rap(ps->p))
  1290. ASSERT(arg)
  1291. ASSERT(out)
  1292. switch (arg->type) {
  1293. case ARG_VALUE_TYPE_STRING: {
  1294. if (!NCDValue_InitStringBin(out, (uint8_t *)arg->string, arg->string_len)) {
  1295. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitStringBin failed");
  1296. return 0;
  1297. }
  1298. } break;
  1299. case ARG_VALUE_TYPE_VARIABLE: {
  1300. if (!process_resolve_variable_expr(ps->p, ps->i, arg->variable_names, out)) {
  1301. return 0;
  1302. }
  1303. } break;
  1304. case ARG_VALUE_TYPE_LIST: do {
  1305. NCDValue_InitList(out);
  1306. for (LinkedList1Node *n = LinkedList1_GetFirst(&arg->list); n; n = LinkedList1Node_Next(n)) {
  1307. struct arg_list_elem *elem = UPPER_OBJECT(n, struct arg_list_elem, list_node);
  1308. NCDValue v;
  1309. if (!process_statement_resolve_argument(ps, &elem->value, &v)) {
  1310. goto list_fail1;
  1311. }
  1312. if (!NCDValue_ListAppend(out, v)) {
  1313. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  1314. NCDValue_Free(&v);
  1315. goto list_fail1;
  1316. }
  1317. }
  1318. break;
  1319. list_fail1:
  1320. NCDValue_Free(out);
  1321. return 0;
  1322. } while (0); break;
  1323. case ARG_VALUE_TYPE_MAP: do {
  1324. NCDValue_InitMap(out);
  1325. for (LinkedList1Node *n = LinkedList1_GetFirst(&arg->maplist); n; n = LinkedList1Node_Next(n)) {
  1326. struct arg_map_elem *elem = UPPER_OBJECT(n, struct arg_map_elem, maplist_node);
  1327. NCDValue key;
  1328. NCDValue val;
  1329. if (!process_statement_resolve_argument(ps, &elem->key, &key)) {
  1330. goto map_fail;
  1331. }
  1332. if (!process_statement_resolve_argument(ps, &elem->val, &val)) {
  1333. NCDValue_Free(&key);
  1334. goto map_fail;
  1335. }
  1336. if (NCDValue_MapFindKey(out, &key)) {
  1337. process_statement_log(ps, BLOG_ERROR, "duplicate map keys");
  1338. NCDValue_Free(&key);
  1339. NCDValue_Free(&val);
  1340. goto map_fail;
  1341. }
  1342. if (!NCDValue_MapInsert(out, key, val)) {
  1343. process_statement_log(ps, BLOG_ERROR, "NCDValue_MapInsert failed");
  1344. NCDValue_Free(&key);
  1345. NCDValue_Free(&val);
  1346. goto map_fail;
  1347. }
  1348. }
  1349. break;
  1350. map_fail:
  1351. NCDValue_Free(out);
  1352. return 0;
  1353. } while (0); break;
  1354. default: ASSERT(0);
  1355. }
  1356. return 1;
  1357. }
  1358. void process_statement_instance_func_event (struct process_statement *ps, int event)
  1359. {
  1360. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  1361. struct process *p = ps->p;
  1362. process_assert_pointers(p);
  1363. // schedule work
  1364. process_schedule_work(p);
  1365. switch (event) {
  1366. case NCDMODULE_EVENT_UP: {
  1367. ASSERT(ps->state == SSTATE_CHILD)
  1368. process_statement_log(ps, BLOG_INFO, "up");
  1369. // set state ADULT
  1370. ps->state = SSTATE_ADULT;
  1371. } break;
  1372. case NCDMODULE_EVENT_DOWN: {
  1373. ASSERT(ps->state == SSTATE_ADULT)
  1374. process_statement_log(ps, BLOG_INFO, "down");
  1375. // set state CHILD
  1376. ps->state = SSTATE_CHILD;
  1377. // update AP
  1378. if (p->ap > ps->i + 1) {
  1379. p->ap = ps->i + 1;
  1380. }
  1381. } break;
  1382. case NCDMODULE_EVENT_DEAD: {
  1383. int is_error = NCDModuleInst_HaveError(&ps->inst);
  1384. if (is_error) {
  1385. process_statement_log(ps, BLOG_ERROR, "died with error");
  1386. } else {
  1387. process_statement_log(ps, BLOG_INFO, "died");
  1388. }
  1389. // free instance
  1390. NCDModuleInst_Free(&ps->inst);
  1391. // free instance arguments
  1392. NCDValue_Free(&ps->inst_args);
  1393. // set state FORGOTTEN
  1394. ps->state = SSTATE_FORGOTTEN;
  1395. // set error
  1396. if (is_error) {
  1397. process_statement_set_error(ps);
  1398. }
  1399. // update AP
  1400. if (p->ap > ps->i) {
  1401. p->ap = ps->i;
  1402. }
  1403. // update FP
  1404. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  1405. p->fp--;
  1406. }
  1407. } break;
  1408. }
  1409. }
  1410. int process_statement_instance_func_getobj (struct process_statement *ps, const char *objname, NCDObject *out_object)
  1411. {
  1412. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1413. return process_find_object(ps->p, ps->i, objname, out_object);
  1414. }
  1415. int process_statement_instance_func_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name)
  1416. {
  1417. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1418. // find template
  1419. struct NCDConfig_processes *conf = config_ast;
  1420. while (conf) {
  1421. if (conf->is_template && !strcmp(conf->name, template_name)) {
  1422. break;
  1423. }
  1424. conf = conf->next;
  1425. }
  1426. if (!conf) {
  1427. process_statement_log(ps, BLOG_ERROR, "no template named %s", template_name);
  1428. return 0;
  1429. }
  1430. // create process
  1431. if (!process_new(conf, mp)) {
  1432. process_statement_log(ps, BLOG_ERROR, "failed to create process from template %s", template_name);
  1433. return 0;
  1434. }
  1435. process_statement_log(ps, BLOG_INFO, "created process from template %s", template_name);
  1436. return 1;
  1437. }
  1438. void process_statement_instance_logfunc (struct process_statement *ps)
  1439. {
  1440. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1441. process_statement_logfunc(ps);
  1442. BLog_Append("module: ");
  1443. }
  1444. void process_statement_instance_func_interp_exit (struct process_statement *ps, int exit_code)
  1445. {
  1446. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1447. start_terminate(exit_code);
  1448. }
  1449. int process_statement_instance_func_interp_getargs (struct process_statement *ps, NCDValue *out_value)
  1450. {
  1451. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1452. NCDValue_InitList(out_value);
  1453. for (int i = 0; i < options.num_extra_args; i++) {
  1454. NCDValue arg;
  1455. if (!NCDValue_InitString(&arg, options.extra_args[i])) {
  1456. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitString failed");
  1457. goto fail1;
  1458. }
  1459. if (!NCDValue_ListAppend(out_value, arg)) {
  1460. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  1461. NCDValue_Free(&arg);
  1462. goto fail1;
  1463. }
  1464. }
  1465. return 1;
  1466. fail1:
  1467. NCDValue_Free(out_value);
  1468. return 0;
  1469. }
  1470. btime_t process_statement_instance_func_interp_getretrytime (struct process_statement *ps)
  1471. {
  1472. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1473. return options.retry_time;
  1474. }
  1475. void process_moduleprocess_func_event (struct process *p, int event)
  1476. {
  1477. ASSERT(p->module_process)
  1478. switch (event) {
  1479. case NCDMODULEPROCESS_INTERP_EVENT_CONTINUE: {
  1480. ASSERT(p->state == PSTATE_WAITING)
  1481. // set state working
  1482. p->state = PSTATE_WORKING;
  1483. // schedule work
  1484. process_schedule_work(p);
  1485. } break;
  1486. case NCDMODULEPROCESS_INTERP_EVENT_TERMINATE: {
  1487. ASSERT(p->state != PSTATE_TERMINATING)
  1488. process_log(p, BLOG_INFO, "process termination requested");
  1489. // start terminating
  1490. process_start_terminating(p);
  1491. } break;
  1492. default: ASSERT(0);
  1493. }
  1494. }
  1495. int process_moduleprocess_func_getobj (struct process *p, const char *name, NCDObject *out_object)
  1496. {
  1497. ASSERT(p->module_process)
  1498. return process_find_object(p, p->num_statements, name, out_object);
  1499. }