storage_conf.c 77.0 KB
Newer Older
1 2 3
/*
 * storage_conf.c: config handling for storage driver
 *
4
 * Copyright (C) 2006-2016 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>

36
#include "virerror.h"
37
#include "datatypes.h"
38
#include "node_device_conf.h"
39
#include "storage_adapter_conf.h"
40
#include "storage_conf.h"
41
#include "virstoragefile.h"
42

43
#include "virxml.h"
44
#include "viruuid.h"
45
#include "virbuffer.h"
46
#include "viralloc.h"
E
Eric Blake 已提交
47
#include "virfile.h"
48
#include "virscsihost.h"
49
#include "virstring.h"
50
#include "virlog.h"
51
#include "virvhba.h"
52

53 54
#define VIR_FROM_THIS VIR_FROM_STORAGE

55 56
VIR_LOG_INIT("conf.storage_conf");

57 58
VIR_ENUM_IMPL(virStorageVol,
              VIR_STORAGE_VOL_LAST,
O
Olga Krishtal 已提交
59 60
              "file", "block", "dir", "network",
              "netdir", "ploop")
61

62 63 64 65
VIR_ENUM_IMPL(virStoragePool,
              VIR_STORAGE_POOL_LAST,
              "dir", "fs", "netfs",
              "logical", "disk", "iscsi",
R
Roman Bogorodskiy 已提交
66
              "scsi", "mpath", "rbd",
67 68
              "sheepdog", "gluster", "zfs",
              "vstorage")
69 70 71 72 73

VIR_ENUM_IMPL(virStoragePoolFormatFileSystem,
              VIR_STORAGE_POOL_FS_LAST,
              "auto", "ext2", "ext3",
              "ext4", "ufs", "iso9660", "udf",
J
Jim Fehlig 已提交
74
              "gfs", "gfs2", "vfat", "hfs+", "xfs", "ocfs2")
75 76 77

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
78
              "auto", "nfs", "glusterfs", "cifs")
79 80 81 82

VIR_ENUM_IMPL(virStoragePoolFormatDisk,
              VIR_STORAGE_POOL_DISK_LAST,
              "unknown", "dos", "dvh", "gpt",
83
              "mac", "bsd", "pc98", "sun", "lvm2")
84 85 86

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
87
              "unknown", "lvm2")
88 89 90 91 92 93 94


VIR_ENUM_IMPL(virStorageVolFormatDisk,
              VIR_STORAGE_VOL_DISK_LAST,
              "none", "linux", "fat16",
              "fat32", "linux-swap",
              "linux-lvm", "linux-raid",
95
              "extended")
96

97
VIR_ENUM_IMPL(virStoragePartedFs,
98
              VIR_STORAGE_PARTED_FS_TYPE_LAST,
99
              "ext2", "ext2", "fat16",
100 101 102
              "fat32", "linux-swap",
              "ext2", "ext2",
              "extended")
103 104 105 106 107 108 109 110 111 112

typedef const char *(*virStorageVolFormatToString)(int format);
typedef int (*virStorageVolFormatFromString)(const char *format);

typedef const char *(*virStoragePoolFormatToString)(int format);
typedef int (*virStoragePoolFormatFromString)(const char *format);

typedef struct _virStorageVolOptions virStorageVolOptions;
typedef virStorageVolOptions *virStorageVolOptionsPtr;
struct _virStorageVolOptions {
113
    int defaultFormat;
114 115 116 117 118 119
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
};

/* Flags to indicate mandatory components in the pool source */
enum {
O
Osier Yang 已提交
120 121 122 123 124 125 126
    VIR_STORAGE_POOL_SOURCE_HOST            = (1 << 0),
    VIR_STORAGE_POOL_SOURCE_DEVICE          = (1 << 1),
    VIR_STORAGE_POOL_SOURCE_DIR             = (1 << 2),
    VIR_STORAGE_POOL_SOURCE_ADAPTER         = (1 << 3),
    VIR_STORAGE_POOL_SOURCE_NAME            = (1 << 4),
    VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN   = (1 << 5),
    VIR_STORAGE_POOL_SOURCE_NETWORK         = (1 << 6),
127 128 129 130 131
};

typedef struct _virStoragePoolOptions virStoragePoolOptions;
typedef virStoragePoolOptions *virStoragePoolOptionsPtr;
struct _virStoragePoolOptions {
E
Eric Blake 已提交
132
    unsigned int flags;
133 134 135 136 137 138 139 140 141 142 143 144 145
    int defaultFormat;
    virStoragePoolFormatToString formatToString;
    virStoragePoolFormatFromString formatFromString;
};

typedef struct _virStoragePoolTypeInfo virStoragePoolTypeInfo;
typedef virStoragePoolTypeInfo *virStoragePoolTypeInfoPtr;
struct _virStoragePoolTypeInfo {
    int poolType;
    virStoragePoolOptions poolOptions;
    virStorageVolOptions volOptions;
};

E
Eric Blake 已提交
146 147 148 149 150 151 152 153 154
static int
virStorageVolumeFormatFromString(const char *format)
{
    int ret = virStorageFileFormatTypeFromString(format);
    if (ret == VIR_STORAGE_FILE_NONE)
        return -1;
    return ret;
}

155
static virStoragePoolTypeInfo poolTypeInfo[] = {
156 157 158 159 160 161 162 163
    {.poolType = VIR_STORAGE_POOL_LOGICAL,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_NAME |
                   VIR_STORAGE_POOL_SOURCE_DEVICE),
         .defaultFormat = VIR_STORAGE_POOL_LOGICAL_LVM2,
         .formatFromString = virStoragePoolFormatLogicalTypeFromString,
         .formatToString = virStoragePoolFormatLogicalTypeToString,
     },
164
    },
165 166 167 168 169 170
    {.poolType = VIR_STORAGE_POOL_DIR,
     .volOptions = {
         .defaultFormat = VIR_STORAGE_FILE_RAW,
         .formatFromString = virStorageVolumeFormatFromString,
         .formatToString = virStorageFileFormatTypeToString,
     },
171
    },
172 173 174 175 176 177 178
    {.poolType = VIR_STORAGE_POOL_FS,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
         .defaultFormat = VIR_STORAGE_POOL_FS_AUTO,
         .formatFromString = virStoragePoolFormatFileSystemTypeFromString,
         .formatToString = virStoragePoolFormatFileSystemTypeToString,
      },
179
      .volOptions = {
180 181 182 183
         .defaultFormat = VIR_STORAGE_FILE_RAW,
         .formatFromString = virStorageVolumeFormatFromString,
         .formatToString = virStorageFileFormatTypeToString,
      },
184
    },
185 186 187 188 189 190 191 192
    {.poolType = VIR_STORAGE_POOL_NETFS,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                   VIR_STORAGE_POOL_SOURCE_DIR),
         .defaultFormat = VIR_STORAGE_POOL_NETFS_AUTO,
         .formatFromString = virStoragePoolFormatFileSystemNetTypeFromString,
         .formatToString = virStoragePoolFormatFileSystemNetTypeToString,
      },
193
      .volOptions = {
194 195 196 197
         .defaultFormat = VIR_STORAGE_FILE_RAW,
         .formatFromString = virStorageVolumeFormatFromString,
         .formatToString = virStorageFileFormatTypeToString,
      },
198
    },
199 200 201 202 203 204
    {.poolType = VIR_STORAGE_POOL_ISCSI,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                   VIR_STORAGE_POOL_SOURCE_DEVICE |
                   VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN),
      },
205
      .volOptions = {
206 207 208 209 210 211 212 213 214 215
         .formatToString = virStoragePoolFormatDiskTypeToString,
      }
    },
    {.poolType = VIR_STORAGE_POOL_SCSI,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_ADAPTER),
     },
     .volOptions = {
         .formatToString = virStoragePoolFormatDiskTypeToString,
     }
216
    },
217 218 219 220 221 222
    {.poolType = VIR_STORAGE_POOL_RBD,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                   VIR_STORAGE_POOL_SOURCE_NETWORK |
                   VIR_STORAGE_POOL_SOURCE_NAME),
      },
223
      .volOptions = {
224
          .defaultFormat = VIR_STORAGE_FILE_RAW,
225 226
          .formatFromString = virStorageVolumeFormatFromString,
          .formatToString = virStorageFileFormatTypeToString,
227
      }
228
    },
229 230 231 232 233 234 235 236 237 238
    {.poolType = VIR_STORAGE_POOL_SHEEPDOG,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                   VIR_STORAGE_POOL_SOURCE_NETWORK |
                   VIR_STORAGE_POOL_SOURCE_NAME),
     },
     .volOptions = {
         .defaultFormat = VIR_STORAGE_FILE_RAW,
         .formatToString = virStoragePoolFormatDiskTypeToString,
     }
239
    },
240 241 242 243 244 245 246 247 248 249 250 251 252
    {.poolType = VIR_STORAGE_POOL_GLUSTER,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                   VIR_STORAGE_POOL_SOURCE_NETWORK |
                   VIR_STORAGE_POOL_SOURCE_NAME |
                   VIR_STORAGE_POOL_SOURCE_DIR),
     },
     .volOptions = {
         .defaultFormat = VIR_STORAGE_FILE_RAW,
         .formatToString = virStorageFileFormatTypeToString,
         .formatFromString = virStorageVolumeFormatFromString,
     }
    },
