virdomainobjlist.c 31.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * virdomainobjlist.c: domain objects list utilities
 *
 * Copyright (C) 2006-2015 Red Hat, Inc.
 * Copyright (C) 2006-2008 Daniel P. Berrange
 * Copyright (c) 2015 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/>.
 */

#include <config.h>

#include "internal.h"
#include "datatypes.h"
#include "virdomainobjlist.h"
28
#include "checkpoint_conf.h"
29 30 31 32 33
#include "snapshot_conf.h"
#include "viralloc.h"
#include "virfile.h"
#include "virlog.h"
#include "virstring.h"
34
#include "virdomainsnapshotobjlist.h"
35
#include "virdomaincheckpointobjlist.h"
36 37 38 39 40 41 42 43 44 45

#define VIR_FROM_THIS VIR_FROM_DOMAIN

VIR_LOG_INIT("conf.virdomainobjlist");

static virClassPtr virDomainObjListClass;
static void virDomainObjListDispose(void *obj);


struct _virDomainObjList {
46
    virObjectRWLockable parent;
47 48 49 50 51 52 53 54 55 56 57 58 59

    /* uuid string -> virDomainObj  mapping
     * for O(1), lockless lookup-by-uuid */
    virHashTable *objs;

    /* name -> virDomainObj mapping for O(1),
     * lockless lookup-by-name */
    virHashTable *objsName;
};


static int virDomainObjListOnceInit(void)
{
60
    if (!VIR_CLASS_NEW(virDomainObjList, virClassForObjectRWLockable()))
61 62 63 64 65
        return -1;

    return 0;
}

66
VIR_ONCE_GLOBAL_INIT(virDomainObjList);
67 68 69 70 71 72 73 74

virDomainObjListPtr virDomainObjListNew(void)
{
    virDomainObjListPtr doms;

    if (virDomainObjListInitialize() < 0)
        return NULL;

75
    if (!(doms = virObjectRWLockableNew(virDomainObjListClass)))
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        return NULL;

    if (!(doms->objs = virHashCreate(50, virObjectFreeHashData)) ||
        !(doms->objsName = virHashCreate(50, virObjectFreeHashData))) {
        virObjectUnref(doms);
        return NULL;
    }

    return doms;
}


static void virDomainObjListDispose(void *obj)
{
    virDomainObjListPtr doms = obj;

    virHashFree(doms->objs);
    virHashFree(doms->objsName);
}


static int virDomainObjListSearchID(const void *payload,
                                    const void *name ATTRIBUTE_UNUSED,
                                    const void *data)
{
    virDomainObjPtr obj = (virDomainObjPtr)payload;
    const int *id = data;
    int want = 0;

    virObjectLock(obj);
    if (virDomainObjIsActive(obj) &&
        obj->def->id == *id)
        want = 1;
    virObjectUnlock(obj);
    return want;
}

113 114 115 116

virDomainObjPtr
virDomainObjListFindByID(virDomainObjListPtr doms,
                         int id)
117 118
{
    virDomainObjPtr obj;
119

120
    virObjectRWLockRead(doms);
121
    obj = virHashSearch(doms->objs, virDomainObjListSearchID, &id, NULL);
122 123
    virObjectRef(obj);
    virObjectRWUnlock(doms);
124 125 126 127
    if (obj) {
        virObjectLock(obj);
        if (obj->removing) {
            virObjectUnlock(obj);
128
            virObjectUnref(obj);
129 130 131
            obj = NULL;
        }
    }
W
Wang Yufei 已提交
132

133
    return obj;
W
Wang Yufei 已提交
134
}
135

136

137 138 139
static virDomainObjPtr
virDomainObjListFindByUUIDLocked(virDomainObjListPtr doms,
                                 const unsigned char *uuid)
140 141 142 143 144 145 146
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainObjPtr obj;

    virUUIDFormat(uuid, uuidstr);
    obj = virHashLookup(doms->objs, uuidstr);
    if (obj) {
147
        virObjectRef(obj);
148 149 150 151 152 153
        virObjectLock(obj);
    }
    return obj;
}


