775d97d74f07080b36cea561ce83cea58a4c7e25
[debian/amanda] / common-src / event.c
1 /*
2  * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3  * Copyright (c) 1999 University of Maryland at College Park
4  * All Rights Reserved.
5  *
6  * Permission to use, copy, modify, distribute, and sell this software and its
7  * documentation for any purpose is hereby granted without fee, provided that
8  * the above copyright notice appear in all copies and that both that
9  * copyright notice and this permission notice appear in supporting
10  * documentation, and that the name of U.M. not be used in advertising or
11  * publicity pertaining to distribution of the software without specific,
12  * written prior permission.  U.M. makes no representations about the
13  * suitability of this software for any purpose.  It is provided "as is"
14  * without express or implied warranty.
15  *
16  * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
18  * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
19  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
20  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
21  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
22  *
23  * Authors: the Amanda Development Team.  Its members are listed in a
24  * file named AUTHORS, in the root directory of this distribution.
25  */
26 /*
27  * $Id: event.c,v 1.24 2006/06/16 10:55:05 martinea Exp $
28  *
29  * Event handler.  Serializes different kinds of events to allow for
30  * a uniform interface, central state storage, and centralized
31  * interdependency logic.
32  *
33  * This is a compatibility wrapper over Glib's GMainLoop.  New code should
34  * use Glib's interface directly.
35  *
36  * Each event_handle is associated with a unique GSource, identified by it
37  * event_source_id.
38  */
39
40 #include "amanda.h"
41 #include "conffile.h"
42 #include "event.h"
43 #include "glib-util.h"
44
45 /* TODO: use mem chunks to allocate event_handles */
46 /* TODO: lock stuff for threading */
47
48 /* Write a debugging message if the config variable debug_event
49  * is greater than or equal to i */
50 #define event_debug(i, ...) do {        \
51        if ((i) <= debug_event) {        \
52            dbprintf(__VA_ARGS__);       \
53        }                                \
54 } while (0)
55
56 /*
57  * The opaque handle passed back to the caller.  This is typedefed to
58  * event_handle_t in our header file.
59  */
60 struct event_handle {
61     event_fn_t fn;              /* function to call when this fires */
62     void *arg;                  /* argument to pass to previous function */
63
64     event_type_t type;          /* type of event */
65     event_id_t data;            /* type data */
66
67     GSource *source;            /* Glib event source, if one exists */
68     guint source_id;            /* ID of the glib event source */
69
70     gboolean has_fired;         /* for use by event_wait() */
71     gboolean is_dead;           /* should this event be deleted? */
72 };
73
74 /* A list of all extant event_handle objects, used for searching for particular
75  * events and for deleting dead events */
76 GSList *all_events;
77
78 /*
79  * Utility functions
80  */
81
82 static const char *event_type2str(event_type_t type);
83
84 /* "Fire" an event handle, by calling its callback function */
85 #define fire(eh) do { \
86         event_debug(1, "firing %p: %s/%jd\n", eh, event_type2str((eh)->type), (eh)->data); \
87         (*(eh)->fn)((eh)->arg); \
88         (eh)->has_fired = TRUE; \
89 } while(0)
90
91 /* Adapt a Glib callback to an event_handle_t callback; assumes that the
92  * user_ptr for the Glib callback is a pointer to the event_handle_t.  */
93 static gboolean 
94 event_handle_callback(
95     gpointer user_ptr)
96 {
97     event_handle_t *hdl = (event_handle_t *)user_ptr;
98
99     /* if the handle is dead, then don't fire the callback; this means that
100      * we're in the process of freeing the event */
101     if (!hdl->is_dead) {
102         fire(hdl);
103     }
104
105     /* don't ever let GMainLoop destroy GSources */
106     return TRUE;
107 }
108
109 /*
110  * Public functions
111  */
112
113 event_handle_t *
114 event_register(
115     event_id_t data,
116     event_type_t type,
117     event_fn_t fn,
118     void *arg)
119 {
120     event_handle_t *handle;
121     GIOCondition cond;
122
123     /* sanity-checking */
124     if ((type == EV_READFD) || (type == EV_WRITEFD)) {
125         /* make sure we aren't given a high fd that will overflow a fd_set */
126         if (data >= (int)FD_SETSIZE) {
127             error(_("event_register: Invalid file descriptor %jd"), data);
128             /*NOTREACHED*/
129         }
130     } else if (type == EV_TIME) {
131         if (data <= 0) {
132             error(_("event_register: interval for EV_TIME must be greater than 0; got %jd"), data);
133         }
134     }
135
136     handle = g_new0(event_handle_t, 1);
137     handle->fn = fn;
138     handle->arg = arg;
139     handle->type = type;
140     handle->data = data;
141     handle->is_dead = FALSE;
142
143     event_debug(1, _("event: register: %p->data=%jd, type=%s\n"),
144                     handle, handle->data, event_type2str(handle->type));
145
146     /* add to the list of events */
147     all_events = g_slist_prepend(all_events, (gpointer)handle);
148
149     /* and set up the GSource for this event */
150     switch (type) {
151         case EV_READFD:
152         case EV_WRITEFD:
153             /* create a new source */
154             if (type == EV_READFD) {
155                 cond = G_IO_IN | G_IO_HUP | G_IO_ERR;
156             } else {
157                 cond = G_IO_OUT | G_IO_ERR;
158             }
159
160             handle->source = new_fdsource(data, cond);
161
162             /* attach it to the default GMainLoop */
163             g_source_attach(handle->source, NULL);
164             handle->source_id = g_source_get_id(handle->source);
165
166             /* And set its callbacks */
167             g_source_set_callback(handle->source, event_handle_callback,
168                                   (gpointer)handle, NULL);
169
170             /* drop our reference to it, so when it's detached, it will be
171              * destroyed. */
172             g_source_unref(handle->source);
173             break;
174
175         case EV_TIME:
176             /* Glib provides a nice shortcut for timeouts.  The *1000 converts
177              * seconds to milliseconds. */
178             handle->source_id = g_timeout_add(data * 1000, event_handle_callback,
179                                               (gpointer)handle);
180
181             /* But it doesn't give us the source directly.. */
182             handle->source = g_main_context_find_source_by_id(NULL, handle->source_id);
183             break;
184
185         case EV_WAIT:
186             /* nothing to do -- these are handled independently of GMainLoop */
187             break;
188
189         default:
190             error(_("Unknown event type %s"), event_type2str(type));
191     }
192
193     return handle;
194 }
195
196 /*
197  * Mark an event to be released.  Because we may be traversing the queue
198  * when this is called, we must wait until later to actually remove
199  * the event.
200  */
201 void
202 event_release(
203     event_handle_t *handle)
204 {
205     assert(handle != NULL);
206
207     event_debug(1, _("event: release (mark): %p data=%jd, type=%s\n"),
208                     handle, handle->data,
209                     event_type2str(handle->type));
210     assert(!handle->is_dead);
211
212     /* Mark it as dead and leave it for the event_loop to remove */
213     handle->is_dead = TRUE;
214 }
215
216 /*
217  * Fire all EV_WAIT events waiting on the specified id.
218  */
219 int
220 event_wakeup(
221     event_id_t id)
222 {
223     GSList *iter;
224     GSList *tofire = NULL;
225     int nwaken = 0;
226
227     event_debug(1, _("event: wakeup: enter (%jd)\n"), id);
228
229     /* search for any and all matching events, and record them.  This way
230      * we have determined the whole list of events we'll be firing *before*
231      * we fire any of them. */
232     for (iter = all_events; iter != NULL; iter = g_slist_next(iter)) {
233         event_handle_t *eh = (event_handle_t *)iter->data;
234         if (eh->type == EV_WAIT && eh->data == id && !eh->is_dead) {
235             tofire = g_slist_append(tofire, (gpointer)eh);
236         }
237     }
238
239     /* fire them */
240     for (iter = tofire; iter != NULL; iter = g_slist_next(iter)) {
241         event_handle_t *eh = (event_handle_t *)iter->data;
242         if (eh->type == EV_WAIT && eh->data == id && !eh->is_dead) {
243             event_debug(1, _("A: event: wakeup triggering: %p id=%jd\n"), eh, id);
244             fire(eh);
245             nwaken++;
246         }
247     }
248
249     /* and free the temporary list */
250     g_slist_free(tofire);
251
252     return (nwaken);
253 }
254
255
256 /*
257  * The event loop.
258  */
259
260 static void event_loop_wait (event_handle_t *, const int);
261
262 void
263 event_loop(
264     int nonblock)
265 {
266     event_loop_wait(NULL, nonblock);
267 }
268
269 void
270 event_wait(
271     event_handle_t *eh)
272 {
273     event_loop_wait(eh, 0);
274 }
275
276 /* Flush out any dead events in all_events.  Be careful that this
277  * isn't called while someone is iterating over all_events.
278  *
279  * @param wait_eh: the event handle we're waiting on, which shouldn't
280  *          be flushed.
281  */
282 static void
283 flush_dead_events(event_handle_t *wait_eh)
284 {
285     GSList *iter, *next;
286
287     for (iter = all_events; iter != NULL; iter = next) {
288         event_handle_t *hdl = (event_handle_t *)iter->data;
289         next = g_slist_next(iter);
290
291         /* (handle the case when wait_eh is dead by simply not deleting
292          * it; the next run of event_loop will take care of it) */
293         if (hdl->is_dead && hdl != wait_eh) {
294             all_events = g_slist_delete_link(all_events, iter);
295             if (hdl->source) g_source_destroy(hdl->source);
296
297             amfree(hdl);
298         }
299     }
300 }
301
302 /* Return TRUE if we have any events outstanding that can be dispatched
303  * by GMainLoop.  Recall EV_WAIT events appear in all_events, but are
304  * not dispatched by GMainLoop.  */
305 static gboolean
306 any_mainloop_events(void)
307 {
308     GSList *iter;
309
310     for (iter = all_events; iter != NULL; iter = g_slist_next(iter)) {
311         event_handle_t *hdl = (event_handle_t *)iter->data;
312         if (hdl->type != EV_WAIT)
313             return TRUE;
314     }
315
316     return FALSE;
317 }
318
319 static void
320 event_loop_wait(
321     event_handle_t *wait_eh,
322     int nonblock)
323 {
324     event_debug(1, _("event: loop: enter: nonblockg=%d, eh=%p\n"), nonblock, wait_eh);
325
326     /* If we're waiting for a specific event, then reset its has_fired flag */
327     if (wait_eh) {
328         wait_eh->has_fired = FALSE;
329     }
330
331     /* Keep looping until there are no events, or until wait_eh has fired */
332     while (1) {
333         /* clean up first, so we don't accidentally check a dead source */
334         flush_dead_events(wait_eh);
335
336         /* if there's nothing to wait for, then don't block, but run an
337          * iteration so that any other users of GMainLoop will get a chance
338          * to run. */
339         if (!any_mainloop_events())
340             break;
341
342         /* Do an interation */
343         g_main_context_iteration(NULL, !nonblock);
344
345         /* If the event we've been waiting for has fired or been released, as
346          * appropriate, we're done.  See the comments for event_wait in event.h
347          * for the skinny on this weird expression. */
348         if (wait_eh && ((wait_eh->type == EV_WAIT && wait_eh->is_dead)
349                      || (wait_eh->type != EV_WAIT && wait_eh->has_fired)))
350             break;
351
352         /* Don't loop if we're not blocking */
353         if (nonblock)
354             break;
355     }
356
357     /* extra cleanup, to keep all_events short, and to delete wait_eh if it
358      * has been released. */
359     flush_dead_events(NULL);
360
361 }
362
363 GMainLoop *
364 default_main_loop(void)
365 {
366     static GMainLoop *loop = NULL;
367     if (!loop)
368         loop = g_main_loop_new(NULL, TRUE);
369     return loop;
370 }
371
372 /*
373  * Convert an event type into a string
374  */
375 static const char *
376 event_type2str(
377     event_type_t type)
378 {
379     static const struct {
380         event_type_t type;
381         const char name[12];
382     } event_types[] = {
383 #define X(s)    { s, stringize(s) }
384         X(EV_READFD),
385         X(EV_WRITEFD),
386         X(EV_TIME),
387         X(EV_WAIT),
388 #undef X
389     };
390     size_t i;
391
392     for (i = 0; i < (size_t)(sizeof(event_types) / sizeof(event_types[0])); i++)
393         if (type == event_types[i].type)
394             return (event_types[i].name);
395     return (_("BOGUS EVENT TYPE"));
396 }
397
398 /*
399  * FDSource -- a source for a file descriptor
400  *
401  * We could use Glib's GIOChannel for this, but it adds some buffering
402  * and Unicode functionality that we really don't want.  The custom GSource
403  * is simple enough anyway, and the Glib documentation describes it in prose.
404  */
405
406 typedef struct FDSource {
407     GSource source; /* must be the first element in the struct */
408     GPollFD pollfd; /* Our file descriptor */
409 } FDSource;
410
411 static gboolean
412 fdsource_prepare(
413     GSource *source G_GNUC_UNUSED,
414     gint *timeout_)
415 {
416     *timeout_ = -1; /* block forever, as far as we're concerned */
417     return FALSE;
418 }
419
420 static gboolean
421 fdsource_check(
422     GSource *source)
423 {
424     FDSource *fds = (FDSource *)source;
425
426     /* we need to be dispatched if any interesting events have been received by the FD */
427     return fds->pollfd.events & fds->pollfd.revents;
428 }
429
430 static gboolean
431 fdsource_dispatch(
432     GSource *source G_GNUC_UNUSED,
433     GSourceFunc callback,
434     gpointer user_data)
435 {
436     if (callback)
437         return callback(user_data);
438
439     /* Don't automatically detach the event source if there's no callback. */
440     return TRUE;
441 }
442
443 GSource *
444 new_fdsource(gint fd, GIOCondition events)
445 {
446     static GSourceFuncs *fdsource_funcs = NULL;
447     GSource *src;
448     FDSource *fds;
449
450     /* initialize these here to avoid a compiler warning */
451     if (!fdsource_funcs) {
452         fdsource_funcs = g_new0(GSourceFuncs, 1);
453         fdsource_funcs->prepare = fdsource_prepare;
454         fdsource_funcs->check = fdsource_check;
455         fdsource_funcs->dispatch = fdsource_dispatch;
456     }
457
458     src = g_source_new(fdsource_funcs, sizeof(FDSource));
459     fds = (FDSource *)src;
460
461     fds->pollfd.fd = fd;
462     fds->pollfd.events = events;
463     g_source_add_poll(src, &fds->pollfd);
464
465     return src;
466 }
467
468 /*
469  * ChildWatchSource -- a source for a file descriptor
470  *
471  * Newer versions of glib provide equivalent functionality; consider
472  * optionally using that, protected by a GLIB_CHECK_VERSION condition.
473  */
474
475 /* Versions before glib-2.4.0 didn't include a child watch source, and versions
476  * before 2.6.0 used unreliable signals.  On these versions, we implement
477  * a "dumb" version of our own invention.  This is dumb in the sense that it
478  * doesn't use SIGCHLD to detect a dead child, preferring to just poll at
479  * exponentially increasing interals.  Writing a smarter implementation runs into
480  * some tricky race conditions and extra machinery.  Since there are few, if any,
481  * users of a glib version this old, such machinery wouldn't get much testing.
482  *
483  * FreeBSD users have also reported problems with the glib child watch source,
484  * so we use the dumb version on FreeBSD, too.
485  */
486
487 #if (defined(__FreeBSD__) || GLIB_MAJOR_VERSION < 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 6))
488 typedef struct ChildWatchSource {
489     GSource source; /* must be the first element in the struct */
490
491     pid_t pid;
492
493     gint dead;
494     gint status;
495
496     gint timeout;
497 } ChildWatchSource;
498
499 /* this corresponds to rapid checks for about 10 seconds, after which the
500  * waitpid() check occurs every 2 seconds. */
501 #define CWS_BASE_TIMEOUT 20
502 #define CWS_MULT_TIMEOUT 1.1
503 #define CWS_MAX_TIMEOUT 2000
504
505 static gboolean
506 child_watch_source_prepare(
507     GSource *source,
508     gint *timeout_)
509 {
510     ChildWatchSource *cws = (ChildWatchSource *)source;
511
512     *timeout_ = cws->timeout;
513
514     cws->timeout *= CWS_MULT_TIMEOUT;
515     if (cws->timeout > CWS_MAX_TIMEOUT) cws->timeout = CWS_MAX_TIMEOUT;
516
517     return FALSE;
518 }
519
520 static gboolean
521 child_watch_source_check(
522     GSource *source)
523 {
524     ChildWatchSource *cws = (ChildWatchSource *)source;
525
526     /* is it dead? */
527     if (!cws->dead && waitpid(cws->pid, &cws->status, WNOHANG) > 0) {
528         cws->dead = TRUE;
529     }
530
531     return cws->dead;
532 }
533
534 static gboolean
535 child_watch_source_dispatch(
536     GSource *source G_GNUC_UNUSED,
537     GSourceFunc callback,
538     gpointer user_data)
539 {
540     ChildWatchSource *cws = (ChildWatchSource *)source;
541
542     /* this shouldn't happen, but just in case */
543     if (cws->dead) {
544         if (!callback) {
545             g_warning("child %jd died before callback was registered", (uintmax_t)cws->pid);
546             return FALSE;
547         }
548
549         ((ChildWatchFunc)callback)(cws->pid, cws->status, user_data);
550
551         /* Un-queue this source unconditionally -- the child can't die twice */
552         return FALSE;
553     }
554
555     return TRUE;
556 }
557
558 GSource *
559 new_child_watch_source(pid_t pid)
560 {
561     static GSourceFuncs *child_watch_source_funcs = NULL;
562     GSource *src;
563     ChildWatchSource *cws;
564
565     /* initialize these here to avoid a compiler warning */
566     if (!child_watch_source_funcs) {
567         child_watch_source_funcs = g_new0(GSourceFuncs, 1);
568         child_watch_source_funcs->prepare = child_watch_source_prepare;
569         child_watch_source_funcs->check = child_watch_source_check;
570         child_watch_source_funcs->dispatch = child_watch_source_dispatch;
571     }
572
573     src = g_source_new(child_watch_source_funcs, sizeof(ChildWatchSource));
574     cws = (ChildWatchSource *)src;
575
576     cws->pid = pid;
577     cws->dead = FALSE;
578     cws->timeout = CWS_BASE_TIMEOUT;
579
580     return src;
581 }
582 #else
583 /* In more recent versions of glib, we just use the built-in glib source */
584 GSource *
585 new_child_watch_source(pid_t pid)
586 {
587     return g_child_watch_source_new(pid);
588 }
589 #endif