object_event.c 31.1 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 35 36 37 38
#include "object_event.h"
#include "object_event_private.h"
#include "virlog.h"
#include "datatypes.h"
#include "viralloc.h"
#include "virerror.h"
#include "virstring.h"

#define VIR_FROM_THIS VIR_FROM_NONE

39 40
VIR_LOG_INIT("conf.object_event");

41 42 43 44 45 46
struct _virObjectEventCallbackList {
    unsigned int nextID;
    size_t count;
    virObjectEventCallbackPtr *callbacks;
};

47
struct _virObjectEventQueue {
48
    size_t count;
49 50
    virObjectEventPtr *events;
};
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
typedef struct _virObjectEventQueue virObjectEventQueue;
typedef virObjectEventQueue *virObjectEventQueuePtr;

struct _virObjectEventState {
    /* 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;
    virMutex lock;
};

struct _virObjectEventCallback {
    int callbackID;
    virClassPtr klass;
    int eventID;
    virConnectPtr conn;
71
    int remoteID;
72 73
    bool uuid_filter;
    unsigned char uuid[VIR_UUID_BUFLEN];
74 75
    virObjectEventCallbackFilter filter;
    void *filter_opaque;
76 77 78 79
    virConnectObjectEventGenericCallback cb;
    void *opaque;
    virFreeCallback freecb;
    bool deleted;
80
    bool legacy; /* true if end user does not know callbackID */
81
};
82 83 84 85 86

static virClassPtr virObjectEventClass;

static void virObjectEventDispose(void *obj);

87 88
static int
virObjectEventOnceInit(void)
89 90 91 92 93 94 95 96 97 98 99 100
{
    if (!(virObjectEventClass =
          virClassNew(virClassForObject(),
                      "virObjectEvent",
                      sizeof(virObjectEvent),
                      virObjectEventDispose)))
        return -1;
    return 0;
}

VIR_ONCE_GLOBAL_INIT(virObjectEvent)

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


116 117
static void
virObjectEventDispose(void *obj)
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
{
    virObjectEventPtr event = obj;

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

    VIR_FREE(event->meta.name);
}

/**
 * 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;

139
    for (i = 0; i < list->count; i++) {
140 141 142 143 144 145 146 147 148 149
        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);
}


150 151 152 153 154 155
/**
 * virObjectEventCallbackListCount:
 * @conn: pointer to the connection
 * @cbList: the list
 * @klass: the base event class
 * @eventID: the event ID
156 157
 * @uuid: optional uuid of per-object filtering
 * @serverFilter: true if server supports object filtering
158 159
 *
 * Internal function to count how many callbacks remain registered for
160 161 162 163 164 165 166 167 168 169 170
 * the given @eventID and @uuid; knowing this allows the client side
 * 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
 * @uuid, and where a remoteID has already been set on the callback
 * 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.
171 172 173 174 175
 */
static int
virObjectEventCallbackListCount(virConnectPtr conn,
                                virObjectEventCallbackListPtr cbList,
                                virClassPtr klass,
176 177 178
                                int eventID,
                                unsigned char uuid[VIR_UUID_BUFLEN],
                                bool serverFilter)
179 180 181 182 183 184 185
{
    size_t i;
    int ret = 0;

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

186 187
        if (cb->filter)
            continue;
188 189 190
        if (cb->klass == klass &&
            cb->eventID == eventID &&
            cb->conn == conn &&
191 192 193 194 195 196
            !cb->deleted &&
            (!serverFilter ||
             (cb->remoteID >= 0 &&
              ((uuid && cb->uuid_filter &&
                memcmp(cb->uuid, uuid, VIR_UUID_BUFLEN) == 0) ||
               (!uuid && !cb->uuid_filter)))))
197 198 199 200 201
            ret++;
    }
    return ret;
}

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
/**
 * virObjectEventCallbackListRemoveID:
 * @conn: pointer to the connection
 * @cbList: the list
 * @callback: the callback to remove
 *
 * Internal function to remove a callback from a virObjectEventCallbackListPtr
 */
