object_event.c 31.5 KB
Newer Older
1 2 3
/*
 * object_event.c: object event queue processing helpers
 *
4
 * Copyright (C) 2010-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 * Copyright (C) 2008 VirtualIron
 * Copyright (C) 2013 SUSE LINUX Products GmbH, Nuernberg, Germany.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Ben Guthro
 */

#include <config.h>

#include "domain_event.h"
28
#include "network_event.h"
29 30 31 32 33 34
#include "object_event.h"
#include "object_event_private.h"
#include "virlog.h"
#include "datatypes.h"
#include "viralloc.h"
#include "virerror.h"
35
#include "virobject.h"
36 37 38 39
#include "virstring.h"

#define VIR_FROM_THIS VIR_FROM_NONE

40 41
VIR_LOG_INIT("conf.object_event");

42 43 44 45 46 47
struct _virObjectEventCallback {
    int callbackID;
    virClassPtr klass;
    int eventID;
    virConnectPtr conn;
    int remoteID;
48 49
    bool key_filter;
    char *key;
50 51 52 53 54 55 56 57 58 59 60
    virObjectEventCallbackFilter filter;
    void *filter_opaque;
    virConnectObjectEventGenericCallback cb;
    void *opaque;
    virFreeCallback freecb;
    bool deleted;
    bool legacy; /* true if end user does not know callbackID */
};
typedef struct _virObjectEventCallback virObjectEventCallback;
typedef virObjectEventCallback *virObjectEventCallbackPtr;

61 62 63 64 65 66
struct _virObjectEventCallbackList {
    unsigned int nextID;
    size_t count;
    virObjectEventCallbackPtr *callbacks;
};

67
struct _virObjectEventQueue {
68
    size_t count;
69 70
    virObjectEventPtr *events;
};
71 72 73 74
typedef struct _virObjectEventQueue virObjectEventQueue;
typedef virObjectEventQueue *virObjectEventQueuePtr;

struct _virObjectEventState {
75
    virObjectLockable parent;
76 77 78 79 80 81 82 83 84 85
    /* The list of domain event callbacks */
    virObjectEventCallbackListPtr callbacks;
    /* The queue of object events */
    virObjectEventQueuePtr queue;
    /* Timer for flushing events queue */
    int timer;
    /* Flag if we're in process of dispatching */
    bool isDispatching;
};

86
static virClassPtr virObjectEventClass;
87
static virClassPtr virObjectEventStateClass;
88 89

static void virObjectEventDispose(void *obj);
90
static void virObjectEventStateDispose(void *obj);
91

92 93
static int
virObjectEventOnceInit(void)
94
{
95
    if (!VIR_CLASS_NEW(virObjectEventState, virClassForObjectLockable()))
96 97
        return -1;

98
    if (!VIR_CLASS_NEW(virObjectEvent, virClassForObject()))
99
        return -1;
100

101 102 103 104 105
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virObjectEvent)

106 107 108 109 110 111
/**
 * virClassForObjectEvent:
 *
 * Return the class object to be used as a parent when creating an
 * event subclass.
 */
112 113
virClassPtr
virClassForObjectEvent(void)
114 115 116 117 118 119 120
{
    if (virObjectEventInitialize() < 0)
        return NULL;
    return virObjectEventClass;
}


121 122
static void
virObjectEventDispose(void *obj)
123 124 125 126 127 128
{
    virObjectEventPtr event = obj;

    VIR_DEBUG("obj=%p", event);

    VIR_FREE(event->meta.name);
129
    VIR_FREE(event->meta.key);
130 131
}

132 133 134 135 136 137 138 139 140 141 142 143 144
/**
 * virObjectEventCallbackFree:
 * @list: event callback to free
 *
 * Free the memory in the domain event callback
 */
static void
virObjectEventCallbackFree(virObjectEventCallbackPtr cb)
{
    if (!cb)
        return;

    virObjectUnref(cb->conn);
145
    VIR_FREE(cb->key);
146 147 148
    VIR_FREE(cb);
}

149 150 151 152 153 154 155 156 157 158 159 160 161
/**
 * virObjectEventCallbackListFree:
 * @list: event callback list head
 *
 * Free the memory in the domain event callback list
 */
