virsh-volume.c 50.0 KB
Newer Older
1 2 3
/*
 * virsh-volume.c: Commands to manage storage volume
 *
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
#include <config.h>
#include "virsh-volume.h"
28

E
Eric Blake 已提交
29 30 31 32 33 34 35 36
#include <fcntl.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 "virutil.h"
E
Eric Blake 已提交
40 41
#include "virfile.h"
#include "virsh-pool.h"
42
#include "virxml.h"
43
#include "virstring.h"
E
Eric Blake 已提交
44 45

virStorageVolPtr
46 47 48
vshCommandOptVolBy(vshControl *ctl, const vshCmd *cmd,
                   const char *optname,
                   const char *pooloptname,
E
Eric Blake 已提交
49
                   const char **name, unsigned int flags)
50 51 52 53
{
    virStorageVolPtr vol = NULL;
    virStoragePoolPtr pool = NULL;
    const char *n = NULL, *p = NULL;
E
Eric Blake 已提交
54
    virCheckFlags(VSH_BYUUID | VSH_BYNAME, NULL);
55

56
    if (vshCommandOptStringReq(ctl, cmd, optname, &n) < 0)
57 58
        return NULL;

59 60
    if (pooloptname != NULL &&
        vshCommandOptStringReq(ctl, cmd, pooloptname, &p) < 0)
61 62
        return NULL;

63 64 65 66 67 68 69 70 71 72
    if (p) {
        if (!(pool = vshCommandOptPoolBy(ctl, cmd, pooloptname, name, flags)))
            return NULL;

        if (virStoragePoolIsActive(pool) != 1) {
            vshError(ctl, _("pool '%s' is not active"), p);
            virStoragePoolFree(pool);
            return NULL;
        }
    }
73 74 75 76 77 78 79 80

    vshDebug(ctl, VSH_ERR_DEBUG, "%s: found option <%s>: %s\n",
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by name */
E
Eric Blake 已提交
81
    if (pool && (flags & VSH_BYNAME)) {
82 83 84 85 86
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as vol name\n",
                 cmd->def->name, optname);
        vol = virStorageVolLookupByName(pool, n);
    }
    /* try it by key */
E
Eric Blake 已提交
87
    if (!vol && (flags & VSH_BYUUID)) {
88 89 90 91 92
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as vol key\n",
                 cmd->def->name, optname);
        vol = virStorageVolLookupByKey(ctl->conn, n);
    }
    /* try it by path */
E
Eric Blake 已提交
93
    if (!vol && (flags & VSH_BYUUID)) {
94 95 96 97 98 99
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as vol path\n",
                 cmd->def->name, optname);
        vol = virStorageVolLookupByPath(ctl->conn, n);
    }

    if (!vol) {
100
        if (pool || !pooloptname)
101 102 103 104 105 106
            vshError(ctl, _("failed to get vol '%s'"), n);
        else
            vshError(ctl, _("failed to get vol '%s', specifying --%s "
                            "might help"), n, pooloptname);
    }

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
    /* If the pool was specified, then make sure that the returned
     * volume is from the given pool */
    if (pool && vol) {
        virStoragePoolPtr volpool = NULL;

        if ((volpool = virStoragePoolLookupByVolume(vol))) {
            if (STRNEQ(virStoragePoolGetName(volpool),
                       virStoragePoolGetName(pool))) {
                vshResetLibvirtError();
                vshError(ctl,
                         _("Requested volume '%s' is not in pool '%s'"),
                         n, virStoragePoolGetName(pool));
                virStorageVolFree(vol);
                vol = NULL;
            }
            virStoragePoolFree(volpool);
        }
    }

126 127 128 129 130 131 132 133 134 135
    if (pool)
        virStoragePoolFree(pool);

    return vol;
}

/*
 * "vol-create-as" command
 */
static const vshCmdInfo info_vol_create_as[] = {
136 137 138 139 140 141 142
    {.name = "help",
     .data = N_("create a volume from a set of args")
    },
    {.name = "desc",
     .data = N_("Create a vol.")
    },
    {.name = NULL}
143 144 145
};

static const vshCmdOptDef opts_vol_create_as[] = {
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 172 173 174 175 176 177 178 179 180 181
    {.name = "pool",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("pool name")
    },
    {.name = "name",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("name of the volume")
    },
    {.name = "capacity",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("size of the vol, as scaled integer (default bytes)")
    },
    {.name = "allocation",
     .type = VSH_OT_STRING,
     .help = N_("initial allocation size, as scaled integer (default bytes)")
    },
    {.name = "format",
     .type = VSH_OT_STRING,
     .help = N_("file format type raw,bochs,qcow,qcow2,qed,vmdk")
    },
    {.name = "backing-vol",
     .type = VSH_OT_STRING,
     .help = N_("the backing volume if taking a snapshot")
    },
    {.name = "backing-vol-format",
     .type = VSH_OT_STRING,
     .help = N_("format of backing volume if taking a snapshot")
    },
    {.name = "prealloc-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("preallocate metadata (for qcow2 instead of full allocation)")
    },
    {.name = NULL}
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
};

static int
vshVolSize(const char *data, unsigned long long *val)
{
    char *end;
    if (virStrToLong_ull(data, &end, 10, val) < 0)
        return -1;
    return virScaleInteger(val, end, 1, ULLONG_MAX);
}

static bool
cmdVolCreateAs(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
    char *xml;
    const char *name, *capacityStr = NULL, *allocationStr = NULL, *format = NULL;
    const char *snapshotStrVol = NULL, *snapshotStrFormat = NULL;
    unsigned long long capacity, allocation = 0;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
203
    unsigned long flags = 0;
204

205 206
    if (vshCommandOptBool(cmd, "prealloc-metadata"))
        flags |= VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA;
207

208
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
209 210
        return false;

211
    if (vshCommandOptStringReq(ctl, cmd, "name", &name) < 0)
212 213
        goto cleanup;

214
    if (vshCommandOptStringReq(ctl, cmd, "capacity", &capacityStr) < 0)
215 216 217 218 219 220 221 222 223 224 225 226 227
        goto cleanup;

    if (vshVolSize(capacityStr, &capacity) < 0) {
        vshError(ctl, _("Malformed size %s"), capacityStr);
        goto cleanup;
    }

    if (vshCommandOptString(cmd, "allocation", &allocationStr) > 0 &&
        vshVolSize(allocationStr, &allocation) < 0) {
        vshError(ctl, _("Malformed size %s"), allocationStr);
        goto cleanup;
    }

228 229 230 231
    if (vshCommandOptStringReq(ctl, cmd, "format", &format) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "backing-vol", &snapshotStrVol) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "backing-vol-format",
                               &snapshotStrFormat) < 0)