253 254 255 256
    {.poolType = VIR_STORAGE_POOL_MPATH,
     .volOptions = {
         .formatToString = virStoragePoolFormatDiskTypeToString,
     }
257
    },
258 259 260 261 262 263 264 265 266 267 268 269
    {.poolType = VIR_STORAGE_POOL_DISK,
     .poolOptions = {
         .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
         .defaultFormat = VIR_STORAGE_POOL_DISK_UNKNOWN,
         .formatFromString = virStoragePoolFormatDiskTypeFromString,
         .formatToString = virStoragePoolFormatDiskTypeToString,
     },
     .volOptions = {
         .defaultFormat = VIR_STORAGE_VOL_DISK_NONE,
         .formatFromString = virStorageVolFormatDiskTypeFromString,
         .formatToString = virStorageVolFormatDiskTypeToString,
     },
R
Roman Bogorodskiy 已提交
270 271 272
    },
    {.poolType = VIR_STORAGE_POOL_ZFS,
     .poolOptions = {
273 274
         .flags = (VIR_STORAGE_POOL_SOURCE_NAME |
                   VIR_STORAGE_POOL_SOURCE_DEVICE),
R
Roman Bogorodskiy 已提交
275 276 277
         .defaultFormat = VIR_STORAGE_FILE_RAW,
     },
    },
278 279 280 281 282 283 284 285 286 287
    {.poolType = VIR_STORAGE_POOL_VSTORAGE,
     .poolOptions = {
        .flags = VIR_STORAGE_POOL_SOURCE_NAME,
     },
     .volOptions = {
        .defaultFormat = VIR_STORAGE_FILE_RAW,
        .formatFromString = virStorageVolumeFormatFromString,
        .formatToString = virStorageFileFormatTypeToString,
     },
    },
288 289 290 291
};


static virStoragePoolTypeInfoPtr
292 293
virStoragePoolTypeInfoLookup(int type)
{
294
    size_t i;
295
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo); i++)
296 297 298
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

299 300
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
301 302 303 304
    return NULL;
}

static virStoragePoolOptionsPtr
305 306
virStoragePoolOptionsForPoolType(int type)
{
307 308 309 310 311 312 313
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
314 315
virStorageVolOptionsForPoolType(int type)
{
316 317 318 319 320 321 322
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


323
void
324 325
virStorageVolDefFree(virStorageVolDefPtr def)
{
326
    size_t i;
327 328 329 330

    if (!def)
        return;

331 332
    VIR_FREE(def->name);
    VIR_FREE(def->key);
333

334
    for (i = 0; i < def->source.nextent; i++)
335 336
        VIR_FREE(def->source.extents[i].path);
    VIR_FREE(def->source.extents);
337

338
    virStorageSourceClear(&def->target);
339
    VIR_FREE(def);
340 341
}

342 343 344 345 346 347 348
void
virStoragePoolSourceDeviceClear(virStoragePoolSourceDevicePtr dev)
{
    VIR_FREE(dev->freeExtents);
    VIR_FREE(dev->path);
}

349
void
350 351
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
352
    size_t i;
353

354
    if (!source)
355 356
        return;

357
    for (i = 0; i < source->nhost; i++)
358 359 360
        VIR_FREE(source->hosts[i].name);
    VIR_FREE(source->hosts);

361 362
    for (i = 0; i < source->ndevice; i++)
        virStoragePoolSourceDeviceClear(&source->devices[i]);
363 364 365
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
366
    virStorageAdapterClear(&source->adapter);
D
David Allan 已提交
367
    VIR_FREE(source->initiator.iqn);
368
    virStorageAuthDefFree(source->auth);
369 370
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
371 372
}

373 374 375 376 377 378 379
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

380
void
381 382
virStoragePoolDefFree(virStoragePoolDefPtr def)
{
383 384 385 386 387
    if (!def)
        return;

    VIR_FREE(def->name);

388
    virStoragePoolSourceClear(&def->source);
389

390 391 392
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
393 394 395 396
}


void
397 398
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
399 400 401
    if (!obj)
        return;

402 403
    virStoragePoolObjClearVols(obj);

404 405
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
406

407 408
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
409 410 411

    virMutexDestroy(&obj->lock);

412
    VIR_FREE(obj);
413 414
}

415 416
void
virStoragePoolObjListFree(virStoragePoolObjListPtr pools)
417
{
418
    size_t i;
419
    for (i = 0; i < pools->count; i++)
420 421 422 423 424
        virStoragePoolObjFree(pools->objs[i]);
    VIR_FREE(pools->objs);
    pools->count = 0;
}

425
void
426
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
427 428
                        virStoragePoolObjPtr pool)
{
429
    size_t i;
430

431 432
    virStoragePoolObjUnlock(pool);

433
    for (i = 0; i < pools->count; i++) {
434
        virStoragePoolObjLock(pools->objs[i]);
435
        if (pools->objs[i] == pool) {
436
            virStoragePoolObjUnlock(pools->objs[i]);
437
            virStoragePoolObjFree(pools->objs[i]);
438

439
            VIR_DELETE_ELEMENT(pools->objs, i, pools->count);
440 441
            break;
        }
442
        virStoragePoolObjUnlock(pools->objs[i]);
443
    }
444 445
}

446

447
static int
448
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
449 450
                             virStoragePoolSourcePtr source,
                             int pool_type,
451 452
                             xmlNodePtr node)
{
453
    int ret = -1;
454
    xmlNodePtr relnode, authnode, *nodeset = NULL;
455
    xmlNodePtr adapternode;
456 457
    int nsource;
    size_t i;
458
    virStoragePoolOptionsPtr options;
459
    virStorageAuthDefPtr authdef = NULL;
460
    char *name = NULL;
461
    char *port = NULL;
462
    int n;
463 464 465 466

    relnode = ctxt->node;
    ctxt->node = node;

467
    if ((options = virStoragePoolOptionsForPoolType(pool_type)) == NULL)
468 469
        goto cleanup;

470
    source->name = virXPathString("string(./name)", ctxt);
471
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
472
        virReportError(VIR_ERR_XML_ERROR, "%s",
473
                       _("element 'name' is mandatory for RBD pool"));
474 475
        goto cleanup;
    }
476 477

    if (options->formatFromString) {
478
        char *format = virXPathString("string(./format/@type)", ctxt);
479 480 481 482 483 484
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
485
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
486
                           _("unknown pool format type %s"), format);
487 488 489 490 491 492
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

493 494
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
495

496 497
    if (n) {
        if (VIR_ALLOC_N(source->hosts, n) < 0)
498
            goto cleanup;
499
        source->nhost = n;
500

501
        for (i = 0; i < source->nhost; i++) {
502 503
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
504 505
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool host name"));
506 507 508 509 510 511 512
                goto cleanup;
            }
            source->hosts[i].name = name;

            port = virXMLPropString(nodeset[i], "port");
            if (port) {
                if (virStrToLong_i(port, NULL, 10, &source->hosts[i].port) < 0) {
513 514 515
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
516 517 518 519 520
                    goto cleanup;
                }
            }
        }
    }
521

522
    VIR_FREE(nodeset);
523
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
524

525
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
526 527 528
    if (nsource < 0)
        goto cleanup;

529
    for (i = 0; i < nsource; i++) {
530
        char *partsep;
531 532 533 534 535 536
        virStoragePoolSourceDevice dev = { .path = NULL };
        dev.path = virXMLPropString(nodeset[i], "path");

        if (dev.path == NULL) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device path"));
537 538 539
            goto cleanup;
        }

540 541 542 543 544 545 546 547 548 549 550 551 552 553
        partsep = virXMLPropString(nodeset[i], "part_separator");
        if (partsep) {
            dev.part_separator = virTristateBoolTypeFromString(partsep);
            if (dev.part_separator <= 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("invalid part_separator setting '%s'"),
                               partsep);
                virStoragePoolSourceDeviceClear(&dev);
                VIR_FREE(partsep);
                goto cleanup;
            }
            VIR_FREE(partsep);
        }

554 555 556
        if (VIR_APPEND_ELEMENT(source->devices, source->ndevice, dev) < 0) {
            virStoragePoolSourceDeviceClear(&dev);
            goto cleanup;
557
        }
558

559 560
    }

561
    source->dir = virXPathString("string(./dir/@path)", ctxt);
562 563 564 565
    /* In gluster, a missing dir defaults to "/" */
    if (!source->dir && pool_type == VIR_STORAGE_POOL_GLUSTER &&
        VIR_STRDUP(source->dir, "/") < 0)
        goto cleanup;
566

567
    if ((adapternode = virXPathNode("./adapter", ctxt))) {
568
        if (virStorageAdapterParseXML(source, adapternode, ctxt) < 0)
569 570
            goto cleanup;
    }
571