static void
virObjectEventCallbackListFree(virObjectEventCallbackListPtr list)
{
    size_t i;
    if (!list)
        return;

162
    for (i = 0; i < list->count; i++) {
163 164 165 166 167 168 169 170 171 172
        virFreeCallback freecb = list->callbacks[i]->freecb;
        if (freecb)
            (*freecb)(list->callbacks[i]->opaque);
        VIR_FREE(list->callbacks[i]);
    }
    VIR_FREE(list->callbacks);
    VIR_FREE(list);
}


173 174 175 176 177 178
/**
 * virObjectEventCallbackListCount:
 * @conn: pointer to the connection
 * @cbList: the list
 * @klass: the base event class
 * @eventID: the event ID
179
 * @key: optional key of per-object filtering
180
 * @serverFilter: true if server supports object filtering
181 182
 *
 * Internal function to count how many callbacks remain registered for
183
 * the given @eventID and @key; knowing this allows the client side
184 185 186 187 188
 * of the remote driver know when it must send an RPC to adjust the
 * callbacks on the server.  When @serverFilter is false, this function
 * returns a count that includes both global and per-object callbacks,
 * since the remote side will use a single global event to feed both.
 * When true, the count is limited to the callbacks with the same
189
 * @key, and where a remoteID has already been set on the callback
190 191 192 193
 * with virObjectEventStateSetRemote().  Note that this function
 * intentionally ignores the legacy field, since RPC calls use only a
 * single callback on the server to manage both legacy and modern
 * global domain lifecycle events.
194 195 196 197 198
 */
static int
virObjectEventCallbackListCount(virConnectPtr conn,
                                virObjectEventCallbackListPtr cbList,
                                virClassPtr klass,
199
                                int eventID,
200
                                const char *key,
201
                                bool serverFilter)
202 203 204 205 206 207 208
{
    size_t i;
    int ret = 0;

    for (i = 0; i < cbList->count; i++) {
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

209 210
        if (cb->filter)
            continue;
211 212 213
        if (cb->klass == klass &&
            cb->eventID == eventID &&
            cb->conn == conn &&
214 215 216
            !cb->deleted &&
            (!serverFilter ||
             (cb->remoteID >= 0 &&
217 218
              ((key && cb->key_filter && STREQ(cb->key, key)) ||
               (!key && !cb->key_filter)))))
219 220 221 222 223
            ret++;
    }
    return ret;
}

224 225 226 227 228
/**
 * virObjectEventCallbackListRemoveID:
 * @conn: pointer to the connection
 * @cbList: the list
 * @callback: the callback to remove
229
 * @doFreeCb: Inhibit calling the freecb
230 231 232 233 234 235
 *
 * Internal function to remove a callback from a virObjectEventCallbackListPtr
 */
static int
virObjectEventCallbackListRemoveID(virConnectPtr conn,
                                   virObjectEventCallbackListPtr cbList,
236 237
                                   int callbackID,
                                   bool doFreeCb)
238 239 240
{
    size_t i;

241 242 243 244
    for (i = 0; i < cbList->count; i++) {
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->callbackID == callbackID && cb->conn == conn) {
245 246
            int ret;

247 248 249
            ret = cb->filter ? 0 :
                (virObjectEventCallbackListCount(conn, cbList, cb->klass,
                                                 cb->eventID,
250
                                                 cb->key_filter ? cb->key : NULL,
251
                                                 cb->remoteID >= 0) - 1);
252

253 254 255 256
            /* @doFreeCb inhibits calling @freecb from error paths in
             * register functions to ensure the caller of a failed register
             * function won't end up with a double free error */
            if (doFreeCb && cb->freecb)
257
                (*cb->freecb)(cb->opaque);
258
            virObjectEventCallbackFree(cb);
259
            VIR_DELETE_ELEMENT(cbList->callbacks, i, cbList->count);
260
            return ret;
261 262 263
        }
    }

264 265 266
    virReportError(VIR_ERR_INVALID_ARG,
                   _("could not find event callback %d for deletion"),
                   callbackID);
267 268 269 270 271 272 273 274 275 276
    return -1;
}


static int
virObjectEventCallbackListMarkDeleteID(virConnectPtr conn,
                                       virObjectEventCallbackListPtr cbList,
                                       int callbackID)
{
    size_t i;
277

278
    for (i = 0; i < cbList->count; i++) {
279 280 281 282
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->callbackID == callbackID && cb->conn == conn) {
            cb->deleted = true;
283 284 285
            return cb->filter ? 0 :
                virObjectEventCallbackListCount(conn, cbList, cb->klass,
                                                cb->eventID,
286
                                                cb->key_filter ? cb->key : NULL,
287
                                                cb->remoteID >= 0);
288 289 290
        }
    }

