storage_conf.c 80.5 KB
Newer Older
1 2 3
/*
 * storage_conf.c: config handling for storage driver
 *
4
 * Copyright (C) 2006-2014 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
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 "storage_conf.h"
39
#include "virstoragefile.h"
40

41
#include "virxml.h"
42
#include "viruuid.h"
43
#include "virbuffer.h"
44
#include "viralloc.h"
E
Eric Blake 已提交
45
#include "virfile.h"
46
#include "virstring.h"
47
#include "virlog.h"
48

49 50
#define VIR_FROM_THIS VIR_FROM_STORAGE

51 52
VIR_LOG_INIT("conf.storage_conf");

53 54
#define DEFAULT_POOL_PERM_MODE 0755
#define DEFAULT_VOL_PERM_MODE  0600
55

56 57
VIR_ENUM_IMPL(virStorageVol,
              VIR_STORAGE_VOL_LAST,
58
              "file", "block", "dir", "network", "netdir")
59

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

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
75
              "auto", "nfs", "glusterfs", "cifs")
76 77 78 79

VIR_ENUM_IMPL(virStoragePoolFormatDisk,
              VIR_STORAGE_POOL_DISK_LAST,
              "unknown", "dos", "dvh", "gpt",
80
              "mac", "bsd", "pc98", "sun", "lvm2")
81 82 83

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
84
              "unknown", "lvm2")
85 86 87 88 89 90 91


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

94
VIR_ENUM_IMPL(virStoragePartedFs,
95
              VIR_STORAGE_PARTED_FS_TYPE_LAST,
96
              "ext2", "ext2", "fat16",
97 98 99
              "fat32", "linux-swap",
              "ext2", "ext2",
              "extended")
100

101
VIR_ENUM_IMPL(virStoragePoolSourceAdapter,
102 103 104
              VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_LAST,
              "default", "scsi_host", "fc_host")

105 106
typedef const char *(*virStorageVolFormatToString)(int format);
typedef int (*virStorageVolFormatFromString)(const char *format);
107 108
typedef const char *(*virStorageVolFeatureToString)(int feature);
typedef int (*virStorageVolFeatureFromString)(const char *feature);
109 110 111 112 113 114 115

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

typedef struct _virStorageVolOptions virStorageVolOptions;
typedef virStorageVolOptions *virStorageVolOptionsPtr;
struct _virStorageVolOptions {
116
    int defaultFormat;
117 118
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
119 120
    virStorageVolFeatureToString featureToString;
    virStorageVolFeatureFromString featureFromString;
121 122 123 124
};

/* Flags to indicate mandatory components in the pool source */
enum {
O
Osier Yang 已提交
125 126 127 128 129 130 131
    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),
132 133 134 135 136
};

typedef struct _virStoragePoolOptions virStoragePoolOptions;
typedef virStoragePoolOptions *virStoragePoolOptionsPtr;
struct _virStoragePoolOptions {
E
Eric Blake 已提交
137
    unsigned int flags;
138 139 140 141 142 143 144 145 146 147 148 149 150
    int defaultFormat;
    virStoragePoolFormatToString formatToString;
    virStoragePoolFormatFromString formatFromString;
};

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

E
Eric Blake 已提交
151 152 153 154 155 156 157 158 159
static int
virStorageVolumeFormatFromString(const char *format)
{
    int ret = virStorageFileFormatTypeFromString(format);
    if (ret == VIR_STORAGE_FILE_NONE)
        return -1;
    return ret;
}

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


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

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

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

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


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

    if (!def)
        return;

333 334
    VIR_FREE(def->name);
    VIR_FREE(def->key);
335

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

340
    virStorageSourceClear(&def->target);
341
    VIR_FREE(def);
342 343
}

344
static void
345
virStoragePoolSourceAdapterClear(virStoragePoolSourceAdapterPtr adapter)
346
{
347 348 349 350 351
    if (adapter->type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
        VIR_FREE(adapter->data.fchost.wwnn);
        VIR_FREE(adapter->data.fchost.wwpn);
        VIR_FREE(adapter->data.fchost.parent);
    } else if (adapter->type ==
352
               VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
353
        VIR_FREE(adapter->data.scsi_host.name);
354 355 356
    }
}

357 358 359 360 361 362 363
void
virStoragePoolSourceDeviceClear(virStoragePoolSourceDevicePtr dev)
{
    VIR_FREE(dev->freeExtents);
    VIR_FREE(dev->path);
}

364
void
365 366
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
367
    size_t i;
368

369
    if (!source)
370 371
        return;

372
    for (i = 0; i < source->nhost; i++)
373 374 375
        VIR_FREE(source->hosts[i].name);
    VIR_FREE(source->hosts);

376 377
    for (i = 0; i < source->ndevice; i++)
        virStoragePoolSourceDeviceClear(&source->devices[i]);
378 379 380
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
381
    virStoragePoolSourceAdapterClear(&source->adapter);
D
David Allan 已提交
382
    VIR_FREE(source->initiator.iqn);
383
    virStorageAuthDefFree(source->auth);
384 385
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
386 387
}

388 389 390 391 392 393 394
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

395
void
396 397
virStoragePoolDefFree(virStoragePoolDefPtr def)
{
398 399 400 401 402
    if (!def)
        return;

    VIR_FREE(def->name);

403
    virStoragePoolSourceClear(&def->source);
404

405 406 407
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
408 409 410 411
}


void
412 413
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
414 415 416
    if (!obj)
        return;

417 418
    virStoragePoolObjClearVols(obj);

419 420
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
421

422 423
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
424 425 426

    virMutexDestroy(&obj->lock);

427
    VIR_FREE(obj);
428 429
}

430 431
void
virStoragePoolObjListFree(virStoragePoolObjListPtr pools)
432
{
433
    size_t i;
434
    for (i = 0; i < pools->count; i++)
435 436 437 438 439
        virStoragePoolObjFree(pools->objs[i]);
    VIR_FREE(pools->objs);
    pools->count = 0;
}

440
void
441
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
442 443
                        virStoragePoolObjPtr pool)
{
444
    size_t i;
445

446 447
    virStoragePoolObjUnlock(pool);

448
    for (i = 0; i < pools->count; i++) {
449
        virStoragePoolObjLock(pools->objs[i]);
450
        if (pools->objs[i] == pool) {
451
            virStoragePoolObjUnlock(pools->objs[i]);
452
            virStoragePoolObjFree(pools->objs[i]);
453

454
            VIR_DELETE_ELEMENT(pools->objs, i, pools->count);
455 456
            break;
        }
457
        virStoragePoolObjUnlock(pools->objs[i]);
458
    }
459 460
}