232 233 234
        goto cleanup;

    virBufferAddLit(&buf, "<volume>\n");
235 236 237
    virBufferAdjustIndent(&buf, 2);
    virBufferAsprintf(&buf, "<name>%s</name>\n", name);
    virBufferAsprintf(&buf, "<capacity>%llu</capacity>\n", capacity);
238
    if (allocationStr)
239
        virBufferAsprintf(&buf, "<allocation>%llu</allocation>\n", allocation);
240 241

    if (format) {
242 243 244 245 246
        virBufferAddLit(&buf, "<target>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<format type='%s'/>\n", format);
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</target>\n");
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    }

    /* Convert the snapshot parameters into backingStore XML */
    if (snapshotStrVol) {
        /* Lookup snapshot backing volume.  Try the backing-vol
         *  parameter as a name */
        vshDebug(ctl, VSH_ERR_DEBUG,
                 "%s: Look up backing store volume '%s' as name\n",
                 cmd->def->name, snapshotStrVol);
        virStorageVolPtr snapVol = virStorageVolLookupByName(pool, snapshotStrVol);
        if (snapVol)
                vshDebug(ctl, VSH_ERR_DEBUG,
                         "%s: Backing store volume found using '%s' as name\n",
                         cmd->def->name, snapshotStrVol);

        if (snapVol == NULL) {
            /* Snapshot backing volume not found by name.  Try the
             *  backing-vol parameter as a key */
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: Look up backing store volume '%s' as key\n",
                     cmd->def->name, snapshotStrVol);
            snapVol = virStorageVolLookupByKey(ctl->conn, snapshotStrVol);
            if (snapVol)
                vshDebug(ctl, VSH_ERR_DEBUG,
                         "%s: Backing store volume found using '%s' as key\n",
                         cmd->def->name, snapshotStrVol);
        }
        if (snapVol == NULL) {
            /* Snapshot backing volume not found by key.  Try the
             *  backing-vol parameter as a path */
            vshDebug(ctl, VSH_ERR_DEBUG,
                     "%s: Look up backing store volume '%s' as path\n",
                     cmd->def->name, snapshotStrVol);
            snapVol = virStorageVolLookupByPath(ctl->conn, snapshotStrVol);
            if (snapVol)
                vshDebug(ctl, VSH_ERR_DEBUG,
                         "%s: Backing store volume found using '%s' as path\n",
                         cmd->def->name, snapshotStrVol);
        }
        if (snapVol == NULL) {
            vshError(ctl, _("failed to get vol '%s'"), snapshotStrVol);
            goto cleanup;
        }

        char *snapshotStrVolPath;
        if ((snapshotStrVolPath = virStorageVolGetPath(snapVol)) == NULL) {
            virStorageVolFree(snapVol);
            goto cleanup;
        }

        /* Create XML for the backing store */
298 299 300
        virBufferAddLit(&buf, "<backingStore>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<path>%s</path>\n", snapshotStrVolPath);
301
        if (snapshotStrFormat)
302
            virBufferAsprintf(&buf, "<format type='%s'/>\n",
303
                              snapshotStrFormat);
304 305
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</backingStore>\n");
306 307 308 309 310 311

        /* Cleanup snapshot allocations */
        VIR_FREE(snapshotStrVolPath);
        virStorageVolFree(snapVol);
    }

312
    virBufferAdjustIndent(&buf, -2);
313 314 315 316 317 318 319
    virBufferAddLit(&buf, "</volume>\n");

    if (virBufferError(&buf)) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        goto cleanup;
    }
    xml = virBufferContentAndReset(&buf);
320
    vol = virStorageVolCreateXML(pool, xml, flags);
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
    VIR_FREE(xml);
    virStoragePoolFree(pool);

    if (vol != NULL) {
        vshPrint(ctl, _("Vol %s created\n"), name);
        virStorageVolFree(vol);
        return true;
    } else {
        vshError(ctl, _("Failed to create vol %s"), name);
        return false;
    }

 cleanup:
    virBufferFreeAndReset(&buf);
    virStoragePoolFree(pool);
    return false;
}

/*
 * "vol-create" command
 */
static const vshCmdInfo info_vol_create[] = {
343 344 345 346 347 348 349
    {.name = "help",
     .data = N_("create a vol from an XML file")
    },
    {.name = "desc",
     .data = N_("Create a vol.")
    },
    {.name = NULL}
350 351 352
};

static const vshCmdOptDef opts_vol_create[] = {
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
    {.name = "pool",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("pool name")
    },
    {.name = "file",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("file containing an XML vol description")
    },
    {.name = "prealloc-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("preallocate metadata (for qcow2 instead of full allocation)")
    },
    {.name = NULL}
368 369 370 371 372 373 374 375
};

static bool
cmdVolCreate(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
    const char *from = NULL;
376
    bool ret = false;
377
    unsigned int flags = 0;
378
    char *buffer = NULL;
379

380 381
    if (vshCommandOptBool(cmd, "prealloc-metadata"))
        flags |= VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA;
382

383
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
384 385
        return false;

386 387
    if (vshCommandOptStringReq(ctl, cmd, "file", &from) < 0)
        goto cleanup;
388

E
Eric Blake 已提交
389
    if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0) {
390 391
        vshSaveLibvirtError();
        goto cleanup;
392 393
    }

394
    if ((vol = virStorageVolCreateXML(pool, buffer, flags))) {
395 396 397
        vshPrint(ctl, _("Vol %s created from %s\n"),
                 virStorageVolGetName(vol), from);
        virStorageVolFree(vol);
398
        ret = true;
399 400 401
    } else {
        vshError(ctl, _("Failed to create vol from %s"), from);
    }
402

403
 cleanup:
404 405
    VIR_FREE(buffer);
    virStoragePoolFree(pool);
406 407 408 409 410 411 412
    return ret;
}

/*
 * "vol-create-from" command
 */
static const vshCmdInfo info_vol_create_from[] = {
413 414 415 416 417 418 419
    {.name = "help",
     .data = N_("create a vol, using another volume as input")
    },
    {.name = "desc",
     .data = N_("Create a vol from an existing volume.")
    },
    {.name = NULL}
420 421 422
};

static const vshCmdOptDef opts_vol_create_from[] = {
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
    {.name = "pool",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("pool name or uuid")
    },
    {.name = "file",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("file containing an XML vol description")
    },
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("input vol name or key")
    },
    {.name = "inputpool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid of the input volume's pool")
    },
    {.name = "prealloc-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("preallocate metadata (for qcow2 instead of full allocation)")
    },
446 447 448 449
    {.name = "reflink",
     .type = VSH_OT_BOOL,
     .help = N_("use btrfs COW lightweight copy")
    },