572 573 574 575 576 577 578 579 580 581 582
    if ((authnode = virXPathNode("./auth", ctxt))) {
        if (!(authdef = virStorageAuthDefParse(node->doc, authnode)))
            goto cleanup;

        if (authdef->authType == VIR_STORAGE_AUTH_TYPE_NONE) {
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                           _("storage pool missing auth type"));
            goto cleanup;
        }

        source->auth = authdef;
583
        authdef = NULL;
584
    }
585

586 587 588
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

589
    ret = 0;
590
 cleanup:
591 592
    ctxt->node = relnode;

593
    VIR_FREE(port);
594
    VIR_FREE(nodeset);
595
    virStorageAuthDefFree(authdef);
596 597
    return ret;
}
598

599
virStoragePoolSourcePtr
600
virStoragePoolDefParseSourceString(const char *srcSpec,
601 602 603 604 605 606 607
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

608 609 610
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
611 612
        goto cleanup;

613
    if (VIR_ALLOC(def) < 0)
614 615
        goto cleanup;

616
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
617 618
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
619 620 621
        goto cleanup;
    }

622
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
623 624 625 626 627
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
628
 cleanup:
629
    virStoragePoolSourceFree(def);
630 631 632 633 634
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
635

636
static int
637
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
638
                        virStoragePermsPtr perms,
639
                        const char *permxpath)
640
{
641
    char *mode;
642
    long long val;
643 644 645
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
646

647
    node = virXPathNode(permxpath, ctxt);
648 649
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
650
        perms->mode = (mode_t) -1;
P
Philipp Hahn 已提交
651 652
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
653 654 655 656 657 658 659
        perms->label = NULL;
        return 0;
    }

    relnode = ctxt->node;
    ctxt->node = node;

660
    if ((mode = virXPathString("string(./mode)", ctxt))) {
661 662 663
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
664
            VIR_FREE(mode);
665 666
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
667
            goto error;
668
        }
669
        perms->mode = tmp;
670
        VIR_FREE(mode);
671 672
    } else {
        perms->mode = (mode_t) -1;
673 674
    }

675
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
676
        perms->uid = (uid_t) -1;
677
    } else {
678
        /* We previously could output -1, so continue to parse it */
679
        if (virXPathLongLong("number(./owner)", ctxt, &val) < 0 ||
680 681
            ((uid_t)val != val &&
             val != -1)) {
682 683
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed owner element"));
684
            goto error;
685
        }
686 687

        perms->uid = val;
688 689
    }

690
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
691
        perms->gid = (gid_t) -1;
692
    } else {
693
        /* We previously could output -1, so continue to parse it */
694
        if (virXPathLongLong("number(./group)", ctxt, &val) < 0 ||
695 696
            ((gid_t) val != val &&
             val != -1)) {
697 698
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed group element"));
699
            goto error;
700
        }
701
        perms->gid = val;
702 703 704
    }

    /* NB, we're ignoring missing labels here - they'll simply inherit */
705
    perms->label = virXPathString("string(./label)", ctxt);
706

707
    ret = 0;
708
 error:
709 710
    ctxt->node = relnode;
    return ret;
711 712
}

713

714
static virStoragePoolDefPtr
715 716
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
717
    virStoragePoolOptionsPtr options;
718
    virStoragePoolDefPtr ret;
719
    xmlNodePtr source_node;
720
    char *type = NULL;
721
    char *uuid = NULL;
722
    char *target_path = NULL;
723

724
    if (VIR_ALLOC(ret) < 0)
725 726
        return NULL;

727
    type = virXPathString("string(./@type)", ctxt);
728 729 730 731 732 733
    if (type == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("storage pool missing type attribute"));
        goto error;
    }

734
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
735
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
736
                       _("unknown storage pool type %s"), type);
737
        goto error;
738 739
    }

740
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL)
741
        goto error;
742

743
    source_node = virXPathNode("./source", ctxt);
744
    if (source_node) {
745
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
746
                                         source_node) < 0)
747
            goto error;
748 749
    }

750
    ret->name = virXPathString("string(./name)", ctxt);
751
    if (ret->name == NULL &&
752
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
753
        ret->name = ret->source.name;
754
    if (ret->name == NULL) {
755 756
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
757
        goto error;
758 759
    }

760 761 762 763 764 765
    if (strchr(ret->name, '/')) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("name %s cannot contain '/'"), ret->name);
        goto error;
    }

766
    uuid = virXPathString("string(./uuid)", ctxt);
767 768
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
769 770
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
771
            goto error;
772 773 774
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
775 776
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
777
            goto error;
778 779 780
        }
    }

781
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
782
        if (!ret->source.nhost) {
783
            virReportError(VIR_ERR_XML_ERROR, "%s",
784
                           _("missing storage pool source host name"));
785
            goto error;
786 787 788
        }
    }

789
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
790
        if (!ret->source.dir) {
791 792
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
793
            goto error;
794 795
        }
    }
796
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
797 798
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
799
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
800
                goto error;
801 802
        }
    }
803

804
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
805
        (virStorageAdapterValidate(ret)) < 0)
806
            goto error;
807

808 809 810
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
811 812
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
813
            goto error;
814 815 816
        }
    }

817 818 819
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
820
        if (ret->type == VIR_STORAGE_POOL_LOGICAL) {
821
            if (virAsprintf(&target_path, "/dev/%s", ret->source.name) < 0)
822
                goto error;
R
Roman Bogorodskiy 已提交
823
        } else if (ret->type == VIR_STORAGE_POOL_ZFS) {
824
            if (virAsprintf(&target_path, "/dev/zvol/%s", ret->source.name) < 0)
R
Roman Bogorodskiy 已提交
825
                goto error;
826 827 828 829 830 831 832
        } else {
            target_path = virXPathString("string(./target/path)", ctxt);
            if (!target_path) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool target path"));
                goto error;
            }
833
        }
834
        ret->target.path = virFileSanitizePath(target_path);
835
        if (!ret->target.path)
836
            goto error;
837

838
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
839
                                    "./target/permissions") < 0)
840
            goto error;
841
    }
842

843
 cleanup:
844
    VIR_FREE(uuid);
845 846 847 848
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

849
 error:
850
    virStoragePoolDefFree(ret);
851 852
    ret = NULL;
    goto cleanup;
853 854 855
}

virStoragePoolDefPtr
856
virStoragePoolDefParseNode(xmlDocPtr xml,
857 858
                           xmlNodePtr root)
{
859 860 861
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

862
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
863
        virReportError(VIR_ERR_XML_ERROR,
864 865 866
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
867 868 869 870 871
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
872
        virReportOOMError();
873 874 875 876
        goto cleanup;
    }

    ctxt->node = root;
877
    def = virStoragePoolDefParseXML(ctxt);
878
 cleanup:
879 880 881 882 883
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
884
virStoragePoolDefParse(const char *xmlStr,
885 886
                       const char *filename)
{
887
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
888
    xmlDocPtr xml;
889

890
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
891 892
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
893 894
    }

895 896 897
    return ret;
}

898
virStoragePoolDefPtr
899
virStoragePoolDefParseString(const char *xmlStr)
900
{
901
    return virStoragePoolDefParse(xmlStr, NULL);
902 903 904
}

virStoragePoolDefPtr
905
virStoragePoolDefParseFile(const char *filename)
906
{
907
    return virStoragePoolDefParse(NULL, filename);
908 909
}

910

911
static int
912
virStoragePoolSourceFormat(virBufferPtr buf,
913
                           virStoragePoolOptionsPtr options,
914 915
                           virStoragePoolSourcePtr src)
{
916
    size_t i, j;
917

918 919 920
    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

921 922
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
923
            virBufferEscapeString(buf, "<host name='%s'",
924
                                  src->hosts[i].name);
925 926 927 928
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
929
    }
930

931
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
932
        src->ndevice) {
933
        for (i = 0; i < src->ndevice; i++) {
934 935 936 937 938 939 940
            virBufferEscapeString(buf, "<device path='%s'",
                                  src->devices[i].path);
            if (src->devices[i].part_separator !=
                VIR_TRISTATE_SWITCH_ABSENT) {
                virBufferAsprintf(buf, " part_separator='%s'",
                                  virTristateBoolTypeToString(src->devices[i].part_separator));
            }
941
            if (src->devices[i].nfreeExtent) {
942
                virBufferAddLit(buf, ">\n");
943
                virBufferAdjustIndent(buf, 2);
944
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
945
                    virBufferAsprintf(buf, "<freeExtent start='%llu' end='%llu'/>\n",
946 947 948
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
949 950
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</device>\n");
951
            } else {
952
                virBufferAddLit(buf, "/>\n");
953
            }
954 955
        }
    }
956

957
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR)
958
        virBufferEscapeString(buf, "<dir path='%s'/>\n", src->dir);
959

960 961 962
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
        (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST ||
         src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST))
963
        virStorageAdapterFormat(buf, src);
964

965
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
966
        virBufferEscapeString(buf, "<name>%s</name>\n", src->name);
967

D
David Allan 已提交
968 969
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN) &&
        src->initiator.iqn) {
970 971 972
        virBufferAddLit(buf, "<initiator>\n");
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<iqn name='%s'/>\n",
E
Eric Blake 已提交
973
                              src->initiator.iqn);
