virsh-pool.c 68.2 KB
Newer Older
1 2 3
/*
 * virsh-pool.c: Commands to manage storage pool
 *
4
 * Copyright (C) 2005, 2007-2016 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-pool.h"
28

E
Eric Blake 已提交
29
#include "internal.h"
30
#include "virbuffer.h"
31
#include "viralloc.h"
32
#include "virfile.h"
33
#include "conf/storage_conf.h"
34
#include "virstring.h"
35
#include "virtime.h"
E
Eric Blake 已提交
36

37 38
#define VIRSH_COMMON_OPT_POOL_FULL(cflags) \
    VIRSH_COMMON_OPT_POOL(N_("pool name or uuid"), cflags)
39 40 41 42 43 44

#define VIRSH_COMMON_OPT_POOL_BUILD \
    {.name = "build", \
     .type = VSH_OT_BOOL, \
     .flags = 0, \
     .help = N_("build the pool as normal") \
45
    }
46 47 48 49 50 51

#define VIRSH_COMMON_OPT_POOL_NO_OVERWRITE \
    {.name = "no-overwrite", \
     .type = VSH_OT_BOOL, \
     .flags = 0, \
     .help = N_("do not overwrite any existing data") \
52
    }
53 54 55 56 57 58

#define VIRSH_COMMON_OPT_POOL_OVERWRITE \
    {.name = "overwrite", \
     .type = VSH_OT_BOOL, \
     .flags = 0, \
     .help = N_("overwrite any existing data") \
59
    }
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

#define VIRSH_COMMON_OPT_POOL_X_AS \
    {.name = "name", \
     .type = VSH_OT_DATA, \
     .flags = VSH_OFLAG_REQ, \
     .help = N_("name of the pool") \
    }, \
    {.name = "type", \
     .type = VSH_OT_DATA, \
     .flags = VSH_OFLAG_REQ, \
     .help = N_("type of the pool") \
    }, \
    {.name = "print-xml", \
     .type = VSH_OT_BOOL, \
     .help = N_("print XML document, but don't define/create") \
    }, \
    {.name = "source-host", \
     .type = VSH_OT_STRING, \
     .help = N_("source-host for underlying storage") \
    }, \
    {.name = "source-path", \
     .type = VSH_OT_STRING, \
     .help = N_("source path for underlying storage") \
    }, \
    {.name = "source-dev", \
     .type = VSH_OT_STRING, \
     .help = N_("source device for underlying storage") \
    }, \
    {.name = "source-name", \
     .type = VSH_OT_STRING, \
     .help = N_("source name for underlying storage") \
    }, \
    {.name = "target", \
     .type = VSH_OT_STRING, \
     .help = N_("target for underlying storage") \
    }, \
    {.name = "source-format", \
     .type = VSH_OT_STRING, \
     .help = N_("format for underlying storage") \
    }, \
    {.name = "auth-type", \
     .type = VSH_OT_STRING, \
     .help = N_("auth type to be used for underlying storage") \
    }, \
    {.name = "auth-username", \
     .type = VSH_OT_STRING, \
     .help = N_("auth username to be used for underlying storage") \
    }, \
    {.name = "secret-usage", \
     .type = VSH_OT_STRING, \
110
     .help = N_("auth secret usage to be used for underlying storage") \
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    }, \
    {.name = "secret-uuid", \
     .type = VSH_OT_STRING, \
     .help = N_("auth secret UUID to be used for underlying storage") \
    }, \
    {.name = "adapter-name", \
     .type = VSH_OT_STRING, \
     .help = N_("adapter name to be used for underlying storage") \
    }, \
    {.name = "adapter-wwnn", \
     .type = VSH_OT_STRING, \
     .help = N_("adapter wwnn to be used for underlying storage") \
    }, \
    {.name = "adapter-wwpn", \
     .type = VSH_OT_STRING, \
     .help = N_("adapter wwpn to be used for underlying storage") \
    }, \
    {.name = "adapter-parent", \
     .type = VSH_OT_STRING, \
130
     .help = N_("adapter parent scsi_hostN to be used for underlying vHBA storage") \
131 132 133 134 135 136 137 138 139 140 141 142
    }, \
    {.name = "adapter-parent-wwnn", \
     .type = VSH_OT_STRING, \
     .help = N_("adapter parent scsi_hostN wwnn to be used for underlying vHBA storage") \
    }, \
    {.name = "adapter-parent-wwpn", \
     .type = VSH_OT_STRING, \
     .help = N_("adapter parent scsi_hostN wwpn to be used for underlying vHBA storage") \
    }, \
    {.name = "adapter-parent-fabric-wwn", \
     .type = VSH_OT_STRING, \
     .help = N_("adapter parent scsi_hostN fabric_wwn to be used for underlying vHBA storage") \
143
    }
144

E
Eric Blake 已提交
145
virStoragePoolPtr
146 147
virshCommandOptPoolBy(vshControl *ctl, const vshCmd *cmd, const char *optname,
                      const char **name, unsigned int flags)
148 149 150
{
    virStoragePoolPtr pool = NULL;
    const char *n = NULL;
151 152 153
    virshControlPtr priv = ctl->privData;

    virCheckFlags(VIRSH_BYUUID | VIRSH_BYNAME, NULL);
154

155
    if (vshCommandOptStringReq(ctl, cmd, optname, &n) < 0)
156 157
        return NULL;

158 159 160
    if (cmd->skipChecks && !n)
        return NULL;

161 162 163 164 165 166 167
    vshDebug(ctl, VSH_ERR_INFO, "%s: found option <%s>: %s\n",
             cmd->def->name, optname, n);

    if (name)
        *name = n;

    /* try it by UUID */
168
    if ((flags & VIRSH_BYUUID) && strlen(n) == VIR_UUID_STRING_BUFLEN-1) {
169 170
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as pool UUID\n",
                 cmd->def->name, optname);
171
        pool = virStoragePoolLookupByUUIDString(priv->conn, n);
172 173
    }
    /* try it by NAME */
174
    if (!pool && (flags & VIRSH_BYNAME)) {
175 176
        vshDebug(ctl, VSH_ERR_DEBUG, "%s: <%s> trying as pool NAME\n",
                 cmd->def->name, optname);
177
        pool = virStoragePoolLookupByName(priv->conn, n);
178 179 180 181 182 183 184 185 186 187 188 189
    }

    if (!pool)
        vshError(ctl, _("failed to get pool '%s'"), n);

    return pool;
}

/*
 * "pool-autostart" command
 */
static const vshCmdInfo info_pool_autostart[] = {
190 191 192 193 194 195 196
    {.name = "help",
     .data = N_("autostart a pool")
    },
    {.name = "desc",
     .data = N_("Configure a pool to be automatically started at boot.")
    },
    {.name = NULL}
197 198 199
};

static const vshCmdOptDef opts_pool_autostart[] = {
200
    VIRSH_COMMON_OPT_POOL_FULL(VIR_CONNECT_LIST_STORAGE_POOLS_PERSISTENT),
201

202 203 204 205 206
    {.name = "disable",
     .type = VSH_OT_BOOL,
     .help = N_("disable autostarting")
    },
    {.name = NULL}
207 208 209 210 211 212 213 214 215
};

static bool
cmdPoolAutostart(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    const char *name;
    int autostart;

216
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", &name)))
217 218 219 220 221 222 223 224 225 226 227 228 229 230
        return false;

    autostart = !vshCommandOptBool(cmd, "disable");

    if (virStoragePoolSetAutostart(pool, autostart) < 0) {
        if (autostart)
            vshError(ctl, _("failed to mark pool %s as autostarted"), name);
        else
            vshError(ctl, _("failed to unmark pool %s as autostarted"), name);
        virStoragePoolFree(pool);
        return false;
    }

    if (autostart)
P
Pino Toscano 已提交
231
        vshPrintExtra(ctl, _("Pool %s marked as autostarted\n"), name);
232
    else
P
Pino Toscano 已提交
233
        vshPrintExtra(ctl, _("Pool %s unmarked as autostarted\n"), name);
234 235 236 237 238 239 240 241 242

    virStoragePoolFree(pool);
    return true;
}

/*
 * "pool-create" command
 */
static const vshCmdInfo info_pool_create[] = {
243 244 245 246 247 248 249
    {.name = "help",
     .data = N_("create a pool from an XML file")
    },
    {.name = "desc",
     .data = N_("Create a pool.")
    },
    {.name = NULL}
250 251 252
};

static const vshCmdOptDef opts_pool_create[] = {
253
    VIRSH_COMMON_OPT_FILE(N_("file containing an XML pool description")),
254 255 256
    VIRSH_COMMON_OPT_POOL_BUILD,
    VIRSH_COMMON_OPT_POOL_NO_OVERWRITE,
    VIRSH_COMMON_OPT_POOL_OVERWRITE,
257

258
    {.name = NULL}
259 260 261 262 263 264 265 266 267
};

static bool
cmdPoolCreate(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    const char *from = NULL;
    bool ret = true;
    char *buffer;
268 269 270 271
    bool build;
    bool overwrite;
    bool no_overwrite;
    unsigned int flags = 0;
272
    virshControlPtr priv = ctl->privData;
273

274
    if (vshCommandOptStringReq(ctl, cmd, "file", &from) < 0)
275 276
        return false;

277 278 279 280 281 282 283 284 285 286 287 288 289 290
    build = vshCommandOptBool(cmd, "build");
    overwrite = vshCommandOptBool(cmd, "overwrite");
    no_overwrite = vshCommandOptBool(cmd, "no-overwrite");

    VSH_EXCLUSIVE_OPTIONS_EXPR("overwrite", overwrite,
                               "no-overwrite", no_overwrite);

    if (build)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD;
    if (overwrite)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE;
    if (no_overwrite)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE;

E
Eric Blake 已提交
291
    if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0)
292 293
        return false;

294
    pool = virStoragePoolCreateXML(priv->conn, buffer, flags);