450
    {.name = NULL}
451 452 453 454 455 456 457 458 459 460
};

static bool
cmdVolCreateFrom(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool = NULL;
    virStorageVolPtr newvol = NULL, inputvol = NULL;
    const char *from = NULL;
    bool ret = false;
    char *buffer = NULL;
461
    unsigned int flags = 0;
462 463 464 465

    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
        goto cleanup;

466 467
    if (vshCommandOptBool(cmd, "prealloc-metadata"))
        flags |= VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA;
468

469 470 471
    if (vshCommandOptBool(cmd, "reflink"))
        flags |= VIR_STORAGE_VOL_CREATE_REFLINK;

472
    if (vshCommandOptStringReq(ctl, cmd, "file", &from) < 0)
473 474 475 476 477
        goto cleanup;

    if (!(inputvol = vshCommandOptVol(ctl, cmd, "vol", "inputpool", NULL)))
        goto cleanup;

E
Eric Blake 已提交
478 479
    if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0) {
        vshReportError(ctl);
480 481 482
        goto cleanup;
    }

483
    newvol = virStorageVolCreateXMLFrom(pool, buffer, inputvol, flags);
484 485 486 487 488 489 490 491 492 493

    if (newvol != NULL) {
        vshPrint(ctl, _("Vol %s created from input vol %s\n"),
                 virStorageVolGetName(newvol), virStorageVolGetName(inputvol));
    } else {
        vshError(ctl, _("Failed to create vol from %s"), from);
        goto cleanup;
    }

    ret = true;
494
 cleanup:
495 496 497 498 499 500 501 502 503 504 505
    VIR_FREE(buffer);
    if (pool)
        virStoragePoolFree(pool);
    if (inputvol)
        virStorageVolFree(inputvol);
    if (newvol)
        virStorageVolFree(newvol);
    return ret;
}

static xmlChar *
506
vshMakeCloneXML(const char *origxml, const char *newname)
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
{

    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlXPathObjectPtr obj = NULL;
    xmlChar *newxml = NULL;
    int size;

    doc = virXMLParseStringCtxt(origxml, _("(volume_definition)"), &ctxt);
    if (!doc)
        goto cleanup;

    obj = xmlXPathEval(BAD_CAST "/volume/name", ctxt);
    if (obj == NULL || obj->nodesetval == NULL ||
        obj->nodesetval->nodeTab == NULL)
        goto cleanup;

    xmlNodeSetContent(obj->nodesetval->nodeTab[0], (const xmlChar *)newname);
    xmlDocDumpMemory(doc, &newxml, &size);

527
 cleanup:
528 529 530 531 532 533 534 535 536 537
    xmlXPathFreeObject(obj);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);
    return newxml;
}

/*
 * "vol-clone" command
 */
static const vshCmdInfo info_vol_clone[] = {
538 539 540 541 542 543 544
    {.name = "help",
     .data = N_("clone a volume.")
    },
    {.name = "desc",
     .data = N_("Clone an existing volume.")
    },
    {.name = NULL}
545 546 547
};

static const vshCmdOptDef opts_vol_clone[] = {
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("orig vol name or key")
    },
    {.name = "newname",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("clone name")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = "prealloc-metadata",
     .type = VSH_OT_BOOL,
     .help = N_("preallocate metadata (for qcow2 instead of full allocation)")
    },
566 567 568 569
    {.name = "reflink",
     .type = VSH_OT_BOOL,
     .help = N_("use btrfs COW lightweight copy")
    },
570
    {.name = NULL}
571 572 573 574 575 576 577 578 579 580 581
};

static bool
cmdVolClone(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr origpool = NULL;
    virStorageVolPtr origvol = NULL, newvol = NULL;
    const char *name = NULL;
    char *origxml = NULL;
    xmlChar *newxml = NULL;
    bool ret = false;
582
    unsigned int flags = 0;
583 584 585 586

    if (!(origvol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        goto cleanup;

587 588 589
    if (vshCommandOptBool(cmd, "prealloc-metadata"))
        flags |= VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA;

590 591 592
    if (vshCommandOptBool(cmd, "reflink"))
        flags |= VIR_STORAGE_VOL_CREATE_REFLINK;

593 594 595 596 597 598
    origpool = virStoragePoolLookupByVolume(origvol);
    if (!origpool) {
        vshError(ctl, "%s", _("failed to get parent pool"));
        goto cleanup;
    }

599
    if (vshCommandOptStringReq(ctl, cmd, "newname", &name) < 0)
600 601 602 603 604 605
        goto cleanup;

    origxml = virStorageVolGetXMLDesc(origvol, 0);
    if (!origxml)
        goto cleanup;

606
    newxml = vshMakeCloneXML(origxml, name);
607 608 609 610 611
    if (!newxml) {
        vshPrint(ctl, "%s", _("Failed to allocate XML buffer"));
        goto cleanup;
    }

612
    newvol = virStorageVolCreateXMLFrom(origpool, (char *) newxml, origvol, flags);
613 614 615 616 617 618 619 620 621 622 623 624

    if (newvol != NULL) {
        vshPrint(ctl, _("Vol %s cloned from %s\n"),
                 virStorageVolGetName(newvol), virStorageVolGetName(origvol));
    } else {
        vshError(ctl, _("Failed to clone vol from %s"),
                 virStorageVolGetName(origvol));
        goto cleanup;
    }

    ret = true;

625
 cleanup:
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    VIR_FREE(origxml);
    xmlFree(newxml);
    if (origvol)
        virStorageVolFree(origvol);
    if (newvol)
        virStorageVolFree(newvol);
    if (origpool)
        virStoragePoolFree(origpool);
    return ret;
}

/*
 * "vol-upload" command
 */
static const vshCmdInfo info_vol_upload[] = {
641
    {.name = "help",
642
     .data = N_("upload file contents to a volume")
643 644
    },
    {.name = "desc",
645
     .data = N_("Upload file contents to a volume")
646 647
    },
    {.name = NULL}
648 649 650
};

static const vshCmdOptDef opts_vol_upload[] = {
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "file",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("file")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = "offset",
     .type = VSH_OT_INT,
     .help = N_("volume offset to upload to")
    },
    {.name = "length",
     .type = VSH_OT_INT,
     .help = N_("amount of data to upload")
    },
    {.name = NULL}
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
};

static int
cmdVolUploadSource(virStreamPtr st ATTRIBUTE_UNUSED,
                   char *bytes, size_t nbytes, void *opaque)
{
    int *fd = opaque;

    return saferead(*fd, bytes, nbytes);
}

static bool
cmdVolUpload(vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    virStorageVolPtr vol = NULL;
    bool ret = false;
    int fd = -1;
    virStreamPtr st = NULL;
    const char *name = NULL;
    unsigned long long offset = 0, length = 0;

696 697
    if (vshCommandOptULongLong(cmd, "offset", &offset) < 0) {
        vshError(ctl, _("Unable to parse offset value"));
698 699 700
        return false;
    }

701
    if (vshCommandOptULongLongWrap(cmd, "length", &length) < 0) {
702
        vshError(ctl, _("Unable to parse length value"));
703 704 705
        return false;
    }

706
    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name)))