154 155 156 157 158 159 160 161 162 163 164
/**
 * @doms: Domain object list
 * @uuid: UUID to search the doms->objs table
 *
 * Lookup the @uuid in the doms->objs hash table and return a
 * locked and ref counted domain object if found. Caller is
 * expected to use the virDomainObjEndAPI when done with the object.
 */
virDomainObjPtr
virDomainObjListFindByUUID(virDomainObjListPtr doms,
                           const unsigned char *uuid)
165 166 167
{
    virDomainObjPtr obj;

168
    virObjectRWLockRead(doms);
169 170 171
    obj = virDomainObjListFindByUUIDLocked(doms, uuid);
    virObjectRWUnlock(doms);

172 173 174 175 176 177
    if (obj && obj->removing) {
        virObjectUnlock(obj);
        virObjectUnref(obj);
        obj = NULL;
    }

178 179 180 181 182 183 184 185 186 187
    return obj;
}


static virDomainObjPtr
virDomainObjListFindByNameLocked(virDomainObjListPtr doms,
                                 const char *name)
{
    virDomainObjPtr obj;

188 189
    obj = virHashLookup(doms->objsName, name);
    if (obj) {
190
        virObjectRef(obj);
191 192 193 194 195 196
        virObjectLock(obj);
    }
    return obj;
}


197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/**
 * @doms: Domain object list
 * @name: Name to search the doms->objsName table
 *
 * Lookup the @name in the doms->objsName hash table and return a
 * locked and ref counted domain object if found. Caller is expected
 * to use the virDomainObjEndAPI when done with the object.
 */
virDomainObjPtr
virDomainObjListFindByName(virDomainObjListPtr doms,
                           const char *name)
{
    virDomainObjPtr obj;

    virObjectRWLockRead(doms);
    obj = virDomainObjListFindByNameLocked(doms, name);
    virObjectRWUnlock(doms);

215 216 217 218 219 220
    if (obj && obj->removing) {
        virObjectUnlock(obj);
        virObjectUnref(obj);
        obj = NULL;
    }

221 222 223 224
    return obj;
}


225 226 227 228 229 230 231
/**
 * @doms: Domain object list pointer
 * @vm: Domain object to be added
 *
 * Upon entry @vm should have at least 1 ref and be locked.
 *
 * Add the @vm into the @doms->objs and @doms->objsName hash
232 233 234 235 236
 * tables. Once successfully added into a table, increase the
 * reference count since upon removal in virHashRemoveEntry
 * the virObjectUnref will be called since the hash tables were
 * configured to call virObjectFreeHashData when the object is
 * removed from the hash table.
237
 *
238
 * Returns 0 on success with 3 references and locked
239 240 241 242 243 244 245 246 247 248 249
 *        -1 on failure with 1 reference and locked
 */
static int
virDomainObjListAddObjLocked(virDomainObjListPtr doms,
                             virDomainObjPtr vm)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(vm->def->uuid, uuidstr);
    if (virHashAddEntry(doms->objs, uuidstr, vm) < 0)
        return -1;
250
    virObjectRef(vm);
251 252 253 254 255 256 257 258 259 260 261

    if (virHashAddEntry(doms->objsName, vm->def->name, vm) < 0) {
        virHashRemoveEntry(doms->objs, uuidstr);
        return -1;
    }
    virObjectRef(vm);

    return 0;
}


262 263 264 265 266 267 268 269 270 271 272
/*
 * virDomainObjListAddLocked:
 *
 * If flags & VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE then
 * this will refuse updating an existing def if the
 * current def is Live
 *
 * If flags & VIR_DOMAIN_OBJ_LIST_ADD_LIVE then
 * the @def being added is assumed to represent a
 * live config, not a future inactive config
 *
273 274 275
 * The returned @vm from this function will be locked and ref
 * counted. The caller is expected to use virDomainObjEndAPI
 * when it completes usage.
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
 */