static int
virObjectEventCallbackListRemoveID(virConnectPtr conn,
                                   virObjectEventCallbackListPtr cbList,
                                   int callbackID)
{
    size_t i;

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

        if (cb->callbackID == callbackID && cb->conn == conn) {
221 222
            int ret;

223 224 225 226 227
            ret = cb->filter ? 0 :
                (virObjectEventCallbackListCount(conn, cbList, cb->klass,
                                                 cb->eventID,
                                                 cb->uuid_filter ? cb->uuid : NULL,
                                                 cb->remoteID >= 0) - 1);
228

229 230 231 232 233
            if (cb->freecb)
                (*cb->freecb)(cb->opaque);
            virObjectUnref(cb->conn);
            VIR_FREE(cb);
            VIR_DELETE_ELEMENT(cbList->callbacks, i, cbList->count);
234
            return ret;
235 236 237
        }
    }

238 239 240
    virReportError(VIR_ERR_INVALID_ARG,
                   _("could not find event callback %d for deletion"),
                   callbackID);
241 242 243 244 245 246 247 248 249 250
    return -1;
}


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

252
    for (i = 0; i < cbList->count; i++) {
253 254 255 256
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->callbackID == callbackID && cb->conn == conn) {
            cb->deleted = true;
257 258 259 260 261
            return cb->filter ? 0 :
                virObjectEventCallbackListCount(conn, cbList, cb->klass,
                                                cb->eventID,
                                                cb->uuid_filter ? cb->uuid : NULL,
                                                cb->remoteID >= 0);
262 263 264
        }
    }

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


static int
virObjectEventCallbackListPurgeMarked(virObjectEventCallbackListPtr cbList)
{
275
    size_t n;
276 277 278 279 280 281 282 283
    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);
            virObjectUnref(cbList->callbacks[n]->conn);
            VIR_FREE(cbList->callbacks[n]);

284
            VIR_DELETE_ELEMENT(cbList->callbacks, n, cbList->count);
285 286 287 288 289 290 291
            n--;
        }
    }
    return 0;
}


292 293 294 295 296 297 298 299
/**
 * virObjectEventCallbackLookup:
 * @conn: pointer to the connection
 * @cbList: the list
 * @uuid: the uuid of the object to filter on
 * @klass: the base event class
 * @eventID: the event ID
 * @callback: the callback to locate
300
 * @legacy: true if callback is tracked by function instead of callbackID
301
 * @remoteID: optionally return a known remoteID
302 303
 *
 * Internal function to determine if @callback already has a
304 305 306 307
 * 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.
 *
308 309 310 311 312 313 314 315
 * 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,
                             unsigned char uuid[VIR_UUID_BUFLEN],
                             virClassPtr klass,
                             int eventID,
316
                             virConnectObjectEventGenericCallback callback,
317 318
                             bool legacy,
                             int *remoteID)
319 320 321
{
    size_t i;

322 323 324
    if (remoteID)
        *remoteID = -1;

325 326 327 328 329
    for (i = 0; i < cbList->count; i++) {
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->deleted)
            continue;
330
        if (cb->klass == klass &&
331 332
            cb->eventID == eventID &&
            cb->conn == conn &&
333 334 335
            ((uuid && cb->uuid_filter &&
              memcmp(cb->uuid, uuid, VIR_UUID_BUFLEN) == 0) ||
             (!uuid && !cb->uuid_filter))) {
336 337
            if (remoteID)
                *remoteID = cb->remoteID;
338 339
            if (cb->legacy == legacy &&
                cb->cb == callback)
340
                return cb->callbackID;
341 342
        }
    }
343
    return -1;
344 345 346
}


347 348 349 350
/**
 * virObjectEventCallbackListAddID:
 * @conn: pointer to the connection
 * @cbList: the list
351 352 353
 * @uuid: the optional uuid of the object to filter on
 * @filter: optional last-ditch filter callback
 * @filter_opaque: opaque data to pass to @filter
354
 * @klass: the base event class
355 356
 * @eventID: the event ID
 * @callback: the callback to add
357 358
 * @opaque: opaque data to pass to @callback
 * @freecb: callback to free @opaque
359
 * @legacy: true if callback is tracked by function instead of callbackID
360
 * @callbackID: filled with callback ID
361
 * @serverFilter: true if server supports object filtering
362 363 364
 *
 * Internal function to add a callback from a virObjectEventCallbackListPtr
 */