295 296 297
    VIR_FREE(buffer);

    if (pool != NULL) {
P
Pino Toscano 已提交
298 299
        vshPrintExtra(ctl, _("Pool %s created from %s\n"),
                      virStoragePoolGetName(pool), from);
300 301 302 303 304 305 306 307
        virStoragePoolFree(pool);
    } else {
        vshError(ctl, _("Failed to create pool from %s"), from);
        ret = false;
    }
    return ret;
}

308
static const vshCmdOptDef opts_pool_define_as[] = {
309
    VIRSH_COMMON_OPT_POOL_X_AS,
310

311
    {.name = NULL}
312 313
};

314
static int
315 316 317 318
virshBuildPoolXML(vshControl *ctl,
                  const vshCmd *cmd,
                  const char **retname,
                  char **xml)
319
{
320
    const char *name = NULL, *type = NULL, *srcHost = NULL, *srcPath = NULL,
321
               *srcDev = NULL, *srcName = NULL, *srcFormat = NULL,
322
               *target = NULL, *authType = NULL, *authUsername = NULL,
323
               *secretUsage = NULL, *adapterName = NULL, *adapterParent = NULL,
324 325 326
               *adapterWwnn = NULL, *adapterWwpn = NULL, *secretUUID = NULL,
               *adapterParentWwnn = NULL, *adapterParentWwpn = NULL,
               *adapterParentFabricWwn = NULL;
327 328
    virBuffer buf = VIR_BUFFER_INITIALIZER;

329 330
    VSH_EXCLUSIVE_OPTIONS("secret-usage", "secret-uuid");

331
    if (vshCommandOptStringReq(ctl, cmd, "name", &name) < 0)
332
        goto cleanup;
333
    if (vshCommandOptStringReq(ctl, cmd, "type", &type) < 0)
334 335
        goto cleanup;

336 337 338 339 340
    if (vshCommandOptStringReq(ctl, cmd, "source-host", &srcHost) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "source-path", &srcPath) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "source-dev", &srcDev) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "source-name", &srcName) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "source-format", &srcFormat) < 0 ||
341 342 343
        vshCommandOptStringReq(ctl, cmd, "target", &target) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "auth-type", &authType) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "auth-username", &authUsername) < 0 ||
344
        vshCommandOptStringReq(ctl, cmd, "secret-usage", &secretUsage) < 0 ||
345
        vshCommandOptStringReq(ctl, cmd, "secret-uuid", &secretUUID) < 0 ||
346 347 348
        vshCommandOptStringReq(ctl, cmd, "adapter-name", &adapterName) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "adapter-wwnn", &adapterWwnn) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "adapter-wwpn", &adapterWwpn) < 0 ||
349 350 351 352
        vshCommandOptStringReq(ctl, cmd, "adapter-parent", &adapterParent) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "adapter-parent-wwnn", &adapterParentWwnn) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "adapter-parent-wwpn", &adapterParentWwpn) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "adapter-parent-fabric-wwn", &adapterParentFabricWwn) < 0)
353 354 355
        goto cleanup;

    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
356 357
    virBufferAdjustIndent(&buf, 2);
    virBufferAsprintf(&buf, "<name>%s</name>\n", name);
358 359
    if (srcHost || srcPath || srcDev || srcFormat || srcName ||
        (adapterWwnn && adapterWwpn) || adapterName) {
360 361
        virBufferAddLit(&buf, "<source>\n");
        virBufferAdjustIndent(&buf, 2);
362 363

        if (srcHost)
364
            virBufferAsprintf(&buf, "<host name='%s'/>\n", srcHost);
365
        if (srcPath)
366
            virBufferAsprintf(&buf, "<dir path='%s'/>\n", srcPath);
367
        if (srcDev)
368
            virBufferAsprintf(&buf, "<device path='%s'/>\n", srcDev);
369 370 371 372
        if (adapterWwnn && adapterWwpn) {
            virBufferAddLit(&buf, "<adapter type='fc_host'");
            if (adapterParent)
                virBufferAsprintf(&buf, " parent='%s'", adapterParent);
373
            else if (adapterParentWwnn && adapterParentWwpn)
374
                virBufferAsprintf(&buf, " parent_wwnn='%s' parent_wwpn='%s'",
375 376 377 378
                                  adapterParentWwnn, adapterParentWwpn);
            else if (adapterParentFabricWwn)
                virBufferAsprintf(&buf, " parent_fabric_wwn='%s'",
                                  adapterParentFabricWwn);
379 380 381 382 383 384
            virBufferAsprintf(&buf, " wwnn='%s' wwpn='%s'/>\n",
                              adapterWwnn, adapterWwpn);
        } else if (adapterName) {
            virBufferAsprintf(&buf, "<adapter type='scsi_host' name='%s'/>\n",
                              adapterName);
        }
385
        if (authType && authUsername && (secretUsage || secretUUID)) {
386 387 388
            virBufferAsprintf(&buf, "<auth type='%s' username='%s'>\n",
                              authType, authUsername);
            virBufferAdjustIndent(&buf, 2);
389 390 391 392
            if (secretUsage)
                virBufferAsprintf(&buf, "<secret usage='%s'/>\n", secretUsage);
            else
                virBufferAsprintf(&buf, "<secret uuid='%s'/>\n", secretUUID);
393 394 395
            virBufferAdjustIndent(&buf, -2);
            virBufferAddLit(&buf, "</auth>\n");
        }
396
        if (srcFormat)
397
            virBufferAsprintf(&buf, "<format type='%s'/>\n", srcFormat);
398
        if (srcName)
399
            virBufferAsprintf(&buf, "<name>%s</name>\n", srcName);
400

401 402
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</source>\n");
403 404
    }
    if (target) {
405 406 407 408 409
        virBufferAddLit(&buf, "<target>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<path>%s</path>\n", target);
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</target>\n");
410
    }
411
    virBufferAdjustIndent(&buf, -2);
412 413 414
    virBufferAddLit(&buf, "</pool>\n");

    if (virBufferError(&buf)) {
415
        vshError(ctl, "%s", _("Failed to allocate XML buffer"));
416 417 418 419 420 421 422
        return false;
    }

    *xml = virBufferContentAndReset(&buf);
    *retname = name;
    return true;

423
 cleanup:
424 425 426 427 428 429 430 431
    virBufferFreeAndReset(&buf);
    return false;
}

/*
 * "pool-create-as" command
 */
static const vshCmdInfo info_pool_create_as[] = {
432 433 434 435 436 437 438
    {.name = "help",
     .data = N_("create a pool from a set of args")
    },
    {.name = "desc",
     .data = N_("Create a pool.")
    },
    {.name = NULL}
439 440
};

441
static const vshCmdOptDef opts_pool_create_as[] = {
442 443 444 445
    VIRSH_COMMON_OPT_POOL_X_AS,
    VIRSH_COMMON_OPT_POOL_BUILD,
    VIRSH_COMMON_OPT_POOL_NO_OVERWRITE,
    VIRSH_COMMON_OPT_POOL_OVERWRITE,
446 447 448 449

    {.name = NULL}
};

450 451 452 453 454 455 456
static bool
cmdPoolCreateAs(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    const char *name;
    char *xml;
    bool printXML = vshCommandOptBool(cmd, "print-xml");
457 458 459 460
    bool build;
    bool overwrite;
    bool no_overwrite;
    unsigned int flags = 0;
461
    virshControlPtr priv = ctl->privData;
462

463 464 465 466 467 468 469 470 471 472 473 474 475 476
    build = vshCommandOptBool(cmd, "build");
    overwrite = vshCommandOptBool(cmd, "overwrite");
    no_overwrite = vshCommandOptBool(cmd, "no-overwrite");

    VSH_EXCLUSIVE_OPTIONS_EXPR("overwrite", overwrite,
                               "no-overwrite", no_overwrite);

    if (build)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD;
    if (overwrite)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE;
    if (no_overwrite)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE;

477
    if (!virshBuildPoolXML(ctl, cmd, &name, &xml))
478 479 480 481 482 483
        return false;

    if (printXML) {
        vshPrint(ctl, "%s", xml);
        VIR_FREE(xml);
    } else {
484
        pool = virStoragePoolCreateXML(priv->conn, xml, flags);
485 486 487
        VIR_FREE(xml);

        if (pool != NULL) {
P
Pino Toscano 已提交
488
            vshPrintExtra(ctl, _("Pool %s created\n"), name);
489 490 491 492 493 494 495 496 497 498 499 500 501
            virStoragePoolFree(pool);
        } else {
            vshError(ctl, _("Failed to create pool %s"), name);
            return false;
        }
    }
    return true;
}

/*
 * "pool-define" command
 */
static const vshCmdInfo info_pool_define[] = {
502
    {.name = "help",
503 504
     .data = N_("define an inactive persistent storage pool or modify "
                "an existing persistent one from an XML file")
505 506
    },
    {.name = "desc",
507
     .data = N_("Define or modify a persistent storage pool.")
508 509
    },
    {.name = NULL}
510 511 512
};

static const vshCmdOptDef opts_pool_define[] = {
513
    VIRSH_COMMON_OPT_FILE(N_("file containing an XML pool description")),
514

515
    {.name = NULL}
516 517 518 519 520 521 522 523 524
};

static bool
cmdPoolDefine(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    const char *from = NULL;
    bool ret = true;
    char *buffer;
525
    virshControlPtr priv = ctl->privData;
526

527
    if (vshCommandOptStringReq(ctl, cmd, "file", &from) < 0)
528 529
        return false;

E
Eric Blake 已提交
530
    if (virFileReadAll(from, VSH_MAX_XML_FILE, &buffer) < 0)
531 532
        return false;

533
    pool = virStoragePoolDefineXML(priv->conn, buffer, 0);
534 535 536
    VIR_FREE(buffer);

    if (pool != NULL) {
P
Pino Toscano 已提交
537 538
        vshPrintExtra(ctl, _("Pool %s defined from %s\n"),
                      virStoragePoolGetName(pool), from);
539 540 541 542 543 544 545 546 547 548 549 550
        virStoragePoolFree(pool);
    } else {
        vshError(ctl, _("Failed to define pool from %s"), from);
        ret = false;
    }
    return ret;
}