static virDomainObjPtr
virDomainObjListAddLocked(virDomainObjListPtr doms,
                          virDomainDefPtr def,
                          virDomainXMLOptionPtr xmlopt,
                          unsigned int flags,
                          virDomainDefPtr *oldDef)
{
    virDomainObjPtr vm;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    if (oldDef)
        *oldDef = NULL;

    /* See if a VM with matching UUID already exists */
291
    if ((vm = virDomainObjListFindByUUIDLocked(doms, def->uuid))) {
292 293 294 295 296 297 298
        if (vm->removing) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("domain '%s' is already being removed"),
                           vm->def->name);
            goto error;
        } else if (STRNEQ(vm->def->name, def->name)) {
            /* UUID matches, but if names don't match, refuse it */
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
            virUUIDFormat(vm->def->uuid, uuidstr);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("domain '%s' is already defined with uuid %s"),
                           vm->def->name, uuidstr);
            goto error;
        }

        if (flags & VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE) {
            /* UUID & name match, but if VM is already active, refuse it */
            if (virDomainObjIsActive(vm)) {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("domain '%s' is already active"),
                               vm->def->name);
                goto error;
            }
            if (!vm->persistent) {
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("domain '%s' is already being started"),
                               vm->def->name);
                goto error;
            }
        }

        virDomainObjAssignDef(vm,
                              def,
                              !!(flags & VIR_DOMAIN_OBJ_LIST_ADD_LIVE),
                              oldDef);
    } else {
        /* UUID does not match, but if a name matches, refuse it */
328
        if ((vm = virDomainObjListFindByNameLocked(doms, def->name))) {
329 330 331 332 333 334 335 336
            virUUIDFormat(vm->def->uuid, uuidstr);
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("domain '%s' already exists with uuid %s"),
                           def->name, uuidstr);
            goto error;
        }

        if (!(vm = virDomainObjNew(xmlopt)))
337
            goto error;
338 339
        vm->def = def;

340 341
        if (virDomainObjListAddObjLocked(doms, vm) < 0) {
            vm->def = NULL;
342
            goto error;
343
        }
344
    }
345

346 347 348
    return vm;

 error:
349 350
    virDomainObjEndAPI(&vm);
    return NULL;
351 352 353 354 355 356 357 358 359 360 361
}


virDomainObjPtr virDomainObjListAdd(virDomainObjListPtr doms,
                                    virDomainDefPtr def,
                                    virDomainXMLOptionPtr xmlopt,
                                    unsigned int flags,
                                    virDomainDefPtr *oldDef)
{
    virDomainObjPtr ret;

362
    virObjectRWLockWrite(doms);
363
    ret = virDomainObjListAddLocked(doms, def, xmlopt, flags, oldDef);
364
    virObjectRWUnlock(doms);
365 366 367 368
    return ret;
}


369 370 371 372 373
/* The caller must hold lock on 'doms' in addition to 'virDomainObjListRemove'
 * requirements
 *
 * Can be used to remove current element while iterating with
 * virDomainObjListForEach
374
 */
375 376 377
void
virDomainObjListRemoveLocked(virDomainObjListPtr doms,
                             virDomainObjPtr dom)
378 379 380 381 382 383 384
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    virUUIDFormat(dom->def->uuid, uuidstr);

    virHashRemoveEntry(doms->objs, uuidstr);
    virHashRemoveEntry(doms->objsName, dom->def->name);
385 386 387 388 389 390 391 392 393 394 395 396 397 398
}


/**
 * @doms: Pointer to the domain object list
 * @dom: Domain pointer from either after Add or FindBy* API where the
 *       @dom was successfully added to both the doms->objs and ->objsName
 *       hash tables that now would need to be removed.
 *
 * The caller must hold a lock on the driver owning 'doms',
 * and must also have locked and ref counted 'dom', to ensure
 * no one else is either waiting for 'dom' or still using it.
 *
 * When this function returns, @dom will be removed from the hash
399
 * tables and returned with lock and refcnt that was present upon entry.
400 401 402 403 404 405 406 407 408 409 410
 */
void
virDomainObjListRemove(virDomainObjListPtr doms,
                       virDomainObjPtr dom)
{
    dom->removing = true;
    virObjectRef(dom);
    virObjectUnlock(dom);
    virObjectRWLockWrite(doms);
    virObjectLock(dom);
    virDomainObjListRemoveLocked(doms, dom);
411
    virObjectUnref(dom);
412
    virObjectRWUnlock(doms);
413 414 415
}