461
static int
462
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
463 464
                             virStoragePoolSourcePtr source,
                             int pool_type,
465 466
                             xmlNodePtr node)
{
467
    int ret = -1;
468
    xmlNodePtr relnode, authnode, *nodeset = NULL;
469 470
    int nsource;
    size_t i;
471
    virStoragePoolOptionsPtr options;
472
    virStorageAuthDefPtr authdef = NULL;
473
    char *name = NULL;
474
    char *port = NULL;
475
    char *adapter_type = NULL;
476
    char *managed = NULL;
477
    int n;
478 479 480 481

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

482
    if ((options = virStoragePoolOptionsForPoolType(pool_type)) == NULL)
483 484
        goto cleanup;

485
    source->name = virXPathString("string(./name)", ctxt);
486
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
487
        virReportError(VIR_ERR_XML_ERROR, "%s",
488
                       _("element 'name' is mandatory for RBD pool"));
489 490
        goto cleanup;
    }
491 492

    if (options->formatFromString) {
493
        char *format = virXPathString("string(./format/@type)", ctxt);
494 495 496 497 498 499
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
500
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
501
                           _("unknown pool format type %s"), format);
502 503 504 505 506 507
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

508 509
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
510

511 512
    if (n) {
        if (VIR_ALLOC_N(source->hosts, n) < 0)
513
            goto cleanup;
514
        source->nhost = n;
515

516
        for (i = 0; i < source->nhost; i++) {
517 518
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
519 520
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool host name"));
521 522 523 524 525 526 527
                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) {
528 529 530
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
531 532 533 534 535
                    goto cleanup;
                }
            }
        }
    }
536

537
    VIR_FREE(nodeset);
538
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
539

540
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
541 542 543
    if (nsource < 0)
        goto cleanup;

544 545 546 547 548 549 550
    for (i = 0; i < nsource; i++) {
        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"));
551 552 553
            goto cleanup;
        }

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

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

    if ((adapter_type = virXPathString("string(./adapter/@type)", ctxt))) {
        if ((source->adapter.type =
568
             virStoragePoolSourceAdapterTypeFromString(adapter_type)) <= 0) {
569
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
570 571 572 573 574 575 576 577 578
                           _("Unknown pool adapter type '%s'"),
                           adapter_type);
            goto cleanup;
        }

        if (source->adapter.type ==
            VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            source->adapter.data.fchost.parent =
                virXPathString("string(./adapter/@parent)", ctxt);
579 580 581 582 583 584 585 586 587 588 589 590
            managed = virXPathString("string(./adapter/@managed)", ctxt);
            if (managed) {
                source->adapter.data.fchost.managed =
                    virTristateBoolTypeFromString(managed);
                if (source->adapter.data.fchost.managed < 0) {
                    virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                                   _("unknown fc_host managed setting '%s'"),
                                   managed);
                    goto cleanup;
                }
            }

591 592 593 594 595 596
            source->adapter.data.fchost.wwnn =
                virXPathString("string(./adapter/@wwnn)", ctxt);
            source->adapter.data.fchost.wwpn =
                virXPathString("string(./adapter/@wwpn)", ctxt);
        } else if (source->adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
597

598
            source->adapter.data.scsi_host.name =
599
                virXPathString("string(./adapter/@name)", ctxt);
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
            if (virXPathNode("./adapter/parentaddr", ctxt)) {
                xmlNodePtr addrnode = virXPathNode("./adapter/parentaddr/address",
                                                   ctxt);
                virDevicePCIAddressPtr addr =
                    &source->adapter.data.scsi_host.parentaddr;

                if (!addrnode) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("Missing scsi_host PCI address element"));
                    goto cleanup;
                }
                source->adapter.data.scsi_host.has_parent = true;
                if (virDevicePCIAddressParseXML(addrnode, addr) < 0)
                    goto cleanup;
                if ((virXPathInt("string(./adapter/parentaddr/@unique_id)",
                                 ctxt,
                                 &source->adapter.data.scsi_host.unique_id) < 0) ||
                    (source->adapter.data.scsi_host.unique_id < 0)) {
                    virReportError(VIR_ERR_XML_ERROR, "%s",
                                   _("Missing or invalid scsi adapter "
                                     "'unique_id' value"));
                    goto cleanup;
                }
            }
624 625 626 627 628 629
        }
    } else {
        char *wwnn = NULL;
        char *wwpn = NULL;
        char *parent = NULL;

630 631 632 633
        /* "type" was not specified in the XML, so we must verify that
         * "wwnn", "wwpn", "parent", or "parentaddr" are also not in the
         * XML. If any are found, then we cannot just use "name" alone".
         */
634 635 636 637 638 639 640 641 642 643
        wwnn = virXPathString("string(./adapter/@wwnn)", ctxt);
        wwpn = virXPathString("string(./adapter/@wwpn)", ctxt);
        parent = virXPathString("string(./adapter/@parent)", ctxt);

        if (wwnn || wwpn || parent) {
            VIR_FREE(wwnn);
            VIR_FREE(wwpn);
            VIR_FREE(parent);
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Use of 'wwnn', 'wwpn', and 'parent' attributes "
644 645 646 647 648 649 650 651
                             "requires use of the adapter 'type'"));
            goto cleanup;
        }

        if (virXPathNode("./adapter/parentaddr", ctxt)) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("Use of 'parent' element requires use "
                             "of the adapter 'type'"));
652 653 654 655 656 657
            goto cleanup;
        }

        /* To keep back-compat, 'type' is not required to specify
         * for scsi_host adapter.
         */
658
        if ((source->adapter.data.scsi_host.name =
659 660 661 662
             virXPathString("string(./adapter/@name)", ctxt)))
            source->adapter.type =
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST;
    }
663

664 665 666 667 668 669 670 671 672 673 674
    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;
675
        authdef = NULL;
676
    }
677

678 679 680
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

681
    ret = 0;
682
 cleanup:
683 684
    ctxt->node = relnode;

685
    VIR_FREE(port);
686
    VIR_FREE(nodeset);
687
    VIR_FREE(adapter_type);
688
    VIR_FREE(managed);
689
    virStorageAuthDefFree(authdef);
690 691
    return ret;
}
692

