snapshot_conf.c 44.0 KB
Newer Older
1 2 3
/*
 * snapshot_conf.c: domain snapshot XML processing
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * 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
18
 * License along with this library.  If not, see
19 20 21 22 23 24 25 26 27 28 29 30 31
 * <http://www.gnu.org/licenses/>.
 *
 * Author: Eric Blake <eblake@redhat.com>
 */

#include <config.h>

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>

#include "internal.h"
32
#include "virbitmap.h"
33
#include "virbuffer.h"
34 35 36
#include "count-one-bits.h"
#include "datatypes.h"
#include "domain_conf.h"
37
#include "virlog.h"
38
#include "viralloc.h"
39 40 41 42 43
#include "netdev_bandwidth_conf.h"
#include "netdev_vport_profile_conf.h"
#include "nwfilter_conf.h"
#include "secret_conf.h"
#include "snapshot_conf.h"
44
#include "virstoragefile.h"
45
#include "viruuid.h"
46
#include "virfile.h"
47
#include "virerror.h"
48
#include "virxml.h"
49
#include "virstring.h"
50 51 52

#define VIR_FROM_THIS VIR_FROM_DOMAIN_SNAPSHOT

53 54
VIR_LOG_INIT("conf.snapshot_conf");

E
Eric Blake 已提交
55
VIR_ENUM_IMPL(virDomainSnapshotLocation, VIR_DOMAIN_SNAPSHOT_LOCATION_LAST,
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
              "default",
              "no",
              "internal",
              "external")

/* virDomainSnapshotState is really virDomainState plus one extra state */
VIR_ENUM_IMPL(virDomainSnapshotState, VIR_DOMAIN_SNAPSHOT_STATE_LAST,
              "nostate",
              "running",
              "blocked",
              "paused",
              "shutdown",
              "shutoff",
              "crashed",
              "pmsuspended",
              "disk-snapshot")

struct _virDomainSnapshotObjList {
    /* name string -> virDomainSnapshotObj  mapping
     * for O(1), lockless lookup-by-name */
    virHashTable *objs;

    virDomainSnapshotObj metaroot; /* Special parent of all root snapshots */
};

/* Snapshot Def functions */
static void
virDomainSnapshotDiskDefClear(virDomainSnapshotDiskDefPtr disk)
{
    VIR_FREE(disk->name);
86 87
    virStorageSourceFree(disk->src);
    disk->src = NULL;
88 89 90 91
}

void virDomainSnapshotDefFree(virDomainSnapshotDefPtr def)
{
92
    size_t i;
93 94 95 96 97 98 99

    if (!def)
        return;

    VIR_FREE(def->name);
    VIR_FREE(def->description);
    VIR_FREE(def->parent);
100
    VIR_FREE(def->file);
101 102 103 104
    for (i = 0; i < def->ndisks; i++)
        virDomainSnapshotDiskDefClear(&def->disks[i]);
    VIR_FREE(def->disks);
    virDomainDefFree(def->dom);
105
    virObjectUnref(def->cookie);
106 107 108 109 110
    VIR_FREE(def);
}

static int
virDomainSnapshotDiskDefParseXML(xmlNodePtr node,
111
                                 xmlXPathContextPtr ctxt,
112
                                 virDomainSnapshotDiskDefPtr def,
113 114
                                 unsigned int flags,
                                 virDomainXMLOptionPtr xmlopt)
115 116 117
{
    int ret = -1;
    char *snapshot = NULL;
118
    char *type = NULL;
119
    char *driver = NULL;
120
    xmlNodePtr cur;
121 122 123
    xmlNodePtr saved = ctxt->node;

    ctxt->node = node;
124

125 126 127
    if (VIR_ALLOC(def->src) < 0)
        goto cleanup;

128 129 130 131 132 133 134 135 136
    def->name = virXMLPropString(node, "name");
    if (!def->name) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing name from disk snapshot element"));
        goto cleanup;
    }

    snapshot = virXMLPropString(node, "snapshot");
    if (snapshot) {
E
Eric Blake 已提交
137
        def->snapshot = virDomainSnapshotLocationTypeFromString(snapshot);
138
        if (def->snapshot <= 0) {
139
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
140 141 142 143 144 145
                           _("unknown disk snapshot setting '%s'"),
                           snapshot);
            goto cleanup;
        }
    }

146
    if ((type = virXMLPropString(node, "type"))) {
147 148 149
        if ((def->src->type = virStorageTypeFromString(type)) <= 0 ||
            def->src->type == VIR_STORAGE_TYPE_VOLUME ||
            def->src->type == VIR_STORAGE_TYPE_DIR) {
150 151 152 153 154
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown disk snapshot type '%s'"), type);
            goto cleanup;
        }
    } else {
155
        def->src->type = VIR_STORAGE_TYPE_FILE;
156
    }
157

158
    if ((cur = virXPathNode("./source", ctxt)) &&
159
        virDomainDiskSourceParse(cur, ctxt, def->src, flags, xmlopt) < 0)
160 161 162 163 164 165 166 167 168 169 170 171
        goto cleanup;

    if ((driver = virXPathString("string(./driver/@type)", ctxt))) {
        def->src->format = virStorageFileFormatTypeFromString(driver);
        if (def->src->format < VIR_STORAGE_FILE_BACKING) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           def->src->format <= 0
                           ? _("unknown disk snapshot driver '%s'")
                           : _("disk format '%s' lacks backing file "
                               "support"),
                           driver);
            goto cleanup;
172 173 174
        }
    }

175
    /* validate that the passed path is absolute */
176
    if (virStorageSourceIsRelative(def->src)) {
177 178 179 180 181 182
        virReportError(VIR_ERR_XML_ERROR,
                       _("disk snapshot image path '%s' must be absolute"),
                       def->src->path);
        goto cleanup;
    }

183
    if (!def->snapshot && (def->src->path || def->src->format))
