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

#include <config.h>

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

36
#include "virerror.h"
37
#include "datatypes.h"
38
#include "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
VIR_ENUM_IMPL(virStorageVol,
              VIR_STORAGE_VOL_LAST,
O
Olga Krishtal 已提交
55 56
              "file", "block", "dir", "network",
              "netdir", "ploop")
57

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

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
73
              "auto", "nfs", "glusterfs", "cifs")
74 75 76 77

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

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
82
              "unknown", "lvm2")
83 84 85 86 87 88 89


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

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

99
VIR_ENUM_IMPL(virStoragePoolSourceAdapter,
100 101 102
              VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_LAST,
              "default", "scsi_host", "fc_host")

103 104 105 106 107 108 109 110 111
typedef const char *(*virStorageVolFormatToString)(int format);
typedef int (*virStorageVolFormatFromString)(const char *format);

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

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

/* Flags to indicate mandatory components in the pool source */
enum {
O
Osier Yang 已提交
119 120 121 122 123 124 125
    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),
126 127 128 129 130
};

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

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

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

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


static virStoragePoolTypeInfoPtr
281 282
virStoragePoolTypeInfoLookup(int type)
{
283
    size_t i;
284
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo); i++)
285 286 287
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

288 289
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
290 291 292 293
    return NULL;
}

static virStoragePoolOptionsPtr
294 295
virStoragePoolOptionsForPoolType(int type)
{
296 297 298 299 300 301 302
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
303 304
virStorageVolOptionsForPoolType(int type)
{
305 306 307 308 309 310 311
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


312
void
313 314
virStorageVolDefFree(virStorageVolDefPtr def)
{
315
    size_t i;
316 317 318 319

    if (!def)
        return;

320 321
    VIR_FREE(def->name);
    VIR_FREE(def->key);
322

323
    for (i = 0; i < def->source.nextent; i++)
324 325
        VIR_FREE(def->source.extents[i].path);
    VIR_FREE(def->source.extents);
326

327
    virStorageSourceClear(&def->target);
328
    VIR_FREE(def);
329 330
}

331
static void
332
virStoragePoolSourceAdapterClear(virStoragePoolSourceAdapterPtr adapter)
333
{
334 335 336 337 338
    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 ==
339
               VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
340
        VIR_FREE(adapter->data.scsi_host.name);
341 342 343
    }
}

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

351
void
352 353
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
354
    size_t i;
355

356
    if (!source)
357 358
        return;

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

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

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

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

    VIR_FREE(def->name);

390
    virStoragePoolSourceClear(&def->source);
391

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


void
399 400
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
401 402 403
    if (!obj)
        return;

404 405
    virStoragePoolObjClearVols(obj);

406 407
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
408

409 410
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
411 412 413

    virMutexDestroy(&obj->lock);

414
    VIR_FREE(obj);
415 416
}

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

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

433 434
    virStoragePoolObjUnlock(pool);

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

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

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

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

469
    if ((options = virStoragePoolOptionsForPoolType(pool_type)) == NULL)
470 471
        goto cleanup;

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

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

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

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

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

503
        for (i = 0; i < source->nhost; i++) {
504 505
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
506 507
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool host name"));
508 509 510 511 512 513 514
                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) {
515 516 517
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
518 519 520 521 522
                    goto cleanup;
                }
            }
        }
    }
523

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

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

531
    for (i = 0; i < nsource; i++) {
532
        char *partsep;
533 534 535 536 537 538
        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"));
539 540 541
            goto cleanup;
        }

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

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

561 562
    }

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

    if ((adapter_type = virXPathString("string(./adapter/@type)", ctxt))) {
        if ((source->adapter.type =
571
             virStoragePoolSourceAdapterTypeFromString(adapter_type)) <= 0) {
572
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
573 574 575 576 577 578 579 580 581
                           _("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);
582 583 584 585 586 587 588 589 590 591 592 593
            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;
                }
            }

594 595 596 597 598 599
            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) {
600

601
            source->adapter.data.scsi_host.name =
602
                virXPathString("string(./adapter/@name)", ctxt);
603 604 605
            if (virXPathNode("./adapter/parentaddr", ctxt)) {
                xmlNodePtr addrnode = virXPathNode("./adapter/parentaddr/address",
                                                   ctxt);
606
                virPCIDeviceAddressPtr addr =
607 608 609 610 611 612 613 614
                    &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;
615
                if (virPCIDeviceAddressParseXML(addrnode, addr) < 0)
616 617 618 619 620 621 622 623 624 625 626
                    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;
                }
            }
627 628 629 630 631 632
        }
    } else {
        char *wwnn = NULL;
        char *wwpn = NULL;
        char *parent = NULL;

633 634 635 636
        /* "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".
         */
637 638 639 640 641 642 643 644 645 646
        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 "
647 648 649 650 651 652 653 654
                             "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'"));
655 656 657 658 659 660
            goto cleanup;
        }

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

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

681 682 683
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

684
    ret = 0;
685
 cleanup:
686 687
    ctxt->node = relnode;

688
    VIR_FREE(port);
689
    VIR_FREE(nodeset);
690
    VIR_FREE(adapter_type);
691
    VIR_FREE(managed);
692
    virStorageAuthDefFree(authdef);
693 694
    return ret;
}
695

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

705 706 707
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
708 709
        goto cleanup;

710
    if (VIR_ALLOC(def) < 0)
711 712
        goto cleanup;

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

719
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
720 721 722 723 724
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
725
 cleanup:
726
    virStoragePoolSourceFree(def);
727 728 729 730 731
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
732

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

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

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

757
    if ((mode = virXPathString("string(./mode)", ctxt))) {
758 759 760
        int tmp;

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

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

        perms->uid = val;
785 786
    }

787
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
788
        perms->gid = (gid_t) -1;
789
    } else {
790
        /* We previously could output -1, so continue to parse it */
791
        if (virXPathLongLong("number(./group)", ctxt, &val) < 0 ||
792 793
            ((gid_t) val != val &&
             val != -1)) {
794 795
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed group element"));
796
            goto error;
797
        }
798
        perms->gid = val;
799 800 801
    }

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

804
    ret = 0;
805
 error:
806 807
    ctxt->node = relnode;
    return ret;
808 809 810
}

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

820
    if (VIR_ALLOC(ret) < 0)
821 822
        return NULL;

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

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

836
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL)
837
        goto error;
838

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

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

856 857 858 859 860 861
    if (strchr(ret->name, '/')) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("name %s cannot contain '/'"), ret->name);
        goto error;
    }

862
    uuid = virXPathString("string(./uuid)", ctxt);
863 864
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
865 866
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
867
            goto error;
868 869 870
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
871 872
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
873
            goto error;
874 875 876
        }
    }

877
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
878
        if (!ret->source.nhost) {
879
            virReportError(VIR_ERR_XML_ERROR, "%s",
880
                           _("missing storage pool source host name"));
881
            goto error;
882 883 884
        }
    }

885
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
886
        if (!ret->source.dir) {
887 888
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
889
            goto error;
890 891
        }
    }
892
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
893 894
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
895
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
896
                goto error;
897 898
        }
    }
899

900
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
901 902 903
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
904
            goto error;
905
        }
906 907 908 909 910 911 912 913

        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'"));
914
                goto error;
915 916 917 918
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
919
                goto error;
920 921
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
922 923 924 925 926 927 928 929 930 931
            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) {
932
                virReportError(VIR_ERR_XML_ERROR, "%s",
933 934
                               _("Both 'name' and 'parent' cannot be specified "
                                 "for the 'scsi_host' adapter"));
935
                goto error;
936 937
            }
        }
938
    }
939

940 941 942
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
943 944
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
945
            goto error;
946 947 948
        }
    }

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

970
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
971
                                    "./target/permissions") < 0)
972
            goto error;
973
    }
974

975
 cleanup:
976
    VIR_FREE(uuid);
977 978 979 980
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

981
 error:
982
    virStoragePoolDefFree(ret);
983 984
    ret = NULL;
    goto cleanup;
985 986 987
}

virStoragePoolDefPtr
988
virStoragePoolDefParseNode(xmlDocPtr xml,
989 990
                           xmlNodePtr root)
{
991 992 993
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

994
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
995
        virReportError(VIR_ERR_XML_ERROR,
996 997 998
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
999 1000 1001 1002 1003
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1004
        virReportOOMError();
1005 1006 1007 1008
        goto cleanup;
    }

    ctxt->node = root;
1009
    def = virStoragePoolDefParseXML(ctxt);
1010
 cleanup:
1011 1012 1013 1014 1015
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
1016
virStoragePoolDefParse(const char *xmlStr,
1017 1018
                       const char *filename)
{
1019
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1020
    xmlDocPtr xml;
1021

1022
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
1023 1024
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1025 1026
    }

1027 1028 1029
    return ret;
}

1030
virStoragePoolDefPtr
1031
virStoragePoolDefParseString(const char *xmlStr)
1032
{
1033
    return virStoragePoolDefParse(xmlStr, NULL);
1034 1035 1036
}

virStoragePoolDefPtr
1037
virStoragePoolDefParseFile(const char *filename)
1038
{
1039
    return virStoragePoolDefParse(NULL, filename);
1040 1041
}

1042
static int
1043
virStoragePoolSourceFormat(virBufferPtr buf,
1044
                           virStoragePoolOptionsPtr options,
1045 1046
                           virStoragePoolSourcePtr src)
{
1047
    size_t i, j;
1048

1049 1050 1051
    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

1052 1053
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
1054
            virBufferEscapeString(buf, "<host name='%s'",
1055
                                  src->hosts[i].name);
1056 1057 1058 1059
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
1060
    }
1061

1062
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
1063
        src->ndevice) {
1064
        for (i = 0; i < src->ndevice; i++) {
1065 1066 1067 1068 1069 1070 1071
            virBufferEscapeString(buf, "<device path='%s'",
                                  src->devices[i].path);
            if (src->devices[i].part_separator !=
                VIR_TRISTATE_SWITCH_ABSENT) {
                virBufferAsprintf(buf, " part_separator='%s'",
                                  virTristateBoolTypeToString(src->devices[i].part_separator));
            }
1072
            if (src->devices[i].nfreeExtent) {
1073
                virBufferAddLit(buf, ">\n");
1074
                virBufferAdjustIndent(buf, 2);
1075
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
1076
                    virBufferAsprintf(buf, "<freeExtent start='%llu' end='%llu'/>\n",
1077 1078 1079
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
1080 1081
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</device>\n");
1082
            } else {
1083
                virBufferAddLit(buf, "/>\n");
1084
            }
1085 1086
        }
    }
1087

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

1091 1092 1093
    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)
1094
            virBufferAsprintf(buf, "<adapter type='%s'",
1095
                              virStoragePoolSourceAdapterTypeToString(src->adapter.type));