291 292 293
    virReportError(VIR_ERR_INVALID_ARG,
                   _("could not find event callback %d for deletion"),
                   callbackID);
294 295 296 297 298 299 300
    return -1;
}


static int
virObjectEventCallbackListPurgeMarked(virObjectEventCallbackListPtr cbList)
{
301
    size_t n;
302 303 304 305 306
    for (n = 0; n < cbList->count; n++) {
        if (cbList->callbacks[n]->deleted) {
            virFreeCallback freecb = cbList->callbacks[n]->freecb;
            if (freecb)
                (*freecb)(cbList->callbacks[n]->opaque);
307
            virObjectEventCallbackFree(cbList->callbacks[n]);
308

309
            VIR_DELETE_ELEMENT(cbList->callbacks, n, cbList->count);
310 311 312 313 314 315 316
            n--;
        }
    }
    return 0;
}


317 318 319 320
/**
 * virObjectEventCallbackLookup:
 * @conn: pointer to the connection
 * @cbList: the list
321
 * @key: the key of the object to filter on
322 323 324
 * @klass: the base event class
 * @eventID: the event ID
 * @callback: the callback to locate
325
 * @legacy: true if callback is tracked by function instead of callbackID
326
 * @remoteID: optionally return a known remoteID
327 328
 *
 * Internal function to determine if @callback already has a
329 330 331 332
 * callbackID in @cbList for the given @conn and other filters.  If
 * @remoteID is non-NULL, and another callback exists that can be
 * serviced by the same remote event, then set it to that remote ID.
 *
333 334 335 336 337
 * Return the id if found, or -1 with no error issued if not present.
 */
static int ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2)
virObjectEventCallbackLookup(virConnectPtr conn,
                             virObjectEventCallbackListPtr cbList,
338
                             const char *key,
339 340
                             virClassPtr klass,
                             int eventID,
341
                             virConnectObjectEventGenericCallback callback,
342 343
                             bool legacy,
                             int *remoteID)
344 345 346
{
    size_t i;

347 348 349
    if (remoteID)
        *remoteID = -1;

350 351 352 353 354
    for (i = 0; i < cbList->count; i++) {
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->deleted)
            continue;
355
        if (cb->klass == klass &&
356 357
            cb->eventID == eventID &&
            cb->conn == conn &&
358 359
            ((key && cb->key_filter && STREQ(cb->key, key)) ||
             (!key && !cb->key_filter))) {
360 361
            if (remoteID)
                *remoteID = cb->remoteID;
362 363
            if (cb->legacy == legacy &&
                cb->cb == callback)
364
                return cb->callbackID;
365 366
        }
    }
367
    return -1;
368 369 370
}


371 372 373 374
/**
 * virObjectEventCallbackListAddID:
 * @conn: pointer to the connection
 * @cbList: the list
375
 * @key: the optional key of the object to filter on
376 377
 * @filter: optional last-ditch filter callback
 * @filter_opaque: opaque data to pass to @filter
378
 * @klass: the base event class
379 380
 * @eventID: the event ID
 * @callback: the callback to add
381 382
 * @opaque: opaque data to pass to @callback
 * @freecb: callback to free @opaque
383
 * @legacy: true if callback is tracked by function instead of callbackID
384
 * @callbackID: filled with callback ID
385
 * @serverFilter: true if server supports object filtering
386 387 388
 *
 * Internal function to add a callback from a virObjectEventCallbackListPtr
 */
389
static int
390 391
virObjectEventCallbackListAddID(virConnectPtr conn,
                                virObjectEventCallbackListPtr cbList,
392
                                const char *key,
393 394
                                virObjectEventCallbackFilter filter,
                                void *filter_opaque,
395
                                virClassPtr klass,
396 397 398 399
                                int eventID,
                                virConnectObjectEventGenericCallback callback,
                                void *opaque,
                                virFreeCallback freecb,
400
                                bool legacy,
401 402
                                int *callbackID,
                                bool serverFilter)
