2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 1999 University of Maryland at College Park
4 * Copyright (c) 2007-2012 Zmanda, Inc. All Rights Reserved.
7 * Permission to use, copy, modify, distribute, and sell this software and its
8 * documentation for any purpose is hereby granted without fee, provided that
9 * the above copyright notice appear in all copies and that both that
10 * copyright notice and this permission notice appear in supporting
11 * documentation, and that the name of U.M. not be used in advertising or
12 * publicity pertaining to distribution of the software without specific,
13 * written prior permission. U.M. makes no representations about the
14 * suitability of this software for any purpose. It is provided "as is"
15 * without express or implied warranty.
17 * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M.
19 * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
20 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
21 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
22 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
24 * Authors: the Amanda Development Team. Its members are listed in a
25 * file named AUTHORS, in the root directory of this distribution.
28 * $Id: event.c,v 1.24 2006/06/16 10:55:05 martinea Exp $
30 * Event handler. Serializes different kinds of events to allow for
31 * a uniform interface, central state storage, and centralized
32 * interdependency logic.
34 * This is a compatibility wrapper over Glib's GMainLoop. New code should
35 * use Glib's interface directly.
37 * Each event_handle is associated with a unique GSource, identified by it
44 #include "glib-util.h"
46 /* TODO: use mem chunks to allocate event_handles */
47 /* TODO: lock stuff for threading */
49 /* Write a debugging message if the config variable debug_event
50 * is greater than or equal to i */
51 #define event_debug(i, ...) do { \
52 if ((i) <= debug_event) { \
53 dbprintf(__VA_ARGS__); \
58 * The opaque handle passed back to the caller. This is typedefed to
59 * event_handle_t in our header file.
62 event_fn_t fn; /* function to call when this fires */
63 void *arg; /* argument to pass to previous function */
65 event_type_t type; /* type of event */
66 event_id_t data; /* type data */
68 GSource *source; /* Glib event source, if one exists */
69 guint source_id; /* ID of the glib event source */
71 gboolean has_fired; /* for use by event_wait() */
72 gboolean is_dead; /* should this event be deleted? */
75 /* A list of all extant event_handle objects, used for searching for particular
76 * events and for deleting dead events */
77 GSList *all_events = NULL;
79 #if (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 31))
80 # pragma GCC diagnostic push
81 # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
83 GStaticMutex event_mutex = G_STATIC_MUTEX_INIT;
84 #if (GLIB_MAJOR_VERSION > 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION >= 31))
85 # pragma GCC diagnostic pop
92 static const char *event_type2str(event_type_t type);
94 /* "Fire" an event handle, by calling its callback function */
95 #define fire(eh) do { \
96 event_debug(1, "firing %p: %s/%jd\n", eh, event_type2str((eh)->type), (eh)->data); \
97 (*(eh)->fn)((eh)->arg); \
98 (eh)->has_fired = TRUE; \
101 /* Adapt a Glib callback to an event_handle_t callback; assumes that the
102 * user_ptr for the Glib callback is a pointer to the event_handle_t. */
104 event_handle_callback(
107 event_handle_t *hdl = (event_handle_t *)user_ptr;
109 /* if the handle is dead, then don't fire the callback; this means that
110 * we're in the process of freeing the event */
115 /* don't ever let GMainLoop destroy GSources */
130 event_handle_t *handle;
132 handle = event_create(data, type, fn, arg);
133 event_activate(handle);
144 event_handle_t *handle;
146 g_static_mutex_lock(&event_mutex);
148 /* sanity-checking */
149 if ((type == EV_READFD) || (type == EV_WRITEFD)) {
150 /* make sure we aren't given a high fd that will overflow a fd_set */
151 if (data >= (int)FD_SETSIZE) {
152 error(_("event_register: Invalid file descriptor %jd"), data);
155 } else if (type == EV_TIME) {
157 error(_("event_register: interval for EV_TIME must be greater than 0; got %jd"), data);
161 handle = g_new0(event_handle_t, 1);
166 handle->is_dead = FALSE;
168 event_debug(1, _("event: register: %p->data=%jd, type=%s\n"),
169 handle, handle->data, event_type2str(handle->type));
171 g_static_mutex_unlock(&event_mutex);
177 event_handle_t *handle)
180 assert(handle != NULL);
182 g_static_mutex_lock(&event_mutex);
184 /* add to the list of events */
185 all_events = g_slist_prepend(all_events, (gpointer)handle);
187 /* and set up the GSource for this event */
188 switch (handle->type) {
191 /* create a new source */
192 if (handle->type == EV_READFD) {
193 cond = G_IO_IN | G_IO_HUP | G_IO_ERR;
195 cond = G_IO_OUT | G_IO_ERR;
198 handle->source = new_fdsource(handle->data, cond);
200 /* attach it to the default GMainLoop */
201 g_source_attach(handle->source, NULL);
202 handle->source_id = g_source_get_id(handle->source);
204 /* And set its callbacks */
205 g_source_set_callback(handle->source, event_handle_callback,
206 (gpointer)handle, NULL);
208 /* drop our reference to it, so when it's detached, it will be
210 g_source_unref(handle->source);
214 /* Glib provides a nice shortcut for timeouts. The *1000 converts
215 * seconds to milliseconds. */
216 handle->source_id = g_timeout_add(handle->data * 1000, event_handle_callback,
219 /* But it doesn't give us the source directly.. */
220 handle->source = g_main_context_find_source_by_id(NULL, handle->source_id);
221 /* EV_TIME must always be handled after EV_READ */
222 g_source_set_priority(handle->source, 10);
226 /* nothing to do -- these are handled independently of GMainLoop */
230 error(_("Unknown event type %s"), event_type2str(handle->type));
233 g_static_mutex_unlock(&event_mutex);
239 * Mark an event to be released. Because we may be traversing the queue
240 * when this is called, we must wait until later to actually remove
245 event_handle_t *handle)
247 assert(handle != NULL);
249 g_static_mutex_lock(&event_mutex);
250 event_debug(1, _("event: release (mark): %p data=%jd, type=%s\n"),
251 handle, handle->data,
252 event_type2str(handle->type));
253 assert(!handle->is_dead);
255 /* Mark it as dead and leave it for the event_loop to remove */
256 handle->is_dead = TRUE;
257 g_static_mutex_unlock(&event_mutex);
261 * Fire all EV_WAIT events waiting on the specified id.
268 GSList *tofire = NULL;
271 g_static_mutex_lock(&event_mutex);
272 event_debug(1, _("event: wakeup: enter (%jd)\n"), id);
274 /* search for any and all matching events, and record them. This way
275 * we have determined the whole list of events we'll be firing *before*
276 * we fire any of them. */
277 for (iter = all_events; iter != NULL; iter = g_slist_next(iter)) {
278 event_handle_t *eh = (event_handle_t *)iter->data;
279 if (eh->type == EV_WAIT && eh->data == id && !eh->is_dead) {
280 tofire = g_slist_append(tofire, (gpointer)eh);
285 for (iter = tofire; iter != NULL; iter = g_slist_next(iter)) {
286 event_handle_t *eh = (event_handle_t *)iter->data;
287 if (eh->type == EV_WAIT && eh->data == id && !eh->is_dead) {
288 event_debug(1, _("A: event: wakeup triggering: %p id=%jd\n"), eh, id);
289 /* The lcok must be release before running the event */
290 g_static_mutex_unlock(&event_mutex);
292 g_static_mutex_lock(&event_mutex);
297 /* and free the temporary list */
298 g_slist_free(tofire);
300 g_static_mutex_unlock(&event_mutex);
309 static void event_loop_wait (event_handle_t *, const int);
315 event_loop_wait(NULL, nonblock);
322 event_loop_wait(eh, 0);
325 /* Flush out any dead events in all_events. Be careful that this
326 * isn't called while someone is iterating over all_events.
328 * @param wait_eh: the event handle we're waiting on, which shouldn't
332 flush_dead_events(event_handle_t *wait_eh)
336 for (iter = all_events; iter != NULL; iter = next) {
337 event_handle_t *hdl = (event_handle_t *)iter->data;
338 next = g_slist_next(iter);
340 /* (handle the case when wait_eh is dead by simply not deleting
341 * it; the next run of event_loop will take care of it) */
342 if (hdl->is_dead && hdl != wait_eh) {
343 all_events = g_slist_delete_link(all_events, iter);
344 if (hdl->source) g_source_destroy(hdl->source);
351 /* Return TRUE if we have any events outstanding that can be dispatched
352 * by GMainLoop. Recall EV_WAIT events appear in all_events, but are
353 * not dispatched by GMainLoop. */
355 any_mainloop_events(void)
358 gboolean ret = FALSE;
360 for (iter = all_events; iter != NULL; iter = g_slist_next(iter)) {
361 event_handle_t *hdl = (event_handle_t *)iter->data;
362 event_debug(2, _("list %p: %s/%jd\n"), hdl, event_type2str((hdl)->type), (hdl)->data);
363 if (hdl->type != EV_WAIT)
372 event_handle_t *wait_eh,
375 g_static_mutex_lock(&event_mutex);
376 event_debug(1, _("event: loop: enter: nonblockg=%d, eh=%p\n"), nonblock, wait_eh);
378 /* If we're waiting for a specific event, then reset its has_fired flag */
380 wait_eh->has_fired = FALSE;
383 /* Keep looping until there are no events, or until wait_eh has fired */
385 /* clean up first, so we don't accidentally check a dead source */
386 flush_dead_events(wait_eh);
388 /* if there's nothing to wait for, then don't block, but run an
389 * iteration so that any other users of GMainLoop will get a chance
391 if (!any_mainloop_events())
394 /* Do an iteration */
395 /* Relese the lock before running an iteration */
396 g_static_mutex_unlock(&event_mutex);
397 g_main_context_iteration(NULL, !nonblock);
398 g_static_mutex_lock(&event_mutex);
400 /* If the event we've been waiting for has fired or been released, as
401 * appropriate, we're done. See the comments for event_wait in event.h
402 * for the skinny on this weird expression. */
403 if (wait_eh && ((wait_eh->type == EV_WAIT && wait_eh->is_dead)
404 || (wait_eh->type != EV_WAIT && wait_eh->has_fired)))
407 /* Don't loop if we're not blocking */
412 /* extra cleanup, to keep all_events short, and to delete wait_eh if it
413 * has been released. */
414 flush_dead_events(NULL);
416 g_static_mutex_unlock(&event_mutex);
420 default_main_loop(void)
422 static GMainLoop *loop = NULL;
424 loop = g_main_loop_new(NULL, TRUE);
429 * Convert an event type into a string
435 static const struct {
439 #define X(s) { s, stringize(s) }
448 for (i = 0; i < (size_t)(sizeof(event_types) / sizeof(event_types[0])); i++)
449 if (type == event_types[i].type)
450 return (event_types[i].name);
451 return (_("BOGUS EVENT TYPE"));
455 * FDSource -- a source for a file descriptor
457 * We could use Glib's GIOChannel for this, but it adds some buffering
458 * and Unicode functionality that we really don't want. The custom GSource
459 * is simple enough anyway, and the Glib documentation describes it in prose.
462 typedef struct FDSource {
463 GSource source; /* must be the first element in the struct */
464 GPollFD pollfd; /* Our file descriptor */
469 GSource *source G_GNUC_UNUSED,
472 *timeout_ = -1; /* block forever, as far as we're concerned */
480 FDSource *fds = (FDSource *)source;
482 /* we need to be dispatched if any interesting events have been received by the FD */
483 return fds->pollfd.events & fds->pollfd.revents;
488 GSource *source G_GNUC_UNUSED,
489 GSourceFunc callback,
493 return callback(user_data);
495 /* Don't automatically detach the event source if there's no callback. */
500 new_fdsource(gint fd, GIOCondition events)
502 static GSourceFuncs *fdsource_funcs = NULL;
506 /* initialize these here to avoid a compiler warning */
507 if (!fdsource_funcs) {
508 fdsource_funcs = g_new0(GSourceFuncs, 1);
509 fdsource_funcs->prepare = fdsource_prepare;
510 fdsource_funcs->check = fdsource_check;
511 fdsource_funcs->dispatch = fdsource_dispatch;
514 src = g_source_new(fdsource_funcs, sizeof(FDSource));
515 fds = (FDSource *)src;
518 fds->pollfd.events = events;
519 g_source_add_poll(src, &fds->pollfd);
525 * ChildWatchSource -- a source for a file descriptor
527 * Newer versions of glib provide equivalent functionality; consider
528 * optionally using that, protected by a GLIB_CHECK_VERSION condition.
531 /* Versions before glib-2.4.0 didn't include a child watch source, and versions
532 * before 2.6.0 used unreliable signals. On these versions, we implement
533 * a "dumb" version of our own invention. This is dumb in the sense that it
534 * doesn't use SIGCHLD to detect a dead child, preferring to just poll at
535 * exponentially increasing interals. Writing a smarter implementation runs into
536 * some tricky race conditions and extra machinery. Since there are few, if any,
537 * users of a glib version this old, such machinery wouldn't get much testing.
539 * FreeBSD users have also reported problems with the glib child watch source,
540 * so we use the dumb version on FreeBSD, too.
543 #if (defined(__FreeBSD__) || GLIB_MAJOR_VERSION < 2 || (GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 6))
544 typedef struct ChildWatchSource {
545 GSource source; /* must be the first element in the struct */
555 /* this corresponds to rapid checks for about 10 seconds, after which the
556 * waitpid() check occurs every 2 seconds. */
557 #define CWS_BASE_TIMEOUT 20
558 #define CWS_MULT_TIMEOUT 1.1
559 #define CWS_MAX_TIMEOUT 2000
562 child_watch_source_prepare(
566 ChildWatchSource *cws = (ChildWatchSource *)source;
568 *timeout_ = cws->timeout;
570 cws->timeout *= CWS_MULT_TIMEOUT;
571 if (cws->timeout > CWS_MAX_TIMEOUT) cws->timeout = CWS_MAX_TIMEOUT;
577 child_watch_source_check(
580 ChildWatchSource *cws = (ChildWatchSource *)source;
583 if (!cws->dead && waitpid(cws->pid, &cws->status, WNOHANG) > 0) {
591 child_watch_source_dispatch(
592 GSource *source G_GNUC_UNUSED,
593 GSourceFunc callback,
596 ChildWatchSource *cws = (ChildWatchSource *)source;
598 /* this shouldn't happen, but just in case */
601 g_warning("child %jd died before callback was registered", (uintmax_t)cws->pid);
605 ((ChildWatchFunc)callback)(cws->pid, cws->status, user_data);
607 /* Un-queue this source unconditionally -- the child can't die twice */
615 new_child_watch_source(pid_t pid)
617 static GSourceFuncs *child_watch_source_funcs = NULL;
619 ChildWatchSource *cws;
621 /* initialize these here to avoid a compiler warning */
622 if (!child_watch_source_funcs) {
623 child_watch_source_funcs = g_new0(GSourceFuncs, 1);
624 child_watch_source_funcs->prepare = child_watch_source_prepare;
625 child_watch_source_funcs->check = child_watch_source_check;
626 child_watch_source_funcs->dispatch = child_watch_source_dispatch;
629 src = g_source_new(child_watch_source_funcs, sizeof(ChildWatchSource));
630 cws = (ChildWatchSource *)src;
634 cws->timeout = CWS_BASE_TIMEOUT;
639 /* In more recent versions of glib, we just use the built-in glib source */
641 new_child_watch_source(pid_t pid)
643 return g_child_watch_source_new(pid);