416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
/**
 * virDomainObjListRename:
 *
 * The caller must hold a lock on dom. Callbacks should not
 * sleep/wait otherwise operations on all domains will be blocked
 * as the callback is called with domains lock hold. Domain lock
 * is dropped/reacquired during this operation thus domain
 * consistency must not rely on this lock solely.
 */
int
virDomainObjListRename(virDomainObjListPtr doms,
                       virDomainObjPtr dom,
                       const char *new_name,
                       unsigned int flags,
                       virDomainObjListRenameCallback callback,
                       void *opaque)
{
    int ret = -1;
    char *old_name = NULL;
    int rc;

    if (STREQ(dom->def->name, new_name)) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("Can't rename domain to itself"));
        return ret;
    }

    if (VIR_STRDUP(old_name, dom->def->name) < 0)
        return ret;

    /* doms and dom locks must be attained in right order thus relock dom. */
    /* dom reference is touched for the benefit of those callers that
     * hold a lock on dom but not refcount it. */
    virObjectRef(dom);
    virObjectUnlock(dom);
451
    virObjectRWLockWrite(doms);
452 453 454 455 456 457 458 459 460 461 462 463 464
    virObjectLock(dom);
    virObjectUnref(dom);

    if (virHashLookup(doms->objsName, new_name) != NULL) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("domain with name '%s' already exists"),
                       new_name);
        goto cleanup;
    }

    if (virHashAddEntry(doms->objsName, new_name, dom) < 0)
        goto cleanup;

465 466 467 468 469
    /* Increment the refcnt for @new_name. We're about to remove
     * the @old_name which will cause the refcnt to be decremented
     * via the virObjectUnref call made during the virObjectFreeHashData
     * as a result of removing something from the object list hash
     * table as set up during virDomainObjListNew. */
470 471 472 473 474 475 476 477 478
    virObjectRef(dom);

    rc = callback(dom, new_name, flags, opaque);
    virHashRemoveEntry(doms->objsName, rc < 0 ? new_name : old_name);
    if (rc < 0)
        goto cleanup;

    ret = 0;
 cleanup:
479
    virObjectRWUnlock(doms);
480 481 482 483
    VIR_FREE(old_name);
    return ret;
}

484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502

static virDomainObjPtr
virDomainObjListLoadConfig(virDomainObjListPtr doms,
                           virCapsPtr caps,
                           virDomainXMLOptionPtr xmlopt,
                           const char *configDir,
                           const char *autostartDir,
                           const char *name,
                           virDomainLoadConfigNotify notify,
                           void *opaque)
{
    char *configFile = NULL, *autostartLink = NULL;
    virDomainDefPtr def = NULL;
    virDomainObjPtr dom;
    int autostart;
    virDomainDefPtr oldDef = NULL;

    if ((configFile = virDomainConfigFile(configDir, name)) == NULL)
        goto error;
503
    if (!(def = virDomainDefParseFile(configFile, caps, xmlopt, NULL,
504
                                      VIR_DOMAIN_DEF_PARSE_INACTIVE |
505 506
                                      VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE |
                                      VIR_DOMAIN_DEF_PARSE_ALLOW_POST_PARSE_FAIL)))
507 508 509 510 511 512 513 514 515 516 517 518 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 545 546 547 548 549 550 551 552 553 554 555
        goto error;

    if ((autostartLink = virDomainConfigFile(autostartDir, name)) == NULL)
        goto error;

    if ((autostart = virFileLinkPointsTo(autostartLink, configFile)) < 0)
        goto error;

    if (!(dom = virDomainObjListAddLocked(doms, def, xmlopt, 0, &oldDef)))
        goto error;

    dom->autostart = autostart;

    if (notify)
        (*notify)(dom, oldDef == NULL, opaque);

    virDomainDefFree(oldDef);
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    return dom;

 error:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
    virDomainDefFree(def);
    return NULL;
}


