]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.c
2172e823b02e85f8d1fdf6adbb3ba63285e73a3f
[libucw.git] / ucw / mainloop.c
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2006 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #undef LOCAL_DEBUG
11
12 #include "ucw/lib.h"
13 #include "ucw/mainloop.h"
14
15 #include <stdio.h>
16 #include <string.h>
17 #include <unistd.h>
18 #include <signal.h>
19 #include <fcntl.h>
20 #include <errno.h>
21 #include <time.h>
22 #include <sys/poll.h>
23 #include <sys/wait.h>
24 #include <sys/time.h>
25
26 timestamp_t main_now;
27 ucw_time_t main_now_seconds;
28 timestamp_t main_idle_time;
29 uns main_shutdown;
30
31 clist main_timer_list, main_file_list, main_hook_list, main_process_list;
32 static uns main_file_cnt;
33 static uns main_poll_table_obsolete, main_poll_table_size;
34 static struct pollfd *main_poll_table;
35 static uns main_sigchld_set_up;
36 static volatile sig_atomic_t chld_received = 0;
37
38 #ifdef CONFIG_LINUX
39 // On Linux, O_CLOEXEC flag is available and we can get around the race
40 // condition of poll().
41 #define USE_SELF_PIPE
42 static int sig_pipe_recv, sig_pipe_send;
43 #endif
44
45 void
46 main_get_time(void)
47 {
48   struct timeval tv;
49   gettimeofday(&tv, NULL);
50   main_now_seconds = tv.tv_sec;
51   main_now = (timestamp_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
52   // DBG("It's %lld o'clock", (long long) main_now);
53 }
54
55 void
56 main_init(void)
57 {
58   DBG("MAIN: Initializing");
59   clist_init(&main_timer_list);
60   clist_init(&main_file_list);
61   clist_init(&main_hook_list);
62   clist_init(&main_process_list);
63   main_file_cnt = 0;
64   main_poll_table_obsolete = 1;
65   main_get_time();
66 }
67
68 void
69 timer_add(struct main_timer *tm, timestamp_t expires)
70 {
71   if (expires)
72     DBG("MAIN: Setting timer %p (expire at now+%lld)", tm, (long long)(expires-main_now));
73   else
74     DBG("MAIN: Clearing timer %p", tm);
75   if (tm->expires)
76     clist_remove(&tm->n);
77   tm->expires = expires;
78   if (expires)
79     {
80       cnode *t = main_timer_list.head.next;
81       while (t != &main_timer_list.head && ((struct main_timer *) t)->expires < expires)
82         t = t->next;
83       clist_insert_before(&tm->n, t);
84     }
85 }
86
87 void
88 timer_del(struct main_timer *tm)
89 {
90   timer_add(tm, 0);
91 }
92
93 static void
94 file_timer_expired(struct main_timer *tm)
95 {
96   struct main_file *fi = tm->data;
97   timer_del(&fi->timer);
98   if (fi->error_handler)
99     fi->error_handler(fi, MFERR_TIMEOUT);
100 }
101
102 void
103 file_add(struct main_file *fi)
104 {
105   DBG("MAIN: Adding file %p (fd=%d)", fi, fi->fd);
106   ASSERT(!fi->n.next);
107   clist_add_tail(&main_file_list, &fi->n);
108   fi->timer.handler = file_timer_expired;
109   fi->timer.data = fi;
110   main_file_cnt++;
111   main_poll_table_obsolete = 1;
112   if (fcntl(fi->fd, F_SETFL, O_NONBLOCK) < 0)
113     msg(L_ERROR, "Error setting fd %d to non-blocking mode: %m. Keep fingers crossed.", fi->fd);
114 }
115
116 void
117 file_chg(struct main_file *fi)
118 {
119   struct pollfd *p = fi->pollfd;
120   if (p)
121     {
122       p->events = 0;
123       if (fi->read_handler)
124         p->events |= POLLIN | POLLHUP | POLLERR;
125       if (fi->write_handler)
126         p->events |= POLLOUT | POLLERR;
127     }
128 }
129
130 void
131 file_del(struct main_file *fi)
132 {
133   DBG("MAIN: Deleting file %p (fd=%d)", fi, fi->fd);
134   ASSERT(fi->n.next);
135   timer_del(&fi->timer);
136   clist_remove(&fi->n);
137   main_file_cnt--;
138   main_poll_table_obsolete = 1;
139   fi->n.next = fi->n.prev = NULL;
140 }
141
142 static int
143 file_read_handler(struct main_file *fi)
144 {
145   while (fi->rpos < fi->rlen)
146     {
147       int l = read(fi->fd, fi->rbuf + fi->rpos, fi->rlen - fi->rpos);
148       DBG("MAIN: FD %d: read %d", fi->fd, l);
149       if (l < 0)
150         {
151           if (errno != EINTR && errno != EAGAIN && fi->error_handler)
152             fi->error_handler(fi, MFERR_READ);
153           return 0;
154         }
155       else if (!l)
156         break;
157       fi->rpos += l;
158     }
159   DBG("MAIN: FD %d done read %d of %d", fi->fd, fi->rpos, fi->rlen);
160   fi->read_handler = NULL;
161   file_chg(fi);
162   fi->read_done(fi);
163   return 1;
164 }
165
166 static int
167 file_write_handler(struct main_file *fi)
168 {
169   while (fi->wpos < fi->wlen)
170     {
171       int l = write(fi->fd, fi->wbuf + fi->wpos, fi->wlen - fi->wpos);
172       DBG("MAIN: FD %d: write %d", fi->fd, l);
173       if (l < 0)
174         {
175           if (errno != EINTR && errno != EAGAIN && fi->error_handler)
176             fi->error_handler(fi, MFERR_WRITE);
177           return 0;
178         }
179       fi->wpos += l;
180     }
181   DBG("MAIN: FD %d done write %d", fi->fd, fi->wpos);
182   fi->write_handler = NULL;
183   file_chg(fi);
184   fi->write_done(fi);
185   return 1;
186 }
187
188 void
189 file_read(struct main_file *fi, void *buf, uns len)
190 {
191   ASSERT(fi->n.next);
192   if (len)
193     {
194       fi->read_handler = file_read_handler;
195       fi->rbuf = buf;
196       fi->rpos = 0;
197       fi->rlen = len;
198     }
199   else
200     {
201       fi->read_handler = NULL;
202       fi->rbuf = NULL;
203       fi->rpos = fi->rlen = 0;
204     }
205   file_chg(fi);
206 }
207
208 void
209 file_write(struct main_file *fi, void *buf, uns len)
210 {
211   ASSERT(fi->n.next);
212   if (len)
213     {
214       fi->write_handler = file_write_handler;
215       fi->wbuf = buf;
216       fi->wpos = 0;
217       fi->wlen = len;
218     }
219   else
220     {
221       fi->write_handler = NULL;
222       fi->wbuf = NULL;
223       fi->wpos = fi->wlen = 0;
224     }
225   file_chg(fi);
226 }
227
228 void
229 file_set_timeout(struct main_file *fi, timestamp_t expires)
230 {
231   ASSERT(fi->n.next);
232   timer_add(&fi->timer, expires);
233 }
234
235 void
236 file_close_all(void)
237 {
238   CLIST_FOR_EACH(struct main_file *, f, main_file_list)
239     close(f->fd);
240 }
241
242 void
243 hook_add(struct main_hook *ho)
244 {
245   DBG("MAIN: Adding hook %p", ho);
246   ASSERT(!ho->n.next);
247   clist_add_tail(&main_hook_list, &ho->n);
248 }
249
250 void
251 hook_del(struct main_hook *ho)
252 {
253   DBG("MAIN: Deleting hook %p", ho);
254   ASSERT(ho->n.next);
255   clist_remove(&ho->n);
256   ho->n.next = ho->n.prev = NULL;
257 }
258
259 #ifdef USE_SELF_PIPE
260 static void
261 main_sigchld_handler(int x UNUSED)
262 {
263   int old_errno = errno;
264   DBG("SIGCHLD received");
265   chld_received = 1;
266   ssize_t result;
267   while((result = write(sig_pipe_send, "c", 1)) == -1 && errno == EINTR);
268   if(result == -1 && errno != EAGAIN)
269     msg(L_SIGHANDLER|L_ERROR, "Could not write to self-pipe: %m");
270   errno = old_errno;
271 }
272
273 static int
274 dummy_read_handler(struct main_file *mp)
275 {
276   char buffer[1024];
277   ssize_t result = read(mp->fd, buffer, 1024);
278   if(result == -1 && errno != EAGAIN)
279     msg(L_ERROR, "Could not read from selfpipe: %m");
280   file_chg(mp);
281   return result == 1024;
282 }
283
284 static void
285 pipe_configure(int fd)
286 {
287   int flags;
288   if((flags = fcntl(fd, F_GETFL)) == -1 || fcntl(fd, F_SETFL, flags|O_NONBLOCK))
289     die("Could not set file descriptor %d to non-blocking: %m", fd);
290   if((flags = fcntl(fd, F_GETFD)) == -1 || fcntl(fd, F_SETFD, flags|O_CLOEXEC))
291     die("Could not set file descriptor %d to close-on-exec: %m", fd);
292 }
293 #else
294 static void
295 main_sigchld_handler(int x UNUSED)
296 {
297   DBG("SIGCHLD received");
298 }
299 #endif
300
301 void
302 process_add(struct main_process *mp)
303 {
304   DBG("MAIN: Adding process %p (pid=%d)", mp, mp->pid);
305   ASSERT(!mp->n.next);
306   ASSERT(mp->handler);
307   clist_add_tail(&main_process_list, &mp->n);
308   if (!main_sigchld_set_up)
309     {
310 #ifdef USE_SELF_PIPE
311       int pipe_result[2];
312       if(pipe(pipe_result) == -1)
313         die("Could not create selfpipe:%m");
314       pipe_configure(pipe_result[0]);
315       pipe_configure(pipe_result[1]);
316       sig_pipe_recv = pipe_result[0];
317       sig_pipe_send = pipe_result[1];
318       static struct main_file self_pipe;
319       self_pipe = (struct main_file) {
320         .fd = sig_pipe_recv,
321         .read_handler = dummy_read_handler
322       };
323       file_add(&self_pipe);
324 #endif
325       struct sigaction sa;
326       bzero(&sa, sizeof(sa));
327       sa.sa_handler = main_sigchld_handler;
328       sa.sa_flags = SA_NOCLDSTOP | SA_RESTART;
329       sigaction(SIGCHLD, &sa, NULL);
330       main_sigchld_set_up = 1;
331       chld_received = 1; // The signal may have come before the handler
332     }
333 }
334
335 void
336 process_del(struct main_process *mp)
337 {
338   DBG("MAIN: Deleting process %p (pid=%d)", mp, mp->pid);
339   ASSERT(mp->n.next);
340   clist_remove(&mp->n);
341   mp->n.next = NULL;
342 }
343
344 int
345 process_fork(struct main_process *mp)
346 {
347   pid_t pid = fork();
348   if (pid < 0)
349     {
350       DBG("MAIN: Fork failed");
351       mp->status = -1;
352       format_exit_status(mp->status_msg, -1);
353       mp->handler(mp);
354       return 1;
355     }
356   else if (!pid)
357     return 0;
358   else
359     {
360       DBG("MAIN: Forked process %d", (int) pid);
361       mp->pid = pid;
362       process_add(mp);
363       return 1;
364     }
365 }
366
367 void
368 main_debug(void)
369 {
370 #ifdef CONFIG_DEBUG
371   msg(L_DEBUG, "### Main loop status on %lld", (long long)main_now);
372   msg(L_DEBUG, "\tActive timers:");
373   struct main_timer *tm;
374   CLIST_WALK(tm, main_timer_list)
375     msg(L_DEBUG, "\t\t%p (expires %lld, data %p)", tm, (long long)(tm->expires ? tm->expires-main_now : 999999), tm->data);
376   struct main_file *fi;
377   msg(L_DEBUG, "\tActive files:");
378   CLIST_WALK(fi, main_file_list)
379     msg(L_DEBUG, "\t\t%p (fd %d, rh %p, wh %p, eh %p, expires %lld, data %p)",
380         fi, fi->fd, fi->read_handler, fi->write_handler, fi->error_handler,
381         (long long)(fi->timer.expires ? fi->timer.expires-main_now : 999999), fi->data);
382   msg(L_DEBUG, "\tActive hooks:");
383   struct main_hook *ho;
384   CLIST_WALK(ho, main_hook_list)
385     msg(L_DEBUG, "\t\t%p (func %p, data %p)", ho, ho->handler, ho->data);
386   msg(L_DEBUG, "\tActive processes:");
387   struct main_process *pr;
388   CLIST_WALK(pr, main_process_list)
389     msg(L_DEBUG, "\t\t%p (pid %d, data %p)", pr, pr->pid, pr->data);
390 #endif
391 }
392
393 static void
394 main_rebuild_poll_table(void)
395 {
396   struct main_file *fi;
397   if (main_poll_table_size < main_file_cnt)
398     {
399       if (main_poll_table)
400         xfree(main_poll_table);
401       else
402         main_poll_table_size = 1;
403       while (main_poll_table_size < main_file_cnt)
404         main_poll_table_size *= 2;
405       main_poll_table = xmalloc(sizeof(struct pollfd) * main_poll_table_size);
406     }
407   struct pollfd *p = main_poll_table;
408   DBG("MAIN: Rebuilding poll table: %d of %d entries set", main_file_cnt, main_poll_table_size);
409   CLIST_WALK(fi, main_file_list)
410     {
411       p->fd = fi->fd;
412       fi->pollfd = p++;
413       file_chg(fi);
414     }
415   main_poll_table_obsolete = 0;
416 }
417
418 void
419 main_loop(void)
420 {
421   DBG("MAIN: Entering main_loop");
422   ASSERT(main_timer_list.head.next);
423
424   struct main_file *fi;
425   struct main_hook *ho;
426   struct main_timer *tm;
427   struct main_process *pr;
428   cnode *tmp;
429
430   main_get_time();
431   for (;;)
432     {
433       timestamp_t wake = main_now + 1000000000;
434       while ((tm = clist_head(&main_timer_list)) && tm->expires <= main_now)
435         {
436           DBG("MAIN: Timer %p expired at now-%lld", tm, (long long)(main_now - tm->expires));
437           tm->handler(tm);
438         }
439       int hook_min = HOOK_RETRY;
440       int hook_max = HOOK_SHUTDOWN;
441       CLIST_WALK_DELSAFE(ho, main_hook_list, tmp)
442         {
443           DBG("MAIN: Hook %p", ho);
444           int ret = ho->handler(ho);
445           hook_min = MIN(hook_min, ret);
446           hook_max = MAX(hook_max, ret);
447         }
448       if (hook_min == HOOK_SHUTDOWN ||
449           hook_min == HOOK_DONE && hook_max == HOOK_DONE ||
450           main_shutdown)
451         {
452           DBG("MAIN: Shut down by %s", main_shutdown ? "main_shutdown" : "a hook");
453           return;
454         }
455       if (hook_max == HOOK_RETRY)
456         wake = 0;
457       if (main_poll_table_obsolete)
458         main_rebuild_poll_table();
459 #ifndef USE_SELF_PIPE
460       // We don't have a reliable flag without the self-pipe.
461       chld_received = 1;
462 #endif
463       if (chld_received && !clist_empty(&main_process_list))
464         {
465           int stat;
466           pid_t pid;
467           wake = MIN(wake, main_now + 10000);
468           chld_received = 0;
469           while ((pid = waitpid(-1, &stat, WNOHANG)) > 0)
470             {
471               DBG("MAIN: Child %d exited with status %x", pid, stat);
472               CLIST_WALK(pr, main_process_list)
473                 if (pr->pid == pid)
474                   {
475                     pr->status = stat;
476                     process_del(pr);
477                     format_exit_status(pr->status_msg, pr->status);
478                     DBG("MAIN: Calling process exit handler");
479                     pr->handler(pr);
480                     break;
481                   }
482               wake = 0;
483             }
484         }
485       if ((tm = clist_head(&main_timer_list)) && tm->expires < wake)
486         wake = tm->expires;
487       main_get_time();
488       int timeout = (wake ? wake - main_now : 0);
489       DBG("MAIN: Poll for %d fds and timeout %d ms", main_file_cnt, timeout);
490       int p = poll(main_poll_table, main_file_cnt, timeout);
491       timestamp_t old_now = main_now;
492       main_get_time();
493       main_idle_time += main_now - old_now;
494       if (p > 0)
495         {
496           struct pollfd *p = main_poll_table;
497           CLIST_WALK(fi, main_file_list)
498             {
499               if (p->revents & (POLLIN | POLLHUP | POLLERR))
500                 {
501                   do
502                     DBG("MAIN: Read event on fd %d", p->fd);
503                   while (fi->read_handler && fi->read_handler(fi) && !main_poll_table_obsolete);
504                   if (main_poll_table_obsolete) /* File entries have been inserted or deleted => better not risk continuing to nowhere */
505                     break;
506                 }
507               if (p->revents & (POLLOUT | POLLERR))
508                 {
509                   do
510                     DBG("MAIN: Write event on fd %d", p->fd);
511                   while (fi->write_handler && fi->write_handler(fi) && !main_poll_table_obsolete);
512                   if (main_poll_table_obsolete)
513                     break;
514                 }
515               p++;
516             }
517         }
518     }
519 }
520
521 #ifdef TEST
522
523 static struct main_process mp;
524 static struct main_file fin, fout;
525 static struct main_hook hook;
526 static struct main_timer tm;
527
528 static byte rb[16];
529
530 static void dread(struct main_file *fi)
531 {
532   if (fi->rpos < fi->rlen)
533     {
534       msg(L_INFO, "Read EOF");
535       file_del(fi);
536     }
537   else
538     {
539       msg(L_INFO, "Read done");
540       file_read(fi, rb, sizeof(rb));
541     }
542 }
543
544 static void derror(struct main_file *fi, int cause)
545 {
546   msg(L_INFO, "Error: %m !!! (cause %d)", cause);
547   file_del(fi);
548 }
549
550 static void dwrite(struct main_file *fi UNUSED)
551 {
552   msg(L_INFO, "Write done");
553 }
554
555 static int dhook(struct main_hook *ho UNUSED)
556 {
557   msg(L_INFO, "Hook called");
558   return 0;
559 }
560
561 static void dtimer(struct main_timer *tm)
562 {
563   msg(L_INFO, "Timer tick");
564   timer_add(tm, main_now + 10000);
565 }
566
567 static void dentry(void)
568 {
569   msg(L_INFO, "*** SUBPROCESS START ***");
570   sleep(2);
571   msg(L_INFO, "*** SUBPROCESS FINISH ***");
572   exit(0);
573 }
574
575 static void dexit(struct main_process *pr)
576 {
577   msg(L_INFO, "Subprocess %d exited with status %x", pr->pid, pr->status);
578 }
579
580 int
581 main(void)
582 {
583   log_init(NULL);
584   main_init();
585
586   fin.fd = 0;
587   fin.read_done = dread;
588   fin.error_handler = derror;
589   file_add(&fin);
590   file_read(&fin, rb, sizeof(rb));
591
592   fout.fd = 1;
593   fout.write_done = dwrite;
594   fout.error_handler = derror;
595   file_add(&fout);
596   file_write(&fout, "Hello, world!\n", 14);
597
598   hook.handler = dhook;
599   hook_add(&hook);
600
601   tm.handler = dtimer;
602   timer_add(&tm, main_now + 1000);
603
604   mp.handler = dexit;
605   if (!process_fork(&mp))
606     dentry();
607
608   main_debug();
609
610   main_loop();
611   msg(L_INFO, "Finished.");
612 }
613
614 #endif