707 708
        return false;

709
    if (vshCommandOptStringReq(ctl, cmd, "file", &file) < 0)
710 711 712 713 714 715 716
        goto cleanup;

    if ((fd = open(file, O_RDONLY)) < 0) {
        vshError(ctl, _("cannot read %s"), file);
        goto cleanup;
    }

717 718 719 720 721
    if (!(st = virStreamNew(ctl->conn, 0))) {
        vshError(ctl, _("cannot create a new stream"));
        goto cleanup;
    }

722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    if (virStorageVolUpload(vol, st, offset, length, 0) < 0) {
        vshError(ctl, _("cannot upload to volume %s"), name);
        goto cleanup;
    }

    if (virStreamSendAll(st, cmdVolUploadSource, &fd) < 0) {
        vshError(ctl, _("cannot send data to volume %s"), name);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        vshError(ctl, _("cannot close file %s"), file);
        virStreamAbort(st);
        goto cleanup;
    }

    if (virStreamFinish(st) < 0) {
        vshError(ctl, _("cannot close volume %s"), name);
        goto cleanup;
    }

    ret = true;

745
 cleanup:
746 747 748 749 750 751 752 753 754 755 756 757
    if (vol)
        virStorageVolFree(vol);
    if (st)
        virStreamFree(st);
    VIR_FORCE_CLOSE(fd);
    return ret;
}

/*
 * "vol-download" command
 */
static const vshCmdInfo info_vol_download[] = {
758
    {.name = "help",
759
     .data = N_("download volume contents to a file")
760 761
    },
    {.name = "desc",
762
     .data = N_("Download volume contents to a file")
763 764
    },
    {.name = NULL}
765 766 767
};

static const vshCmdOptDef opts_vol_download[] = {
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "file",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("file")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = "offset",
     .type = VSH_OT_INT,
     .help = N_("volume offset to download from")
    },
    {.name = "length",
     .type = VSH_OT_INT,
     .help = N_("amount of data to download")
    },
    {.name = NULL}
791 792 793 794 795 796 797 798 799 800 801 802 803 804
};

static bool
cmdVolDownload(vshControl *ctl, const vshCmd *cmd)
{
    const char *file = NULL;
    virStorageVolPtr vol = NULL;
    bool ret = false;
    int fd = -1;
    virStreamPtr st = NULL;
    const char *name = NULL;
    unsigned long long offset = 0, length = 0;
    bool created = false;

805 806
    if (vshCommandOptULongLong(cmd, "offset", &offset) < 0) {
        vshError(ctl, _("Unable to parse offset value"));
807 808 809
        return false;
    }

810
    if (vshCommandOptULongLongWrap(cmd, "length", &length) < 0) {
811
        vshError(ctl, _("Unable to parse length value"));
812 813 814 815 816 817
        return false;
    }

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name)))
        return false;

818
    if (vshCommandOptStringReq(ctl, cmd, "file", &file) < 0)
819 820 821 822 823 824 825 826 827 828 829 830
        goto cleanup;

    if ((fd = open(file, O_WRONLY|O_CREAT|O_EXCL, 0666)) < 0) {
        if (errno != EEXIST ||
            (fd = open(file, O_WRONLY|O_TRUNC, 0666)) < 0) {
            vshError(ctl, _("cannot create %s"), file);
            goto cleanup;
        }
    } else {
        created = true;
    }

831 832 833 834 835
    if (!(st = virStreamNew(ctl->conn, 0))) {
        vshError(ctl, _("cannot create a new stream"));
        goto cleanup;
    }

836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    if (virStorageVolDownload(vol, st, offset, length, 0) < 0) {
        vshError(ctl, _("cannot download from volume %s"), name);
        goto cleanup;
    }

    if (virStreamRecvAll(st, vshStreamSink, &fd) < 0) {
        vshError(ctl, _("cannot receive data from volume %s"), name);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        vshError(ctl, _("cannot close file %s"), file);
        virStreamAbort(st);
        goto cleanup;
    }

    if (virStreamFinish(st) < 0) {
        vshError(ctl, _("cannot close volume %s"), name);
        goto cleanup;
    }

    ret = true;

859
 cleanup:
860 861 862 863 864 865 866 867 868 869 870 871 872 873
    VIR_FORCE_CLOSE(fd);
    if (!ret && created)
        unlink(file);
    if (vol)
        virStorageVolFree(vol);
    if (st)
        virStreamFree(st);
    return ret;
}

/*
 * "vol-delete" command
 */
static const vshCmdInfo info_vol_delete[] = {
874 875 876 877 878 879 880
    {.name = "help",
     .data = N_("delete a vol")
    },
    {.name = "desc",
     .data = N_("Delete a given vol.")
    },
    {.name = NULL}
881 882 883
};

static const vshCmdOptDef opts_vol_delete[] = {
884 885 886 887 888 889 890 891 892 893
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = NULL}
894 895 896 897 898 899 900 901 902
};

static bool
cmdVolDelete(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
    bool ret = true;
    const char *name;

903
    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name)))
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
        return false;

    if (virStorageVolDelete(vol, 0) == 0) {
        vshPrint(ctl, _("Vol %s deleted\n"), name);
    } else {
        vshError(ctl, _("Failed to delete vol %s"), name);
        ret = false;
    }

    virStorageVolFree(vol);
    return ret;
}

/*
 * "vol-wipe" command
 */
static const vshCmdInfo info_vol_wipe[] = {
921 922 923 924 925 926 927
    {.name = "help",
     .data = N_("wipe a vol")
    },
    {.name = "desc",
     .data = N_("Ensure data previously on a volume is not accessible to future reads")
    },
    {.name = NULL}
928 929 930
};

static const vshCmdOptDef opts_vol_wipe[] = {
931 932 933 934 935 936 937 938 939 940 941 942 943 944
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = "algorithm",
     .type = VSH_OT_STRING,
     .help = N_("perform selected wiping algorithm")
    },
    {.name = NULL}
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
};

VIR_ENUM_DECL(virStorageVolWipeAlgorithm)
VIR_ENUM_IMPL(virStorageVolWipeAlgorithm, VIR_STORAGE_VOL_WIPE_ALG_LAST,
              "zero", "nnsa", "dod", "bsi", "gutmann", "schneier",
              "pfitzner7", "pfitzner33", "random");

