3 * tailing reliable realtime streaming feeder for inn
4 * statemc.c - state machine core (see README.states).
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.)
30 /* statemc_init initialises */
31 StateMachineState sms;
33 InputFile *main_input_file, *flushing_input_file, *backlog_input_file;
36 /* initialisation to 0 is good */
37 int until_connect, until_backlog_nextscan;
38 double accept_proportion;
39 int nocheck, nocheck_reported, in_child;
40 sig_atomic_t terminate_sig_flag;
43 static void startup_set_input_file(InputFile *f) {
44 assert(!main_input_file);
46 inputfile_reading_start(f);
49 void statemc_lock(void) {
51 struct stat stab, stabf;
54 lockfd= open(path_lock, O_CREAT|O_RDWR, 0600);
55 if (lockfd<0) sysdie("open lockfile %s", path_lock);
58 memset(&fl,0,sizeof(fl));
60 fl.l_whence= SEEK_SET;
61 int r= fcntl(lockfd, F_SETLK, &fl);
63 if (errno==EACCES || isewouldblock(errno)) {
64 if (quiet_multiple) exit(0);
65 die("another duct holds the lockfile");
67 sysdie("fcntl F_SETLK lockfile %s", path_lock);
70 xfstat_isreg(lockfd, &stabf, path_lock, "lockfile");
72 xlstat_isreg(path_lock, &stab, &lock_noent, "lockfile");
74 if (!lock_noent && samefile(&stab, &stabf))
77 xclose(lockfd, "stale lockfile ", path_lock);
80 FILE *lockfile= fdopen(lockfd, "w");
81 if (!lockfile) syscrash("fdopen lockfile");
83 int r= ftruncate(lockfd, 0);
84 if (r) syscrash("truncate lockfile to write new info");
86 if (fprintf(lockfile, "pid %ld\nsite %s\nfeedfile %s\nfqdn %s\n",
87 (unsigned long)self_pid,
88 sitename, feedfile, remote_host) == EOF ||
90 sysdie("write info to lockfile %s", path_lock);
92 dbg("startup: locked");
95 void statemc_init(void) {
96 struct stat stabdefer;
98 search_backlog_file();
101 xlstat_isreg(path_defer, &stabdefer, &defer_noent, "defer file");
103 dbg("startup: ductdefer ENOENT");
105 dbg("startup: ductdefer nlink=%ld", (long)stabdefer.st_nlink);
106 switch (stabdefer.st_nlink==1) {
108 open_defer(); /* so that we will later close it and rename it */
111 xunlink(path_defer, "stale defer file link"
112 " (presumably hardlink to backlog file)");
115 crash("defer file %s has unexpected link count %d",
116 path_defer, stabdefer.st_nlink);
120 struct stat stab_f, stab_d;
123 InputFile *file_d= open_input_file(path_flushing);
124 if (file_d) xfstat_isreg(file_d->fd, &stab_d, path_flushing,"flushing file");
126 xlstat_isreg(feedfile, &stab_f, &noent_f, "feedfile");
128 if (!noent_f && file_d && samefile(&stab_f, &stab_d)) {
129 dbg("startup: F==D => Hardlinked");
130 xunlink(feedfile, "feed file (during startup)"); /* => Moved */
135 dbg("startup: F ENOENT => Moved");
136 if (file_d) startup_set_input_file(file_d);
137 spawn_inndcomm_flush("feedfile missing at startup");
138 /* => Flushing, sms:=FLUSHING */
141 dbg("startup: F!=D => Separated");
142 startup_set_input_file(file_d);
143 flushing_input_file= main_input_file;
144 main_input_file= open_input_file(feedfile);
145 if (!main_input_file) crash("feedfile vanished during startup");
146 SMS(SEPARATED, max_separated_periods,
147 "found both old and current feed files");
149 dbg("startup: F exists, D ENOENT => Normal");
150 InputFile *file_f= open_input_file(feedfile);
151 if (!file_f) crash("feed file vanished during startup");
152 startup_set_input_file(file_f);
153 SMS(NORMAL, spontaneous_flush_periods, "normal startup");
158 void statemc_start_flush(const char *why) { /* Normal => Flushing */
159 assert(sms == sm_NORMAL);
161 dbg("starting flush (%s) (%lu >?= %lu) (%d)",
163 (unsigned long)(main_input_file ? main_input_file->offset : 0),
164 (unsigned long)target_max_feedfile_size,
167 int r= link(feedfile, path_flushing);
168 if (r) sysdie("link feedfile %s to flushing file %s",
169 feedfile, path_flushing);
172 xunlink(feedfile, "old feedfile link");
175 spawn_inndcomm_flush(why); /* => Flushing FLUSHING */
178 int trigger_flush_ok(const char *why) {
182 statemc_start_flush(why ? why : "periodic");
183 return 1; /* Normal => Flushing; => FLUSHING */
186 spawn_inndcomm_flush(why ? why : "retry");
187 return 1; /* Moved => Flushing; => FLUSHING */
191 warn("abandoning old feedfile after flush (%s), autodeferring",
192 why ? why : "took too long to complete");
193 assert(flushing_input_file);
194 autodefer_input_file(flushing_input_file);
202 void statemc_period_poll(void) {
203 if (!until_flush) return;
205 assert(until_flush>=0);
207 if (until_flush) return;
208 int ok= trigger_flush_ok(0);
212 static int inputfile_is_done(InputFile *ipf) {
214 if (ipf->inprogress) return 0; /* new article in the meantime */
215 if (ipf->rd) return 0; /* not had EOF */
219 static void notice_processed(InputFile *ipf, int completed,
220 const char *what, const char *spec) {
221 if (!ipf) return; /* allows preterminate to be lazy */
223 #define RCI_NOTHING(x) /* nothing */
224 #define RCI_TRIPLE_FMT(x) " " #x "=" RCI_TRIPLE_FMT_BASE
225 #define RCI_TRIPLE_VALS(x) , RCI_TRIPLE_VALS_BASE(ipf->counts, [RC_##x])
227 #define CNT(art,rc) (ipf->counts[art_##art][RC_##rc])
229 char *inprog= completed
230 ? xasprintf("%s","") /* GCC produces a stupid warning for printf("") ! */
231 : xasprintf(" inprogress=%ld", ipf->inprogress);
232 char *autodefer= ipf->autodefer >= 0
233 ? xasprintf(" autodeferred=%ld", ipf->autodefer)
234 : xasprintf("%s","");
236 info("%s %s%s read=%d (+bl=%d,+err=%d)%s%s"
237 " missing=%d offered=%d (ch=%d,nc=%d) accepted=%d (ch=%d,nc=%d)"
238 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_FMT)
240 completed?"completed":"processed", what, spec,
241 ipf->readcount_ok, ipf->readcount_blank, ipf->readcount_err,
242 inprog, autodefer, ipf->count_nooffer_missing,
243 CNT(Unchecked,sent) + CNT(Unsolicited,sent)
244 , CNT(Unchecked,sent), CNT(Unsolicited,sent),
245 CNT(Wanted,accepted) + CNT(Unsolicited,accepted)
246 , CNT(Wanted,accepted), CNT(Unsolicited,accepted)
247 RESULT_COUNTS(RCI_NOTHING, RCI_TRIPLE_VALS)
250 memset(ipf->counts, 0, sizeof(ipf->counts));
251 ipf->readcount_ok= ipf->readcount_blank=
252 ipf->readcount_err= ipf->count_nooffer_missing= 0;
260 void statemc_check_backlog_done(void) {
261 InputFile *ipf= backlog_input_file;
262 if (!inputfile_is_done(ipf)) return;
264 const char *slash= strrchr(ipf->path, '/');
265 const char *leaf= slash ? slash+1 : ipf->path;
266 const char *under= strchr(slash, '_');
267 const char *rest= under ? under+1 : leaf;
268 if (!strncmp(rest,"backlog",7)) rest += 7;
269 notice_processed(ipf,1,"backlog ",rest);
271 close_input_file(ipf);
272 if (unlink(ipf->path)) {
274 syscrash("could not unlink processed backlog file %s", ipf->path);
275 warn("backlog file %s vanished while we were reading it"
276 " so we couldn't remove it (but it's done now, anyway)",
280 backlog_input_file= 0;
281 search_backlog_file();
285 void statemc_check_flushing_done(void) {
286 InputFile *ipf= flushing_input_file;
287 if (!inputfile_is_done(ipf)) return;
289 assert(sms==sm_SEPARATED || sms==sm_DROPPING);
291 notice_processed(ipf,1,"feedfile","");
295 xunlink(path_flushing, "old flushing file");
297 close_input_file(flushing_input_file);
298 free(flushing_input_file);
299 flushing_input_file= 0;
301 if (sms==sm_SEPARATED) {
302 notice("flush complete");
303 SMS(NORMAL, spontaneous_flush_periods, "flush complete");
304 } else if (sms==sm_DROPPING) {
305 SMS(DROPPED, max_separated_periods, "old flush complete");
306 search_backlog_file();
307 notice("feed dropped, but will continue until backlog is finished");
311 static void *statemc_check_input_done(oop_source *lp, struct timeval now,
313 /* main input file may be idle but if so that's because
314 * we haven't got to it yet, but that doesn't mean it's really done */
315 statemc_check_flushing_done();
316 statemc_check_backlog_done();
320 void queue_check_input_done(void) {
321 loop->on_time(loop, OOP_TIME_NOW, statemc_check_input_done, 0);
324 void statemc_setstate(StateMachineState newsms, int periods,
325 const char *forlog, const char *why) {
327 until_flush= periods;
329 const char *xtra= "";
333 if (!main_input_file) xtra= "-ABSENT";
337 xtra= flushing_input_file->rd ? "-1" : "-2";
343 info("state %s%s[%d] %s",forlog,xtra,periods,why);
345 info("state %s%s %s",forlog,xtra,why);
349 /*========== flushing the feed ==========*/
351 pid_t inndcomm_child;
352 static int inndcomm_sentinel_fd;
354 static void *inndcomm_event(oop_source *lp, int fd, oop_event e, void *u) {
355 assert(inndcomm_child);
356 assert(fd == inndcomm_sentinel_fd);
357 int status= xwaitpid(&inndcomm_child, "inndcomm");
360 cancel_fd_read_except(fd);
361 xclose_perhaps(&fd, "inndcomm sentinel pipe",0);
362 inndcomm_sentinel_fd= 0;
364 assert(!flushing_input_file);
366 if (WIFEXITED(status)) {
367 switch (WEXITSTATUS(status)) {
369 case INNDCOMMCHILD_ESTATUS_FAIL:
372 case INNDCOMMCHILD_ESTATUS_NONESUCH:
373 notice("feed has been dropped by innd, finishing up");
374 flushing_input_file= main_input_file;
375 tailing_make_readable(flushing_input_file);
376 /* we probably previously returned EAGAIN from our fake read method
377 * when in fact we were at EOF, so signal another readable event
378 * so we actually see the EOF */
382 if (flushing_input_file) {
383 SMS(DROPPING, max_separated_periods,
384 "feed dropped by innd, but must finish last flush");
387 SMS(DROPPED, 0, "feed dropped by innd");
388 search_backlog_file();
394 flushing_input_file= main_input_file;
395 tailing_make_readable(flushing_input_file);
397 main_input_file= open_input_file(feedfile);
398 if (!main_input_file)
399 crash("flush succeeded but feedfile %s does not exist!"
400 " (this probably means feedfile does not correspond"
401 " to site %s in newsfeeds)", feedfile, sitename);
403 if (flushing_input_file) {
404 SMS(SEPARATED, max_separated_periods, "flush complete");
407 SMS(NORMAL, spontaneous_flush_periods, "recovery flush complete");
412 goto unexpected_exitstatus;
415 } else if (WIFSIGNALED(status) && WTERMSIG(status) == SIGALRM) {
416 warn("flush timed out trying to talk to innd");
419 unexpected_exitstatus:
420 report_child_status("inndcomm child", status);
424 SMS(FLUSHFAILED, flushfail_retry_periods, "flush failed, will retry");
428 static void inndcommfail(const char *what) {
429 syswarn("error communicating with innd: %s failed: %s", what, ICCfailure);
430 exit(INNDCOMMCHILD_ESTATUS_FAIL);
433 void spawn_inndcomm_flush(const char *why) { /* Moved => Flushing */
436 notice("flushing %s",why);
438 assert(sms==sm_NORMAL || sms==sm_FLUSHFAILED);
439 assert(!inndcomm_child);
440 assert(!inndcomm_sentinel_fd);
442 if (pipe(pipefds)) sysdie("create pipe for inndcomm child sentinel");
444 inndcomm_child= xfork("inndcomm child");
446 if (!inndcomm_child) {
447 const char *flushargv[2]= { sitename, 0 };
451 xclose(pipefds[0], "(in child) inndcomm sentinel parent's end",0);
452 /* parent spots the autoclose of pipefds[1] when we die or exit */
454 if (simulate_flush>=0) {
455 warn("SIMULATING flush child status %d", simulate_flush);
456 if (simulate_flush>128) raise(simulate_flush-128);
457 else exit(simulate_flush);
460 alarm(inndcomm_flush_timeout);
461 r= ICCopen(); if (r) inndcommfail("connect");
462 r= ICCcommand('f',flushargv,&reply); if (r<0) inndcommfail("transmit");
463 if (!r) exit(0); /* yay! */
465 if (!strcmp(reply, "1 No such site")) exit(INNDCOMMCHILD_ESTATUS_NONESUCH);
466 syswarn("innd ctlinnd flush failed: innd said %s", reply);
467 exit(INNDCOMMCHILD_ESTATUS_FAIL);
472 xclose(pipefds[1], "inndcomm sentinel child's end",0);
473 inndcomm_sentinel_fd= pipefds[0];
474 assert(inndcomm_sentinel_fd);
475 on_fd_read_except(inndcomm_sentinel_fd, inndcomm_event);
477 SMS(FLUSHING, 0, why);
480 /*---------- shutdown and signal handling ----------*/
482 void preterminate(void) {
483 if (in_child) return;
487 void showstats(void) {
488 notice_processed(main_input_file,0,"feedfile","");
489 notice_processed(flushing_input_file,0,"flushing","");
490 if (backlog_input_file)
491 notice_processed(backlog_input_file,0, "backlog file ",
492 backlog_input_file->path);
493 until_stats_log= stats_log_periods;
496 static int signal_self_pipe[2];
498 static void *sigarrived_event(oop_source *lp, int fd, oop_event e, void *u) {
499 assert(fd=signal_self_pipe[0]);
501 int r= read(signal_self_pipe[0], buf, sizeof(buf));
502 if (r<0 && !isewouldblock(errno))
503 syscrash("failed to read signal self pipe");
504 if (r==0) crash("eof on signal self pipe");
505 if (terminate_sig_flag) {
507 notice("terminating (%s)", strsignal(terminate_sig_flag));
508 raise_default(terminate_sig_flag);
513 static void sigarrived_handler(int signum) {
518 if (!terminate_sig_flag) terminate_sig_flag= signum;
523 write(signal_self_pipe[1],&x,1);
526 void init_signals(void) {
527 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
528 syscrash("could not ignore SIGPIPE");
530 if (pipe(signal_self_pipe)) sysdie("create self-pipe for signals");
532 xsetnonblock(signal_self_pipe[0],1);
533 xsetnonblock(signal_self_pipe[1],1);
536 memset(&sa,0,sizeof(sa));
537 sa.sa_handler= sigarrived_handler;
538 sa.sa_flags= SA_RESTART;
539 xsigaction(SIGTERM,&sa);
540 xsigaction(SIGINT,&sa);
542 on_fd_read_except(signal_self_pipe[0], sigarrived_event);