365
static int
366 367 368
virObjectEventCallbackListAddID(virConnectPtr conn,
                                virObjectEventCallbackListPtr cbList,
                                unsigned char uuid[VIR_UUID_BUFLEN],
369 370
                                virObjectEventCallbackFilter filter,
                                void *filter_opaque,
371
                                virClassPtr klass,
372 373 374 375
                                int eventID,
                                virConnectObjectEventGenericCallback callback,
                                void *opaque,
                                virFreeCallback freecb,
376
                                bool legacy,
377 378
                                int *callbackID,
                                bool serverFilter)
379 380
{
    virObjectEventCallbackPtr event;
381
    int ret = -1;
382
    int remoteID = -1;
383

384
    VIR_DEBUG("conn=%p cblist=%p uuid=%p filter=%p filter_opaque=%p "
385 386 387 388
              "klass=%p eventID=%d callback=%p opaque=%p "
              "legacy=%d callbackID=%p serverFilter=%d",
              conn, cbList, uuid, filter, filter_opaque, klass, eventID,
              callback, opaque, legacy, callbackID, serverFilter);
389

390
    /* Check incoming */
391
    if (!cbList)
392 393
        return -1;

394 395 396 397
    /* If there is no additional filtering, then check if we already
     * have this callback on our list.  */
    if (!filter &&
        virObjectEventCallbackLookup(conn, cbList, uuid,
398
                                     klass, eventID, callback, legacy,
399
                                     serverFilter ? &remoteID : NULL) != -1) {
400
        virReportError(VIR_ERR_INVALID_ARG, "%s",
401 402
                       _("event callback already tracked"));
        return -1;
403 404 405
    }
    /* Allocate new event */
    if (VIR_ALLOC(event) < 0)
406 407
        goto cleanup;
    event->conn = virObjectRef(conn);
408
    *callbackID = event->callbackID = cbList->nextID++;
409
    event->cb = callback;
410
    event->klass = klass;
411 412 413
    event->eventID = eventID;
    event->opaque = opaque;
    event->freecb = freecb;
414
    event->remoteID = remoteID;
415

416 417 418 419 420 421
    /* Only need 'uuid' for matching; 'id' can change as domain
     * switches between running and shutoff, and 'name' can change in
     * Xen migration.  */
    if (uuid) {
        event->uuid_filter = true;
        memcpy(event->uuid, uuid, VIR_UUID_BUFLEN);
422
    }
423 424
    event->filter = filter;
    event->filter_opaque = filter_opaque;
425
    event->legacy = legacy;
426

427 428
    if (VIR_APPEND_ELEMENT(cbList->callbacks, cbList->count, event) < 0)
        goto cleanup;
429

430 431 432 433 434 435 436 437 438 439
    /* 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,
                                              uuid, serverFilter);
        if (serverFilter && remoteID < 0)
            ret++;
    }
440

441
 cleanup:
442
    if (event)
443
        virObjectUnref(event->conn);
444
    VIR_FREE(event);
445
    return ret;
446 447 448 449 450 451 452 453 454
}


/**
 * virObjectEventQueueClear:
 * @queue: pointer to the queue
 *
 * Removes all elements from the queue
 */
455
static void
456 457 458 459 460 461
virObjectEventQueueClear(virObjectEventQueuePtr queue)
{
    size_t i;
    if (!queue)
        return;

462
    for (i = 0; i < queue->count; i++)
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
        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;
}

493 494 495 496 497 498 499

/**
 * virObjectEventStateLock:
 * @state: the event state object
 *
 * Lock event state before calling functions from object_event_private.h.
 */
500
static void
501 502 503 504 505
virObjectEventStateLock(virObjectEventStatePtr state)
{
    virMutexLock(&state->lock);
}

506 507 508 509 510 511 512

/**
 * virObjectEventStateUnlock:
 * @state: the event state object
 *
 * Unlock event state after calling functions from object_event_private.h.
 */
513
static void
514 515 516 517 518
virObjectEventStateUnlock(virObjectEventStatePtr state)
{
    virMutexUnlock(&state->lock);
}

519

520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
/**
 * virObjectEventStateFree:
 * @list: virObjectEventStatePtr to free
 *
 * Free a virObjectEventStatePtr and its members, and unregister the timer.
 */
void
virObjectEventStateFree(virObjectEventStatePtr state)
{
    if (!state)
        return;

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

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

    virMutexDestroy(&state->lock);
    VIR_FREE(state);
}


static void virObjectEventStateFlush(virObjectEventStatePtr state);

545 546 547 548 549 550 551 552 553 554

/**
 * 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.
 */
555
static void
556 557 558 559 560 561 562
virObjectEventTimer(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    virObjectEventStatePtr state = opaque;

    virObjectEventStateFlush(state);
}

563

564 565
/**
 * virObjectEventStateNew:
566 567
 *
 * Allocate a new event state object.
568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
 */
virObjectEventStatePtr
virObjectEventStateNew(void)
{
    virObjectEventStatePtr state = NULL;

    if (VIR_ALLOC(state) < 0)
        goto error;

    if (virMutexInit(&state->lock) < 0) {
        virReportSystemError(errno, "%s",
                             _("unable to initialize state mutex"));
        VIR_FREE(state);
        goto error;
    }

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

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

    state->timer = -1;

    return state;

594
 error:
595 596 597 598
    virObjectEventStateFree(state);
    return NULL;
}

599 600 601 602 603 604 605 606 607 608 609 610

/**
 * 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
 *
 * Create a new event, with the information common to all events.
 */
611 612
void *
virObjectEventNew(virClassPtr klass,
613
                  virObjectEventDispatchFunc dispatcher,
614 615 616 617
                  int eventID,
                  int id,
                  const char *name,
                  const unsigned char *uuid)
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
{
    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;

634
    event->dispatch = dispatcher;
635
    event->eventID = eventID;
636
    event->remoteID = -1;
637 638 639 640 641 642 643 644 645 646 647 648

    if (VIR_STRDUP(event->meta.name, name) < 0) {
        VIR_FREE(event);
        return NULL;
    }
    event->meta.id = id;
    memcpy(event->meta.uuid, uuid, VIR_UUID_BUFLEN);

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

649

650 651 652 653 654 655 656 657 658 659 660 661 662
/**
 * 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)
{
663
    if (!evtQueue)
664 665
        return -1;

666
    if (VIR_APPEND_ELEMENT(evtQueue->events, evtQueue->count, event) < 0)
667 668 669 670 671
        return -1;
    return 0;
}


E
Eric Blake 已提交
672
static bool
673 674
virObjectEventDispatchMatchCallback(virObjectEventPtr event,
                                    virObjectEventCallbackPtr cb)
675 676
{
    if (!cb)
E
Eric Blake 已提交
677
        return false;
678
    if (cb->deleted)
E
Eric Blake 已提交
679
        return false;
680
    if (!virObjectIsClass(event, cb->klass))
E
Eric Blake 已提交
681
        return false;
682
    if (cb->eventID != event->eventID)
E
Eric Blake 已提交
683
        return false;
684 685
    if (cb->remoteID != event->remoteID)
        return false;
686

687 688 689
    if (cb->filter && !(cb->filter)(cb->conn, event, cb->filter_opaque))
        return false;

690
    if (cb->uuid_filter) {
691 692 693 694
        /* Deliberately ignoring 'id' for matching, since that
         * will cause problems when a domain switches between
         * running & shutoff states & ignoring 'name' since
         * Xen sometimes renames guests during migration, thus
695
         * leaving 'uuid' as the only truly reliable ID we can use. */
696

697
        return memcmp(event->meta.uuid, cb->uuid, VIR_UUID_BUFLEN) == 0;
698
    }
E
Eric Blake 已提交
699
    return true;
700 701 702 703
}


