3 * tailing reliable realtime streaming feeder for inn
4 * duct.c - main program, option parsing and startup
6 * Copyright (C) 2010 Ian Jackson <ijackson@chiark.greenend.org.uk>
8 * This program is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * (at your option) any later version.
13 * This program 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.
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 * (I believe that when you compile and link this as part of the inn2
22 * build, with the Makefile runes I have provided, all the libraries
23 * and files which end up included in innduct are licence-compatible
24 * with GPLv3. If not then please let me know. -Ian Jackson.)
29 const char *sms_names[]= {
30 #define SMS_DEF_NAME(s) #s ,
31 SMS_LIST(SMS_DEF_NAME)
36 /*----- general operational variables -----*/
38 /* main initialises */
41 char *path_lock, *path_flushing, *path_defer, *path_dump;
42 char *globpat_backlog;
44 int *lowvol_perperiod;
46 int lowvol_total; /* does not include current period */
48 /*---------- configuration option variables ----------*/
49 /* when changing defaults, remember to update the manpage */
51 const char *sitename, *remote_host;
52 const char *feedfile, *path_run, *path_cli, *path_cli_dir;
54 int interactive=0, try_filemon=1;
57 const char *inndconffile;
59 int max_connections=10;
60 int max_queue_per_conn=200;
61 int target_max_feedfile_size=100000;
62 int period_seconds=30;
63 int filepoll_seconds=5;
64 int max_queue_per_ipf=-1;
66 int connection_setup_timeout=200;
67 int inndcomm_flush_timeout=100;
69 double nocheck_thresh= 95.0; /* converted from percentage by main */
70 double nocheck_decay= 100; /* conv'd from articles to lambda by main */
72 /* all these are initialised to seconds, and converted to periods in main */
73 int reconnect_delay_periods=1000;
74 int flushfail_retry_periods=1000;
75 int backlog_retry_minperiods=100;
76 int backlog_spontrescan_periods=300;
77 int spontaneous_flush_periods=100000;
78 int max_separated_periods=2000;
79 int need_activity_periods=1000;
81 int lowvol_periods=1000;
83 double max_bad_data_ratio= 1; /* conv'd from percentage by main */
84 int max_bad_data_initial= 30;
85 /* in one corrupt 4096-byte block the number of newlines has
86 * mean 16 and standard deviation 3.99. 30 corresponds to z=+3.5 */
88 /*========== main program ==========*/
90 static void postfork_inputfile(InputFile *ipf) {
92 xclose(ipf->fd, "(in child) input file ", ipf->path);
95 static void postfork_stdio(FILE *f, const char *what, const char *what2) {
96 /* we have no stdio streams that are buffered long-term */
98 if (fclose(f)) syscrash("(in child) close %s%s", what, what2?what2:0);
101 void postfork(void) {
104 xsigsetdefault(SIGTERM);
105 xsigsetdefault(SIGINT);
106 xsigsetdefault(SIGPIPE);
107 if (terminate_sig_flag) raise(terminate_sig_flag);
109 postfork_inputfile(main_input_file);
110 postfork_inputfile(flushing_input_file);
114 conn_closefd(conn,"(in child) ");
116 postfork_stdio(defer, "defer file ", path_defer);
119 typedef struct Every Every;
121 struct timeval interval;
126 static void every_schedule(Every *e, struct timeval base);
128 static void *every_happens(oop_source *lp, struct timeval base, void *e_v) {
131 if (!e->fixed_rate) xgettimeofday(&base);
132 every_schedule(e, base);
136 static void every_schedule(Every *e, struct timeval base) {
138 timeradd(&base, &e->interval, &when);
139 loop->on_time(loop, when, every_happens, e);
142 static void every(int interval, int fixed_rate, void (*f)(void)) {
144 e->interval.tv_sec= interval;
145 e->interval.tv_usec= 0;
146 e->fixed_rate= fixed_rate;
150 every_schedule(e, now);
154 char *dipf_main= dbg_report_ipf(main_input_file);
155 char *dipf_flushing= dbg_report_ipf(flushing_input_file);
156 char *dipf_backlog= dbg_report_ipf(backlog_input_file);
159 " sms=%s[%d] conns=%d until_connect=%d"
160 " input_files main:%s flushing:%s backlog:%s[%d]"
161 " children connecting=%ld inndcomm=%ld lowvol_total=%d"
163 sms_names[sms], until_flush, conns.count, until_connect,
164 dipf_main, dipf_flushing, dipf_backlog, until_backlog_nextscan,
165 (long)connecting_child, (long)inndcomm_child, lowvol_total
172 if (until_connect) until_connect--;
174 inputfile_queue_check_expired(backlog_input_file);
176 if (!backlog_input_file) close_defer(); /* want to start on a new backlog */
177 statemc_period_poll();
178 check_assign_articles();
183 /*========== option parsing ==========*/
185 static void vbadusage(const char *fmt, va_list al) NORET_PRINTF(1,0);
186 static void vbadusage(const char *fmt, va_list al) {
187 char *m= xvasprintf(fmt,al);
188 fprintf(stderr, "bad usage: %s\n"
189 "say --help for help, or read the manpage\n",
192 syslog(LOG_ERR,"innduct: invoked with bad usage: %s",m);
196 /*---------- generic option parser ----------*/
198 static void badusage(const char *fmt, ...) NORET_PRINTF(1,2);
199 static void badusage(const char *fmt, ...) {
210 typedef struct Option Option;
211 typedef void OptionParser(const Option*, const char *val);
215 const char *lng, *formarg;
221 static void parse_options(const Option *options, char ***argvp) {
222 /* on return *argvp is first non-option arg; argc is not updated */
225 const char *arg= *++(*argvp);
227 if (*arg != '-') break;
228 if (!strcmp(arg,"--")) { arg= *++(*argvp); break; }
230 while ((a= *++arg)) {
234 char *equals= strchr(arg,'=');
235 unsigned len= equals ? (size_t)(equals - arg) : strlen(arg);
236 for (o=options; o->shrt || o->lng; o++)
237 if (strlen(o->lng) == len && !memcmp(o->lng,arg,len))
239 badusage("unknown long option --%s",arg);
242 if (equals) badusage("option --%s does not take a value",o->lng);
248 if (!arg) badusage("option --%s needs a value for %s",
252 break; /* eaten the whole argument now */
254 for (o=options; o->shrt || o->lng; o++)
257 badusage("unknown short option -%c",a);
264 if (!arg) badusage("option -%c needs a value for %s",
265 o->shrt, o->formarg);
268 break; /* eaten the whole argument now */
274 #define DELIMPERHAPS(delim,str) (str) ? (delim) : "", (str) ? (str) : ""
276 static void print_options(const Option *options, FILE *f) {
278 for (o=options; o->shrt || o->lng; o++) {
279 char shrt[2] = { o->shrt, 0 };
280 char *optspec= xasprintf("%s%s%s%s%s",
281 o->shrt ? "-" : "", shrt,
282 o->shrt && o->lng ? "|" : "",
283 DELIMPERHAPS("--", o->lng));
284 fprintf(f, " %s%s%s\n", optspec, DELIMPERHAPS(" ", o->formarg));
289 /*---------- specific option types ----------*/
291 static void op_integer(const Option *o, const char *val) {
294 unsigned long ul= strtoul(val,&ep,10);
295 if (*ep || ep==val || errno || ul>INT_MAX)
296 badusage("bad integer value for %s",o->lng);
297 int *store= o->store;
301 static void op_double(const Option *o, const char *val) {
302 int *store= o->store;
305 *store= strtod(val, &ep);
306 if (*ep || ep==val || errno)
307 badusage("bad floating point value for %s",o->lng);
310 static void op_string(const Option *o, const char *val) {
311 const char **store= o->store;
315 static void op_seconds(const Option *o, const char *val) {
316 int *store= o->store;
320 double v= strtod(val,&ep);
321 if (ep==val) badusage("bad time/duration value for %s",o->lng);
323 if (!*ep || !strcmp(ep,"s") || !strcmp(ep,"sec")) unit= 1;
324 else if (!strcmp(ep,"m") || !strcmp(ep,"min")) unit= 60;
325 else if (!strcmp(ep,"h") || !strcmp(ep,"hour")) unit= 3600;
326 else if (!strcmp(ep,"d") || !strcmp(ep,"day")) unit= 86400;
327 else if (!strcmp(ep,"das")) unit= 10;
328 else if (!strcmp(ep,"hs")) unit= 100;
329 else if (!strcmp(ep,"ks")) unit= 1000;
330 else if (!strcmp(ep,"Ms")) unit= 1000000;
331 else badusage("bad units %s for time/duration value for %s",ep,o->lng);
335 if (v > INT_MAX) badusage("time/duration value for %s out of range",o->lng);
339 static void op_setint(const Option *o, const char *val) {
340 int *store= o->store;
344 /*---------- specific options ----------*/
346 static void help(const Option *o, const char *val);
348 static const Option innduct_options[]= {
349 {'f',"feedfile", "F", &feedfile, op_string },
350 {'q',"quiet-multiple", 0, &quiet_multiple, op_setint, 1 },
351 {0,"no-daemon", 0, &interactive, op_setint, 1 },
352 {0,"interactive", 0, &interactive, op_setint, 2 },
353 {0,"no-streaming", 0, &try_stream, op_setint, 0 },
354 {0,"no-filemon", 0, &try_filemon, op_setint, 0 },
355 {'C',"inndconf", "F", &inndconffile, op_string },
356 {'P',"port", "PORT", &port, op_integer },
357 {0,"chdir", "DIR", &path_run, op_string },
358 {0,"cli", "DIR/|PATH", &path_cli, op_string },
359 {0,"help", 0, 0, help },
361 {0,"max-connections", "N", &max_connections, op_integer },
362 {0,"max-queue-per-conn", "N", &max_queue_per_conn, op_integer },
363 {0,"max-queue-per-file", "N", &max_queue_per_ipf, op_integer },
364 {0,"feedfile-flush-size","BYTES", &target_max_feedfile_size, op_integer },
365 {0,"period-interval", "TIME", &period_seconds, op_seconds },
367 {0,"connection-timeout", "TIME", &connection_setup_timeout, op_seconds },
368 {0,"stuck-flush-timeout", "TIME", &inndcomm_flush_timeout, op_seconds },
369 {0,"feedfile-poll", "TIME", &filepoll_seconds, op_seconds },
371 {0,"no-check-proportion", "PERCENT", &nocheck_thresh, op_double },
372 {0,"no-check-response-time","ARTICLES", &nocheck_decay, op_double },
374 {0,"reconnect-interval", "PERIOD", &reconnect_delay_periods, op_seconds },
375 {0,"flush-retry-interval", "PERIOD", &flushfail_retry_periods, op_seconds },
376 {0,"earliest-deferred-retry","PERIOD", &backlog_retry_minperiods, op_seconds },
377 {0,"backlog-rescan-interval","PERIOD",&backlog_spontrescan_periods,op_seconds},
378 {0,"max-flush-interval", "PERIOD", &spontaneous_flush_periods,op_seconds },
379 {0,"flush-finish-timeout", "PERIOD", &max_separated_periods, op_seconds },
380 {0,"idle-timeout", "PERIOD", &need_activity_periods, op_seconds },
381 {0,"low-volume-thresh", "PERIOD", &lowvol_thresh, op_integer },
382 {0,"low-volume-window", "PERIOD", &lowvol_periods, op_seconds },
384 {0,"max-bad-input-data-ratio","PERCENT", &max_bad_data_ratio, op_double },
385 {0,"max-bad-input-data-init", "PERCENT", &max_bad_data_initial, op_integer },
390 static void printusage(FILE *f) {
391 fputs("usage: innduct [options] site [fqdn]\n"
392 "available options are:\n", f);
393 print_options(innduct_options, f);
396 static void help(const Option *o, const char *val) {
398 if (ferror(stdout) || fflush(stdout)) {
399 perror("innduct: writing help");
405 static void convert_to_periods_rndup(int *store) {
406 *store += period_seconds-1;
407 *store /= period_seconds;
410 static int path_ends_slash(const char *specified) {
411 int l= strlen(specified);
413 return specified[l-1] == '/';
416 static int innduct_fatal_cleanup(void) { return 12; } /* used for libinn die */
418 int main(int argc, char **argv) {
419 /* set up libinn logging */
420 message_program_name= "innduct";
421 message_fatal_cleanup= innduct_fatal_cleanup;
423 #define INNLOGSET_CALL(fn, pfx, sysloglevel) \
424 message_handlers_##fn(1, duct_log_##fn);
425 INNLOGSETS(INNLOGSET_CALL)
432 parse_options(innduct_options, &argv);
437 if (!sitename) badusage("need site name argument");
439 if (*argv) remote_host= *argv++;
440 else remote_host= sitename;
442 if (*argv) badusage("too many non-option arguments");
446 int r= innconf_read(inndconffile);
447 if (!r) badusage("could not read inn.conf");
449 if (!remote_host) remote_host= sitename;
451 if (nocheck_thresh < 0 || nocheck_thresh > 100)
452 badusage("nocheck threshold percentage must be between 0..100");
453 nocheck_thresh *= 0.01;
455 if (nocheck_decay < 0.1)
456 badusage("nocheck decay articles must be at least 0.1");
457 nocheck_decay= pow(0.5, 1.0/nocheck_decay);
459 convert_to_periods_rndup(&reconnect_delay_periods);
460 convert_to_periods_rndup(&flushfail_retry_periods);
461 convert_to_periods_rndup(&backlog_retry_minperiods);
462 convert_to_periods_rndup(&backlog_spontrescan_periods);
463 convert_to_periods_rndup(&spontaneous_flush_periods);
464 convert_to_periods_rndup(&max_separated_periods);
465 convert_to_periods_rndup(&need_activity_periods);
466 convert_to_periods_rndup(&lowvol_periods);
468 if (max_bad_data_ratio < 0 || max_bad_data_ratio > 100)
469 badusage("bad input data ratio must be between 0..100");
470 max_bad_data_ratio *= 0.01;
473 path_run= innconf->pathrun;
475 if (!feedfile) feedfile= sitename;
476 if (!feedfile[0]) badusage("feed filename, if specified, must be nonempty");
477 if (path_ends_slash(feedfile))
478 feedfile= xasprintf("%s%s", feedfile, sitename);
479 if (feedfile[0] != '/')
480 feedfile= xasprintf("%s/%s", innconf->pathoutgoing, feedfile);
483 path_cli_dir= "innduct";
484 } else if (!path_cli[0] || !strcmp(path_cli,"none")) {
485 path_cli= 0; /* ok, don't then */
486 } else if (path_ends_slash(path_cli)) {
487 path_cli_dir= xasprintf("%.*s", strlen(path_cli)-1, path_cli);
490 path_cli= xasprintf("%s/%s", path_cli_dir, sitename);
492 if (max_queue_per_ipf<0)
493 max_queue_per_ipf= max_queue_per_conn * 2;
495 const char *feedfile_forbidden= "?*[~#";
497 while ((c= *feedfile_forbidden++))
498 if (strchr(feedfile, c))
499 badusage("feed filename may not contain metacharacter %c",c);
502 lowvol_perperiod= xcalloc(sizeof(*lowvol_perperiod), lowvol_periods);
503 for (i=0; i<lowvol_periods; i++) {
504 lowvol_perperiod[i]= lowvol_thresh;
505 lowvol_total += lowvol_thresh;
507 lowvol_total -= lowvol_thresh;
511 path_lock= xasprintf("%s_lock", feedfile);
512 path_flushing= xasprintf("%s_flushing", feedfile);
513 path_defer= xasprintf("%s_defer", feedfile);
514 path_dump= xasprintf("%s_dump", feedfile);
515 globpat_backlog= xasprintf("%s_backlog*", feedfile);
517 oop_source_sys *sysloop= oop_sys_new();
518 if (!sysloop) syscrash("could not create liboop event loop");
519 loop= (oop_source*)sysloop;
523 if (interactive < 1) {
524 for (i=3; i<255; i++)
525 /* do this now before we open syslog, etc. */
529 logv_prefix= xasprintf("%s| ", sitename);
530 if (interactive < 2) {
531 openlog("innduct",LOG_NDELAY|LOG_PID,LOG_NEWS);
535 if (interactive < 1) {
536 int null= open("/dev/null",O_RDWR);
537 if (null<0) sysdie("failed to open /dev/null");
541 xclose(null, "/dev/null original fd",0);
543 pid_t child1= xfork("daemonise first fork");
544 if (child1) _exit(0);
547 if (sid == -1) sysdie("setsid failed");
549 pid_t child2= xfork("daemonise second fork");
550 if (child2) _exit(0);
554 if (self_pid==-1) syscrash("getpid");
557 if (r) sysdie("could not chdir to pathrun %s", path_run);
566 r= SMsetup(SM_PREOPEN, &val); if (!r) warn("SMsetup SM_PREOPEN failed");
567 r= SMinit(); if (!r) die("storage manager initialisation (SMinit) failed");
569 if (interactive >= 2)
576 notice("filemon: suppressed by command line option, polling");
578 filemon_ok= filemon_method_init();
580 warn("filemon: no file monitoring available, polling");
583 every(filepoll_seconds,0,filepoll);
585 every(period_seconds,1,period);
591 void *run= oop_sys_run(sysloop);
592 assert(run == OOP_ERROR);
593 syscrash("event loop failed");