/*
 * "pool-define-as" command
 */
static const vshCmdInfo info_pool_define_as[] = {
551 552 553 554 555 556 557
    {.name = "help",
     .data = N_("define a pool from a set of args")
    },
    {.name = "desc",
     .data = N_("Define a pool.")
    },
    {.name = NULL}
558 559 560 561 562 563 564 565 566
};

static bool
cmdPoolDefineAs(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    const char *name;
    char *xml;
    bool printXML = vshCommandOptBool(cmd, "print-xml");
567
    virshControlPtr priv = ctl->privData;
568

569
    if (!virshBuildPoolXML(ctl, cmd, &name, &xml))
570 571 572 573 574 575
        return false;

    if (printXML) {
        vshPrint(ctl, "%s", xml);
        VIR_FREE(xml);
    } else {
576
        pool = virStoragePoolDefineXML(priv->conn, xml, 0);
577 578 579
        VIR_FREE(xml);

        if (pool != NULL) {
P
Pino Toscano 已提交
580
            vshPrintExtra(ctl, _("Pool %s defined\n"), name);
581 582 583 584 585 586 587 588 589 590 591 592 593
            virStoragePoolFree(pool);
        } else {
            vshError(ctl, _("Failed to define pool %s"), name);
            return false;
        }
    }
    return true;
}

/*
 * "pool-build" command
 */
static const vshCmdInfo info_pool_build[] = {
594 595 596 597 598 599 600
    {.name = "help",
     .data = N_("build a pool")
    },
    {.name = "desc",
     .data = N_("Build a given pool.")
    },
    {.name = NULL}
601 602 603
};

static const vshCmdOptDef opts_pool_build[] = {
604
    VIRSH_COMMON_OPT_POOL_FULL(0),
605 606
    VIRSH_COMMON_OPT_POOL_NO_OVERWRITE,
    VIRSH_COMMON_OPT_POOL_OVERWRITE,
607

608
    {.name = NULL}
609 610 611 612 613 614 615 616 617 618
};

static bool
cmdPoolBuild(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    const char *name;
    unsigned int flags = 0;

619
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", &name)))
620 621
        return false;

622
    if (vshCommandOptBool(cmd, "no-overwrite"))
623 624
        flags |= VIR_STORAGE_POOL_BUILD_NO_OVERWRITE;

625
    if (vshCommandOptBool(cmd, "overwrite"))
626 627 628
        flags |= VIR_STORAGE_POOL_BUILD_OVERWRITE;

    if (virStoragePoolBuild(pool, flags) == 0) {
P
Pino Toscano 已提交
629
        vshPrintExtra(ctl, _("Pool %s built\n"), name);
630 631 632 633 634 635 636 637 638 639 640 641 642 643
    } else {
        vshError(ctl, _("Failed to build pool %s"), name);
        ret = false;
    }

    virStoragePoolFree(pool);

    return ret;
}

/*
 * "pool-destroy" command
 */
static const vshCmdInfo info_pool_destroy[] = {
644 645 646 647 648 649 650
    {.name = "help",
     .data = N_("destroy (stop) a pool")
    },
    {.name = "desc",
     .data = N_("Forcefully stop a given pool. Raw data in the pool is untouched")
    },
    {.name = NULL}
651 652 653
};

static const vshCmdOptDef opts_pool_destroy[] = {
654
    VIRSH_COMMON_OPT_POOL_FULL(VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE),
655

656
    {.name = NULL}
657 658 659 660 661 662 663 664 665
};

static bool
cmdPoolDestroy(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    const char *name;

666
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", &name)))
667 668 669
        return false;

    if (virStoragePoolDestroy(pool) == 0) {
P
Pino Toscano 已提交
670
        vshPrintExtra(ctl, _("Pool %s destroyed\n"), name);
671 672 673 674 675 676 677 678 679 680 681 682 683
    } else {
        vshError(ctl, _("Failed to destroy pool %s"), name);
        ret = false;
    }

    virStoragePoolFree(pool);
    return ret;
}

/*
 * "pool-delete" command
 */
static const vshCmdInfo info_pool_delete[] = {
684 685 686 687 688 689 690
    {.name = "help",
     .data = N_("delete a pool")
    },
    {.name = "desc",
     .data = N_("Delete a given pool.")
    },
    {.name = NULL}
691 692 693
};

static const vshCmdOptDef opts_pool_delete[] = {
694
    VIRSH_COMMON_OPT_POOL_FULL(VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE),
695

696
    {.name = NULL}
697 698 699 700 701 702 703 704 705
};

static bool
cmdPoolDelete(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    const char *name;

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

    if (virStoragePoolDelete(pool, 0) == 0) {
P
Pino Toscano 已提交
710
        vshPrintExtra(ctl, _("Pool %s deleted\n"), name);
711 712 713 714 715 716 717 718 719 720 721 722 723
    } else {
        vshError(ctl, _("Failed to delete pool %s"), name);
        ret = false;
    }

    virStoragePoolFree(pool);
    return ret;
}

/*
 * "pool-refresh" command
 */
static const vshCmdInfo info_pool_refresh[] = {
724 725 726 727 728 729 730
    {.name = "help",
     .data = N_("refresh a pool")
    },
    {.name = "desc",
     .data = N_("Refresh a given pool.")
    },
    {.name = NULL}
731 732 733
};

static const vshCmdOptDef opts_pool_refresh[] = {
734
    VIRSH_COMMON_OPT_POOL_FULL(0),
735

736
    {.name = NULL}
737 738 739 740 741 742 743 744 745
};

static bool
cmdPoolRefresh(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    const char *name;

746
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", &name)))
747 748 749
        return false;

    if (virStoragePoolRefresh(pool, 0) == 0) {
P
Pino Toscano 已提交
750
        vshPrintExtra(ctl, _("Pool %s refreshed\n"), name);
751 752 753 754 755 756 757 758 759 760 761 762 763
    } else {
        vshError(ctl, _("Failed to refresh pool %s"), name);
        ret = false;
    }
    virStoragePoolFree(pool);

    return ret;
}

/*
 * "pool-dumpxml" command
 */
static const vshCmdInfo info_pool_dumpxml[] = {
764 765 766 767 768 769 770
    {.name = "help",
     .data = N_("pool information in XML")
    },
    {.name = "desc",
     .data = N_("Output the pool information as an XML dump to stdout.")
    },
    {.name = NULL}
771 772 773
};

static const vshCmdOptDef opts_pool_dumpxml[] = {
774
    VIRSH_COMMON_OPT_POOL_FULL(0),
775

776 777 778 779 780
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("show inactive defined XML")
    },
    {.name = NULL}
781 782 783 784 785 786 787 788 789 790 791 792 793 794
};

static bool
cmdPoolDumpXML(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    bool inactive = vshCommandOptBool(cmd, "inactive");
    unsigned int flags = 0;
    char *dump;

    if (inactive)
        flags |= VIR_STORAGE_XML_INACTIVE;

795
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", NULL)))
796 797 798 799 800 801 802 803 804 805 806 807 808 809
        return false;

    dump = virStoragePoolGetXMLDesc(pool, flags);
    if (dump != NULL) {
        vshPrint(ctl, "%s", dump);
        VIR_FREE(dump);
    } else {
        ret = false;
    }

    virStoragePoolFree(pool);
    return ret;
}

810
static int
811
virshStoragePoolSorter(const void *a, const void *b)
812 813 814 815 816 817 818 819 820 821 822 823 824 825
{
    virStoragePoolPtr *pa = (virStoragePoolPtr *) a;
    virStoragePoolPtr *pb = (virStoragePoolPtr *) b;

    if (*pa && !*pb)
        return -1;

    if (!*pa)
        return *pb != NULL;

    return vshStrcasecmp(virStoragePoolGetName(*pa),
                         virStoragePoolGetName(*pb));
}

826
struct virshStoragePoolList {
827 828 829
    virStoragePoolPtr *pools;
    size_t npools;
};
830
typedef struct virshStoragePoolList *virshStoragePoolListPtr;
831 832

static void
833
virshStoragePoolListFree(virshStoragePoolListPtr list)
834
{
835
    size_t i;
836 837 838 839 840 841 842 843 844 845 846

    if (list && list->pools) {
        for (i = 0; i < list->npools; i++) {
            if (list->pools[i])
                virStoragePoolFree(list->pools[i]);
        }
        VIR_FREE(list->pools);
    }
    VIR_FREE(list);
}

847 848 849
static virshStoragePoolListPtr
virshStoragePoolListCollect(vshControl *ctl,
                            unsigned int flags)
850
{
851
    virshStoragePoolListPtr list = vshMalloc(ctl, sizeof(*list));
852
    size_t i;
853 854 855 856 857 858 859 860 861 862
    int ret;
    char **names = NULL;
    virStoragePoolPtr pool;
    bool success = false;
    size_t deleted = 0;
    int persistent;
    int autostart;
    int nActivePools = 0;
    int nInactivePools = 0;
    int nAllPools = 0;
863
    virshControlPtr priv = ctl->privData;
864

865
    /* try the list with flags support (0.10.2 and later) */
866
    if ((ret = virConnectListAllStoragePools(priv->conn,
867 868 869 870 871 872 873
                                             &list->pools,
                                             flags)) >= 0) {
        list->npools = ret;
        goto finished;
    }

    /* check if the command is actually supported */
874
    if (last_error && last_error->code == VIR_ERR_NO_SUPPORT)
875 876 877 878 879 880 881
        goto fallback;

    if (last_error && last_error->code ==  VIR_ERR_INVALID_ARG) {
        /* try the new API again but mask non-guaranteed flags */
        unsigned int newflags = flags & (VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE |
                                         VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE);
        vshResetLibvirtError();
882
        if ((ret = virConnectListAllStoragePools(priv->conn, &list->pools,
883 884 885 886 887 888 889 890 891 892 893
                                                 newflags)) >= 0) {
            list->npools = ret;
            goto filter;
        }
    }

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


894
 fallback:
895
    /* fall back to old method (0.10.1 and older) */
896 897 898
    vshResetLibvirtError();

    /* There is no way to get the pool type */
E
Eric Blake 已提交
899
    if (VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_POOL_TYPE)) {
900 901 902 903 904 905
        vshError(ctl, "%s", _("Filtering using --type is not supported "
                              "by this libvirt"));
        goto cleanup;
    }

    /* Get the number of active pools */
