virsh-snapshot.c 61.9 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * virsh-snapshot.c: Commands to manage domain snapshot
3
 *
4
 * Copyright (C) 2005, 2007-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
18 19 20 21 22 23 24 25
 * <http://www.gnu.org/licenses/>.
 *
 *  Daniel Veillard <veillard@redhat.com>
 *  Karel Zak <kzak@redhat.com>
 *  Daniel P. Berrange <berrange@redhat.com>
 *
 */

E
Eric Blake 已提交
26 27 28 29 30 31 32 33 34 35 36
#include <config.h>
#include "virsh-snapshot.h"

#include <assert.h>

#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/xmlsave.h>

#include "internal.h"
37
#include "virbuffer.h"
38
#include "viralloc.h"
39
#include "virfile.h"
E
Eric Blake 已提交
40
#include "virsh-domain.h"
41
#include "virstring.h"
42
#include "virxml.h"
43
#include "conf/snapshot_conf.h"
E
Eric Blake 已提交
44

45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
/* Helper for snapshot-create and snapshot-create-as */
static bool
vshSnapshotCreate(vshControl *ctl, virDomainPtr dom, const char *buffer,
                  unsigned int flags, const char *from)
{
    bool ret = false;
    virDomainSnapshotPtr snapshot;
    bool halt = false;
    char *doc = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    const char *name = NULL;

    snapshot = virDomainSnapshotCreateXML(dom, buffer, flags);

    /* Emulate --halt on older servers.  */
    if (!snapshot && last_error->code == VIR_ERR_INVALID_ARG &&
        (flags & VIR_DOMAIN_SNAPSHOT_CREATE_HALT)) {
        int persistent;

65
        vshResetLibvirtError();
66 67
        persistent = virDomainIsPersistent(dom);
        if (persistent < 0) {
E
Eric Blake 已提交
68
            vshReportError(ctl);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
            goto cleanup;
        }
        if (!persistent) {
            vshError(ctl, "%s",
                     _("cannot halt after snapshot of transient domain"));
            goto cleanup;
        }
        if (virDomainIsActive(dom) == 1)
            halt = true;
        flags &= ~VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
        snapshot = virDomainSnapshotCreateXML(dom, buffer, flags);
    }

    if (snapshot == NULL)
        goto cleanup;

    if (halt && virDomainDestroy(dom) < 0) {
E
Eric Blake 已提交
86
        vshReportError(ctl);
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        goto cleanup;
    }

    name = virDomainSnapshotGetName(snapshot);
    if (!name) {
        vshError(ctl, "%s", _("Could not get snapshot name"));
        goto cleanup;
    }

    if (from)
        vshPrint(ctl, _("Domain snapshot %s created from '%s'"), name, from);
    else
        vshPrint(ctl, _("Domain snapshot %s created"), name);

    ret = true;

103
 cleanup:
104 105 106 107 108 109 110 111 112 113 114 115
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    VIR_FREE(doc);
    return ret;
}

/*
 * "snapshot-create" command
 */
static const vshCmdInfo info_snapshot_create[] = {
116 117 118 119 120 121 122
    {.name = "help",
     .data = N_("Create a snapshot from XML")
    },
    {.name = "desc",
     .data = N_("Create a snapshot (disk and RAM) from XML")
    },
    {.name = NULL}
123 124 125
};

static const vshCmdOptDef opts_snapshot_create[] = {
126 127 128 129 130 131
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "xmlfile",
132
     .type = VSH_OT_STRING,
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
     .help = N_("domain snapshot XML")
    },
    {.name = "redefine",
     .type = VSH_OT_BOOL,
     .help = N_("redefine metadata for existing snapshot")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("with redefine, set current snapshot")
    },
    {.name = "no-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("take snapshot but create no metadata")
    },
    {.name = "halt",
     .type = VSH_OT_BOOL,
     .help = N_("halt domain after snapshot is created")
    },
    {.name = "disk-only",
     .type = VSH_OT_BOOL,
     .help = N_("capture disk state but not vm state")
    },
    {.name = "reuse-external",
     .type = VSH_OT_BOOL,
     .help = N_("reuse any existing external files")
    },
    {.name = "quiesce",
     .type = VSH_OT_BOOL,
     .help = N_("quiesce guest's file systems")
    },
    {.name = "atomic",
     .type = VSH_OT_BOOL,
     .help = N_("require atomic operation")
    },
    {.name = "live",
     .type = VSH_OT_BOOL,
     .help = N_("take a live snapshot")
    },
    {.name = NULL}
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
};