974 975
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</initiator>\n");
D
David Allan 已提交
976 977
    }

978 979 980
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
981 982 983
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
984 985
            return -1;
        }
986
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
987 988
    }

989 990 991
    if (src->auth) {
        if (virStorageAuthDefFormat(buf, src->auth) < 0)
            return -1;
992 993
    }

994 995
    virBufferEscapeString(buf, "<vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "<product name='%s'/>\n", src->product);
996

997 998
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
999 1000 1001
    return 0;
}

1002

1003 1004 1005
static int
virStoragePoolDefFormatBuf(virBufferPtr buf,
                           virStoragePoolDefPtr def)
1006
{
1007
    virStoragePoolOptionsPtr options;
1008
    char uuid[VIR_UUID_STRING_BUFLEN];
1009
    const char *type;
1010

1011
    options = virStoragePoolOptionsForPoolType(def->type);
1012
    if (options == NULL)
1013
        return -1;
1014

1015
    type = virStoragePoolTypeToString(def->type);
1016
    if (!type) {
1017 1018
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1019
        return -1;
1020
    }
1021 1022 1023
    virBufferAsprintf(buf, "<pool type='%s'>\n", type);
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<name>%s</name>\n", def->name);
1024 1025

    virUUIDFormat(def->uuid, uuid);
1026
    virBufferAsprintf(buf, "<uuid>%s</uuid>\n", uuid);
1027

1028
    virBufferAsprintf(buf, "<capacity unit='bytes'>%llu</capacity>\n",
1029
                      def->capacity);
1030
    virBufferAsprintf(buf, "<allocation unit='bytes'>%llu</allocation>\n",
1031
                      def->allocation);
1032
    virBufferAsprintf(buf, "<available unit='bytes'>%llu</available>\n",
1033
                      def->available);
1034

1035 1036
    if (virStoragePoolSourceFormat(buf, options, &def->source) < 0)
        return -1;
1037

1038 1039
    /* RBD, Sheepdog, and Gluster devices are not local block devs nor
     * files, so they don't have a target */
1040
    if (def->type != VIR_STORAGE_POOL_RBD &&
1041 1042
        def->type != VIR_STORAGE_POOL_SHEEPDOG &&
        def->type != VIR_STORAGE_POOL_GLUSTER) {
1043 1044
        virBufferAddLit(buf, "<target>\n");
        virBufferAdjustIndent(buf, 2);
1045

1046
        virBufferEscapeString(buf, "<path>%s</path>\n", def->target.path);
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        if (def->target.perms.mode != (mode_t) -1 ||
            def->target.perms.uid != (uid_t) -1 ||
            def->target.perms.gid != (gid_t) -1 ||
            def->target.perms.label) {
            virBufferAddLit(buf, "<permissions>\n");
            virBufferAdjustIndent(buf, 2);
            if (def->target.perms.mode != (mode_t) -1)
                virBufferAsprintf(buf, "<mode>0%o</mode>\n",
                                  def->target.perms.mode);
            if (def->target.perms.uid != (uid_t) -1)
                virBufferAsprintf(buf, "<owner>%d</owner>\n",
                                  (int) def->target.perms.uid);
            if (def->target.perms.gid != (gid_t) -1)
                virBufferAsprintf(buf, "<group>%d</group>\n",
                                  (int) def->target.perms.gid);
            virBufferEscapeString(buf, "<label>%s</label>\n",
                                  def->target.perms.label);

            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</permissions>\n");
        }
1069

1070 1071
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</target>\n");
1072
    }
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</pool>\n");

    return 0;
}

char *
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

    if (virStoragePoolDefFormatBuf(&buf, def) < 0)
        goto error;
1086

1087
    if (virBufferCheckError(&buf) < 0)
1088
        goto error;
1089

1090
    return virBufferContentAndReset(&buf);
1091

1092
 error:
1093
    virBufferFreeAndReset(&buf);
1094 1095 1096 1097 1098
    return NULL;
}


static int
1099
virStorageSize(const char *unit,
1100
               const char *val,
1101 1102 1103
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1104 1105
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("malformed capacity element"));
1106 1107
        return -1;
    }
1108 1109 1110 1111
    /* off_t is signed, so you cannot create a file larger than 2**63
     * bytes in the first place.  */
    if (virScaleInteger(ret, unit, 1, LLONG_MAX) < 0)
        return -1;
1112 1113 1114 1115 1116

    return 0;
}

static virStorageVolDefPtr
1117
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1118 1119
                         xmlXPathContextPtr ctxt,
                         unsigned int flags)
1120
{
1121
    virStorageVolDefPtr ret;
1122
    virStorageVolOptionsPtr options;
1123
    char *type = NULL;
1124 1125 1126
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1127
    char *backingStore = NULL;
1128
    xmlNodePtr node;
1129
    xmlNodePtr *nodes = NULL;
1130 1131
    size_t i;
    int n;
1132

1133 1134
    virCheckFlags(VIR_VOL_XML_PARSE_NO_CAPACITY |
                  VIR_VOL_XML_PARSE_OPT_CAPACITY, NULL);
1135

1136
    options = virStorageVolOptionsForPoolType(pool->type);
1137 1138 1139
    if (options == NULL)
        return NULL;

1140
    if (VIR_ALLOC(ret) < 0)
1141 1142
        return NULL;

1143
    ret->name = virXPathString("string(./name)", ctxt);
1144
    if (ret->name == NULL) {
1145 1146
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing volume name element"));
1147
        goto error;
1148 1149
    }

1150 1151
    /* Normally generated by pool refresh, but useful for unit tests */
    ret->key = virXPathString("string(./key)", ctxt);
1152

1153 1154 1155 1156
    /* Technically overridden by pool refresh, but useful for unit tests */
    type = virXPathString("string(./@type)", ctxt);
    if (type) {
        if ((ret->type = virStorageVolTypeFromString(type)) < 0) {
1157
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1158 1159 1160 1161 1162
                           _("unknown volume type '%s'"), type);
            goto error;
        }
    }

1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    if ((backingStore = virXPathString("string(./backingStore/path)", ctxt))) {
        if (VIR_ALLOC(ret->target.backingStore) < 0)
            goto error;

        ret->target.backingStore->path = backingStore;
        backingStore = NULL;

        if (options->formatFromString) {
            char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
            if (format == NULL)
                ret->target.backingStore->format = options->defaultFormat;
            else
                ret->target.backingStore->format = (options->formatFromString)(format);

            if (ret->target.backingStore->format < 0) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("unknown volume format type %s"), format);
                VIR_FREE(format);
                goto error;
            }
            VIR_FREE(format);
        }

        if (VIR_ALLOC(ret->target.backingStore->perms) < 0)
            goto error;
        if (virStorageDefParsePerms(ctxt, ret->target.backingStore->perms,
1189
                                    "./backingStore/permissions") < 0)
1190 1191 1192
            goto error;
    }

1193 1194
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1195 1196 1197
    if (capacity) {
        if (virStorageSize(unit, capacity, &ret->target.capacity) < 0)
            goto error;
1198 1199
    } else if (!(flags & VIR_VOL_XML_PARSE_NO_CAPACITY) &&
               !((flags & VIR_VOL_XML_PARSE_OPT_CAPACITY) && ret->target.backingStore)) {
1200
        virReportError(VIR_ERR_XML_ERROR, "%s", _("missing capacity element"));
1201
        goto error;
1202
    }
1203
    VIR_FREE(unit);
1204

1205
    allocation = virXPathString("string(./allocation)", ctxt);
1206
    if (allocation) {
1207
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1208
        if (virStorageSize(unit, allocation, &ret->target.allocation) < 0)
1209
            goto error;
1210
        ret->target.has_allocation = true;
1211
    } else {
1212
        ret->target.allocation = ret->target.capacity;
1213 1214
    }

1215
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1216
    if (options->formatFromString) {
1217
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1218 1219 1220 1221 1222 1223
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1224
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1225
                           _("unknown volume format type %s"), format);
1226
            VIR_FREE(format);
1227
            goto error;
1228
        }
1229
        VIR_FREE(format);
1230 1231
    }

1232 1233 1234
    if (VIR_ALLOC(ret->target.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->target.perms,
1235
                                "./target/permissions") < 0)
1236
        goto error;
1237

1238
    node = virXPathNode("./target/encryption", ctxt);
1239
    if (node != NULL) {
1240
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1241 1242
                                                               node);
        if (ret->target.encryption == NULL)
1243
            goto error;
1244 1245
    }

1246
    ret->target.compat = virXPathString("string(./target/compat)", ctxt);
1247 1248
    if (virStorageFileCheckCompat(ret->target.compat) < 0)
        goto error;
1249

C
Chunyan Liu 已提交
1250 1251 1252
    if (virXPathNode("./target/nocow", ctxt))
        ret->target.nocow = true;

