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