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