1253
    if (virXPathNode("./target/features", ctxt)) {
1254 1255 1256 1257 1258 1259 1260
        if ((n = virXPathNodeSet("./target/features/*", ctxt, &nodes)) < 0)
            goto error;

        if (!ret->target.compat && VIR_STRDUP(ret->target.compat, "1.1") < 0)
            goto error;

        if (!(ret->target.features = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
1261
            goto error;
1262 1263

        for (i = 0; i < n; i++) {
1264
            int f = virStorageFileFeatureTypeFromString((const char*)nodes[i]->name);
1265 1266

            if (f < 0) {
1267
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unsupported feature %s"),
1268 1269 1270 1271 1272 1273 1274 1275
                               (const char*)nodes[i]->name);
                goto error;
            }
            ignore_value(virBitmapSetBit(ret->target.features, f));
        }
        VIR_FREE(nodes);
    }

1276
 cleanup:
1277
    VIR_FREE(nodes);
1278 1279 1280
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1281
    VIR_FREE(type);
1282
    VIR_FREE(backingStore);
1283 1284
    return ret;

1285
 error:
1286
    virStorageVolDefFree(ret);
1287 1288
    ret = NULL;
    goto cleanup;
1289 1290 1291
}

virStorageVolDefPtr
1292
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1293
                          xmlDocPtr xml,
1294 1295
                          xmlNodePtr root,
                          unsigned int flags)
1296
{
1297 1298 1299
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1300
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1301
        virReportError(VIR_ERR_XML_ERROR,
1302 1303 1304
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1305 1306 1307 1308 1309
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1310
        virReportOOMError();
1311 1312 1313 1314
        goto cleanup;
    }

    ctxt->node = root;
1315
    def = virStorageVolDefParseXML(pool, ctxt, flags);
1316
 cleanup:
1317 1318 1319 1320 1321
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1322
virStorageVolDefParse(virStoragePoolDefPtr pool,
1323
                      const char *xmlStr,
1324 1325
                      const char *filename,
                      unsigned int flags)
1326
{
1327
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1328
    xmlDocPtr xml;
1329

1330
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
1331
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml), flags);
J
Jiri Denemark 已提交
1332
        xmlFreeDoc(xml);
1333 1334 1335 1336 1337
    }

    return ret;
}

1338
virStorageVolDefPtr
1339
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1340 1341
                            const char *xmlStr,
                            unsigned int flags)
1342
{
1343
    return virStorageVolDefParse(pool, xmlStr, NULL, flags);
1344 1345 1346
}

virStorageVolDefPtr
1347
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1348 1349
                          const char *filename,
                          unsigned int flags)
1350
{
1351
    return virStorageVolDefParse(pool, NULL, filename, flags);
1352
}
1353

1354 1355 1356 1357 1358 1359
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
1360
    virBufferAsprintf(buf, "<%s>%llu", name,
1361 1362 1363 1364 1365 1366
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1367
static int
1368
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1369
                             virBufferPtr buf,
1370
                             virStorageSourcePtr def,
1371 1372
                             const char *type)
{
1373 1374
    virBufferAsprintf(buf, "<%s>\n", type);
    virBufferAdjustIndent(buf, 2);
1375

1376
    virBufferEscapeString(buf, "<path>%s</path>\n", def->path);
1377 1378 1379 1380

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1381 1382 1383
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1384 1385
            return -1;
        }
1386
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1387 1388
    }

1389 1390 1391 1392 1393
    if (def->perms &&
        (def->perms->mode != (mode_t) -1 ||
         def->perms->uid != (uid_t) -1 ||
         def->perms->gid != (gid_t) -1 ||
         def->perms->label)) {
1394 1395
        virBufferAddLit(buf, "<permissions>\n");
        virBufferAdjustIndent(buf, 2);
1396

1397 1398 1399
        if (def->perms->mode != (mode_t) -1)
            virBufferAsprintf(buf, "<mode>0%o</mode>\n",
                              def->perms->mode);
1400 1401 1402 1403 1404 1405
        if (def->perms->uid != (uid_t) -1)
            virBufferAsprintf(buf, "<owner>%d</owner>\n",
                              (int) def->perms->uid);
        if (def->perms->gid != (gid_t) -1)
            virBufferAsprintf(buf, "<group>%d</group>\n",
                              (int) def->perms->gid);
1406

1407 1408
        virBufferEscapeString(buf, "<label>%s</label>\n",
                              def->perms->label);
1409

1410 1411 1412
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</permissions>\n");
    }
1413

1414
    if (def->timestamps) {
1415 1416
        virBufferAddLit(buf, "<timestamps>\n");
        virBufferAdjustIndent(buf, 2);
1417 1418 1419 1420
        virStorageVolTimestampFormat(buf, "atime", &def->timestamps->atime);
        virStorageVolTimestampFormat(buf, "mtime", &def->timestamps->mtime);
        virStorageVolTimestampFormat(buf, "ctime", &def->timestamps->ctime);
        virStorageVolTimestampFormat(buf, "btime", &def->timestamps->btime);
1421 1422
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timestamps>\n");
1423 1424
    }

1425 1426
    if (def->encryption &&
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1427
            return -1;
1428

1429
    virBufferEscapeString(buf, "<compat>%s</compat>\n", def->compat);
1430

1431
    if (def->features) {
1432
        size_t i;
1433 1434
        bool empty = virBitmapIsAllClear(def->features);

1435 1436 1437 1438 1439 1440
        if (empty) {
            virBufferAddLit(buf, "<features/>\n");
        } else {
            virBufferAddLit(buf, "<features>\n");
            virBufferAdjustIndent(buf, 2);
        }
1441 1442

        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
J
Ján Tomko 已提交
1443
            if (virBitmapIsBitSet(def->features, i))
1444
                virBufferAsprintf(buf, "<%s/>\n",
1445
                                  virStorageFileFeatureTypeToString(i));
1446
        }
1447 1448 1449 1450
        if (!empty) {
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</features>\n");
        }
1451 1452
    }

1453 1454
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", type);
1455 1456
    return 0;
}
1457 1458

char *
1459
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1460 1461
                       virStorageVolDefPtr def)
{
1462
    virStorageVolOptionsPtr options;
1463
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1464

1465
    options = virStorageVolOptionsForPoolType(pool->type);
1466 1467 1468
    if (options == NULL)
        return NULL;

1469 1470
    virBufferAsprintf(&buf, "<volume type='%s'>\n",
                      virStorageVolTypeToString(def->type));
1471 1472 1473 1474 1475 1476
    virBufferAdjustIndent(&buf, 2);

    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
    virBufferEscapeString(&buf, "<key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "<source>\n");
    virBufferAdjustIndent(&buf, 2);
1477 1478

    if (def->source.nextent) {
1479
        size_t i;
1480
        const char *thispath = NULL;
1481
        for (i = 0; i < def->source.nextent; i++) {
1482 1483 1484
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1485
                    virBufferAddLit(&buf, "</device>\n");
1486

1487
                virBufferEscapeString(&buf, "<device path='%s'>\n",
1488
                                      def->source.extents[i].path);
1489 1490
            }

1491 1492
            virBufferAdjustIndent(&buf, 2);
            virBufferAsprintf(&buf, "<extent start='%llu' end='%llu'/>\n",
1493 1494
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1495
            virBufferAdjustIndent(&buf, -2);
1496 1497 1498
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1499
            virBufferAddLit(&buf, "</device>\n");
1500 1501
    }

1502 1503 1504 1505
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</source>\n");

    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1506
                      def->target.capacity);
1507
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1508
                      def->target.allocation);
1509 1510 1511 1512 1513 1514
    /* NB: Display only - since virStorageVolInfo is limited to just
     * 'capacity' and 'allocation' on output. Since we don't read this
     * in, be sure it was filled in before printing */
    if (def->target.physical)
        virBufferAsprintf(&buf, "<physical unit='bytes'>%llu</physical>\n",
                          def->target.physical);
1515

1516
    if (virStorageVolTargetDefFormat(options, &buf,
1517 1518
                                     &def->target, "target") < 0)
        goto cleanup;
1519

1520
    if (def->target.backingStore &&
1521
        virStorageVolTargetDefFormat(options, &buf,
1522 1523
                                     def->target.backingStore,
                                     "backingStore") < 0)
1524
        goto cleanup;
1525

1526
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1527
    virBufferAddLit(&buf, "</volume>\n");
1528

1529 1530
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1531

1532
    return virBufferContentAndReset(&buf);
1533

1534
 cleanup:
1535
    virBufferFreeAndReset(&buf);
1536 1537 1538 1539 1540
    return NULL;
}


virStoragePoolObjPtr
1541
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1542 1543
                            const unsigned char *uuid)
{
1544
    size_t i;
1545

1546
    for (i = 0; i < pools->count; i++) {
1547
        virStoragePoolObjLock(pools->objs[i]);
1548 1549
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1550 1551
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1552 1553 1554 1555 1556

    return NULL;
}

virStoragePoolObjPtr
1557
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1558 1559
                            const char *name)
{
1560
    size_t i;
1561

1562
    for (i = 0; i < pools->count; i++) {
1563
        virStoragePoolObjLock(pools->objs[i]);
1564 1565
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1566 1567
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1568 1569 1570 1571

    return NULL;
}

1572 1573
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1574 1575
                                         virStoragePoolDefPtr def)
{
1576
    size_t i, j;
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587

    for (i = 0; i < pool->def->source.ndevice; i++) {
        for (j = 0; j < def->source.ndevice; j++) {
            if (STREQ(pool->def->source.devices[i].path, def->source.devices[j].path))
                return pool;
        }
    }

    return NULL;
}