static bool
cmdVolWipe(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
    bool ret = false;
    const char *name;
    const char *algorithm_str = NULL;
    int algorithm = VIR_STORAGE_VOL_WIPE_ALG_ZERO;
    int funcRet;

962
    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", &name)))
963 964
        return false;

965
    if (vshCommandOptStringReq(ctl, cmd, "algorithm", &algorithm_str) < 0)
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
        goto out;

    if (algorithm_str &&
        (algorithm = virStorageVolWipeAlgorithmTypeFromString(algorithm_str)) < 0) {
        vshError(ctl, _("Unsupported algorithm '%s'"), algorithm_str);
        goto out;
    }

    if ((funcRet = virStorageVolWipePattern(vol, algorithm, 0)) < 0) {
        if (last_error->code == VIR_ERR_NO_SUPPORT &&
            algorithm == VIR_STORAGE_VOL_WIPE_ALG_ZERO)
            funcRet = virStorageVolWipe(vol, 0);
    }

    if (funcRet < 0) {
        vshError(ctl, _("Failed to wipe vol %s"), name);
        goto out;
    }

    vshPrint(ctl, _("Vol %s wiped\n"), name);
    ret = true;
987
 out:
988 989 990 991
    virStorageVolFree(vol);
    return ret;
}

992

993 994 995 996 997 998 999 1000 1001
VIR_ENUM_DECL(vshStorageVol)
VIR_ENUM_IMPL(vshStorageVol,
              VIR_STORAGE_VOL_LAST,
              N_("file"),
              N_("block"),
              N_("dir"),
              N_("network"),
              N_("netdir"))

1002 1003 1004
static const char *
vshVolumeTypeToString(int type)
{
1005 1006
    const char *str = vshStorageVolTypeToString(type);
    return str ? _(str) : _("unknown");
1007 1008 1009
}


1010 1011 1012 1013
/*
 * "vol-info" command
 */
static const vshCmdInfo info_vol_info[] = {
1014 1015 1016 1017 1018 1019 1020
    {.name = "help",
     .data = N_("storage vol information")
    },
    {.name = "desc",
     .data = N_("Returns basic information about the storage vol.")
    },
    {.name = NULL}
1021 1022 1023
};

static const vshCmdOptDef opts_vol_info[] = {
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = NULL}
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
};

static bool
cmdVolInfo(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolInfo info;
    virStorageVolPtr vol;
    bool ret = true;

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        return false;

    vshPrint(ctl, "%-15s %s\n", _("Name:"), virStorageVolGetName(vol));

    if (virStorageVolGetInfo(vol, &info) == 0) {
        double val;
        const char *unit;

1052
        vshPrint(ctl, "%-15s %s\n", _("Type:"),
1053
                 vshVolumeTypeToString(info.type));
1054

E
Eric Blake 已提交
1055
        val = vshPrettyCapacity(info.capacity, &unit);
1056 1057
        vshPrint(ctl, "%-15s %2.2lf %s\n", _("Capacity:"), val, unit);

E
Eric Blake 已提交
1058
        val = vshPrettyCapacity(info.allocation, &unit);
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        vshPrint(ctl, "%-15s %2.2lf %s\n", _("Allocation:"), val, unit);
    } else {
        ret = false;
    }

    virStorageVolFree(vol);
    return ret;
}

/*
 * "vol-resize" command
 */
static const vshCmdInfo info_vol_resize[] = {
1072 1073 1074 1075 1076 1077 1078
    {.name = "help",
     .data = N_("resize a vol")
    },
    {.name = "desc",
     .data = N_("Resizes a storage volume.")
    },
    {.name = NULL}
1079 1080 1081
};

static const vshCmdOptDef opts_vol_resize[] = {
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "capacity",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("new capacity for the vol, as scaled integer (default bytes)")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = "allocate",
     .type = VSH_OT_BOOL,
     .help = N_("allocate the new capacity, rather than leaving it sparse")
    },
    {.name = "delta",
     .type = VSH_OT_BOOL,
     .help = N_("use capacity as a delta to current size, rather than the new size")
    },
    {.name = "shrink",
     .type = VSH_OT_BOOL,
     .help = N_("allow the resize to shrink the volume")
    },
    {.name = NULL}
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
};

static bool
cmdVolResize(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
    const char *capacityStr = NULL;
    unsigned long long capacity = 0;
    unsigned int flags = 0;
    bool ret = false;
    bool delta = false;

    if (vshCommandOptBool(cmd, "allocate"))
        flags |= VIR_STORAGE_VOL_RESIZE_ALLOCATE;
    if (vshCommandOptBool(cmd, "delta")) {
        delta = true;
        flags |= VIR_STORAGE_VOL_RESIZE_DELTA;
    }
    if (vshCommandOptBool(cmd, "shrink"))
        flags |= VIR_STORAGE_VOL_RESIZE_SHRINK;

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        return false;

O
Osier Yang 已提交
1133
    if (vshCommandOptStringReq(ctl, cmd, "capacity", &capacityStr) < 0)
1134 1135 1136 1137 1138
        goto cleanup;
    virSkipSpaces(&capacityStr);
    if (*capacityStr == '-') {
        /* The API always requires a positive value; but we allow a
         * negative value for convenience.  */
1139
        if (delta && vshCommandOptBool(cmd, "shrink")) {
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
            capacityStr++;
        } else {
            vshError(ctl, "%s",
                     _("negative size requires --delta and --shrink"));
            goto cleanup;
        }
    }
    if (vshVolSize(capacityStr, &capacity) < 0) {
        vshError(ctl, _("Malformed size %s"), capacityStr);
        goto cleanup;
    }

    if (virStorageVolResize(vol, capacity, flags) == 0) {
        vshPrint(ctl,
                 delta ? _("Size of volume '%s' successfully changed by %s\n")
                 : _("Size of volume '%s' successfully changed to %s\n"),
                 virStorageVolGetName(vol), capacityStr);
        ret = true;
    } else {
        vshError(ctl,
                 delta ? _("Failed to change size of volume '%s' by %s\n")
                 : _("Failed to change size of volume '%s' to %s\n"),
                 virStorageVolGetName(vol), capacityStr);
        ret = false;
    }

1166
 cleanup:
1167 1168 1169 1170 1171 1172 1173 1174
    virStorageVolFree(vol);
    return ret;
}

/*
 * "vol-dumpxml" command
 */
static const vshCmdInfo info_vol_dumpxml[] = {
1175 1176 1177 1178 1179 1180 1181
    {.name = "help",
     .data = N_("vol information in XML")
    },
    {.name = "desc",
     .data = N_("Output the vol information as an XML dump to stdout.")
    },
    {.name = NULL}
1182 1183 1184
};