1096 1097 1098 1099

        if (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            virBufferEscapeString(buf, " parent='%s'",
                                  src->adapter.data.fchost.parent);
1100 1101 1102
            if (src->adapter.data.fchost.managed)
                virBufferAsprintf(buf, " managed='%s'",
                                  virTristateBoolTypeToString(src->adapter.data.fchost.managed));
E
Eric Blake 已提交
1103
            virBufferAsprintf(buf, " wwnn='%s' wwpn='%s'/>\n",
1104 1105 1106
                              src->adapter.data.fchost.wwnn,
                              src->adapter.data.fchost.wwpn);
        } else if (src->adapter.type ==
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 {
1112
                virPCIDeviceAddress addr;
1113 1114 1115 1116 1117 1118
                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;
1119
                ignore_value(virPCIDeviceAddressFormat(buf, addr, false));
1120 1121 1122 1123 1124
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</parentaddr>\n");
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</adapter>\n");
            }
1125 1126
        }
    }
1127

1128
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
1129
        virBufferEscapeString(buf, "<name>%s</name>\n", src->name);
1130

D
David Allan 已提交
1131 1132
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN) &&
        src->initiator.iqn) {
1133 1134 1135
        virBufferAddLit(buf, "<initiator>\n");
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<iqn name='%s'/>\n",
E
Eric Blake 已提交
1136
                              src->initiator.iqn);
1137 1138
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</initiator>\n");
D
David Allan 已提交
1139 1140
    }

1141 1142 1143
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
1144 1145 1146
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
1147 1148
            return -1;
        }
1149
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1150 1151
    }

1152 1153 1154
    if (src->auth) {
        if (virStorageAuthDefFormat(buf, src->auth) < 0)
            return -1;
1155 1156
    }

1157 1158
    virBufferEscapeString(buf, "<vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "<product name='%s'/>\n", src->product);
1159

1160 1161
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
1162 1163 1164
    return 0;
}

1165

1166 1167 1168
static int
virStoragePoolDefFormatBuf(virBufferPtr buf,
                           virStoragePoolDefPtr def)
1169
{
1170
    virStoragePoolOptionsPtr options;
1171
    char uuid[VIR_UUID_STRING_BUFLEN];
1172
    const char *type;
1173

1174
    options = virStoragePoolOptionsForPoolType(def->type);
1175
    if (options == NULL)
1176
        return -1;
1177

1178
    type = virStoragePoolTypeToString(def->type);
1179
    if (!type) {
1180 1181
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1182
        return -1;
1183
    }
1184 1185 1186
    virBufferAsprintf(buf, "<pool type='%s'>\n", type);
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<name>%s</name>\n", def->name);
1187 1188

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

1191
    virBufferAsprintf(buf, "<capacity unit='bytes'>%llu</capacity>\n",
1192
                      def->capacity);
1193
    virBufferAsprintf(buf, "<allocation unit='bytes'>%llu</allocation>\n",
1194
                      def->allocation);
1195
    virBufferAsprintf(buf, "<available unit='bytes'>%llu</available>\n",
1196
                      def->available);
1197

1198 1199
    if (virStoragePoolSourceFormat(buf, options, &def->source) < 0)
        return -1;
1200

1201 1202
    /* RBD, Sheepdog, and Gluster devices are not local block devs nor
     * files, so they don't have a target */
1203
    if (def->type != VIR_STORAGE_POOL_RBD &&
1204 1205
        def->type != VIR_STORAGE_POOL_SHEEPDOG &&
        def->type != VIR_STORAGE_POOL_GLUSTER) {
1206 1207
        virBufferAddLit(buf, "<target>\n");
        virBufferAdjustIndent(buf, 2);
1208

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

1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
        if (def->target.perms.mode != (mode_t) -1 ||
            def->target.perms.uid != (uid_t) -1 ||
            def->target.perms.gid != (gid_t) -1 ||
            def->target.perms.label) {
            virBufferAddLit(buf, "<permissions>\n");
            virBufferAdjustIndent(buf, 2);
            if (def->target.perms.mode != (mode_t) -1)
                virBufferAsprintf(buf, "<mode>0%o</mode>\n",
                                  def->target.perms.mode);
            if (def->target.perms.uid != (uid_t) -1)
                virBufferAsprintf(buf, "<owner>%d</owner>\n",
                                  (int) def->target.perms.uid);
            if (def->target.perms.gid != (gid_t) -1)
                virBufferAsprintf(buf, "<group>%d</group>\n",
                                  (int) def->target.perms.gid);
            virBufferEscapeString(buf, "<label>%s</label>\n",
                                  def->target.perms.label);

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

1233 1234
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</target>\n");
1235
    }
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</pool>\n");

    return 0;
}

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

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

1250
    if (virBufferCheckError(&buf) < 0)
1251
        goto error;
1252

1253
    return virBufferContentAndReset(&buf);
1254

1255
 error:
1256
    virBufferFreeAndReset(&buf);
1257 1258 1259 1260 1261
    return NULL;
}


static int
1262
virStorageSize(const char *unit,
1263
               const char *val,
1264 1265 1266
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1267 1268
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("malformed capacity element"));
1269 1270
        return -1;
    }