E
Eric Blake 已提交
906 907
    if (!VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ACTIVE) ||
        VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE)) {
908
        if ((nActivePools = virConnectNumOfStoragePools(priv->conn)) < 0) {
909 910 911 912 913 914
            vshError(ctl, "%s", _("Failed to get the number of active pools "));
            goto cleanup;
        }
    }

    /* Get the number of inactive pools */
E
Eric Blake 已提交
915 916
    if (!VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ACTIVE) ||
        VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE)) {
917
        if ((nInactivePools = virConnectNumOfDefinedStoragePools(priv->conn)) < 0) {
918 919 920 921 922 923 924 925 926 927 928 929 930
            vshError(ctl, "%s", _("Failed to get the number of inactive pools"));
            goto cleanup;
        }
    }

    nAllPools = nActivePools + nInactivePools;

    if (nAllPools == 0)
        return list;

    names = vshMalloc(ctl, sizeof(char *) * nAllPools);

    /* Retrieve a list of active storage pool names */
E
Eric Blake 已提交
931 932
    if (!VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ACTIVE) ||
        VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE)) {
933
        if (virConnectListStoragePools(priv->conn,
934 935 936 937 938 939 940
                                       names, nActivePools) < 0) {
            vshError(ctl, "%s", _("Failed to list active pools"));
            goto cleanup;
        }
    }

    /* Add the inactive storage pools to the end of the name list */
E
Eric Blake 已提交
941 942
    if (!VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ACTIVE) ||
        VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE)) {
943
        if (virConnectListDefinedStoragePools(priv->conn,
944 945 946 947 948 949 950 951 952 953 954 955
                                              &names[nActivePools],
                                              nInactivePools) < 0) {
            vshError(ctl, "%s", _("Failed to list inactive pools"));
            goto cleanup;
        }
    }

    list->pools = vshMalloc(ctl, sizeof(virStoragePoolPtr) * (nAllPools));
    list->npools = 0;

    /* get active pools */
    for (i = 0; i < nActivePools; i++) {
956
        if (!(pool = virStoragePoolLookupByName(priv->conn, names[i])))
957 958 959 960 961 962
            continue;
        list->pools[list->npools++] = pool;
    }

    /* get inactive pools */
    for (i = 0; i < nInactivePools; i++) {
963
        if (!(pool = virStoragePoolLookupByName(priv->conn, names[i])))
964 965 966 967 968 969 970
            continue;
        list->pools[list->npools++] = pool;
    }

    /* truncate pools that weren't found */
    deleted = nAllPools - list->npools;

971
 filter:
972 973 974 975 976
    /* filter list the list if the list was acquired by fallback means */
    for (i = 0; i < list->npools; i++) {
        pool = list->pools[i];

        /* persistence filter */
E
Eric Blake 已提交
977
        if (VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_PERSISTENT)) {
978 979 980 981 982
            if ((persistent = virStoragePoolIsPersistent(pool)) < 0) {
                vshError(ctl, "%s", _("Failed to get pool persistence info"));
                goto cleanup;
            }

E
Eric Blake 已提交
983 984
            if (!((VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_PERSISTENT) && persistent) ||
                  (VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_TRANSIENT) && !persistent)))
985 986 987 988
                goto remove_entry;
        }

        /* autostart filter */
E
Eric Blake 已提交
989
        if (VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_AUTOSTART)) {
990 991 992 993 994
            if (virStoragePoolGetAutostart(pool, &autostart) < 0) {
                vshError(ctl, "%s", _("Failed to get pool autostart state"));
                goto cleanup;
            }

E
Eric Blake 已提交
995 996
            if (!((VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_AUTOSTART) && autostart) ||
                  (VSH_MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_NO_AUTOSTART) && !autostart)))
997 998 999 1000 1001 1002
                goto remove_entry;
        }

        /* the pool matched all filters, it may stay */
        continue;

1003
 remove_entry:
1004 1005 1006 1007 1008 1009
        /* the pool has to be removed as it failed one of the filters */
        virStoragePoolFree(list->pools[i]);
        list->pools[i] = NULL;
        deleted++;
    }

1010
 finished:
1011 1012 1013
    /* sort the list */
    if (list->pools && list->npools)
        qsort(list->pools, list->npools,
1014
              sizeof(*list->pools), virshStoragePoolSorter);
1015 1016 1017 1018 1019 1020 1021

    /* truncate the list if filter simulation deleted entries */
    if (deleted)
        VIR_SHRINK_N(list->pools, list->npools, deleted);

    success = true;

1022
 cleanup:
1023 1024 1025 1026
    for (i = 0; i < nAllPools; i++)
        VIR_FREE(names[i]);

    if (!success) {
1027
        virshStoragePoolListFree(list);
1028 1029 1030 1031 1032 1033 1034
        list = NULL;
    }

    VIR_FREE(names);
    return list;
}

1035

1036 1037
VIR_ENUM_DECL(virshStoragePoolState)
VIR_ENUM_IMPL(virshStoragePoolState,
1038 1039 1040 1041 1042 1043 1044 1045
              VIR_STORAGE_POOL_STATE_LAST,
              N_("inactive"),
              N_("building"),
              N_("running"),
              N_("degraded"),
              N_("inaccessible"))

static const char *
1046
virshStoragePoolStateToString(int state)
1047
{
1048
    const char *str = virshStoragePoolStateTypeToString(state);
1049 1050 1051 1052
    return str ? _(str) : _("unknown");
}


1053 1054 1055 1056
/*
 * "pool-list" command
 */
static const vshCmdInfo info_pool_list[] = {
1057 1058 1059 1060 1061 1062 1063
    {.name = "help",
     .data = N_("list pools")
    },
    {.name = "desc",
     .data = N_("Returns list of pools.")
    },
    {.name = NULL}
1064 1065 1066
};

static const vshCmdOptDef opts_pool_list[] = {
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
    {.name = "inactive",
     .type = VSH_OT_BOOL,
     .help = N_("list inactive pools")
    },
    {.name = "all",
     .type = VSH_OT_BOOL,
     .help = N_("list inactive & active pools")
    },
    {.name = "transient",
     .type = VSH_OT_BOOL,
     .help = N_("list transient pools")
    },
    {.name = "persistent",
     .type = VSH_OT_BOOL,
     .help = N_("list persistent pools")
    },
    {.name = "autostart",
     .type = VSH_OT_BOOL,
     .help = N_("list pools with autostart enabled")
    },
    {.name = "no-autostart",
     .type = VSH_OT_BOOL,
     .help = N_("list pools with autostart disabled")
    },
    {.name = "type",
     .type = VSH_OT_STRING,
     .help = N_("only list pool of specified type(s) (if supported)")
    },
    {.name = "details",
     .type = VSH_OT_BOOL,
     .help = N_("display extended details for pools")
    },
1099 1100 1101 1102
    {.name = "uuid",
     .type = VSH_OT_BOOL,
     .help = N_("list UUID of active pools only")
    },
1103 1104 1105 1106
    {.name = "name",
     .type = VSH_OT_BOOL,
     .help = N_("list name of active pools only")
    },
1107
    {.name = NULL}
1108 1109 1110 1111 1112 1113
};