693
virStoragePoolSourcePtr
694
virStoragePoolDefParseSourceString(const char *srcSpec,
695 696 697 698 699 700 701
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

702 703 704
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
705 706
        goto cleanup;

707
    if (VIR_ALLOC(def) < 0)
708 709
        goto cleanup;

710
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
711 712
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
713 714 715
        goto cleanup;
    }

716
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
717 718 719 720 721
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
722
 cleanup:
723
    virStoragePoolSourceFree(def);
724 725 726 727 728
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
729

730
static int
731
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
732 733
                        virStoragePermsPtr perms,
                        const char *permxpath,
734 735
                        int defaultmode)
{
736
    char *mode;
737
    long long val;
738 739 740
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
741

742
    node = virXPathNode(permxpath, ctxt);
743 744 745
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
P
Philipp Hahn 已提交
746 747
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
748 749 750 751 752 753 754
        perms->label = NULL;
        return 0;
    }

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

755
    mode = virXPathString("string(./mode)", ctxt);
756
    if (!mode) {
757
        perms->mode = defaultmode;
758
    } else {
759 760 761
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
762
            VIR_FREE(mode);
763 764
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
765
            goto error;
766
        }
767
        perms->mode = tmp;
768
        VIR_FREE(mode);
769 770
    }

771
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
772
        perms->uid = (uid_t) -1;
773
    } else {
774
        if (virXPathLongLong("number(./owner)", ctxt, &val) < 0 ||
775 776
            ((uid_t)val != val &&
             val != -1)) {
777 778
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed owner element"));
779
            goto error;
780
        }
781 782

        perms->uid = val;
783 784
    }

785
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
786
        perms->gid = (gid_t) -1;
787
    } else {
788
        if (virXPathLongLong("number(./group)", ctxt, &val) < 0 ||
789 790
            ((gid_t) val != val &&
             val != -1)) {
791 792
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed group element"));
793
            goto error;
794
        }
795
        perms->gid = val;
796 797 798
    }

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

801
    ret = 0;
802
 error:
803 804
    ctxt->node = relnode;
    return ret;
805 806 807
}

static virStoragePoolDefPtr
808 809
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
810
    virStoragePoolOptionsPtr options;
811
    virStoragePoolDefPtr ret;
812
    xmlNodePtr source_node;
813
    char *type = NULL;
814
    char *uuid = NULL;
815
    char *target_path = NULL;
816

817
    if (VIR_ALLOC(ret) < 0)
818 819
        return NULL;

820
    type = virXPathString("string(./@type)", ctxt);
821 822 823 824 825 826
    if (type == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("storage pool missing type attribute"));
        goto error;
    }

827
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
828
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
829
                       _("unknown storage pool type %s"), type);
830
        goto error;
831 832
    }

833
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL)
834
        goto error;
835

836
    source_node = virXPathNode("./source", ctxt);
837
    if (source_node) {
838
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
839
                                         source_node) < 0)
840
            goto error;
841 842
    }

843
    ret->name = virXPathString("string(./name)", ctxt);
844
    if (ret->name == NULL &&
845
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
846
        ret->name = ret->source.name;
847
    if (ret->name == NULL) {
848 849
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
850
        goto error;
851 852
    }

853
    uuid = virXPathString("string(./uuid)", ctxt);
854 855
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
856 857
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
858
            goto error;
859 860 861
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
862 863
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
864
            goto error;
865 866 867
        }
    }

868
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
869
        if (!ret->source.nhost) {
870
            virReportError(VIR_ERR_XML_ERROR, "%s",
871
                           _("missing storage pool source host name"));
872
            goto error;
873 874 875
        }
    }

876
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
877
        if (!ret->source.dir) {
878 879
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
880
            goto error;
881 882
        }
    }
883
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
884 885
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
886
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
887
                goto error;
888 889
        }
    }
890

891
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
892 893 894
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
895
            goto error;
896
        }
897 898 899 900 901 902 903 904

        if (ret->source.adapter.type ==
            VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            if (!ret->source.adapter.data.fchost.wwnn ||
                !ret->source.adapter.data.fchost.wwpn) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("'wwnn' and 'wwpn' must be specified for adapter "
                                 "type 'fchost'"));
905
                goto error;
906 907 908 909
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
910
                goto error;
911 912
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
913 914 915 916 917 918 919 920 921 922
            if (!ret->source.adapter.data.scsi_host.name &&
                !ret->source.adapter.data.scsi_host.has_parent) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("Either 'name' or 'parent' must be specified "
                                 "for the 'scsi_host' adapter"));
                goto error;
            }

            if (ret->source.adapter.data.scsi_host.name &&
                ret->source.adapter.data.scsi_host.has_parent) {
923
                virReportError(VIR_ERR_XML_ERROR, "%s",
924 925
                               _("Both 'name' and 'parent' cannot be specified "
                                 "for the 'scsi_host' adapter"));
926
                goto error;
927 928
            }
        }
929
    }
930

931 932 933
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
934 935
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
936
            goto error;
937 938 939
        }
    }

940 941 942
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
943
        if (ret->type == VIR_STORAGE_POOL_LOGICAL) {
944
            if (virAsprintf(&target_path, "/dev/%s", ret->source.name) < 0)
945
                goto error;
R
Roman Bogorodskiy 已提交
946
        } else if (ret->type == VIR_STORAGE_POOL_ZFS) {
947
            if (virAsprintf(&target_path, "/dev/zvol/%s", ret->source.name) < 0)
R
Roman Bogorodskiy 已提交
948
                goto error;
949 950 951 952 953 954 955
        } else {
            target_path = virXPathString("string(./target/path)", ctxt);
            if (!target_path) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool target path"));
                goto error;
            }
956
        }
957
        ret->target.path = virFileSanitizePath(target_path);
958
        if (!ret->target.path)
959
            goto error;
960

961
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
962 963
                                    "./target/permissions",
                                    DEFAULT_POOL_PERM_MODE) < 0)
964
            goto error;
965
    }
966

967
 cleanup:
968
    VIR_FREE(uuid);
969 970 971 972
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

973
 error:
974
    virStoragePoolDefFree(ret);
975 976
    ret = NULL;
    goto cleanup;
977 978 979
}