1588 1589 1590
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1591
    size_t i;
1592
    for (i = 0; i < pool->volumes.count; i++)
1593 1594 1595 1596
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1597 1598 1599 1600
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1601 1602
                          const char *key)
{
1603
    size_t i;
1604

1605
    for (i = 0; i < pool->volumes.count; i++)
1606 1607
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1608 1609 1610 1611 1612 1613

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1614 1615
                           const char *path)
{
1616
    size_t i;
1617

1618
    for (i = 0; i < pool->volumes.count; i++)
1619 1620
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1621 1622 1623 1624 1625 1626

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1627 1628
                           const char *name)
{
1629
    size_t i;
1630

1631
    for (i = 0; i < pool->volumes.count; i++)
1632 1633
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1634 1635 1636 1637 1638

    return NULL;
}

virStoragePoolObjPtr
1639
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1640 1641
                           virStoragePoolDefPtr def)
{
1642 1643
    virStoragePoolObjPtr pool;

1644
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1645 1646 1647 1648
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1649
            virStoragePoolDefFree(pool->newDef);
1650 1651 1652 1653 1654
            pool->newDef = def;
        }
        return pool;
    }

1655
    if (VIR_ALLOC(pool) < 0)
1656 1657
        return NULL;

1658
    if (virMutexInit(&pool->lock) < 0) {
1659 1660
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1661 1662 1663
        VIR_FREE(pool);
        return NULL;
    }
1664
    virStoragePoolObjLock(pool);
1665 1666
    pool->active = 0;

1667
    if (VIR_APPEND_ELEMENT_COPY(pools->objs, pools->count, pool) < 0) {
1668
        virStoragePoolObjUnlock(pool);
1669 1670 1671
        virStoragePoolObjFree(pool);
        return NULL;
    }
1672
    pool->def = def;
1673 1674 1675 1676 1677

    return pool;
}

static virStoragePoolObjPtr
1678
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1679 1680
                      const char *file,
                      const char *path,
1681 1682
                      const char *autostartLink)
{
1683 1684 1685
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1686
    if (!(def = virStoragePoolDefParseFile(path)))
1687 1688 1689
        return NULL;

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1690
        virReportError(VIR_ERR_XML_ERROR,
1691 1692
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1693
                       path, def->name);
1694 1695 1696 1697
        virStoragePoolDefFree(def);
        return NULL;
    }

1698
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1699 1700 1701 1702
        virStoragePoolDefFree(def);
        return NULL;
    }

1703
    VIR_FREE(pool->configFile);  /* for driver reload */
1704
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1705
        virStoragePoolObjRemove(pools, pool);
1706 1707
        return NULL;
    }
1708
    VIR_FREE(pool->autostartLink); /* for driver reload */
1709
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1710
        virStoragePoolObjRemove(pools, pool);
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
        return NULL;
    }

    pool->autostart = virFileLinkPointsTo(pool->autostartLink,
                                          pool->configFile);

    return pool;
}


1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
virStoragePoolObjPtr
virStoragePoolLoadState(virStoragePoolObjListPtr pools,
                        const char *stateDir,
                        const char *name)
{
    char *stateFile = NULL;
    virStoragePoolDefPtr def = NULL;
    virStoragePoolObjPtr pool = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr node = NULL;

    if (!(stateFile = virFileBuildPath(stateDir, name, ".xml")))
        goto error;

    if (!(xml = virXMLParseCtxt(stateFile, NULL, _("(pool state)"), &ctxt)))
        goto error;

    if (!(node = virXPathNode("//pool", ctxt))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Could not find any 'pool' element in state file"));
        goto error;
    }

    ctxt->node = node;
    if (!(def = virStoragePoolDefParseXML(ctxt)))
        goto error;

1749
    if (STRNEQ(name, def->name)) {
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Storage pool state file '%s' does not match "
                         "pool name '%s'"),
                       stateFile, def->name);
        goto error;
    }

    /* create the object */
    if (!(pool = virStoragePoolObjAssignDef(pools, def)))
        goto error;

    /* XXX: future handling of some additional useful status data,
     * for now, if a status file for a pool exists, the pool will be marked
     * as active
     */

    pool->active = 1;

 cleanup:
    VIR_FREE(stateFile);
1770
    xmlFreeDoc(xml);
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    xmlXPathFreeContext(ctxt);
    return pool;

 error:
    virStoragePoolDefFree(def);
    goto cleanup;
}


int
virStoragePoolLoadAllState(virStoragePoolObjListPtr pools,
                           const char *stateDir)
{
    DIR *dir;
    struct dirent *entry;
    int ret = -1;
J
Ján Tomko 已提交
1787
    int rc;
1788

J
Ján Tomko 已提交
1789 1790
    if ((rc = virDirOpenIfExists(&dir, stateDir)) <= 0)
        return rc;
1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802

    while ((ret = virDirRead(dir, &entry, stateDir)) > 0) {
        virStoragePoolObjPtr pool;

        if (!virFileStripSuffix(entry->d_name, ".xml"))
            continue;

        if (!(pool = virStoragePoolLoadState(pools, stateDir, entry->d_name)))
            continue;
        virStoragePoolObjUnlock(pool);
    }

J
Ján Tomko 已提交
1803
    VIR_DIR_CLOSE(dir);
1804 1805 1806 1807
    return ret;
}


1808
int
1809
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1810
                             const char *configDir,
1811 1812
                             const char *autostartDir)
{
1813 1814
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
1815
    int ret;
J
Ján Tomko 已提交
1816
    int rc;
1817

J
Ján Tomko 已提交
1818 1819
    if ((rc = virDirOpenIfExists(&dir, configDir)) <= 0)
        return rc;
1820

E
Eric Blake 已提交
1821
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
1822 1823
        char *path;
        char *autostartLink;
1824
        virStoragePoolObjPtr pool;
1825 1826 1827 1828

        if (!virFileHasSuffix(entry->d_name, ".xml"))
            continue;

1829
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1830 1831
            continue;

1832 1833 1834
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1835 1836 1837
            continue;
        }

1838
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1839
                                     autostartLink);
1840 1841
        if (pool)
            virStoragePoolObjUnlock(pool);
1842 1843 1844

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1845 1846
    }

J
Ján Tomko 已提交
1847
    VIR_DIR_CLOSE(dir);
E
Eric Blake 已提交
1848
    return ret;
1849 1850
}

1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865

static int virStoragePoolSaveXML(const char *path,
                                 virStoragePoolDefPtr def,
                                 const char *xml)
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    int ret = -1;

    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(path,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);

    return ret;
}
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899


int
virStoragePoolSaveState(const char *stateFile,
                        virStoragePoolDefPtr def)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    int ret = -1;
    char *xml;

    virBufferAddLit(&buf, "<poolstate>\n");
    virBufferAdjustIndent(&buf, 2);

    if (virStoragePoolDefFormatBuf(&buf, def) < 0)
        goto error;

    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</poolstate>\n");

    if (virBufferCheckError(&buf) < 0)
        goto error;

    if (!(xml = virBufferContentAndReset(&buf)))
        goto error;

    if (virStoragePoolSaveXML(stateFile, def, xml))
        goto error;

    ret = 0;

 error:
    VIR_FREE(xml);
    return ret;
}
1900 1901


1902
int
1903
virStoragePoolSaveConfig(const char *configFile,
1904 1905
                         virStoragePoolDefPtr def)
{
1906
    char *xml;
1907
    int ret = -1;
1908

1909 1910 1911 1912 1913 1914
    if (!(xml = virStoragePoolDefFormat(def))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
        return -1;
    }

1915 1916
    if (virStoragePoolSaveXML(configFile, def, xml))
        goto cleanup;
1917

1918 1919 1920
    ret = 0;
 cleanup:
    VIR_FREE(xml);
1921 1922 1923 1924 1925 1926 1927 1928
    return ret;
}

int
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
                         virStoragePoolObjPtr pool,
                         virStoragePoolDefPtr def)
{
1929
    if (!pool->configFile) {
1930 1931
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1932 1933
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1934 1935 1936
            return -1;
        }

1937 1938
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1939 1940 1941
            return -1;
        }

1942 1943
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1944
            VIR_FREE(pool->configFile);
1945 1946 1947 1948
            return -1;
        }
    }

1949
    return virStoragePoolSaveConfig(pool->configFile, def);
1950 1951 1952
}

int
1953 1954
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
1955
    if (!pool->configFile) {
1956 1957
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1958 1959 1960 1961
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1962 1963 1964
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1965 1966 1967 1968 1969
        return -1;
    }

    return 0;
}
1970