static bool
cmdPoolList(vshControl *ctl, const vshCmd *cmd ATTRIBUTE_UNUSED)
{
    virStoragePoolInfo info;
1114
    size_t i;
1115
    bool ret = false;
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    size_t stringLength = 0, nameStrLength = 0;
    size_t autostartStrLength = 0, persistStrLength = 0;
    size_t stateStrLength = 0, capStrLength = 0;
    size_t allocStrLength = 0, availStrLength = 0;
    struct poolInfoText {
        char *state;
        char *autostart;
        char *persistent;
        char *capacity;
        char *allocation;
        char *available;
    };
    struct poolInfoText *poolInfoTexts = NULL;
1129
    unsigned int flags = VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE;
1130
    virshStoragePoolListPtr list = NULL;
1131
    const char *type = NULL;
1132
    bool details = vshCommandOptBool(cmd, "details");
1133
    bool inactive, all;
1134
    bool uuid = false;
1135
    bool name = false;
1136
    char *outputStr = NULL;
1137

1138 1139
    inactive = vshCommandOptBool(cmd, "inactive");
    all = vshCommandOptBool(cmd, "all");
1140

1141 1142
    if (inactive)
        flags = VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE;
1143

1144 1145 1146
    if (all)
        flags = VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE |
                VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE;
1147

1148 1149
    if (vshCommandOptBool(cmd, "autostart"))
        flags |= VIR_CONNECT_LIST_STORAGE_POOLS_AUTOSTART;
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159
    if (vshCommandOptBool(cmd, "no-autostart"))
        flags |= VIR_CONNECT_LIST_STORAGE_POOLS_NO_AUTOSTART;

    if (vshCommandOptBool(cmd, "persistent"))
        flags |= VIR_CONNECT_LIST_STORAGE_POOLS_PERSISTENT;

    if (vshCommandOptBool(cmd, "transient"))
        flags |= VIR_CONNECT_LIST_STORAGE_POOLS_TRANSIENT;

1160 1161 1162
    if (vshCommandOptBool(cmd, "uuid"))
        uuid = true;

1163 1164 1165
    if (vshCommandOptBool(cmd, "name"))
        name = true;

1166
    if (vshCommandOptStringReq(ctl, cmd, "type", &type) < 0)
1167
        return false;
1168

1169
    VSH_EXCLUSIVE_OPTIONS("details", "uuid");
1170
    VSH_EXCLUSIVE_OPTIONS("details", "name");
1171

1172 1173 1174 1175 1176
    if (type) {
        int poolType = -1;
        char **poolTypes = NULL;
        int npoolTypes = 0;

1177 1178
        if ((npoolTypes = vshStringToArray(type, &poolTypes)) < 0)
            return false;
1179 1180 1181

        for (i = 0; i < npoolTypes; i++) {
            if ((poolType = virStoragePoolTypeFromString(poolTypes[i])) < 0) {
1182
                vshError(ctl, _("Invalid pool type '%s'"), poolTypes[i]);
1183
                virStringListFree(poolTypes);
1184 1185 1186
                return false;
            }

1187
            switch ((virStoragePoolType) poolType) {
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
            case VIR_STORAGE_POOL_DIR:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_DIR;
                break;
            case VIR_STORAGE_POOL_FS:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_FS;
                break;
            case VIR_STORAGE_POOL_NETFS:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_NETFS;
                break;
            case VIR_STORAGE_POOL_LOGICAL:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_LOGICAL;
                break;
            case VIR_STORAGE_POOL_DISK:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_DISK;
                break;
            case VIR_STORAGE_POOL_ISCSI:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_ISCSI;
                break;
1206 1207 1208
            case VIR_STORAGE_POOL_ISCSI_DIRECT:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_ISCSI;
                break;
1209 1210 1211 1212 1213 1214 1215 1216 1217
            case VIR_STORAGE_POOL_SCSI:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_SCSI;
                break;
            case VIR_STORAGE_POOL_MPATH:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_MPATH;
                break;
            case VIR_STORAGE_POOL_RBD:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_RBD;
                break;
1218 1219 1220 1221 1222 1223
            case VIR_STORAGE_POOL_SHEEPDOG:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_SHEEPDOG;
                break;
            case VIR_STORAGE_POOL_GLUSTER:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER;
                break;
R
Roman Bogorodskiy 已提交
1224 1225 1226
            case VIR_STORAGE_POOL_ZFS:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_ZFS;
                break;
1227 1228 1229
            case VIR_STORAGE_POOL_VSTORAGE:
                flags |= VIR_CONNECT_LIST_STORAGE_POOLS_VSTORAGE;
                break;
1230
            case VIR_STORAGE_POOL_LAST:
1231 1232
                break;
            }
1233
        }
1234
        virStringListFree(poolTypes);
1235 1236
    }

1237
    if (!(list = virshStoragePoolListCollect(ctl, flags)))
1238 1239 1240
        goto cleanup;

    poolInfoTexts = vshCalloc(ctl, list->npools, sizeof(*poolInfoTexts));
1241 1242

    /* Collect the storage pool information for display */
1243
    for (i = 0; i < list->npools; i++) {
1244 1245 1246
        int autostart = 0, persistent = 0;

        /* Retrieve the autostart status of the pool */
1247
        if (virStoragePoolGetAutostart(list->pools[i], &autostart) < 0)
1248 1249 1250 1251 1252 1253 1254
            poolInfoTexts[i].autostart = vshStrdup(ctl, _("no autostart"));
        else
            poolInfoTexts[i].autostart = vshStrdup(ctl, autostart ?
                                                    _("yes") : _("no"));

        /* Retrieve the persistence status of the pool */
        if (details) {
1255
            persistent = virStoragePoolIsPersistent(list->pools[i]);
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
            vshDebug(ctl, VSH_ERR_DEBUG, "Persistent flag value: %d\n",
                     persistent);
            if (persistent < 0)
                poolInfoTexts[i].persistent = vshStrdup(ctl, _("unknown"));
            else
                poolInfoTexts[i].persistent = vshStrdup(ctl, persistent ?
                                                         _("yes") : _("no"));

            /* Keep the length of persistent string if longest so far */
            stringLength = strlen(poolInfoTexts[i].persistent);
            if (stringLength > persistStrLength)
                persistStrLength = stringLength;
        }

        /* Collect further extended information about the pool */
1271
        if (virStoragePoolGetInfo(list->pools[i], &info) != 0) {
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
            /* Something went wrong retrieving pool info, cope with it */
            vshError(ctl, "%s", _("Could not retrieve pool information"));
            poolInfoTexts[i].state = vshStrdup(ctl, _("unknown"));
            if (details) {
                poolInfoTexts[i].capacity = vshStrdup(ctl, _("unknown"));
                poolInfoTexts[i].allocation = vshStrdup(ctl, _("unknown"));
                poolInfoTexts[i].available = vshStrdup(ctl, _("unknown"));
            }
        } else {
            /* Decide which state string to display */
            if (details) {
1283
                const char *state = virshStoragePoolStateToString(info.state);
1284 1285

                poolInfoTexts[i].state = vshStrdup(ctl, state);
1286 1287 1288 1289 1290 1291 1292

                /* Create the pool size related strings */
                if (info.state == VIR_STORAGE_POOL_RUNNING ||
                    info.state == VIR_STORAGE_POOL_DEGRADED) {
                    double val;
                    const char *unit;

E
Eric Blake 已提交
1293
                    val = vshPrettyCapacity(info.capacity, &unit);
1294 1295 1296
                    if (virAsprintf(&poolInfoTexts[i].capacity,
                                    "%.2lf %s", val, unit) < 0)
                        goto cleanup;
1297

E
Eric Blake 已提交
1298
                    val = vshPrettyCapacity(info.allocation, &unit);
1299 1300 1301
                    if (virAsprintf(&poolInfoTexts[i].allocation,
                                    "%.2lf %s", val, unit) < 0)
                        goto cleanup;
1302

E
Eric Blake 已提交
1303
                    val = vshPrettyCapacity(info.available, &unit);
1304 1305 1306
                    if (virAsprintf(&poolInfoTexts[i].available,
                                    "%.2lf %s", val, unit) < 0)
                        goto cleanup;
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
                } else {
                    /* Capacity related information isn't available */
                    poolInfoTexts[i].capacity = vshStrdup(ctl, _("-"));
                    poolInfoTexts[i].allocation = vshStrdup(ctl, _("-"));
                    poolInfoTexts[i].available = vshStrdup(ctl, _("-"));
                }

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

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

                /* Keep the length of available string if longest so far */
                stringLength = strlen(poolInfoTexts[i].available);
                if (stringLength > availStrLength)
                    availStrLength = stringLength;
            } else {
                /* --details option was not specified, only active/inactive
1330 1331
                 * state strings are used */
                if (virStoragePoolIsActive(list->pools[i]))
1332
                    poolInfoTexts[i].state = vshStrdup(ctl, _("active"));
1333 1334 1335
                else
                    poolInfoTexts[i].state = vshStrdup(ctl, _("inactive"));
           }
1336 1337 1338
        }

        /* Keep the length of name string if longest so far */
1339
        stringLength = strlen(virStoragePoolGetName(list->pools[i]));
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        if (stringLength > nameStrLength)
            nameStrLength = stringLength;

        /* Keep the length of state string if longest so far */
        stringLength = strlen(poolInfoTexts[i].state);
        if (stringLength > stateStrLength)
            stateStrLength = stringLength;

        /* Keep the length of autostart string if longest so far */
        stringLength = strlen(poolInfoTexts[i].autostart);
        if (stringLength > autostartStrLength)
            autostartStrLength = stringLength;
    }

    /* If the --details option wasn't selected, we output the pool
     * 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) {
1361
        if (uuid || name) {
1362
            for (i = 0; i < list->npools; i++) {
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
                if (uuid) {
                    char uuid_str[VIR_UUID_STRING_BUFLEN];
                    virStoragePoolGetUUIDString(list->pools[i], uuid_str);
                    vshPrint(ctl, "%-36s%c", uuid_str, name ? ' ': '\n');
                }
                if (name) {
                    const char *name_str =
                        virStoragePoolGetName(list->pools[i]);
                    vshPrint(ctl, "%-20s\n", name_str);
                }
1373 1374 1375 1376 1377
            }
            ret = true;
            goto cleanup;
        }

1378
        /* Output old style header */
1379
        vshPrintExtra(ctl, " %-20s %-10s %-10s\n", _("Name"), _("State"),
1380
                      _("Autostart"));
1381
        vshPrintExtra(ctl, "-------------------------------------------\n");
1382 1383

        /* Output old style pool info */
1384
        for (i = 0; i < list->npools; i++) {
1385
            const char *name_str = virStoragePoolGetName(list->pools[i]);
1386
            vshPrint(ctl, " %-20s %-10s %-10s\n",
1387
                 name_str,
1388 1389 1390 1391 1392
                 poolInfoTexts[i].state,
                 poolInfoTexts[i].autostart);
        }

        /* Cleanup and return */
1393
        ret = true;
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
        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 state header string if it's longest */
    stringLength = strlen(_("State"));
    if (stringLength > stateStrLength)
        stateStrLength = stringLength;

    /* Use the length of autostart header string if it's longest */
    stringLength = strlen(_("Autostart"));
    if (stringLength > autostartStrLength)
        autostartStrLength = stringLength;

    /* Use the length of persistent header string if it's longest */
    stringLength = strlen(_("Persistent"));
    if (stringLength > persistStrLength)
        persistStrLength = 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;

    /* Use the length of available header string if it's longest */
    stringLength = strlen(_("Available"));
    if (stringLength > availStrLength)
        availStrLength = stringLength;

    /* Display the string lengths for debugging. */
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest name string = %lu chars\n",
             (unsigned long) nameStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest state string = %lu chars\n",
             (unsigned long) stateStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest autostart string = %lu chars\n",
             (unsigned long) autostartStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest persistent string = %lu chars\n",
             (unsigned long) persistStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest capacity string = %lu chars\n",
             (unsigned long) capStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest allocation string = %lu chars\n",
             (unsigned long) allocStrLength);
    vshDebug(ctl, VSH_ERR_DEBUG, "Longest available string = %lu chars\n",
             (unsigned long) availStrLength);

    /* Create the output template.  Each column is sized according to
     * the longest string.
     */
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
    if (virAsprintf(&outputStr,
                    " %%-%lus  %%-%lus  %%-%lus  %%-%lus  %%%lus  %%%lus  %%%lus\n",
                    (unsigned long) nameStrLength,
                    (unsigned long) stateStrLength,
                    (unsigned long) autostartStrLength,
                    (unsigned long) persistStrLength,
                    (unsigned long) capStrLength,
                    (unsigned long) allocStrLength,
                    (unsigned long) availStrLength) < 0)
        goto cleanup;