virStoragePoolDefPtr
980
virStoragePoolDefParseNode(xmlDocPtr xml,
981 982
                           xmlNodePtr root)
{
983 984 985
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

986
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
987
        virReportError(VIR_ERR_XML_ERROR,
988 989 990
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
991 992 993 994 995
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
996
        virReportOOMError();
997 998 999 1000
        goto cleanup;
    }

    ctxt->node = root;
1001
    def = virStoragePoolDefParseXML(ctxt);
1002
 cleanup:
1003 1004 1005 1006 1007
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
1008
virStoragePoolDefParse(const char *xmlStr,
1009 1010
                       const char *filename)
{
1011
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1012
    xmlDocPtr xml;
1013

1014
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
1015 1016
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1017 1018
    }

1019 1020 1021
    return ret;
}

1022
virStoragePoolDefPtr
1023
virStoragePoolDefParseString(const char *xmlStr)
1024
{
1025
    return virStoragePoolDefParse(xmlStr, NULL);
1026 1027 1028
}

virStoragePoolDefPtr
1029
virStoragePoolDefParseFile(const char *filename)
1030
{
1031
    return virStoragePoolDefParse(NULL, filename);
1032 1033
}

1034
static int
1035
virStoragePoolSourceFormat(virBufferPtr buf,
1036
                           virStoragePoolOptionsPtr options,
1037 1038
                           virStoragePoolSourcePtr src)
{
1039
    size_t i, j;
1040

1041 1042 1043
    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

1044 1045
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
1046
            virBufferEscapeString(buf, "<host name='%s'",
1047
                                  src->hosts[i].name);
1048 1049 1050 1051
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
1052
    }
1053

1054
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
1055
        src->ndevice) {
1056
        for (i = 0; i < src->ndevice; i++) {
1057
            if (src->devices[i].nfreeExtent) {
1058
                virBufferEscapeString(buf, "<device path='%s'>\n",
1059
                                      src->devices[i].path);
1060
                virBufferAdjustIndent(buf, 2);
1061
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
1062
                    virBufferAsprintf(buf, "<freeExtent start='%llu' end='%llu'/>\n",
1063 1064 1065
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
1066 1067
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</device>\n");
1068
            } else {
1069
                virBufferEscapeString(buf, "<device path='%s'/>\n",
1070
                                      src->devices[i].path);
1071
            }
1072 1073
        }
    }
1074

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

1078 1079 1080
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER)) {
        if (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST ||
            src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST)
1081
            virBufferAsprintf(buf, "<adapter type='%s'",
1082
                              virStoragePoolSourceAdapterTypeToString(src->adapter.type));
1083 1084 1085 1086

        if (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            virBufferEscapeString(buf, " parent='%s'",
                                  src->adapter.data.fchost.parent);
1087 1088 1089
            if (src->adapter.data.fchost.managed)
                virBufferAsprintf(buf, " managed='%s'",
                                  virTristateBoolTypeToString(src->adapter.data.fchost.managed));
E
Eric Blake 已提交
1090
            virBufferAsprintf(buf, " wwnn='%s' wwpn='%s'/>\n",
1091 1092 1093
                              src->adapter.data.fchost.wwnn,
                              src->adapter.data.fchost.wwpn);
        } else if (src->adapter.type ==
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            if (src->adapter.data.scsi_host.name) {
                virBufferAsprintf(buf, " name='%s'/>\n",
                                  src->adapter.data.scsi_host.name);
            } else {
                virDevicePCIAddress addr;
                virBufferAddLit(buf, ">\n");
                virBufferAdjustIndent(buf, 2);
                virBufferAsprintf(buf, "<parentaddr unique_id='%d'>\n",
                                  src->adapter.data.scsi_host.unique_id);
                virBufferAdjustIndent(buf, 2);
                addr = src->adapter.data.scsi_host.parentaddr;
                ignore_value(virDevicePCIAddressFormat(buf, addr, false));
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</parentaddr>\n");
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</adapter>\n");
            }
1112 1113
        }
    }
1114

1115
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
1116
        virBufferEscapeString(buf, "<name>%s</name>\n", src->name);
1117

D
David Allan 已提交
1118 1119
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN) &&
        src->initiator.iqn) {
1120 1121 1122
        virBufferAddLit(buf, "<initiator>\n");
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<iqn name='%s'/>\n",
E
Eric Blake 已提交
1123
                              src->initiator.iqn);
1124 1125
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</initiator>\n");
D
David Allan 已提交
1126 1127
    }

1128 1129 1130
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
1131 1132 1133
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
1134 1135
            return -1;
        }
1136
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1137 1138
    }

1139 1140 1141
    if (src->auth) {
        if (virStorageAuthDefFormat(buf, src->auth) < 0)
            return -1;
1142 1143
    }

1144 1145
    virBufferEscapeString(buf, "<vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "<product name='%s'/>\n", src->product);
1146

1147 1148
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
1149 1150 1151
    return 0;
}

1152 1153

char *
1154 1155
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
1156
    virStoragePoolOptionsPtr options;
1157
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1158 1159 1160
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1161
    options = virStoragePoolOptionsForPoolType(def->type);
1162 1163 1164
    if (options == NULL)
        return NULL;

1165
    type = virStoragePoolTypeToString(def->type);
1166
    if (!type) {
1167 1168
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1169 1170
        goto cleanup;
    }
1171
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
1172 1173
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
1174 1175

    virUUIDFormat(def->uuid, uuid);
1176
    virBufferAsprintf(&buf, "<uuid>%s</uuid>\n", uuid);
1177

1178
    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1179
                      def->capacity);
1180
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1181
                      def->allocation);
1182
    virBufferAsprintf(&buf, "<available unit='bytes'>%llu</available>\n",
1183
                      def->available);
1184

1185
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1186
        goto cleanup;
1187

1188 1189
    /* RBD, Sheepdog, and Gluster devices are not local block devs nor
     * files, so they don't have a target */
1190
    if (def->type != VIR_STORAGE_POOL_RBD &&
1191 1192
        def->type != VIR_STORAGE_POOL_SHEEPDOG &&
        def->type != VIR_STORAGE_POOL_GLUSTER) {
1193 1194
        virBufferAddLit(&buf, "<target>\n");
        virBufferAdjustIndent(&buf, 2);
1195

1196
        virBufferEscapeString(&buf, "<path>%s</path>\n", def->target.path);
1197

1198 1199 1200
        virBufferAddLit(&buf, "<permissions>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<mode>0%o</mode>\n",
1201
                          def->target.perms.mode);
1202
        virBufferAsprintf(&buf, "<owner>%d</owner>\n",
1203
                          (int) def->target.perms.uid);
1204
        virBufferAsprintf(&buf, "<group>%d</group>\n",
1205
                          (int) def->target.perms.gid);
1206
        virBufferEscapeString(&buf, "<label>%s</label>\n",
1207
                              def->target.perms.label);
1208

1209 1210 1211 1212
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</permissions>\n");
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</target>\n");
1213
    }