1971
virStoragePoolSourcePtr
1972
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1973 1974 1975
{
    virStoragePoolSourcePtr source;

1976
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0)
1977 1978 1979 1980 1981 1982 1983 1984
        return NULL;

    source = &list->sources[list->nsources++];
    memset(source, 0, sizeof(*source));

    return source;
}

1985 1986
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1987
{
1988
    virStoragePoolOptionsPtr options;
1989
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1990
    const char *type;
1991
    size_t i;
1992

1993
    options = virStoragePoolOptionsForPoolType(def->type);
1994 1995 1996
    if (options == NULL)
        return NULL;

1997
    type = virStoragePoolTypeToString(def->type);
1998
    if (!type) {
1999 2000
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
2001 2002 2003 2004
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
2005
    virBufferAdjustIndent(&buf, 2);
2006

2007
    for (i = 0; i < def->nsources; i++)
2008
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
2009

2010
    virBufferAdjustIndent(&buf, -2);
2011 2012
    virBufferAddLit(&buf, "</sources>\n");

2013 2014
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
2015 2016

    return virBufferContentAndReset(&buf);
2017

2018
 cleanup:
2019
    virBufferFreeAndReset(&buf);
2020
    return NULL;
2021
}
D
Daniel P. Berrange 已提交
2022 2023


2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
/*
 * virStoragePoolObjIsDuplicate:
 * @doms : virStoragePoolObjListPtr to search
 * @def  : virStoragePoolDefPtr definition of pool to lookup
 * @check_active: If true, ensure that pool is not active
 *
 * Returns: -1 on error
 *          0 if pool is new
 *          1 if pool is a duplicate
 */
2034 2035 2036 2037
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
{
    int ret = -1;
    virStoragePoolObjPtr pool = NULL;

    /* See if a Pool with matching UUID already exists */
    pool = virStoragePoolObjFindByUUID(pools, def->uuid);
    if (pool) {
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(pool->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(pool->def->uuid, uuidstr);
2049 2050 2051
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
2052 2053 2054 2055 2056 2057
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
2058 2059 2060
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
2061 2062 2063 2064
                goto cleanup;
            }
        }

J
Ján Tomko 已提交
2065
        ret = 1;
2066 2067 2068 2069 2070 2071
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        pool = virStoragePoolObjFindByName(pools, def->name);
        if (pool) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(pool->def->uuid, uuidstr);
2072 2073 2074
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2075 2076
            goto cleanup;
        }
J
Ján Tomko 已提交
2077
        ret = 0;
2078 2079
    }

2080
 cleanup:
2081 2082 2083 2084 2085
    if (pool)
        virStoragePoolObjUnlock(pool);
    return ret;
}

2086

2087 2088 2089
static int
getSCSIHostNumber(virStoragePoolSourceAdapter adapter,
                  unsigned int *hostnum)
2090
{
2091 2092 2093 2094 2095
    int ret = -1;
    unsigned int num;
    char *name = NULL;

    if (adapter.data.scsi_host.has_parent) {
2096
        virPCIDeviceAddress addr = adapter.data.scsi_host.parentaddr;
2097 2098
        unsigned int unique_id = adapter.data.scsi_host.unique_id;

2099
        if (!(name = virSCSIHostGetNameByParentaddr(addr.domain,
2100 2101 2102 2103 2104
                                                    addr.bus,
                                                    addr.slot,
                                                    addr.function,
                                                    unique_id)))
            goto cleanup;
2105
        if (virSCSIHostGetNumber(name, &num) < 0)
2106 2107
            goto cleanup;
    } else {
2108
        if (virSCSIHostGetNumber(adapter.data.scsi_host.name, &num) < 0)
2109 2110 2111 2112 2113 2114 2115 2116 2117
            goto cleanup;
    }

    *hostnum = num;
    ret = 0;

 cleanup:
    VIR_FREE(name);
    return ret;
2118
}
2119

2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134

static bool
virStorageIsSameHostnum(const char *name,
                        unsigned int scsi_hostnum)
{
    unsigned int fc_hostnum;

    if (virSCSIHostGetNumber(name, &fc_hostnum) == 0 &&
        scsi_hostnum == fc_hostnum)
        return true;

    return false;
}


2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
/*
 * matchFCHostToSCSIHost:
 *
 * @conn: Connection pointer
 * @fc_adapter: fc_host adapter (either def or pool->def)
 * @scsi_hostnum: Already determined "scsi_pool" hostnum
 *
 * Returns true/false whether there is a match between the incoming
 *         fc_adapter host# and the scsi_host host#
 */
static bool
matchFCHostToSCSIHost(virConnectPtr conn,
                      virStoragePoolSourceAdapter fc_adapter,
                      unsigned int scsi_hostnum)
{
2150
    bool ret = false;
2151
    char *name = NULL;
2152
    char *scsi_host_name = NULL;
2153 2154
    char *parent_name = NULL;

2155
    /* If we have a parent defined, get its hostnum, and compare to the
2156 2157 2158
     * scsi_hostnum. If they are the same, then we have a match
     */
    if (fc_adapter.data.fchost.parent &&
2159
        virStorageIsSameHostnum(fc_adapter.data.fchost.parent, scsi_hostnum))
2160 2161 2162 2163 2164
        return true;

    /* If we find an fc_adapter name, then either libvirt created a vHBA
     * for this fc_host or a 'virsh nodedev-create' generated a vHBA.
     */
2165 2166
    if ((name = virVHBAGetHostByWWN(NULL, fc_adapter.data.fchost.wwnn,
                                    fc_adapter.data.fchost.wwpn))) {
2167 2168 2169 2170

        /* Get the scsi_hostN for the vHBA in order to see if it
         * matches our scsi_hostnum
         */
2171
        if (virStorageIsSameHostnum(name, scsi_hostnum)) {
2172 2173
            ret = true;
            goto cleanup;
2174 2175 2176 2177 2178 2179 2180 2181
        }

        /* We weren't provided a parent, so we have to query the node
         * device driver in order to ascertain the parent of the vHBA.
         * If the parent fc_hostnum is the same as the scsi_hostnum, we
         * have a match.
         */
        if (conn && !fc_adapter.data.fchost.parent) {
2182 2183
            if (virAsprintf(&scsi_host_name, "scsi_%s", name) < 0)
                goto cleanup;
2184 2185
            if ((parent_name = virNodeDeviceGetParentName(conn,
                                                          scsi_host_name))) {
2186
                if (virStorageIsSameHostnum(parent_name, scsi_hostnum)) {
2187 2188
                    ret = true;
                    goto cleanup;
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
                }
            } else {
                /* Throw away the error and fall through */
                virResetLastError();
                VIR_DEBUG("Could not determine parent vHBA");
            }
        }
    }

    /* NB: Lack of a name means that this vHBA hasn't yet been created,
     *     which means our scsi_host cannot be using the vHBA. Furthermore,
     *     lack of a provided parent means libvirt is going to choose the
     *     "best" fc_host capable adapter based on availabilty. That could
     *     conflict with an existing scsi_host definition, but there's no
     *     way to know that now.
     */
2205 2206 2207 2208 2209 2210

 cleanup:
    VIR_FREE(name);
    VIR_FREE(parent_name);
    VIR_FREE(scsi_host_name);
    return ret;
2211 2212
}

2213 2214 2215 2216
static bool
matchSCSIAdapterParent(virStoragePoolObjPtr pool,
                       virStoragePoolDefPtr def)
{
2217
    virPCIDeviceAddressPtr pooladdr =
2218
        &pool->def->source.adapter.data.scsi_host.parentaddr;
2219
    virPCIDeviceAddressPtr defaddr =
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
        &def->source.adapter.data.scsi_host.parentaddr;
    int pool_unique_id =
        pool->def->source.adapter.data.scsi_host.unique_id;
    int def_unique_id =
        def->source.adapter.data.scsi_host.unique_id;
    if (pooladdr->domain == defaddr->domain &&
        pooladdr->bus == defaddr->bus &&
        pooladdr->slot == defaddr->slot &&
        pooladdr->function == defaddr->function &&
        pool_unique_id == def_unique_id) {
        return true;
    }
    return false;
}

2235 2236 2237 2238 2239 2240 2241
static bool
virStoragePoolSourceMatchSingleHost(virStoragePoolSourcePtr poolsrc,
                                    virStoragePoolSourcePtr defsrc)
{
    if (poolsrc->nhost != 1 && defsrc->nhost != 1)
        return false;

2242 2243
    if (defsrc->hosts[0].port &&
        poolsrc->hosts[0].port != defsrc->hosts[0].port)
2244 2245
        return false;

2246 2247 2248
    return STREQ(poolsrc->hosts[0].name, defsrc->hosts[0].name);
}

2249

2250 2251 2252 2253 2254 2255 2256
static bool
virStoragePoolSourceISCSIMatch(virStoragePoolObjPtr matchpool,
                               virStoragePoolDefPtr def)
{
    virStoragePoolSourcePtr poolsrc = &matchpool->def->source;
    virStoragePoolSourcePtr defsrc = &def->source;

2257
    /* NB: Do not check the source host name */
2258 2259 2260 2261 2262 2263 2264
    if (STRNEQ_NULLABLE(poolsrc->initiator.iqn, defsrc->initiator.iqn))
        return false;

    return true;
}