static virDomainObjPtr
virDomainObjListLoadStatus(virDomainObjListPtr doms,
                           const char *statusDir,
                           const char *name,
                           virCapsPtr caps,
                           virDomainXMLOptionPtr xmlopt,
                           virDomainLoadConfigNotify notify,
                           void *opaque)
{
    char *statusFile = NULL;
    virDomainObjPtr obj = NULL;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    if ((statusFile = virDomainConfigFile(statusDir, name)) == NULL)
        goto error;

    if (!(obj = virDomainObjParseFile(statusFile, caps, xmlopt,
                                      VIR_DOMAIN_DEF_PARSE_STATUS |
                                      VIR_DOMAIN_DEF_PARSE_ACTUAL_NET |
                                      VIR_DOMAIN_DEF_PARSE_PCI_ORIG_STATES |
556 557
                                      VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE |
                                      VIR_DOMAIN_DEF_PARSE_ALLOW_POST_PARSE_FAIL)))
558 559 560 561 562 563 564 565 566 567 568
        goto error;

    virUUIDFormat(obj->def->uuid, uuidstr);

    if (virHashLookup(doms->objs, uuidstr) != NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected domain %s already exists"),
                       obj->def->name);
        goto error;
    }

569
    if (virDomainObjListAddObjLocked(doms, obj) < 0)
570 571 572 573 574 575 576 577 578
        goto error;

    if (notify)
        (*notify)(obj, 1, opaque);

    VIR_FREE(statusFile);
    return obj;

 error:
579
    virDomainObjEndAPI(&obj);
580 581 582 583 584 585 586 587 588
    VIR_FREE(statusFile);
    return NULL;
}


int
virDomainObjListLoadAllConfigs(virDomainObjListPtr doms,
                               const char *configDir,
                               const char *autostartDir,
589
                               bool liveStatus,
590 591 592 593 594 595 596 597
                               virCapsPtr caps,
                               virDomainXMLOptionPtr xmlopt,
                               virDomainLoadConfigNotify notify,
                               void *opaque)
{
    DIR *dir;
    struct dirent *entry;
    int ret = -1;
J
Ján Tomko 已提交
598
    int rc;
599 600 601

    VIR_INFO("Scanning for configs in %s", configDir);

J
Ján Tomko 已提交
602 603
    if ((rc = virDirOpenIfExists(&dir, configDir)) <= 0)
        return rc;
604

605
    virObjectRWLockWrite(doms);
606 607 608 609

    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
        virDomainObjPtr dom;

610
        if (!virStringStripSuffix(entry->d_name, ".xml"))
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
            continue;

        /* NB: ignoring errors, so one malformed config doesn't
           kill the whole process */
        VIR_INFO("Loading config file '%s.xml'", entry->d_name);
        if (liveStatus)
            dom = virDomainObjListLoadStatus(doms,
                                             configDir,
                                             entry->d_name,
                                             caps,
                                             xmlopt,
                                             notify,
                                             opaque);
        else
            dom = virDomainObjListLoadConfig(doms,
                                             caps,
                                             xmlopt,
                                             configDir,
                                             autostartDir,
                                             entry->d_name,
                                             notify,
                                             opaque);
        if (dom) {
            if (!liveStatus)
                dom->persistent = 1;
636
            virDomainObjEndAPI(&dom);
637 638
        } else {
            VIR_ERROR(_("Failed to load config for domain '%s'"), entry->d_name);
639 640 641
        }
    }

J
Ján Tomko 已提交
642
    VIR_DIR_CLOSE(dir);
643
    virObjectRWUnlock(doms);
644 645 646 647 648 649 650 651 652 653 654 655
    return ret;
}


struct virDomainObjListData {
    virDomainObjListACLFilter filter;
    virConnectPtr conn;
    bool active;
    int count;
};


656
static int
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
virDomainObjListCount(void *payload,
                      const void *name ATTRIBUTE_UNUSED,
                      void *opaque)
{
    virDomainObjPtr obj = payload;
    struct virDomainObjListData *data = opaque;
    virObjectLock(obj);
    if (data->filter &&
        !data->filter(data->conn, obj->def))
        goto cleanup;
    if (virDomainObjIsActive(obj)) {
        if (data->active)
            data->count++;
    } else {
        if (!data->active)
            data->count++;
    }
 cleanup:
    virObjectUnlock(obj);
676
    return 0;
677 678 679 680 681 682 683 684 685 686
}