403
{
404
    virObjectEventCallbackPtr cb;
405
    int ret = -1;
406
    int remoteID = -1;
407

408
    VIR_DEBUG("conn=%p cblist=%p key=%p filter=%p filter_opaque=%p "
409 410
              "klass=%p eventID=%d callback=%p opaque=%p "
              "legacy=%d callbackID=%p serverFilter=%d",
411
              conn, cbList, key, filter, filter_opaque, klass, eventID,
412
              callback, opaque, legacy, callbackID, serverFilter);
413

414
    /* Check incoming */
415
    if (!cbList)
416 417
        return -1;

418 419 420
    /* If there is no additional filtering, then check if we already
     * have this callback on our list.  */
    if (!filter &&
421
        virObjectEventCallbackLookup(conn, cbList, key,
422
                                     klass, eventID, callback, legacy,
423
                                     serverFilter ? &remoteID : NULL) != -1) {
424
        virReportError(VIR_ERR_INVALID_ARG, "%s",
425 426
                       _("event callback already tracked"));
        return -1;
427
    }
428 429
    /* Allocate new cb */
    if (VIR_ALLOC(cb) < 0)
430
        goto cleanup;
431 432 433 434 435 436 437 438
    cb->conn = virObjectRef(conn);
    *callbackID = cb->callbackID = cbList->nextID++;
    cb->cb = callback;
    cb->klass = klass;
    cb->eventID = eventID;
    cb->opaque = opaque;
    cb->freecb = freecb;
    cb->remoteID = remoteID;
439

440 441 442
    if (key) {
        cb->key_filter = true;
        if (VIR_STRDUP(cb->key, key) < 0)
C
Cole Robinson 已提交
443
            goto cleanup;
444
    }
445 446 447
    cb->filter = filter;
    cb->filter_opaque = filter_opaque;
    cb->legacy = legacy;
448

449
    if (VIR_APPEND_ELEMENT(cbList->callbacks, cbList->count, cb) < 0)
450
        goto cleanup;
451

452 453 454 455 456 457
    /* When additional filtering is being done, every client callback
     * is matched to exactly one server callback.  */
    if (filter) {
        ret = 1;
    } else {
        ret = virObjectEventCallbackListCount(conn, cbList, klass, eventID,
458
                                              key, serverFilter);
459 460 461
        if (serverFilter && remoteID < 0)
            ret++;
    }
462

463
 cleanup:
464
    virObjectEventCallbackFree(cb);
465
    return ret;
466 467 468 469 470 471 472 473 474
}


/**
 * virObjectEventQueueClear:
 * @queue: pointer to the queue
 *
 * Removes all elements from the queue
 */
475
static void
476 477 478 479 480 481
virObjectEventQueueClear(virObjectEventQueuePtr queue)
{
    size_t i;
    if (!queue)
        return;

482
    for (i = 0; i < queue->count; i++)
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        virObjectUnref(queue->events[i]);
    VIR_FREE(queue->events);
    queue->count = 0;
}

/**
 * virObjectEventQueueFree:
 * @queue: pointer to the queue
 *
 * Free the memory in the queue. We process this like a list here
 */
static void
virObjectEventQueueFree(virObjectEventQueuePtr queue)
{
    if (!queue)
        return;

    virObjectEventQueueClear(queue);
    VIR_FREE(queue);
}

static virObjectEventQueuePtr
virObjectEventQueueNew(void)
{
    virObjectEventQueuePtr ret;

    ignore_value(VIR_ALLOC(ret));
    return ret;
}

513 514

/**
515
 * virObjectEventStateDispose:
516 517 518 519
 * @list: virObjectEventStatePtr to free
 *
 * Free a virObjectEventStatePtr and its members, and unregister the timer.
 */
520 521
static void
virObjectEventStateDispose(void *obj)
522
{
523 524 525
    virObjectEventStatePtr state = obj;

    VIR_DEBUG("obj=%p", state);
526 527 528 529 530 531 532 533 534 535 536

    virObjectEventCallbackListFree(state->callbacks);
    virObjectEventQueueFree(state->queue);

    if (state->timer != -1)
        virEventRemoveTimeout(state->timer);
}


static void virObjectEventStateFlush(virObjectEventStatePtr state);

537 538 539 540 541 542 543 544 545 546

/**
 * virObjectEventTimer:
 * @timer: id of the event loop timer
 * @opaque: the event state object
 *
 * Register this function with the event state as its opaque data as
 * the callback of a periodic timer on the event loop, in order to
 * flush the callback queue.
 */
