]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.h
Main: Update documentation
[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 sets <<var_main_shutdown,`main_shutdown`>>
93  * to nonzero, when all <<hook,hooks>> return
94  * <<enum_main_hook_return,`HOOK_DONE`>> or at last one <<hook,hook>>
95  * returns <<enum_main_hook_return,`HOOK_SHUTDOWN`>>.
96  **/
97 void main_loop(void);
98
99 /** Ask the main loop to terminate at the nearest occasion. **/
100 static inline void main_shut_down(void)
101 {
102   main_current()->shutdown = 1;
103 }
104
105 /** Show the current state of a given context (use @main_debug() for the current context). **/
106 void main_debug_context(struct main_context *m);
107
108 static inline void
109 main_debug(void)
110 {
111   main_debug_context(main_current());
112 }
113
114 /***
115  * [[time]]
116  * Timers
117  * ------
118  *
119  * The event loop provides the current time, measured as a 64-bit number
120  * of milliseconds since the system epoch (represented in the type `timestamp_t`).
121  *
122  * You can also register timers, which call a handler function at a given moment.
123  * The handler function must either call @timer_del() to delete the timer, or call
124  * @timer_add() with a different expiration time.
125  ***/
126
127 /**
128  * Get the current timestamp cached in the current context. It is refreshed in every
129  * iteration of the event loop, or explicitly by calling @main_get_time().
130  **/
131 static inline timestamp_t main_get_now(void)
132 {
133   return main_current()->now;
134 }
135
136 /** An analog of @main_get_now() returning the number of seconds since the system epoch. **/
137 static inline ucw_time_t main_get_now_seconds(void)
138 {
139   return main_current()->now_seconds;
140 }
141
142 /**
143  * This is a description of a timer.
144  * You define the handler function and possibly user-defined data you wish
145  * to pass to the handler, and then you invoke @timer_add().
146  **/
147 struct main_timer {
148   cnode n;
149   timestamp_t expires;
150   uns index;
151   void (*handler)(struct main_timer *tm);       /* [*] Function to be called when the timer expires. */
152   void *data;                                   /* [*] Data for use by the handler */
153 };
154
155 /**
156  * Add a new timer into the main loop to be watched and called
157  * when it expires. It can also be used to modify an already running
158  * timer. It is permitted (and usual) to call this function from the
159  * timer's handler itself if you want the timer to trigger again.
160  *
161  * The @expire parameter is absolute, use @timer_add_rel() for a relative version.
162  **/
163 void timer_add(struct main_timer *tm, timestamp_t expires);
164
165 /** Like @timer_add(), but the expiration time is relative to the current time. **/
166 void timer_add_rel(struct main_timer *tm, timestamp_t expires_delta);
167
168 /**
169  * Removes a timer from the active ones. It is permitted (and common) to call
170  * this function from the timer's handler itself if you want to deactivate
171  * the timer.
172  **/
173 void timer_del(struct main_timer *tm);
174
175 /**
176  * Forces refresh of the current timestamp cached in the active context.
177  * You usually do not need to call this, since it is called every time the
178  * loop polls for events. It is here if you need extra precision or some of the
179  * hooks takes a long time.
180  **/
181 void main_get_time(void);
182
183 /***
184  * [[file]]
185  * Activity on file descriptors
186  * ----------------------------
187  *
188  * You can ask the main loop to watch a set of file descriptors for activity.
189  * (This is a generalization of the select() and poll() system calls. Internally,
190  * it uses either poll() or the more efficient epoll().)
191  *
192  * You create a <<struct_main_file,`struct main_file`>>, fill in a file descriptor
193  * and pointers to handler functions to be called when the descriptor becomes
194  * ready for reading and/or writing, and call @file_add(). When you need to
195  * modify the handlers (e.g., to set them to NULL if you are no longer interested
196  * in a given event), you should call @file_chg() to notify the main loop about
197  * the changes.
198  *
199  * From within the handler functions, you are allowed to call @file_chg() and even
200  * @file_del().
201  *
202  * The return value of a handler function should be either `HOOK_RETRY` or `HOOK_IDLE`.
203  * `HOOK_RETRY` signals that the function would like to consume more data immediately
204  * (i.e., it wants to be called again soon, but the event loop can postpone it after
205  * processing other events to avoid starvation). `HOOK_IDLE` tells that the handler
206  * wants to be called when the descriptor becomes ready again.
207  *
208  * For backward compatibility, 0 can be used instead of `HOOK_IDLE` and 1 for `HOOK_RETRY`.
209  *
210  * If you want to read/write fixed-size blocks of data asynchronously, the
211  * <<blockio,Asynchronous block I/O>> interface could be more convenient.
212  ***/
213
214 /**
215  * This structure describes a file descriptor to be watched and the handlers
216  * to be called when the descriptor is ready for reading and/or writing.
217  **/
218 struct main_file {
219   cnode n;
220   int fd;                                       /* [*] File descriptor */
221   int (*read_handler)(struct main_file *fi);    /* [*] To be called when ready for reading/writing; must call file_chg() afterwards */
222   int (*write_handler)(struct main_file *fi);
223   void *data;                                   /* [*] Data for use by the handlers */
224   uns events;
225 #ifdef CONFIG_UCW_EPOLL
226   uns last_want_events;
227 #else
228   struct pollfd *pollfd;
229 #endif
230 };
231
232 /**
233  * Insert a <<struct_main_file,`main_file`>> structure into the main loop to be
234  * watched for activity. You can call this at any time, even inside a handler
235  * (of course for a different file descriptor than the one of the handler).
236  *
237  * The file descriptor is automatically set to the non-blocking mode.
238  **/
239 void file_add(struct main_file *fi);
240 /**
241  * Tell the main loop that the file structure has changed. Call it whenever you
242  * change any of the handlers.
243  *
244  * Can be called only on active files (only the ones added by @file_add()).
245  **/
246 void file_chg(struct main_file *fi);
247 /**
248  * Removes a file from the watched set. If you want to close a descriptor,
249  * please use this function first.
250  *
251  * Can be called from a handler.
252  **/
253 void file_del(struct main_file *fi);
254
255 /***
256  * [[blockio]]
257  * Asynchronous block I/O
258  * ----------------------
259  *
260  * If you are reading or writing fixed-size blocks of data, you can let the
261  * block I/O interface handle the boring routine of handling partial reads
262  * and writes for you.
263  *
264  * You just create <<struct_main_block_io,`struct main_block_io`>> and call
265  * @block_io_add() on it, which sets up some `main_file`s internally.
266  * Then you can just call @block_io_read() or @block_io_write() to ask for
267  * reading or writing of a given block. When the operation is finished,
268  * your handler function is called.
269  *
270  * Additionally, the block I/O is equipped with a timer, which can be used
271  * to detect communication timeouts. The timer is not touched internally
272  * (except that it gets added and deleted at the right places), feel free
273  * to adjust it from your handler functions by @block_io_set_timeout().
274  * When the timer expires, the error handler is automatically called with
275  * `MFERR_TIMEOUT`.
276  ***/
277
278 /** The block I/O structure. **/
279 struct main_block_io {
280   struct main_file file;
281   byte *rbuf;                                   /* Read/write pointers for use by file_read/write */
282   uns rpos, rlen;
283   byte *wbuf;
284   uns wpos, wlen;
285   void (*read_done)(struct main_block_io *bio); /* [*] Called when file_read is finished; rpos < rlen if EOF */
286   void (*write_done)(struct main_block_io *bio);        /* [*] Called when file_write is finished */
287   void (*error_handler)(struct main_block_io *bio, int cause);  /* [*] Handler to call on errors */
288   struct main_timer timer;
289   void *data;                                   /* [*] Data for use by the handlers */
290 };
291
292 /** Activate a block I/O structure. **/
293 void block_io_add(struct main_block_io *bio, int fd);
294
295 /** Deactivate a block I/O structure. **/
296 void block_io_del(struct main_block_io *bio);
297
298 /**
299  * Specifies when or why an error happened. This is passed to the error handler.
300  * `errno` is still set to the original source of error. The only exception
301  * is `MFERR_TIMEOUT`, in which case `errno` is not set and the only possible
302  * cause of it is timeout of the timer associated with the block_io
303  * (see @block_io_set_timeout()).
304  **/
305 enum block_io_err_cause {
306   MFERR_READ,
307   MFERR_WRITE,
308   MFERR_TIMEOUT
309 };
310
311 /**
312  * Ask the main loop to read @len bytes of data from @bio into @buf.
313  * It cancels any previous unfinished read requested in this way.
314  *
315  * When the read is done, the read_done() handler is called. If an EOF occurred,
316  * `rpos < rlen` (eg. not all data were read).
317  *
318  * Can be called from a handler.
319  *
320  * You can use a call with zero @len to cancel the current read, but all read data
321  * will be thrown away.
322  **/
323 void block_io_read(struct main_block_io *bio, void *buf, uns len);
324
325 /**
326  * Request that the main loop writes @len bytes of data from @buf to @bio.
327  * Cancels any previous unfinished write and overwrites `write_handler`.
328  *
329  * When it is written, the write_done() handler is called.
330  *
331  * Can be called from a handler.
332  *
333  * If you call it with zero @len, it will cancel the previous write, but note
334  * that some data may already be written.
335  **/
336 void block_io_write(struct main_block_io *bio, void *buf, uns len);
337
338 /**
339  * Sets a timer for a file @bio. If the timer is not overwritten or disabled
340  * until @expires_delta milliseconds, the file timeouts and error_handler() is called with
341  * <<enum_block_io_err_cause,`MFERR_TIMEOUT`>>. A value of `0` stops the timer.
342  *
343  * Previous setting of the timeout on the same file will be overwritten.
344  *
345  * The use-cases for this are mainly sockets or pipes, when:
346  *
347  * - You want to drop inactive connections (no data comes in or out for a given time, not
348  *   incomplete messages).
349  * - You want to enforce answer in a given time (for example authentication).
350  * - Watching maximum time for a whole connection.
351  **/
352 void block_io_set_timeout(struct main_block_io *bio, timestamp_t expires_delta);
353
354 /***
355  * [[hooks]]
356  * Loop hooks
357  * ----------
358  *
359  * The hooks are called whenever the main loop performs an iteration.
360  * You can shutdown the main loop from within them or request an iteration
361  * to happen without sleeping (just poll, no waiting for events).
362  ***/
363
364 /**
365  * A hook. It contains the function to call and some user data.
366  *
367  * The handler() must return one value from
368  * <<enum_main_hook_return,`main_hook_return`>>.
369  *
370  * Fill with the hook and data and pass it to @hook_add().
371  **/
372 struct main_hook {
373   cnode n;
374   int (*handler)(struct main_hook *ho);         /* [*] Hook function; returns HOOK_xxx */
375   void *data;                                   /* [*] For use by the handler */
376 };
377
378 /**
379  * Return value of the hook handler().
380  * Specifies what should happen next.
381  *
382  * - `HOOK_IDLE` -- Let the loop sleep until something happens, call after that.
383  * - `HOOK_RETRY` -- Force the loop to perform another iteration without sleeping.
384  *   This will cause calling of all the hooks again soon.
385  * - `HOOK_DONE` -- The loop will terminate if all hooks return this.
386  * - `HOOK_SHUTDOWN` -- Shuts down the loop.
387  **/
388 enum main_hook_return {
389   HOOK_IDLE,
390   HOOK_RETRY,
391   HOOK_DONE = -1,
392   HOOK_SHUTDOWN = -2
393 };
394
395 /**
396  * Inserts a new hook into the loop.
397  * The hook will be scheduled at least once before next sleep.
398  * May be called from inside a hook handler too.
399  **/
400 void hook_add(struct main_hook *ho);
401 /**
402  * Removes an existing hook from the loop.
403  * May be called from inside a hook handler (to delete itself or other hook).
404  **/
405 void hook_del(struct main_hook *ho);
406
407 /***
408  * [[process]]
409  * Child processes
410  * ---------------
411  *
412  * The main loop can watch child processes and notify you,
413  * when some of them terminates.
414  ***/
415
416 /**
417  * Description of a watched process.
418  * You fill in the handler() and `data`.
419  * The rest is set with @process_fork().
420  **/
421 struct main_process {
422   cnode n;
423   int pid;                                      /* Process id (0=not running) */
424   int status;                                   /* Exit status (-1=fork failed) */
425   char status_msg[EXIT_STATUS_MSG_SIZE];
426   void (*handler)(struct main_process *mp);     /* [*] Called when the process exits; process_del done automatically */
427   void *data;                                   /* [*] For use by the handler */
428 };
429
430 /**
431  * Asks the main loop to watch this process.
432  * As it is done automatically in @process_fork(), you need this only
433  * if you removed the process previously by @process_del().
434  **/
435 void process_add(struct main_process *mp);
436 /**
437  * Removes the process from the watched set. This is done
438  * automatically, when the process terminates, so you need it only
439  * when you do not want to watch a running process any more.
440  */
441 void process_del(struct main_process *mp);
442 /**
443  * Forks and fills the @mp with information about the new process.
444  *
445  * If the fork() succeeds, it:
446  *
447  * - Returns 0 in the child.
448  * - Returns 1 in the parent and calls @process_add() on it.
449  *
450  * In the case of unsuccessful fork(), it:
451  *
452  * - Fills in the `status_msg` and sets `status` to -1.
453  * - Calls the handler() as if the process terminated.
454  * - Returns 1.
455  **/
456 int process_fork(struct main_process *mp);
457
458 /* FIXME: Docs */
459
460 struct main_signal {
461   cnode n;
462   int signum;
463   void (*handler)(struct main_signal *ms);
464   void *data;
465 };
466
467 void signal_add(struct main_signal *ms);
468 void signal_del(struct main_signal *ms);
469
470 #endif