int
virDomainObjListNumOfDomains(virDomainObjListPtr doms,
                             bool active,
                             virDomainObjListACLFilter filter,
                             virConnectPtr conn)
{
    struct virDomainObjListData data = { filter, conn, active, 0 };
687
    virObjectRWLockRead(doms);
688
    virHashForEach(doms->objs, virDomainObjListCount, &data);
689
    virObjectRWUnlock(doms);
690 691 692 693 694 695 696 697 698 699 700 701 702
    return data.count;
}


struct virDomainIDData {
    virDomainObjListACLFilter filter;
    virConnectPtr conn;
    int numids;
    int maxids;
    int *ids;
};


703
static int
704 705 706 707 708 709 710 711 712 713 714 715 716 717
virDomainObjListCopyActiveIDs(void *payload,
                              const void *name ATTRIBUTE_UNUSED,
                              void *opaque)
{
    virDomainObjPtr obj = payload;
    struct virDomainIDData *data = opaque;
    virObjectLock(obj);
    if (data->filter &&
        !data->filter(data->conn, obj->def))
        goto cleanup;
    if (virDomainObjIsActive(obj) && data->numids < data->maxids)
        data->ids[data->numids++] = obj->def->id;
 cleanup:
    virObjectUnlock(obj);
718
    return 0;
719 720 721 722 723 724 725 726 727 728 729 730
}


int
virDomainObjListGetActiveIDs(virDomainObjListPtr doms,
                             int *ids,
                             int maxids,
                             virDomainObjListACLFilter filter,
                             virConnectPtr conn)
{
    struct virDomainIDData data = { filter, conn,
                                    0, maxids, ids };
731
    virObjectRWLockRead(doms);
732
    virHashForEach(doms->objs, virDomainObjListCopyActiveIDs, &data);
733
    virObjectRWUnlock(doms);
734 735 736 737 738 739 740 741 742 743 744 745 746 747
    return data.numids;
}


struct virDomainNameData {
    virDomainObjListACLFilter filter;
    virConnectPtr conn;
    int oom;
    int numnames;
    int maxnames;
    char **const names;
};


748
static int
749 750 751 752 753 754 755 756
virDomainObjListCopyInactiveNames(void *payload,
                                  const void *name ATTRIBUTE_UNUSED,
                                  void *opaque)
{
    virDomainObjPtr obj = payload;
    struct virDomainNameData *data = opaque;

    if (data->oom)
757
        return 0;
758 759 760 761 762 763 764 765 766 767 768 769 770

    virObjectLock(obj);
    if (data->filter &&
        !data->filter(data->conn, obj->def))
        goto cleanup;
    if (!virDomainObjIsActive(obj) && data->numnames < data->maxnames) {
        if (VIR_STRDUP(data->names[data->numnames], obj->def->name) < 0)
            data->oom = 1;
        else
            data->numnames++;
    }
 cleanup:
    virObjectUnlock(obj);
771
    return 0;
772 773 774 775 776 777 778 779 780 781 782 783 784
}


int
virDomainObjListGetInactiveNames(virDomainObjListPtr doms,
                                 char **const names,
                                 int maxnames,
                                 virDomainObjListACLFilter filter,
                                 virConnectPtr conn)
{
    struct virDomainNameData data = { filter, conn,
                                      0, 0, maxnames, names };
    size_t i;
785
    virObjectRWLockRead(doms);
786
    virHashForEach(doms->objs, virDomainObjListCopyInactiveNames, &data);
787
    virObjectRWUnlock(doms);
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
    if (data.oom) {
        for (i = 0; i < data.numnames; i++)
            VIR_FREE(data.names[i]);
        return -1;
    }

    return data.numnames;
}


struct virDomainListIterData {
    virDomainObjListIterator callback;
    void *opaque;
    int ret;
};


805
static int
806 807 808 809 810 811 812 813
virDomainObjListHelper(void *payload,
                       const void *name ATTRIBUTE_UNUSED,
                       void *opaque)
{
    struct virDomainListIterData *data = opaque;

    if (data->callback(payload, data->opaque) < 0)
        data->ret = -1;
814
    return 0;
815 816 817
}