1271 1272 1273 1274
    /* 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;
1275 1276 1277 1278 1279

    return 0;
}

static virStorageVolDefPtr
1280
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1281 1282
                         xmlXPathContextPtr ctxt,
                         unsigned int flags)
1283
{
1284
    virStorageVolDefPtr ret;
1285
    virStorageVolOptionsPtr options;
1286
    char *type = NULL;
1287 1288 1289
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1290
    char *backingStore = NULL;
1291
    xmlNodePtr node;
1292
    xmlNodePtr *nodes = NULL;
1293 1294
    size_t i;
    int n;
1295

1296 1297
    virCheckFlags(VIR_VOL_XML_PARSE_NO_CAPACITY |
                  VIR_VOL_XML_PARSE_OPT_CAPACITY, NULL);
1298

1299
    options = virStorageVolOptionsForPoolType(pool->type);
1300 1301 1302
    if (options == NULL)
        return NULL;

1303
    if (VIR_ALLOC(ret) < 0)
1304 1305
        return NULL;

1306
    ret->name = virXPathString("string(./name)", ctxt);
1307
    if (ret->name == NULL) {
1308 1309
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing volume name element"));
1310
        goto error;
1311 1312
    }

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

1316 1317 1318 1319
    /* Technically overridden by pool refresh, but useful for unit tests */
    type = virXPathString("string(./@type)", ctxt);
    if (type) {
        if ((ret->type = virStorageVolTypeFromString(type)) < 0) {
1320
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1321 1322 1323 1324 1325
                           _("unknown volume type '%s'"), type);
            goto error;
        }
    }

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
    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,
1352
                                    "./backingStore/permissions") < 0)
1353 1354 1355
            goto error;
    }

1356 1357
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1358 1359 1360
    if (capacity) {
        if (virStorageSize(unit, capacity, &ret->target.capacity) < 0)
            goto error;
1361 1362
    } else if (!(flags & VIR_VOL_XML_PARSE_NO_CAPACITY) &&
               !((flags & VIR_VOL_XML_PARSE_OPT_CAPACITY) && ret->target.backingStore)) {
1363
        virReportError(VIR_ERR_XML_ERROR, "%s", _("missing capacity element"));
1364
        goto error;
1365
    }
1366
    VIR_FREE(unit);
1367

1368
    allocation = virXPathString("string(./allocation)", ctxt);
1369
    if (allocation) {
1370
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1371
        if (virStorageSize(unit, allocation, &ret->target.allocation) < 0)
1372
            goto error;
1373
        ret->target.has_allocation = true;
1374
    } else {
1375
        ret->target.allocation = ret->target.capacity;
1376 1377
    }

1378
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1379
    if (options->formatFromString) {
1380
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1381 1382 1383 1384 1385 1386
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1387
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1388
                           _("unknown volume format type %s"), format);
1389
            VIR_FREE(format);
1390
            goto error;
1391
        }
1392
        VIR_FREE(format);
1393 1394
    }

1395 1396 1397
    if (VIR_ALLOC(ret->target.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->target.perms,
1398
                                "./target/permissions") < 0)
1399
        goto error;
1400

1401
    node = virXPathNode("./target/encryption", ctxt);
1402
    if (node != NULL) {
1403
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1404 1405
                                                               node);
        if (ret->target.encryption == NULL)
1406
            goto error;
1407 1408
    }

1409
    ret->target.compat = virXPathString("string(./target/compat)", ctxt);
1410 1411
    if (virStorageFileCheckCompat(ret->target.compat) < 0)
        goto error;
1412

C
Chunyan Liu 已提交
1413 1414 1415
    if (virXPathNode("./target/nocow", ctxt))
        ret->target.nocow = true;

1416
    if (virXPathNode("./target/features", ctxt)) {
1417 1418 1419 1420 1421 1422 1423
        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)))
1424
            goto error;
1425 1426

        for (i = 0; i < n; i++) {
1427
            int f = virStorageFileFeatureTypeFromString((const char*)nodes[i]->name);
1428 1429

            if (f < 0) {
1430
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unsupported feature %s"),
1431 1432 1433 1434 1435 1436 1437 1438
                               (const char*)nodes[i]->name);
                goto error;
            }
            ignore_value(virBitmapSetBit(ret->target.features, f));
        }
        VIR_FREE(nodes);
    }

1439
 cleanup:
1440
    VIR_FREE(nodes);
1441 1442 1443
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1444
    VIR_FREE(type);
1445
    VIR_FREE(backingStore);
1446 1447
    return ret;

1448
 error:
1449
    virStorageVolDefFree(ret);
1450 1451
    ret = NULL;
    goto cleanup;
1452 1453 1454
}

virStorageVolDefPtr
1455
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1456
                          xmlDocPtr xml,
1457 1458
                          xmlNodePtr root,
                          unsigned int flags)
1459
{
1460 1461 1462
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1463
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1464
        virReportError(VIR_ERR_XML_ERROR,
1465 1466 1467
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1468 1469 1470 1471 1472
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1473
        virReportOOMError();
1474 1475 1476 1477
        goto cleanup;
    }

    ctxt->node = root;
1478
    def = virStorageVolDefParseXML(pool, ctxt, flags);
1479
 cleanup:
1480 1481 1482 1483 1484
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1485
virStorageVolDefParse(virStoragePoolDefPtr pool,
1486
                      const char *xmlStr,
1487 1488
                      const char *filename,
                      unsigned int flags)
1489
{
1490
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1491
    xmlDocPtr xml;
1492

1493
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
1494
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml), flags);
J
Jiri Denemark 已提交
1495
        xmlFreeDoc(xml);
1496 1497 1498 1499 1500
    }

    return ret;
}

1501
virStorageVolDefPtr
1502
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1503 1504
                            const char *xmlStr,
                            unsigned int flags)
