]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.h
Main: Allow main_loop() to be re-entered after shutdown
[libucw.git] / ucw / mainloop.h
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2011 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 #ifndef _UCW_MAINLOOP_H
11 #define _UCW_MAINLOOP_H
12
13 #include "ucw/clists.h"
14
15 #include <signal.h>
16
17 /***
18  * [[basic]]
19  * Basic operations
20  * ----------------
21  *
22  * First of all, let us take a look at the basic operations with main loop contexts.
23  ***/
24
25 /** The main loop context **/
26 struct main_context {
27   timestamp_t now;                      /* [*] Current time in milliseconds since the UNIX epoch. See @main_get_time(). */
28   ucw_time_t now_seconds;               /* [*] Current time in seconds since the epoch. */
29   timestamp_t idle_time;                /* [*] Total time in milliseconds spent by waiting for events. */
30   uns shutdown;                         /* [*] Setting this to nonzero forces the @main_loop() function to terminate. */
31   clist file_list;
32   clist file_active_list;
33   clist hook_list;
34   clist hook_done_list;
35   clist process_list;
36   clist signal_list;
37   uns file_cnt;
38 #ifdef CONFIG_UCW_EPOLL
39   int epoll_fd;                         /* File descriptor used for epoll */
40   struct epoll_event *epoll_events;
41   clist file_recalc_list;
42 #else
43   uns poll_table_obsolete;
44   struct pollfd *poll_table;
45   struct main_file **poll_file_table;
46 #endif
47   struct main_timer **timer_table;      /* Growing array containing the heap of timers */
48   sigset_t want_signals;
49   int sig_pipe_send;
50   int sig_pipe_recv;
51   struct main_file *sig_pipe_file;
52   struct main_signal *sigchld_handler;
53 };
54
55 struct main_context *main_new(void);            /** Create a new context. **/
56
57 /**
58  * Delete a context, assuming it does have any event handlers attached. Does nothing if @m is NULL.
59  * It is allowed to call @main_delete() from a hook function of the same context, but you must
60  * never return to the main loop -- e.g., you can exit() the process instead.
61  **/
62 void main_delete(struct main_context *m);
63
64 /**
65  * Delete a context. If there are any event handlers attached, they are deactivated
66  * (but the responsibility to free the memory there were allocated from lies upon you).
67  * If there are any file handlers, the corresponding file descriptors are closed.
68  **/
69 void main_destroy(struct main_context *m);
70
71 /** Switch the current context of the calling thread. Returns the previous current context. **/
72 struct main_context *main_switch_context(struct main_context *m);
73
74 /** Return the current context. Dies if there is none or if the context has been deleted. **/
75 struct main_context *main_current(void);
76
77 /** Initialize the main loop module and create a top-level context. **/
78 void main_init(void);
79
80 /** Deinitialize the main loop module, calling @main_delete() on the top-level context. **/
81 void main_cleanup(void);
82
83 /**
84  * Deinitialize the main loop module, calling @main_destroy() on the top-level context.
85  * This is especially useful in a freshly forked-off child process.
86  **/
87 void main_teardown(void);
88
89 /**
90  * Start the event loop on the current context.
91  * It will watch the provided objects and call callbacks.
92  * Terminates when someone calls @main_shut_down(),
93  * or when all <<hook,hooks>> return <<enum_main_hook_return,`HOOK_DONE`>>
94  * or at last one <<hook,hook>> returns <<enum_main_hook_return,`HOOK_SHUTDOWN`>>.
95  **/
96 void main_loop(void);
97
98 /** Ask the main loop to terminate at the nearest occasion. **/
99 static inline void main_shut_down(void)
100 {
101   main_current()->shutdown = 1;
102 }
103
104 /**
105  * Show the current state of a given context (use @main_debug() for the current context).
106  * Available only if LibUCW has been compiled with `CONFIG_DEBUG`.
107  **/
108 void main_debug_context(struct main_context *m);
109
110 static inline void
111 main_debug(void)
112 {
113   main_debug_context(main_current());
114 }
115
116 /***
117  * [[time]]
118  * Timers
119  * ------
120  *
121  * The event loop provides the current time, measured as a 64-bit number
122  * of milliseconds since the system epoch (represented in the type `timestamp_t`).
123  *
124  * You can also register timers, which call a handler function at a given moment.
125  * The handler function must either call @timer_del() to delete the timer, or call
126  * @timer_add() with a different expiration time.
127  ***/
128
129 /**
130  * Get the current timestamp cached in the current context. It is refreshed in every
131  * iteration of the event loop, or explicitly by calling @main_get_time().
132  **/
133 static inline timestamp_t main_get_now(void)
134 {
135   return main_current()->now;
136 }
137
138 /** An analog of @main_get_now() returning the number of seconds since the system epoch. **/
139 static inline ucw_time_t main_get_now_seconds(void)
140 {
141   return main_current()->now_seconds;
142 }
143
144 /**
145  * This is a description of a timer.
146  * You define the handler function and possibly user-defined data you wish
147  * to pass to the handler, and then you invoke @timer_add().
148  **/
149 struct main_timer {
150   cnode n;
151   timestamp_t expires;
152   uns index;
153   void (*handler)(struct main_timer *tm);       /* [*] Function to be called when the timer expires. */
154   void *data;                                   /* [*] Data for use by the handler */
155 };
156
157 /**
158  * Add a new timer into the main loop to be watched and called
159  * when it expires. It can also be used to modify an already running
160  * timer. It is permitted (and usual) to call this function from the
161  * timer's handler itself if you want the timer to trigger again.
162  *
163  * The @expire parameter is absolute, use @timer_add_rel() for a relative version.
164  **/
165 void timer_add(struct main_timer *tm, timestamp_t expires);
166
167 /** Like @timer_add(), but the expiration time is relative to the current time. **/
168 void timer_add_rel(struct main_timer *tm, timestamp_t expires_delta);
169
170 /**
171  * Removes a timer from the active ones. It is permitted (and common) to call
172  * this function from the timer's handler itself if you want to deactivate
173  * the timer.
174  **/
175 void timer_del(struct main_timer *tm);
176
177 /**
178  * Forces refresh of the current timestamp cached in the active context.
179  * You usually do not need to call this, since it is called every time the
180  * loop polls for events. It is here if you need extra precision or some of the
181  * hooks takes a long time.
182  **/
183 void main_get_time(void);
184
185 /** Show current state of a timer. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
186 void timer_debug(struct main_timer *tm);
187
188 /***
189  * [[file]]
190  * Activity on file descriptors
191  * ----------------------------
192  *
193  * You can ask the main loop to watch a set of file descriptors for activity.
194  * (This is a generalization of the select() and poll() system calls. Internally,
195  * it uses either poll() or the more efficient epoll().)
196  *
197  * You create a <<struct_main_file,`struct main_file`>>, fill in a file descriptor
198  * and pointers to handler functions to be called when the descriptor becomes
199  * ready for reading and/or writing, and call @file_add(). When you need to
200  * modify the handlers (e.g., to set them to NULL if you are no longer interested
201  * in a given event), you should call @file_chg() to notify the main loop about
202  * the changes.
203  *
204  * From within the handler functions, you are allowed to call @file_chg() and even
205  * @file_del().
206  *
207  * The return value of a handler function should be either <<enum_main_hook_return,`HOOK_RETRY`>>
208  * or <<enum_main_hook_return,`HOOK_IDLE`>>. <<enum_main_hook_return,`HOOK_RETRY`>>
209  * signals that the function would like to consume more data immediately
210  * (i.e., it wants to be called again soon, but the event loop can postpone it after
211  * processing other events to avoid starvation). <<enum_main_hook_return,`HOOK_IDLE`>>
212  * tells that the handler wants to be called when the descriptor becomes ready again.
213  *
214  * For backward compatibility, 0 can be used instead of <<enum_main_hook_return,`HOOK_IDLE`>>
215  * and 1 for <<enum_main_hook_return,`HOOK_RETRY`>>.
216  *
217  * If you want to read/write fixed-size blocks of data asynchronously, the
218  * <<blockio,Asynchronous block I/O>> interface could be more convenient.
219  ***/
220
221 /**
222  * This structure describes a file descriptor to be watched and the handlers
223  * to be called when the descriptor is ready for reading and/or writing.
224  **/
225 struct main_file {
226   cnode n;
227   int fd;                                       /* [*] File descriptor */
228   int (*read_handler)(struct main_file *fi);    /* [*] To be called when ready for reading/writing; must call file_chg() afterwards */
229   int (*write_handler)(struct main_file *fi);
230   void *data;                                   /* [*] Data for use by the handlers */
231   uns events;
232 #ifdef CONFIG_UCW_EPOLL
233   uns last_want_events;
234 #else
235   struct pollfd *pollfd;
236 #endif
237 };
238
239 /**
240  * Insert a <<struct_main_file,`main_file`>> structure into the main loop to be
241  * watched for activity. You can call this at any time, even inside a handler
242  * (of course for a different file descriptor than the one of the handler).
243  *
244  * The file descriptor is automatically set to the non-blocking mode.
245  **/
246 void file_add(struct main_file *fi);
247
248 /**
249  * Tell the main loop that the file structure has changed. Call it whenever you
250  * change any of the handlers.
251  *
252  * Can be called only on active files (only the ones added by @file_add()).
253  **/
254 void file_chg(struct main_file *fi);
255
256 /**
257  * Removes a file from the watched set. If you want to close a descriptor,
258  * please use this function first.
259  *
260  * Can be called from a handler.
261  **/
262 void file_del(struct main_file *fi);
263
264 /** Show current state of a file. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
265 void file_debug(struct main_file *fi);
266
267 /***
268  * [[blockio]]
269  * Asynchronous block I/O
270  * ----------------------
271  *
272  * If you are reading or writing fixed-size blocks of data, you can let the
273  * block I/O interface handle the boring routine of handling partial reads
274  * and writes for you.
275  *
276  * You just create <<struct_main_block_io,`struct main_block_io`>> and call
277  * @block_io_add() on it, which sets up some <<struct_main_file,`main_file`>>s internally.
278  * Then you can just call @block_io_read() or @block_io_write() to ask for
279  * reading or writing of a given block. When the operation is finished,
280  * your handler function is called.
281  *
282  * Additionally, the block I/O is equipped with a timer, which can be used
283  * to detect communication timeouts. The timer is not touched internally
284  * (except that it gets added and deleted at the right places), feel free
285  * to adjust it from your handler functions by @block_io_set_timeout().
286  * When the timer expires, the error handler is automatically called with
287  * <<enum_block_io_err_cause,`BIO_ERR_TIMEOUT`>>.
288  ***/
289
290 /** The block I/O structure. **/
291 struct main_block_io {
292   struct main_file file;
293   byte *rbuf;                                   /* Read/write pointers for use by file_read/write */
294   uns rpos, rlen;
295   byte *wbuf;
296   uns wpos, wlen;
297   void (*read_done)(struct main_block_io *bio); /* [*] Called when file_read is finished; rpos < rlen if EOF */
298   void (*write_done)(struct main_block_io *bio);        /* [*] Called when file_write is finished */
299   void (*error_handler)(struct main_block_io *bio, int cause);  /* [*] Handler to call on errors */
300   struct main_timer timer;
301   void *data;                                   /* [*] Data for use by the handlers */
302 };
303
304 /** Activate a block I/O structure. **/
305 void block_io_add(struct main_block_io *bio, int fd);
306
307 /** Deactivate a block I/O structure. **/
308 void block_io_del(struct main_block_io *bio);
309
310 /**
311  * Specifies when or why an error happened. This is passed to the error handler.
312  * `errno` is still set to the original source of error. The only exception
313  * is `BIO_ERR_TIMEOUT`, in which case `errno` is not set and the only possible
314  * cause of it is timeout of the timer associated with the block_io
315  * (see @block_io_set_timeout()).
316  **/
317 enum block_io_err_cause {
318   BIO_ERR_READ,
319   BIO_ERR_WRITE,
320   BIO_ERR_TIMEOUT
321 };
322
323 /**
324  * Ask the main loop to read @len bytes of data from @bio into @buf.
325  * It cancels any previous unfinished read requested in this way.
326  *
327  * When the read is done, the read_done() handler is called. If an EOF occurred,
328  * `rpos < rlen` (eg. not all data were read).
329  *
330  * Can be called from a handler.
331  *
332  * You can use a call with zero @len to cancel the current read, but all read data
333  * will be thrown away.
334  **/
335 void block_io_read(struct main_block_io *bio, void *buf, uns len);
336
337 /**
338  * Request that the main loop writes @len bytes of data from @buf to @bio.
339  * Cancels any previous unfinished write and overwrites `write_handler`.
340  *
341  * When it is written, the write_done() handler is called.
342  *
343  * Can be called from a handler.
344  *
345  * If you call it with zero @len, it will cancel the previous write, but note
346  * that some data may already be written.
347  **/
348 void block_io_write(struct main_block_io *bio, void *buf, uns len);
349
350 /**
351  * Sets a timer for a file @bio. If the timer is not overwritten or disabled
352  * until @expires_delta milliseconds, the file timeouts and error_handler() is called with
353  * <<enum_block_io_err_cause,`BIO_ERR_TIMEOUT`>>. A value of `0` stops the timer.
354  *
355  * Previous setting of the timeout on the same file will be overwritten.
356  *
357  * The use-cases for this are mainly sockets or pipes, when:
358  *
359  * - You want to drop inactive connections (no data comes in or out for a given time, not
360  *   incomplete messages).
361  * - You want to enforce answer in a given time (for example authentication).
362  * - Watching maximum time for a whole connection.
363  **/
364 void block_io_set_timeout(struct main_block_io *bio, timestamp_t expires_delta);
365
366 /***
367  * [[hooks]]
368  * Loop hooks
369  * ----------
370  *
371  * The hooks are called whenever the main loop performs an iteration.
372  * You can shutdown the main loop from within them or request an iteration
373  * to happen without sleeping (just poll, no waiting for events).
374  ***/
375
376 /**
377  * A hook. It contains the function to call and some user data.
378  *
379  * The handler() must return one value from
380  * <<enum_main_hook_return,`main_hook_return`>>.
381  *
382  * Fill with the hook and data and pass it to @hook_add().
383  **/
384 struct main_hook {
385   cnode n;
386   int (*handler)(struct main_hook *ho);         /* [*] Hook function; returns HOOK_xxx */
387   void *data;                                   /* [*] For use by the handler */
388 };
389
390 /**
391  * Return value of the hook handler().
392  * Specifies what should happen next.
393  *
394  * - `HOOK_IDLE` -- Let the loop sleep until something happens, call after that.
395  * - `HOOK_RETRY` -- Force the loop to perform another iteration without sleeping.
396  *   This will cause calling of all the hooks again soon.
397  * - `HOOK_DONE` -- The loop will terminate if all hooks return this.
398  * - `HOOK_SHUTDOWN` -- Shuts down the loop.
399  *
400  * The `HOOK_IDLE` and `HOOK_RETRY` constants are also used as return values
401  * of file handlers.
402  **/
403 enum main_hook_return {
404   HOOK_IDLE,
405   HOOK_RETRY,
406   HOOK_DONE = -1,
407   HOOK_SHUTDOWN = -2
408 };
409
410 /**
411  * Inserts a new hook into the loop.
412  * The hook will be scheduled at least once before next sleep.
413  * May be called from inside a hook handler too.
414  **/
415 void hook_add(struct main_hook *ho);
416
417 /**
418  * Removes an existing hook from the loop.
419  * May be called from inside a hook handler (to delete itself or another hook).
420  **/
421 void hook_del(struct main_hook *ho);
422
423 /** Show current state of a hook. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
424 void hook_debug(struct main_hook *ho);
425
426 /***
427  * [[process]]
428  * Child processes
429  * ---------------
430  *
431  * The main loop can watch child processes and notify you,
432  * when some of them terminates.
433  ***/
434
435 /**
436  * Description of a watched process.
437  * You fill in the handler() and `data`.
438  * The rest is set with @process_fork().
439  **/
440 struct main_process {
441   cnode n;
442   int pid;                                      /* Process id (0=not running) */
443   int status;                                   /* Exit status (-1=fork failed) */
444   char status_msg[EXIT_STATUS_MSG_SIZE];
445   void (*handler)(struct main_process *mp);     /* [*] Called when the process exits; process_del done automatically */
446   void *data;                                   /* [*] For use by the handler */
447 };
448
449 /**
450  * Asks the main loop to watch this process.
451  * As it is done automatically in @process_fork(), you need this only
452  * if you removed the process previously by @process_del().
453  **/
454 void process_add(struct main_process *mp);
455
456 /**
457  * Removes the process from the watched set. This is done
458  * automatically, when the process terminates, so you need it only
459  * when you do not want to watch a running process any more.
460  */
461 void process_del(struct main_process *mp);
462
463 /**
464  * Forks and fills the @mp with information about the new process.
465  *
466  * If the fork() succeeds, it:
467  *
468  * - Returns 0 in the child.
469  * - Returns 1 in the parent and calls @process_add() on it.
470  *
471  * In the case of unsuccessful fork(), it:
472  *
473  * - Fills in the `status_msg` and sets `status` to -1.
474  * - Calls the handler() as if the process terminated.
475  * - Returns 1.
476  **/
477 int process_fork(struct main_process *mp);
478
479 /** Show current state of a process. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
480 void process_debug(struct main_process *pr);
481
482 /***
483  * [[signal]]
484  * Synchronous delivery of signals
485  * -------------------------------
486  *
487  * UNIX signals are delivered to processes in an asynchronous way: when a signal
488  * arrives (and it is not blocked), the process is interrupted and the corresponding
489  * signal handler function is called. However, most data structures and even most
490  * system library calls are not safe with respect to interrupts, so most program
491  * using signals contain subtle race conditions and may fail once in a long while.
492  *
493  * To avoid this problem, the event loop can be asked for synchronous delivery
494  * of signals. When a signal registered with @signal_add() arrives, it wakes up
495  * the loop (if it is not already awake) and it is processed in the same way
496  * as all other events.
497  *
498  * When used in a multi-threaded program, the signals are delivered to the thread
499  * which is currently using the particular main loop context. If the context is not
500  * current in any thread, the signals are blocked.
501  *
502  * As usually with UNIX signals, multiple instances of a single signal can be
503  * merged and delivered only once. (Some implementations of the main loop can even
504  * drop a signal completely during very intensive signal traffic, when an internal
505  * signal queue overflows.)
506  ***/
507
508 /** Description of a signal to catch. **/
509 struct main_signal {
510   cnode n;
511   int signum;                                   /* [*] Signal to catch */
512   void (*handler)(struct main_signal *ms);      /* [*] Called when the signal arrives */
513   void *data;                                   /* [*] For use by the handler */
514 };
515
516 /** Request a signal to be caught and delivered synchronously. **/
517 void signal_add(struct main_signal *ms);
518
519 /** Cancel a request for signal catching. **/
520 void signal_del(struct main_signal *ms);
521
522 /** Show current state of a signal catcher. Available only if LibUCW has been compiled with `CONFIG_DEBUG`. **/
523 void signal_debug(struct main_signal *sg);
524
525 #endif