static const vshCmdOptDef opts_vol_dumpxml[] = {
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("vol name, key or path")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = NULL}
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
};

static bool
cmdVolDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
    bool ret = true;
    char *dump;

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        return false;

    dump = virStorageVolGetXMLDesc(vol, 0);
    if (dump != NULL) {
        vshPrint(ctl, "%s", dump);
        VIR_FREE(dump);
    } else {
        ret = false;
    }

    virStorageVolFree(vol);
    return ret;
}

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
static int
vshStorageVolSorter(const void *a, const void *b)
{
    virStorageVolPtr *va = (virStorageVolPtr *) a;
    virStorageVolPtr *vb = (virStorageVolPtr *) b;

    if (*va && !*vb)
        return -1;

    if (!*va)
        return *vb != NULL;

    return vshStrcasecmp(virStorageVolGetName(*va),
                      virStorageVolGetName(*vb));
}

struct vshStorageVolList {
    virStorageVolPtr *vols;
    size_t nvols;
};
typedef struct vshStorageVolList *vshStorageVolListPtr;

static void
vshStorageVolListFree(vshStorageVolListPtr list)
{
1244
    size_t i;
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261

    if (list && list->vols) {
        for (i = 0; i < list->nvols; i++) {
            if (list->vols[i])
                virStorageVolFree(list->vols[i]);
        }
        VIR_FREE(list->vols);
    }
    VIR_FREE(list);
}

static vshStorageVolListPtr
vshStorageVolListCollect(vshControl *ctl,
                         virStoragePoolPtr pool,
                         unsigned int flags)
{
    vshStorageVolListPtr list = vshMalloc(ctl, sizeof(*list));
1262
    size_t i;
1263 1264 1265 1266 1267 1268 1269
    char **names = NULL;
    virStorageVolPtr vol = NULL;
    bool success = false;
    size_t deleted = 0;
    int nvols = 0;
    int ret = -1;

1270
    /* try the list with flags support (0.10.2 and later) */
1271 1272 1273 1274 1275 1276 1277 1278
    if ((ret = virStoragePoolListAllVolumes(pool,
                                            &list->vols,
                                            flags)) >= 0) {
        list->nvols = ret;
        goto finished;
    }

    /* check if the command is actually supported */
1279
    if (last_error && last_error->code == VIR_ERR_NO_SUPPORT)
1280 1281 1282 1283 1284 1285
        goto fallback;

    /* there was an error during the call */
    vshError(ctl, "%s", _("Failed to list volumes"));
    goto cleanup;

1286
 fallback:
1287
    /* fall back to old method (0.10.1 and older) */
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
    vshResetLibvirtError();

    /* Determine the number of volumes in the pool */
    if ((nvols = virStoragePoolNumOfVolumes(pool)) < 0) {
        vshError(ctl, "%s", _("Failed to list storage volumes"));
        goto cleanup;
    }

    if (nvols == 0) {
        success = true;
        return list;
    }

    /* Retrieve the list of volume names in the pool */
    names = vshCalloc(ctl, nvols, sizeof(*names));
    if ((nvols = virStoragePoolListVolumes(pool, names, nvols)) < 0) {
        vshError(ctl, "%s", _("Failed to list storage volumes"));
        goto cleanup;
    }

    list->vols = vshMalloc(ctl, sizeof(virStorageVolPtr) * (nvols));
    list->nvols = 0;

    /* get the vols */
    for (i = 0; i < nvols; i++) {
        if (!(vol = virStorageVolLookupByName(pool, names[i])))
            continue;
        list->vols[list->nvols++] = vol;
    }

    /* truncate the list for not found vols */
    deleted = nvols - list->nvols;

1321
 finished:
1322 1323 1324 1325 1326 1327 1328 1329 1330
    /* sort the list */
    if (list->vols && list->nvols)
        qsort(list->vols, list->nvols, sizeof(*list->vols), vshStorageVolSorter);

    if (deleted)
        VIR_SHRINK_N(list->vols, list->nvols, deleted);

    success = true;

1331
 cleanup:
1332 1333 1334
    if (nvols > 0)
        for (i = 0; i < nvols; i++)
            VIR_FREE(names[i]);
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
    VIR_FREE(names);

    if (!success) {
        vshStorageVolListFree(list);
        list = NULL;
    }

    return list;
}

1345 1346 1347 1348
/*
 * "vol-list" command
 */
static const vshCmdInfo info_vol_list[] = {
1349 1350 1351 1352 1353 1354 1355
    {.name = "help",
     .data = N_("list vols")
    },
    {.name = "desc",
     .data = N_("Returns list of vols by pool.")
    },
    {.name = NULL}
1356 1357 1358
};

static const vshCmdOptDef opts_vol_list[] = {
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    {.name = "pool",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("pool name or uuid")
    },
    {.name = "details",
     .type = VSH_OT_BOOL,
     .help = N_("display extended details for volumes")
    },
    {.name = NULL}
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
};

static bool
cmdVolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    virStorageVolInfo volumeInfo;
    virStoragePoolPtr pool;
    char *outputStr = NULL;
    const char *unit;
    double val;
    bool details = vshCommandOptBool(cmd, "details");
1380
    size_t i;
1381
    bool ret = false;
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
    int stringLength = 0;
    size_t allocStrLength = 0, capStrLength = 0;
    size_t nameStrLength = 0, pathStrLength = 0;
    size_t typeStrLength = 0;
    struct volInfoText {
        char *allocation;
        char *capacity;
        char *path;
        char *type;
    };
    struct volInfoText *volInfoTexts = NULL;
1393
    vshStorageVolListPtr list = NULL;
1394 1395 1396 1397 1398

    /* Look up the pool information given to us by the user */
    if (!(pool = vshCommandOptPool(ctl, cmd, "pool", NULL)))
        return false;

1399 1400
    if (!(list = vshStorageVolListCollect(ctl, pool, 0)))
        goto cleanup;
1401

1402 1403
    if (list->nvols > 0)
        volInfoTexts = vshCalloc(ctl, list->nvols, sizeof(*volInfoTexts));
1404 1405

    /* Collect the rest of the volume information for display */