E
Eric Blake 已提交
184
        def->snapshot = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
185 186

    ret = 0;
187
 cleanup:
188 189 190
    ctxt->node = saved;

    VIR_FREE(driver);
191
    VIR_FREE(snapshot);
192
    VIR_FREE(type);
193 194 195 196 197 198 199
    if (ret < 0)
        virDomainSnapshotDiskDefClear(def);
    return ret;
}

/* flags is bitwise-or of virDomainSnapshotParseFlags.
 * If flags does not include VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE, then
200
 * caps are ignored.
201
 */
202 203 204 205 206
static virDomainSnapshotDefPtr
virDomainSnapshotDefParse(xmlXPathContextPtr ctxt,
                          virCapsPtr caps,
                          virDomainXMLOptionPtr xmlopt,
                          unsigned int flags)
207 208 209 210
{
    virDomainSnapshotDefPtr def = NULL;
    virDomainSnapshotDefPtr ret = NULL;
    xmlNodePtr *nodes = NULL;
211 212
    size_t i;
    int n;
213 214 215 216
    char *creation = NULL, *state = NULL;
    struct timeval tv;
    int active;
    char *tmp;
217 218 219
    char *memorySnapshot = NULL;
    char *memoryFile = NULL;
    bool offline = !!(flags & VIR_DOMAIN_SNAPSHOT_PARSE_OFFLINE);
220
    virSaveCookieCallbacksPtr saveCookie = virDomainXMLOptionGetSaveCookie(xmlopt);
221

222
    if (VIR_ALLOC(def) < 0)
223 224 225 226 227 228 229 230 231 232 233
        goto cleanup;

    gettimeofday(&tv, NULL);

    def->name = virXPathString("string(./name)", ctxt);
    if (def->name == NULL) {
        if (flags & VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("a redefined snapshot must have a name"));
            goto cleanup;
        }
234
        if (virAsprintf(&def->name, "%lld", (long long)tv.tv_sec) < 0)
235
            goto cleanup;
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    }

    def->description = virXPathString("string(./description)", ctxt);

    if (flags & VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE) {
        if (virXPathLongLong("string(./creationTime)", ctxt,
                             &def->creationTime) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("missing creationTime from existing snapshot"));
            goto cleanup;
        }

        def->parent = virXPathString("string(./parent/name)", ctxt);

        state = virXPathString("string(./state)", ctxt);
        if (state == NULL) {
            /* there was no state in an existing snapshot; this
             * should never happen
             */
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing state from existing snapshot"));
            goto cleanup;
        }
        def->state = virDomainSnapshotStateTypeFromString(state);
        if (def->state < 0) {
261
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
262 263 264 265
                           _("Invalid state '%s' in domain snapshot XML"),
                           state);
            goto cleanup;
        }
266 267
        offline = (def->state == VIR_DOMAIN_SHUTOFF ||
                   def->state == VIR_DOMAIN_DISK_SNAPSHOT);
268 269 270 271 272 273

        /* Older snapshots were created with just <domain>/<uuid>, and
         * lack domain/@type.  In that case, leave dom NULL, and
         * clients will have to decide between best effort
         * initialization or outright failure.  */
        if ((tmp = virXPathString("string(./domain/@type)", ctxt))) {
274 275
            int domainflags = VIR_DOMAIN_DEF_PARSE_INACTIVE |
                              VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE;
276 277
            if (flags & VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL)
                domainflags |= VIR_DOMAIN_DEF_PARSE_SKIP_OSTYPE_CHECKS;
278 279 280 281 282 283 284 285
            xmlNodePtr domainNode = virXPathNode("./domain", ctxt);

            VIR_FREE(tmp);
            if (!domainNode) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("missing domain in snapshot"));
                goto cleanup;
            }
286
            def->dom = virDomainDefParseNode(ctxt->node->doc, domainNode,
287
                                             caps, xmlopt, NULL, domainflags);
288 289 290 291 292 293 294 295 296
            if (!def->dom)
                goto cleanup;
        } else {
            VIR_WARN("parsing older snapshot that lacks domain");
        }
    } else {
        def->creationTime = tv.tv_sec;
    }

297 298 299 300 301
    memorySnapshot = virXPathString("string(./memory/@snapshot)", ctxt);
    memoryFile = virXPathString("string(./memory/@file)", ctxt);
    if (memorySnapshot) {
        def->memory = virDomainSnapshotLocationTypeFromString(memorySnapshot);
        if (def->memory <= 0) {
302
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
303 304 305 306 307 308 309 310 311 312 313
                           _("unknown memory snapshot setting '%s'"),
                           memorySnapshot);
            goto cleanup;
        }
        if (memoryFile &&
            def->memory != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("memory filename '%s' requires external snapshot"),
                           memoryFile);
            goto cleanup;
        }
314 315 316 317 318 319
        if (!memoryFile &&
            def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("external memory snapshots require a filename"));
            goto cleanup;
        }
320 321 322 323 324 325 326 327 328 329
    } else if (memoryFile) {
        def->memory = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
    } else if (flags & VIR_DOMAIN_SNAPSHOT_PARSE_REDEFINE) {
        def->memory = (offline ?
                       VIR_DOMAIN_SNAPSHOT_LOCATION_NONE :
                       VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL);
    }
    if (offline && def->memory &&
        def->memory != VIR_DOMAIN_SNAPSHOT_LOCATION_NONE) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
330 331
                       _("memory state cannot be saved with offline or "
                         "disk-only snapshot"));
332 333
        goto cleanup;
    }
334
    VIR_STEAL_PTR(def->file, memoryFile);
335

336 337 338 339 340 341 342 343
    /* verify that memory path is absolute */
    if (def->file && def->file[0] != '/') {
        virReportError(VIR_ERR_XML_ERROR,
                       _("memory snapshot file path (%s) must be absolute"),
                       def->file);
        goto cleanup;
    }