static void
704 705 706
virObjectEventStateDispatchCallbacks(virObjectEventStatePtr state,
                                     virObjectEventPtr event,
                                     virObjectEventCallbackListPtr callbacks)
707 708 709 710 711
{
    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 */
712
    size_t cbCount = callbacks->count;
713 714

    for (i = 0; i < cbCount; i++) {
715 716 717
        virObjectEventCallbackPtr cb = callbacks->callbacks[i];

        if (!virObjectEventDispatchMatchCallback(event, cb))
718 719
            continue;

720 721
        /* Drop the lock whle dispatching, for sake of re-entrancy */
        virObjectEventStateUnlock(state);
722
        event->dispatch(cb->conn, event, cb->cb, cb->opaque);
723
        virObjectEventStateLock(state);
724 725 726 727 728
    }
}


static void
729 730 731
virObjectEventStateQueueDispatch(virObjectEventStatePtr state,
                                 virObjectEventQueuePtr queue,
                                 virObjectEventCallbackListPtr callbacks)
732 733 734 735
{
    size_t i;

    for (i = 0; i < queue->count; i++) {
736 737
        virObjectEventStateDispatchCallbacks(state, queue->events[i],
                                             callbacks);
738 739 740 741 742 743
        virObjectUnref(queue->events[i]);
    }
    VIR_FREE(queue->events);
    queue->count = 0;
}