1406
    for (i = 0; i < list->nvols; i++) {
1407
        /* Retrieve volume info */
1408
        virStorageVolPtr vol = list->vols[i];
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426

        /* Retrieve the volume path */
        if ((volInfoTexts[i].path = virStorageVolGetPath(vol)) == NULL) {
            /* Something went wrong retrieving a volume path, cope with it */
            volInfoTexts[i].path = vshStrdup(ctl, _("unknown"));
        }

        /* If requested, retrieve volume type and sizing information */
        if (details) {
            if (virStorageVolGetInfo(vol, &volumeInfo) != 0) {
                /* Something went wrong retrieving volume info, cope with it */
                volInfoTexts[i].allocation = vshStrdup(ctl, _("unknown"));
                volInfoTexts[i].capacity = vshStrdup(ctl, _("unknown"));
                volInfoTexts[i].type = vshStrdup(ctl, _("unknown"));
            } else {
                /* Convert the returned volume info into output strings */

                /* Volume type */
1427
                volInfoTexts[i].type = vshStrdup(ctl,
1428
                                                 vshVolumeTypeToString(volumeInfo.type));
1429

E
Eric Blake 已提交
1430
                val = vshPrettyCapacity(volumeInfo.capacity, &unit);
1431 1432 1433 1434
                if (virAsprintf(&volInfoTexts[i].capacity,
                                "%.2lf %s", val, unit) < 0)
                    goto cleanup;

E
Eric Blake 已提交
1435
                val = vshPrettyCapacity(volumeInfo.allocation, &unit);
1436 1437 1438
                if (virAsprintf(&volInfoTexts[i].allocation,
                                "%.2lf %s", val, unit) < 0)
                    goto cleanup;
1439 1440 1441 1442 1443 1444 1445 1446
            }

            /* Remember the largest length for each output string.
             * This lets us displaying header and volume information rows
             * using a single, properly sized, printf style output string.
             */

            /* Keep the length of name string if longest so far */
1447
            stringLength = strlen(virStorageVolGetName(list->vols[i]));
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
            if (stringLength > nameStrLength)
                nameStrLength = stringLength;

            /* Keep the length of path string if longest so far */
            stringLength = strlen(volInfoTexts[i].path);
            if (stringLength > pathStrLength)
                pathStrLength = stringLength;

            /* Keep the length of type string if longest so far */
            stringLength = strlen(volInfoTexts[i].type);
            if (stringLength > typeStrLength)
                typeStrLength = stringLength;

            /* Keep the length of capacity string if longest so far */
            stringLength = strlen(volInfoTexts[i].capacity);
            if (stringLength > capStrLength)
                capStrLength = stringLength;

            /* Keep the length of allocation string if longest so far */
            stringLength = strlen(volInfoTexts[i].allocation);
            if (stringLength > allocStrLength)
                allocStrLength = stringLength;
        }
    }

    /* If the --details option wasn't selected, we output the volume
     * info using the fixed string format from previous versions to
     * maintain backward compatibility.
     */

    /* Output basic info then return if --details option not selected */
    if (!details) {
        /* The old output format */
1481 1482 1483
        vshPrintExtra(ctl, " %-20s %-40s\n", _("Name"), _("Path"));
        vshPrintExtra(ctl, "---------------------------------------"
                           "---------------------------------------\n");
1484
        for (i = 0; i < list->nvols; i++) {
1485
            vshPrint(ctl, " %-20s %-40s\n", virStorageVolGetName(list->vols[i]),
1486 1487 1488 1489
                     volInfoTexts[i].path);
        }

        /* Cleanup and return */
1490
        ret = true;
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
        goto cleanup;
    }

    /* We only get here if the --details option was selected. */

    /* Use the length of name header string if it's longest */
    stringLength = strlen(_("Name"));
    if (stringLength > nameStrLength)
        nameStrLength = stringLength;

    /* Use the length of path header string if it's longest */
    stringLength = strlen(_("Path"));
    if (stringLength > pathStrLength)
        pathStrLength = stringLength;

    /* Use the length of type header string if it's longest */
    stringLength = strlen(_("Type"));
    if (stringLength > typeStrLength)
        typeStrLength = stringLength;

    /* Use the length of capacity header string if it's longest */
    stringLength = strlen(_("Capacity"));
    if (stringLength > capStrLength)
        capStrLength = stringLength;

    /* Use the length of allocation header string if it's longest */
    stringLength = strlen(_("Allocation"));
    if (stringLength > allocStrLength)
        allocStrLength = stringLength;

    /* Display the string lengths for debugging */
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest name string = %zu chars\n", nameStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest path string = %zu chars\n", pathStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest type string = %zu chars\n", typeStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest capacity string = %zu chars\n", capStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG,
             "Longest allocation string = %zu chars\n", allocStrLength);

1533 1534 1535 1536 1537 1538 1539 1540
    if (virAsprintf(&outputStr,
                    " %%-%lus  %%-%lus  %%-%lus  %%%lus  %%%lus\n",
                    (unsigned long) nameStrLength,
                    (unsigned long) pathStrLength,
                    (unsigned long) typeStrLength,
                    (unsigned long) capStrLength,
                    (unsigned long) allocStrLength) < 0)
        goto cleanup;
1541 1542 1543 1544 1545 1546

    /* Display the header */
    vshPrint(ctl, outputStr, _("Name"), _("Path"), _("Type"),
             ("Capacity"), _("Allocation"));
    for (i = nameStrLength + pathStrLength + typeStrLength
                           + capStrLength + allocStrLength
1547
                           + 10; i > 0; i--)
1548 1549 1550 1551
        vshPrintExtra(ctl, "-");
    vshPrintExtra(ctl, "\n");

    /* Display the volume info rows */
1552
    for (i = 0; i < list->nvols; i++) {
1553
        vshPrint(ctl, outputStr,
1554
                 virStorageVolGetName(list->vols[i]),
1555 1556 1557 1558 1559 1560 1561
                 volInfoTexts[i].path,
                 volInfoTexts[i].type,
                 volInfoTexts[i].capacity,
                 volInfoTexts[i].allocation);
    }

    /* Cleanup and return */
1562
    ret = true;
1563

1564
 cleanup:
1565 1566

    /* Safely free the memory allocated in this function */
1567 1568 1569 1570 1571 1572 1573 1574
    if (list && list->nvols) {
        for (i = 0; i < list->nvols; i++) {
            /* Cleanup the memory for one volume info structure per loop */
            VIR_FREE(volInfoTexts[i].path);
            VIR_FREE(volInfoTexts[i].type);
            VIR_FREE(volInfoTexts[i].capacity);
            VIR_FREE(volInfoTexts[i].allocation);
        }
1575 1576 1577 1578 1579 1580
    }

    /* Cleanup remaining memory */
    VIR_FREE(outputStr);
    VIR_FREE(volInfoTexts);
    virStoragePoolFree(pool);
1581
    vshStorageVolListFree(list);
1582 1583

    /* Return the desired value */
1584
    return ret;
1585 1586 1587 1588 1589 1590
}

/*
 * "vol-name" command
 */