547
static void
548 549 550 551 552 553 554
virObjectEventTimer(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    virObjectEventStatePtr state = opaque;

    virObjectEventStateFlush(state);
}

555

556 557
/**
 * virObjectEventStateNew:
558 559
 *
 * Allocate a new event state object.
560 561 562 563 564 565
 */
virObjectEventStatePtr
virObjectEventStateNew(void)
{
    virObjectEventStatePtr state = NULL;

566 567
    if (virObjectEventInitialize() < 0)
        return NULL;
568

569 570
    if (!(state = virObjectLockableNew(virObjectEventStateClass)))
        return NULL;
571 572 573 574 575 576 577 578 579 580 581

    if (VIR_ALLOC(state->callbacks) < 0)
        goto error;

    if (!(state->queue = virObjectEventQueueNew()))
        goto error;

    state->timer = -1;

    return state;

582
 error:
583
    virObjectUnref(state);
584 585 586
    return NULL;
}

587 588 589 590 591 592 593 594 595

/**
 * virObjectEventNew:
 * @klass: subclass of event to be created
 * @dispatcher: callback for dispatching the particular subclass of event
 * @eventID: id of the event
 * @id: id of the object the event describes, or 0
 * @name: name of the object the event describes
 * @uuid: uuid of the object the event describes
596
 * @key: key for per-object filtering
597 598 599
 *
 * Create a new event, with the information common to all events.
 */
600 601
void *
virObjectEventNew(virClassPtr klass,
602
                  virObjectEventDispatchFunc dispatcher,
603 604 605
                  int eventID,
                  int id,
                  const char *name,
606 607
                  const unsigned char *uuid,
                  const char *key)
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
{
    virObjectEventPtr event;

    if (virObjectEventInitialize() < 0)
        return NULL;

    if (!virClassIsDerivedFrom(klass, virObjectEventClass)) {
        virReportInvalidArg(klass,
                            _("Class %s must derive from virObjectEvent"),
                            virClassName(klass));
        return NULL;
    }

    if (!(event = virObjectNew(klass)))
        return NULL;

624
    event->dispatch = dispatcher;
625
    event->eventID = eventID;
626
    event->remoteID = -1;
627

628 629 630
    if (VIR_STRDUP(event->meta.name, name) < 0 ||
        VIR_STRDUP(event->meta.key, key) < 0) {
        virObjectUnref(event);
631 632
        return NULL;
    }
633
    event->meta.id = id;
634 635
    if (uuid)
        memcpy(event->meta.uuid, uuid, VIR_UUID_BUFLEN);
636 637 638 639 640

    VIR_DEBUG("obj=%p", event);
    return event;
}

641

642 643 644 645 646 647 648 649 650 651 652 653 654
/**
 * virObjectEventQueuePush:
 * @evtQueue: the object event queue
 * @event: the event to add
 *
 * Internal function to push to the back of a virObjectEventQueue
 *
 * Returns: 0 on success, -1 on failure
 */
static int
virObjectEventQueuePush(virObjectEventQueuePtr evtQueue,
                        virObjectEventPtr event)
{
655
    if (!evtQueue)
656 657
        return -1;

658
    if (VIR_APPEND_ELEMENT(evtQueue->events, evtQueue->count, event) < 0)
659 660 661 662 663
        return -1;
    return 0;
}


E
Eric Blake 已提交
664
static bool
665 666
virObjectEventDispatchMatchCallback(virObjectEventPtr event,
                                    virObjectEventCallbackPtr cb)
667 668
{
    if (!cb)
E
Eric Blake 已提交
669
        return false;
670
    if (cb->deleted)
E
Eric Blake 已提交
671
        return false;
672
    if (!virObjectIsClass(event, cb->klass))
E
Eric Blake 已提交
673
        return false;
674
    if (cb->eventID != event->eventID)
E
Eric Blake 已提交
675
        return false;
676 677
    if (cb->remoteID != event->remoteID)
        return false;
678

679 680 681
    if (cb->filter && !(cb->filter)(cb->conn, event, cb->filter_opaque))
        return false;

682 683
    if (cb->key_filter)
        return STREQ(event->meta.key, cb->key);
E
Eric Blake 已提交
684
    return true;
685 686 687 688
}


static void
689 690 691
virObjectEventStateDispatchCallbacks(virObjectEventStatePtr state,
                                     virObjectEventPtr event,
                                     virObjectEventCallbackListPtr callbacks)