818 819 820
/**
 * virDomainObjListForEach:
 * @doms: Pointer to the domain object list
821
 * @modify: Whether to lock @doms for modify operation
822 823 824 825 826
 * @callback: callback to run over each domain on the list
 * @opaque: opaque data to pass to @callback
 *
 * For every domain on the list (@doms) run @callback on it. If
 * @callback fails (i.e. returns a negative value), the iteration
827 828 829
 * carries still on until all domains are visited. Moreover, if
 * @callback wants to modify the list of domains (@doms) then
 * @modify must be set to true.
830 831 832 833
 *
 * Returns: 0 on success,
 *         -1 otherwise.
 */
834 835
int
virDomainObjListForEach(virDomainObjListPtr doms,
836
                        bool modify,
837 838 839 840 841 842
                        virDomainObjListIterator callback,
                        void *opaque)
{
    struct virDomainListIterData data = {
        callback, opaque, 0,
    };
843 844 845 846 847

    if (modify)
        virObjectRWLockWrite(doms);
    else
        virObjectRWLockRead(doms);
848
    virHashForEach(doms->objs, virDomainObjListHelper, &data);
849
    virObjectRWUnlock(doms);
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
    return data.ret;
}


#define MATCH(FLAG) (filter & (FLAG))
static bool
virDomainObjMatchFilter(virDomainObjPtr vm,
                        unsigned int filter)
{
    /* filter by active state */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_ACTIVE) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_ACTIVE) &&
           virDomainObjIsActive(vm)) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_INACTIVE) &&
           !virDomainObjIsActive(vm))))
        return false;

    /* filter by persistence */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_PERSISTENT) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_PERSISTENT) &&
           vm->persistent) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_TRANSIENT) &&
           !vm->persistent)))
        return false;

    /* filter by domain state */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_STATE)) {
        int st = virDomainObjGetState(vm, NULL);
        if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_RUNNING) &&
               st == VIR_DOMAIN_RUNNING) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_PAUSED) &&
               st == VIR_DOMAIN_PAUSED) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_SHUTOFF) &&
               st == VIR_DOMAIN_SHUTOFF) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_OTHER) &&
               (st != VIR_DOMAIN_RUNNING &&
                st != VIR_DOMAIN_PAUSED &&
                st != VIR_DOMAIN_SHUTOFF))))
            return false;
    }

    /* filter by existence of managed save state */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_MANAGEDSAVE) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE) &&
           vm->hasManagedSave) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE) &&
           !vm->hasManagedSave)))
        return false;

    /* filter by autostart option */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_AUTOSTART) &&
        !((MATCH(VIR_CONNECT_LIST_DOMAINS_AUTOSTART) && vm->autostart) ||
          (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART) && !vm->autostart)))
        return false;

    /* filter by snapshot existence */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_SNAPSHOT)) {
        int nsnap = virDomainSnapshotObjListNum(vm->snapshots, NULL, 0);
        if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT) && nsnap > 0) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT) && nsnap <= 0)))
            return false;
    }

913 914 915 916 917 918 919 920 921
    /* filter by checkpoint existence */
    if (MATCH(VIR_CONNECT_LIST_DOMAINS_FILTERS_CHECKPOINT)) {
        int nchk = virDomainListCheckpoints(vm->checkpoints, NULL, NULL,
                                            NULL, 0);
        if (!((MATCH(VIR_CONNECT_LIST_DOMAINS_HAS_CHECKPOINT) && nchk > 0) ||
              (MATCH(VIR_CONNECT_LIST_DOMAINS_NO_CHECKPOINT) && nchk <= 0)))
            return false;
    }

922 923 924 925 926 927 928 929 930 931 932
    return true;
}
#undef MATCH


struct virDomainListData {
    virDomainObjPtr *vms;
    size_t nvms;
};


933
static int
934 935 936 937 938 939 940
virDomainObjListCollectIterator(void *payload,
                                const void *name ATTRIBUTE_UNUSED,
                                void *opaque)
{
    struct virDomainListData *data = opaque;

    data->vms[data->nvms++] = virObjectRef(payload);
941
    return 0;
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
}