1505
{
1506
    return virStorageVolDefParse(pool, xmlStr, NULL, flags);
1507 1508 1509
}

virStorageVolDefPtr
1510
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1511 1512
                          const char *filename,
                          unsigned int flags)
1513
{
1514
    return virStorageVolDefParse(pool, NULL, filename, flags);
1515
}
1516

1517 1518 1519 1520 1521 1522
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
1523
    virBufferAsprintf(buf, "<%s>%llu", name,
1524 1525 1526 1527 1528 1529
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1530
static int
1531
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1532
                             virBufferPtr buf,
1533
                             virStorageSourcePtr def,
1534 1535
                             const char *type)
{
1536 1537
    virBufferAsprintf(buf, "<%s>\n", type);
    virBufferAdjustIndent(buf, 2);
1538

1539
    virBufferEscapeString(buf, "<path>%s</path>\n", def->path);
1540 1541 1542 1543

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1544 1545 1546
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1547 1548
            return -1;
        }
1549
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1550 1551
    }

1552 1553 1554 1555 1556
    if (def->perms &&
        (def->perms->mode != (mode_t) -1 ||
         def->perms->uid != (uid_t) -1 ||
         def->perms->gid != (gid_t) -1 ||
         def->perms->label)) {
1557 1558
        virBufferAddLit(buf, "<permissions>\n");
        virBufferAdjustIndent(buf, 2);
1559

1560 1561 1562
        if (def->perms->mode != (mode_t) -1)
            virBufferAsprintf(buf, "<mode>0%o</mode>\n",
                              def->perms->mode);
1563 1564 1565 1566 1567 1568
        if (def->perms->uid != (uid_t) -1)
            virBufferAsprintf(buf, "<owner>%d</owner>\n",
                              (int) def->perms->uid);
        if (def->perms->gid != (gid_t) -1)
            virBufferAsprintf(buf, "<group>%d</group>\n",
                              (int) def->perms->gid);
1569

1570 1571
        virBufferEscapeString(buf, "<label>%s</label>\n",
                              def->perms->label);
1572

1573 1574 1575
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</permissions>\n");
    }
1576

1577
    if (def->timestamps) {
1578 1579
        virBufferAddLit(buf, "<timestamps>\n");
        virBufferAdjustIndent(buf, 2);
1580 1581 1582 1583
        virStorageVolTimestampFormat(buf, "atime", &def->timestamps->atime);
        virStorageVolTimestampFormat(buf, "mtime", &def->timestamps->mtime);
        virStorageVolTimestampFormat(buf, "ctime", &def->timestamps->ctime);
        virStorageVolTimestampFormat(buf, "btime", &def->timestamps->btime);
1584 1585
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timestamps>\n");
1586 1587
    }

1588 1589
    if (def->encryption &&
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1590
            return -1;
1591

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

1594
    if (def->features) {
1595
        size_t i;
1596 1597
        bool empty = virBitmapIsAllClear(def->features);

1598 1599 1600 1601 1602 1603
        if (empty) {
            virBufferAddLit(buf, "<features/>\n");
        } else {
            virBufferAddLit(buf, "<features>\n");
            virBufferAdjustIndent(buf, 2);
        }
1604 1605

        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
J
Ján Tomko 已提交
1606
            if (virBitmapIsBitSet(def->features, i))
1607
                virBufferAsprintf(buf, "<%s/>\n",
1608
                                  virStorageFileFeatureTypeToString(i));
1609
        }
1610 1611 1612 1613
        if (!empty) {
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</features>\n");
        }
1614 1615
    }

1616 1617
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", type);
1618 1619
    return 0;
}
1620 1621

char *
1622
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1623 1624
                       virStorageVolDefPtr def)
{
1625
    virStorageVolOptionsPtr options;
1626
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1627

1628
    options = virStorageVolOptionsForPoolType(pool->type);
1629 1630 1631
    if (options == NULL)
        return NULL;

1632 1633
    virBufferAsprintf(&buf, "<volume type='%s'>\n",
                      virStorageVolTypeToString(def->type));
1634 1635 1636 1637 1638 1639
    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);
1640 1641

    if (def->source.nextent) {
1642
        size_t i;
1643
        const char *thispath = NULL;
1644
        for (i = 0; i < def->source.nextent; i++) {
1645 1646 1647
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1648
                    virBufferAddLit(&buf, "</device>\n");
1649

1650
                virBufferEscapeString(&buf, "<device path='%s'>\n",
1651
                                      def->source.extents[i].path);
1652 1653
            }

1654 1655
            virBufferAdjustIndent(&buf, 2);
            virBufferAsprintf(&buf, "<extent start='%llu' end='%llu'/>\n",
1656 1657
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1658
            virBufferAdjustIndent(&buf, -2);
1659 1660 1661
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1662
            virBufferAddLit(&buf, "</device>\n");
1663 1664
    }

1665 1666 1667 1668
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</source>\n");

    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1669
                      def->target.capacity);
1670
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1671
                      def->target.allocation);
1672

1673
    if (virStorageVolTargetDefFormat(options, &buf,
1674 1675
                                     &def->target, "target") < 0)
        goto cleanup;
1676

1677
    if (def->target.backingStore &&
1678
        virStorageVolTargetDefFormat(options, &buf,
1679 1680
                                     def->target.backingStore,
                                     "backingStore") < 0)
1681
        goto cleanup;
1682

1683
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1684
    virBufferAddLit(&buf, "</volume>\n");