692 693 694 695 696
{
    size_t i;
    /* Cache this now, since we may be dropping the lock,
       and have more callbacks added. We're guaranteed not
       to have any removed */
697
    size_t cbCount = callbacks->count;
698 699

    for (i = 0; i < cbCount; i++) {
700 701 702
        virObjectEventCallbackPtr cb = callbacks->callbacks[i];

        if (!virObjectEventDispatchMatchCallback(event, cb))
703 704
            continue;

705
        /* Drop the lock whle dispatching, for sake of re-entrancy */
706
        virObjectUnlock(state);
707
        event->dispatch(cb->conn, event, cb->cb, cb->opaque);
708
        virObjectLock(state);
709 710 711 712 713
    }
}


static void
714 715 716
virObjectEventStateQueueDispatch(virObjectEventStatePtr state,
                                 virObjectEventQueuePtr queue,
                                 virObjectEventCallbackListPtr callbacks)
717 718 719 720
{
    size_t i;

    for (i = 0; i < queue->count; i++) {
721 722
        virObjectEventStateDispatchCallbacks(state, queue->events[i],
                                             callbacks);
723 724 725 726 727 728
        virObjectUnref(queue->events[i]);
    }
    VIR_FREE(queue->events);
    queue->count = 0;
}

729 730

/**
731
 * virObjectEventStateQueueRemote:
732 733
 * @state: the event state object
 * @event: event to add to the queue
734
 * @remoteID: limit dispatch to callbacks with the same remote id
735 736 737
 *
 * Adds @event to the queue of events to be dispatched at the next
 * safe moment.  The caller should no longer use @event after this
738 739 740
 * call.  If @remoteID is non-negative, the event will only be sent to
 * callbacks where virObjectEventStateSetRemote() registered a remote
 * id.
741
 */
742
void
743 744 745
virObjectEventStateQueueRemote(virObjectEventStatePtr state,
                               virObjectEventPtr event,
                               int remoteID)
746
{
747 748 749
    if (!event)
        return;

750 751 752 753 754
    if (state->timer < 0) {
        virObjectUnref(event);
        return;
    }

755
    virObjectLock(state);
756

757
    event->remoteID = remoteID;
758 759 760 761 762 763 764
    if (virObjectEventQueuePush(state->queue, event) < 0) {
        VIR_DEBUG("Error adding event to queue");
        virObjectUnref(event);
    }

    if (state->queue->count == 1)
        virEventUpdateTimeout(state->timer, 0);
765
    virObjectUnlock(state);
766 767 768
}


769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
/**
 * virObjectEventStateQueue:
 * @state: the event state object
 * @event: event to add to the queue
 *
 * Adds @event to the queue of events to be dispatched at the next
 * safe moment.  The caller should no longer use @event after this
 * call.
 */
void
virObjectEventStateQueue(virObjectEventStatePtr state,
                         virObjectEventPtr event)
{
    virObjectEventStateQueueRemote(state, event, -1);
}


786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
static void
virObjectEventStateCleanupTimer(virObjectEventStatePtr state, bool clear_queue)
{
    /* There are still some callbacks, keep the timer. */
    if (state->callbacks->count)
        return;

    /* The timer is not registered, nothing to do. */
    if (state->timer == -1)
        return;

    virEventRemoveTimeout(state->timer);
    state->timer = -1;

    if (clear_queue)
        virObjectEventQueueClear(state->queue);
}


805 806 807 808 809
static void
virObjectEventStateFlush(virObjectEventStatePtr state)
{
    virObjectEventQueue tempQueue;

810 811 812
    /* We need to lock as well as ref due to the fact that we might
     * unref the state we're working on in this very function */
    virObjectRef(state);
813
    virObjectLock(state);
814 815 816 817 818 819 820 821
    state->isDispatching = true;

    /* Copy the queue, so we're reentrant safe when dispatchFunc drops the
     * driver lock */
    tempQueue.count = state->queue->count;
    tempQueue.events = state->queue->events;
    state->queue->count = 0;
    state->queue->events = NULL;
822 823
    if (state->timer != -1)
        virEventUpdateTimeout(state->timer, -1);
824

825 826 827
    virObjectEventStateQueueDispatch(state,
                                     &tempQueue,
                                     state->callbacks);
828 829 830 831

    /* Purge any deleted callbacks */
    virObjectEventCallbackListPurgeMarked(state->callbacks);

832 833 834 835
    /* If we purged all callbacks, we need to remove the timeout as
     * well like virObjectEventStateDeregisterID() would do. */
    virObjectEventStateCleanupTimer(state, true);

836
    state->isDispatching = false;
837
    virObjectUnlock(state);
838
    virObjectUnref(state);
839 840 841 842 843 844 845
}


