]> mj.ucw.cz Git - libucw.git/blob - ucw/mainloop.h
95565d1362dcdce07372c8594d9011245b13b782
[libucw.git] / ucw / mainloop.h
1 /*
2  *      UCW Library -- Main Loop
3  *
4  *      (c) 2004--2010 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  * [[conventions]]
19  * Conventions
20  * -----------
21  *
22  * The descriptions of structures contain some fields marked with `[*]`.
23  * These are the only ones that are intended to be manipulated by the user.
24  * The remaining fields serve for internal use only and you must initialize them
25  * to zeroes.
26  *
27  * FIXME: The documentation is outdated.
28  ***/
29
30 struct main_context {
31   timestamp_t now;                      /** [*] Current time in milliseconds since the UNIX epoch. See @main_get_time(). **/
32   ucw_time_t now_seconds;               /** [*] Current time in seconds since the epoch. **/
33   timestamp_t idle_time;                /** [*] Total time in milliseconds spent by waiting for events. **/
34   uns shutdown;                         /** [*] Setting this to nonzero forces the @main_loop() function to terminate. **/
35   clist file_list;
36   clist hook_list;
37   clist hook_done_list;
38   clist process_list;
39   clist signal_list;
40   uns file_cnt;
41   uns poll_table_obsolete;
42   uns poll_table_size;
43   struct pollfd *poll_table;
44   struct main_timer **timer_table;      /* Growing array containing the heap of timers */
45   sigset_t want_signals;
46   int sig_pipe_send;
47   int sig_pipe_recv;
48   struct main_file *sig_pipe_file;
49   struct main_signal *sigchld_handler;
50 };
51
52 struct main_context *main_new(void);
53 void main_delete(struct main_context *m);
54 struct main_context *main_switch_context(struct main_context *m);
55 struct main_context *main_current(void);
56
57 void main_init(void);
58 void main_cleanup(void);
59
60 /**
61  * Start the mainloop.
62  * It will watch the provided objects and call callbacks.
63  * Terminates when someone sets <<var_main_shutdown,`main_shutdown`>>
64  * to nonzero, when all <<hook,hooks>> return
65  * <<enum_main_hook_return,`HOOK_DONE`>> or at last one <<hook,hook>>
66  * returns <<enum_main_hook_return,`HOOK_SHUTDOWN`>>.
67  **/
68 void main_loop(void);
69
70 void main_debug_context(struct main_context *m);
71
72 static inline void
73 main_debug(void)
74 {
75   main_debug_context(main_current());
76 }
77
78 /***
79  * [[time]]
80  * Timers
81  * ------
82  *
83  * This part allows you to get the current time and request
84  * to have your function called when the time comes.
85  ***/
86
87 static inline timestamp_t
88 main_get_now(void)
89 {
90   return main_current()->now;
91 }
92
93 static inline ucw_time_t
94 main_get_now_seconds(void)
95 {
96   return main_current()->now_seconds;
97 }
98
99 static inline void
100 main_shut_down(void)
101 {
102   main_current()->shutdown = 1;
103 }
104
105 /**
106  * This is a description of a timer.
107  * You fill in a handler function, any user-defined data you wish to pass
108  * to the handler, and then you invoke @timer_add().
109  *
110  * The handler() function must either call @timer_del() to delete the timer,
111  * or call @timer_add() with a different expiration time.
112  **/
113 struct main_timer {
114   cnode n;
115   timestamp_t expires;
116   uns index;
117   void (*handler)(struct main_timer *tm);       /* [*] Function to be called when the timer expires. */
118   void *data;                                   /* [*] Data for use by the handler */
119 };
120
121 /**
122  * Adds a new timer into the mainloop to be watched and called
123  * when it expires. It can also be used to modify an already running
124  * timer. It is permitted (and usual) to call this function from the
125  * timer's handler itself if you want the timer to trigger again.
126  *
127  * The @expire parameter is absolute, just add <<var_main_now,`main_now`>> if you need a relative timer.
128  **/
129 void timer_add(struct main_timer *tm, timestamp_t expires);
130
131 void timer_add_rel(struct main_timer *tm, timestamp_t expires_delta);
132
133 /**
134  * Removes a timer from the active ones. It is permitted (and usual) to call
135  * this function from the timer's handler itself if you want to deactivate
136  * the timer.
137  **/
138 void timer_del(struct main_timer *tm);
139
140 /**
141  * Forces refresh of <<var_main_now,`main_now`>>. You do not usually
142  * need to call this, since it is called every time the loop polls for
143  * changes. It is here if you need extra precision or some of the
144  * hooks takes a long time.
145  **/
146 void main_get_time(void);
147
148 /***
149  * [[file]]
150  * Activity on file descriptors
151  * ----------------------------
152  *
153  * You can let the mainloop watch over a set of file descriptors
154  * for a changes.
155  *
156  * It supports two ways of use. With the first one, you provide
157  * low-level handlers for reading and writing (`read_handler` and
158  * `write_handler`). They will be called every time the file descriptor
159  * is ready to be read from or written to.
160  *
161  * Return non-zero if you want to get the handler called again right now (you
162  * handled a block of data and expect more). If you return `0`, the hook will
163  * be called again in the next iteration, if it is still ready to be read/written.
164  *
165  * This way is suitable for listening sockets, interactive connections, where
166  * you need to parse everything that comes right away and similar cases.
167  *
168  * The second way is to ask mainloop to read or write a buffer of data. You
169  * provide a `read_done` or `write_done` handler respectively and call @file_read()
170  * or @file_write(). This is handy for data connections where you need to transfer
171  * data between two endpoints or for binary connections where the size of message
172  * is known in advance.
173  *
174  * It is possible to combine both methods, but it may be tricky to do it right.
175  *
176  * Both ways use `error_handler` to notify you about errors.
177  ***/
178
179 /**
180  * If you want mainloop to watch a file descriptor, fill at last `fd` into this
181  * structure. To get any useful information from the mainloop, provide some handlers
182  * too.
183  *
184  * After that, insert it into the mainloop by calling @file_add().
185  **/
186 struct main_file {
187   cnode n;
188   int fd;                                       /* [*] File descriptor */
189   int (*read_handler)(struct main_file *fi);    /* [*] To be called when ready for reading/writing; must call file_chg() afterwards */
190   int (*write_handler)(struct main_file *fi);
191   void *data;                                   /* [*] Data for use by the handlers */
192   struct pollfd *pollfd;
193 };
194
195 /**
196  * Inserts a <<struct_main_file,`main_file`>> structure into the mainloop to be
197  * watched for activity. You can call this at any time, even inside a handler
198  * (of course for a different file descriptor than the one of the handler).
199  **/
200 void file_add(struct main_file *fi);
201 /**
202  * Tells the mainloop the file has changed its state. Call it whenever you
203  * change any of the handlers.
204  *
205  * Can be called only on active files (only the ones added by @file_add()).
206  **/
207 void file_chg(struct main_file *fi);
208 /**
209  * Removes a file from the watched set. You have to call this on closed files
210  * too, since the mainloop does not handle close in any way.
211  *
212  * Can be called from a handler.
213  **/
214 void file_del(struct main_file *fi);
215 /**
216  * Closes all file descriptors known to mainloop. Often used between fork()
217  * and exec().
218  **/
219 void file_close_all(void);
220
221 struct main_block_io {
222   struct main_file file;
223   byte *rbuf;                                   /* Read/write pointers for use by file_read/write */
224   uns rpos, rlen;
225   byte *wbuf;
226   uns wpos, wlen;
227   void (*read_done)(struct main_block_io *bio); /* [*] Called when file_read is finished; rpos < rlen if EOF */
228   void (*write_done)(struct main_block_io *bio);        /* [*] Called when file_write is finished */
229   void (*error_handler)(struct main_block_io *bio, int cause);  /* [*] Handler to call on errors */
230   struct main_timer timer;
231   void *data;                                   /* [*] Data for use by the handlers */
232 };
233
234 void block_io_add(struct main_block_io *bio, int fd);
235 void block_io_del(struct main_block_io *bio);
236
237 /**
238  * Specifies when or why an error happened. This is passed to the error handler.
239  * `errno` is still set to the original source of error. The only exception
240  * is `MFERR_TIMEOUT`, in which case `errno` is not set and the only possible
241  * cause of it is timeout on the file descriptor (see @file_set_timeout).
242  **/
243 enum block_io_err_cause {
244   MFERR_READ,
245   MFERR_WRITE,
246   MFERR_TIMEOUT
247 };
248
249 /**
250  * Asks the mainloop to read @len bytes of data from @bio into @buf.
251  * It cancels any previous unfinished read requested this way and overwrites
252  * `read_handler`.
253  *
254  * When the read is done, read_done() handler is called. If an EOF occurred,
255  * `rpos < rlen` (eg. not all data were read).
256  *
257  * Can be called from a handler.
258  *
259  * You can use a call with zero @len to cancel current read, but all read data
260  * will be thrown away.
261  **/
262 void block_io_read(struct main_block_io *bio, void *buf, uns len);
263 /**
264  * Requests that the mainloop writes @len bytes of data from @buf to @bio.
265  * Cancels any previous unfinished write and overwrites `write_handler`.
266  *
267  * When it is written, write_done() handler is called.
268  *
269  * Can be called from a handler.
270  *
271  * If you call it with zero @len, it will cancel the previous write, but note
272  * some data may already be written.
273  **/
274 void block_io_write(struct main_block_io *bio, void *buf, uns len);
275 /**
276  * Sets a timer for a file @bio. If the timer is not overwritten or disabled
277  * until @expires, the file timeouts and error_handler() is called with
278  * <<enum_block_io_err_cause,`MFERR_TIMEOUT`>>.
279  *
280  * The mainloop does not disable or reset it, when something happens, it just
281  * bundles a timer with the file. If you want to watch for inactivity, it is
282  * your task to reset it whenever your handler is called.
283  *
284  * The @expires parameter is absolute (add <<var_main_now,`main_now`>> if you
285  * need relative). The call and overwrites previously set timeout. Value of `0`
286  * disables the timeout (the <<enum_block_io_err_cause,`MFERR_TIMEOUT`>> will
287  * not trigger).
288  *
289  * The use-cases for this are mainly sockets or pipes, when:
290  *
291  * - You want to drop inactive connections (no data come or go for a given time, not
292  *   incomplete messages).
293  * - You want to enforce answer in a given time (for example authentication).
294  * - You give maximum time for a whole connection.
295  **/
296 void block_io_set_timeout(struct main_block_io *bio, timestamp_t expires);
297
298 /***
299  * [[hooks]]
300  * Loop hooks
301  * ----------
302  *
303  * The hooks are called whenever the mainloop performs an iteration.
304  * You can shutdown the mainloop from within them or request an iteration
305  * to happen without sleeping (just poll, no waiting for events).
306  ***/
307
308 /**
309  * A hook. It contains the function to call and some user data.
310  *
311  * The handler() must return one value from
312  * <<enum_main_hook_return,`main_hook_return`>>.
313  *
314  * Fill with the hook and data and pass it to @hook_add().
315  **/
316 struct main_hook {
317   cnode n;
318   int (*handler)(struct main_hook *ho);         /* [*] Hook function; returns HOOK_xxx */
319   void *data;                                   /* [*] For use by the handler */
320 };
321
322 /**
323  * Return value of the hook handler().
324  * Specifies what should happen next.
325  *
326  * - `HOOK_IDLE` -- Let the loop sleep until something happens, call after that.
327  * - `HOOK_RETRY` -- Force the loop to perform another iteration without sleeping.
328  *   This will cause calling of all the hooks again soon.
329  * - `HOOK_DONE` -- The loop will terminate if all hooks return this.
330  * - `HOOK_SHUTDOWN` -- Shuts down the loop.
331  **/
332 enum main_hook_return {
333   HOOK_IDLE,
334   HOOK_RETRY,
335   HOOK_DONE = -1,
336   HOOK_SHUTDOWN = -2
337 };
338
339 /**
340  * Inserts a new hook into the loop.
341  * The hook will be scheduled at least once before next sleep.
342  * May be called from inside a hook handler too.
343  **/
344 void hook_add(struct main_hook *ho);
345 /**
346  * Removes an existing hook from the loop.
347  * May be called from inside a hook handler (to delete itself or other hook).
348  **/
349 void hook_del(struct main_hook *ho);
350
351 /***
352  * [[process]]
353  * Child processes
354  * ---------------
355  *
356  * The main loop can watch child processes and notify you,
357  * when some of them terminates.
358  ***/
359
360 /**
361  * Description of a watched process.
362  * You fill in the handler() and `data`.
363  * The rest is set with @process_fork().
364  **/
365 struct main_process {
366   cnode n;
367   int pid;                                      /* Process id (0=not running) */
368   int status;                                   /* Exit status (-1=fork failed) */
369   char status_msg[EXIT_STATUS_MSG_SIZE];
370   void (*handler)(struct main_process *mp);     /* [*] Called when the process exits; process_del done automatically */
371   void *data;                                   /* [*] For use by the handler */
372 };
373
374 /**
375  * Asks the mainloop to watch this process.
376  * As it is done automatically in @process_fork(), you need this only
377  * if you removed the process previously by @process_del().
378  **/
379 void process_add(struct main_process *mp);
380 /**
381  * Removes the process from the watched set. This is done
382  * automatically, when the process terminates, so you need it only
383  * when you do not want to watch a running process any more.
384  */
385 void process_del(struct main_process *mp);
386 /**
387  * Forks and fills the @mp with information about the new process.
388  *
389  * If the fork() succeeds, it:
390  *
391  * - Returns 0 in the child.
392  * - Returns 1 in the parent and calls @process_add() on it.
393  *
394  * In the case of unsuccessful fork(), it:
395  *
396  * - Fills in the `status_msg` and sets `status` to -1.
397  * - Calls the handler() as if the process terminated.
398  * - Returns 1.
399  **/
400 int process_fork(struct main_process *mp);
401
402 /* FIXME: Docs */
403
404 struct main_signal {
405   cnode n;
406   int signum;
407   void (*handler)(struct main_signal *ms);
408   void *data;
409 };
410
411 void signal_add(struct main_signal *ms);
412 void signal_del(struct main_signal *ms);
413
414 #endif