ncd.c 38 KB

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