ncd.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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 <stddef.h>
  25. #include <string.h>
  26. #include <stdlib.h>
  27. #include <misc/version.h>
  28. #include <misc/loggers_string.h>
  29. #include <misc/loglevel.h>
  30. #include <misc/offset.h>
  31. #include <misc/read_file.h>
  32. #include <misc/balloc.h>
  33. #include <structure/LinkedList2.h>
  34. #include <system/BLog.h>
  35. #include <system/BReactor.h>
  36. #include <system/BProcess.h>
  37. #include <system/BSignal.h>
  38. #include <system/BSocket.h>
  39. #include <ncdconfig/NCDConfigParser.h>
  40. #include <ncd/NCDModule.h>
  41. #include <ncd/modules/modules.h>
  42. #ifndef BADVPN_USE_WINAPI
  43. #include <system/BLog_syslog.h>
  44. #endif
  45. #include <ncd/ncd.h>
  46. #include <generated/blog_channel_ncd.h>
  47. #define LOGGER_STDOUT 1
  48. #define LOGGER_SYSLOG 2
  49. #define SSTATE_CHILD 1
  50. #define SSTATE_ADULT 2
  51. #define SSTATE_DYING 3
  52. #define SSTATE_FORGOTTEN 4
  53. struct statement {
  54. const struct NCDModule *module;
  55. struct argument_elem *first_arg;
  56. char *name;
  57. };
  58. struct argument_elem {
  59. int is_var;
  60. union {
  61. struct {
  62. char *modname;
  63. char *varname;
  64. } var;
  65. NCDValue val;
  66. };
  67. struct argument_elem *next_arg;
  68. };
  69. struct process {
  70. char *name;
  71. size_t num_statements;
  72. struct process_statement *statements;
  73. size_t ap;
  74. size_t fp;
  75. BTimer wait_timer;
  76. BPending advance_job;
  77. LinkedList2Node list_node; // node in processes
  78. };
  79. struct process_statement {
  80. struct process *p;
  81. size_t i;
  82. struct statement s;
  83. int state;
  84. int have_error;
  85. btime_t error_until;
  86. NCDModuleInst inst;
  87. NCDValue inst_args;
  88. char logprefix[50];
  89. };
  90. // command-line options
  91. struct {
  92. int help;
  93. int version;
  94. int logger;
  95. #ifndef BADVPN_USE_WINAPI
  96. char *logger_syslog_facility;
  97. char *logger_syslog_ident;
  98. #endif
  99. int loglevel;
  100. int loglevels[BLOG_NUM_CHANNELS];
  101. char *config_file;
  102. } options;
  103. // reactor
  104. BReactor ss;
  105. // are we terminating
  106. int terminating;
  107. // process manager
  108. BProcessManager manager;
  109. // configuration
  110. struct NCDConfig_interfaces *configuration;
  111. // processes
  112. LinkedList2 processes;
  113. // job for initializing processes
  114. BPending init_job;
  115. // next process for init job
  116. struct NCDConfig_interfaces *init_next;
  117. // job for initiating shutdown of processes
  118. BPending free_job;
  119. // process iterator for free job
  120. LinkedList2Iterator free_it;
  121. static void terminate (void);
  122. static void print_help (const char *name);
  123. static void print_version (void);
  124. static int parse_arguments (int argc, char *argv[]);
  125. static void signal_handler (void *unused);
  126. static const struct NCDModule * find_module (const char *name);
  127. static int statement_init (struct statement *s, struct NCDConfig_statements *conf);
  128. static void statement_free (struct statement *s);
  129. static void statement_free_args (struct statement *s);
  130. static int process_new (struct NCDConfig_interfaces *conf);
  131. static void process_free (struct process *p);
  132. static void process_free_statements (struct process *p);
  133. static void process_assert_pointers (struct process *p);
  134. static void process_log (struct process *p, int level, const char *fmt, ...);
  135. static void process_work (struct process *p);
  136. static void process_advance_job_handler (struct process *p);
  137. static void process_advance (struct process *p);
  138. static void process_wait (struct process *p);
  139. static void process_wait_timer_handler (struct process *p);
  140. static void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...);
  141. static void process_statement_set_error (struct process_statement *ps);
  142. static void process_statement_instance_handler_event (struct process_statement *ps, int event);
  143. static void process_statement_instance_handler_died (struct process_statement *ps, int is_error);
  144. static void init_job_handler (void *unused);
  145. static void free_job_handler (void *unused);
  146. int main (int argc, char **argv)
  147. {
  148. if (argc <= 0) {
  149. return 1;
  150. }
  151. // parse command-line arguments
  152. if (!parse_arguments(argc, argv)) {
  153. fprintf(stderr, "Failed to parse arguments\n");
  154. print_help(argv[0]);
  155. goto fail0;
  156. }
  157. // handle --help and --version
  158. if (options.help) {
  159. print_version();
  160. print_help(argv[0]);
  161. return 0;
  162. }
  163. if (options.version) {
  164. print_version();
  165. return 0;
  166. }
  167. // initialize logger
  168. switch (options.logger) {
  169. case LOGGER_STDOUT:
  170. BLog_InitStdout();
  171. break;
  172. #ifndef BADVPN_USE_WINAPI
  173. case LOGGER_SYSLOG:
  174. if (!BLog_InitSyslog(options.logger_syslog_ident, options.logger_syslog_facility)) {
  175. fprintf(stderr, "Failed to initialize syslog logger\n");
  176. goto fail0;
  177. }
  178. break;
  179. #endif
  180. default:
  181. ASSERT(0);
  182. }
  183. // configure logger channels
  184. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  185. if (options.loglevels[i] >= 0) {
  186. BLog_SetChannelLoglevel(i, options.loglevels[i]);
  187. }
  188. else if (options.loglevel >= 0) {
  189. BLog_SetChannelLoglevel(i, options.loglevel);
  190. }
  191. }
  192. BLog(BLOG_NOTICE, "initializing "GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION);
  193. // initialize sockets
  194. if (BSocket_GlobalInit() < 0) {
  195. BLog(BLOG_ERROR, "BSocket_GlobalInit failed");
  196. goto fail1;
  197. }
  198. // init time
  199. BTime_Init();
  200. // init reactor
  201. if (!BReactor_Init(&ss)) {
  202. BLog(BLOG_ERROR, "BReactor_Init failed");
  203. goto fail1;
  204. }
  205. // set not terminating
  206. terminating = 0;
  207. // init process manager
  208. if (!BProcessManager_Init(&manager, &ss)) {
  209. BLog(BLOG_ERROR, "BProcessManager_Init failed");
  210. goto fail1a;
  211. }
  212. // setup signal handler
  213. if (!BSignal_Init(&ss, signal_handler, NULL)) {
  214. BLog(BLOG_ERROR, "BSignal_Init failed");
  215. goto fail2;
  216. }
  217. // read config file
  218. uint8_t *file;
  219. size_t file_len;
  220. if (!read_file(options.config_file, &file, &file_len)) {
  221. BLog(BLOG_ERROR, "failed to read config file");
  222. goto fail3;
  223. }
  224. // parse config file
  225. if (!NCDConfigParser_Parse((char *)file, file_len, &configuration)) {
  226. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  227. free(file);
  228. goto fail3;
  229. }
  230. // fee config file memory
  231. free(file);
  232. // init modules
  233. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  234. if ((*g)->func_globalinit && !(*g)->func_globalinit()) {
  235. BLog(BLOG_ERROR, "globalinit failed for some module");
  236. goto fail5;
  237. }
  238. }
  239. // init processes list
  240. LinkedList2_Init(&processes);
  241. // init init job
  242. BPending_Init(&init_job, BReactor_PendingGroup(&ss), init_job_handler, NULL);
  243. // init free job
  244. BPending_Init(&free_job, BReactor_PendingGroup(&ss), free_job_handler, NULL);
  245. // start initializing processes
  246. init_next = configuration;
  247. BPending_Set(&init_job);
  248. // enter event loop
  249. BLog(BLOG_NOTICE, "entering event loop");
  250. BReactor_Exec(&ss);
  251. // free processes
  252. LinkedList2Node *n;
  253. while (n = LinkedList2_GetFirst(&processes)) {
  254. struct process *p = UPPER_OBJECT(n, struct process, list_node);
  255. process_free(p);
  256. }
  257. // free free job
  258. BPending_Free(&free_job);
  259. // free init job
  260. BPending_Free(&init_job);
  261. fail5:
  262. // free configuration
  263. NCDConfig_free_interfaces(configuration);
  264. fail3:
  265. // remove signal handler
  266. BSignal_Finish();
  267. fail2:
  268. // free process manager
  269. BProcessManager_Free(&manager);
  270. fail1a:
  271. // free reactor
  272. BReactor_Free(&ss);
  273. fail1:
  274. // free logger
  275. BLog(BLOG_NOTICE, "exiting");
  276. BLog_Free();
  277. fail0:
  278. // finish objects
  279. DebugObjectGlobal_Finish();
  280. return 1;
  281. }
  282. void terminate (void)
  283. {
  284. ASSERT(!terminating)
  285. BLog(BLOG_NOTICE, "tearing down");
  286. terminating = 1;
  287. if (LinkedList2_IsEmpty(&processes)) {
  288. BReactor_Quit(&ss, 1);
  289. return;
  290. }
  291. // start free job
  292. LinkedList2Iterator_InitForward(&free_it, &processes);
  293. BPending_Set(&free_job);
  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. name
  313. );
  314. }
  315. void print_version (void)
  316. {
  317. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  318. }
  319. int parse_arguments (int argc, char *argv[])
  320. {
  321. if (argc <= 0) {
  322. return 0;
  323. }
  324. options.help = 0;
  325. options.version = 0;
  326. options.logger = LOGGER_STDOUT;
  327. #ifndef BADVPN_USE_WINAPI
  328. options.logger_syslog_facility = "daemon";
  329. options.logger_syslog_ident = argv[0];
  330. #endif
  331. options.loglevel = -1;
  332. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  333. options.loglevels[i] = -1;
  334. }
  335. options.config_file = NULL;
  336. for (int i = 1; i < argc; i++) {
  337. char *arg = argv[i];
  338. if (!strcmp(arg, "--help")) {
  339. options.help = 1;
  340. }
  341. else if (!strcmp(arg, "--version")) {
  342. options.version = 1;
  343. }
  344. else if (!strcmp(arg, "--logger")) {
  345. if (1 >= argc - i) {
  346. fprintf(stderr, "%s: requires an argument\n", arg);
  347. return 0;
  348. }
  349. char *arg2 = argv[i + 1];
  350. if (!strcmp(arg2, "stdout")) {
  351. options.logger = LOGGER_STDOUT;
  352. }
  353. #ifndef BADVPN_USE_WINAPI
  354. else if (!strcmp(arg2, "syslog")) {
  355. options.logger = LOGGER_SYSLOG;
  356. }
  357. #endif
  358. else {
  359. fprintf(stderr, "%s: wrong argument\n", arg);
  360. return 0;
  361. }
  362. i++;
  363. }
  364. #ifndef BADVPN_USE_WINAPI
  365. else if (!strcmp(arg, "--syslog-facility")) {
  366. if (1 >= argc - i) {
  367. fprintf(stderr, "%s: requires an argument\n", arg);
  368. return 0;
  369. }
  370. options.logger_syslog_facility = argv[i + 1];
  371. i++;
  372. }
  373. else if (!strcmp(arg, "--syslog-ident")) {
  374. if (1 >= argc - i) {
  375. fprintf(stderr, "%s: requires an argument\n", arg);
  376. return 0;
  377. }
  378. options.logger_syslog_ident = argv[i + 1];
  379. i++;
  380. }
  381. #endif
  382. else if (!strcmp(arg, "--loglevel")) {
  383. if (1 >= argc - i) {
  384. fprintf(stderr, "%s: requires an argument\n", arg);
  385. return 0;
  386. }
  387. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  388. fprintf(stderr, "%s: wrong argument\n", arg);
  389. return 0;
  390. }
  391. i++;
  392. }
  393. else if (!strcmp(arg, "--channel-loglevel")) {
  394. if (2 >= argc - i) {
  395. fprintf(stderr, "%s: requires two arguments\n", arg);
  396. return 0;
  397. }
  398. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  399. if (channel < 0) {
  400. fprintf(stderr, "%s: wrong channel argument\n", arg);
  401. return 0;
  402. }
  403. int loglevel = parse_loglevel(argv[i + 2]);
  404. if (loglevel < 0) {
  405. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  406. return 0;
  407. }
  408. options.loglevels[channel] = loglevel;
  409. i += 2;
  410. }
  411. else if (!strcmp(arg, "--config-file")) {
  412. if (1 >= argc - i) {
  413. fprintf(stderr, "%s: requires an argument\n", arg);
  414. return 0;
  415. }
  416. options.config_file = argv[i + 1];
  417. i++;
  418. }
  419. else {
  420. fprintf(stderr, "unknown option: %s\n", arg);
  421. return 0;
  422. }
  423. }
  424. if (options.help || options.version) {
  425. return 1;
  426. }
  427. if (!options.config_file) {
  428. fprintf(stderr, "--config-file is required\n");
  429. return 0;
  430. }
  431. return 1;
  432. }
  433. void signal_handler (void *unused)
  434. {
  435. BLog(BLOG_NOTICE, "termination requested");
  436. if (!terminating) {
  437. terminate();
  438. }
  439. }
  440. const struct NCDModule * find_module (const char *name)
  441. {
  442. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  443. for (const struct NCDModule *m = (*g)->modules; m->type; m++) {
  444. if (!strcmp(m->type, name)) {
  445. return m;
  446. }
  447. }
  448. }
  449. return NULL;
  450. }
  451. int statement_init (struct statement *s, struct NCDConfig_statements *conf)
  452. {
  453. // find module
  454. char *module_name = NCDConfig_concat_strings(conf->names);
  455. if (!module_name) {
  456. goto fail0;
  457. }
  458. const struct NCDModule *m = find_module(module_name);
  459. if (!m) {
  460. BLog(BLOG_ERROR, "no module for statement %s", module_name);
  461. free(module_name);
  462. goto fail0;
  463. }
  464. free(module_name);
  465. // set module
  466. s->module = m;
  467. // init arguments
  468. s->first_arg = NULL;
  469. struct argument_elem **prevptr = &s->first_arg;
  470. struct NCDConfig_arguments *arg = conf->args;
  471. while (arg) {
  472. struct argument_elem *e = malloc(sizeof(*e));
  473. if (!e) {
  474. goto fail1;
  475. }
  476. switch (arg->type) {
  477. case NCDCONFIG_ARG_STRING: {
  478. if (!NCDValue_InitString(&e->val, arg->string)) {
  479. free(e);
  480. goto fail1;
  481. }
  482. e->is_var = 0;
  483. } break;
  484. case NCDCONFIG_ARG_VAR: {
  485. if (!(e->var.modname = strdup(arg->var->value))) {
  486. free(e);
  487. goto fail1;
  488. }
  489. if (!arg->var->next) {
  490. e->var.varname = NULL;
  491. } else {
  492. if (!(e->var.varname = NCDConfig_concat_strings(arg->var->next))) {
  493. free(e->var.modname);
  494. free(e);
  495. goto fail1;
  496. }
  497. }
  498. e->is_var = 1;
  499. } break;
  500. default:
  501. ASSERT(0);
  502. }
  503. *prevptr = e;
  504. e->next_arg = NULL;
  505. prevptr = &e->next_arg;
  506. arg = arg->next;
  507. }
  508. // init name
  509. if (!conf->name) {
  510. s->name = NULL;
  511. } else {
  512. if (!(s->name = strdup(conf->name))) {
  513. goto fail1;
  514. }
  515. }
  516. return 1;
  517. fail1:
  518. statement_free_args(s);
  519. fail0:
  520. return 0;
  521. }
  522. void statement_free (struct statement *s)
  523. {
  524. // free name
  525. free(s->name);
  526. // free arguments
  527. statement_free_args(s);
  528. }
  529. void statement_free_args (struct statement *s)
  530. {
  531. struct argument_elem *e = s->first_arg;
  532. while (e) {
  533. if (e->is_var) {
  534. free(e->var.modname);
  535. free(e->var.varname);
  536. } else {
  537. NCDValue_Free(&e->val);
  538. }
  539. struct argument_elem *n = e->next_arg;
  540. free(e);
  541. e = n;
  542. }
  543. }
  544. int process_new (struct NCDConfig_interfaces *conf)
  545. {
  546. // allocate strucure
  547. struct process *p = malloc(sizeof(*p));
  548. if (!p) {
  549. goto fail0;
  550. }
  551. // init name
  552. if (!(p->name = strdup(conf->name))) {
  553. goto fail1;
  554. }
  555. // count statements
  556. size_t num_st = 0;
  557. struct NCDConfig_statements *st = conf->statements;
  558. while (st) {
  559. num_st++;
  560. st = st->next;
  561. }
  562. // statements array
  563. if (!(p->statements = BAllocArray(num_st, sizeof(p->statements[0])))) {
  564. goto fail2;
  565. }
  566. p->num_statements = 0;
  567. // init statements
  568. st = conf->statements;
  569. while (st) {
  570. struct process_statement *ps = &p->statements[p->num_statements];
  571. ps->p = p;
  572. ps->i = p->num_statements;
  573. if (!statement_init(&ps->s, st)) {
  574. goto fail3;
  575. }
  576. ps->state = SSTATE_FORGOTTEN;
  577. ps->have_error = 0;
  578. p->num_statements++;
  579. st = st->next;
  580. }
  581. // set AP=0
  582. p->ap = 0;
  583. // set FP=0
  584. p->fp = 0;
  585. // init timer
  586. BTimer_Init(&p->wait_timer, RETRY_TIME, (BTimer_handler)process_wait_timer_handler, p);
  587. // init advance job
  588. BPending_Init(&p->advance_job, BReactor_PendingGroup(&ss), (BPending_handler)process_advance_job_handler, p);
  589. // insert to processes list
  590. LinkedList2_Append(&processes, &p->list_node);
  591. process_work(p);
  592. return 1;
  593. fail3:
  594. process_free_statements(p);
  595. fail2:
  596. free(p->name);
  597. fail1:
  598. free(p);
  599. fail0:
  600. return 0;
  601. }
  602. void process_free (struct process *p)
  603. {
  604. ASSERT(p->ap == 0)
  605. ASSERT(p->fp == 0)
  606. // remove from processes list
  607. LinkedList2_Remove(&processes, &p->list_node);
  608. // free advance job
  609. BPending_Free(&p->advance_job);
  610. // free timer
  611. BReactor_RemoveTimer(&ss, &p->wait_timer);
  612. // free statements
  613. process_free_statements(p);
  614. // free name
  615. free(p->name);
  616. // free strucure
  617. free(p);
  618. }
  619. void process_free_statements (struct process *p)
  620. {
  621. // free statments
  622. for (size_t i = 0; i < p->num_statements; i++) {
  623. struct process_statement *ps = &p->statements[i];
  624. statement_free(&ps->s);
  625. }
  626. // free stataments array
  627. free(p->statements);
  628. }
  629. void process_assert_pointers (struct process *p)
  630. {
  631. ASSERT(p->ap <= p->num_statements)
  632. ASSERT(p->fp >= p->ap)
  633. ASSERT(p->fp <= p->num_statements)
  634. // check AP
  635. for (size_t i = 0; i < p->ap; i++) {
  636. if (i == p->ap - 1) {
  637. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  638. } else {
  639. ASSERT(p->statements[i].state == SSTATE_ADULT)
  640. }
  641. }
  642. // check FP
  643. size_t fp = p->num_statements;
  644. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  645. fp--;
  646. }
  647. ASSERT(p->fp == fp)
  648. }
  649. void process_log (struct process *p, int level, const char *fmt, ...)
  650. {
  651. va_list vl;
  652. va_start(vl, fmt);
  653. BLog_Append("process %s: ", p->name);
  654. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  655. va_end(vl);
  656. }
  657. void process_work (struct process *p)
  658. {
  659. process_assert_pointers(p);
  660. // stop timer in case we were WAITING
  661. BReactor_RemoveTimer(&ss, &p->wait_timer);
  662. // stop advance job (if we need to advance, we will re-schedule it)
  663. BPending_Unset(&p->advance_job);
  664. if (terminating) {
  665. if (p->fp == 0) {
  666. // finished retreating
  667. process_free(p);
  668. // if there are no more processes, exit program
  669. if (LinkedList2_IsEmpty(&processes)) {
  670. BReactor_Quit(&ss, 1);
  671. }
  672. return;
  673. }
  674. // order the last living statement to die, if needed
  675. struct process_statement *ps = &p->statements[p->fp - 1];
  676. if (ps->state != SSTATE_DYING) {
  677. process_statement_log(ps, BLOG_INFO, "killing");
  678. // order it to die
  679. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_DIE);
  680. // set statement state DYING
  681. ps->state = SSTATE_DYING;
  682. // update AP
  683. if (p->ap > ps->i) {
  684. p->ap = ps->i;
  685. }
  686. }
  687. process_assert_pointers(p);
  688. return;
  689. }
  690. if (p->ap == p->fp) {
  691. // schedule advance
  692. if (!(p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD)) {
  693. BPending_Set(&p->advance_job);
  694. }
  695. // report clean
  696. if (p->ap > 0) {
  697. NCDModuleInst_Event(&p->statements[p->ap - 1].inst, NCDMODULE_TOEVENT_CLEAN);
  698. }
  699. } else {
  700. // order the last living statement to die, if needed
  701. struct process_statement *ps = &p->statements[p->fp - 1];
  702. if (ps->state != SSTATE_DYING) {
  703. process_statement_log(ps, BLOG_INFO, "killing");
  704. // order it to die
  705. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_DIE);
  706. // set statement state DYING
  707. ps->state = SSTATE_DYING;
  708. }
  709. }
  710. process_assert_pointers(p);
  711. }
  712. void process_advance_job_handler (struct process *p)
  713. {
  714. ASSERT(p->ap == p->fp)
  715. ASSERT(!(p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD))
  716. ASSERT(!terminating)
  717. // advance
  718. process_advance(p);
  719. }
  720. void process_advance (struct process *p)
  721. {
  722. ASSERT(p->ap == p->fp)
  723. ASSERT(!(p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD))
  724. if (p->ap == p->num_statements) {
  725. process_log(p, BLOG_INFO, "victory");
  726. process_assert_pointers(p);
  727. return;
  728. }
  729. struct process_statement *ps = &p->statements[p->ap];
  730. // check if we need to wait
  731. if (ps->have_error && ps->error_until > btime_gettime()) {
  732. process_wait(p);
  733. return;
  734. }
  735. process_statement_log(ps, BLOG_INFO, "initializing");
  736. // init arguments list
  737. NCDValue_InitList(&ps->inst_args);
  738. // build arguments
  739. struct argument_elem *arg = ps->s.first_arg;
  740. while (arg) {
  741. NCDValue v;
  742. if (arg->is_var) {
  743. // find referred-to statement
  744. struct process_statement *rps;
  745. size_t i;
  746. for (i = p->ap; i > 0; i--) {
  747. rps = &p->statements[i - 1];
  748. if (rps->s.name && !strcmp(rps->s.name, arg->var.modname)) {
  749. break;
  750. }
  751. }
  752. if (i == 0) {
  753. process_statement_log(ps, BLOG_ERROR, "unknown statement name in variable: %s.%s", arg->var.modname, arg->var.varname);
  754. goto fail1;
  755. }
  756. ASSERT(rps->state == SSTATE_ADULT)
  757. // resolve variable
  758. const char *real_varname = (arg->var.varname ? arg->var.varname : "");
  759. if (!NCDModuleInst_GetVar(&rps->inst, real_varname, &v)) {
  760. process_statement_log(ps, BLOG_ERROR, "failed to resolve variable: %s.%s", arg->var.modname, real_varname);
  761. goto fail1;
  762. }
  763. } else {
  764. if (!NCDValue_InitCopy(&v, &arg->val)) {
  765. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitCopy failed");
  766. goto fail1;
  767. }
  768. }
  769. // move to list
  770. if (!NCDValue_ListAppend(&ps->inst_args, v)) {
  771. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  772. NCDValue_Free(&v);
  773. goto fail1;
  774. }
  775. arg = arg->next_arg;
  776. }
  777. // generate log prefix
  778. snprintf(ps->logprefix, sizeof(ps->logprefix), "process %s: statement %zu: module: ", p->name, ps->i);
  779. // initialize module instance
  780. if (!NCDModuleInst_Init(
  781. &ps->inst, ps->s.name, ps->s.module, &ps->inst_args, ps->logprefix, &ss, &manager,
  782. (NCDModule_handler_event)process_statement_instance_handler_event, (NCDModule_handler_died)process_statement_instance_handler_died, ps
  783. )) {
  784. process_statement_log(ps, BLOG_ERROR, "failed to initialize");
  785. goto fail1;
  786. }
  787. // set statement state CHILD
  788. ps->state = SSTATE_CHILD;
  789. // increment AP
  790. p->ap++;
  791. // increment FP
  792. p->fp++;
  793. process_assert_pointers(p);
  794. return;
  795. fail1:
  796. NCDValue_Free(&ps->inst_args);
  797. process_statement_set_error(ps);
  798. process_wait(p);
  799. }
  800. void process_wait (struct process *p)
  801. {
  802. ASSERT(p->ap == p->fp)
  803. ASSERT(!(p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD))
  804. ASSERT(p->ap < p->num_statements)
  805. ASSERT(p->statements[p->ap].have_error)
  806. process_statement_log(&p->statements[p->ap], BLOG_INFO, "waiting after error");
  807. // set timer
  808. BReactor_SetTimerAbsolute(&ss, &p->wait_timer, p->statements[p->ap].error_until);
  809. process_assert_pointers(p);
  810. }
  811. void process_wait_timer_handler (struct process *p)
  812. {
  813. ASSERT(p->ap == p->fp)
  814. ASSERT(!(p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD))
  815. ASSERT(p->ap < p->num_statements)
  816. ASSERT(p->statements[p->ap].have_error)
  817. process_log(p, BLOG_INFO, "retrying");
  818. // clear error
  819. p->statements[p->ap].have_error = 0;
  820. process_advance(p);
  821. }
  822. void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...)
  823. {
  824. va_list vl;
  825. va_start(vl, fmt);
  826. BLog_Append("process %s: statement %zu: ", ps->p->name, ps->i);
  827. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  828. va_end(vl);
  829. }
  830. void process_statement_set_error (struct process_statement *ps)
  831. {
  832. ASSERT(ps->state == SSTATE_FORGOTTEN)
  833. ps->have_error = 1;
  834. ps->error_until = btime_gettime() + RETRY_TIME;
  835. }
  836. void process_statement_instance_handler_event (struct process_statement *ps, int event)
  837. {
  838. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT)
  839. struct process *p = ps->p;
  840. switch (event) {
  841. case NCDMODULE_EVENT_UP: {
  842. ASSERT(ps->state == SSTATE_CHILD)
  843. process_statement_log(ps, BLOG_INFO, "up");
  844. // set state ADULT
  845. ps->state = SSTATE_ADULT;
  846. } break;
  847. case NCDMODULE_EVENT_DOWN: {
  848. ASSERT(ps->state == SSTATE_ADULT)
  849. process_statement_log(ps, BLOG_INFO, "down");
  850. // set state CHILD
  851. ps->state = SSTATE_CHILD;
  852. // update AP
  853. if (p->ap > ps->i + 1) {
  854. p->ap = ps->i + 1;
  855. }
  856. } break;
  857. case NCDMODULE_EVENT_DYING: {
  858. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT)
  859. process_statement_log(ps, BLOG_INFO, "dying");
  860. // set state DYING
  861. ps->state = SSTATE_DYING;
  862. // update AP
  863. if (p->ap > ps->i) {
  864. p->ap = ps->i;
  865. }
  866. } break;
  867. }
  868. process_work(p);
  869. return;
  870. }
  871. void process_statement_instance_handler_died (struct process_statement *ps, int is_error)
  872. {
  873. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  874. struct process *p = ps->p;
  875. // free instance
  876. NCDModuleInst_Free(&ps->inst);
  877. // free instance arguments
  878. NCDValue_Free(&ps->inst_args);
  879. // set state FORGOTTEN
  880. ps->state = SSTATE_FORGOTTEN;
  881. // set error
  882. if (is_error) {
  883. process_statement_set_error(ps);
  884. } else {
  885. ps->have_error = 0;
  886. }
  887. // update AP
  888. if (p->ap > ps->i) {
  889. p->ap = ps->i;
  890. }
  891. // update FP
  892. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  893. p->fp--;
  894. }
  895. process_statement_log(ps, BLOG_INFO, "died");
  896. if (is_error) {
  897. process_statement_log(ps, BLOG_ERROR, "with error");
  898. }
  899. process_work(p);
  900. return;
  901. }
  902. void init_job_handler (void *unused)
  903. {
  904. ASSERT(!terminating)
  905. if (!init_next) {
  906. // initialized all processes
  907. return;
  908. }
  909. struct NCDConfig_interfaces *conf = init_next;
  910. // schedule next
  911. init_next = init_next->next;
  912. BPending_Set(&init_job);
  913. // init process
  914. process_new(conf);
  915. }
  916. void free_job_handler (void *unused)
  917. {
  918. ASSERT(terminating)
  919. LinkedList2Node *n = LinkedList2Iterator_Next(&free_it);
  920. if (!n) {
  921. // done initiating shutdown for all processes
  922. return;
  923. }
  924. struct process *p = UPPER_OBJECT(n, struct process, list_node);
  925. // schedule next
  926. BPending_Set(&free_job);
  927. process_work(p);
  928. return;
  929. }