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