1685

1686 1687
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1688

1689
    return virBufferContentAndReset(&buf);
1690

1691
 cleanup:
1692
    virBufferFreeAndReset(&buf);
1693 1694 1695 1696 1697
    return NULL;
}


virStoragePoolObjPtr
1698
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1699 1700
                            const unsigned char *uuid)
{
1701
    size_t i;
1702

1703
    for (i = 0; i < pools->count; i++) {
1704
        virStoragePoolObjLock(pools->objs[i]);
1705 1706
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1707 1708
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1709 1710 1711 1712 1713

    return NULL;
}

virStoragePoolObjPtr
1714
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1715 1716
                            const char *name)
{
1717
    size_t i;
1718

1719
    for (i = 0; i < pools->count; i++) {
1720
        virStoragePoolObjLock(pools->objs[i]);
1721 1722
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1723 1724
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1725 1726 1727 1728

    return NULL;
}

1729 1730
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1731 1732
                                         virStoragePoolDefPtr def)
{
1733
    size_t i, j;
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744

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

1745 1746 1747
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1748
    size_t i;
1749
    for (i = 0; i < pool->volumes.count; i++)
1750 1751 1752 1753
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1754 1755 1756 1757
}

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

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

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1771 1772
                           const char *path)
{
1773
    size_t i;
1774

1775
    for (i = 0; i < pool->volumes.count; i++)
1776 1777
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1778 1779 1780 1781 1782 1783

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1784 1785
                           const char *name)
{
1786
    size_t i;
1787

1788
    for (i = 0; i < pool->volumes.count; i++)
1789 1790
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1791 1792 1793 1794 1795

    return NULL;
}

virStoragePoolObjPtr
1796
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1797 1798
                           virStoragePoolDefPtr def)
{
1799 1800
    virStoragePoolObjPtr pool;

1801
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1802 1803 1804 1805
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1806
            virStoragePoolDefFree(pool->newDef);
1807 1808 1809 1810 1811
            pool->newDef = def;
        }
        return pool;
    }

1812
    if (VIR_ALLOC(pool) < 0)
1813 1814
        return NULL;

1815
    if (virMutexInit(&pool->lock) < 0) {
1816 1817
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1818 1819 1820
        VIR_FREE(pool);
        return NULL;
    }
1821
    virStoragePoolObjLock(pool);
1822 1823
    pool->active = 0;

1824
    if (VIR_APPEND_ELEMENT_COPY(pools->objs, pools->count, pool) < 0) {
1825
        virStoragePoolObjUnlock(pool);
1826 1827 1828
        virStoragePoolObjFree(pool);
        return NULL;
    }
1829
    pool->def = def;
1830 1831 1832 1833 1834

    return pool;
}

static virStoragePoolObjPtr
1835
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1836 1837
                      const char *file,
                      const char *path,
1838 1839
                      const char *autostartLink)
{
1840 1841 1842
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1843
    if (!(def = virStoragePoolDefParseFile(path)))
1844 1845 1846
        return NULL;

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1847
        virReportError(VIR_ERR_XML_ERROR,
1848 1849
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1850
                       path, def->name);
1851 1852 1853 1854
        virStoragePoolDefFree(def);
        return NULL;
    }

1855
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1856 1857 1858 1859
        virStoragePoolDefFree(def);
        return NULL;
    }

1860
    VIR_FREE(pool->configFile);  /* for driver reload */
1861
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1862
        virStoragePoolObjRemove(pools, pool);
1863 1864
        return NULL;
    }
1865
    VIR_FREE(pool->autostartLink); /* for driver reload */
1866
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1867
        virStoragePoolObjRemove(pools, pool);
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
        return NULL;
    }

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

    return pool;
}


1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
virStoragePoolObjPtr
virStoragePoolLoadState(virStoragePoolObjListPtr pools,
                        const char *stateDir,
                        const char *name)
{
    char *stateFile = NULL;
    virStoragePoolDefPtr def = NULL;
    virStoragePoolObjPtr pool = NULL;
    xmlDocPtr xml = NULL;
    xmlXPathContextPtr ctxt = NULL;
    xmlNodePtr node = NULL;

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

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

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

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

1906
    if (STRNEQ(name, def->name)) {
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Storage pool state file '%s' does not match "
                         "pool name '%s'"),
                       stateFile, def->name);
        goto error;
    }

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

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

    pool->active = 1;

 cleanup:
    VIR_FREE(stateFile);
1927
    xmlFreeDoc(xml);
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943
    xmlXPathFreeContext(ctxt);
    return pool;

 error:
    virStoragePoolDefFree(def);
    goto cleanup;
}


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

J
Ján Tomko 已提交
1946 1947
    if ((rc = virDirOpenIfExists(&dir, stateDir)) <= 0)
        return rc;
1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959

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

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

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

J
Ján Tomko 已提交
1960
    VIR_DIR_CLOSE(dir);
1961 1962 1963 1964
    return ret;
}


1965
int
1966
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1967
                             const char *configDir,
1968 1969
                             const char *autostartDir)
{
1970 1971
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
1972
    int ret;
J
Ján Tomko 已提交
1973
    int rc;
1974

J
Ján Tomko 已提交
1975 1976
    if ((rc = virDirOpenIfExists(&dir, configDir)) <= 0)
        return rc;
1977

E
Eric Blake 已提交
1978
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
1979 1980
        char *path;
        char *autostartLink;
1981
        virStoragePoolObjPtr pool;
1982 1983 1984 1985

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

1986
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1987 1988
            continue;

1989 1990 1991
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1992 1993 1994
            continue;
        }

