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