/**
 * virObjectEventStateRegisterID:
 * @conn: connection to associate with callback
 * @state: domain event state
846
 * @key: key of the object for event filtering
847
 * @klass: the base event class
848
 * @eventID: ID of the event type to register for
849 850
 * @cb: function to invoke when event occurs
 * @opaque: data blob to pass to @callback
851
 * @freecb: callback to free @opaque
852
 * @legacy: true if callback is tracked by function instead of callbackID
853
 * @callbackID: filled with callback ID
854
 * @serverFilter: true if server supports object filtering
855
 *
856 857 858
 * Register the function @cb with connection @conn, from @state, for
 * events of type @eventID, and return the registration handle in
 * @callbackID.
859
 *
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
 * The return value is only important when registering client-side
 * mirroring of remote events (since the public API is documented to
 * return the callbackID rather than a count).  A return of 1 means
 * that this is the first use of this type of event, so a remote event
 * must be enabled; a return larger than 1 means that an existing
 * remote event can already feed this callback.  If @serverFilter is
 * false, the return count assumes that a single global remote feeds
 * both generic and per-object callbacks, and that the event queue
 * will be fed with virObjectEventStateQueue().  If it is true, then
 * the return count assumes that the remote side is capable of per-
 * object filtering; the user must call virObjectEventStateSetRemote()
 * to record the remote id, and queue events with
 * virObjectEventStateQueueRemote().
 *
 * Returns: the number of callbacks now registered, or -1 on error.
875 876 877 878
 */
int
virObjectEventStateRegisterID(virConnectPtr conn,
                              virObjectEventStatePtr state,
879
                              const char *key,
880 881
                              virObjectEventCallbackFilter filter,
                              void *filter_opaque,
882
                              virClassPtr klass,
883 884 885 886
                              int eventID,
                              virConnectObjectEventGenericCallback cb,
                              void *opaque,
                              virFreeCallback freecb,
887
                              bool legacy,
888 889
                              int *callbackID,
                              bool serverFilter)
890 891 892
{
    int ret = -1;

893
    virObjectLock(state);
894 895 896 897 898 899

    if ((state->callbacks->count == 0) &&
        (state->timer == -1) &&
        (state->timer = virEventAddTimeout(-1,
                                           virObjectEventTimer,
                                           state,
900
                                           virObjectFreeCallback)) < 0) {
901 902 903 904 905
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("could not initialize domain event timer"));
        goto cleanup;
    }

906 907 908 909
    /* event loop has one reference, but we need one more for the
     * timer's opaque argument */
    virObjectRef(state);

910
    ret = virObjectEventCallbackListAddID(conn, state->callbacks,
911
                                          key, filter, filter_opaque,
912
                                          klass, eventID,
913
                                          cb, opaque, freecb,
914
                                          legacy, callbackID, serverFilter);
915

916 917
    if (ret < 0)
        virObjectEventStateCleanupTimer(state, false);
918

919
 cleanup:
920
    virObjectUnlock(state);
921 922 923 924 925 926 927 928 929
    return ret;
}


/**
 * virObjectEventStateDeregisterID:
 * @conn: connection to associate with callback
 * @state: object event state
 * @callbackID: ID of the function to remove from event
930
 * @doFreeCb: Allow the calling of a freecb
931 932
 *
 * Unregister the function @callbackID with connection @conn,
933 934 935 936 937
 * from @state, for events. If @doFreeCb is false, then we
 * are being called from a remote call failure path for the
 * Event registration indicating a -1 return to the caller. The
 * caller wouldn't expect us to run their freecb function if it
 * exists, so we cannot do so.
938 939 940 941 942 943
 *
 * Returns: the number of callbacks still registered, or -1 on error
 */
int
virObjectEventStateDeregisterID(virConnectPtr conn,
                                virObjectEventStatePtr state,
944 945
                                int callbackID,
                                bool doFreeCb)