1995
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1996
                                     autostartLink);
1997 1998
        if (pool)
            virStoragePoolObjUnlock(pool);
1999 2000 2001

        VIR_FREE(path);
        VIR_FREE(autostartLink);
2002 2003
    }

J
Ján Tomko 已提交
2004
    VIR_DIR_CLOSE(dir);
E
Eric Blake 已提交
2005
    return ret;
2006 2007
}

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022

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

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

    return ret;
}
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056


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

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

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

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

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

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

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

    ret = 0;

 error:
    VIR_FREE(xml);
    return ret;
}
2057 2058


2059
int
2060
virStoragePoolSaveConfig(const char *configFile,
2061 2062
                         virStoragePoolDefPtr def)
{
2063
    char *xml;
2064
    int ret = -1;
2065

2066 2067 2068 2069 2070 2071
    if (!(xml = virStoragePoolDefFormat(def))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
        return -1;
    }

2072 2073
    if (virStoragePoolSaveXML(configFile, def, xml))
        goto cleanup;
2074

2075 2076 2077
    ret = 0;
 cleanup:
    VIR_FREE(xml);
2078 2079 2080 2081 2082 2083 2084 2085
    return ret;
}

int
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
                         virStoragePoolObjPtr pool,
                         virStoragePoolDefPtr def)
{
2086
    if (!pool->configFile) {
2087 2088
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
2089 2090
                                 _("cannot create config directory %s"),
                                 driver->configDir);
2091 2092 2093
            return -1;
        }

2094 2095
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
2096 2097 2098
            return -1;
        }

2099 2100
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
2101
            VIR_FREE(pool->configFile);
2102 2103 2104 2105
            return -1;
        }
    }

2106
    return virStoragePoolSaveConfig(pool->configFile, def);
2107 2108 2109
}

int
2110 2111
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
2112
    if (!pool->configFile) {
2113 2114
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
2115 2116 2117 2118
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
2119 2120 2121
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
2122 2123 2124 2125 2126
        return -1;
    }

    return 0;
}
2127

2128
virStoragePoolSourcePtr
2129
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
2130 2131 2132
{
    virStoragePoolSourcePtr source;

2133
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0)
2134 2135 2136 2137 2138 2139 2140 2141
        return NULL;

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

    return source;
}

2142 2143
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
2144
{
2145
    virStoragePoolOptionsPtr options;
2146
    virBuffer buf = VIR_BUFFER_INITIALIZER;
2147
    const char *type;
2148
    size_t i;
2149

2150
    options = virStoragePoolOptionsForPoolType(def->type);
2151 2152 2153
    if (options == NULL)
        return NULL;

2154
    type = virStoragePoolTypeToString(def->type);
2155
    if (!type) {
2156 2157
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
2158 2159 2160 2161
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
2162
    virBufferAdjustIndent(&buf, 2);
2163

2164
    for (i = 0; i < def->nsources; i++)
2165
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
2166

2167
    virBufferAdjustIndent(&buf, -2);
2168 2169
    virBufferAddLit(&buf, "</sources>\n");

2170 2171
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
2172 2173

    return virBufferContentAndReset(&buf);
2174

2175
 cleanup:
2176
    virBufferFreeAndReset(&buf);
2177
    return NULL;
2178
}
D
Daniel P. Berrange 已提交
2179 2180


2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
/*
 * 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
 */
2191 2192 2193 2194
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
{
    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);
2206 2207 2208
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
2209 2210 2211 2212 2213 2214
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
2215 2216 2217
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
2218 2219 2220 2221
                goto cleanup;
            }
        }

J
Ján Tomko 已提交
2222
        ret = 1;
2223 2224 2225 2226 2227 2228
    } 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);
2229 2230 2231
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2232 2233
            goto cleanup;
        }
J
Ján Tomko 已提交
2234
        ret = 0;
2235 2236
    }

2237
 cleanup:
2238 2239 2240 2241 2242
    if (pool)
        virStoragePoolObjUnlock(pool);
    return ret;
}

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301
/*
 * 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;
}

2302 2303 2304
static int
getSCSIHostNumber(virStoragePoolSourceAdapter adapter,
                  unsigned int *hostnum)
2305
{
2306 2307 2308 2309 2310
    int ret = -1;
    unsigned int num;
    char *name = NULL;

    if (adapter.data.scsi_host.has_parent) {
2311
        virPCIDeviceAddress addr = adapter.data.scsi_host.parentaddr;
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332
        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;
2333
}
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353

/*
 * 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;

2354
    /* If we have a parent defined, get its hostnum, and compare to the
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410
     * 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;
}

2411 2412 2413 2414
static bool
matchSCSIAdapterParent(virStoragePoolObjPtr pool,
                       virStoragePoolDefPtr def)
{
2415
    virPCIDeviceAddressPtr pooladdr =
2416
        &pool->def->source.adapter.data.scsi_host.parentaddr;
2417
    virPCIDeviceAddressPtr defaddr =
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432
        &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;
}

2433 2434 2435 2436 2437 2438 2439
static bool
virStoragePoolSourceMatchSingleHost(virStoragePoolSourcePtr poolsrc,
                                    virStoragePoolSourcePtr defsrc)
{
    if (poolsrc->nhost != 1 && defsrc->nhost != 1)
        return false;

2440 2441
    if (defsrc->hosts[0].port &&
        poolsrc->hosts[0].port != defsrc->hosts[0].port)
2442 2443
        return false;

2444 2445 2446
    return STREQ(poolsrc->hosts[0].name, defsrc->hosts[0].name);
}

2447

2448 2449 2450 2451 2452 2453 2454
static bool
virStoragePoolSourceISCSIMatch(virStoragePoolObjPtr matchpool,
                               virStoragePoolDefPtr def)
{
    virStoragePoolSourcePtr poolsrc = &matchpool->def->source;
    virStoragePoolSourcePtr defsrc = &def->source;

2455
    /* NB: Do not check the source host name */