1214
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1215
    virBufferAddLit(&buf, "</pool>\n");
1216

1217 1218
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1219

1220
    return virBufferContentAndReset(&buf);
1221

1222
 cleanup:
1223
    virBufferFreeAndReset(&buf);
1224 1225 1226 1227 1228
    return NULL;
}


static int
1229
virStorageSize(const char *unit,
1230
               const char *val,
1231 1232 1233
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1234 1235
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("malformed capacity element"));
1236 1237
        return -1;
    }
1238 1239 1240 1241
    /* 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;
1242 1243 1244 1245 1246

    return 0;
}

static virStorageVolDefPtr
1247
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1248 1249
                         xmlXPathContextPtr ctxt,
                         unsigned int flags)
1250
{
1251
    virStorageVolDefPtr ret;
1252
    virStorageVolOptionsPtr options;
1253
    char *type = NULL;
1254 1255 1256
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1257
    char *backingStore = NULL;
1258
    xmlNodePtr node;
1259
    xmlNodePtr *nodes = NULL;
1260 1261
    size_t i;
    int n;
1262

1263
    virCheckFlags(VIR_VOL_XML_PARSE_NO_CAPACITY, NULL);
1264

1265
    options = virStorageVolOptionsForPoolType(pool->type);
1266 1267 1268
    if (options == NULL)
        return NULL;

1269
    if (VIR_ALLOC(ret) < 0)
1270 1271
        return NULL;

1272
    ret->name = virXPathString("string(./name)", ctxt);
1273
    if (ret->name == NULL) {
1274 1275
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing volume name element"));
1276
        goto error;
1277 1278
    }

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

1282 1283 1284 1285
    /* Technically overridden by pool refresh, but useful for unit tests */
    type = virXPathString("string(./@type)", ctxt);
    if (type) {
        if ((ret->type = virStorageVolTypeFromString(type)) < 0) {
1286
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1287 1288 1289 1290 1291
                           _("unknown volume type '%s'"), type);
            goto error;
        }
    }

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
    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,
                                    "./backingStore/permissions",
                                    DEFAULT_VOL_PERM_MODE) < 0)
            goto error;
    }

1323 1324
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1325 1326 1327 1328 1329
    if (capacity) {
        if (virStorageSize(unit, capacity, &ret->target.capacity) < 0)
            goto error;
    } else if (!(flags & VIR_VOL_XML_PARSE_NO_CAPACITY)) {
        virReportError(VIR_ERR_XML_ERROR, "%s", _("missing capacity element"));
1330
        goto error;
1331
    }
1332
    VIR_FREE(unit);
1333

1334
    allocation = virXPathString("string(./allocation)", ctxt);
1335
    if (allocation) {
1336
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1337
        if (virStorageSize(unit, allocation, &ret->target.allocation) < 0)
1338
            goto error;
1339
    } else {
1340
        ret->target.allocation = ret->target.capacity;
1341 1342
    }

1343
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1344
    if (options->formatFromString) {
1345
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1346 1347 1348 1349 1350 1351
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1352
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1353
                           _("unknown volume format type %s"), format);
1354
            VIR_FREE(format);
1355
            goto error;
1356
        }
1357
        VIR_FREE(format);
1358 1359
    }

1360 1361 1362
    if (VIR_ALLOC(ret->target.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->target.perms,
1363 1364
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1365
        goto error;
1366

1367
    node = virXPathNode("./target/encryption", ctxt);
1368
    if (node != NULL) {
1369
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1370 1371
                                                               node);
        if (ret->target.encryption == NULL)
1372
            goto error;
1373 1374
    }

1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    ret->target.compat = virXPathString("string(./target/compat)", ctxt);
    if (ret->target.compat) {
        char **version = virStringSplit(ret->target.compat, ".", 2);
        unsigned int result;

        if (!version || !version[1] ||
            virStrToLong_ui(version[0], NULL, 10, &result) < 0 ||
            virStrToLong_ui(version[1], NULL, 10, &result) < 0) {
            virStringFreeList(version);
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("forbidden characters in 'compat' attribute"));
            goto error;
        }
        virStringFreeList(version);
    }

C
Chunyan Liu 已提交
1391 1392 1393
    if (virXPathNode("./target/nocow", ctxt))
        ret->target.nocow = true;

1394 1395 1396 1397 1398 1399 1400 1401
    if (options->featureFromString && virXPathNode("./target/features", ctxt)) {
        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)))
1402
            goto error;
1403 1404 1405 1406 1407

        for (i = 0; i < n; i++) {
            int f = options->featureFromString((const char*)nodes[i]->name);

            if (f < 0) {
1408
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unsupported feature %s"),
1409 1410 1411 1412 1413 1414 1415 1416
                               (const char*)nodes[i]->name);
                goto error;
            }
            ignore_value(virBitmapSetBit(ret->target.features, f));
        }
        VIR_FREE(nodes);
    }

1417
 cleanup:
1418
    VIR_FREE(nodes);
1419 1420 1421
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1422
    VIR_FREE(type);
1423
    VIR_FREE(backingStore);
1424 1425
    return ret;

1426
 error:
1427
    virStorageVolDefFree(ret);
1428 1429
    ret = NULL;
    goto cleanup;
1430 1431 1432
}

virStorageVolDefPtr
1433
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1434
                          xmlDocPtr xml,
1435 1436
                          xmlNodePtr root,
                          unsigned int flags)
1437
{
1438 1439 1440
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1441
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1442
        virReportError(VIR_ERR_XML_ERROR,
1443 1444 1445
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1446 1447 1448 1449 1450
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1451
        virReportOOMError();
1452 1453 1454 1455
        goto cleanup;
    }

    ctxt->node = root;
1456
    def = virStorageVolDefParseXML(pool, ctxt, flags);
1457
 cleanup:
1458 1459 1460 1461 1462
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1463
virStorageVolDefParse(virStoragePoolDefPtr pool,
1464
                      const char *xmlStr,
1465 1466
                      const char *filename,
                      unsigned int flags)
1467
{
1468
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1469
    xmlDocPtr xml;
1470

1471
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
1472
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml), flags);
J
Jiri Denemark 已提交
1473
        xmlFreeDoc(xml);