static void
virDomainObjListFilter(virDomainObjPtr **list,
                       size_t *nvms,
                       virConnectPtr conn,
                       virDomainObjListACLFilter filter,
                       unsigned int flags)
{
    size_t i = 0;

    while (i < *nvms) {
        virDomainObjPtr vm = (*list)[i];

        virObjectLock(vm);

        /* do not list the object if:
         * 1) it's being removed.
         * 2) connection does not have ACL to see it
         * 3) it doesn't match the filter
         */
        if (vm->removing ||
            (filter && !filter(conn, vm->def)) ||
            !virDomainObjMatchFilter(vm, flags)) {
            virObjectUnlock(vm);
            virObjectUnref(vm);
            VIR_DELETE_ELEMENT(*list, i, *nvms);
            continue;
        }

        virObjectUnlock(vm);
        i++;
    }
}


int
virDomainObjListCollect(virDomainObjListPtr domlist,
                        virConnectPtr conn,
                        virDomainObjPtr **vms,
                        size_t *nvms,
                        virDomainObjListACLFilter filter,
                        unsigned int flags)
{
    struct virDomainListData data = { NULL, 0 };

989
    virObjectRWLockRead(domlist);
990 991
    sa_assert(domlist->objs);
    if (VIR_ALLOC_N(data.vms, virHashSize(domlist->objs)) < 0) {
992
        virObjectRWUnlock(domlist);
993 994 995 996
        return -1;
    }

    virHashForEach(domlist->objs, virDomainObjListCollectIterator, &data);
997
    virObjectRWUnlock(domlist);
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025

    virDomainObjListFilter(&data.vms, &data.nvms, conn, filter, flags);

    *nvms = data.nvms;
    *vms = data.vms;

    return 0;
}


int
virDomainObjListConvert(virDomainObjListPtr domlist,
                        virConnectPtr conn,
                        virDomainPtr *doms,
                        size_t ndoms,
                        virDomainObjPtr **vms,
                        size_t *nvms,
                        virDomainObjListACLFilter filter,
                        unsigned int flags,
                        bool skip_missing)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainObjPtr vm;
    size_t i;

    *nvms = 0;
    *vms = NULL;

1026
    virObjectRWLockRead(domlist);
1027 1028 1029 1030 1031 1032 1033 1034 1035
    for (i = 0; i < ndoms; i++) {
        virDomainPtr dom = doms[i];

        virUUIDFormat(dom->uuid, uuidstr);

        if (!(vm = virHashLookup(domlist->objs, uuidstr))) {
            if (skip_missing)
                continue;

1036
            virObjectRWUnlock(domlist);
1037 1038 1039 1040 1041 1042 1043 1044 1045
            virReportError(VIR_ERR_NO_DOMAIN,
                           _("no domain with matching uuid '%s' (%s)"),
                           uuidstr, dom->name);
            goto error;
        }

        virObjectRef(vm);

        if (VIR_APPEND_ELEMENT(*vms, *nvms, vm) < 0) {
1046
            virObjectRWUnlock(domlist);
1047 1048 1049 1050
            virObjectUnref(vm);
            goto error;
        }
    }
1051
    virObjectRWUnlock(domlist);
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090

    sa_assert(*vms);
    virDomainObjListFilter(vms, nvms, conn, filter, flags);

    return 0;

 error:
    virObjectListFreeCount(*vms, *nvms);
    *vms = NULL;
    *nvms = 0;

    return -1;
}


int
virDomainObjListExport(virDomainObjListPtr domlist,
                       virConnectPtr conn,
                       virDomainPtr **domains,
                       virDomainObjListACLFilter filter,
                       unsigned int flags)
{
    virDomainObjPtr *vms = NULL;
    virDomainPtr *doms = NULL;
    size_t nvms = 0;
    size_t i;
    int ret = -1;

    if (virDomainObjListCollect(domlist, conn, &vms, &nvms, filter, flags) < 0)
        return -1;

    if (domains) {
        if (VIR_ALLOC_N(doms, nvms + 1) < 0)
            goto cleanup;

        for (i = 0; i < nvms; i++) {
            virDomainObjPtr vm = vms[i];

            virObjectLock(vm);
1091 1092
            doms[i] = virGetDomain(conn, vm->def->name, vm->def->uuid, vm->def->id);
            virObjectUnlock(vm);
1093

1094
            if (!doms[i])
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
                goto cleanup;
        }

        *domains = doms;
        doms = NULL;
    }

    ret = nvms;

 cleanup:
    virObjectListFree(doms);
    virObjectListFreeCount(vms, nvms);
    return ret;
}