ncd.c 39 KB

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