344
    if ((n = virXPathNodeSet("./disks/*", ctxt, &nodes)) < 0)
345
        goto cleanup;
346
    if (flags & VIR_DOMAIN_SNAPSHOT_PARSE_DISKS) {
347
        if (n && VIR_ALLOC_N(def->disks, n) < 0)
348
            goto cleanup;
349
        def->ndisks = n;
350
        for (i = 0; i < def->ndisks; i++) {
351 352
            if (virDomainSnapshotDiskDefParseXML(nodes[i], ctxt, &def->disks[i],
                                                 flags, xmlopt) < 0)
353 354 355
                goto cleanup;
        }
        VIR_FREE(nodes);
356
    } else if (n) {
357 358 359 360 361 362 363 364 365 366 367 368 369 370
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("unable to handle disk requests in snapshot"));
        goto cleanup;
    }

    if (flags & VIR_DOMAIN_SNAPSHOT_PARSE_INTERNAL) {
        if (virXPathInt("string(./active)", ctxt, &active) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Could not find 'active' element"));
            goto cleanup;
        }
        def->current = active != 0;
    }

371 372 373
    if (!offline && virSaveCookieParse(ctxt, &def->cookie, saveCookie) < 0)
        goto cleanup;

374
    VIR_STEAL_PTR(ret, def);
375

376
 cleanup:
377 378 379
    VIR_FREE(creation);
    VIR_FREE(state);
    VIR_FREE(nodes);
380 381
    VIR_FREE(memorySnapshot);
    VIR_FREE(memoryFile);
382
    virDomainSnapshotDefFree(def);
383 384 385 386 387 388 389 390 391 392 393 394 395 396

    return ret;
}

virDomainSnapshotDefPtr
virDomainSnapshotDefParseNode(xmlDocPtr xml,
                              xmlNodePtr root,
                              virCapsPtr caps,
                              virDomainXMLOptionPtr xmlopt,
                              unsigned int flags)
{
    xmlXPathContextPtr ctxt = NULL;
    virDomainSnapshotDefPtr def = NULL;

397
    if (!virXMLNodeNameEqual(root, "domainsnapshot")) {
398 399 400 401 402 403 404 405 406 407 408
        virReportError(VIR_ERR_XML_ERROR, "%s", _("domainsnapshot"));
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virReportOOMError();
        goto cleanup;
    }

    ctxt->node = root;
409
    def = virDomainSnapshotDefParse(ctxt, caps, xmlopt, flags);
410
 cleanup:
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
    xmlXPathFreeContext(ctxt);
    return def;
}

virDomainSnapshotDefPtr
virDomainSnapshotDefParseString(const char *xmlStr,
                                virCapsPtr caps,
                                virDomainXMLOptionPtr xmlopt,
                                unsigned int flags)
{
    virDomainSnapshotDefPtr ret = NULL;
    xmlDocPtr xml;
    int keepBlanksDefault = xmlKeepBlanksDefault(0);

    if ((xml = virXMLParse(NULL, xmlStr, _("(domain_snapshot)")))) {
        xmlKeepBlanksDefault(keepBlanksDefault);
        ret = virDomainSnapshotDefParseNode(xml, xmlDocGetRootElement(xml),
428
                                            caps, xmlopt, flags);
429 430 431
        xmlFreeDoc(xml);
    }
    xmlKeepBlanksDefault(keepBlanksDefault);
432 433 434 435

    return ret;
}

436 437 438 439 440 441 442 443 444 445 446

/**
 * virDomainSnapshotDefAssignExternalNames:
 * @def: snapshot def object
 *
 * Generate default external file names for snapshot targets. Returns 0 on
 * success, -1 on error.
 */
static int
virDomainSnapshotDefAssignExternalNames(virDomainSnapshotDefPtr def)
{
447 448 449 450
    const char *origpath;
    char *tmppath;
    char *tmp;
    struct stat sb;
451
    size_t i;
452
    size_t j;
453 454 455 456

    for (i = 0; i < def->ndisks; i++) {
        virDomainSnapshotDiskDefPtr disk = &def->disks[i];

457 458 459
        if (disk->snapshot != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL ||
            disk->src->path)
            continue;
460

461 462 463 464 465 466 467
        if (disk->src->type != VIR_STORAGE_TYPE_FILE) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("cannot generate external snapshot name "
                             "for disk '%s' on a '%s' device"),
                           disk->name, virStorageTypeToString(disk->src->type));
            return -1;
        }
468

469 470 471 472 473 474
        if (!(origpath = virDomainDiskGetSource(def->dom->disks[i]))) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("cannot generate external snapshot name "
                             "for disk '%s' without source"),
                           disk->name);
            return -1;
475 476
        }

477 478 479 480 481 482 483 484
        if (stat(origpath, &sb) < 0 || !S_ISREG(sb.st_mode)) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("source for disk '%s' is not a regular "
                             "file; refusing to generate external "
                             "snapshot name"),
                           disk->name);
            return -1;
        }
485

486 487 488 489 490 491 492 493 494 495 496 497 498
        if (VIR_STRDUP(tmppath, origpath) < 0)
            return -1;

        /* drop suffix of the file name */
        if ((tmp = strrchr(tmppath, '.')) && !strchr(tmp, '/'))
            *tmp = '\0';

        if (virAsprintf(&disk->src->path, "%s.%s", tmppath, def->name) < 0) {
            VIR_FREE(tmppath);
            return -1;
        }

        VIR_FREE(tmppath);
499 500 501 502 503 504 505 506 507 508 509

        /* verify that we didn't generate a duplicate name */
        for (j = 0; j < i; j++) {
            if (STREQ_NULLABLE(disk->src->path, def->disks[j].src->path)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("cannot generate external snapshot name for "
                                 "disk '%s': collision with disk '%s'"),
                               disk->name, def->disks[j].name);
                return -1;
            }
        }