946 947 948
{
    int ret;

949
    virObjectLock(state);
950 951
    if (state->isDispatching)
        ret = virObjectEventCallbackListMarkDeleteID(conn,
952 953
                                                     state->callbacks,
                                                     callbackID);
954
    else
955 956
        ret = virObjectEventCallbackListRemoveID(conn, state->callbacks,
                                                 callbackID, doFreeCb);
957

958
    virObjectEventStateCleanupTimer(state, true);
959

960
    virObjectUnlock(state);
961 962 963
    return ret;
}

964 965 966 967 968 969 970
/**
 * virObjectEventStateCallbackID:
 * @conn: connection associated with callback
 * @state: object event state
 * @klass: the base event class
 * @eventID: the event ID
 * @callback: function registered as a callback
971
 * @remoteID: optional output, containing resulting remote id
972 973
 *
 * Returns the callbackID of @callback, or -1 with an error issued if the
974 975 976
 * function is not currently registered.  This only finds functions
 * registered via virConnectDomainEventRegister, even if modern style
 * virConnectDomainEventRegisterAny also registers the same callback.
977 978 979 980 981 982
 */
int
virObjectEventStateCallbackID(virConnectPtr conn,
                              virObjectEventStatePtr state,
                              virClassPtr klass,
                              int eventID,
983 984
                              virConnectObjectEventGenericCallback callback,
                              int *remoteID)
985 986 987
{
    int ret = -1;

988
    virObjectLock(state);
989
    ret = virObjectEventCallbackLookup(conn, state->callbacks, NULL,
990 991
                                       klass, eventID, callback, true,
                                       remoteID);
992
    virObjectUnlock(state);
993 994

    if (ret < 0)
995
        virReportError(VIR_ERR_INVALID_ARG,
996 997 998 999 1000
                       _("event callback function %p not registered"),
                       callback);
    return ret;
}

1001 1002 1003 1004 1005 1006

/**
 * virObjectEventStateEventID:
 * @conn: connection associated with the callback
 * @state: object event state
 * @callbackID: the callback to query
1007
 * @remoteID: optionally output remote ID of the callback
1008
 *
1009 1010 1011 1012
 * Query what event ID type is associated with the callback
 * @callbackID for connection @conn.  If @remoteID is non-null, it
 * will be set to the remote id previously registered with
 * virObjectEventStateSetRemote().
1013 1014 1015 1016 1017 1018
 *
 * Returns 0 on success, -1 on error
 */
int
virObjectEventStateEventID(virConnectPtr conn,
                           virObjectEventStatePtr state,
1019 1020
                           int callbackID,
                           int *remoteID)
1021
{
1022 1023 1024
    int ret = -1;
    size_t i;
    virObjectEventCallbackListPtr cbList = state->callbacks;
1025

1026
    virObjectLock(state);
1027 1028 1029 1030 1031 1032 1033
    for (i = 0; i < cbList->count; i++) {
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->deleted)
            continue;

        if (cb->callbackID == callbackID && cb->conn == conn) {
1034 1035
            if (remoteID)
                *remoteID = cb->remoteID;
1036 1037 1038 1039
            ret = cb->eventID;
            break;
        }
    }
1040
    virObjectUnlock(state);
1041 1042 1043 1044 1045

    if (ret < 0)
        virReportError(VIR_ERR_INVALID_ARG,
                       _("event callback id %d not registered"),
                       callbackID);
1046 1047
    return ret;
}
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069


/**
 * virObjectEventStateSetRemote:
 * @conn: connection associated with the callback
 * @state: object event state
 * @callbackID: the callback to adjust
 * @remoteID: the remote ID to associate with the callback
 *
 * Update @callbackID for connection @conn to record that it is now
 * tied to @remoteID, and will therefore only match events that are
 * sent with virObjectEventStateQueueRemote() with the same remote ID.
 * Silently does nothing if @callbackID is invalid.
 */
void
virObjectEventStateSetRemote(virConnectPtr conn,
                             virObjectEventStatePtr state,
                             int callbackID,
                             int remoteID)
{
    size_t i;

1070
    virObjectLock(state);
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
    for (i = 0; i < state->callbacks->count; i++) {
        virObjectEventCallbackPtr cb = state->callbacks->callbacks[i];

        if (cb->deleted)
            continue;

        if (cb->callbackID == callbackID && cb->conn == conn) {
            cb->remoteID = remoteID;
            break;
        }
    }
1082
    virObjectUnlock(state);
1083
}