ncd.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  1. /**
  2. * @file ncd.c
  3. * @author Ambroz Bizjak <[email protected]>
  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_assert (struct process *p);
  135. static void process_log (struct process *p, int level, const char *fmt, ...);
  136. static void process_work (struct process *p);
  137. static void process_fight (struct process *p);
  138. static void process_advance_job_handler (struct process *p);
  139. static void process_advance (struct process *p);
  140. static void process_wait (struct process *p);
  141. static void process_wait_timer_handler (struct process *p);
  142. static void process_retreat (struct process *p);
  143. static void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...);
  144. static void process_statement_set_error (struct process_statement *ps);
  145. static void process_statement_instance_handler_event (struct process_statement *ps, int event);
  146. static void process_statement_instance_handler_died (struct process_statement *ps, int is_error);
  147. static void init_job_handler (void *unused);
  148. static void free_job_handler (void *unused);
  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, &configuration)) {
  229. BLog(BLOG_ERROR, "NCDConfigParser_Parse failed");
  230. free(file);
  231. goto fail3;
  232. }
  233. // fee config file memory
  234. free(file);
  235. // init modules
  236. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  237. if ((*g)->func_globalinit && !(*g)->func_globalinit()) {
  238. BLog(BLOG_ERROR, "globalinit failed for some module");
  239. goto fail5;
  240. }
  241. }
  242. // init processes list
  243. LinkedList2_Init(&processes);
  244. // init init job
  245. BPending_Init(&init_job, BReactor_PendingGroup(&ss), init_job_handler, NULL);
  246. // init free job
  247. BPending_Init(&free_job, BReactor_PendingGroup(&ss), free_job_handler, NULL);
  248. // start initializing processes
  249. init_next = configuration;
  250. BPending_Set(&init_job);
  251. // enter event loop
  252. BLog(BLOG_NOTICE, "entering event loop");
  253. BReactor_Exec(&ss);
  254. // free processes
  255. LinkedList2Node *n;
  256. while (n = LinkedList2_GetFirst(&processes)) {
  257. struct process *p = UPPER_OBJECT(n, struct process, list_node);
  258. process_free(p);
  259. }
  260. // free free job
  261. BPending_Free(&free_job);
  262. // free init job
  263. BPending_Free(&init_job);
  264. fail5:
  265. // free configuration
  266. NCDConfig_free_interfaces(configuration);
  267. fail3:
  268. // remove signal handler
  269. BSignal_Finish();
  270. fail2:
  271. // free process manager
  272. BProcessManager_Free(&manager);
  273. fail1a:
  274. // free reactor
  275. BReactor_Free(&ss);
  276. fail1:
  277. // free logger
  278. BLog(BLOG_NOTICE, "exiting");
  279. BLog_Free();
  280. fail0:
  281. // finish objects
  282. DebugObjectGlobal_Finish();
  283. return 1;
  284. }
  285. void terminate (void)
  286. {
  287. ASSERT(!terminating)
  288. BLog(BLOG_NOTICE, "tearing down");
  289. terminating = 1;
  290. if (LinkedList2_IsEmpty(&processes)) {
  291. BReactor_Quit(&ss, 1);
  292. return;
  293. }
  294. // start free job
  295. LinkedList2Iterator_InitForward(&free_it, &processes);
  296. BPending_Set(&free_job);
  297. }
  298. void print_help (const char *name)
  299. {
  300. printf(
  301. "Usage:\n"
  302. " %s\n"
  303. " [--help]\n"
  304. " [--version]\n"
  305. " [--logger <"LOGGERS_STRING">]\n"
  306. #ifndef BADVPN_USE_WINAPI
  307. " (logger=syslog?\n"
  308. " [--syslog-facility <string>]\n"
  309. " [--syslog-ident <string>]\n"
  310. " )\n"
  311. #endif
  312. " [--loglevel <0-5/none/error/warning/notice/info/debug>]\n"
  313. " [--channel-loglevel <channel-name> <0-5/none/error/warning/notice/info/debug>] ...\n"
  314. " --config-file <file>\n",
  315. name
  316. );
  317. }
  318. void print_version (void)
  319. {
  320. printf(GLOBAL_PRODUCT_NAME" "PROGRAM_NAME" "GLOBAL_VERSION"\n"GLOBAL_COPYRIGHT_NOTICE"\n");
  321. }
  322. int parse_arguments (int argc, char *argv[])
  323. {
  324. if (argc <= 0) {
  325. return 0;
  326. }
  327. options.help = 0;
  328. options.version = 0;
  329. options.logger = LOGGER_STDOUT;
  330. #ifndef BADVPN_USE_WINAPI
  331. options.logger_syslog_facility = "daemon";
  332. options.logger_syslog_ident = argv[0];
  333. #endif
  334. options.loglevel = -1;
  335. for (int i = 0; i < BLOG_NUM_CHANNELS; i++) {
  336. options.loglevels[i] = -1;
  337. }
  338. options.config_file = NULL;
  339. for (int i = 1; i < argc; i++) {
  340. char *arg = argv[i];
  341. if (!strcmp(arg, "--help")) {
  342. options.help = 1;
  343. }
  344. else if (!strcmp(arg, "--version")) {
  345. options.version = 1;
  346. }
  347. else if (!strcmp(arg, "--logger")) {
  348. if (1 >= argc - i) {
  349. fprintf(stderr, "%s: requires an argument\n", arg);
  350. return 0;
  351. }
  352. char *arg2 = argv[i + 1];
  353. if (!strcmp(arg2, "stdout")) {
  354. options.logger = LOGGER_STDOUT;
  355. }
  356. #ifndef BADVPN_USE_WINAPI
  357. else if (!strcmp(arg2, "syslog")) {
  358. options.logger = LOGGER_SYSLOG;
  359. }
  360. #endif
  361. else {
  362. fprintf(stderr, "%s: wrong argument\n", arg);
  363. return 0;
  364. }
  365. i++;
  366. }
  367. #ifndef BADVPN_USE_WINAPI
  368. else if (!strcmp(arg, "--syslog-facility")) {
  369. if (1 >= argc - i) {
  370. fprintf(stderr, "%s: requires an argument\n", arg);
  371. return 0;
  372. }
  373. options.logger_syslog_facility = argv[i + 1];
  374. i++;
  375. }
  376. else if (!strcmp(arg, "--syslog-ident")) {
  377. if (1 >= argc - i) {
  378. fprintf(stderr, "%s: requires an argument\n", arg);
  379. return 0;
  380. }
  381. options.logger_syslog_ident = argv[i + 1];
  382. i++;
  383. }
  384. #endif
  385. else if (!strcmp(arg, "--loglevel")) {
  386. if (1 >= argc - i) {
  387. fprintf(stderr, "%s: requires an argument\n", arg);
  388. return 0;
  389. }
  390. if ((options.loglevel = parse_loglevel(argv[i + 1])) < 0) {
  391. fprintf(stderr, "%s: wrong argument\n", arg);
  392. return 0;
  393. }
  394. i++;
  395. }
  396. else if (!strcmp(arg, "--channel-loglevel")) {
  397. if (2 >= argc - i) {
  398. fprintf(stderr, "%s: requires two arguments\n", arg);
  399. return 0;
  400. }
  401. int channel = BLogGlobal_GetChannelByName(argv[i + 1]);
  402. if (channel < 0) {
  403. fprintf(stderr, "%s: wrong channel argument\n", arg);
  404. return 0;
  405. }
  406. int loglevel = parse_loglevel(argv[i + 2]);
  407. if (loglevel < 0) {
  408. fprintf(stderr, "%s: wrong loglevel argument\n", arg);
  409. return 0;
  410. }
  411. options.loglevels[channel] = loglevel;
  412. i += 2;
  413. }
  414. else if (!strcmp(arg, "--config-file")) {
  415. if (1 >= argc - i) {
  416. fprintf(stderr, "%s: requires an argument\n", arg);
  417. return 0;
  418. }
  419. options.config_file = argv[i + 1];
  420. i++;
  421. }
  422. else {
  423. fprintf(stderr, "unknown option: %s\n", arg);
  424. return 0;
  425. }
  426. }
  427. if (options.help || options.version) {
  428. return 1;
  429. }
  430. if (!options.config_file) {
  431. fprintf(stderr, "--config-file is required\n");
  432. return 0;
  433. }
  434. return 1;
  435. }
  436. void signal_handler (void *unused)
  437. {
  438. BLog(BLOG_NOTICE, "termination requested");
  439. if (!terminating) {
  440. terminate();
  441. }
  442. }
  443. const struct NCDModule * find_module (const char *name)
  444. {
  445. for (const struct NCDModuleGroup **g = ncd_modules; *g; g++) {
  446. for (const struct NCDModule *m = (*g)->modules; m->type; m++) {
  447. if (!strcmp(m->type, name)) {
  448. return m;
  449. }
  450. }
  451. }
  452. return NULL;
  453. }
  454. int statement_init (struct statement *s, struct NCDConfig_statements *conf)
  455. {
  456. // find module
  457. char *module_name = NCDConfig_concat_strings(conf->names);
  458. if (!module_name) {
  459. goto fail0;
  460. }
  461. const struct NCDModule *m = find_module(module_name);
  462. if (!m) {
  463. BLog(BLOG_ERROR, "no module for statement %s", module_name);
  464. free(module_name);
  465. goto fail0;
  466. }
  467. free(module_name);
  468. // set module
  469. s->module = m;
  470. // init arguments
  471. s->first_arg = NULL;
  472. struct argument_elem **prevptr = &s->first_arg;
  473. struct NCDConfig_arguments *arg = conf->args;
  474. while (arg) {
  475. struct argument_elem *e = malloc(sizeof(*e));
  476. if (!e) {
  477. goto fail1;
  478. }
  479. switch (arg->type) {
  480. case NCDCONFIG_ARG_STRING: {
  481. if (!NCDValue_InitString(&e->val, arg->string)) {
  482. free(e);
  483. goto fail1;
  484. }
  485. e->is_var = 0;
  486. } break;
  487. case NCDCONFIG_ARG_VAR: {
  488. if (!(e->var.modname = strdup(arg->var->value))) {
  489. free(e);
  490. goto fail1;
  491. }
  492. if (!arg->var->next) {
  493. e->var.varname = NULL;
  494. } else {
  495. if (!(e->var.varname = NCDConfig_concat_strings(arg->var->next))) {
  496. free(e->var.modname);
  497. free(e);
  498. goto fail1;
  499. }
  500. }
  501. e->is_var = 1;
  502. } break;
  503. default:
  504. ASSERT(0);
  505. }
  506. *prevptr = e;
  507. e->next_arg = NULL;
  508. prevptr = &e->next_arg;
  509. arg = arg->next;
  510. }
  511. // init name
  512. if (!conf->name) {
  513. s->name = NULL;
  514. } else {
  515. if (!(s->name = strdup(conf->name))) {
  516. goto fail1;
  517. }
  518. }
  519. return 1;
  520. fail1:
  521. statement_free_args(s);
  522. fail0:
  523. return 0;
  524. }
  525. void statement_free (struct statement *s)
  526. {
  527. // free name
  528. free(s->name);
  529. // free arguments
  530. statement_free_args(s);
  531. }
  532. void statement_free_args (struct statement *s)
  533. {
  534. struct argument_elem *e = s->first_arg;
  535. while (e) {
  536. if (e->is_var) {
  537. free(e->var.modname);
  538. free(e->var.varname);
  539. } else {
  540. NCDValue_Free(&e->val);
  541. }
  542. struct argument_elem *n = e->next_arg;
  543. free(e);
  544. e = n;
  545. }
  546. }
  547. int process_new (struct NCDConfig_interfaces *conf)
  548. {
  549. // allocate strucure
  550. struct process *p = malloc(sizeof(*p));
  551. if (!p) {
  552. goto fail0;
  553. }
  554. // init name
  555. if (!(p->name = strdup(conf->name))) {
  556. goto fail1;
  557. }
  558. // count statements
  559. size_t num_st = 0;
  560. struct NCDConfig_statements *st = conf->statements;
  561. while (st) {
  562. num_st++;
  563. st = st->next;
  564. }
  565. // statements array
  566. if (!(p->statements = BAllocArray(num_st, sizeof(p->statements[0])))) {
  567. goto fail2;
  568. }
  569. p->num_statements = 0;
  570. // init statements
  571. st = conf->statements;
  572. while (st) {
  573. struct process_statement *ps = &p->statements[p->num_statements];
  574. ps->p = p;
  575. ps->i = p->num_statements;
  576. if (!statement_init(&ps->s, st)) {
  577. goto fail3;
  578. }
  579. ps->state = SSTATE_FORGOTTEN;
  580. ps->have_error = 0;
  581. p->num_statements++;
  582. st = st->next;
  583. }
  584. // set AP=0
  585. p->ap = 0;
  586. // set FP=0
  587. p->fp = 0;
  588. // init timer
  589. BTimer_Init(&p->wait_timer, RETRY_TIME, (BTimer_handler)process_wait_timer_handler, p);
  590. // init advance job
  591. BPending_Init(&p->advance_job, BReactor_PendingGroup(&ss), (BPending_handler)process_advance_job_handler, p);
  592. // insert to processes list
  593. LinkedList2_Append(&processes, &p->list_node);
  594. process_work(p);
  595. return 1;
  596. fail3:
  597. process_free_statements(p);
  598. fail2:
  599. free(p->name);
  600. fail1:
  601. free(p);
  602. fail0:
  603. return 0;
  604. }
  605. void process_free (struct process *p)
  606. {
  607. ASSERT(p->ap == 0)
  608. ASSERT(p->fp == 0)
  609. // remove from processes list
  610. LinkedList2_Remove(&processes, &p->list_node);
  611. // free advance job
  612. BPending_Free(&p->advance_job);
  613. // free timer
  614. BReactor_RemoveTimer(&ss, &p->wait_timer);
  615. // free statements
  616. process_free_statements(p);
  617. // free name
  618. free(p->name);
  619. // free strucure
  620. free(p);
  621. }
  622. void process_free_statements (struct process *p)
  623. {
  624. // free statments
  625. for (size_t i = 0; i < p->num_statements; i++) {
  626. struct process_statement *ps = &p->statements[i];
  627. statement_free(&ps->s);
  628. }
  629. // free stataments array
  630. free(p->statements);
  631. }
  632. void process_assert_pointers (struct process *p)
  633. {
  634. ASSERT(p->ap <= p->num_statements)
  635. ASSERT(p->fp >= p->ap)
  636. ASSERT(p->fp <= p->num_statements)
  637. // check AP
  638. for (size_t i = 0; i < p->ap; i++) {
  639. if (i == p->ap - 1) {
  640. ASSERT(p->statements[i].state == SSTATE_ADULT || p->statements[i].state == SSTATE_CHILD)
  641. } else {
  642. ASSERT(p->statements[i].state == SSTATE_ADULT)
  643. }
  644. }
  645. // check FP
  646. size_t fp = p->num_statements;
  647. while (fp > 0 && p->statements[fp - 1].state == SSTATE_FORGOTTEN) {
  648. fp--;
  649. }
  650. ASSERT(p->fp == fp)
  651. }
  652. void process_assert (struct process *p)
  653. {
  654. process_assert_pointers(p);
  655. }
  656. void process_log (struct process *p, int level, const char *fmt, ...)
  657. {
  658. va_list vl;
  659. va_start(vl, fmt);
  660. BLog_Append("process %s: ", p->name);
  661. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  662. va_end(vl);
  663. }
  664. void process_work (struct process *p)
  665. {
  666. process_assert_pointers(p);
  667. // stop timer in case we were WAITING
  668. BReactor_RemoveTimer(&ss, &p->wait_timer);
  669. // stop advance job if we can't advance
  670. if (!(p->ap == p->fp && !terminating)) {
  671. BPending_Unset(&p->advance_job);
  672. }
  673. if (terminating) {
  674. process_retreat(p);
  675. return;
  676. }
  677. process_fight(p);
  678. }
  679. void process_fight (struct process *p)
  680. {
  681. if (p->ap == p->fp) {
  682. // schedule advance
  683. BPending_Set(&p->advance_job);
  684. // report clean
  685. if (p->ap > 0) {
  686. NCDModuleInst_Event(&p->statements[p->ap - 1].inst, NCDMODULE_TOEVENT_CLEAN);
  687. }
  688. } else {
  689. // order the last living statement to die, if needed
  690. struct process_statement *ps = &p->statements[p->fp - 1];
  691. if (ps->state != SSTATE_DYING) {
  692. process_statement_log(ps, BLOG_INFO, "killing");
  693. // order it to die
  694. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_DIE);
  695. // set statement state DYING
  696. ps->state = SSTATE_DYING;
  697. }
  698. process_assert(p);
  699. }
  700. }
  701. void process_advance_job_handler (struct process *p)
  702. {
  703. ASSERT(p->ap == p->fp)
  704. ASSERT(!terminating)
  705. if (!(p->ap > 0 && p->statements[p->ap - 1].state == SSTATE_CHILD)) {
  706. // advance
  707. process_advance(p);
  708. }
  709. }
  710. void process_advance (struct process *p)
  711. {
  712. ASSERT(p->ap == p->fp)
  713. ASSERT(!(p->ap > 0) || p->statements[p->ap - 1].state == SSTATE_ADULT)
  714. if (p->ap == p->num_statements) {
  715. process_log(p, BLOG_INFO, "victory");
  716. process_assert(p);
  717. return;
  718. }
  719. struct process_statement *ps = &p->statements[p->ap];
  720. // check if we need to wait
  721. if (ps->have_error && ps->error_until > btime_gettime()) {
  722. process_wait(p);
  723. return;
  724. }
  725. process_statement_log(ps, BLOG_INFO, "initializing");
  726. // init arguments list
  727. NCDValue_InitList(&ps->inst_args);
  728. // build arguments
  729. struct argument_elem *arg = ps->s.first_arg;
  730. while (arg) {
  731. NCDValue v;
  732. if (arg->is_var) {
  733. // find referred-to statement
  734. struct process_statement *rps;
  735. size_t i;
  736. for (i = p->ap; i > 0; i--) {
  737. rps = &p->statements[i - 1];
  738. if (rps->s.name && !strcmp(rps->s.name, arg->var.modname)) {
  739. break;
  740. }
  741. }
  742. if (i == 0) {
  743. process_statement_log(ps, BLOG_ERROR, "unknown statement name in variable: %s.%s", arg->var.modname, arg->var.varname);
  744. goto fail1;
  745. }
  746. ASSERT(rps->state == SSTATE_ADULT)
  747. // resolve variable
  748. const char *real_varname = (arg->var.varname ? arg->var.varname : "");
  749. if (!NCDModuleInst_GetVar(&rps->inst, real_varname, &v)) {
  750. process_statement_log(ps, BLOG_ERROR, "failed to resolve variable: %s.%s", arg->var.modname, real_varname);
  751. goto fail1;
  752. }
  753. } else {
  754. if (!NCDValue_InitCopy(&v, &arg->val)) {
  755. process_statement_log(ps, BLOG_ERROR, "NCDValue_InitCopy failed");
  756. goto fail1;
  757. }
  758. }
  759. // move to list
  760. if (!NCDValue_ListAppend(&ps->inst_args, v)) {
  761. process_statement_log(ps, BLOG_ERROR, "NCDValue_ListAppend failed");
  762. NCDValue_Free(&v);
  763. goto fail1;
  764. }
  765. arg = arg->next_arg;
  766. }
  767. // generate log prefix
  768. snprintf(ps->logprefix, sizeof(ps->logprefix), "process %s: statement %zu: module: ", p->name, ps->i);
  769. // initialize module instance
  770. if (!NCDModuleInst_Init(
  771. &ps->inst, ps->s.name, ps->s.module, &ps->inst_args, ps->logprefix, &ss, &manager,
  772. (NCDModule_handler_event)process_statement_instance_handler_event, (NCDModule_handler_died)process_statement_instance_handler_died, ps
  773. )) {
  774. process_statement_log(ps, BLOG_ERROR, "failed to initialize");
  775. goto fail1;
  776. }
  777. // set statement state CHILD
  778. ps->state = SSTATE_CHILD;
  779. // increment AP
  780. p->ap++;
  781. // increment FP
  782. p->fp++;
  783. process_assert(p);
  784. return;
  785. fail1:
  786. NCDValue_Free(&ps->inst_args);
  787. process_statement_set_error(ps);
  788. process_wait(p);
  789. }
  790. void process_wait (struct process *p)
  791. {
  792. ASSERT(p->ap == p->fp)
  793. ASSERT(!(p->ap > 0) || p->statements[p->ap - 1].state == SSTATE_ADULT)
  794. ASSERT(p->ap < p->num_statements)
  795. ASSERT(p->statements[p->ap].have_error)
  796. process_statement_log(&p->statements[p->ap], BLOG_INFO, "waiting after error");
  797. // set timer
  798. BReactor_SetTimerAbsolute(&ss, &p->wait_timer, p->statements[p->ap].error_until);
  799. process_assert(p);
  800. }
  801. void process_wait_timer_handler (struct process *p)
  802. {
  803. ASSERT(p->ap == p->fp)
  804. ASSERT(!(p->ap > 0) || p->statements[p->ap - 1].state == SSTATE_ADULT)
  805. ASSERT(p->ap < p->num_statements)
  806. ASSERT(p->statements[p->ap].have_error)
  807. process_log(p, BLOG_INFO, "retrying");
  808. // clear error
  809. p->statements[p->ap].have_error = 0;
  810. process_advance(p);
  811. }
  812. void process_retreat (struct process *p)
  813. {
  814. if (p->fp == 0) {
  815. // finished retreating
  816. process_free(p);
  817. // if there are no more processes, exit program
  818. if (LinkedList2_IsEmpty(&processes)) {
  819. BReactor_Quit(&ss, 1);
  820. }
  821. return;
  822. }
  823. // order the last living statement to die, if needed
  824. struct process_statement *ps = &p->statements[p->fp - 1];
  825. if (ps->state != SSTATE_DYING) {
  826. process_statement_log(ps, BLOG_INFO, "killing");
  827. // order it to die
  828. NCDModuleInst_Event(&ps->inst, NCDMODULE_TOEVENT_DIE);
  829. // set statement state DYING
  830. ps->state = SSTATE_DYING;
  831. // update AP
  832. if (p->ap > ps->i) {
  833. p->ap = ps->i;
  834. }
  835. }
  836. process_assert(p);
  837. }
  838. void process_statement_log (struct process_statement *ps, int level, const char *fmt, ...)
  839. {
  840. va_list vl;
  841. va_start(vl, fmt);
  842. BLog_Append("process %s: statement %zu: ", ps->p->name, ps->i);
  843. BLog_LogToChannelVarArg(BLOG_CURRENT_CHANNEL, level, fmt, vl);
  844. va_end(vl);
  845. }
  846. void process_statement_set_error (struct process_statement *ps)
  847. {
  848. ASSERT(ps->state == SSTATE_FORGOTTEN)
  849. ps->have_error = 1;
  850. ps->error_until = btime_gettime() + RETRY_TIME;
  851. }
  852. void process_statement_instance_handler_event (struct process_statement *ps, int event)
  853. {
  854. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT)
  855. struct process *p = ps->p;
  856. switch (event) {
  857. case NCDMODULE_EVENT_UP: {
  858. ASSERT(ps->state == SSTATE_CHILD)
  859. process_statement_log(ps, BLOG_INFO, "up");
  860. // set state ADULT
  861. ps->state = SSTATE_ADULT;
  862. } break;
  863. case NCDMODULE_EVENT_DOWN: {
  864. ASSERT(ps->state == SSTATE_ADULT)
  865. process_statement_log(ps, BLOG_INFO, "down");
  866. // set state CHILD
  867. ps->state = SSTATE_CHILD;
  868. // update AP
  869. if (p->ap > ps->i + 1) {
  870. p->ap = ps->i + 1;
  871. }
  872. } break;
  873. case NCDMODULE_EVENT_DYING: {
  874. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT)
  875. process_statement_log(ps, BLOG_INFO, "dying");
  876. // set state DYING
  877. ps->state = SSTATE_DYING;
  878. // update AP
  879. if (p->ap > ps->i) {
  880. p->ap = ps->i;
  881. }
  882. } break;
  883. }
  884. process_work(p);
  885. return;
  886. }
  887. void process_statement_instance_handler_died (struct process_statement *ps, int is_error)
  888. {
  889. ASSERT(ps->state == SSTATE_CHILD || ps->state == SSTATE_ADULT || ps->state == SSTATE_DYING)
  890. struct process *p = ps->p;
  891. // free instance
  892. NCDModuleInst_Free(&ps->inst);
  893. // free instance arguments
  894. NCDValue_Free(&ps->inst_args);
  895. // set state FORGOTTEN
  896. ps->state = SSTATE_FORGOTTEN;
  897. // set error
  898. if (is_error) {
  899. process_statement_set_error(ps);
  900. } else {
  901. ps->have_error = 0;
  902. }
  903. // update AP
  904. if (p->ap > ps->i) {
  905. p->ap = ps->i;
  906. }
  907. // update FP
  908. while (p->fp > 0 && p->statements[p->fp - 1].state == SSTATE_FORGOTTEN) {
  909. p->fp--;
  910. }
  911. process_statement_log(ps, BLOG_INFO, "died");
  912. if (is_error) {
  913. process_statement_log(ps, BLOG_ERROR, "with error");
  914. }
  915. process_work(p);
  916. return;
  917. }
  918. void init_job_handler (void *unused)
  919. {
  920. ASSERT(!terminating)
  921. if (!init_next) {
  922. // initialized all processes
  923. return;
  924. }
  925. struct NCDConfig_interfaces *conf = init_next;
  926. // schedule next
  927. init_next = init_next->next;
  928. BPending_Set(&init_job);
  929. // init process
  930. process_new(conf);
  931. }
  932. void free_job_handler (void *unused)
  933. {
  934. ASSERT(terminating)
  935. LinkedList2Node *n = LinkedList2Iterator_Next(&free_it);
  936. if (!n) {
  937. // done initiating shutdown for all processes
  938. return;
  939. }
  940. struct process *p = UPPER_OBJECT(n, struct process, list_node);
  941. // schedule next
  942. BPending_Set(&free_job);
  943. process_work(p);
  944. return;
  945. }