510 511 512
    }

    return 0;
513 514 515
}


516
static int
517
virDomainSnapshotCompareDiskIndex(const void *a, const void *b)
518 519 520 521 522
{
    const virDomainSnapshotDiskDef *diska = a;
    const virDomainSnapshotDiskDef *diskb = b;

    /* Integer overflow shouldn't be a problem here.  */
J
John Ferlan 已提交
523
    return diska->idx - diskb->idx;
524 525 526 527 528 529 530
}

/* Align def->disks to def->domain.  Sort the list of def->disks,
 * filling in any missing disks or snapshot state defaults given by
 * the domain, with a fallback to a passed in default.  Convert paths
 * to disk targets for uniformity.  Issue an error and return -1 if
 * any def->disks[n]->name appears more than once or does not map to
E
Eric Blake 已提交
531 532
 * dom->disks.  If require_match, also ensure that there is no
 * conflicting requests for both internal and external snapshots.  */
533 534 535 536 537 538 539
int
virDomainSnapshotAlignDisks(virDomainSnapshotDefPtr def,
                            int default_snapshot,
                            bool require_match)
{
    int ret = -1;
    virBitmapPtr map = NULL;
540
    size_t i;
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    int ndisks;

    if (!def->dom) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing domain in snapshot"));
        goto cleanup;
    }

    if (def->ndisks > def->dom->ndisks) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("too many disk snapshot requests for domain"));
        goto cleanup;
    }

    /* Unlikely to have a guest without disks but technically possible.  */
    if (!def->dom->ndisks) {
        ret = 0;
        goto cleanup;
    }

561
    if (!(map = virBitmapNew(def->dom->ndisks)))
562 563 564 565 566 567 568 569 570 571 572 573 574 575
        goto cleanup;

    /* Double check requested disks.  */
    for (i = 0; i < def->ndisks; i++) {
        virDomainSnapshotDiskDefPtr disk = &def->disks[i];
        int idx = virDomainDiskIndexByName(def->dom, disk->name, false);
        int disk_snapshot;

        if (idx < 0) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("no disk named '%s'"), disk->name);
            goto cleanup;
        }

J
Ján Tomko 已提交
576
        if (virBitmapIsBitSet(map, idx)) {
577 578 579 580 581 582
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk '%s' specified twice"),
                           disk->name);
            goto cleanup;
        }
        ignore_value(virBitmapSetBit(map, idx));
J
John Ferlan 已提交
583
        disk->idx = idx;
E
Eric Blake 已提交
584 585

        disk_snapshot = def->dom->disks[idx]->snapshot;
586
        if (!disk->snapshot) {
E
Eric Blake 已提交
587 588 589 590 591 592 593 594 595 596
            if (disk_snapshot &&
                (!require_match ||
                 disk_snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE))
                disk->snapshot = disk_snapshot;
            else
                disk->snapshot = default_snapshot;
        } else if (require_match &&
                   disk->snapshot != default_snapshot &&
                   !(disk->snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE &&
                     disk_snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_NONE)) {
E
Eric Blake 已提交
597 598
            const char *tmp;

E
Eric Blake 已提交
599
            tmp = virDomainSnapshotLocationTypeToString(default_snapshot);
600 601 602 603 604
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("disk '%s' must use snapshot mode '%s'"),
                           disk->name, tmp);
            goto cleanup;
        }
605
        if (disk->src->path &&
E
Eric Blake 已提交
606
            disk->snapshot != VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
607 608 609
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                           _("file '%s' for disk '%s' requires "
                             "use of external snapshot mode"),
610
                           disk->src->path, disk->name);
611 612 613 614
            goto cleanup;
        }
        if (STRNEQ(disk->name, def->dom->disks[idx]->dst)) {
            VIR_FREE(disk->name);
615
            if (VIR_STRDUP(disk->name, def->dom->disks[idx]->dst) < 0)
616 617 618 619 620 621 622
                goto cleanup;
        }
    }

    /* Provide defaults for all remaining disks.  */
    ndisks = def->ndisks;
    if (VIR_EXPAND_N(def->disks, def->ndisks,
623
                     def->dom->ndisks - def->ndisks) < 0)
624 625 626 627 628
        goto cleanup;

    for (i = 0; i < def->dom->ndisks; i++) {
        virDomainSnapshotDiskDefPtr disk;

J
Ján Tomko 已提交
629
        if (virBitmapIsBitSet(map, i))
630 631
            continue;
        disk = &def->disks[ndisks++];
632 633
        if (VIR_ALLOC(disk->src) < 0)
            goto cleanup;
634
        if (VIR_STRDUP(disk->name, def->dom->disks[i]->dst) < 0)
635
            goto cleanup;
J
John Ferlan 已提交
636
        disk->idx = i;
637 638 639 640 641 642 643

        /* Don't snapshot empty drives */
        if (virStorageSourceIsEmpty(def->dom->disks[i]->src))
            disk->snapshot = VIR_DOMAIN_SNAPSHOT_LOCATION_NONE;
        else
            disk->snapshot = def->dom->disks[i]->snapshot;

644
        disk->src->type = VIR_STORAGE_TYPE_FILE;
645 646 647 648
        if (!disk->snapshot)
            disk->snapshot = default_snapshot;
    }

649 650
    qsort(&def->disks[0], def->ndisks, sizeof(def->disks[0]),
          virDomainSnapshotCompareDiskIndex);
651

652 653 654
    /* Generate default external file names for external snapshot locations */
    if (virDomainSnapshotDefAssignExternalNames(def) < 0)
        goto cleanup;
655 656 657

    ret = 0;

658
 cleanup:
659 660 661 662
    virBitmapFree(map);
    return ret;
}

663
static int
664
virDomainSnapshotDiskDefFormat(virBufferPtr buf,
665 666
                               virDomainSnapshotDiskDefPtr disk,
                               virDomainXMLOptionPtr xmlopt)