1463 1464

    /* Display the header */
1465 1466 1467
    vshPrintExtra(ctl, outputStr, _("Name"), _("State"), _("Autostart"),
                  _("Persistent"), _("Capacity"), _("Allocation"),
                  _("Available"));
1468 1469 1470
    for (i = nameStrLength + stateStrLength + autostartStrLength
                           + persistStrLength + capStrLength
                           + allocStrLength + availStrLength
1471
                           + 14; i > 0; i--)
1472 1473 1474 1475
        vshPrintExtra(ctl, "-");
    vshPrintExtra(ctl, "\n");

    /* Display the pool info rows */
1476
    for (i = 0; i < list->npools; i++) {
1477
        vshPrint(ctl, outputStr,
1478
                 virStoragePoolGetName(list->pools[i]),
1479 1480 1481 1482 1483 1484 1485 1486 1487
                 poolInfoTexts[i].state,
                 poolInfoTexts[i].autostart,
                 poolInfoTexts[i].persistent,
                 poolInfoTexts[i].capacity,
                 poolInfoTexts[i].allocation,
                 poolInfoTexts[i].available);
    }

    /* Cleanup and return */
1488
    ret = true;
1489

1490
 cleanup:
1491
    VIR_FREE(outputStr);
1492 1493 1494 1495 1496 1497 1498 1499 1500
    if (list && list->npools) {
        for (i = 0; i < list->npools; i++) {
            VIR_FREE(poolInfoTexts[i].state);
            VIR_FREE(poolInfoTexts[i].autostart);
            VIR_FREE(poolInfoTexts[i].persistent);
            VIR_FREE(poolInfoTexts[i].capacity);
            VIR_FREE(poolInfoTexts[i].allocation);
            VIR_FREE(poolInfoTexts[i].available);
        }
1501 1502 1503
    }
    VIR_FREE(poolInfoTexts);

1504
    virshStoragePoolListFree(list);
1505
    return ret;
1506 1507 1508 1509 1510 1511
}

/*
 * "find-storage-pool-sources-as" command
 */
static const vshCmdInfo info_find_storage_pool_sources_as[] = {
1512 1513 1514 1515 1516 1517 1518
    {.name = "help",
     .data = N_("find potential storage pool sources")
    },
    {.name = "desc",
     .data = N_("Returns XML <sources> document.")
    },
    {.name = NULL}
1519 1520 1521
};

static const vshCmdOptDef opts_find_storage_pool_sources_as[] = {
1522 1523 1524 1525 1526 1527
    {.name = "type",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("type of storage pool sources to find")
    },
    {.name = "host",
1528
     .type = VSH_OT_STRING,
1529 1530 1531
     .help = N_("optional host to query")
    },
    {.name = "port",
1532
     .type = VSH_OT_STRING,
1533 1534 1535
     .help = N_("optional port to query")
    },
    {.name = "initiator",
1536
     .type = VSH_OT_STRING,
1537 1538 1539
     .help = N_("optional initiator IQN to use for query")
    },
    {.name = NULL}
1540 1541 1542 1543 1544 1545 1546 1547 1548
};

static bool
cmdPoolDiscoverSourcesAs(vshControl * ctl, const vshCmd * cmd ATTRIBUTE_UNUSED)
{
    const char *type = NULL, *host = NULL;
    char *srcSpec = NULL;
    char *srcList;
    const char *initiator = NULL;
1549
    virshControlPtr priv = ctl->privData;
1550

1551 1552 1553
    if (vshCommandOptStringReq(ctl, cmd, "type", &type) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "host", &host) < 0 ||
        vshCommandOptStringReq(ctl, cmd, "initiator", &initiator) < 0)
1554 1555 1556 1557 1558 1559
        return false;

    if (host) {
        const char *port = NULL;
        virBuffer buf = VIR_BUFFER_INITIALIZER;

1560
        if (vshCommandOptStringReq(ctl, cmd, "port", &port) < 0) {
1561 1562 1563 1564 1565
            vshError(ctl, "%s", _("missing argument"));
            virBufferFreeAndReset(&buf);
            return false;
        }
        virBufferAddLit(&buf, "<source>\n");
1566 1567
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<host name='%s'", host);
1568 1569 1570 1571
        if (port)
            virBufferAsprintf(&buf, " port='%s'", port);
        virBufferAddLit(&buf, "/>\n");
        if (initiator) {
1572 1573 1574 1575 1576
            virBufferAddLit(&buf, "<initiator>\n");
            virBufferAdjustIndent(&buf, 2);
            virBufferAsprintf(&buf, "<iqn name='%s'/>\n", initiator);
            virBufferAdjustIndent(&buf, -2);
            virBufferAddLit(&buf, "</initiator>\n");
1577
        }
1578
        virBufferAdjustIndent(&buf, -2);
1579 1580 1581 1582 1583 1584 1585 1586
        virBufferAddLit(&buf, "</source>\n");
        if (virBufferError(&buf)) {
            vshError(ctl, "%s", _("Out of memory"));
            return false;
        }
        srcSpec = virBufferContentAndReset(&buf);
    }

1587
    srcList = virConnectFindStoragePoolSources(priv->conn, type, srcSpec, 0);
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
    VIR_FREE(srcSpec);
    if (srcList == NULL) {
        vshError(ctl, _("Failed to find any %s pool sources"), type);
        return false;
    }
    vshPrint(ctl, "%s", srcList);
    VIR_FREE(srcList);

    return true;
}

/*
 * "find-storage-pool-sources" command
 */
static const vshCmdInfo info_find_storage_pool_sources[] = {
1603 1604 1605 1606 1607 1608 1609
    {.name = "help",
     .data = N_("discover potential storage pool sources")
    },
    {.name = "desc",
     .data = N_("Returns XML <sources> document.")
    },
    {.name = NULL}
1610 1611 1612
};

static const vshCmdOptDef opts_find_storage_pool_sources[] = {
1613 1614 1615 1616 1617 1618
    {.name = "type",
     .type = VSH_OT_DATA,
     .flags = VSH_OFLAG_REQ,
     .help = N_("type of storage pool sources to discover")
    },
    {.name = "srcSpec",
1619
     .type = VSH_OT_STRING,
1620 1621 1622
     .help = N_("optional file of source xml to query for pools")
    },
    {.name = NULL}
1623 1624 1625 1626 1627 1628 1629
};

static bool
cmdPoolDiscoverSources(vshControl * ctl, const vshCmd * cmd ATTRIBUTE_UNUSED)
{
    const char *type = NULL, *srcSpecFile = NULL;
    char *srcSpec = NULL, *srcList;
1630
    virshControlPtr priv = ctl->privData;
1631

1632
    if (vshCommandOptStringReq(ctl, cmd, "type", &type) < 0)
1633 1634
        return false;

1635
    if (vshCommandOptStringReq(ctl, cmd, "srcSpec", &srcSpecFile) < 0)
1636 1637
        return false;

E
Eric Blake 已提交
1638 1639
    if (srcSpecFile && virFileReadAll(srcSpecFile, VSH_MAX_XML_FILE,
                                      &srcSpec) < 0)
1640 1641
        return false;

1642
    srcList = virConnectFindStoragePoolSources(priv->conn, type, srcSpec, 0);
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
    VIR_FREE(srcSpec);
    if (srcList == NULL) {
        vshError(ctl, _("Failed to find any %s pool sources"), type);
        return false;
    }
    vshPrint(ctl, "%s", srcList);
    VIR_FREE(srcList);

    return true;
}

/*
 * "pool-info" command
 */
static const vshCmdInfo info_pool_info[] = {
1658 1659 1660 1661 1662 1663 1664
    {.name = "help",
     .data = N_("storage pool information")
    },
    {.name = "desc",
     .data = N_("Returns basic information about the storage pool.")
    },
    {.name = NULL}
1665 1666 1667
};

static const vshCmdOptDef opts_pool_info[] = {
1668
    VIRSH_COMMON_OPT_POOL_FULL(0),
1669

1670 1671 1672 1673
    {.name = "bytes",
     .type = VSH_OT_BOOL,
     .help = N_("Reture pool info in bytes"),
    },
1674
    {.name = NULL}
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
};