1474 1475 1476 1477 1478
    }

    return ret;
}

1479
virStorageVolDefPtr
1480
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1481 1482
                            const char *xmlStr,
                            unsigned int flags)
1483
{
1484
    return virStorageVolDefParse(pool, xmlStr, NULL, flags);
1485 1486 1487
}

virStorageVolDefPtr
1488
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1489 1490
                          const char *filename,
                          unsigned int flags)
1491
{
1492
    return virStorageVolDefParse(pool, NULL, filename, flags);
1493
}
1494

1495 1496 1497 1498 1499 1500
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
1501
    virBufferAsprintf(buf, "<%s>%llu", name,
1502 1503 1504 1505 1506 1507
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1508
static int
1509
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1510
                             virBufferPtr buf,
1511
                             virStorageSourcePtr def,
1512 1513
                             const char *type)
{
1514 1515
    virBufferAsprintf(buf, "<%s>\n", type);
    virBufferAdjustIndent(buf, 2);
1516

1517
    virBufferEscapeString(buf, "<path>%s</path>\n", def->path);
1518 1519 1520 1521

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1522 1523 1524
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1525 1526
            return -1;
        }
1527
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1528 1529
    }

1530 1531 1532
    if (def->perms) {
        virBufferAddLit(buf, "<permissions>\n");
        virBufferAdjustIndent(buf, 2);
1533

1534 1535
        virBufferAsprintf(buf, "<mode>0%o</mode>\n",
                          def->perms->mode);
1536 1537 1538 1539
        virBufferAsprintf(buf, "<owner>%d</owner>\n",
                          (int) def->perms->uid);
        virBufferAsprintf(buf, "<group>%d</group>\n",
                          (int) def->perms->gid);
1540 1541


1542 1543
        virBufferEscapeString(buf, "<label>%s</label>\n",
                              def->perms->label);
1544

1545 1546 1547
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</permissions>\n");
    }
1548

1549
    if (def->timestamps) {
1550 1551
        virBufferAddLit(buf, "<timestamps>\n");
        virBufferAdjustIndent(buf, 2);
1552 1553 1554 1555
        virStorageVolTimestampFormat(buf, "atime", &def->timestamps->atime);
        virStorageVolTimestampFormat(buf, "mtime", &def->timestamps->mtime);
        virStorageVolTimestampFormat(buf, "ctime", &def->timestamps->ctime);
        virStorageVolTimestampFormat(buf, "btime", &def->timestamps->btime);
1556 1557
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timestamps>\n");
1558 1559
    }

1560 1561
    if (def->encryption &&
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1562
            return -1;
1563

1564
    virBufferEscapeString(buf, "<compat>%s</compat>\n", def->compat);
1565 1566

    if (options->featureToString && def->features) {
1567
        size_t i;
1568 1569 1570
        bool b;
        bool empty = virBitmapIsAllClear(def->features);

1571 1572 1573 1574 1575 1576
        if (empty) {
            virBufferAddLit(buf, "<features/>\n");
        } else {
            virBufferAddLit(buf, "<features>\n");
            virBufferAdjustIndent(buf, 2);
        }
1577 1578 1579 1580

        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
            ignore_value(virBitmapGetBit(def->features, i, &b));
            if (b)
1581
                virBufferAsprintf(buf, "<%s/>\n",
1582 1583
                                  options->featureToString(i));
        }
1584 1585 1586 1587
        if (!empty) {
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</features>\n");
        }
1588 1589
    }

1590 1591
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", type);
1592 1593
    return 0;
}
1594 1595

char *
1596
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1597 1598
                       virStorageVolDefPtr def)
{
1599
    virStorageVolOptionsPtr options;
1600
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1601

1602
    options = virStorageVolOptionsForPoolType(pool->type);
1603 1604 1605
    if (options == NULL)
        return NULL;

1606 1607
    virBufferAsprintf(&buf, "<volume type='%s'>\n",
                      virStorageVolTypeToString(def->type));
1608 1609 1610 1611 1612 1613
    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);
1614 1615

    if (def->source.nextent) {
1616
        size_t i;
1617
        const char *thispath = NULL;
1618
        for (i = 0; i < def->source.nextent; i++) {
1619 1620 1621
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1622
                    virBufferAddLit(&buf, "</device>\n");
1623

1624
                virBufferEscapeString(&buf, "<device path='%s'>\n",
1625
                                      def->source.extents[i].path);
1626 1627
            }

1628 1629
            virBufferAdjustIndent(&buf, 2);
            virBufferAsprintf(&buf, "<extent start='%llu' end='%llu'/>\n",
1630 1631
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1632
            virBufferAdjustIndent(&buf, -2);
1633 1634 1635
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1636
            virBufferAddLit(&buf, "</device>\n");
1637 1638
    }

1639 1640 1641 1642
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</source>\n");

    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1643
                      def->target.capacity);
1644
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1645
                      def->target.allocation);
1646

1647
    if (virStorageVolTargetDefFormat(options, &buf,
1648 1649
                                     &def->target, "target") < 0)
        goto cleanup;
1650

1651
    if (def->target.backingStore &&
1652
        virStorageVolTargetDefFormat(options, &buf,
1653 1654
                                     def->target.backingStore,
                                     "backingStore") < 0)
1655
        goto cleanup;
1656

1657
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1658
    virBufferAddLit(&buf, "</volume>\n");
1659

1660 1661
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1662

1663
    return virBufferContentAndReset(&buf);
1664

1665
 cleanup:
1666
    virBufferFreeAndReset(&buf);
1667 1668 1669 1670 1671
    return NULL;
}


virStoragePoolObjPtr
1672
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1673 1674
                            const unsigned char *uuid)
{
1675
    size_t i;
1676

1677
    for (i = 0; i < pools->count; i++) {
1678
        virStoragePoolObjLock(pools->objs[i]);
1679 1680
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1681 1682
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1683 1684 1685 1686 1687

    return NULL;
}

virStoragePoolObjPtr
1688
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1689 1690
                            const char *name)
{
1691
    size_t i;
1692

1693
    for (i = 0; i < pools->count; i++) {
1694
        virStoragePoolObjLock(pools->objs[i]);
1695 1696
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1697 1698
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1699 1700 1701 1702

    return NULL;
}

1703 1704
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1705 1706
                                         virStoragePoolDefPtr def)
{
1707
    size_t i, j;
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718

    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;
}