static const vshCmdInfo info_vol_name[] = {
1591 1592 1593 1594 1595 1596 1597
    {.name = "help",
     .data = N_("returns the volume name for a given volume key or path")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
1598 1599 1600
};

static const vshCmdOptDef opts_vol_name[] = {
1601 1602 1603 1604 1605 1606
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("volume key or path")
    },
    {.name = NULL}
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
};

static bool
cmdVolName(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;

    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", NULL, NULL,
                                   VSH_BYUUID)))
        return false;

    vshPrint(ctl, "%s\n", virStorageVolGetName(vol));
    virStorageVolFree(vol);
    return true;
}

/*
 * "vol-pool" command
 */
static const vshCmdInfo info_vol_pool[] = {
1627 1628 1629 1630 1631 1632 1633
    {.name = "help",
     .data = N_("returns the storage pool for a given volume key or path")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
1634 1635 1636
};

static const vshCmdOptDef opts_vol_pool[] = {
1637 1638 1639 1640 1641
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("volume key or path")
    },
M
Martin Kletzander 已提交
1642 1643 1644 1645
    {.name = "uuid",
     .type = VSH_OT_BOOL,
     .help = N_("return the pool uuid rather than pool name")
    },
1646
    {.name = NULL}
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689
};

static bool
cmdVolPool(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    virStorageVolPtr vol;
    char uuid[VIR_UUID_STRING_BUFLEN];

    /* Use the supplied string to locate the volume */
    if (!(vol = vshCommandOptVolBy(ctl, cmd, "vol", NULL, NULL,
                                   VSH_BYUUID))) {
        return false;
    }

    /* Look up the parent storage pool for the volume */
    pool = virStoragePoolLookupByVolume(vol);
    if (pool == NULL) {
        vshError(ctl, "%s", _("failed to get parent pool"));
        virStorageVolFree(vol);
        return false;
    }

    /* Return the requested details of the parent storage pool */
    if (vshCommandOptBool(cmd, "uuid")) {
        /* Retrieve and return pool UUID string */
        if (virStoragePoolGetUUIDString(pool, &uuid[0]) == 0)
            vshPrint(ctl, "%s\n", uuid);
    } else {
        /* Return the storage pool name */
        vshPrint(ctl, "%s\n", virStoragePoolGetName(pool));
    }

    /* Cleanup */
    virStorageVolFree(vol);
    virStoragePoolFree(pool);
    return true;
}

/*
 * "vol-key" command
 */
static const vshCmdInfo info_vol_key[] = {
1690 1691 1692 1693 1694 1695 1696
    {.name = "help",
     .data = N_("returns the volume key for a given volume name or path")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
1697 1698 1699
};

static const vshCmdOptDef opts_vol_key[] = {
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("volume name or path")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = NULL}
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
};

static bool
cmdVolKey(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;

    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
        return false;

    vshPrint(ctl, "%s\n", virStorageVolGetKey(vol));
    virStorageVolFree(vol);
    return true;
}

/*
 * "vol-path" command
 */
static const vshCmdInfo info_vol_path[] = {
1729 1730 1731 1732 1733 1734 1735
    {.name = "help",
     .data = N_("returns the volume path for a given volume name or key")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
1736 1737 1738
};

static const vshCmdOptDef opts_vol_path[] = {
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
    {.name = "vol",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("volume name or key")
    },
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("pool name or uuid")
    },
    {.name = NULL}
1749 1750 1751 1752 1753 1754 1755 1756
};

static bool
cmdVolPath(vshControl *ctl, const vshCmd *cmd)
{
    virStorageVolPtr vol;
    char * StorageVolPath;

1757
    if (!(vol = vshCommandOptVol(ctl, cmd, "vol", "pool", NULL)))
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
        return false;

    if ((StorageVolPath = virStorageVolGetPath(vol)) == NULL) {
        virStorageVolFree(vol);
        return false;
    }

    vshPrint(ctl, "%s\n", StorageVolPath);
    VIR_FREE(StorageVolPath);
    virStorageVolFree(vol);
    return true;
}
1770

E
Eric Blake 已提交
1771
const vshCmdDef storageVolCmds[] = {
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 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 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
    {.name = "vol-clone",
     .handler = cmdVolClone,
     .opts = opts_vol_clone,
     .info = info_vol_clone,
     .flags = 0
    },
    {.name = "vol-create-as",
     .handler = cmdVolCreateAs,
     .opts = opts_vol_create_as,
     .info = info_vol_create_as,
     .flags = 0
    },
    {.name = "vol-create",
     .handler = cmdVolCreate,
     .opts = opts_vol_create,
     .info = info_vol_create,
     .flags = 0
    },
    {.name = "vol-create-from",
     .handler = cmdVolCreateFrom,
     .opts = opts_vol_create_from,
     .info = info_vol_create_from,
     .flags = 0
    },
    {.name = "vol-delete",
     .handler = cmdVolDelete,
     .opts = opts_vol_delete,
     .info = info_vol_delete,
     .flags = 0
    },
    {.name = "vol-download",
     .handler = cmdVolDownload,
     .opts = opts_vol_download,
     .info = info_vol_download,
     .flags = 0
    },
    {.name = "vol-dumpxml",
     .handler = cmdVolDumpXML,
     .opts = opts_vol_dumpxml,
     .info = info_vol_dumpxml,
     .flags = 0
    },
    {.name = "vol-info",
     .handler = cmdVolInfo,
     .opts = opts_vol_info,
     .info = info_vol_info,
     .flags = 0
    },
    {.name = "vol-key",
     .handler = cmdVolKey,
     .opts = opts_vol_key,
     .info = info_vol_key,
     .flags = 0
    },
    {.name = "vol-list",
     .handler = cmdVolList,
     .opts = opts_vol_list,
     .info = info_vol_list,
     .flags = 0
    },
    {.name = "vol-name",
     .handler = cmdVolName,
     .opts = opts_vol_name,
     .info = info_vol_name,
     .flags = 0
    },
    {.name = "vol-path",
     .handler = cmdVolPath,
     .opts = opts_vol_path,
     .info = info_vol_path,
     .flags = 0
    },
    {.name = "vol-pool",
     .handler = cmdVolPool,
     .opts = opts_vol_pool,
     .info = info_vol_pool,
     .flags = 0
    },
    {.name = "vol-resize",
     .handler = cmdVolResize,
     .opts = opts_vol_resize,
     .info = info_vol_resize,
     .flags = 0
    },
    {.name = "vol-upload",
     .handler = cmdVolUpload,
     .opts = opts_vol_upload,
     .info = info_vol_upload,
     .flags = 0
    },
    {.name = "vol-wipe",
     .handler = cmdVolWipe,
     .opts = opts_vol_wipe,
     .info = info_vol_wipe,
     .flags = 0
    },
    {.name = NULL}
1869
};