static bool
cmdSnapshotCreate(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    const char *from = NULL;
    char *buffer = NULL;
    unsigned int flags = 0;

    if (vshCommandOptBool(cmd, "redefine"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE;
    if (vshCommandOptBool(cmd, "current"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;
    if (vshCommandOptBool(cmd, "no-metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA;
    if (vshCommandOptBool(cmd, "halt"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
    if (vshCommandOptBool(cmd, "disk-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
    if (vshCommandOptBool(cmd, "reuse-external"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT;
    if (vshCommandOptBool(cmd, "quiesce"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE;
    if (vshCommandOptBool(cmd, "atomic"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
199 200
    if (vshCommandOptBool(cmd, "live"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_LIVE;
201

202
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
203 204
        goto cleanup;

205 206 207
    if (vshCommandOptStringReq(ctl, cmd, "xmlfile", &from) < 0)
        goto cleanup;
    if (!from) {
208
        buffer = vshStrdup(ctl, "<domainsnapshot/>");
209
    } else {
E
Eric Blake 已提交
210
        if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0) {
211
            vshSaveLibvirtError();
212 213 214 215 216 217
            goto cleanup;
        }
    }

    ret = vshSnapshotCreate(ctl, dom, buffer, flags, from);

218
 cleanup:
219 220 221 222 223 224 225 226 227 228
    VIR_FREE(buffer);
    if (dom)
        virDomainFree(dom);

    return ret;
}

/*
 * "snapshot-create-as" command
 */
229 230 231 232 233 234 235 236
static int
vshParseSnapshotMemspec(vshControl *ctl, virBufferPtr buf, const char *str)
{
    int ret = -1;
    const char *snapshot = NULL;
    const char *file = NULL;
    char **array = NULL;
    int narray;
237
    size_t i;
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256

    if (!str)
        return 0;

    narray = vshStringToArray(str, &array);
    if (narray < 0)
        goto cleanup;

    for (i = 0; i < narray; i++) {
        if (!snapshot && STRPREFIX(array[i], "snapshot="))
            snapshot = array[i] + strlen("snapshot=");
        else if (!file && STRPREFIX(array[i], "file="))
            file = array[i] + strlen("file=");
        else if (!file && *array[i] == '/')
            file = array[i];
        else
            goto cleanup;
    }

257
    virBufferAddLit(buf, "<memory");
258 259 260 261
    virBufferEscapeString(buf, " snapshot='%s'", snapshot);
    virBufferEscapeString(buf, " file='%s'", file);
    virBufferAddLit(buf, "/>\n");
    ret = 0;
262
 cleanup:
263 264
    if (ret < 0)
        vshError(ctl, _("unable to parse memspec: %s"), str);
265
    virStringFreeList(array);
266 267 268
    return ret;
}

269 270 271 272
static int
vshParseSnapshotDiskspec(vshControl *ctl, virBufferPtr buf, const char *str)
{
    int ret = -1;
E
Eric Blake 已提交
273 274 275 276 277 278
    const char *name = NULL;
    const char *snapshot = NULL;
    const char *driver = NULL;
    const char *file = NULL;
    char **array = NULL;
    int narray;
279
    size_t i;
280

E
Eric Blake 已提交
281 282
    narray = vshStringToArray(str, &array);
    if (narray <= 0)
283
        goto cleanup;
E
Eric Blake 已提交
284 285 286 287 288 289 290 291 292

    name = array[0];
    for (i = 1; i < narray; i++) {
        if (!snapshot && STRPREFIX(array[i], "snapshot="))
            snapshot = array[i] + strlen("snapshot=");
        else if (!driver && STRPREFIX(array[i], "driver="))
            driver = array[i] + strlen("driver=");
        else if (!file && STRPREFIX(array[i], "file="))
            file = array[i] + strlen("file=");
293 294 295 296
        else
            goto cleanup;
    }

297
    virBufferEscapeString(buf, "<disk name='%s'", name);
298 299 300 301
    if (snapshot)
        virBufferAsprintf(buf, " snapshot='%s'", snapshot);
    if (driver || file) {
        virBufferAddLit(buf, ">\n");
302
        virBufferAdjustIndent(buf, 2);
303
        if (driver)
304
            virBufferAsprintf(buf, "<driver type='%s'/>\n", driver);
305
        if (file)
306 307 308
            virBufferEscapeString(buf, "<source file='%s'/>\n", file);
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</disk>\n");
309 310 311 312
    } else {
        virBufferAddLit(buf, "/>\n");
    }
    ret = 0;
313
 cleanup:
314 315
    if (ret < 0)
        vshError(ctl, _("unable to parse diskspec: %s"), str);
316
    virStringFreeList(array);
317 318 319 320
    return ret;
}

static const vshCmdInfo info_snapshot_create_as[] = {
321 322 323 324 325 326 327
    {.name = "help",
     .data = N_("Create a snapshot from a set of args")
    },
    {.name = "desc",
     .data = N_("Create a snapshot (disk and RAM) from arguments")
    },
    {.name = NULL}
328 329 330
};

static const vshCmdOptDef opts_snapshot_create_as[] = {
331 332 333 334 335 336
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "name",
337
     .type = VSH_OT_STRING,
338 339 340
     .help = N_("name of snapshot")
    },
    {.name = "description",
341
     .type = VSH_OT_STRING,
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
     .help = N_("description of snapshot")
    },
    {.name = "print-xml",
     .type = VSH_OT_BOOL,
     .help = N_("print XML document rather than create")
    },
    {.name = "no-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("take snapshot but create no metadata")
    },
    {.name = "halt",
     .type = VSH_OT_BOOL,
     .help = N_("halt domain after snapshot is created")
    },
    {.name = "disk-only",
     .type = VSH_OT_BOOL,
     .help = N_("capture disk state but not vm state")
    },
    {.name = "reuse-external",
     .type = VSH_OT_BOOL,
     .help = N_("reuse any existing external files")
    },
    {.name = "quiesce",
     .type = VSH_OT_BOOL,
     .help = N_("quiesce guest's file systems")
    },
    {.name = "atomic",
     .type = VSH_OT_BOOL,
     .help = N_("require atomic operation")
    },
    {.name = "live",
     .type = VSH_OT_BOOL,
     .help = N_("take a live snapshot")
    },
    {.name = "memspec",
377
     .type = VSH_OT_STRING,
378 379 380 381 382 383 384 385
     .flags = VSH_OFLAG_REQ_OPT,
     .help = N_("memory attributes: [file=]name[,snapshot=type]")
    },
    {.name = "diskspec",
     .type = VSH_OT_ARGV,
     .help = N_("disk attributes: disk[,snapshot=type][,driver=type][,file=name]")
    },
    {.name = NULL}
386 387 388 389 390 391 392 393 394 395
};

static bool
cmdSnapshotCreateAs(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    char *buffer = NULL;
    const char *name = NULL;
    const char *desc = NULL;
396
    const char *memspec = NULL;
397 398 399 400
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    unsigned int flags = 0;
    const vshCmdOpt *opt = NULL;

401 402 403 404 405 406
    if (vshCommandOptBool(cmd, "no-metadata")) {
        if (vshCommandOptBool(cmd, "print-xml")) {
            vshError(ctl, "%s",
                     _("--print-xml is incompatible with --no-metadata"));
            return false;
        }
407
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA;
408
    }
409 410 411 412 413 414 415 416 417 418
    if (vshCommandOptBool(cmd, "halt"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_HALT;
    if (vshCommandOptBool(cmd, "disk-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
    if (vshCommandOptBool(cmd, "reuse-external"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT;
    if (vshCommandOptBool(cmd, "quiesce"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE;
    if (vshCommandOptBool(cmd, "atomic"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_ATOMIC;
419 420
    if (vshCommandOptBool(cmd, "live"))
        flags |= VIR_DOMAIN_SNAPSHOT_CREATE_LIVE;
421

422 423
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;
424

425 426
    if (vshCommandOptStringReq(ctl, cmd, "name", &name) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "description", &desc) < 0)
427 428 429
        goto cleanup;

    virBufferAddLit(&buf, "<domainsnapshot>\n");
430 431 432
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", name);
    virBufferEscapeString(&buf, "<description>%s</description>\n", desc);
433

434
    if (vshCommandOptStringReq(ctl, cmd, "memspec", &memspec) < 0)
435
        goto cleanup;
436 437 438 439

    if (memspec && vshParseSnapshotMemspec(ctl, &buf, memspec) < 0)
        goto cleanup;

440
    if (vshCommandOptBool(cmd, "diskspec")) {
441 442
        virBufferAddLit(&buf, "<disks>\n");
        virBufferAdjustIndent(&buf, 2);
443
        while ((opt = vshCommandOptArgv(ctl, cmd, opt))) {
444
            if (vshParseSnapshotDiskspec(ctl, &buf, opt->data) < 0)
445 446
                goto cleanup;
        }
447 448
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</disks>\n");
449
    }
450
    virBufferAdjustIndent(&buf, -2);
451 452
    virBufferAddLit(&buf, "</domainsnapshot>\n");

453
    if (virBufferError(&buf)) {
454 455 456 457
        vshError(ctl, "%s", _("Out of memory"));
        goto cleanup;
    }

458 459
    buffer = virBufferContentAndReset(&buf);

460 461 462 463 464 465 466 467
    if (vshCommandOptBool(cmd, "print-xml")) {
        vshPrint(ctl, "%s\n",  buffer);
        ret = true;
        goto cleanup;
    }

    ret = vshSnapshotCreate(ctl, dom, buffer, flags, NULL);

468
 cleanup:
469
    virBufferFreeAndReset(&buf);
470
    VIR_FREE(buffer);
471
    virDomainFree(dom);
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    return ret;
}

/* Helper for resolving {--current | --ARG name} into a snapshot
 * belonging to DOM.  If EXCLUSIVE, fail if both --current and arg are
 * present.  On success, populate *SNAP and *NAME, before returning 0.
 * On failure, return -1 after issuing an error message.  */
static int
vshLookupSnapshot(vshControl *ctl, const vshCmd *cmd,
                  const char *arg, bool exclusive, virDomainPtr dom,
                  virDomainSnapshotPtr *snap, const char **name)
{
    bool current = vshCommandOptBool(cmd, "current");
    const char *snapname = NULL;

488
    if (vshCommandOptStringReq(ctl, cmd, arg, &snapname) < 0)
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
        return -1;

    if (exclusive && current && snapname) {
        vshError(ctl, _("--%s and --current are mutually exclusive"), arg);
        return -1;
    }

    if (snapname) {
        *snap = virDomainSnapshotLookupByName(dom, snapname, 0);
    } else if (current) {
        *snap = virDomainSnapshotCurrent(dom, 0);
    } else {
        vshError(ctl, _("--%s or --current is required"), arg);
        return -1;
    }
    if (!*snap) {
E
Eric Blake 已提交
505
        vshReportError(ctl);
506 507 508 509 510 511 512 513 514 515 516
        return -1;
    }

    *name = virDomainSnapshotGetName(*snap);
    return 0;
}

/*
 * "snapshot-edit" command
 */
static const vshCmdInfo info_snapshot_edit[] = {
517 518 519 520 521 522 523
    {.name = "help",
     .data = N_("edit XML for a snapshot")
    },
    {.name = "desc",
     .data = N_("Edit the domain snapshot XML for a named snapshot")
    },
    {.name = NULL}
524 525 526
};

static const vshCmdOptDef opts_snapshot_edit[] = {
527 528 529 530 531 532
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "snapshotname",
533
     .type = VSH_OT_STRING,
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
     .help = N_("snapshot name")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("also set edited snapshot as current")
    },
    {.name = "rename",
     .type = VSH_OT_BOOL,
     .help = N_("allow renaming an existing snapshot")
    },
    {.name = "clone",
     .type = VSH_OT_BOOL,
     .help = N_("allow cloning to new name")
    },
    {.name = NULL}
549 550 551 552 553 554 555 556
};

static bool
cmdSnapshotEdit(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    virDomainSnapshotPtr edited = NULL;
557
    const char *name = NULL;
558 559 560 561 562 563 564
    const char *edited_name;
    bool ret = false;
    unsigned int getxml_flags = VIR_DOMAIN_XML_SECURE;
    unsigned int define_flags = VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE;
    bool rename_okay = vshCommandOptBool(cmd, "rename");
    bool clone_okay = vshCommandOptBool(cmd, "clone");

565
    VSH_EXCLUSIVE_OPTIONS_EXPR("rename", rename_okay, "clone", clone_okay)
566 567 568 569 570

    if (vshCommandOptBool(cmd, "current") &&
        vshCommandOptBool(cmd, "snapshotname"))
        define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT;

571 572
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;
573 574 575 576 577 578 579

    if (vshLookupSnapshot(ctl, cmd, "snapshotname", false, dom,
                          &snapshot, &name) < 0)
        goto cleanup;

#define EDIT_GET_XML \
    virDomainSnapshotGetXMLDesc(snapshot, getxml_flags)
580 581 582 583 584 585 586 587 588 589 590
#define EDIT_NOT_CHANGED                                                \
    do {                                                                \
        /* Depending on flags, we re-edit even if XML is unchanged.  */ \
        if (!(define_flags & VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT)) {     \
            vshPrint(ctl,                                               \
                     _("Snapshot %s XML configuration not changed.\n"), \
                     name);                                             \
            ret = true;                                                 \
            goto edit_cleanup;                                          \
        }                                                               \
    } while (0)
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
#define EDIT_DEFINE \
    (strstr(doc, "<state>disk-snapshot</state>") ? \
    define_flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY : 0), \
    edited = virDomainSnapshotCreateXML(dom, doc_edited, define_flags)
#include "virsh-edit.c"

    edited_name = virDomainSnapshotGetName(edited);
    if (STREQ(name, edited_name)) {
        vshPrint(ctl, _("Snapshot %s edited.\n"), name);
    } else if (clone_okay) {
        vshPrint(ctl, _("Snapshot %s cloned to %s.\n"), name,
                 edited_name);
    } else {
        unsigned int delete_flags;

        delete_flags = VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY;
        if (virDomainSnapshotDelete(rename_okay ? snapshot : edited,
                                    delete_flags) < 0) {
E
Eric Blake 已提交
609
            vshReportError(ctl);
610 611 612 613 614 615 616 617 618 619 620 621 622
            vshError(ctl, _("Failed to clean up %s"),
                     rename_okay ? name : edited_name);
            goto cleanup;
        }
        if (!rename_okay) {
            vshError(ctl, _("Must use --rename or --clone to change %s to %s"),
                     name, edited_name);
            goto cleanup;
        }
    }

    ret = true;

623
 cleanup:
624
    if (!ret && name)
625
        vshError(ctl, _("Failed to update %s"), name);
626 627 628 629
    if (edited)
        virDomainSnapshotFree(edited);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
630
    virDomainFree(dom);
631 632 633 634 635 636 637
    return ret;
}

/*
 * "snapshot-current" command
 */
static const vshCmdInfo info_snapshot_current[] = {
638 639 640 641 642 643 644
    {.name = "help",
     .data = N_("Get or set the current snapshot")
    },
    {.name = "desc",
     .data = N_("Get or set the current snapshot")
    },
    {.name = NULL}
645 646 647
};

static const vshCmdOptDef opts_snapshot_current[] = {
648 649 650 651 652 653 654 655 656 657 658 659 660 661
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "name",
     .type = VSH_OT_BOOL,
     .help = N_("list the name, rather than the full xml")
    },
    {.name = "security-info",
     .type = VSH_OT_BOOL,
     .help = N_("include security sensitive information in XML dump")
    },
    {.name = "snapshotname",
662
     .type = VSH_OT_STRING,
663 664 665
     .help = N_("name of existing snapshot to make current")
    },
    {.name = NULL}
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
};

static bool
cmdSnapshotCurrent(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    int current;
    virDomainSnapshotPtr snapshot = NULL;
    char *xml = NULL;
    const char *snapshotname = NULL;
    unsigned int flags = 0;
    const char *domname;

    if (vshCommandOptBool(cmd, "security-info"))
        flags |= VIR_DOMAIN_XML_SECURE;

683 684 685 686
    VSH_EXCLUSIVE_OPTIONS("name", "snapshotname");

    if (!(dom = vshCommandOptDomain(ctl, cmd, &domname)))
        return false;
687

688
    if (vshCommandOptStringReq(ctl, cmd, "snapshotname", &snapshotname) < 0)
689
        goto cleanup;
690

691 692 693 694 695
    if (snapshotname) {
        virDomainSnapshotPtr snapshot2 = NULL;
        flags = (VIR_DOMAIN_SNAPSHOT_CREATE_REDEFINE |
                 VIR_DOMAIN_SNAPSHOT_CREATE_CURRENT);

696
        if (!(snapshot = virDomainSnapshotLookupByName(dom, snapshotname, 0)))
697
            goto cleanup;
698

699 700 701
        xml = virDomainSnapshotGetXMLDesc(snapshot, VIR_DOMAIN_XML_SECURE);
        if (!xml)
            goto cleanup;
702

703 704 705
        /* strstr is safe here, since xml came from libvirt API and not user */
        if (strstr(xml, "<state>disk-snapshot</state>"))
            flags |= VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY;
706 707

        if (!(snapshot2 = virDomainSnapshotCreateXML(dom, xml, flags)))
708
            goto cleanup;
709

710 711 712 713 714 715
        virDomainSnapshotFree(snapshot2);
        vshPrint(ctl, _("Snapshot %s set as current"), snapshotname);
        ret = true;
        goto cleanup;
    }

716
    if ((current = virDomainHasCurrentSnapshot(dom, 0)) < 0)
717
        goto cleanup;
718 719

    if (!current) {
720 721 722 723 724 725 726
        vshError(ctl, _("domain '%s' has no current snapshot"), domname);
        goto cleanup;
    } else {
        if (!(snapshot = virDomainSnapshotCurrent(dom, 0)))
            goto cleanup;

        if (vshCommandOptBool(cmd, "name")) {
727 728
            const char *name;
            if (!(name = virDomainSnapshotGetName(snapshot)))
729
                goto cleanup;
730 731

            vshPrint(ctl, "%s", name);
732
        } else {
733
            if (!(xml = virDomainSnapshotGetXMLDesc(snapshot, flags)))
734 735
                goto cleanup;

736 737
            vshPrint(ctl, "%s", xml);
        }
738 739 740 741
    }

    ret = true;

742
 cleanup:
743
    if (!ret)
E
Eric Blake 已提交
744
        vshReportError(ctl);
745 746 747
    VIR_FREE(xml);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
748
    virDomainFree(dom);
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797

    return ret;
}

/* Helper function to get the name of a snapshot's parent.  Caller
 * must free the result.  Returns 0 on success (including when it was
 * proven no parent exists), and -1 on failure with error reported
 * (such as no snapshot support or domain deleted in meantime).  */
static int
vshGetSnapshotParent(vshControl *ctl, virDomainSnapshotPtr snapshot,
                     char **parent_name)
{
    virDomainSnapshotPtr parent = NULL;
    char *xml = NULL;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ret = -1;

    *parent_name = NULL;

    /* Try new API, since it is faster. */
    if (!ctl->useSnapshotOld) {
        parent = virDomainSnapshotGetParent(snapshot, 0);
        if (parent) {
            /* API works, and virDomainSnapshotGetName will succeed */
            *parent_name = vshStrdup(ctl, virDomainSnapshotGetName(parent));
            ret = 0;
            goto cleanup;
        }
        if (last_error->code == VIR_ERR_NO_DOMAIN_SNAPSHOT) {
            /* API works, and we found a root with no parent */
            ret = 0;
            goto cleanup;
        }
        /* API didn't work, fall back to XML scraping. */
        ctl->useSnapshotOld = true;
    }

    xml = virDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!xml)
        goto cleanup;

    xmldoc = virXMLParseStringCtxt(xml, _("(domain_snapshot)"), &ctxt);
    if (!xmldoc)
        goto cleanup;

    *parent_name = virXPathString("string(/domainsnapshot/parent/name)", ctxt);
    ret = 0;

798
 cleanup:
799
    if (ret < 0) {
E
Eric Blake 已提交
800
        vshReportError(ctl);
801 802
        vshError(ctl, "%s", _("unable to determine if snapshot has parent"));
    } else {
803
        vshResetLibvirtError();
804 805 806 807 808 809 810 811 812
    }
    if (parent)
        virDomainSnapshotFree(parent);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xmldoc);
    VIR_FREE(xml);
    return ret;
}

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 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
/* Helper function to filter snapshots according to status and
 * location portion of flags.  Returns 0 if filter excluded snapshot,
 * 1 if snapshot is okay (or if snapshot is already NULL), and -1 on
 * failure, with error already reported.  */
static int
vshSnapshotFilter(vshControl *ctl, virDomainSnapshotPtr snapshot,
                  unsigned int flags)
{
    char *xml = NULL;
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    int ret = -1;
    char *state = NULL;

    if (!snapshot)
        return 1;

    xml = virDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!xml)
        goto cleanup;

    xmldoc = virXMLParseStringCtxt(xml, _("(domain_snapshot)"), &ctxt);
    if (!xmldoc)
        goto cleanup;

    /* Libvirt 1.0.1 and newer never call this function, because the
     * filtering is already supported by the listing functions.  Older
     * libvirt lacked /domainsnapshot/memory, but was also limited in
     * the types of snapshots it could create: if state was disk-only,
     * the snapshot is external; all other snapshots are internal.  */
    state = virXPathString("string(/domainsnapshot/state)", ctxt);
    if (!state) {
        vshError(ctl, "%s", _("unable to perform snapshot filtering"));
        goto cleanup;
    }
    if (STREQ(state, "disk-snapshot")) {
        ret = ((flags & (VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY |
                         VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL)) ==
               (VIR_DOMAIN_SNAPSHOT_LIST_DISK_ONLY |
                VIR_DOMAIN_SNAPSHOT_LIST_EXTERNAL));
    } else {
        if (!(flags & VIR_DOMAIN_SNAPSHOT_LIST_INTERNAL))
            ret = 0;
        else if (STREQ(state, "shutoff"))
            ret = !!(flags & VIR_DOMAIN_SNAPSHOT_LIST_INACTIVE);
        else
            ret = !!(flags & VIR_DOMAIN_SNAPSHOT_LIST_ACTIVE);
    }

862
 cleanup:
863 864 865 866 867 868 869
    VIR_FREE(state);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xmldoc);
    VIR_FREE(xml);
    return ret;
}

870 871 872 873
/*
 * "snapshot-info" command
 */
static const vshCmdInfo info_snapshot_info[] = {
874 875 876 877 878 879 880
    {.name = "help",
     .data = N_("snapshot information")
    },
    {.name = "desc",
     .data = N_("Returns basic information about a snapshot.")
    },
    {.name = NULL}
881 882 883
};

static const vshCmdOptDef opts_snapshot_info[] = {
884 885 886 887 888 889
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "snapshotname",
890
     .type = VSH_OT_STRING,
891 892 893 894 895 896 897
     .help = N_("snapshot name")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("info on current snapshot")
    },
    {.name = NULL}
898 899 900 901 902 903 904 905 906
};

static bool
cmdSnapshotInfo(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom;
    virDomainSnapshotPtr snapshot = NULL;
    const char *name;
    char *doc = NULL;
907 908 909 910
    xmlDocPtr xmldoc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    char *state = NULL;
    int external;
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    char *parent = NULL;
    bool ret = false;
    int count;
    unsigned int flags;
    int current;
    int metadata;

    dom = vshCommandOptDomain(ctl, cmd, NULL);
    if (dom == NULL)
        return false;

    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
        goto cleanup;

    vshPrint(ctl, "%-15s %s\n", _("Name:"), name);
    vshPrint(ctl, "%-15s %s\n", _("Domain:"), virDomainGetName(dom));

    /* Determine if snapshot is current; this is useful enough that we
     * attempt a fallback.  */
    current = virDomainSnapshotIsCurrent(snapshot, 0);
    if (current < 0) {
        virDomainSnapshotPtr other = virDomainSnapshotCurrent(dom, 0);

935
        vshResetLibvirtError();
936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
        current = 0;
        if (other) {
            if (STREQ(name, virDomainSnapshotGetName(other)))
                current = 1;
            virDomainSnapshotFree(other);
        }
    }
    vshPrint(ctl, "%-15s %s\n", _("Current:"),
             current > 0 ? _("yes") : _("no"));

    /* Get the XML configuration of the snapshot to determine the
     * state of the machine at the time of the snapshot.  */
    doc = virDomainSnapshotGetXMLDesc(snapshot, 0);
    if (!doc)
        goto cleanup;

952 953 954 955 956 957
    xmldoc = virXMLParseStringCtxt(doc, _("(domain_snapshot)"), &ctxt);
    if (!xmldoc)
        goto cleanup;

    state = virXPathString("string(/domainsnapshot/state)", ctxt);
    if (!state) {
958 959 960 961
        vshError(ctl, "%s",
                 _("unexpected problem reading snapshot xml"));
        goto cleanup;
    }
962 963 964 965 966 967 968 969 970
    vshPrint(ctl, "%-15s %s\n", _("State:"), state);

    /* In addition to state, location is useful.  If the snapshot has
     * a <memory> element, then the existence of snapshot='external'
     * prior to <domain> is the deciding factor; for snapshots
     * created prior to 1.0.1, a state of disk-only is the only
     * external snapshot.  */
    switch (virXPathBoolean("boolean(/domainsnapshot/memory)", ctxt)) {
    case 1:
971 972
        external = virXPathBoolean("boolean(/domainsnapshot/memory[@snapshot='external'] "
                                   "| /domainsnapshot/disks/disk[@snapshot='external'])",
973 974 975 976 977 978 979 980 981 982 983 984 985
                                   ctxt);
        break;
    case 0:
        external = STREQ(state, "disk-snapshot");
        break;
    default:
        external = -1;
        break;

    }
    if (external < 0) {
        vshError(ctl, "%s",
                 _("unexpected problem reading snapshot xml"));
986
        goto cleanup;
987 988 989 990 991 992 993
    }
    vshPrint(ctl, "%-15s %s\n", _("Location:"),
             external ? _("external") : _("internal"));

    /* Since we already have the XML, there's no need to call
     * virDomainSnapshotGetParent */
    parent = virXPathString("string(/domainsnapshot/parent/name)", ctxt);
994 995 996 997 998 999 1000 1001 1002 1003 1004
    vshPrint(ctl, "%-15s %s\n", _("Parent:"), parent ? parent : "-");

    /* Children, Descendants.  After this point, the fallback to
     * compute children is too expensive, so we gracefully quit if the
     * APIs don't exist.  */
    if (ctl->useSnapshotOld) {
        ret = true;
        goto cleanup;
    }
    flags = 0;
    count = virDomainSnapshotNumChildren(snapshot, flags);
1005 1006 1007 1008 1009
    if (count < 0) {
        if (last_error->code == VIR_ERR_NO_SUPPORT) {
            vshResetLibvirtError();
            ret = true;
        }
1010
        goto cleanup;
1011
    }
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
    vshPrint(ctl, "%-15s %d\n", _("Children:"), count);
    flags = VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
    count = virDomainSnapshotNumChildren(snapshot, flags);
    if (count < 0)
        goto cleanup;
    vshPrint(ctl, "%-15s %d\n", _("Descendants:"), count);

    /* Metadata; the fallback here relies on the fact that metadata
     * used to have an all-or-nothing effect on snapshot count.  */
    metadata = virDomainSnapshotHasMetadata(snapshot, 0);
    if (metadata < 0) {
        metadata = virDomainSnapshotNum(dom,
                                        VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
1025
        vshResetLibvirtError();
1026 1027 1028 1029 1030 1031 1032
    }
    if (metadata >= 0)
        vshPrint(ctl, "%-15s %s\n", _("Metadata:"),
                 metadata ? _("yes") : _("no"));

    ret = true;

1033
 cleanup:
1034 1035 1036
    VIR_FREE(state);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xmldoc);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
    VIR_FREE(doc);
    VIR_FREE(parent);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    virDomainFree(dom);
    return ret;
}

/* Helpers for collecting a list of snapshots.  */
struct vshSnap {
    virDomainSnapshotPtr snap;
    char *parent;
};
struct vshSnapshotList {
    struct vshSnap *snaps;
    int nsnaps;
};
typedef struct vshSnapshotList *vshSnapshotListPtr;

static void
vshSnapshotListFree(vshSnapshotListPtr snaplist)
{
1059
    size_t i;
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

    if (!snaplist)
        return;
    if (snaplist->snaps) {
        for (i = 0; i < snaplist->nsnaps; i++) {
            if (snaplist->snaps[i].snap)
                virDomainSnapshotFree(snaplist->snaps[i].snap);
            VIR_FREE(snaplist->snaps[i].parent);
        }
        VIR_FREE(snaplist->snaps);
    }
    VIR_FREE(snaplist);
}

static int
vshSnapSorter(const void *a, const void *b)
{
    const struct vshSnap *sa = a;
    const struct vshSnap *sb = b;

    if (sa->snap && !sb->snap)
        return -1;
    if (!sa->snap)
        return sb->snap != NULL;

1085 1086
    return vshStrcasecmp(virDomainSnapshotGetName(sa->snap),
                         virDomainSnapshotGetName(sb->snap));
1087 1088 1089 1090 1091 1092 1093 1094 1095
}

/* Compute a list of snapshots from DOM.  If FROM is provided, the
 * list is limited to descendants of the given snapshot.  If FLAGS is
 * given, the list is filtered.  If TREE is specified, then all but
 * FROM or the roots will also have parent information.  */
static vshSnapshotListPtr
vshSnapshotListCollect(vshControl *ctl, virDomainPtr dom,
                       virDomainSnapshotPtr from,
1096
                       unsigned int orig_flags, bool tree)
1097
{
1098
    size_t i;
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    char **names = NULL;
    int count = -1;
    bool descendants = false;
    bool roots = false;
    virDomainSnapshotPtr *snaps;
    vshSnapshotListPtr snaplist = vshMalloc(ctl, sizeof(*snaplist));
    vshSnapshotListPtr ret = NULL;
    const char *fromname = NULL;
    int start_index = -1;
    int deleted = 0;
1109 1110
    bool filter_fallback = false;
    unsigned int flags = orig_flags;
1111 1112 1113 1114 1115 1116 1117

    /* Try the interface available in 0.9.13 and newer.  */
    if (!ctl->useSnapshotOld) {
        if (from)
            count = virDomainSnapshotListAllChildren(from, &snaps, flags);
        else
            count = virDomainListAllSnapshots(dom, &snaps, flags);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
        /* If we failed because of flags added in 1.0.1, we can do
         * fallback filtering. */
        if  (count < 0 && last_error->code == VIR_ERR_INVALID_ARG &&
             flags & (VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS |
                      VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION)) {
            flags &= ~(VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS |
                       VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION);
            vshResetLibvirtError();
            filter_fallback = true;
            if (from)
                count = virDomainSnapshotListAllChildren(from, &snaps, flags);
            else
                count = virDomainListAllSnapshots(dom, &snaps, flags);
        }
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    }
    if (count >= 0) {
        /* When mixing --from and --tree, we also want a copy of from
         * in the list, but with no parent for that one entry.  */
        snaplist->snaps = vshCalloc(ctl, count + (tree && from),
                                    sizeof(*snaplist->snaps));
        snaplist->nsnaps = count;
        for (i = 0; i < count; i++)
            snaplist->snaps[i].snap = snaps[i];
        VIR_FREE(snaps);
        if (tree) {
            for (i = 0; i < count; i++) {
                if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap,
                                         &snaplist->snaps[i].parent) < 0)
                    goto cleanup;
            }
            if (from) {
O
Osier Yang 已提交
1149
                snaplist->snaps[snaplist->nsnaps++].snap = from;
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178
                virDomainSnapshotRef(from);
            }
        }
        goto success;
    }

    /* Assume that if we got this far, then the --no-leaves and
     * --no-metadata flags were not supported.  Disable groups that
     * have no impact.  */
    /* XXX should we emulate --no-leaves?  */
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES &&
        flags & VIR_DOMAIN_SNAPSHOT_LIST_LEAVES)
        flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_LEAVES |
                   VIR_DOMAIN_SNAPSHOT_LIST_LEAVES);
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA &&
        flags & VIR_DOMAIN_SNAPSHOT_LIST_METADATA)
        flags &= ~(VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA |
                   VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
    if (flags & VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA) {
        /* We can emulate --no-metadata if --metadata was supported,
         * since it was an all-or-none attribute on old servers.  */
        count = virDomainSnapshotNum(dom,
                                     VIR_DOMAIN_SNAPSHOT_LIST_METADATA);
        if (count < 0)
            goto cleanup;
        if (count > 0)
            return snaplist;
        flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA;
    }
1179 1180 1181 1182 1183 1184
    if (flags & (VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS |
                 VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION)) {
        flags &= ~(VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS |
                   VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION);
        filter_fallback = true;
    }
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219

    /* This uses the interfaces available in 0.8.0-0.9.6
     * (virDomainSnapshotListNames, global list only) and in
     * 0.9.7-0.9.12 (addition of virDomainSnapshotListChildrenNames
     * for child listing, and new flags), as follows, with [*] by the
     * combinations that need parent info (either for filtering
     * purposes or for the resulting tree listing):
     *                              old               new
     * list                         global as-is      global as-is
     * list --roots                *global + filter   global + flags
     * list --from                 *global + filter   child as-is
     * list --from --descendants   *global + filter   child + flags
     * list --tree                 *global as-is     *global as-is
     * list --tree --from          *global + filter  *child + flags
     *
     * Additionally, when --tree and --from are both used, from is
     * added to the final list as the only element without a parent.
     * Otherwise, --from does not appear in the final list.
     */
    if (from) {
        fromname = virDomainSnapshotGetName(from);
        if (!fromname) {
            vshError(ctl, "%s", _("Could not get snapshot name"));
            goto cleanup;
        }
        descendants = (flags & VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS) || tree;
        if (tree)
            flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;

        /* Determine if we can use the new child listing API.  */
        if (ctl->useSnapshotOld ||
            ((count = virDomainSnapshotNumChildren(from, flags)) < 0 &&
             last_error->code == VIR_ERR_NO_SUPPORT)) {
            /* We can emulate --from.  */
            /* XXX can we also emulate --leaves? */
1220
            vshResetLibvirtError();
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
            ctl->useSnapshotOld = true;
            flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
            goto global;
        }
        if (tree && count >= 0)
            count++;
    } else {
    global:
        /* Global listing (including fallback when --from failed with
         * child listing).  */
        count = virDomainSnapshotNum(dom, flags);

        /* Fall back to simulation if --roots was unsupported. */
        /* XXX can we also emulate --leaves? */
        if (!from && count < 0 && last_error->code == VIR_ERR_INVALID_ARG &&
            (flags & VIR_DOMAIN_SNAPSHOT_LIST_ROOTS)) {
1237
            vshResetLibvirtError();
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 1316 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
            roots = true;
            flags &= ~VIR_DOMAIN_SNAPSHOT_LIST_ROOTS;
            count = virDomainSnapshotNum(dom, flags);
        }
    }

    if (count < 0) {
        if (!last_error)
            vshError(ctl, _("failed to collect snapshot list"));
        goto cleanup;
    }

    if (!count)
        goto success;

    names = vshCalloc(ctl, sizeof(*names), count);

    /* Now that we have a count, collect the list.  */
    if (from && !ctl->useSnapshotOld) {
        if (tree) {
            if (count)
                count = virDomainSnapshotListChildrenNames(from, names + 1,
                                                           count - 1, flags);
            if (count >= 0) {
                count++;
                names[0] = vshStrdup(ctl, fromname);
            }
        } else {
            count = virDomainSnapshotListChildrenNames(from, names,
                                                       count, flags);
        }
    } else {
        count = virDomainSnapshotListNames(dom, names, count, flags);
    }
    if (count < 0)
        goto cleanup;

    snaplist->snaps = vshCalloc(ctl, sizeof(*snaplist->snaps), count);
    snaplist->nsnaps = count;
    for (i = 0; i < count; i++) {
        snaplist->snaps[i].snap = virDomainSnapshotLookupByName(dom,
                                                                names[i], 0);
        if (!snaplist->snaps[i].snap)
            goto cleanup;
    }

    /* Collect parents when needed.  With the new API, --tree and
     * --from together put from as the first element without a parent;
     * with the old API we still need to do a post-process filtering
     * based on all parent information.  */
    if (tree || (from && ctl->useSnapshotOld) || roots) {
        for (i = (from && !ctl->useSnapshotOld); i < count; i++) {
            if (from && ctl->useSnapshotOld && STREQ(names[i], fromname)) {
                start_index = i;
                if (tree)
                    continue;
            }
            if (vshGetSnapshotParent(ctl, snaplist->snaps[i].snap,
                                     &snaplist->snaps[i].parent) < 0)
                goto cleanup;
            if ((from && ((tree && !snaplist->snaps[i].parent) ||
                          (!descendants &&
                           STRNEQ_NULLABLE(fromname,
                                           snaplist->snaps[i].parent)))) ||
                (roots && snaplist->snaps[i].parent)) {
                virDomainSnapshotFree(snaplist->snaps[i].snap);
                snaplist->snaps[i].snap = NULL;
                VIR_FREE(snaplist->snaps[i].parent);
                deleted++;
            }
        }
    }
    if (tree)
        goto success;

    if (ctl->useSnapshotOld && descendants) {
        bool changed = false;
        bool remaining = false;

        /* Make multiple passes over the list - first pass finds
         * direct children and NULLs out all roots and from, remaining
         * passes NULL out any undecided entry whose parent is not
         * still in list.  We mark known descendants by clearing
         * snaps[i].parents.  Sorry, this is O(n^3) - hope your
         * hierarchy isn't huge.  XXX Is it worth making O(n^2 log n)
         * by using qsort and bsearch?  */
        if (start_index < 0) {
            vshError(ctl, _("snapshot %s disappeared from list"), fromname);
            goto cleanup;
        }
        for (i = 0; i < count; i++) {
            if (i == start_index || !snaplist->snaps[i].parent) {
                VIR_FREE(names[i]);
                virDomainSnapshotFree(snaplist->snaps[i].snap);
                snaplist->snaps[i].snap = NULL;
                VIR_FREE(snaplist->snaps[i].parent);
                deleted++;
            } else if (STREQ(snaplist->snaps[i].parent, fromname)) {
                VIR_FREE(snaplist->snaps[i].parent);
                changed = true;
            } else {
                remaining = true;
            }
        }
        if (!changed) {
            ret = vshMalloc(ctl, sizeof(*snaplist));
            goto cleanup;
        }
        while (changed && remaining) {
            changed = remaining = false;
            for (i = 0; i < count; i++) {
                bool found_parent = false;
1350
                size_t j;
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377

                if (!names[i] || !snaplist->snaps[i].parent)
                    continue;
                for (j = 0; j < count; j++) {
                    if (!names[j] || i == j)
                        continue;
                    if (STREQ(snaplist->snaps[i].parent, names[j])) {
                        found_parent = true;
                        if (!snaplist->snaps[j].parent)
                            VIR_FREE(snaplist->snaps[i].parent);
                        else
                            remaining = true;
                        break;
                    }
                }
                if (!found_parent) {
                    changed = true;
                    VIR_FREE(names[i]);
                    virDomainSnapshotFree(snaplist->snaps[i].snap);
                    snaplist->snaps[i].snap = NULL;
                    VIR_FREE(snaplist->snaps[i].parent);
                    deleted++;
                }
            }
        }
    }

1378
 success:
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    if (filter_fallback) {
        /* Older API didn't filter on status or location, but the
         * information is available in domain XML.  */
        if (!(orig_flags & VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS))
            orig_flags |= VIR_DOMAIN_SNAPSHOT_FILTERS_STATUS;
        if (!(orig_flags & VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION))
            orig_flags |= VIR_DOMAIN_SNAPSHOT_FILTERS_LOCATION;
        for (i = 0; i < snaplist->nsnaps; i++) {
            switch (vshSnapshotFilter(ctl, snaplist->snaps[i].snap,
                                      orig_flags)) {
            case 1:
                break;
            case 0:
                virDomainSnapshotFree(snaplist->snaps[i].snap);
                snaplist->snaps[i].snap = NULL;
                VIR_FREE(snaplist->snaps[i].parent);
                deleted++;
                break;
            default:
                goto cleanup;
            }
        }
    }
1402 1403 1404 1405 1406 1407 1408
    qsort(snaplist->snaps, snaplist->nsnaps, sizeof(*snaplist->snaps),
          vshSnapSorter);
    snaplist->nsnaps -= deleted;

    ret = snaplist;
    snaplist = NULL;

1409
 cleanup:
1410
    vshSnapshotListFree(snaplist);
1411
    if (names && count > 0)
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
        for (i = 0; i < count; i++)
            VIR_FREE(names[i]);
    VIR_FREE(names);
    return ret;
}

static const char *
vshSnapshotListLookup(int id, bool parent, void *opaque)
{
    vshSnapshotListPtr snaplist = opaque;
    if (parent)
        return snaplist->snaps[id].parent;
    return virDomainSnapshotGetName(snaplist->snaps[id].snap);
}

/*
 * "snapshot-list" command
 */
static const vshCmdInfo info_snapshot_list[] = {
1431 1432 1433 1434 1435 1436 1437
    {.name = "help",
     .data = N_("List snapshots for a domain")
    },
    {.name = "desc",
     .data = N_("Snapshot List")
    },
    {.name = NULL}
1438 1439 1440
};

static const vshCmdOptDef opts_snapshot_list[] = {
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "parent",
     .type = VSH_OT_BOOL,
     .help = N_("add a column showing parent snapshot")
    },
    {.name = "roots",
     .type = VSH_OT_BOOL,
     .help = N_("list only snapshots without parents")
    },
    {.name = "leaves",
     .type = VSH_OT_BOOL,
     .help = N_("list only snapshots without children")
    },
    {.name = "no-leaves",
     .type = VSH_OT_BOOL,
     .help = N_("list only snapshots that are not leaves (with children)")
    },
    {.name = "metadata",
     .type = VSH_OT_BOOL,
     .help = N_("list only snapshots that have metadata that would prevent undefine")
    },
    {.name = "no-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("list only snapshots that have no metadata managed by libvirt")
    },
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("filter by snapshots taken while inactive")
    },
    {.name = "active",
     .type = VSH_OT_BOOL,
     .help = N_("filter by snapshots taken while active (system checkpoints)")
    },
    {.name = "disk-only",
     .type = VSH_OT_BOOL,
     .help = N_("filter by disk-only snapshots")
    },
    {.name = "internal",
     .type = VSH_OT_BOOL,
     .help = N_("filter by internal snapshots")
    },
    {.name = "external",
     .type = VSH_OT_BOOL,
     .help = N_("filter by external snapshots")
    },
    {.name = "tree",
     .type = VSH_OT_BOOL,
     .help = N_("list snapshots in a tree")
    },
    {.name = "from",
1495
     .type = VSH_OT_STRING,
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
     .help = N_("limit list to children of given snapshot")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("limit list to children of current snapshot")
    },
    {.name = "descendants",
     .type = VSH_OT_BOOL,
     .help = N_("with --from, list all descendants")
    },
1506 1507 1508 1509 1510
    {.name = "name",
     .type = VSH_OT_BOOL,
     .help = N_("list snapshot names only")
    },

1511
    {.name = NULL}
1512 1513 1514 1515 1516 1517 1518 1519
};

static bool
cmdSnapshotList(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    unsigned int flags = 0;
1520
    size_t i;
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    char *doc = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char *state = NULL;
    long long creation_longlong;
    time_t creation_time_t;
    char timestr[100];
    struct tm time_info;
    bool tree = vshCommandOptBool(cmd, "tree");
1531
    bool name = vshCommandOptBool(cmd, "name");
1532 1533 1534 1535 1536 1537
    bool from = vshCommandOptBool(cmd, "from");
    bool parent = vshCommandOptBool(cmd, "parent");
    bool roots = vshCommandOptBool(cmd, "roots");
    bool current = vshCommandOptBool(cmd, "current");
    const char *from_snap = NULL;
    char *parent_snap = NULL;
1538 1539 1540
    virDomainSnapshotPtr start = NULL;
    vshSnapshotListPtr snaplist = NULL;

1541 1542 1543 1544 1545 1546
    VSH_EXCLUSIVE_OPTIONS_VAR(tree, name);
    VSH_EXCLUSIVE_OPTIONS_VAR(parent, roots);
    VSH_EXCLUSIVE_OPTIONS_VAR(parent, tree);
    VSH_EXCLUSIVE_OPTIONS_VAR(roots, tree);
    VSH_EXCLUSIVE_OPTIONS_VAR(roots, from);
    VSH_EXCLUSIVE_OPTIONS_VAR(roots, current);
1547

1548 1549 1550 1551 1552 1553 1554
#define FILTER(option, flag)                                          \
    do {                                                              \
        if (vshCommandOptBool(cmd, option)) {                         \
            if (tree) {                                               \
                vshError(ctl,                                         \
                         _("--%s and --tree are mutually exclusive"), \
                         option);                                     \
1555
                return false;                                         \
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
            }                                                         \
            flags |= VIR_DOMAIN_SNAPSHOT_LIST_ ## flag;               \
        }                                                             \
    } while (0)

    FILTER("leaves", LEAVES);
    FILTER("no-leaves", NO_LEAVES);
    FILTER("inactive", INACTIVE);
    FILTER("active", ACTIVE);
    FILTER("disk-only", DISK_ONLY);
    FILTER("internal", INTERNAL);
    FILTER("external", EXTERNAL);
#undef FILTER
1569

1570 1571 1572 1573
    if (roots)
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_ROOTS;

    if (vshCommandOptBool(cmd, "metadata"))
1574
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_METADATA;
1575 1576

    if (vshCommandOptBool(cmd, "no-metadata"))
1577 1578 1579
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_NO_METADATA;

    if (vshCommandOptBool(cmd, "descendants")) {
1580
        if (!from && !current) {
1581 1582
            vshError(ctl, "%s",
                     _("--descendants requires either --from or --current"));
1583
            return false;
1584 1585 1586 1587
        }
        flags |= VIR_DOMAIN_SNAPSHOT_LIST_DESCENDANTS;
    }

1588 1589 1590 1591 1592 1593 1594 1595
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;

    if ((from || current) &&
        vshLookupSnapshot(ctl, cmd, "from", true, dom, &start, &from_snap) < 0)
        goto cleanup;

    if (!(snaplist = vshSnapshotListCollect(ctl, dom, start, flags, tree)))
1596 1597
        goto cleanup;

1598
    if (!tree && !name) {
1599
        if (parent)
1600 1601 1602 1603 1604 1605 1606
            vshPrintExtra(ctl, " %-20s %-25s %-15s %s",
                          _("Name"), _("Creation Time"), _("State"),
                          _("Parent"));
        else
            vshPrintExtra(ctl, " %-20s %-25s %s",
                          _("Name"), _("Creation Time"), _("State"));
        vshPrintExtra(ctl, "\n"
1607 1608
                           "------------------------------"
                           "------------------------------\n");
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
    }

    if (tree) {
        for (i = 0; i < snaplist->nsnaps; i++) {
            if (!snaplist->snaps[i].parent &&
                vshTreePrint(ctl, vshSnapshotListLookup, snaplist,
                             snaplist->nsnaps, i) < 0)
                goto cleanup;
        }
        ret = true;
        goto cleanup;
    }

    for (i = 0; i < snaplist->nsnaps; i++) {
1623
        const char *snap_name;
1624 1625

        /* free up memory from previous iterations of the loop */
1626
        VIR_FREE(parent_snap);
1627 1628 1629 1630 1631 1632
        VIR_FREE(state);
        xmlXPathFreeContext(ctxt);
        xmlFreeDoc(xml);
        VIR_FREE(doc);

        snapshot = snaplist->snaps[i].snap;
1633 1634 1635 1636
        snap_name = virDomainSnapshotGetName(snapshot);
        assert(snap_name);

        if (name) {
1637
            /* just print the snapshot name */
1638 1639 1640
            vshPrint(ctl, "%s\n", snap_name);
            continue;
        }
1641

1642
        if (!(doc = virDomainSnapshotGetXMLDesc(snapshot, 0)))
1643 1644
            continue;

1645
        if (!(xml = virXMLParseStringCtxt(doc, _("(domain_snapshot)"), &ctxt)))
1646 1647
            continue;

1648 1649 1650
        if (parent)
            parent_snap = virXPathString("string(/domainsnapshot/parent/name)",
                                         ctxt);
1651

1652
        if (!(state = virXPathString("string(/domainsnapshot/state)", ctxt)))
1653
            continue;
1654

1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
        if (virXPathLongLong("string(/domainsnapshot/creationTime)", ctxt,
                             &creation_longlong) < 0)
            continue;
        creation_time_t = creation_longlong;
        if (creation_time_t != creation_longlong) {
            vshError(ctl, "%s", _("time_t overflow"));
            continue;
        }
        localtime_r(&creation_time_t, &time_info);
        strftime(timestr, sizeof(timestr), "%Y-%m-%d %H:%M:%S %z",
                 &time_info);

        if (parent)
            vshPrint(ctl, " %-20s %-25s %-15s %s\n",
1669
                     snap_name, timestr, state, parent_snap);
1670
        else
1671
            vshPrint(ctl, " %-20s %-25s %s\n", snap_name, timestr, state);
1672 1673 1674 1675
    }

    ret = true;

1676
 cleanup:
1677 1678
    /* this frees up memory from the last iteration of the loop */
    vshSnapshotListFree(snaplist);
1679
    VIR_FREE(parent_snap);
1680
    VIR_FREE(state);
1681 1682
    if (start)
        virDomainSnapshotFree(start);
1683 1684 1685
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    VIR_FREE(doc);
1686
    virDomainFree(dom);
1687 1688 1689 1690 1691 1692 1693 1694

    return ret;
}

/*
 * "snapshot-dumpxml" command
 */
static const vshCmdInfo info_snapshot_dumpxml[] = {
1695 1696 1697 1698 1699 1700 1701
    {.name = "help",
     .data = N_("Dump XML for a domain snapshot")
    },
    {.name = "desc",
     .data = N_("Snapshot Dump XML")
    },
    {.name = NULL}
1702 1703 1704
};

static const vshCmdOptDef opts_snapshot_dumpxml[] = {
1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "snapshotname",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("snapshot name")
    },
    {.name = "security-info",
     .type = VSH_OT_BOOL,
     .help = N_("include security sensitive information in XML dump")
    },
    {.name = NULL}
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
};

static bool
cmdSnapshotDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    const char *name = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char *xml = NULL;
    unsigned int flags = 0;

    if (vshCommandOptBool(cmd, "security-info"))
        flags |= VIR_DOMAIN_XML_SECURE;

1735 1736
    if (vshCommandOptStringReq(ctl, cmd, "snapshotname", &name) < 0)
        return false;
1737

1738 1739
    if (!(dom = vshCommandOptDomain(ctl, cmd, NULL)))
        return false;
1740

1741
    if (!(snapshot = virDomainSnapshotLookupByName(dom, name, 0)))
1742 1743
        goto cleanup;

1744
    if (!(xml = virDomainSnapshotGetXMLDesc(snapshot, flags)))
1745 1746 1747 1748 1749
        goto cleanup;

    vshPrint(ctl, "%s", xml);
    ret = true;

1750
 cleanup:
1751 1752 1753
    VIR_FREE(xml);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
1754
    virDomainFree(dom);
1755 1756 1757 1758 1759 1760 1761 1762

    return ret;
}

/*
 * "snapshot-parent" command
 */
static const vshCmdInfo info_snapshot_parent[] = {
1763 1764 1765 1766 1767 1768 1769
    {.name = "help",
     .data = N_("Get the name of the parent of a snapshot")
    },
    {.name = "desc",
     .data = N_("Extract the snapshot's parent, if any")
    },
    {.name = NULL}
1770 1771 1772
};

static const vshCmdOptDef opts_snapshot_parent[] = {
1773 1774 1775 1776 1777 1778
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "snapshotname",
1779
     .type = VSH_OT_STRING,
1780 1781 1782 1783 1784 1785 1786
     .help = N_("find parent of snapshot name")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("find parent of current snapshot")
    },
    {.name = NULL}
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816
};

static bool
cmdSnapshotParent(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    const char *name = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    char *parent = NULL;

    dom = vshCommandOptDomain(ctl, cmd, NULL);
    if (dom == NULL)
        goto cleanup;

    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
        goto cleanup;

    if (vshGetSnapshotParent(ctl, snapshot, &parent) < 0)
        goto cleanup;
    if (!parent) {
        vshError(ctl, _("snapshot '%s' has no parent"), name);
        goto cleanup;
    }

    vshPrint(ctl, "%s", parent);

    ret = true;

1817
 cleanup:
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
    VIR_FREE(parent);
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

/*
 * "snapshot-revert" command
 */
static const vshCmdInfo info_snapshot_revert[] = {
1831 1832 1833 1834 1835 1836 1837
    {.name = "help",
     .data = N_("Revert a domain to a snapshot")
    },
    {.name = "desc",
     .data = N_("Revert domain to snapshot")
    },
    {.name = NULL}
1838 1839 1840
};

static const vshCmdOptDef opts_snapshot_revert[] = {
1841 1842 1843 1844 1845 1846
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "snapshotname",
1847
     .type = VSH_OT_STRING,
1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866
     .help = N_("snapshot name")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("revert to current snapshot")
    },
    {.name = "running",
     .type = VSH_OT_BOOL,
     .help = N_("after reverting, change state to running")
    },
    {.name = "paused",
     .type = VSH_OT_BOOL,
     .help = N_("after reverting, change state to paused")
    },
    {.name = "force",
     .type = VSH_OT_BOOL,
     .help = N_("try harder on risky reverts")
    },
    {.name = NULL}
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
};

static bool
cmdDomainSnapshotRevert(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    const char *name = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    unsigned int flags = 0;
    bool force = false;
    int result;

    if (vshCommandOptBool(cmd, "running"))
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_RUNNING;
    if (vshCommandOptBool(cmd, "paused"))
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_PAUSED;
    /* We want virsh snapshot-revert --force to work even when talking
     * to older servers that did the unsafe revert by default but
     * reject the flag, so we probe without the flag, and only use it
     * when the error says it will make a difference.  */
    if (vshCommandOptBool(cmd, "force"))
        force = true;

    dom = vshCommandOptDomain(ctl, cmd, NULL);
    if (dom == NULL)
        goto cleanup;

    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
        goto cleanup;

    result = virDomainRevertToSnapshot(snapshot, flags);
    if (result < 0 && force &&
        last_error->code == VIR_ERR_SNAPSHOT_REVERT_RISKY) {
        flags |= VIR_DOMAIN_SNAPSHOT_REVERT_FORCE;
1903
        vshResetLibvirtError();
1904 1905 1906 1907 1908 1909 1910
        result = virDomainRevertToSnapshot(snapshot, flags);
    }
    if (result < 0)
        goto cleanup;

    ret = true;

1911
 cleanup:
1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}

/*
 * "snapshot-delete" command
 */
static const vshCmdInfo info_snapshot_delete[] = {
1924 1925 1926 1927 1928 1929 1930
    {.name = "help",
     .data = N_("Delete a domain snapshot")
    },
    {.name = "desc",
     .data = N_("Snapshot Delete")
    },
    {.name = NULL}
1931 1932 1933
};

static const vshCmdOptDef opts_snapshot_delete[] = {
1934 1935 1936 1937 1938 1939
    {.name = "domain",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("domain name, id or uuid")
    },
    {.name = "snapshotname",
1940
     .type = VSH_OT_STRING,
1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959
     .help = N_("snapshot name")
    },
    {.name = "current",
     .type = VSH_OT_BOOL,
     .help = N_("delete current snapshot")
    },
    {.name = "children",
     .type = VSH_OT_BOOL,
     .help = N_("delete snapshot and all children")
    },
    {.name = "children-only",
     .type = VSH_OT_BOOL,
     .help = N_("delete children but not snapshot")
    },
    {.name = "metadata",
     .type = VSH_OT_BOOL,
     .help = N_("delete only libvirt metadata, leaving snapshot contents behind")
    },
    {.name = NULL}
1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
};

static bool
cmdSnapshotDelete(vshControl *ctl, const vshCmd *cmd)
{
    virDomainPtr dom = NULL;
    bool ret = false;
    const char *name = NULL;
    virDomainSnapshotPtr snapshot = NULL;
    unsigned int flags = 0;

    dom = vshCommandOptDomain(ctl, cmd, NULL);
    if (dom == NULL)
        goto cleanup;

    if (vshLookupSnapshot(ctl, cmd, "snapshotname", true, dom,
                          &snapshot, &name) < 0)
        goto cleanup;

    if (vshCommandOptBool(cmd, "children"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN;
    if (vshCommandOptBool(cmd, "children-only"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY;
    if (vshCommandOptBool(cmd, "metadata"))
        flags |= VIR_DOMAIN_SNAPSHOT_DELETE_METADATA_ONLY;

    /* XXX If we wanted, we could emulate DELETE_CHILDREN_ONLY even on
     * older servers that reject the flag, by manually computing the
     * list of descendants.  But that's a lot of code to maintain.  */
    if (virDomainSnapshotDelete(snapshot, flags) == 0) {
        if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY)
            vshPrint(ctl, _("Domain snapshot %s children deleted\n"), name);
        else
            vshPrint(ctl, _("Domain snapshot %s deleted\n"), name);
    } else {
        vshError(ctl, _("Failed to delete snapshot %s"), name);
        goto cleanup;
    }

    ret = true;

2001
 cleanup:
2002 2003 2004 2005 2006 2007 2008
    if (snapshot)
        virDomainSnapshotFree(snapshot);
    if (dom)
        virDomainFree(dom);

    return ret;
}
2009

E
Eric Blake 已提交
2010
const vshCmdDef snapshotCmds[] = {
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    {.name = "snapshot-create",
     .handler = cmdSnapshotCreate,
     .opts = opts_snapshot_create,
     .info = info_snapshot_create,
     .flags = 0
    },
    {.name = "snapshot-create-as",
     .handler = cmdSnapshotCreateAs,
     .opts = opts_snapshot_create_as,
     .info = info_snapshot_create_as,
     .flags = 0
    },
    {.name = "snapshot-current",
     .handler = cmdSnapshotCurrent,
     .opts = opts_snapshot_current,
     .info = info_snapshot_current,
     .flags = 0
    },
    {.name = "snapshot-delete",
     .handler = cmdSnapshotDelete,
     .opts = opts_snapshot_delete,
     .info = info_snapshot_delete,
     .flags = 0
    },
    {.name = "snapshot-dumpxml",
     .handler = cmdSnapshotDumpXML,
     .opts = opts_snapshot_dumpxml,
     .info = info_snapshot_dumpxml,
     .flags = 0
    },
    {.name = "snapshot-edit",
     .handler = cmdSnapshotEdit,
     .opts = opts_snapshot_edit,
     .info = info_snapshot_edit,
     .flags = 0
    },
    {.name = "snapshot-info",
     .handler = cmdSnapshotInfo,
     .opts = opts_snapshot_info,
     .info = info_snapshot_info,
     .flags = 0
    },
    {.name = "snapshot-list",
     .handler = cmdSnapshotList,
     .opts = opts_snapshot_list,
     .info = info_snapshot_list,
     .flags = 0
    },
    {.name = "snapshot-parent",
     .handler = cmdSnapshotParent,
     .opts = opts_snapshot_parent,
     .info = info_snapshot_parent,
     .flags = 0
    },
    {.name = "snapshot-revert",
     .handler = cmdDomainSnapshotRevert,
     .opts = opts_snapshot_revert,
     .info = info_snapshot_revert,
     .flags = 0
    },
    {.name = NULL}
2072
};