ncd.c 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389
  1. /**
  2. * @file ncd.c
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. #include <stdint.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include <stdlib.h>
  26. #include <misc/version.h>
  27. #include <misc/loggers_string.h>
  28. #include <misc/loglevel.h>
  29. #include <misc/offset.h>
  30. #include <misc/read_file.h>
  31. #include <misc/balloc.h>
  32. #include <misc/concat_strings.h>
  33. #include <misc/string_begins_with.h>
  34. #include <misc/parse_number.h>
  35. #include <structure/LinkedList2.h>
  36. #include <system/BLog.h>
  37. #include <system/BReactor.h>
  38. #include <system/BSignal.h>
  39. #include <system/BSocket.h>
  40. #include <process/BProcess.h>
  41. #include <ncdconfig/NCDConfigParser.h>
  42. #include <ncd/NCDModule.h>
  43. #include <ncd/modules/modules.h>
  44. #ifndef BADVPN_USE_WINAPI
  45. #include <system/BLog_syslog.h>
  46. #endif
  47. #include <ncd/ncd.h>
  48. #include <generated/blog_channel_ncd.h>
  49. #define LOGGER_STDOUT 1
  50. #define LOGGER_SYSLOG 2
  51. #define SSTATE_CHILD 1
  52. #define SSTATE_ADULT 2
  53. #define SSTATE_DYING 3
  54. #define SSTATE_FORGOTTEN 4
  55. struct statement {
  56. char *object_name;
  57. char *method_name;
  58. struct argument_elem *first_arg;
  59. char *name;
  60. };
  61. struct argument_elem {
  62. int is_var;
  63. union {
  64. char *var;
  65. NCDValue val;
  66. };
  67. struct argument_elem *next_arg;
  68. };
  69. struct process {
  70. NCDModuleProcess *module_process;
  71. NCDValue args;
  72. char *name;
  73. size_t num_statements;
  74. struct process_statement *statements;
  75. int terminating;
  76. size_t ap;
  77. size_t fp;
  78. BTimer wait_timer;
  79. BPending advance_job;
  80. BPending work_job;
  81. LinkedList2Node list_node; // node in processes
  82. };
  83. struct process_statement {
  84. struct process *p;
  85. size_t i;
  86. struct statement s;
  87. int state;
  88. char *type;
  89. int have_error;
  90. btime_t error_until;
  91. NCDModuleInst inst;
  92. NCDValue inst_args;
  93. };
  94. // command-line options
  95. struct {
  96. int help;
  97. int version;
  98. int logger;
  99. #ifndef BADVPN_USE_WINAPI
  100. char *logger_syslog_facility;
  101. char *logger_syslog_ident;
  102. #endif
  103. int loglevel;
  104. int loglevels[BLOG_NUM_CHANNELS];
  105. char *config_file;
  106. int retry_time;
  107. } options;
  108. // reactor
  109. BReactor ss;
  110. // are we terminating
  111. int terminating;
  112. // process manager
  113. BProcessManager manager;
  114. // config AST
  115. struct NCDConfig_interfaces *config_ast;
  116. // processes
  117. LinkedList2 processes;
  118. static void print_help (const char *name);
  119. static void print_version (void);
  120. static int parse_arguments (int argc, char *argv[]);
  121. static void signal_handler (void *unused);
  122. static const struct NCDModule * find_module (const char *name);
  123. static int statement_init (struct statement *s, struct NCDConfig_statements *conf);
  124. static void statement_free (struct statement *s);
  125. static void statement_free_args (struct statement *s);
  126. static int process_new (struct NCDConfig_interfaces *conf, NCDModuleProcess *module_process, NCDValue args);
  127. static void process_free (struct process *p);
  128. static void process_start_teminating (struct process *p);
  129. static void process_free_statements (struct process *p);
  130. static size_t process_rap (struct process *p);
  131. static void process_assert_pointers (struct process *p);
  132. static void process_log (struct process *p, int level, const char *fmt, ...);
  133. static void process_schedule_work (struct process *p);
  134. static void process_work_job_handler (struct process *p);
  135. static void process_advance_job_handler (struct process *p);
  136. static void process_wait_timer_handler (struct process *p);
  137. static struct process_statement * process_find_statement (struct process *p, size_t pos, const char *name);
  138. static int process_resolve_name (struct process *p, size_t pos, const char *name, struct process_statement **first_ps, const char **rest);
  139. static int process_resolve_variable (struct process *p, size_t pos, const char *varname, NCDValue *out);
  140. static struct process_statement * process_resolve_object (struct process *p, size_t pos, const char *objname);
  141. static void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...);
  142. static void process_statement_set_error (struct process_statement *ps);
  143. static void process_statement_instance_handler_event (struct process_statement *ps, int event);
  144. static int process_statement_instance_handler_getvar (struct process_statement *ps, const char *varname, NCDValue *out);
  145. static NCDModuleInst * process_statement_instance_handler_getobj (struct process_statement *ps, const char *objname);
  146. static int process_statement_instance_handler_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name, NCDValue args);
  147. static void process_statement_instance_handler_log (struct process_statement *ps);
  148. static void process_moduleprocess_handler_die (struct process *p);
  149. int main (int argc, char **argv)
  150. {
  151. if (argc <= 0) {
  152. return 1;
  153. }
  154. // parse command-line arguments
  155. if (!parse_arguments(argc, argv)) {
  156. fprintf(stderr, "Failed to parse arguments\n");
  157. print_help(argv[0]);
  158. goto fail0;
  159. }
  160. // handle --help and --version
  161. if (options.help) {
  162. print_version();
  163. print_help(argv[0]);
  164. return 0;
  165. }
  166. if (options.version) {
  167. print_version();
  168. return 0;
  169. }
  170. // initialize logger
  171. switch (options.logger) {
  172. case LOGGER_STDOUT:
  173. BLog_InitStdout();
  174. break;
  175. #ifndef BADVPN_USE_WINAPI
  176. case LOGGER_SYSLOG:
  177. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  178. fprintf(stderr, "Failed to initialize syslog logger\n");
  179. goto fail0;
  180. }
  181. break;
  182. #endif
  183. default:
  184. ASSERT(0);
  185. }
  186. // configure logger channels
  187. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  188. if (options.loglevels[i] >= 0) {
  189. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  190. }
  191. else if (options.loglevel >= 0) {
  192. BLog_SetChannelLoglevel(i, options.loglevel);
  193. }
  194. }
  195. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  196. // initialize sockets
  197. if (BSocket_GlobalInit() < 0) {
  198. BLog(BLOG_ERROR, "BSocket_GlobalInit failed");
  199. goto fail1;
  200. }
  201. // init time
  202. BTime_Init();
  203. // init reactor
  204. if (!BReactor_Init(&ss)) {
  205. BLog(BLOG_ERROR, "BReactor_Init failed");
  206. goto fail1;
  207. }
  208. // set not terminating
  209. terminating = 0;
  210. // init process manager
  211. if (!BProcessManager_Init(&manager, &ss)) {
  212. BLog(BLOG_ERROR, "BProcessManager_Init failed");
  213. goto fail1a;
  214. }
  215. // setup signal handler
  216. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  217. BLog(BLOG_ERROR, "BSignal_Init failed");
  218. goto fail2;
  219. }
  220. // read config file
  221. uint8_t *file;
  222. size_t file_len;
  223. if (!read_file(options.config_file, &file, &file_len)) {
  224. BLog(BLOG_ERROR, "failed to read config file");
  225. goto fail3;
  226. }
  227. // parse config file
  228. if (!NCDConfigParser_Parse((char *)file, file_len, &config_ast)) {
  229. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  230. free(file);
  231. goto fail3;
  232. }
  233. // fee config file memory
  234. free(file);
  235. // init module params
  236. struct NCDModuleInitParams params;
  237. params.reactor = &ss;
  238. params.manager = &manager;
  239. // init modules
  240. size_t num_inited_modules = 0;
  241. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  242. if ((*g)->func_globalinit && !(*g)->func_globalinit(params)) {
  243. BLog(BLOG_ERROR, "globalinit failed for some module");
  244. goto fail5;
  245. }
  246. num_inited_modules++;
  247. }
  248. // init processes list
  249. LinkedList2_Init(&processes);
  250. // init processes
  251. struct NCDConfig_interfaces *conf = config_ast;
  252. while (conf) {
  253. if (!conf->is_template) {
  254. NCDValue args;
  255. NCDValue_InitList(&args);
  256. if (!process_new(conf, NULL, args)) {
  257. NCDValue_Free(&args);
  258. }
  259. }
  260. conf = conf->next;
  261. }
  262. // enter event loop
  263. BLog(BLOG_NOTICE, "entering event loop");
  264. BReactor_Exec(&ss);
  265. ASSERT(LinkedList2_IsEmpty(&processes))
  266. fail5:
  267. // free modules
  268. while (num_inited_modules > 0) {
  269. const struct NCDModuleGroup **g = &ncd_modules[num_inited_modules - 1];
  270. if ((*g)->func_globalfree) {
  271. (*g)->func_globalfree();
  272. }
  273. num_inited_modules--;
  274. }
  275. // free configuration
  276. NCDConfig_free_interfaces(config_ast);
  277. fail3:
  278. // remove signal handler
  279. BSignal_Finish();
  280. fail2:
  281. // free process manager
  282. BProcessManager_Free(&manager);
  283. fail1a:
  284. // free reactor
  285. BReactor_Free(&ss);
  286. fail1:
  287. // free logger
  288. BLog(BLOG_NOTICE, "exiting");
  289. BLog_Free();
  290. fail0:
  291. // finish objects
  292. DebugObjectGlobal_Finish();
  293. return 1;
  294. }
  295. void print_help (const char *name)
  296. {
  297. printf(
  298. "Usage:\n"
  299. " %s\n"
  300. " [--help]\n"
  301. " [--version]\n"
  302. " [--logger <"LOGGERS_STRING">]\n"
  303. #ifndef BADVPN_USE_WINAPI
  304. " (logger=syslog?\n"
  305. " [--syslog-facility <string>]\n"
  306. " [--syslog-ident <string>]\n"
  307. " )\n"
  308. #endif
  309. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  310. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  311. " --config-file <file>\n"
  312. " [--retry-time <ms>]\n",
  313. name
  314. );
  315. }
  316. void print_version (void)
  317. {
  318. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  319. }
  320. int parse_arguments (int argc, char *argv[])
  321. {
  322. if (argc <= 0) {
  323. return 0;
  324. }
  325. options.help = 0;
  326. options.version = 0;
  327. options.logger = LOGGER_STDOUT;
  328. #ifndef BADVPN_USE_WINAPI
  329. options.logger_syslog_facility = "daemon";
  330. options.logger_syslog_ident = argv[0];
  331. #endif
  332. options.loglevel = -1;
  333. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  334. options.loglevels[i] = -1;
  335. }
  336. options.config_file = NULL;
  337. options.retry_time = DEFAULT_RETRY_TIME;
  338. for (int i = 1; i < argc; i++) {
  339. char *arg = argv[i];
  340. if (!strcmp(arg, "--help")) {
  341. options.help = 1;
  342. }
  343. else if (!strcmp(arg, "--version")) {
  344. options.version = 1;
  345. }
  346. else if (!strcmp(arg, "--logger")) {
  347. if (1 >= argc - i) {
  348. fprintf(stderr, "%s: requires an argument\n", arg);
  349. return 0;
  350. }
  351. char *arg2 = argv[i + 1];
  352. if (!strcmp(arg2, "stdout")) {
  353. options.logger = LOGGER_STDOUT;
  354. }
  355. #ifndef BADVPN_USE_WINAPI
  356. else if (!strcmp(arg2, "syslog")) {
  357. options.logger = LOGGER_SYSLOG;
  358. }
  359. #endif
  360. else {
  361. fprintf(stderr, "%s: wrong argument\n", arg);
  362. return 0;
  363. }
  364. i++;
  365. }
  366. #ifndef BADVPN_USE_WINAPI
  367. else if (!strcmp(arg, "--syslog-facility")) {
  368. if (1 >= argc - i) {
  369. fprintf(stderr, "%s: requires an argument\n", arg);
  370. return 0;
  371. }
  372. options.logger_syslog_facility = argv[i + 1];
  373. i++;
  374. }
  375. else if (!strcmp(arg, "--syslog-ident")) {
  376. if (1 >= argc - i) {
  377. fprintf(stderr, "%s: requires an argument\n", arg);
  378. return 0;
  379. }
  380. options.logger_syslog_ident = argv[i + 1];
  381. i++;
  382. }
  383. #endif
  384. else if (!strcmp(arg, "--loglevel")) {
  385. if (1 >= argc - i) {
  386. fprintf(stderr, "%s: requires an argument\n", arg);
  387. return 0;
  388. }
  389. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  390. fprintf(stderr, "%s: wrong argument\n", arg);
  391. return 0;
  392. }
  393. i++;
  394. }
  395. else if (!strcmp(arg, "--channel-loglevel")) {
  396. if (2 >= argc - i) {
  397. fprintf(stderr, "%s: requires two arguments\n", arg);
  398. return 0;
  399. }
  400. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  401. if (channel < 0) {
  402. fprintf(stderr, "%s: wrong channel argument\n", arg);
  403. return 0;
  404. }
  405. int loglevel = parse_loglevel(argv[i + 2]);
  406. if (loglevel < 0) {
  407. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  408. return 0;
  409. }
  410. options.loglevels[channel] = loglevel;
  411. i += 2;
  412. }
  413. else if (!strcmp(arg, "--config-file")) {
  414. if (1 >= argc - i) {
  415. fprintf(stderr, "%s: requires an argument\n", arg);
  416. return 0;
  417. }
  418. options.config_file = argv[i + 1];
  419. i++;
  420. }
  421. else if (!strcmp(arg, "--retry-time")) {
  422. if (1 >= argc - i) {
  423. fprintf(stderr, "%s: requires an argument\n", arg);
  424. return 0;
  425. }
  426. if ((options.retry_time = atoi(argv[i + 1])) < 0) {
  427. fprintf(stderr, "%s: wrong argument\n", arg);
  428. return 0;
  429. }
  430. i++;
  431. }
  432. else {
  433. fprintf(stderr, "unknown option: %s\n", arg);
  434. return 0;
  435. }
  436. }
  437. if (options.help || options.version) {
  438. return 1;
  439. }
  440. if (!options.config_file) {
  441. fprintf(stderr, "--config-file is required\n");
  442. return 0;
  443. }
  444. return 1;
  445. }
  446. void signal_handler (void *unused)
  447. {
  448. BLog(BLOG_NOTICE, "termination requested");
  449. if (terminating) {
  450. return;
  451. }
  452. terminating = 1;
  453. if (LinkedList2_IsEmpty(&processes)) {
  454. BReactor_Quit(&ss, 1);
  455. return;
  456. }
  457. // start terminating all processes
  458. LinkedList2Iterator it;
  459. LinkedList2Iterator_InitForward(&it, &processes);
  460. LinkedList2Node *n;
  461. while (n = LinkedList2Iterator_Next(&it)) {
  462. struct process *p = UPPER_OBJECT(n, struct process, list_node);
  463. process_start_teminating(p);
  464. }
  465. }
  466. const struct NCDModule * find_module (const char *name)
  467. {
  468. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  469. for (const struct NCDModule *m = (*g)->modules; m->type; m++) {
  470. if (!strcmp(m->type, name)) {
  471. return m;
  472. }
  473. }
  474. }
  475. return NULL;
  476. }
  477. int statement_init (struct statement *s, struct NCDConfig_statements *conf)
  478. {
  479. s->object_name = NULL;
  480. s->method_name = NULL;
  481. s->name = NULL;
  482. s->first_arg = NULL;
  483. // set object name
  484. if (conf->objname) {
  485. if (!(s->object_name = NCDConfig_concat_strings(conf->objname))) {
  486. BLog(BLOG_ERROR, "NCDConfig_concat_strings failed");
  487. goto fail;
  488. }
  489. }
  490. // set method name
  491. if (!(s->method_name = NCDConfig_concat_strings(conf->names))) {
  492. BLog(BLOG_ERROR, "NCDConfig_concat_strings failed");
  493. goto fail;
  494. }
  495. // init name
  496. if (conf->name) {
  497. if (!(s->name = strdup(conf->name))) {
  498. BLog(BLOG_ERROR, "strdup failed");
  499. goto fail;
  500. }
  501. }
  502. // init arguments
  503. struct argument_elem **prevptr = &s->first_arg;
  504. struct NCDConfig_arguments *arg = conf->args;
  505. while (arg) {
  506. struct argument_elem *e = malloc(sizeof(*e));
  507. if (!e) {
  508. BLog(BLOG_ERROR, "malloc failed");
  509. goto loop_fail0;
  510. }
  511. switch (arg->type) {
  512. case NCDCONFIG_ARG_STRING: {
  513. if (!NCDValue_InitString(&e->val, arg->string)) {
  514. BLog(BLOG_ERROR, "NCDValue_InitString failed");
  515. goto loop_fail1;
  516. }
  517. e->is_var = 0;
  518. } break;
  519. case NCDCONFIG_ARG_VAR: {
  520. if (!(e->var = NCDConfig_concat_strings(arg->var))) {
  521. BLog(BLOG_ERROR, "NCDConfig_concat_strings failed");
  522. goto loop_fail1;
  523. }
  524. e->is_var = 1;
  525. } break;
  526. default:
  527. ASSERT(0);
  528. }
  529. *prevptr = e;
  530. e->next_arg = NULL;
  531. prevptr = &e->next_arg;
  532. arg = arg->next;
  533. continue;
  534. loop_fail1:
  535. free(e);
  536. loop_fail0:
  537. goto fail;
  538. }
  539. return 1;
  540. fail:
  541. statement_free_args(s);
  542. free(s->name);
  543. free(s->method_name);
  544. free(s->object_name);
  545. return 0;
  546. }
  547. void statement_free (struct statement *s)
  548. {
  549. // free arguments
  550. statement_free_args(s);
  551. // free names
  552. free(s->name);
  553. free(s->method_name);
  554. free(s->object_name);
  555. }
  556. void statement_free_args (struct statement *s)
  557. {
  558. struct argument_elem *e = s->first_arg;
  559. while (e) {
  560. if (e->is_var) {
  561. free(e->var);
  562. } else {
  563. NCDValue_Free(&e->val);
  564. }
  565. struct argument_elem *n = e->next_arg;
  566. free(e);
  567. e = n;
  568. }
  569. }
  570. int process_new (struct NCDConfig_interfaces *conf, NCDModuleProcess *module_process, NCDValue args)
  571. {
  572. ASSERT(NCDValue_Type(&args) == NCDVALUE_LIST)
  573. // allocate strucure
  574. struct process *p = malloc(sizeof(*p));
  575. if (!p) {
  576. BLog(BLOG_ERROR, "malloc failed");
  577. goto fail0;
  578. }
  579. // set module process
  580. p->module_process = module_process;
  581. // set module process handlers
  582. if (p->module_process) {
  583. NCDModuleProcess_Interp_SetHandlers(p->module_process, p, (NCDModuleProcess_interp_handler_die)process_moduleprocess_handler_die);
  584. }
  585. // set arguments
  586. p->args = args;
  587. // init name
  588. if (!(p->name = strdup(conf->name))) {
  589. BLog(BLOG_ERROR, "strdup failed");
  590. goto fail1;
  591. }
  592. // count statements
  593. size_t num_st = 0;
  594. struct NCDConfig_statements *st = conf->statements;
  595. while (st) {
  596. if (num_st == SIZE_MAX) {
  597. BLog(BLOG_ERROR, "too many statements");
  598. goto fail2;
  599. }
  600. num_st++;
  601. st = st->next;
  602. }
  603. // allocate statements array
  604. if (!(p->statements = BAllocArray(num_st, sizeof(p->statements[0])))) {
  605. goto fail2;
  606. }
  607. p->num_statements = 0;
  608. // init statements
  609. st = conf->statements;
  610. while (st) {
  611. struct process_statement *ps = &p->statements[p->num_statements];
  612. ps->p = p;
  613. ps->i = p->num_statements;
  614. if (!statement_init(&ps->s, st)) {
  615. goto fail3;
  616. }
  617. ps->state = SSTATE_FORGOTTEN;
  618. ps->have_error = 0;
  619. p->num_statements++;
  620. st = st->next;
  621. }
  622. // set not terminating
  623. p->terminating = 0;
  624. // set AP=0
  625. p->ap = 0;
  626. // set FP=0
  627. p->fp = 0;
  628. // init timer
  629. BTimer_Init(&p->wait_timer, 0, (BTimer_handler)process_wait_timer_handler, p);
  630. // init advance job
  631. BPending_Init(&p->advance_job, BReactor_PendingGroup(&ss), (BPending_handler)process_advance_job_handler, p);
  632. // init work job
  633. BPending_Init(&p->work_job, BReactor_PendingGroup(&ss), (BPending_handler)process_work_job_handler, p);
  634. // insert to processes list
  635. LinkedList2_Append(&processes, &p->list_node);
  636. // schedule work
  637. BPending_Set(&p->work_job);
  638. return 1;
  639. fail3:
  640. process_free_statements(p);
  641. fail2:
  642. free(p->name);
  643. fail1:
  644. free(p);
  645. fail0:
  646. BLog(BLOG_ERROR, "failed to initialize process %s", conf->name);
  647. return 0;
  648. }
  649. void process_free (struct process *p)
  650. {
  651. ASSERT(p->ap == 0)
  652. ASSERT(p->fp == 0)
  653. // inform module process that the process is dead
  654. if (p->module_process) {
  655. NCDModuleProcess_Interp_Dead(p->module_process);
  656. }
  657. // remove from processes list
  658. LinkedList2_Remove(&processes, &p->list_node);
  659. // free work job
  660. BPending_Free(&p->work_job);
  661. // free advance job
  662. BPending_Free(&p->advance_job);
  663. // free timer
  664. BReactor_RemoveTimer(&ss, &p->wait_timer);
  665. // free statements
  666. process_free_statements(p);
  667. // free name
  668. free(p->name);
  669. // free arguments
  670. NCDValue_Free(&p->args);
  671. // free strucure
  672. free(p);
  673. }
  674. void process_start_teminating (struct process *p)
  675. {
  676. if (p->terminating) {
  677. return;
  678. }
  679. // set terminating
  680. p->terminating = 1;
  681. // schedule work
  682. process_schedule_work(p);
  683. }
  684. size_t process_rap (struct process *p)
  685. {
  686. if (p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD) {
  687. return (p->ap - 1);
  688. } else {
  689. return p->ap;
  690. }
  691. }
  692. void process_free_statements (struct process *p)
  693. {
  694. // free statments
  695. while (p->num_statements > 0) {
  696. statement_free(&p->statements[p->num_statements - 1].s);
  697. p->num_statements--;
  698. }
  699. // free stataments array
  700. free(p->statements);
  701. }
  702. void process_assert_pointers (struct process *p)
  703. {
  704. ASSERT(p->ap <= p->num_statements)
  705. ASSERT(p->fp >= p->ap)
  706. ASSERT(p->fp <= p->num_statements)
  707. // check AP
  708. for (size_t i = 0; i < p->ap; i++) {
  709. if (i == p->ap - 1) {
  710. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  711. } else {
  712. ASSERT(p->statements[i].state == SSTATE_ADULT)
  713. }
  714. }
  715. // check FP
  716. size_t fp = p->num_statements;
  717. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  718. fp--;
  719. }
  720. ASSERT(p->fp == fp)
  721. }
  722. void process_log (struct process *p, int level, const char *fmt, ...)
  723. {
  724. va_list vl;
  725. va_start(vl, fmt);
  726. BLog_Append("process %s: ", p->name);
  727. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  728. va_end(vl);
  729. }
  730. void process_schedule_work (struct process *p)
  731. {
  732. process_assert_pointers(p);
  733. // stop timer
  734. BReactor_RemoveTimer(&ss, &p->wait_timer);
  735. // stop advance job
  736. BPending_Unset(&p->advance_job);
  737. // schedule work
  738. BPending_Set(&p->work_job);
  739. }
  740. void process_work_job_handler (struct process *p)
  741. {
  742. process_assert_pointers(p);
  743. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  744. ASSERT(!BPending_IsSet(&p->advance_job))
  745. if (p->terminating) {
  746. if (p->fp == 0) {
  747. // finished retreating
  748. process_free(p);
  749. // if program is terminating amd there are no more processes, exit program
  750. if (terminating && LinkedList2_IsEmpty(&processes)) {
  751. BReactor_Quit(&ss, 1);
  752. }
  753. } else {
  754. // order the last living statement to die, if needed
  755. struct process_statement *ps = &p->statements[p->fp - 1];
  756. ASSERT(ps->state != SSTATE_FORGOTTEN)
  757. if (ps->state != SSTATE_DYING) {
  758. process_statement_log(ps, BLOG_INFO, "killing");
  759. // order it to die
  760. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_DIE);
  761. // set statement state DYING
  762. ps->state = SSTATE_DYING;
  763. // update AP
  764. if (p->ap > ps->i) {
  765. p->ap = ps->i;
  766. }
  767. }
  768. process_assert_pointers(p);
  769. }
  770. return;
  771. }
  772. if (p->ap == p->fp) {
  773. if (p->ap == process_rap(p)) {
  774. if (p->ap == p->num_statements) {
  775. // all statements are up
  776. process_log(p, BLOG_INFO, "victory");
  777. } else {
  778. struct process_statement *ps = &p->statements[p->ap];
  779. ASSERT(ps->state == SSTATE_FORGOTTEN)
  780. // clear expired error
  781. if (ps->have_error && ps->error_until <= btime_gettime()) {
  782. ps->have_error = 0;
  783. }
  784. if (ps->have_error) {
  785. // next statement has error, wait
  786. process_statement_log(ps, BLOG_INFO, "waiting after error");
  787. BReactor_SetTimerAbsolute(&ss, &p->wait_timer, ps->error_until);
  788. } else {
  789. // schedule advance
  790. BPending_Set(&p->advance_job);
  791. }
  792. }
  793. } else {
  794. ASSERT(p->ap > 0)
  795. ASSERT(p->ap <= p->num_statements)
  796. struct process_statement *ps = &p->statements[p->ap - 1];
  797. ASSERT(ps->state == SSTATE_CHILD)
  798. process_statement_log(ps, BLOG_INFO, "clean");
  799. // report clean
  800. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_CLEAN);
  801. }
  802. } else {
  803. // order the last living statement to die, if needed
  804. struct process_statement *ps = &p->statements[p->fp - 1];
  805. if (ps->state != SSTATE_DYING) {
  806. process_statement_log(ps, BLOG_INFO, "killing");
  807. // order it to die
  808. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_DIE);
  809. // set statement state DYING
  810. ps->state = SSTATE_DYING;
  811. }
  812. }
  813. process_assert_pointers(p);
  814. }
  815. void process_advance_job_handler (struct process *p)
  816. {
  817. process_assert_pointers(p);
  818. ASSERT(p->ap == p->fp)
  819. ASSERT(p->ap == process_rap(p))
  820. ASSERT(p->ap < p->num_statements)
  821. ASSERT(!p->statements[p->ap].have_error)
  822. ASSERT(!BPending_IsSet(&p->work_job))
  823. ASSERT(!BTimer_IsRunning(&p->wait_timer))
  824. ASSERT(!p->terminating)
  825. struct process_statement *ps = &p->statements[p->ap];
  826. ASSERT(ps->state == SSTATE_FORGOTTEN)
  827. process_statement_log(ps, BLOG_INFO, "initializing");
  828. NCDModuleInst *method_object = NULL;
  829. // construct type
  830. if (!ps->s.object_name) {
  831. // this is a function_call(); type is "function_call"
  832. if (!(ps->type = strdup(ps->s.method_name))) {
  833. process_statement_log(ps, BLOG_ERROR, "strdup failed");
  834. goto fail0;
  835. }
  836. } else {
  837. // this is a some.object.somewhere->method_call(); type is "typeof(some.object.somewhere)::method_call"
  838. // resolve object
  839. struct process_statement *obj_ps = process_resolve_object(p, p->ap, ps->s.object_name);
  840. if (!obj_ps) {
  841. process_statement_log(ps, BLOG_ERROR, "failed to resolve object %s for method call", ps->s.object_name);
  842. goto fail0;
  843. }
  844. ASSERT(obj_ps->state == SSTATE_ADULT)
  845. // build type string
  846. if (!(ps->type = concat_strings(3, obj_ps->type, "::", ps->s.method_name))) {
  847. process_statement_log(ps, BLOG_ERROR, "concat_strings failed");
  848. goto fail0;
  849. }
  850. method_object = &obj_ps->inst;
  851. }
  852. // find module to instantiate
  853. const struct NCDModule *module = find_module(ps->type);
  854. if (!module) {
  855. process_statement_log(ps, BLOG_ERROR, "failed to find module: %s", ps->type);
  856. goto fail1;
  857. }
  858. // init arguments list
  859. NCDValue_InitList(&ps->inst_args);
  860. // build arguments
  861. struct argument_elem *arg = ps->s.first_arg;
  862. while (arg) {
  863. // resolve argument
  864. NCDValue v;
  865. if (arg->is_var) {
  866. if (!process_resolve_variable(p, p->ap, arg->var, &v)) {
  867. process_statement_log(ps, BLOG_ERROR, "failed to resolve variable");
  868. goto fail2;
  869. }
  870. } else {
  871. if (!NCDValue_InitCopy(&v, &arg->val)) {
  872. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitCopy failed");
  873. goto fail2;
  874. }
  875. }
  876. // move to list
  877. if (!NCDValue_ListAppend(&ps->inst_args, v)) {
  878. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  879. NCDValue_Free(&v);
  880. goto fail2;
  881. }
  882. arg = arg->next_arg;
  883. }
  884. // initialize module instance
  885. NCDModuleInst_Init(
  886. &ps->inst, module, method_object, &ps->inst_args, &ss, &manager, ps,
  887. (NCDModule_handler_event)process_statement_instance_handler_event,
  888. (NCDModule_handler_getvar)process_statement_instance_handler_getvar,
  889. (NCDModule_handler_getobj)process_statement_instance_handler_getobj,
  890. (NCDModule_handler_initprocess)process_statement_instance_handler_initprocess,
  891. (NCDModule_handler_log)process_statement_instance_handler_log
  892. );
  893. // set statement state CHILD
  894. ps->state = SSTATE_CHILD;
  895. // increment AP
  896. p->ap++;
  897. // increment FP
  898. p->fp++;
  899. process_assert_pointers(p);
  900. return;
  901. fail2:
  902. NCDValue_Free(&ps->inst_args);
  903. fail1:
  904. free(ps->type);
  905. fail0:
  906. // mark error
  907. process_statement_set_error(ps);
  908. // schedule work to start the timer
  909. BPending_Set(&p->work_job);
  910. }
  911. void process_wait_timer_handler (struct process *p)
  912. {
  913. process_assert_pointers(p);
  914. ASSERT(p->ap == p->fp)
  915. ASSERT(p->ap == process_rap(p))
  916. ASSERT(p->ap < p->num_statements)
  917. ASSERT(p->statements[p->ap].have_error)
  918. ASSERT(!BPending_IsSet(&p->work_job))
  919. ASSERT(!BPending_IsSet(&p->advance_job))
  920. ASSERT(!p->terminating)
  921. process_log(p, BLOG_INFO, "retrying");
  922. // clear error
  923. p->statements[p->ap].have_error = 0;
  924. // schedule work
  925. BPending_Set(&p->work_job);
  926. }
  927. struct process_statement * process_find_statement (struct process *p, size_t pos, const char *name)
  928. {
  929. process_assert_pointers(p);
  930. ASSERT(pos >= 0)
  931. ASSERT(pos <= process_rap(p))
  932. for (size_t i = pos; i > 0; i--) {
  933. struct process_statement *ps = &p->statements[i - 1];
  934. if (ps->s.name && !strcmp(ps->s.name, name)) {
  935. return ps;
  936. }
  937. }
  938. return NULL;
  939. }
  940. int process_resolve_name (struct process *p, size_t pos, const char *name, struct process_statement **first_ps, const char **rest)
  941. {
  942. process_assert_pointers(p);
  943. ASSERT(pos >= 0)
  944. ASSERT(pos <= process_rap(p))
  945. ASSERT(name)
  946. char *dot = strstr(name, ".");
  947. if (!dot) {
  948. *first_ps = process_find_statement(p, pos, name);
  949. *rest = NULL;
  950. } else {
  951. // copy modname and terminate
  952. char *modname = malloc((dot - name) + 1);
  953. if (!modname) {
  954. process_log(p, BLOG_ERROR, "malloc failed");
  955. return 0;
  956. }
  957. memcpy(modname, name, dot - name);
  958. modname[dot - name] = '\0';
  959. *first_ps = process_find_statement(p, pos, modname);
  960. *rest = dot + 1;
  961. free(modname);
  962. }
  963. return 1;
  964. }
  965. int process_resolve_variable (struct process *p, size_t pos, const char *varname, NCDValue *out)
  966. {
  967. process_assert_pointers(p);
  968. ASSERT(pos >= 0)
  969. ASSERT(pos <= process_rap(p))
  970. ASSERT(varname)
  971. // find referred statement and remaining name
  972. struct process_statement *rps;
  973. const char *rest;
  974. if (!process_resolve_name(p, pos, varname, &rps, &rest)) {
  975. return 0;
  976. }
  977. if (!rps) {
  978. // handle _args
  979. if (!strcmp(varname, "_args")) {
  980. if (!NCDValue_InitCopy(out, &p->args)) {
  981. process_log(p, BLOG_ERROR, "NCDValue_InitCopy failed");
  982. return 0;
  983. }
  984. return 1;
  985. }
  986. // handle _argN
  987. size_t len;
  988. uintmax_t n;
  989. if ((len = string_begins_with(varname, "_arg")) && parse_unsigned_integer(varname + len, &n) && n < NCDValue_ListCount(&p->args)) {
  990. if (!NCDValue_InitCopy(out, NCDValue_ListGet(&p->args, n))) {
  991. process_log(p, BLOG_ERROR, "NCDValue_InitCopy failed");
  992. return 0;
  993. }
  994. return 1;
  995. }
  996. process_log(p, BLOG_ERROR, "unknown statement name in variable: %s", varname);
  997. return 0;
  998. }
  999. ASSERT(rps->state == SSTATE_ADULT)
  1000. // resolve variable in referred statement
  1001. if (!NCDModuleInst_GetVar(&rps->inst, (rest ? rest : ""), out)) {
  1002. process_log(p, BLOG_ERROR, "referred module failed to resolve variable: %s", varname);
  1003. return 0;
  1004. }
  1005. return 1;
  1006. }
  1007. struct process_statement * process_resolve_object (struct process *p, size_t pos, const char *objname)
  1008. {
  1009. process_assert_pointers(p);
  1010. ASSERT(pos >= 0)
  1011. ASSERT(pos <= process_rap(p))
  1012. ASSERT(objname)
  1013. // find referred statement and remaining name
  1014. struct process_statement *rps;
  1015. const char *rest;
  1016. if (!process_resolve_name(p, pos, objname, &rps, &rest)) {
  1017. return NULL;
  1018. }
  1019. if (!rps) {
  1020. process_log(p, BLOG_ERROR, "unknown statement name in object: %s", objname);
  1021. return NULL;
  1022. }
  1023. ASSERT(rps->state == SSTATE_ADULT)
  1024. if (!rest) {
  1025. // this is the target
  1026. return rps;
  1027. }
  1028. // resolve object in referred statement
  1029. NCDModuleInst *inst = NCDModuleInst_GetObj(&rps->inst, rest);
  1030. if (!inst) {
  1031. process_log(p, BLOG_ERROR, "referred module failed to resolve object: %s", objname);
  1032. return NULL;
  1033. }
  1034. struct process_statement *res_ps = UPPER_OBJECT(inst, struct process_statement, inst);
  1035. ASSERT(res_ps->state == SSTATE_ADULT)
  1036. return res_ps;
  1037. }
  1038. void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...)
  1039. {
  1040. va_list vl;
  1041. va_start(vl, fmt);
  1042. BLog_Append("process %s: statement %zu: ", ps->p->name, ps->i);
  1043. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  1044. va_end(vl);
  1045. }
  1046. void process_statement_set_error (struct process_statement *ps)
  1047. {
  1048. ASSERT(ps->state == SSTATE_FORGOTTEN)
  1049. ps->have_error = 1;
  1050. ps->error_until = btime_add(btime_gettime(), options.retry_time);
  1051. }
  1052. void process_statement_instance_handler_event (struct process_statement *ps, int event)
  1053. {
  1054. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  1055. struct process *p = ps->p;
  1056. process_assert_pointers(p);
  1057. // schedule work
  1058. process_schedule_work(p);
  1059. switch (event) {
  1060. case NCDMODULE_EVENT_UP: {
  1061. ASSERT(ps->state == SSTATE_CHILD)
  1062. process_statement_log(ps, BLOG_INFO, "up");
  1063. // set state ADULT
  1064. ps->state = SSTATE_ADULT;
  1065. } break;
  1066. case NCDMODULE_EVENT_DOWN: {
  1067. ASSERT(ps->state == SSTATE_ADULT)
  1068. process_statement_log(ps, BLOG_INFO, "down");
  1069. // set state CHILD
  1070. ps->state = SSTATE_CHILD;
  1071. // update AP
  1072. if (p->ap > ps->i + 1) {
  1073. p->ap = ps->i + 1;
  1074. }
  1075. } break;
  1076. case NCDMODULE_EVENT_DEAD: {
  1077. int is_error = NCDModuleInst_HaveError(&ps->inst);
  1078. if (is_error) {
  1079. process_statement_log(ps, BLOG_ERROR, "died with error");
  1080. } else {
  1081. process_statement_log(ps, BLOG_INFO, "died");
  1082. }
  1083. // free instance
  1084. NCDModuleInst_Free(&ps->inst);
  1085. // free instance arguments
  1086. NCDValue_Free(&ps->inst_args);
  1087. // free type
  1088. free(ps->type);
  1089. // set state FORGOTTEN
  1090. ps->state = SSTATE_FORGOTTEN;
  1091. // set error
  1092. if (is_error) {
  1093. process_statement_set_error(ps);
  1094. }
  1095. // update AP
  1096. if (p->ap > ps->i) {
  1097. p->ap = ps->i;
  1098. }
  1099. // update FP
  1100. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  1101. p->fp--;
  1102. }
  1103. } break;
  1104. }
  1105. }
  1106. int process_statement_instance_handler_getvar (struct process_statement *ps, const char *varname, NCDValue *out)
  1107. {
  1108. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1109. if (ps->i > process_rap(ps->p)) {
  1110. process_statement_log(ps, BLOG_ERROR, "tried to resolve variable %s but it's dirty", varname);
  1111. return 0;
  1112. }
  1113. return process_resolve_variable(ps->p, ps->i, varname, out);
  1114. }
  1115. NCDModuleInst * process_statement_instance_handler_getobj (struct process_statement *ps, const char *objname)
  1116. {
  1117. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1118. if (ps->i > process_rap(ps->p)) {
  1119. process_statement_log(ps, BLOG_ERROR, "tried to resolve object %s but it's dirty", objname);
  1120. return 0;
  1121. }
  1122. struct process_statement *rps = process_resolve_object(ps->p, ps->i, objname);
  1123. if (!rps) {
  1124. return NULL;
  1125. }
  1126. return &rps->inst;
  1127. }
  1128. int process_statement_instance_handler_initprocess (struct process_statement *ps, NCDModuleProcess *mp, const char *template_name, NCDValue args)
  1129. {
  1130. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1131. ASSERT(NCDValue_Type(&args) == NCDVALUE_LIST)
  1132. // find template
  1133. struct NCDConfig_interfaces *conf = config_ast;
  1134. while (conf) {
  1135. if (conf->is_template && !strcmp(conf->name, template_name)) {
  1136. break;
  1137. }
  1138. conf = conf->next;
  1139. }
  1140. if (!conf) {
  1141. process_statement_log(ps, BLOG_ERROR, "no template named %s", template_name);
  1142. return 0;
  1143. }
  1144. // create process
  1145. if (!process_new(conf, mp, args)) {
  1146. process_statement_log(ps, BLOG_ERROR, "failed to create process from template %s", template_name);
  1147. return 0;
  1148. }
  1149. process_statement_log(ps, BLOG_INFO, "created process from template %s", template_name);
  1150. return 1;
  1151. }
  1152. void process_statement_instance_handler_log (struct process_statement *ps)
  1153. {
  1154. ASSERT(ps->state != SSTATE_FORGOTTEN)
  1155. BLog_Append("process %s: statement %zu: module: ", ps->p->name, ps->i);
  1156. }
  1157. void process_moduleprocess_handler_die (struct process *p)
  1158. {
  1159. process_log(p, BLOG_INFO, "process termination requested");
  1160. process_start_teminating(p);
  1161. }