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