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