667
{
668
    int type = disk->src->type;
669

670
    if (!disk->name)
671
        return 0;
672

673
    virBufferEscapeString(buf, "<disk name='%s'", disk->name);
674 675 676
    if (disk->snapshot > 0)
        virBufferAsprintf(buf, " snapshot='%s'",
                          virDomainSnapshotLocationTypeToString(disk->snapshot));
677

678
    if (!disk->src->path && disk->src->format == 0) {
679
        virBufferAddLit(buf, "/>\n");
680
        return 0;
681 682
    }

E
Eric Blake 已提交
683
    virBufferAsprintf(buf, " type='%s'>\n", virStorageTypeToString(type));
684
    virBufferAdjustIndent(buf, 2);
685

686
    if (disk->src->format > 0)
687
        virBufferEscapeString(buf, "<driver type='%s'/>\n",
688
                              virStorageFileFormatTypeToString(disk->src->format));
689 690
    if (virDomainDiskSourceFormat(buf, disk->src, 0, 0, xmlopt) < 0)
        return -1;
691

692 693
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</disk>\n");
694
    return 0;
695 696
}

697 698 699 700 701

char *
virDomainSnapshotDefFormat(const char *domain_uuid,
                           virDomainSnapshotDefPtr def,
                           virCapsPtr caps,
702
                           virDomainXMLOptionPtr xmlopt,
703 704
                           unsigned int flags,
                           int internal)
705 706
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
707
    size_t i;
708

709
    virCheckFlags(VIR_DOMAIN_DEF_FORMAT_SECURE, NULL);
710

711
    flags |= VIR_DOMAIN_DEF_FORMAT_INACTIVE;
712 713

    virBufferAddLit(&buf, "<domainsnapshot>\n");
714
    virBufferAdjustIndent(&buf, 2);
715

716
    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
717
    if (def->description)
718
        virBufferEscapeString(&buf, "<description>%s</description>\n",
719
                              def->description);
720
    virBufferAsprintf(&buf, "<state>%s</state>\n",
721
                      virDomainSnapshotStateTypeToString(def->state));
722

723
    if (def->parent) {
724 725 726 727 728
        virBufferAddLit(&buf, "<parent>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferEscapeString(&buf, "<name>%s</name>\n", def->parent);
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</parent>\n");
729
    }
730

731
    virBufferAsprintf(&buf, "<creationTime>%lld</creationTime>\n",
732
                      def->creationTime);
733

734
    if (def->memory) {
735
        virBufferAsprintf(&buf, "<memory snapshot='%s'",
736 737 738 739
                          virDomainSnapshotLocationTypeToString(def->memory));
        virBufferEscapeString(&buf, " file='%s'", def->file);
        virBufferAddLit(&buf, "/>\n");
    }
740

741
    if (def->ndisks) {
742 743
        virBufferAddLit(&buf, "<disks>\n");
        virBufferAdjustIndent(&buf, 2);
744 745 746 747
        for (i = 0; i < def->ndisks; i++) {
            if (virDomainSnapshotDiskDefFormat(&buf, &def->disks[i], xmlopt) < 0)
                goto error;
        }
748 749
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</disks>\n");
750
    }
751

752
    if (def->dom) {
753
        if (virDomainDefFormatInternal(def->dom, caps, flags, &buf, xmlopt) < 0)
754
            goto error;
755
    } else if (domain_uuid) {
756 757 758 759 760
        virBufferAddLit(&buf, "<domain>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<uuid>%s</uuid>\n", domain_uuid);
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</domain>\n");
761
    }
762

763 764 765 766
    if (virSaveCookieFormatBuf(&buf, def->cookie,
                               virDomainXMLOptionGetSaveCookie(xmlopt)) < 0)
        goto error;

767
    if (internal)
768
        virBufferAsprintf(&buf, "<active>%d</active>\n", def->current);
769

770
    virBufferAdjustIndent(&buf, -2);
771 772
    virBufferAddLit(&buf, "</domainsnapshot>\n");

773
    if (virBufferCheckError(&buf) < 0)
774 775 776
        return NULL;

    return virBufferContentAndReset(&buf);
777 778 779 780

 error:
    virBufferFreeAndReset(&buf);
    return NULL;
781 782 783 784 785 786 787
}

/* Snapshot Obj functions */
static virDomainSnapshotObjPtr virDomainSnapshotObjNew(void)
{
    virDomainSnapshotObjPtr snapshot;

788
    if (VIR_ALLOC(snapshot) < 0)
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
        return NULL;

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

    return snapshot;
}

static void virDomainSnapshotObjFree(virDomainSnapshotObjPtr snapshot)
{
    if (!snapshot)
        return;

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

    virDomainSnapshotDefFree(snapshot->def);
    VIR_FREE(snapshot);
}

virDomainSnapshotObjPtr virDomainSnapshotAssignDef(virDomainSnapshotObjListPtr snapshots,
E
Eric Blake 已提交
808
                                                   virDomainSnapshotDefPtr def)
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
{
    virDomainSnapshotObjPtr snap;

    if (virHashLookup(snapshots->objs, def->name) != NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected domain snapshot %s already exists"),
                       def->name);
        return NULL;
    }

    if (!(snap = virDomainSnapshotObjNew()))
        return NULL;
    snap->def = def;

    if (virHashAddEntry(snapshots->objs, snap->def->name, snap) < 0) {
        VIR_FREE(snap);
        return NULL;
    }

    return snap;
}

/* Snapshot Obj List functions */
static void
virDomainSnapshotObjListDataFree(void *payload,
                                 const void *name ATTRIBUTE_UNUSED)
{
    virDomainSnapshotObjPtr obj = payload;

    virDomainSnapshotObjFree(obj);
}