2265
int
2266 2267
virStoragePoolSourceFindDuplicate(virConnectPtr conn,
                                  virStoragePoolObjListPtr pools,
2268
                                  virStoragePoolDefPtr def)
2269
{
2270
    size_t i;
2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
    int ret = 1;
    virStoragePoolObjPtr pool = NULL;
    virStoragePoolObjPtr matchpool = NULL;

    /* Check the pool list for duplicate underlying storage */
    for (i = 0; i < pools->count; i++) {
        pool = pools->objs[i];
        if (def->type != pool->def->type)
            continue;

N
Nitesh Konkar 已提交
2281
        /* Don't match against ourself if re-defining existing pool ! */
2282 2283 2284
        if (STREQ(pool->def->name, def->name))
            continue;

2285 2286
        virStoragePoolObjLock(pool);

2287
        switch ((virStoragePoolType)pool->def->type) {
2288 2289 2290 2291
        case VIR_STORAGE_POOL_DIR:
            if (STREQ(pool->def->target.path, def->target.path))
                matchpool = pool;
            break;
2292

2293
        case VIR_STORAGE_POOL_GLUSTER:
2294 2295 2296 2297 2298 2299 2300 2301
            if (STREQ(pool->def->source.name, def->source.name) &&
                STREQ_NULLABLE(pool->def->source.dir, def->source.dir) &&
                virStoragePoolSourceMatchSingleHost(&pool->def->source,
                                                    &def->source))
                matchpool = pool;
            break;

        case VIR_STORAGE_POOL_NETFS:
2302 2303 2304
            if (STREQ(pool->def->source.dir, def->source.dir) &&
                virStoragePoolSourceMatchSingleHost(&pool->def->source,
                                                    &def->source))
2305 2306
                matchpool = pool;
            break;
2307

2308
        case VIR_STORAGE_POOL_SCSI:
2309
            if (pool->def->source.adapter.type ==
2310 2311
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST &&
                def->source.adapter.type ==
2312 2313 2314 2315 2316 2317 2318
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
                if (STREQ(pool->def->source.adapter.data.fchost.wwnn,
                          def->source.adapter.data.fchost.wwnn) &&
                    STREQ(pool->def->source.adapter.data.fchost.wwpn,
                          def->source.adapter.data.fchost.wwpn))
                    matchpool = pool;
            } else if (pool->def->source.adapter.type ==
2319 2320
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST &&
                       def->source.adapter.type ==
2321
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
2322 2323
                unsigned int pool_hostnum, def_hostnum;

2324 2325 2326 2327 2328 2329 2330
                if (pool->def->source.adapter.data.scsi_host.has_parent &&
                    def->source.adapter.data.scsi_host.has_parent &&
                    matchSCSIAdapterParent(pool, def)) {
                    matchpool = pool;
                    break;
                }

2331 2332 2333
                if (getSCSIHostNumber(pool->def->source.adapter,
                                      &pool_hostnum) < 0 ||
                    getSCSIHostNumber(def->source.adapter, &def_hostnum) < 0)
2334
                    break;
2335 2336
                if (pool_hostnum == def_hostnum)
                    matchpool = pool;
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
            } else if (pool->def->source.adapter.type ==
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST &&
                       def->source.adapter.type ==
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
                unsigned int scsi_hostnum;

                /* Get the scsi_hostN for the scsi_host source adapter def */
                if (getSCSIHostNumber(def->source.adapter,
                                      &scsi_hostnum) < 0)
                    break;

                if (matchFCHostToSCSIHost(conn, pool->def->source.adapter,
                                          scsi_hostnum)) {
                    matchpool = pool;
                    break;
                }

            } else if (pool->def->source.adapter.type ==
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST &&
                       def->source.adapter.type ==
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
                unsigned int scsi_hostnum;

                if (getSCSIHostNumber(pool->def->source.adapter,
                                      &scsi_hostnum) < 0)
                    break;

                if (matchFCHostToSCSIHost(conn, def->source.adapter,
                                          scsi_hostnum)) {
                    matchpool = pool;
                    break;
                }
2369
            }
2370 2371 2372 2373
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2374 2375
                if (!virStoragePoolSourceISCSIMatch(matchpool, def))
                    matchpool = NULL;
2376 2377 2378 2379 2380
            }
            break;
        case VIR_STORAGE_POOL_FS:
        case VIR_STORAGE_POOL_LOGICAL:
        case VIR_STORAGE_POOL_DISK:
2381
        case VIR_STORAGE_POOL_ZFS:
2382 2383
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            break;
2384 2385 2386 2387 2388
        case VIR_STORAGE_POOL_SHEEPDOG:
            if (virStoragePoolSourceMatchSingleHost(&pool->def->source,
                                                    &def->source))
                matchpool = pool;
            break;
2389
        case VIR_STORAGE_POOL_MPATH:
2390 2391 2392
            /* Only one mpath pool is valid per host */
            matchpool = pool;
            break;
2393 2394 2395 2396
        case VIR_STORAGE_POOL_VSTORAGE:
            if (STREQ(pool->def->source.name, def->source.name))
                matchpool = pool;
            break;
2397 2398
        case VIR_STORAGE_POOL_RBD:
        case VIR_STORAGE_POOL_LAST:
2399 2400 2401
            break;
        }
        virStoragePoolObjUnlock(pool);
2402 2403 2404

        if (matchpool)
            break;
2405 2406 2407
    }

    if (matchpool) {
2408 2409 2410
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2411 2412 2413 2414
        ret = -1;
    }
    return ret;
}
2415

2416 2417
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2418
{
2419
    virMutexLock(&obj->lock);
2420 2421
}

2422 2423
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2424
{
2425
    virMutexUnlock(&obj->lock);
2426
}
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477

#define MATCH(FLAG) (flags & (FLAG))
static bool
virStoragePoolMatch(virStoragePoolObjPtr poolobj,
                    unsigned int flags)
{
    /* filter by active state */
    if (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ACTIVE) &&
        !((MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_ACTIVE) &&
           virStoragePoolObjIsActive(poolobj)) ||
          (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_INACTIVE) &&
           !virStoragePoolObjIsActive(poolobj))))
        return false;

    /* filter by persistence */
    if (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_PERSISTENT) &&
        !((MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_PERSISTENT) &&
           poolobj->configFile) ||
          (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_TRANSIENT) &&
           !poolobj->configFile)))
        return false;

    /* filter by autostart option */
    if (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_AUTOSTART) &&
        !((MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_AUTOSTART) &&
           poolobj->autostart) ||
          (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_NO_AUTOSTART) &&
           !poolobj->autostart)))
        return false;

    /* filter by pool type */
    if (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_POOL_TYPE)) {
        if (!((MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_DIR) &&
               (poolobj->def->type == VIR_STORAGE_POOL_DIR))     ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_FS) &&
               (poolobj->def->type == VIR_STORAGE_POOL_FS))      ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_NETFS) &&
               (poolobj->def->type == VIR_STORAGE_POOL_NETFS))   ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_LOGICAL) &&
               (poolobj->def->type == VIR_STORAGE_POOL_LOGICAL)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_DISK) &&
               (poolobj->def->type == VIR_STORAGE_POOL_DISK))    ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_ISCSI) &&
               (poolobj->def->type == VIR_STORAGE_POOL_ISCSI))   ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_SCSI) &&
               (poolobj->def->type == VIR_STORAGE_POOL_SCSI))    ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_MPATH) &&
               (poolobj->def->type == VIR_STORAGE_POOL_MPATH))   ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_RBD) &&
               (poolobj->def->type == VIR_STORAGE_POOL_RBD))     ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_SHEEPDOG) &&
2478 2479
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
2480 2481 2482 2483 2484
               (poolobj->def->type == VIR_STORAGE_POOL_GLUSTER)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_ZFS) &&
               poolobj->def->type == VIR_STORAGE_POOL_ZFS)       ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_VSTORAGE) &&
               poolobj->def->type == VIR_STORAGE_POOL_VSTORAGE)))
2485 2486 2487 2488 2489 2490 2491 2492
            return false;
    }

    return true;
}
#undef MATCH

int
2493 2494 2495 2496 2497
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2498 2499 2500 2501 2502
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2503
    size_t i;
2504

2505 2506
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2507 2508 2509 2510

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2511 2512
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2513 2514 2515
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2516 2517
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
                    virStoragePoolObjUnlock(poolobj);
                    goto cleanup;
                }
                tmp_pools[npools] = pool;
            }
            npools++;
        }
        virStoragePoolObjUnlock(poolobj);
    }

    if (tmp_pools) {
        /* trim the array to the final size */
        ignore_value(VIR_REALLOC_N(tmp_pools, npools + 1));
        *pools = tmp_pools;
        tmp_pools = NULL;
    }

    ret = npools;

2537
 cleanup:
2538
    if (tmp_pools) {
2539 2540
        for (i = 0; i < npools; i++)
            virObjectUnref(tmp_pools[i]);
2541 2542 2543 2544 2545
    }

    VIR_FREE(tmp_pools);
    return ret;
}