744 745

/**
746
 * virObjectEventStateQueueRemote:
747 748
 * @state: the event state object
 * @event: event to add to the queue
749
 * @remoteID: limit dispatch to callbacks with the same remote id
750 751 752
 *
 * Adds @event to the queue of events to be dispatched at the next
 * safe moment.  The caller should no longer use @event after this
753 754 755
 * call.  If @remoteID is non-negative, the event will only be sent to
 * callbacks where virObjectEventStateSetRemote() registered a remote
 * id.
756
 */
757
void
758 759 760
virObjectEventStateQueueRemote(virObjectEventStatePtr state,
                               virObjectEventPtr event,
                               int remoteID)
761 762 763 764 765 766 767 768
{
    if (state->timer < 0) {
        virObjectUnref(event);
        return;
    }

    virObjectEventStateLock(state);

769
    event->remoteID = remoteID;
770 771 772 773 774 775 776 777 778 779 780
    if (virObjectEventQueuePush(state->queue, event) < 0) {
        VIR_DEBUG("Error adding event to queue");
        virObjectUnref(event);
    }

    if (state->queue->count == 1)
        virEventUpdateTimeout(state->timer, 0);
    virObjectEventStateUnlock(state);
}


781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
/**
 * 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);
}


798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
static void
virObjectEventStateFlush(virObjectEventStatePtr state)
{
    virObjectEventQueue tempQueue;

    virObjectEventStateLock(state);
    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;
    virEventUpdateTimeout(state->timer, -1);

814 815 816
    virObjectEventStateQueueDispatch(state,
                                     &tempQueue,
                                     state->callbacks);
817 818 819 820 821 822 823 824 825 826 827 828 829

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

    state->isDispatching = false;
    virObjectEventStateUnlock(state);
}


/**
 * virObjectEventStateRegisterID:
 * @conn: connection to associate with callback
 * @state: domain event state
830
 * @uuid: uuid of the object for event filtering
831
 * @klass: the base event class
832
 * @eventID: ID of the event type to register for
833 834
 * @cb: function to invoke when event occurs
 * @opaque: data blob to pass to @callback
835
 * @freecb: callback to free @opaque
836
 * @legacy: true if callback is tracked by function instead of callbackID
837
 * @callbackID: filled with callback ID
838
 * @serverFilter: true if server supports object filtering
839
 *
840 841 842
 * Register the function @cb with connection @conn, from @state, for
 * events of type @eventID, and return the registration handle in
 * @callbackID.
843
 *
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
 * 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.
859 860 861 862 863
 */
int
virObjectEventStateRegisterID(virConnectPtr conn,
                              virObjectEventStatePtr state,
                              unsigned char *uuid,
864 865
                              virObjectEventCallbackFilter filter,
                              void *filter_opaque,
866
                              virClassPtr klass,
867 868 869 870
                              int eventID,
                              virConnectObjectEventGenericCallback cb,
                              void *opaque,
                              virFreeCallback freecb,
871
                              bool legacy,
872 873
                              int *callbackID,
                              bool serverFilter)