virDomainSnapshotObjListPtr
virDomainSnapshotObjListNew(void)
{
    virDomainSnapshotObjListPtr snapshots;
845
    if (VIR_ALLOC(snapshots) < 0)
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
        return NULL;
    snapshots->objs = virHashCreate(50, virDomainSnapshotObjListDataFree);
    if (!snapshots->objs) {
        VIR_FREE(snapshots);
        return NULL;
    }
    return snapshots;
}

void
virDomainSnapshotObjListFree(virDomainSnapshotObjListPtr snapshots)
{
    if (!snapshots)
        return;
    virHashFree(snapshots->objs);
    VIR_FREE(snapshots);
}

struct virDomainSnapshotNameData {
    char **const names;
    int maxnames;
    unsigned int flags;
    int count;
    bool error;
};

872 873 874
static int virDomainSnapshotObjListCopyNames(void *payload,
                                             const void *name ATTRIBUTE_UNUSED,
                                             void *opaque)
875 876 877 878 879
{
    virDomainSnapshotObjPtr obj = payload;
    struct virDomainSnapshotNameData *data = opaque;

    if (data->error)
880
        return 0;
881 882 883
    /* Caller already sanitized flags.  Filtering on DESCENDANTS was
     * done by choice of iteration in the caller.  */
    if ((data->flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES) && obj->nchildren)
884
        return 0;
885
    if ((data->flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES) && !obj->nchildren)
886
        return 0;
887

E
Eric Blake 已提交
888 889 890
    if (data->flags & VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS) {
        if (!(data->flags & VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE) &&
            obj->def->state == VIR_DOMAIN_SHUTOFF)
891
            return 0;
E
Eric Blake 已提交
892 893
        if (!(data->flags & VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY) &&
            obj->def->state == VIR_DOMAIN_DISK_SNAPSHOT)
894
            return 0;
E
Eric Blake 已提交
895 896 897
        if (!(data->flags & VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE) &&
            obj->def->state != VIR_DOMAIN_SHUTOFF &&
            obj->def->state != VIR_DOMAIN_DISK_SNAPSHOT)
898
            return 0;
E
Eric Blake 已提交
899 900 901 902
    }

    if ((data->flags & VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL) &&
        virDomainSnapshotIsExternal(obj))
903
        return 0;
E
Eric Blake 已提交
904 905
    if ((data->flags & VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL) &&
        !virDomainSnapshotIsExternal(obj))
906
        return 0;
E
Eric Blake 已提交
907

908
    if (data->names && data->count < data->maxnames &&
909
        VIR_STRDUP(data->names[data->count], obj->def->name) < 0) {
910
        data->error = true;
911
        return 0;
912 913
    }
    data->count++;
914
    return 0;
915 916 917 918 919 920 921 922 923 924
}

int
virDomainSnapshotObjListGetNames(virDomainSnapshotObjListPtr snapshots,
                                 virDomainSnapshotObjPtr from,
                                 char **const names, int maxnames,
                                 unsigned int flags)
{
    struct virDomainSnapshotNameData data = { names, maxnames, flags, 0,
                                              false };
925
    size_t i;
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948

    if (!from) {
        /* LIST_ROOTS and LIST_DESCENDANTS have the same bit value,
         * but opposite semantics.  Toggle here to get the correct
         * traversal on the metaroot.  */
        flags ^= VIR_DOMAIN_SNAPSHOT_LIST_ROOTS;
        from = &snapshots->metaroot;
    }

    /* We handle LIST_ROOT/LIST_DESCENDANTS directly, mask that bit
     * out to determine when we must use the filter callback.  */
    data.flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;

    /* If this common code is being used, we assume that all snapshots
     * have metadata, and thus can handle METADATA up front as an
     * all-or-none filter.  XXX This might not always be true, if we
     * add the ability to track qcow2 internal snapshots without the
     * use of metadata.  */
    if ((data.flags & VIR_DOMAIN_SNAPSHOT_FILTERS_METADATA) ==
        VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA)
        return 0;
    data.flags &= ~VIR_DOMAIN_SNAPSHOT_FILTERS_METADATA;

E
Eric Blake 已提交
949 950
    /* For ease of coding the visitor, it is easier to zero each group
     * where all of the bits are set.  */
951 952 953
    if ((data.flags & VIR_DOMAIN_SNAPSHOT_FILTERS_LEAVES) ==
        VIR_DOMAIN_SNAPSHOT_FILTERS_LEAVES)
        data.flags &= ~VIR_DOMAIN_SNAPSHOT_FILTERS_LEAVES;
E
Eric Blake 已提交
954 955 956 957 958 959
    if ((data.flags & VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS) ==
        VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS)
        data.flags &= ~VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS;
    if ((data.flags & VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION) ==
        VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION)
        data.flags &= ~VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION;
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 989 990 991 992 993 994 995

    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) {
        if (from->def)
            virDomainSnapshotForEachDescendant(from,
                                               virDomainSnapshotObjListCopyNames,
                                               &data);
        else if (names || data.flags)
            virHashForEach(snapshots->objs, virDomainSnapshotObjListCopyNames,
                           &data);
        else
            data.count = virHashSize(snapshots->objs);
    } else if (names || data.flags) {
        virDomainSnapshotForEachChild(from,
                                      virDomainSnapshotObjListCopyNames, &data);
    } else {
        data.count = from->nchildren;
    }

    if (data.error) {
        for (i = 0; i < data.count; i++)
            VIR_FREE(names[i]);
        return -1;
    }

    return data.count;
}

int
virDomainSnapshotObjListNum(virDomainSnapshotObjListPtr snapshots,
                            virDomainSnapshotObjPtr from,
                            unsigned int flags)
{
    return virDomainSnapshotObjListGetNames(snapshots, from, NULL, 0, flags);
}

virDomainSnapshotObjPtr
E
Eric Blake 已提交
996
virDomainSnapshotFindByName(virDomainSnapshotObjListPtr snapshots,
997 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 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
                            const char *name)
{
    return name ? virHashLookup(snapshots->objs, name) : &snapshots->metaroot;
}

