ncd.c 39 KB

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