1719 1720 1721
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1722
    size_t i;
1723
    for (i = 0; i < pool->volumes.count; i++)
1724 1725 1726 1727
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1728 1729 1730 1731
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1732 1733
                          const char *key)
{
1734
    size_t i;
1735

1736
    for (i = 0; i < pool->volumes.count; i++)
1737 1738
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1739 1740 1741 1742 1743 1744

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1745 1746
                           const char *path)
{
1747
    size_t i;
1748

1749
    for (i = 0; i < pool->volumes.count; i++)
1750 1751
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1752 1753 1754 1755 1756 1757

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1758 1759
                           const char *name)
{
1760
    size_t i;
1761

1762
    for (i = 0; i < pool->volumes.count; i++)
1763 1764
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1765 1766 1767 1768 1769

    return NULL;
}

virStoragePoolObjPtr
1770
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1771 1772
                           virStoragePoolDefPtr def)
{
1773 1774
    virStoragePoolObjPtr pool;

1775
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1776 1777 1778 1779
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1780
            virStoragePoolDefFree(pool->newDef);
1781 1782 1783 1784 1785
            pool->newDef = def;
        }
        return pool;
    }

1786
    if (VIR_ALLOC(pool) < 0)
1787 1788
        return NULL;

1789
    if (virMutexInit(&pool->lock) < 0) {
1790 1791
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1792 1793 1794
        VIR_FREE(pool);
        return NULL;
    }
1795
    virStoragePoolObjLock(pool);
1796 1797
    pool->active = 0;

1798
    if (VIR_APPEND_ELEMENT_COPY(pools->objs, pools->count, pool) < 0) {
1799
        virStoragePoolObjUnlock(pool);
1800 1801 1802
        virStoragePoolObjFree(pool);
        return NULL;
    }
1803
    pool->def = def;
1804 1805 1806 1807 1808

    return pool;
}

static virStoragePoolObjPtr
1809
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1810 1811
                      const char *file,
                      const char *path,
1812 1813
                      const char *autostartLink)
{
1814 1815 1816
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1817
    if (!(def = virStoragePoolDefParseFile(path)))
1818 1819 1820
        return NULL;

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1821
        virReportError(VIR_ERR_XML_ERROR,
1822 1823
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1824
                       path, def->name);
1825 1826 1827 1828
        virStoragePoolDefFree(def);
        return NULL;
    }

1829
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1830 1831 1832 1833
        virStoragePoolDefFree(def);
        return NULL;
    }

1834
    VIR_FREE(pool->configFile);  /* for driver reload */
1835
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1836 1837 1838
        virStoragePoolDefFree(def);
        return NULL;
    }
1839
    VIR_FREE(pool->autostartLink); /* for driver reload */
1840
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1853
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1854
                             const char *configDir,
1855 1856
                             const char *autostartDir)
{
1857 1858
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
1859
    int ret;
1860

1861
    if (!(dir = opendir(configDir))) {
1862 1863
        if (errno == ENOENT)
            return 0;
1864
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1865
                             configDir);
1866 1867 1868
        return -1;
    }

E
Eric Blake 已提交
1869
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
1870 1871
        char *path;
        char *autostartLink;
1872
        virStoragePoolObjPtr pool;
1873 1874 1875 1876 1877 1878 1879

        if (entry->d_name[0] == '.')
            continue;

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

1880
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1881 1882
            continue;

1883 1884 1885
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1886 1887 1888
            continue;
        }

1889
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1890
                                     autostartLink);
1891 1892
        if (pool)
            virStoragePoolObjUnlock(pool);
1893 1894 1895

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1896 1897 1898
    }

    closedir(dir);
E
Eric Blake 已提交
1899
    return ret;
1900 1901 1902
}

int
1903
virStoragePoolSaveConfig(const char *configFile,
1904 1905
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1906
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1907
    char *xml;
1908
    int ret = -1;
1909

1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
    if (!(xml = virStoragePoolDefFormat(def))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
        return -1;
    }

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

    return ret;
}

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

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

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

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

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

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

    return 0;
}
1971

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

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

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

    return source;
}

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

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

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

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

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

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

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

    return virBufferContentAndReset(&buf);
2018

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


2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
/*
 * 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
 */
2035 2036 2037 2038
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
{
    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);
2050 2051 2052
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
2053 2054 2055 2056 2057 2058
            goto cleanup;
        }

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

J
Ján Tomko 已提交
2066
        ret = 1;
2067 2068 2069 2070 2071 2072
    } 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);
2073 2074 2075
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2076 2077
            goto cleanup;
        }
J
Ján Tomko 已提交
2078
        ret = 0;
2079 2080
    }

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

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 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 2142 2143 2144 2145
/*
 * virStoragePoolGetVhbaSCSIHostParent:
 *
 * Using the Node Device Driver, find the host# name found via wwnn/wwpn
 * lookup in the fc_host sysfs tree (e.g. virGetFCHostNameByWWN) to get
 * the parent 'scsi_host#'.
 *
 * @conn: Connection pointer (must be non-NULL on entry)
 * @name: Pointer a string from a virGetFCHostNameByWWN (e.g., "host#")
 *
 * Returns a "scsi_host#" string of the parent of the vHBA
 */
char *
virStoragePoolGetVhbaSCSIHostParent(virConnectPtr conn,
                                    const char *name)
{
    char *nodedev_name = NULL;
    virNodeDevicePtr device = NULL;
    char *xml = NULL;
    virNodeDeviceDefPtr def = NULL;
    char *vhba_parent = NULL;

    VIR_DEBUG("conn=%p, name=%s", conn, name);

    /* We get passed "host#" from the return from virGetFCHostNameByWWN,
     * so we need to adjust that to what the nodedev lookup expects
     */
    if (virAsprintf(&nodedev_name, "scsi_%s", name) < 0)
        goto cleanup;

    /* Compare the scsi_host for the name with the provided parent
     * if not the same, then fail
     */
    if (!(device = virNodeDeviceLookupByName(conn, nodedev_name))) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("Cannot find '%s' in node device database"),
                       nodedev_name);
        goto cleanup;
    }

    if (!(xml = virNodeDeviceGetXMLDesc(device, 0)))
        goto cleanup;

    if (!(def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE, NULL)))
        goto cleanup;

    /* The caller checks whether the returned value is NULL or not
     * before continuing
     */
    ignore_value(VIR_STRDUP(vhba_parent, def->parent));

 cleanup:
    VIR_FREE(nodedev_name);
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    virObjectUnref(device);
    return vhba_parent;
}