static bool
cmdPoolInfo(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolInfo info;
    virStoragePoolPtr pool;
    int autostart = 0;
    int persistent = 0;
    bool ret = true;
1685
    bool bytes = false;
1686 1687
    char uuid[VIR_UUID_STRING_BUFLEN];

1688
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", NULL)))
1689 1690
        return false;

1691 1692
    bytes = vshCommandOptBool(cmd, "bytes");

1693 1694
    vshPrint(ctl, "%-15s %s\n", _("Name:"), virStoragePoolGetName(pool));

1695
    if (virStoragePoolGetUUIDString(pool, &uuid[0]) == 0)
1696 1697 1698 1699 1700
        vshPrint(ctl, "%-15s %s\n", _("UUID:"), uuid);

    if (virStoragePoolGetInfo(pool, &info) == 0) {
        double val;
        const char *unit;
1701
        vshPrint(ctl, "%-15s %s\n", _("State:"),
1702
                 virshStoragePoolStateToString(info.state));
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713

        /* Check and display whether the pool is persistent or not */
        persistent = virStoragePoolIsPersistent(pool);
        vshDebug(ctl, VSH_ERR_DEBUG, "Pool persistent flag value: %d\n",
                 persistent);
        if (persistent < 0)
            vshPrint(ctl, "%-15s %s\n", _("Persistent:"),  _("unknown"));
        else
            vshPrint(ctl, "%-15s %s\n", _("Persistent:"), persistent ? _("yes") : _("no"));

        /* Check and display whether the pool is autostarted or not */
1714
        if (virStoragePoolGetAutostart(pool, &autostart) < 0)
1715 1716 1717 1718 1719 1720
            vshPrint(ctl, "%-15s %s\n", _("Autostart:"), _("no autostart"));
        else
            vshPrint(ctl, "%-15s %s\n", _("Autostart:"), autostart ? _("yes") : _("no"));

        if (info.state == VIR_STORAGE_POOL_RUNNING ||
            info.state == VIR_STORAGE_POOL_DEGRADED) {
1721 1722 1723 1724 1725 1726 1727
            if (bytes) {
                vshPrint(ctl, "%-15s %llu\n", _("Capacity:"), info.capacity);
                vshPrint(ctl, "%-15s %llu\n", _("Allocation:"), info.allocation);
                vshPrint(ctl, "%-15s %llu\n", _("Available:"), info.available);
            } else {
                val = vshPrettyCapacity(info.capacity, &unit);
                vshPrint(ctl, "%-15s %2.2lf %s\n", _("Capacity:"), val, unit);
1728

1729 1730
                val = vshPrettyCapacity(info.allocation, &unit);
                vshPrint(ctl, "%-15s %2.2lf %s\n", _("Allocation:"), val, unit);
1731

1732 1733 1734
                val = vshPrettyCapacity(info.available, &unit);
                vshPrint(ctl, "%-15s %2.2lf %s\n", _("Available:"), val, unit);
            }
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
        }
    } else {
        ret = false;
    }

    virStoragePoolFree(pool);
    return ret;
}

/*
 * "pool-name" command
 */
static const vshCmdInfo info_pool_name[] = {
1748 1749 1750 1751 1752 1753 1754
    {.name = "help",
     .data = N_("convert a pool UUID to pool name")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
1755 1756 1757
};

static const vshCmdOptDef opts_pool_name[] = {
1758
    VIRSH_COMMON_OPT_POOL_FULL(0),
1759

1760
    {.name = NULL}
1761 1762 1763 1764 1765 1766 1767
};

static bool
cmdPoolName(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;

1768
    if (!(pool = virshCommandOptPoolBy(ctl, cmd, "pool", NULL, VIRSH_BYUUID)))
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
        return false;

    vshPrint(ctl, "%s\n", virStoragePoolGetName(pool));
    virStoragePoolFree(pool);
    return true;
}

/*
 * "pool-start" command
 */
static const vshCmdInfo info_pool_start[] = {
1780 1781 1782 1783 1784 1785 1786
    {.name = "help",
     .data = N_("start a (previously defined) inactive pool")
    },
    {.name = "desc",
     .data = N_("Start a pool.")
    },
    {.name = NULL}
1787 1788 1789
};

static const vshCmdOptDef opts_pool_start[] = {
1790
    VIRSH_COMMON_OPT_POOL_FULL(VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE),
1791 1792 1793
    VIRSH_COMMON_OPT_POOL_BUILD,
    VIRSH_COMMON_OPT_POOL_NO_OVERWRITE,
    VIRSH_COMMON_OPT_POOL_OVERWRITE,
1794

1795
    {.name = NULL}
1796 1797 1798 1799 1800 1801 1802 1803
};

static bool
cmdPoolStart(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    const char *name = NULL;
1804 1805 1806 1807
    bool build;
    bool overwrite;
    bool no_overwrite;
    unsigned int flags = 0;
1808

1809
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", &name)))
1810 1811
         return false;

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
    build = vshCommandOptBool(cmd, "build");
    overwrite = vshCommandOptBool(cmd, "overwrite");
    no_overwrite = vshCommandOptBool(cmd, "no-overwrite");

    VSH_EXCLUSIVE_OPTIONS_EXPR("overwrite", overwrite,
                               "no-overwrite", no_overwrite);

    if (build)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD;
    if (overwrite)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE;
    if (no_overwrite)
        flags |= VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE;

    if (virStoragePoolCreate(pool, flags) == 0) {
P
Pino Toscano 已提交
1827
        vshPrintExtra(ctl, _("Pool %s started\n"), name);
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    } else {
        vshError(ctl, _("Failed to start pool %s"), name);
        ret = false;
    }

    virStoragePoolFree(pool);
    return ret;
}

/*
 * "pool-undefine" command
 */
static const vshCmdInfo info_pool_undefine[] = {
1841 1842 1843 1844 1845 1846 1847
    {.name = "help",
     .data = N_("undefine an inactive pool")
    },
    {.name = "desc",
     .data = N_("Undefine the configuration for an inactive pool.")
    },
    {.name = NULL}
1848 1849 1850
};

static const vshCmdOptDef opts_pool_undefine[] = {
1851
    VIRSH_COMMON_OPT_POOL_FULL(VIR_CONNECT_LIST_STORAGE_POOLS_PERSISTENT),
1852

1853
    {.name = NULL}
1854 1855 1856 1857 1858 1859 1860 1861 1862
};

static bool
cmdPoolUndefine(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool;
    bool ret = true;
    const char *name;

1863
    if (!(pool = virshCommandOptPool(ctl, cmd, "pool", &name)))
1864 1865 1866
        return false;

    if (virStoragePoolUndefine(pool) == 0) {
P
Pino Toscano 已提交
1867
        vshPrintExtra(ctl, _("Pool %s has been undefined\n"), name);
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
    } else {
        vshError(ctl, _("Failed to undefine pool %s"), name);
        ret = false;
    }

    virStoragePoolFree(pool);
    return ret;
}

/*
 * "pool-uuid" command
 */
static const vshCmdInfo info_pool_uuid[] = {
1881 1882 1883 1884 1885 1886 1887
    {.name = "help",
     .data = N_("convert a pool name to pool UUID")
    },
    {.name = "desc",
     .data = ""
    },
    {.name = NULL}
1888 1889 1890
};

static const vshCmdOptDef opts_pool_uuid[] = {
1891
    VIRSH_COMMON_OPT_POOL_FULL(0),
1892

1893
    {.name = NULL}
1894 1895 1896 1897 1898 1899 1900 1901
};

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

1902
    if (!(pool = virshCommandOptPoolBy(ctl, cmd, "pool", NULL, VIRSH_BYNAME)))
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
        return false;

    if (virStoragePoolGetUUIDString(pool, uuid) != -1)
        vshPrint(ctl, "%s\n", uuid);
    else
        vshError(ctl, "%s", _("failed to get pool UUID"));

    virStoragePoolFree(pool);
    return true;
}

/*
 * "pool-edit" command
 */
static const vshCmdInfo info_pool_edit[] = {
1918 1919 1920 1921 1922 1923 1924
    {.name = "help",
     .data = N_("edit XML configuration for a storage pool")
    },
    {.name = "desc",
     .data = N_("Edit the XML configuration for a storage pool.")
    },
    {.name = NULL}
1925 1926 1927
};

static const vshCmdOptDef opts_pool_edit[] = {
1928
    VIRSH_COMMON_OPT_POOL_FULL(0),
1929

1930
    {.name = NULL}
1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
};

static bool
cmdPoolEdit(vshControl *ctl, const vshCmd *cmd)
{
    bool ret = false;
    virStoragePoolPtr pool = NULL;
    virStoragePoolPtr pool_edited = NULL;
    unsigned int flags = VIR_STORAGE_XML_INACTIVE;
    char *tmp_desc = NULL;
1941
    virshControlPtr priv = ctl->privData;
1942

1943
    pool = virshCommandOptPool(ctl, cmd, "pool", NULL);
1944 1945 1946 1947 1948 1949 1950
    if (pool == NULL)
        goto cleanup;

    /* Some old daemons don't support _INACTIVE flag */
    if (!(tmp_desc = virStoragePoolGetXMLDesc(pool, flags))) {
        if (last_error->code == VIR_ERR_INVALID_ARG) {
            flags &= ~VIR_STORAGE_XML_INACTIVE;
1951
            vshResetLibvirtError();
1952 1953 1954 1955 1956 1957 1958 1959
        } else {
            goto cleanup;
        }
    } else {
        VIR_FREE(tmp_desc);
    }

#define EDIT_GET_XML virStoragePoolGetXMLDesc(pool, flags)
1960 1961 1962 1963 1964 1965
#define EDIT_NOT_CHANGED \
    do { \
        vshPrintExtra(ctl, _("Pool %s XML configuration not changed.\n"), \
                 virStoragePoolGetName(pool)); \
        ret = true; \
        goto edit_cleanup; \
1966
    } while (0)
1967
#define EDIT_DEFINE \
1968
    (pool_edited = virStoragePoolDefineXML(priv->conn, doc_edited, 0))
1969 1970
#include "virsh-edit.c"

1971 1972
    vshPrintExtra(ctl, _("Pool %s XML configuration edited.\n"),
                  virStoragePoolGetName(pool_edited));
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983

    ret = true;

 cleanup:
    if (pool)
        virStoragePoolFree(pool);
    if (pool_edited)
        virStoragePoolFree(pool_edited);

    return ret;
}
1984

1985 1986 1987 1988 1989 1990 1991 1992 1993
/*
 * "pool-event" command
 */
VIR_ENUM_DECL(virshPoolEvent)
VIR_ENUM_IMPL(virshPoolEvent,
              VIR_STORAGE_POOL_EVENT_LAST,
              N_("Defined"),
              N_("Undefined"),
              N_("Started"),
1994 1995 1996
              N_("Stopped"),
              N_("Created"),
              N_("Deleted"))
1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009

static const char *
virshPoolEventToString(int event)
{
    const char *str = virshPoolEventTypeToString(event);
    return str ? _(str) : _("unknown");
}

struct virshPoolEventData {
    vshControl *ctl;
    bool loop;
    bool timestamp;
    int count;
2010
    virshPoolEventCallback *cb;
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
};
typedef struct virshPoolEventData virshPoolEventData;