874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
{
    int ret = -1;

    virObjectEventStateLock(state);

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

    ret = virObjectEventCallbackListAddID(conn, state->callbacks,
891 892
                                          uuid, filter, filter_opaque,
                                          klass, eventID,
893
                                          cb, opaque, freecb,
894
                                          legacy, callbackID, serverFilter);
895 896 897 898 899 900 901 902

    if (ret == -1 &&
        state->callbacks->count == 0 &&
        state->timer != -1) {
        virEventRemoveTimeout(state->timer);
        state->timer = -1;
    }

903
 cleanup:
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
    virObjectEventStateUnlock(state);
    return ret;
}


/**
 * virObjectEventStateDeregisterID:
 * @conn: connection to associate with callback
 * @state: object event state
 * @callbackID: ID of the function to remove from event
 *
 * Unregister the function @callbackID with connection @conn,
 * from @state, for events.
 *
 * Returns: the number of callbacks still registered, or -1 on error
 */
int
virObjectEventStateDeregisterID(virConnectPtr conn,
                                virObjectEventStatePtr state,
                                int callbackID)
{
    int ret;

    virObjectEventStateLock(state);
    if (state->isDispatching)
        ret = virObjectEventCallbackListMarkDeleteID(conn,
930 931
                                                     state->callbacks,
                                                     callbackID);
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
    else
        ret = virObjectEventCallbackListRemoveID(conn,
                                                 state->callbacks, callbackID);

    if (state->callbacks->count == 0 &&
        state->timer != -1) {
        virEventRemoveTimeout(state->timer);
        state->timer = -1;
        virObjectEventQueueClear(state->queue);
    }

    virObjectEventStateUnlock(state);
    return ret;
}

947 948 949 950 951 952 953
/**
 * 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
954
 * @remoteID: optional output, containing resulting remote id
955 956
 *
 * Returns the callbackID of @callback, or -1 with an error issued if the
957 958 959
 * function is not currently registered.  This only finds functions
 * registered via virConnectDomainEventRegister, even if modern style
 * virConnectDomainEventRegisterAny also registers the same callback.
960 961 962 963 964 965
 */
int
virObjectEventStateCallbackID(virConnectPtr conn,
                              virObjectEventStatePtr state,
                              virClassPtr klass,
                              int eventID,
966 967
                              virConnectObjectEventGenericCallback callback,
                              int *remoteID)
968 969 970 971 972
{
    int ret = -1;

    virObjectEventStateLock(state);
    ret = virObjectEventCallbackLookup(conn, state->callbacks, NULL,
973 974
                                       klass, eventID, callback, true,
                                       remoteID);
975 976 977
    virObjectEventStateUnlock(state);

    if (ret < 0)
978
        virReportError(VIR_ERR_INVALID_ARG,
979 980 981 982 983
                       _("event callback function %p not registered"),
                       callback);
    return ret;
}

984 985 986 987 988 989

/**
 * virObjectEventStateEventID:
 * @conn: connection associated with the callback
 * @state: object event state
 * @callbackID: the callback to query
990
 * @remoteID: optionally output remote ID of the callback
991
 *
992 993 994 995
 * 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().
996 997 998 999 1000 1001
 *
 * Returns 0 on success, -1 on error
 */
int
virObjectEventStateEventID(virConnectPtr conn,
                           virObjectEventStatePtr state,
1002 1003
                           int callbackID,
                           int *remoteID)
1004
{
1005 1006 1007
    int ret = -1;
    size_t i;
    virObjectEventCallbackListPtr cbList = state->callbacks;
1008 1009

    virObjectEventStateLock(state);
1010 1011 1012 1013 1014 1015 1016
    for (i = 0; i < cbList->count; i++) {
        virObjectEventCallbackPtr cb = cbList->callbacks[i];

        if (cb->deleted)
            continue;

        if (cb->callbackID == callbackID && cb->conn == conn) {
1017 1018
            if (remoteID)
                *remoteID = cb->remoteID;
1019 1020 1021 1022
            ret = cb->eventID;
            break;
        }
    }
1023
    virObjectEventStateUnlock(state);
1024 1025 1026 1027 1028

    if (ret < 0)
        virReportError(VIR_ERR_INVALID_ARG,
                       _("event callback id %d not registered"),
                       callbackID);
1029 1030
    return ret;
}
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066


/**
 * 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;

    virObjectEventStateLock(state);
    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;
        }
    }
    virObjectEventStateUnlock(state);
}