2146 2147 2148
static int
getSCSIHostNumber(virStoragePoolSourceAdapter adapter,
                  unsigned int *hostnum)
2149
{
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176
    int ret = -1;
    unsigned int num;
    char *name = NULL;

    if (adapter.data.scsi_host.has_parent) {
        virDevicePCIAddress addr = adapter.data.scsi_host.parentaddr;
        unsigned int unique_id = adapter.data.scsi_host.unique_id;

        if (!(name = virGetSCSIHostNameByParentaddr(addr.domain,
                                                    addr.bus,
                                                    addr.slot,
                                                    addr.function,
                                                    unique_id)))
            goto cleanup;
        if (virGetSCSIHostNumber(name, &num) < 0)
            goto cleanup;
    } else {
        if (virGetSCSIHostNumber(adapter.data.scsi_host.name, &num) < 0)
            goto cleanup;
    }

    *hostnum = num;
    ret = 0;

 cleanup:
    VIR_FREE(name);
    return ret;
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 2205 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 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254

/*
 * 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)
{
    char *name = NULL;
    char *parent_name = NULL;
    unsigned int fc_hostnum;

    /* If we have a parent defined, get it's hostnum, and compare to the
     * scsi_hostnum. If they are the same, then we have a match
     */
    if (fc_adapter.data.fchost.parent &&
        virGetSCSIHostNumber(fc_adapter.data.fchost.parent, &fc_hostnum) == 0 &&
        scsi_hostnum == fc_hostnum)
        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.
     */
    if ((name = virGetFCHostNameByWWN(NULL, fc_adapter.data.fchost.wwnn,
                                      fc_adapter.data.fchost.wwpn))) {

        /* Get the scsi_hostN for the vHBA in order to see if it
         * matches our scsi_hostnum
         */
        if (virGetSCSIHostNumber(name, &fc_hostnum) == 0 &&
            scsi_hostnum == fc_hostnum) {
            VIR_FREE(name);
            return true;
        }

        /* 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) {
            parent_name = virStoragePoolGetVhbaSCSIHostParent(conn, name);
            if (parent_name) {
                if (virGetSCSIHostNumber(parent_name, &fc_hostnum) == 0 &&
                    scsi_hostnum == fc_hostnum) {
                    VIR_FREE(parent_name);
                    VIR_FREE(name);
                    return true;
                }
                VIR_FREE(parent_name);
            } else {
                /* Throw away the error and fall through */
                virResetLastError();
                VIR_DEBUG("Could not determine parent vHBA");
            }
        }
        VIR_FREE(name);
    }

    /* 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.
     */
    return false;
}

2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
static bool
matchSCSIAdapterParent(virStoragePoolObjPtr pool,
                       virStoragePoolDefPtr def)
{
    virDevicePCIAddressPtr pooladdr =
        &pool->def->source.adapter.data.scsi_host.parentaddr;
    virDevicePCIAddressPtr defaddr =
        &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;
}

2277

2278
int
2279 2280
virStoragePoolSourceFindDuplicate(virConnectPtr conn,
                                  virStoragePoolObjListPtr pools,
2281
                                  virStoragePoolDefPtr def)
2282
{
2283
    size_t i;
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293
    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;

2294 2295 2296 2297
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2298 2299 2300 2301 2302 2303 2304 2305 2306
        virStoragePoolObjLock(pool);

        switch (pool->def->type) {
        case VIR_STORAGE_POOL_DIR:
            if (STREQ(pool->def->target.path, def->target.path))
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_NETFS:
            if ((STREQ(pool->def->source.dir, def->source.dir)) \
2307 2308
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
2309 2310 2311
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2312
            if (pool->def->source.adapter.type ==
2313 2314
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST &&
                def->source.adapter.type ==
2315 2316 2317 2318 2319 2320 2321
                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 ==
2322 2323
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST &&
                       def->source.adapter.type ==
2324
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
2325 2326
                unsigned int pool_hostnum, def_hostnum;

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

2334 2335 2336
                if (getSCSIHostNumber(pool->def->source.adapter,
                                      &pool_hostnum) < 0 ||
                    getSCSIHostNumber(def->source.adapter, &def_hostnum) < 0)
2337
                    break;
2338 2339
                if (pool_hostnum == def_hostnum)
                    matchpool = pool;
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 2369 2370 2371
            } 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;
                }
2372
            }
2373 2374 2375 2376
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2377 2378 2379 2380 2381 2382 2383 2384
                if (matchpool->def->source.nhost == 1 && def->source.nhost == 1) {
                    if (STREQ(matchpool->def->source.hosts[0].name, def->source.hosts[0].name)) {
                        if ((matchpool->def->source.initiator.iqn) && (def->source.initiator.iqn)) {
                            if (STREQ(matchpool->def->source.initiator.iqn, def->source.initiator.iqn))
                                break;
                            matchpool = NULL;
                        }
                        break;
2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
                    }
                }
                matchpool = NULL;
            }
            break;
        case VIR_STORAGE_POOL_FS:
        case VIR_STORAGE_POOL_LOGICAL:
        case VIR_STORAGE_POOL_DISK:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            break;
        default:
            break;
        }
        virStoragePoolObjUnlock(pool);
2399 2400 2401

        if (matchpool)
            break;
2402 2403 2404
    }

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

2413 2414
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2415
{
2416
    virMutexLock(&obj->lock);
2417 2418
}

2419 2420
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2421
{
2422
    virMutexUnlock(&obj->lock);
2423
}
2424 2425 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

#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) &&
2475 2476 2477
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
               (poolobj->def->type == VIR_STORAGE_POOL_GLUSTER))))
2478 2479 2480 2481 2482 2483 2484 2485
            return false;
    }

    return true;
}
#undef MATCH

int
2486 2487 2488 2489 2490
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2491 2492 2493 2494 2495
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2496
    size_t i;
2497

2498 2499
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2500 2501 2502 2503

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2504 2505
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2506 2507 2508
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2509 2510
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
                    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;

2530
 cleanup:
2531
    if (tmp_pools) {
2532 2533
        for (i = 0; i < npools; i++)
            virObjectUnref(tmp_pools[i]);
2534 2535 2536 2537 2538
    }

    VIR_FREE(tmp_pools);
    return ret;
}