2456 2457 2458 2459 2460 2461 2462
    if (STRNEQ_NULLABLE(poolsrc->initiator.iqn, defsrc->initiator.iqn))
        return false;

    return true;
}


2463
int
2464 2465
virStoragePoolSourceFindDuplicate(virConnectPtr conn,
                                  virStoragePoolObjListPtr pools,
2466
                                  virStoragePoolDefPtr def)
2467
{
2468
    size_t i;
2469 2470 2471 2472 2473 2474 2475 2476 2477 2478
    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;

2479 2480 2481 2482
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2483 2484
        virStoragePoolObjLock(pool);

2485
        switch ((virStoragePoolType)pool->def->type) {
2486 2487 2488 2489
        case VIR_STORAGE_POOL_DIR:
            if (STREQ(pool->def->target.path, def->target.path))
                matchpool = pool;
            break;
2490

2491
        case VIR_STORAGE_POOL_GLUSTER:
2492 2493 2494 2495 2496 2497 2498 2499
            if (STREQ(pool->def->source.name, def->source.name) &&
                STREQ_NULLABLE(pool->def->source.dir, def->source.dir) &&
                virStoragePoolSourceMatchSingleHost(&pool->def->source,
                                                    &def->source))
                matchpool = pool;
            break;

        case VIR_STORAGE_POOL_NETFS:
2500 2501 2502
            if (STREQ(pool->def->source.dir, def->source.dir) &&
                virStoragePoolSourceMatchSingleHost(&pool->def->source,
                                                    &def->source))
2503 2504
                matchpool = pool;
            break;
2505

2506
        case VIR_STORAGE_POOL_SCSI:
2507
            if (pool->def->source.adapter.type ==
2508 2509
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST &&
                def->source.adapter.type ==
2510 2511 2512 2513 2514 2515 2516
                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 ==
2517 2518
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST &&
                       def->source.adapter.type ==
2519
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
2520 2521
                unsigned int pool_hostnum, def_hostnum;

2522 2523 2524 2525 2526 2527 2528
                if (pool->def->source.adapter.data.scsi_host.has_parent &&
                    def->source.adapter.data.scsi_host.has_parent &&
                    matchSCSIAdapterParent(pool, def)) {
                    matchpool = pool;
                    break;
                }

2529 2530 2531
                if (getSCSIHostNumber(pool->def->source.adapter,
                                      &pool_hostnum) < 0 ||
                    getSCSIHostNumber(def->source.adapter, &def_hostnum) < 0)
2532
                    break;
2533 2534
                if (pool_hostnum == def_hostnum)
                    matchpool = pool;
2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566
            } 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;
                }
2567
            }
2568 2569 2570 2571
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2572 2573
                if (!virStoragePoolSourceISCSIMatch(matchpool, def))
                    matchpool = NULL;
2574 2575 2576 2577 2578
            }
            break;
        case VIR_STORAGE_POOL_FS:
        case VIR_STORAGE_POOL_LOGICAL:
        case VIR_STORAGE_POOL_DISK:
2579
        case VIR_STORAGE_POOL_ZFS:
2580 2581
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            break;
2582 2583 2584 2585 2586
        case VIR_STORAGE_POOL_SHEEPDOG:
            if (virStoragePoolSourceMatchSingleHost(&pool->def->source,
                                                    &def->source))
                matchpool = pool;
            break;
2587
        case VIR_STORAGE_POOL_MPATH:
2588 2589 2590
            /* Only one mpath pool is valid per host */
            matchpool = pool;
            break;
2591 2592
        case VIR_STORAGE_POOL_RBD:
        case VIR_STORAGE_POOL_LAST:
2593 2594 2595
            break;
        }
        virStoragePoolObjUnlock(pool);
2596 2597 2598

        if (matchpool)
            break;
2599 2600 2601
    }

    if (matchpool) {
2602 2603 2604
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2605 2606 2607 2608
        ret = -1;
    }
    return ret;
}
2609

2610 2611
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2612
{
2613
    virMutexLock(&obj->lock);
2614 2615
}

2616 2617
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2618
{
2619
    virMutexUnlock(&obj->lock);
2620
}
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671

#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) &&
2672 2673 2674
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
               (poolobj->def->type == VIR_STORAGE_POOL_GLUSTER))))
2675 2676 2677 2678 2679 2680 2681 2682
            return false;
    }

    return true;
}
#undef MATCH

int
2683 2684 2685 2686 2687
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2688 2689 2690 2691 2692
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2693
    size_t i;
2694

2695 2696
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2697 2698 2699 2700

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2701 2702
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2703 2704 2705
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2706 2707
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
                    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;

2727
 cleanup:
2728
    if (tmp_pools) {
2729 2730
        for (i = 0; i < npools; i++)
            virObjectUnref(tmp_pools[i]);
2731 2732 2733 2734 2735
    }

    VIR_FREE(tmp_pools);
    return ret;
}