void virDomainSnapshotObjListRemove(virDomainSnapshotObjListPtr snapshots,
                                    virDomainSnapshotObjPtr snapshot)
{
    virHashRemoveEntry(snapshots->objs, snapshot->def->name);
}

int
virDomainSnapshotForEach(virDomainSnapshotObjListPtr snapshots,
                         virHashIterator iter,
                         void *data)
{
    return virHashForEach(snapshots->objs, iter, data);
}

/* Run iter(data) on all direct children of snapshot, while ignoring all
 * other entries in snapshots.  Return the number of children
 * visited.  No particular ordering is guaranteed.  */
int
virDomainSnapshotForEachChild(virDomainSnapshotObjPtr snapshot,
                              virHashIterator iter,
                              void *data)
{
    virDomainSnapshotObjPtr child = snapshot->first_child;

    while (child) {
        virDomainSnapshotObjPtr next = child->sibling;
        (iter)(child, child->def->name, data);
        child = next;
    }

    return snapshot->nchildren;
}

struct snapshot_act_on_descendant {
    int number;
    virHashIterator iter;
    void *data;
};

1041
static int
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
virDomainSnapshotActOnDescendant(void *payload,
                                 const void *name,
                                 void *data)
{
    virDomainSnapshotObjPtr obj = payload;
    struct snapshot_act_on_descendant *curr = data;

    curr->number += 1 + virDomainSnapshotForEachDescendant(obj,
                                                           curr->iter,
                                                           curr->data);
    (curr->iter)(payload, name, curr->data);
1053
    return 0;
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
}

/* Run iter(data) on all descendants of snapshot, while ignoring all
 * other entries in snapshots.  Return the number of descendants
 * visited.  No particular ordering is guaranteed.  */
int
virDomainSnapshotForEachDescendant(virDomainSnapshotObjPtr snapshot,
                                   virHashIterator iter,
                                   void *data)
{
    struct snapshot_act_on_descendant act;

    act.number = 0;
    act.iter = iter;
    act.data = data;
    virDomainSnapshotForEachChild(snapshot,
                                  virDomainSnapshotActOnDescendant, &act);

    return act.number;
}

/* Struct and callback function used as a hash table callback; each call
 * inspects the pre-existing snapshot->def->parent field, and adjusts
 * the snapshot->parent field as well as the parent's child fields to
 * wire up the hierarchical relations for the given snapshot.  The error
 * indicator gets set if a parent is missing or a requested parent would
 * cause a circular parent chain.  */
struct snapshot_set_relation {
    virDomainSnapshotObjListPtr snapshots;
    int err;
};
1085
static int
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
virDomainSnapshotSetRelations(void *payload,
                              const void *name ATTRIBUTE_UNUSED,
                              void *data)
{
    virDomainSnapshotObjPtr obj = payload;
    struct snapshot_set_relation *curr = data;
    virDomainSnapshotObjPtr tmp;

    obj->parent = virDomainSnapshotFindByName(curr->snapshots,
                                              obj->def->parent);
    if (!obj->parent) {
        curr->err = -1;
        obj->parent = &curr->snapshots->metaroot;
        VIR_WARN("snapshot %s lacks parent", obj->def->name);
    } else {
        tmp = obj->parent;
        while (tmp && tmp->def) {
            if (tmp == obj) {
                curr->err = -1;
                obj->parent = &curr->snapshots->metaroot;
                VIR_WARN("snapshot %s in circular chain", obj->def->name);
                break;
            }
            tmp = tmp->parent;
        }
    }
    obj->parent->nchildren++;
    obj->sibling = obj->parent->first_child;
    obj->parent->first_child = obj;
1115
    return 0;
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
}

/* Populate parent link and child count of all snapshots, with all
 * relations starting as 0/NULL.  Return 0 on success, -1 if a parent
 * is missing or if a circular relationship was requested.  */
int
virDomainSnapshotUpdateRelations(virDomainSnapshotObjListPtr snapshots)
{
    struct snapshot_set_relation act = { snapshots, 0 };

    virHashForEach(snapshots->objs, virDomainSnapshotSetRelations, &act);
    return act.err;
}

/* Prepare to reparent or delete snapshot, by removing it from its
 * current listed parent.  Note that when bulk removing all children
 * of a parent, it is faster to just 0 the count rather than calling
 * this function on each child.  */
void
virDomainSnapshotDropParent(virDomainSnapshotObjPtr snapshot)
{
    virDomainSnapshotObjPtr prev = NULL;
    virDomainSnapshotObjPtr curr = NULL;

    snapshot->parent->nchildren--;
    curr = snapshot->parent->first_child;
    while (curr != snapshot) {
        if (!curr) {
            VIR_WARN("inconsistent snapshot relations");
            return;
        }
        prev = curr;
        curr = curr->sibling;
    }
    if (prev)
        prev->sibling = snapshot->sibling;
    else
        snapshot->parent->first_child = snapshot->sibling;
    snapshot->parent = NULL;
    snapshot->sibling = NULL;
}

int
virDomainListSnapshots(virDomainSnapshotObjListPtr snapshots,
                       virDomainSnapshotObjPtr from,
                       virDomainPtr dom,
                       virDomainSnapshotPtr **snaps,
                       unsigned int flags)
{
    int count = virDomainSnapshotObjListNum(snapshots, from, flags);
1166
    virDomainSnapshotPtr *list = NULL;
1167 1168
    char **names;
    int ret = -1;
1169
    size_t i;
1170

1171
    if (!snaps || count < 0)
1172 1173
        return count;
    if (VIR_ALLOC_N(names, count) < 0 ||
1174
        VIR_ALLOC_N(list, count + 1) < 0)
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
        goto cleanup;

    if (virDomainSnapshotObjListGetNames(snapshots, from, names, count,
                                         flags) < 0)
        goto cleanup;
    for (i = 0; i < count; i++)
        if ((list[i] = virGetDomainSnapshot(dom, names[i])) == NULL)
            goto cleanup;

    ret = count;
    *snaps = list;

1187
 cleanup:
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
    for (i = 0; i < count; i++)
        VIR_FREE(names[i]);
    VIR_FREE(names);
    if (ret < 0 && list) {
        for (i = 0; i < count; i++)
            virObjectUnref(list[i]);
        VIR_FREE(list);
    }
    return ret;
}
1198 1199 1200