static void
vshEventLifecyclePrint(virConnectPtr conn ATTRIBUTE_UNUSED,
                       virStoragePoolPtr pool,
                       int event,
                       int detail ATTRIBUTE_UNUSED,
                       void *opaque)
{
    virshPoolEventData *data = opaque;

    if (!data->loop && data->count)
        return;

    if (data->timestamp) {
        char timestamp[VIR_TIME_STRING_BUFLEN];

        if (virTimeStringNowRaw(timestamp) < 0)
            timestamp[0] = '\0';

        vshPrint(data->ctl, _("%s: event 'lifecycle' for storage pool %s: %s\n"),
                 timestamp,
                 virStoragePoolGetName(pool),
                 virshPoolEventToString(event));
    } else {
        vshPrint(data->ctl, _("event 'lifecycle' for storage pool %s: %s\n"),
                 virStoragePoolGetName(pool),
                 virshPoolEventToString(event));
    }

    data->count++;
    if (!data->loop)
        vshEventDone(data->ctl);
}

2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
static void
vshEventGenericPrint(virConnectPtr conn ATTRIBUTE_UNUSED,
                     virStoragePoolPtr pool,
                     void *opaque)
{
    virshPoolEventData *data = opaque;

    if (!data->loop && data->count)
        return;

    if (data->timestamp) {
        char timestamp[VIR_TIME_STRING_BUFLEN];

        if (virTimeStringNowRaw(timestamp) < 0)
            timestamp[0] = '\0';

Y
Yuri Chornoivan 已提交
2064
        vshPrint(data->ctl, _("%s: event '%s' for storage pool %s\n"),
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
                 timestamp,
                 data->cb->name,
                 virStoragePoolGetName(pool));
    } else {
        vshPrint(data->ctl, _("event '%s' for storage pool %s\n"),
                 data->cb->name,
                 virStoragePoolGetName(pool));
    }

    data->count++;
    if (!data->loop)
        vshEventDone(data->ctl);
}

2079
virshPoolEventCallback virshPoolEventCallbacks[] = {
2080 2081 2082 2083
    { "lifecycle",
      VIR_STORAGE_POOL_EVENT_CALLBACK(vshEventLifecyclePrint), },
    { "refresh", vshEventGenericPrint, }
};
2084
verify(VIR_STORAGE_POOL_EVENT_ID_LAST == ARRAY_CARDINALITY(virshPoolEventCallbacks));
2085 2086


2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
static const vshCmdInfo info_pool_event[] = {
    {.name = "help",
     .data = N_("Storage Pool Events")
    },
    {.name = "desc",
     .data = N_("List event types, or wait for storage pool events to occur")
    },
    {.name = NULL}
};

static const vshCmdOptDef opts_pool_event[] = {
    {.name = "pool",
     .type = VSH_OT_STRING,
     .help = N_("filter by storage pool name or uuid")
    },
    {.name = "event",
     .type = VSH_OT_STRING,
2104
     .completer = virshPoolEventNameCompleter,
2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141
     .help = N_("which event type to wait for")
    },
    {.name = "loop",
     .type = VSH_OT_BOOL,
     .help = N_("loop until timeout or interrupt, rather than one-shot")
    },
    {.name = "timeout",
     .type = VSH_OT_INT,
     .help = N_("timeout seconds")
    },
    {.name = "list",
     .type = VSH_OT_BOOL,
     .help = N_("list valid event types")
    },
    {.name = "timestamp",
     .type = VSH_OT_BOOL,
     .help = N_("show timestamp for each printed event")
    },
    {.name = NULL}
};

static bool
cmdPoolEvent(vshControl *ctl, const vshCmd *cmd)
{
    virStoragePoolPtr pool = NULL;
    bool ret = false;
    int eventId = -1;
    int timeout = 0;
    virshPoolEventData data;
    const char *eventName = NULL;
    int event;
    virshControlPtr priv = ctl->privData;

    if (vshCommandOptBool(cmd, "list")) {
        size_t i;

        for (i = 0; i < VIR_STORAGE_POOL_EVENT_ID_LAST; i++)
2142
            vshPrint(ctl, "%s\n", virshPoolEventCallbacks[i].name);
2143 2144 2145 2146 2147 2148
        return true;
    }

    if (vshCommandOptStringReq(ctl, cmd, "event", &eventName) < 0)
        return false;
    if (!eventName) {
2149
        vshError(ctl, "%s", _("either --list or --event <type> is required"));
2150 2151
        return false;
    }
2152 2153

    for (event = 0; event < VIR_STORAGE_POOL_EVENT_ID_LAST; event++)
2154
        if (STREQ(eventName, virshPoolEventCallbacks[event].name))
2155 2156
            break;
    if (event == VIR_STORAGE_POOL_EVENT_ID_LAST) {
2157 2158 2159 2160 2161 2162 2163 2164
        vshError(ctl, _("unknown event type %s"), eventName);
        return false;
    }

    data.ctl = ctl;
    data.loop = vshCommandOptBool(cmd, "loop");
    data.timestamp = vshCommandOptBool(cmd, "timestamp");
    data.count = 0;
2165
    data.cb = &virshPoolEventCallbacks[event];
2166 2167 2168 2169 2170 2171 2172 2173 2174
    if (vshCommandOptTimeoutToMs(ctl, cmd, &timeout) < 0)
        return false;

    if (vshCommandOptBool(cmd, "pool"))
        pool = virshCommandOptPool(ctl, cmd, "pool", NULL);
    if (vshEventStart(ctl, timeout) < 0)
        goto cleanup;

    if ((eventId = virConnectStoragePoolEventRegisterAny(priv->conn, pool, event,
2175
                                                         data.cb->cb,
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
                                                         &data, NULL)) < 0)
        goto cleanup;
    switch (vshEventWait(ctl)) {
    case VSH_EVENT_INTERRUPT:
        vshPrint(ctl, "%s", _("event loop interrupted\n"));
        break;
    case VSH_EVENT_TIMEOUT:
        vshPrint(ctl, "%s", _("event loop timed out\n"));
        break;
    case VSH_EVENT_DONE:
        break;
    default:
        goto cleanup;
    }
    vshPrint(ctl, _("events received: %d\n"), data.count);
    if (data.count)
        ret = true;

 cleanup:
    vshEventCleanup(ctl);
    if (eventId >= 0 &&
        virConnectStoragePoolEventDeregisterAny(priv->conn, eventId) < 0)
        ret = false;
    if (pool)
        virStoragePoolFree(pool);
    return ret;
}


E
Eric Blake 已提交
2205
const vshCmdDef storagePoolCmds[] = {
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231
    {.name = "find-storage-pool-sources-as",
     .handler = cmdPoolDiscoverSourcesAs,
     .opts = opts_find_storage_pool_sources_as,
     .info = info_find_storage_pool_sources_as,
     .flags = 0
    },
    {.name = "find-storage-pool-sources",
     .handler = cmdPoolDiscoverSources,
     .opts = opts_find_storage_pool_sources,
     .info = info_find_storage_pool_sources,
     .flags = 0
    },
    {.name = "pool-autostart",
     .handler = cmdPoolAutostart,
     .opts = opts_pool_autostart,
     .info = info_pool_autostart,
     .flags = 0
    },
    {.name = "pool-build",
     .handler = cmdPoolBuild,
     .opts = opts_pool_build,
     .info = info_pool_build,
     .flags = 0
    },
    {.name = "pool-create-as",
     .handler = cmdPoolCreateAs,
2232
     .opts = opts_pool_create_as,
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243
     .info = info_pool_create_as,
     .flags = 0
    },
    {.name = "pool-create",
     .handler = cmdPoolCreate,
     .opts = opts_pool_create,
     .info = info_pool_create,
     .flags = 0
    },
    {.name = "pool-define-as",
     .handler = cmdPoolDefineAs,
2244
     .opts = opts_pool_define_as,
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
     .info = info_pool_define_as,
     .flags = 0
    },
    {.name = "pool-define",
     .handler = cmdPoolDefine,
     .opts = opts_pool_define,
     .info = info_pool_define,
     .flags = 0
    },
    {.name = "pool-delete",
     .handler = cmdPoolDelete,
     .opts = opts_pool_delete,
     .info = info_pool_delete,
     .flags = 0
    },
    {.name = "pool-destroy",
     .handler = cmdPoolDestroy,
     .opts = opts_pool_destroy,
     .info = info_pool_destroy,
     .flags = 0
    },
    {.name = "pool-dumpxml",
     .handler = cmdPoolDumpXML,
     .opts = opts_pool_dumpxml,
     .info = info_pool_dumpxml,
     .flags = 0
    },
    {.name = "pool-edit",
     .handler = cmdPoolEdit,
     .opts = opts_pool_edit,
     .info = info_pool_edit,
     .flags = 0
    },
    {.name = "pool-info",
     .handler = cmdPoolInfo,
     .opts = opts_pool_info,
     .info = info_pool_info,
     .flags = 0
    },
    {.name = "pool-list",
     .handler = cmdPoolList,
     .opts = opts_pool_list,
     .info = info_pool_list,
     .flags = 0
    },
    {.name = "pool-name",
     .handler = cmdPoolName,
     .opts = opts_pool_name,
     .info = info_pool_name,
     .flags = 0
    },
    {.name = "pool-refresh",
     .handler = cmdPoolRefresh,
     .opts = opts_pool_refresh,
     .info = info_pool_refresh,
     .flags = 0
    },
    {.name = "pool-start",
     .handler = cmdPoolStart,
     .opts = opts_pool_start,
     .info = info_pool_start,
     .flags = 0
    },
    {.name = "pool-undefine",
     .handler = cmdPoolUndefine,
     .opts = opts_pool_undefine,
     .info = info_pool_undefine,
     .flags = 0
    },
    {.name = "pool-uuid",
     .handler = cmdPoolUuid,
     .opts = opts_pool_uuid,
     .info = info_pool_uuid,
     .flags = 0
    },
2320 2321 2322 2323 2324 2325
    {.name = "pool-event",
     .handler = cmdPoolEvent,
     .opts = opts_pool_event,
     .info = info_pool_event,
     .flags = 0
    },
2326
    {.name = NULL}
2327
};