bool
1201
virDomainSnapshotDefIsExternal(virDomainSnapshotDefPtr def)
1202
{
1203
    size_t i;
1204

1205
    if (def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL)
1206 1207
        return true;

1208 1209
    for (i = 0; i < def->ndisks; i++) {
        if (def->disks[i].snapshot == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL)
1210 1211 1212 1213 1214
            return true;
    }

    return false;
}
1215 1216 1217 1218 1219 1220

bool
virDomainSnapshotIsExternal(virDomainSnapshotObjPtr snap)
{
    return virDomainSnapshotDefIsExternal(snap->def);
}
1221 1222 1223 1224 1225 1226

int
virDomainSnapshotRedefinePrep(virDomainPtr domain,
                              virDomainObjPtr vm,
                              virDomainSnapshotDefPtr *defptr,
                              virDomainSnapshotObjPtr *snap,
1227
                              virDomainXMLOptionPtr xmlopt,
1228 1229 1230 1231 1232 1233
                              bool *update_current,
                              unsigned int flags)
{
    virDomainSnapshotDefPtr def = *defptr;
    int ret = -1;
    int align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_INTERNAL;
E
Eric Blake 已提交
1234
    bool align_match = true;
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virDomainSnapshotObjPtr other;

    virUUIDFormat(domain->uuid, uuidstr);

    /* Prevent circular chains */
    if (def->parent) {
        if (STREQ(def->name, def->parent)) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("cannot set snapshot %s as its own parent"),
                           def->name);
            goto cleanup;
        }
        other = virDomainSnapshotFindByName(vm->snapshots, def->parent);
        if (!other) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("parent %s for snapshot %s not found"),
                           def->parent, def->name);
            goto cleanup;
        }
        while (other->def->parent) {
            if (STREQ(other->def->parent, def->name)) {
                virReportError(VIR_ERR_INVALID_ARG,
                               _("parent %s would create cycle to %s"),
                               other->def->name, def->name);
                goto cleanup;
            }
            other = virDomainSnapshotFindByName(vm->snapshots,
                                                other->def->parent);
            if (!other) {
                VIR_WARN("snapshots are inconsistent for %s",
                         vm->def->name);
                break;
            }
        }
    }

    /* Check that any replacement is compatible */
    if ((flags & VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY) &&
        def->state != VIR_DOMAIN_DISK_SNAPSHOT) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("disk-only flag for snapshot %s requires "
                         "disk-snapshot state"),
                       def->name);
        goto cleanup;

    }

    if (def->dom &&
        memcmp(def->dom->uuid, domain->uuid, VIR_UUID_BUFLEN)) {
        virReportError(VIR_ERR_INVALID_ARG,
                       _("definition for snapshot %s must use uuid %s"),
                       def->name, uuidstr);
        goto cleanup;
    }

    other = virDomainSnapshotFindByName(vm->snapshots, def->name);
    if (other) {
        if ((other->def->state == VIR_DOMAIN_RUNNING ||
             other->def->state == VIR_DOMAIN_PAUSED) !=
            (def->state == VIR_DOMAIN_RUNNING ||
             def->state == VIR_DOMAIN_PAUSED)) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("cannot change between online and offline "
                             "snapshot state in snapshot %s"),
                           def->name);
            goto cleanup;
        }

        if ((other->def->state == VIR_DOMAIN_DISK_SNAPSHOT) !=
            (def->state == VIR_DOMAIN_DISK_SNAPSHOT)) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("cannot change between disk snapshot and "
                             "system checkpoint in snapshot %s"),
                           def->name);
            goto cleanup;
        }

        if (other->def->dom) {
            if (def->dom) {
                if (!virDomainDefCheckABIStability(other->def->dom,
1316
                                                   def->dom, xmlopt))
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
                    goto cleanup;
            } else {
                /* Transfer the domain def */
                def->dom = other->def->dom;
                other->def->dom = NULL;
            }
        }

        if (def->dom) {
            if (def->state == VIR_DOMAIN_DISK_SNAPSHOT ||
                virDomainSnapshotDefIsExternal(def)) {
                align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
                align_match = false;
            }

            if (virDomainSnapshotAlignDisks(def, align_location,
                                            align_match) < 0) {
                /* revert stealing of the snapshot domain definition */
                if (def->dom && !other->def->dom) {
                    other->def->dom = def->dom;
                    def->dom = NULL;
                }
                goto cleanup;
            }
        }

        if (other == vm->current_snapshot) {
            *update_current = true;
            vm->current_snapshot = NULL;
        }

        /* Drop and rebuild the parent relationship, but keep all
         * child relations by reusing snap.  */
        virDomainSnapshotDropParent(other);
        virDomainSnapshotDefFree(other->def);
        other->def = def;
        *defptr = NULL;
        *snap = other;
    } else {
        if (def->dom) {
            if (def->state == VIR_DOMAIN_DISK_SNAPSHOT ||
                def->memory == VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL) {
                align_location = VIR_DOMAIN_SNAPSHOT_LOCATION_EXTERNAL;
                align_match = false;
            }
            if (virDomainSnapshotAlignDisks(def, align_location,
                                            align_match) < 0)
                goto cleanup;
        }
    }

    ret = 0;
1369
 cleanup:
1370 1371
    return ret;
}