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

#include <config.h>

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

36
#include "virerror.h"
37
#include "datatypes.h"
38
#include "storage_conf.h"
39
#include "virstoragefile.h"
40

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

49 50
#define VIR_FROM_THIS VIR_FROM_STORAGE

51 52
VIR_LOG_INIT("conf.storage_conf");

53 54
#define DEFAULT_POOL_PERM_MODE 0755
#define DEFAULT_VOL_PERM_MODE  0600
55

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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


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

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

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

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


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

    if (!def)
        return;

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

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

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

345 346 347 348 349 350 351 352 353
static void
virStoragePoolSourceAdapterClear(virStoragePoolSourceAdapter adapter)
{
    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 ==
               VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
354
        VIR_FREE(adapter.data.scsi_host.name);
355 356 357
    }
}

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

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

370
    if (!source)
371 372
        return;

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

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

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

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

    VIR_FREE(def->name);

405
    virStoragePoolSourceClear(&def->source);
406

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


void
414 415
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
416 417 418
    if (!obj)
        return;

419 420
    virStoragePoolObjClearVols(obj);

421 422
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
423

424 425
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
426 427 428

    virMutexDestroy(&obj->lock);

429
    VIR_FREE(obj);
430 431
}

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

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

448 449
    virStoragePoolObjUnlock(pool);

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

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

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

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

    if ((options = virStoragePoolOptionsForPoolType(pool_type)) == NULL) {
        goto cleanup;
    }

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

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

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

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

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

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

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

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

546 547 548 549 550 551 552
    for (i = 0; i < nsource; i++) {
        virStoragePoolSourceDevice dev = { .path = NULL };
        dev.path = virXMLPropString(nodeset[i], "path");

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

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

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

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

588
            source->adapter.data.scsi_host.name =
589
                virXPathString("string(./adapter/@name)", ctxt);
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
            if (virXPathNode("./adapter/parentaddr", ctxt)) {
                xmlNodePtr addrnode = virXPathNode("./adapter/parentaddr/address",
                                                   ctxt);
                virDevicePCIAddressPtr addr =
                    &source->adapter.data.scsi_host.parentaddr;

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

620 621 622 623
        /* "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".
         */
624 625 626 627 628 629 630 631 632 633
        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 "
634 635 636 637 638 639 640 641
                             "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'"));
642 643 644 645 646 647
            goto cleanup;
        }

        /* To keep back-compat, 'type' is not required to specify
         * for scsi_host adapter.
         */
648
        if ((source->adapter.data.scsi_host.name =
649 650 651 652
             virXPathString("string(./adapter/@name)", ctxt)))
            source->adapter.type =
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST;
    }
653

654 655 656 657 658 659 660 661 662 663 664
    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;
665
        authdef = NULL;
666
    }
667

668 669 670
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

671
    ret = 0;
672
 cleanup:
673 674
    ctxt->node = relnode;

675
    VIR_FREE(port);
676
    VIR_FREE(nodeset);
677
    VIR_FREE(adapter_type);
678
    virStorageAuthDefFree(authdef);
679 680
    return ret;
}
681

682
virStoragePoolSourcePtr
683
virStoragePoolDefParseSourceString(const char *srcSpec,
684 685 686 687 688 689 690
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

691 692 693
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
694 695
        goto cleanup;

696
    if (VIR_ALLOC(def) < 0)
697 698
        goto cleanup;

699
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
700 701
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
702 703 704
        goto cleanup;
    }

705
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
706 707 708 709 710
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
711
 cleanup:
712
    virStoragePoolSourceFree(def);
713 714 715 716 717
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
718

719
static int
720
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
721 722
                        virStoragePermsPtr perms,
                        const char *permxpath,
723 724
                        int defaultmode)
{
725
    char *mode;
726
    long val;
727 728 729
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
730

731
    node = virXPathNode(permxpath, ctxt);
732 733 734
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
P
Philipp Hahn 已提交
735 736
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
737 738 739 740 741 742 743
        perms->label = NULL;
        return 0;
    }

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

744
    mode = virXPathString("string(./mode)", ctxt);
745
    if (!mode) {
746
        perms->mode = defaultmode;
747
    } else {
748 749 750
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
751
            VIR_FREE(mode);
752 753
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
754
            goto error;
755
        }
756
        perms->mode = tmp;
757
        VIR_FREE(mode);
758 759
    }

760
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
761
        perms->uid = (uid_t) -1;
762
    } else {
763 764 765
        if (virXPathLong("number(./owner)", ctxt, &val) < 0 ||
            ((uid_t)val != val &&
             val != -1)) {
766 767
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed owner element"));
768
            goto error;
769
        }
770 771

        perms->uid = val;
772 773
    }

774
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
775
        perms->gid = (gid_t) -1;
776
    } else {
777 778 779
        if (virXPathLong("number(./group)", ctxt, &val) < 0 ||
            ((gid_t) val != val &&
             val != -1)) {
780 781
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed group element"));
782
            goto error;
783
        }
784
        perms->gid = val;
785 786 787
    }

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

790
    ret = 0;
791
 error:
792 793
    ctxt->node = relnode;
    return ret;
794 795 796
}

static virStoragePoolDefPtr
797 798
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
799
    virStoragePoolOptionsPtr options;
800
    virStoragePoolDefPtr ret;
801
    xmlNodePtr source_node;
802
    char *type = NULL;
803
    char *uuid = NULL;
804
    char *target_path = NULL;
805

806
    if (VIR_ALLOC(ret) < 0)
807 808
        return NULL;

809
    type = virXPathString("string(./@type)", ctxt);
810 811 812 813 814 815
    if (type == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("storage pool missing type attribute"));
        goto error;
    }

816
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
817
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
818
                       _("unknown storage pool type %s"), type);
819
        goto error;
820 821 822
    }

    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
823
        goto error;
824 825
    }

826
    source_node = virXPathNode("./source", ctxt);
827
    if (source_node) {
828
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
829
                                         source_node) < 0)
830
            goto error;
831 832
    }

833
    ret->name = virXPathString("string(./name)", ctxt);
834
    if (ret->name == NULL &&
835
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
836
        ret->name = ret->source.name;
837
    if (ret->name == NULL) {
838 839
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
840
        goto error;
841 842
    }

843
    uuid = virXPathString("string(./uuid)", ctxt);
844 845
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
846 847
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
848
            goto error;
849 850 851
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
852 853
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
854
            goto error;
855 856 857
        }
    }

858
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
859
        if (!ret->source.nhost) {
860
            virReportError(VIR_ERR_XML_ERROR, "%s",
861
                           _("missing storage pool source host name"));
862
            goto error;
863 864 865
        }
    }

866
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
867
        if (!ret->source.dir) {
868 869
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
870
            goto error;
871 872
        }
    }
873
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
874 875
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
876
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
877
                goto error;
878 879
        }
    }
880

881
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
882 883 884
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
885
            goto error;
886
        }
887 888 889 890 891 892 893 894

        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'"));
895
                goto error;
896 897 898 899
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
900
                goto error;
901 902
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
903 904 905 906 907 908 909 910 911 912
            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) {
913
                virReportError(VIR_ERR_XML_ERROR, "%s",
914 915
                               _("Both 'name' and 'parent' cannot be specified "
                                 "for the 'scsi_host' adapter"));
916
                goto error;
917 918
            }
        }
919
    }
920

921 922 923
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
924 925
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
926
            goto error;
927 928 929
        }
    }

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

953
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
954 955
                                    "./target/permissions",
                                    DEFAULT_POOL_PERM_MODE) < 0)
956
            goto error;
957
    }
958

959
 cleanup:
960
    VIR_FREE(uuid);
961 962 963 964
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

965
 error:
966
    virStoragePoolDefFree(ret);
967 968
    ret = NULL;
    goto cleanup;
969 970 971
}

virStoragePoolDefPtr
972
virStoragePoolDefParseNode(xmlDocPtr xml,
973 974
                           xmlNodePtr root)
{
975 976 977
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

978
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
979
        virReportError(VIR_ERR_XML_ERROR,
980 981 982
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
983 984 985 986 987
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
988
        virReportOOMError();
989 990 991 992
        goto cleanup;
    }

    ctxt->node = root;
993
    def = virStoragePoolDefParseXML(ctxt);
994
 cleanup:
995 996 997 998 999
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
1000
virStoragePoolDefParse(const char *xmlStr,
1001 1002
                       const char *filename)
{
1003
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1004
    xmlDocPtr xml;
1005

1006
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
1007 1008
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1009 1010
    }

1011 1012 1013
    return ret;
}

1014
virStoragePoolDefPtr
1015
virStoragePoolDefParseString(const char *xmlStr)
1016
{
1017
    return virStoragePoolDefParse(xmlStr, NULL);
1018 1019 1020
}

virStoragePoolDefPtr
1021
virStoragePoolDefParseFile(const char *filename)
1022
{
1023
    return virStoragePoolDefParse(NULL, filename);
1024 1025
}

1026
static int
1027
virStoragePoolSourceFormat(virBufferPtr buf,
1028
                           virStoragePoolOptionsPtr options,
1029 1030
                           virStoragePoolSourcePtr src)
{
1031
    size_t i, j;
1032

1033 1034 1035
    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

1036 1037
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
1038
            virBufferEscapeString(buf, "<host name='%s'",
1039
                                  src->hosts[i].name);
1040 1041 1042 1043
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
1044
    }
1045

1046
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
1047
        src->ndevice) {
1048
        for (i = 0; i < src->ndevice; i++) {
1049
            if (src->devices[i].nfreeExtent) {
1050
                virBufferEscapeString(buf, "<device path='%s'>\n",
1051
                                      src->devices[i].path);
1052
                virBufferAdjustIndent(buf, 2);
1053
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
1054
                    virBufferAsprintf(buf, "<freeExtent start='%llu' end='%llu'/>\n",
1055 1056 1057
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
1058 1059
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</device>\n");
1060
            } else {
1061
                virBufferEscapeString(buf, "<device path='%s'/>\n",
1062
                                      src->devices[i].path);
1063
            }
1064 1065
        }
    }
1066

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

1070 1071 1072
    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)
1073
            virBufferAsprintf(buf, "<adapter type='%s'",
1074
                              virStoragePoolSourceAdapterTypeToString(src->adapter.type));
1075 1076 1077 1078

        if (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            virBufferEscapeString(buf, " parent='%s'",
                                  src->adapter.data.fchost.parent);
E
Eric Blake 已提交
1079
            virBufferAsprintf(buf, " wwnn='%s' wwpn='%s'/>\n",
1080 1081 1082
                              src->adapter.data.fchost.wwnn,
                              src->adapter.data.fchost.wwpn);
        } else if (src->adapter.type ==
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            if (src->adapter.data.scsi_host.name) {
                virBufferAsprintf(buf, " name='%s'/>\n",
                                  src->adapter.data.scsi_host.name);
            } else {
                virDevicePCIAddress addr;
                virBufferAddLit(buf, ">\n");
                virBufferAdjustIndent(buf, 2);
                virBufferAsprintf(buf, "<parentaddr unique_id='%d'>\n",
                                  src->adapter.data.scsi_host.unique_id);
                virBufferAdjustIndent(buf, 2);
                addr = src->adapter.data.scsi_host.parentaddr;
                ignore_value(virDevicePCIAddressFormat(buf, addr, false));
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</parentaddr>\n");
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</adapter>\n");
            }
1101 1102
        }
    }
1103

1104
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
1105
        virBufferEscapeString(buf, "<name>%s</name>\n", src->name);
1106

D
David Allan 已提交
1107 1108
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN) &&
        src->initiator.iqn) {
1109 1110 1111
        virBufferAddLit(buf, "<initiator>\n");
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<iqn name='%s'/>\n",
E
Eric Blake 已提交
1112
                              src->initiator.iqn);
1113 1114
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</initiator>\n");
D
David Allan 已提交
1115 1116
    }

1117 1118 1119
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
1120 1121 1122
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
1123 1124
            return -1;
        }
1125
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1126 1127
    }

1128 1129 1130
    if (src->auth) {
        if (virStorageAuthDefFormat(buf, src->auth) < 0)
            return -1;
1131 1132
    }

1133 1134
    virBufferEscapeString(buf, "<vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "<product name='%s'/>\n", src->product);
1135

1136 1137
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
1138 1139 1140
    return 0;
}

1141 1142

char *
1143 1144
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
1145
    virStoragePoolOptionsPtr options;
1146
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1147 1148 1149
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1150
    options = virStoragePoolOptionsForPoolType(def->type);
1151 1152 1153
    if (options == NULL)
        return NULL;

1154
    type = virStoragePoolTypeToString(def->type);
1155
    if (!type) {
1156 1157
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1158 1159
        goto cleanup;
    }
1160
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
1161 1162
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
1163 1164

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

1167
    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1168
                      def->capacity);
1169
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1170
                      def->allocation);
1171
    virBufferAsprintf(&buf, "<available unit='bytes'>%llu</available>\n",
1172
                      def->available);
1173

1174
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1175
        goto cleanup;
1176

1177 1178
    /* RBD, Sheepdog, and Gluster devices are not local block devs nor
     * files, so they don't have a target */
1179
    if (def->type != VIR_STORAGE_POOL_RBD &&
1180 1181
        def->type != VIR_STORAGE_POOL_SHEEPDOG &&
        def->type != VIR_STORAGE_POOL_GLUSTER) {
1182 1183
        virBufferAddLit(&buf, "<target>\n");
        virBufferAdjustIndent(&buf, 2);
1184

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

1187 1188 1189
        virBufferAddLit(&buf, "<permissions>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<mode>0%o</mode>\n",
1190
                          def->target.perms.mode);
1191
        virBufferAsprintf(&buf, "<owner>%d</owner>\n",
1192
                          (int) def->target.perms.uid);
1193
        virBufferAsprintf(&buf, "<group>%d</group>\n",
1194
                          (int) def->target.perms.gid);
1195

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

1199 1200 1201 1202
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</permissions>\n");
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</target>\n");
1203
    }
1204
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1205
    virBufferAddLit(&buf, "</pool>\n");
1206

1207 1208
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1209

1210
    return virBufferContentAndReset(&buf);
1211

1212
 cleanup:
1213
    virBufferFreeAndReset(&buf);
1214 1215 1216 1217 1218
    return NULL;
}


static int
1219
virStorageSize(const char *unit,
1220
               const char *val,
1221 1222 1223
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1224 1225
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("malformed capacity element"));
1226 1227
        return -1;
    }
1228 1229 1230 1231
    /* 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;
1232 1233 1234 1235 1236

    return 0;
}

static virStorageVolDefPtr
1237
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1238 1239
                         xmlXPathContextPtr ctxt)
{
1240
    virStorageVolDefPtr ret;
1241
    virStorageVolOptionsPtr options;
1242
    char *type = NULL;
1243 1244 1245
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1246
    char *backingStore = NULL;
1247
    xmlNodePtr node;
1248
    xmlNodePtr *nodes = NULL;
1249 1250
    size_t i;
    int n;
1251

1252
    options = virStorageVolOptionsForPoolType(pool->type);
1253 1254 1255
    if (options == NULL)
        return NULL;

1256
    if (VIR_ALLOC(ret) < 0)
1257 1258
        return NULL;

1259
    ret->name = virXPathString("string(./name)", ctxt);
1260
    if (ret->name == NULL) {
1261 1262
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing volume name element"));
1263
        goto error;
1264 1265
    }

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

1269 1270 1271 1272
    /* Technically overridden by pool refresh, but useful for unit tests */
    type = virXPathString("string(./@type)", ctxt);
    if (type) {
        if ((ret->type = virStorageVolTypeFromString(type)) < 0) {
1273
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1274 1275 1276 1277 1278
                           _("unknown volume type '%s'"), type);
            goto error;
        }
    }

1279 1280
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1281
    if (capacity == NULL) {
1282 1283
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing capacity element"));
1284
        goto error;
1285
    }
1286
    if (virStorageSize(unit, capacity, &ret->target.capacity) < 0)
1287
        goto error;
1288
    VIR_FREE(unit);
1289

1290
    allocation = virXPathString("string(./allocation)", ctxt);
1291
    if (allocation) {
1292
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1293
        if (virStorageSize(unit, allocation, &ret->target.allocation) < 0)
1294
            goto error;
1295
    } else {
1296
        ret->target.allocation = ret->target.capacity;
1297 1298
    }

1299
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1300
    if (options->formatFromString) {
1301
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1302 1303 1304 1305 1306 1307
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1308
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1309
                           _("unknown volume format type %s"), format);
1310
            VIR_FREE(format);
1311
            goto error;
1312
        }
1313
        VIR_FREE(format);
1314 1315
    }

1316 1317 1318
    if (VIR_ALLOC(ret->target.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->target.perms,
1319 1320
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1321
        goto error;
1322

1323
    node = virXPathNode("./target/encryption", ctxt);
1324
    if (node != NULL) {
1325
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1326 1327
                                                               node);
        if (ret->target.encryption == NULL)
1328
            goto error;
1329 1330
    }

1331 1332 1333
    if ((backingStore = virXPathString("string(./backingStore/path)", ctxt))) {
        if (VIR_ALLOC(ret->target.backingStore) < 0)
            goto error;
1334

1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
        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;
            }
1351 1352
            VIR_FREE(format);
        }
1353 1354 1355 1356 1357 1358 1359

        if (VIR_ALLOC(ret->target.backingStore->perms) < 0)
            goto error;
        if (virStorageDefParsePerms(ctxt, ret->target.backingStore->perms,
                                    "./backingStore/permissions",
                                    DEFAULT_VOL_PERM_MODE) < 0)
            goto error;
1360 1361
    }

1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    ret->target.compat = virXPathString("string(./target/compat)", ctxt);
    if (ret->target.compat) {
        char **version = virStringSplit(ret->target.compat, ".", 2);
        unsigned int result;

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

C
Chunyan Liu 已提交
1378 1379 1380
    if (virXPathNode("./target/nocow", ctxt))
        ret->target.nocow = true;

1381 1382 1383 1384 1385 1386 1387 1388
    if (options->featureFromString && virXPathNode("./target/features", ctxt)) {
        if ((n = virXPathNodeSet("./target/features/*", ctxt, &nodes)) < 0)
            goto error;

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

        if (!(ret->target.features = virBitmapNew(VIR_STORAGE_FILE_FEATURE_LAST)))
1389
            goto error;
1390 1391 1392 1393 1394

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

            if (f < 0) {
1395
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unsupported feature %s"),
1396 1397 1398 1399 1400 1401 1402 1403
                               (const char*)nodes[i]->name);
                goto error;
            }
            ignore_value(virBitmapSetBit(ret->target.features, f));
        }
        VIR_FREE(nodes);
    }

1404
 cleanup:
1405
    VIR_FREE(nodes);
1406 1407 1408
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1409
    VIR_FREE(type);
1410
    VIR_FREE(backingStore);
1411 1412
    return ret;

1413
 error:
1414
    virStorageVolDefFree(ret);
1415 1416
    ret = NULL;
    goto cleanup;
1417 1418 1419
}

virStorageVolDefPtr
1420
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1421
                          xmlDocPtr xml,
1422 1423
                          xmlNodePtr root)
{
1424 1425 1426
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1427
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1428
        virReportError(VIR_ERR_XML_ERROR,
1429 1430 1431
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1432 1433 1434 1435 1436
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1437
        virReportOOMError();
1438 1439 1440 1441
        goto cleanup;
    }

    ctxt->node = root;
1442
    def = virStorageVolDefParseXML(pool, ctxt);
1443
 cleanup:
1444 1445 1446 1447 1448
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1449
virStorageVolDefParse(virStoragePoolDefPtr pool,
1450
                      const char *xmlStr,
1451 1452
                      const char *filename)
{
1453
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1454
    xmlDocPtr xml;
1455

1456
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1457 1458
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1459 1460 1461 1462 1463
    }

    return ret;
}

1464
virStorageVolDefPtr
1465
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1466 1467
                            const char *xmlStr)
{
1468
    return virStorageVolDefParse(pool, xmlStr, NULL);
1469 1470 1471
}

virStorageVolDefPtr
1472
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1473 1474
                          const char *filename)
{
1475
    return virStorageVolDefParse(pool, NULL, filename);
1476
}
1477

1478 1479 1480 1481 1482 1483
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
1484
    virBufferAsprintf(buf, "<%s>%llu", name,
1485 1486 1487 1488 1489 1490
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1491
static int
1492
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1493
                             virBufferPtr buf,
1494
                             virStorageSourcePtr def,
1495 1496
                             const char *type)
{
1497 1498
    virBufferAsprintf(buf, "<%s>\n", type);
    virBufferAdjustIndent(buf, 2);
1499

1500
    virBufferEscapeString(buf, "<path>%s</path>\n", def->path);
1501 1502 1503 1504

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1505 1506 1507
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1508 1509
            return -1;
        }
1510
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1511 1512
    }

1513 1514 1515
    if (def->perms) {
        virBufferAddLit(buf, "<permissions>\n");
        virBufferAdjustIndent(buf, 2);
1516

1517 1518 1519 1520 1521 1522
        virBufferAsprintf(buf, "<mode>0%o</mode>\n",
                          def->perms->mode);
        virBufferAsprintf(buf, "<owner>%u</owner>\n",
                          (unsigned int) def->perms->uid);
        virBufferAsprintf(buf, "<group>%u</group>\n",
                          (unsigned int) def->perms->gid);
1523 1524


1525 1526
        virBufferEscapeString(buf, "<label>%s</label>\n",
                              def->perms->label);
1527

1528 1529 1530
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</permissions>\n");
    }
1531

1532
    if (def->timestamps) {
1533 1534
        virBufferAddLit(buf, "<timestamps>\n");
        virBufferAdjustIndent(buf, 2);
1535 1536 1537 1538
        virStorageVolTimestampFormat(buf, "atime", &def->timestamps->atime);
        virStorageVolTimestampFormat(buf, "mtime", &def->timestamps->mtime);
        virStorageVolTimestampFormat(buf, "ctime", &def->timestamps->ctime);
        virStorageVolTimestampFormat(buf, "btime", &def->timestamps->btime);
1539 1540
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timestamps>\n");
1541 1542
    }

1543 1544
    if (def->encryption &&
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1545
            return -1;
1546

1547
    virBufferEscapeString(buf, "<compat>%s</compat>\n", def->compat);
1548 1549

    if (options->featureToString && def->features) {
1550
        size_t i;
1551 1552 1553
        bool b;
        bool empty = virBitmapIsAllClear(def->features);

1554 1555 1556 1557 1558 1559
        if (empty) {
            virBufferAddLit(buf, "<features/>\n");
        } else {
            virBufferAddLit(buf, "<features>\n");
            virBufferAdjustIndent(buf, 2);
        }
1560 1561 1562 1563

        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
            ignore_value(virBitmapGetBit(def->features, i, &b));
            if (b)
1564
                virBufferAsprintf(buf, "<%s/>\n",
1565 1566
                                  options->featureToString(i));
        }
1567 1568 1569 1570
        if (!empty) {
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</features>\n");
        }
1571 1572
    }

1573 1574
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", type);
1575 1576
    return 0;
}
1577 1578

char *
1579
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1580 1581
                       virStorageVolDefPtr def)
{
1582
    virStorageVolOptionsPtr options;
1583
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1584

1585
    options = virStorageVolOptionsForPoolType(pool->type);
1586 1587 1588
    if (options == NULL)
        return NULL;

1589 1590
    virBufferAsprintf(&buf, "<volume type='%s'>\n",
                      virStorageVolTypeToString(def->type));
1591 1592 1593 1594 1595 1596
    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);
1597 1598

    if (def->source.nextent) {
1599
        size_t i;
1600
        const char *thispath = NULL;
1601
        for (i = 0; i < def->source.nextent; i++) {
1602 1603 1604
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1605
                    virBufferAddLit(&buf, "</device>\n");
1606

1607
                virBufferEscapeString(&buf, "<device path='%s'>\n",
1608
                                      def->source.extents[i].path);
1609 1610
            }

1611 1612
            virBufferAdjustIndent(&buf, 2);
            virBufferAsprintf(&buf, "<extent start='%llu' end='%llu'/>\n",
1613 1614
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1615
            virBufferAdjustIndent(&buf, -2);
1616 1617 1618
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1619
            virBufferAddLit(&buf, "</device>\n");
1620 1621
    }

1622 1623 1624 1625
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</source>\n");

    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1626
                      def->target.capacity);
1627
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1628
                      def->target.allocation);
1629

1630
    if (virStorageVolTargetDefFormat(options, &buf,
1631 1632
                                     &def->target, "target") < 0)
        goto cleanup;
1633

1634
    if (def->target.backingStore &&
1635
        virStorageVolTargetDefFormat(options, &buf,
1636 1637
                                     def->target.backingStore,
                                     "backingStore") < 0)
1638
        goto cleanup;
1639

1640
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1641
    virBufferAddLit(&buf, "</volume>\n");
1642

1643 1644
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1645

1646
    return virBufferContentAndReset(&buf);
1647

1648
 cleanup:
1649
    virBufferFreeAndReset(&buf);
1650 1651 1652 1653 1654
    return NULL;
}


virStoragePoolObjPtr
1655
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1656 1657
                            const unsigned char *uuid)
{
1658
    size_t i;
1659

1660
    for (i = 0; i < pools->count; i++) {
1661
        virStoragePoolObjLock(pools->objs[i]);
1662 1663
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1664 1665
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1666 1667 1668 1669 1670

    return NULL;
}

virStoragePoolObjPtr
1671
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1672 1673
                            const char *name)
{
1674
    size_t i;
1675

1676
    for (i = 0; i < pools->count; i++) {
1677
        virStoragePoolObjLock(pools->objs[i]);
1678 1679
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1680 1681
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1682 1683 1684 1685

    return NULL;
}

1686 1687
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1688 1689
                                         virStoragePoolDefPtr def)
{
1690
    size_t i, j;
1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701

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

1702 1703 1704
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1705
    size_t i;
1706
    for (i = 0; i < pool->volumes.count; i++)
1707 1708 1709 1710
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1711 1712 1713 1714
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1715 1716
                          const char *key)
{
1717
    size_t i;
1718

1719
    for (i = 0; i < pool->volumes.count; i++)
1720 1721
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1722 1723 1724 1725 1726 1727

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1728 1729
                           const char *path)
{
1730
    size_t i;
1731

1732
    for (i = 0; i < pool->volumes.count; i++)
1733 1734
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1735 1736 1737 1738 1739 1740

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1741 1742
                           const char *name)
{
1743
    size_t i;
1744

1745
    for (i = 0; i < pool->volumes.count; i++)
1746 1747
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1748 1749 1750 1751 1752

    return NULL;
}

virStoragePoolObjPtr
1753
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1754 1755
                           virStoragePoolDefPtr def)
{
1756 1757
    virStoragePoolObjPtr pool;

1758
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1759 1760 1761 1762
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1763
            virStoragePoolDefFree(pool->newDef);
1764 1765 1766 1767 1768
            pool->newDef = def;
        }
        return pool;
    }

1769
    if (VIR_ALLOC(pool) < 0)
1770 1771
        return NULL;

1772
    if (virMutexInit(&pool->lock) < 0) {
1773 1774
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1775 1776 1777
        VIR_FREE(pool);
        return NULL;
    }
1778
    virStoragePoolObjLock(pool);
1779 1780
    pool->active = 0;

1781
    if (VIR_APPEND_ELEMENT_COPY(pools->objs, pools->count, pool) < 0) {
1782
        virStoragePoolObjUnlock(pool);
1783 1784 1785
        virStoragePoolObjFree(pool);
        return NULL;
    }
1786
    pool->def = def;
1787 1788 1789 1790 1791

    return pool;
}

static virStoragePoolObjPtr
1792
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1793 1794
                      const char *file,
                      const char *path,
1795 1796
                      const char *autostartLink)
{
1797 1798 1799
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1800
    if (!(def = virStoragePoolDefParseFile(path))) {
1801 1802 1803 1804
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1805
        virReportError(VIR_ERR_XML_ERROR,
1806 1807
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1808
                       path, def->name);
1809 1810 1811 1812
        virStoragePoolDefFree(def);
        return NULL;
    }

1813
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1814 1815 1816 1817
        virStoragePoolDefFree(def);
        return NULL;
    }

1818
    VIR_FREE(pool->configFile);  /* for driver reload */
1819
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1820 1821 1822
        virStoragePoolDefFree(def);
        return NULL;
    }
1823
    VIR_FREE(pool->autostartLink); /* for driver reload */
1824
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1837
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1838
                             const char *configDir,
1839 1840
                             const char *autostartDir)
{
1841 1842
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
1843
    int ret;
1844

1845
    if (!(dir = opendir(configDir))) {
1846 1847
        if (errno == ENOENT)
            return 0;
1848
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1849
                             configDir);
1850 1851 1852
        return -1;
    }

E
Eric Blake 已提交
1853
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
1854 1855
        char *path;
        char *autostartLink;
1856
        virStoragePoolObjPtr pool;
1857 1858 1859 1860 1861 1862 1863

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

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

1864
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1865 1866
            continue;

1867 1868 1869
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1870 1871 1872
            continue;
        }

1873
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1874
                                     autostartLink);
1875 1876
        if (pool)
            virStoragePoolObjUnlock(pool);
1877 1878 1879

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1880 1881 1882
    }

    closedir(dir);
E
Eric Blake 已提交
1883
    return ret;
1884 1885 1886
}

int
1887
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1888
                         virStoragePoolObjPtr pool,
1889 1890
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1891
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1892
    char *xml;
1893
    int ret = -1;
1894 1895

    if (!pool->configFile) {
1896 1897
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1898 1899
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1900 1901 1902
            return -1;
        }

1903 1904
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1905 1906 1907
            return -1;
        }

1908 1909
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1910
            VIR_FREE(pool->configFile);
1911 1912 1913 1914
            return -1;
        }
    }

1915
    if (!(xml = virStoragePoolDefFormat(def))) {
1916 1917
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
1918 1919 1920
        return -1;
    }

J
Ján Tomko 已提交
1921 1922 1923 1924
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1925
    VIR_FREE(xml);
1926 1927 1928 1929 1930

    return ret;
}

int
1931 1932
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
1933
    if (!pool->configFile) {
1934 1935
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1936 1937 1938 1939
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1940 1941 1942
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1943 1944 1945 1946 1947
        return -1;
    }

    return 0;
}
1948

1949
virStoragePoolSourcePtr
1950
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1951 1952 1953
{
    virStoragePoolSourcePtr source;

1954
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0)
1955 1956 1957 1958 1959 1960 1961 1962
        return NULL;

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

    return source;
}

1963 1964
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1965
{
1966
    virStoragePoolOptionsPtr options;
1967
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1968
    const char *type;
1969
    size_t i;
1970

1971
    options = virStoragePoolOptionsForPoolType(def->type);
1972 1973 1974
    if (options == NULL)
        return NULL;

1975
    type = virStoragePoolTypeToString(def->type);
1976
    if (!type) {
1977 1978
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1979 1980 1981 1982
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1983
    virBufferAdjustIndent(&buf, 2);
1984 1985

    for (i = 0; i < def->nsources; i++) {
1986
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1987 1988
    }

1989
    virBufferAdjustIndent(&buf, -2);
1990 1991
    virBufferAddLit(&buf, "</sources>\n");

1992 1993
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1994 1995

    return virBufferContentAndReset(&buf);
1996

1997
 cleanup:
1998
    virBufferFreeAndReset(&buf);
1999
    return NULL;
2000
}
D
Daniel P. Berrange 已提交
2001 2002


2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
/*
 * 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
 */
2013 2014 2015 2016
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
{
    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);
2028 2029 2030
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
2031 2032 2033 2034 2035 2036
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
2037 2038 2039
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
2040 2041 2042 2043
                goto cleanup;
            }
        }

J
Ján Tomko 已提交
2044
        ret = 1;
2045 2046 2047 2048 2049 2050
    } 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);
2051 2052 2053
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2054 2055
            goto cleanup;
        }
J
Ján Tomko 已提交
2056
        ret = 0;
2057 2058
    }

2059
 cleanup:
2060 2061 2062 2063 2064
    if (pool)
        virStoragePoolObjUnlock(pool);
    return ret;
}

2065 2066 2067
static int
getSCSIHostNumber(virStoragePoolSourceAdapter adapter,
                  unsigned int *hostnum)
2068
{
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
    int ret = -1;
    unsigned int num;
    char *name = NULL;

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

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

    *hostnum = num;
    ret = 0;

 cleanup:
    VIR_FREE(name);
    return ret;
2096
}
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
static bool
matchSCSIAdapterParent(virStoragePoolObjPtr pool,
                       virStoragePoolDefPtr def)
{
    virDevicePCIAddressPtr pooladdr =
        &pool->def->source.adapter.data.scsi_host.parentaddr;
    virDevicePCIAddressPtr defaddr =
        &def->source.adapter.data.scsi_host.parentaddr;
    int pool_unique_id =
        pool->def->source.adapter.data.scsi_host.unique_id;
    int def_unique_id =
        def->source.adapter.data.scsi_host.unique_id;
    if (pooladdr->domain == defaddr->domain &&
        pooladdr->bus == defaddr->bus &&
        pooladdr->slot == defaddr->slot &&
        pooladdr->function == defaddr->function &&
        pool_unique_id == def_unique_id) {
        return true;
    }
    return false;
}

2119

2120 2121 2122
int
virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                  virStoragePoolDefPtr def)
2123
{
2124
    size_t i;
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
    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;

2135 2136 2137 2138
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2139 2140 2141 2142 2143 2144 2145 2146 2147
        virStoragePoolObjLock(pool);

        switch (pool->def->type) {
        case VIR_STORAGE_POOL_DIR:
            if (STREQ(pool->def->target.path, def->target.path))
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_NETFS:
            if ((STREQ(pool->def->source.dir, def->source.dir)) \
2148 2149
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
2150 2151 2152
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2153
            if (pool->def->source.adapter.type ==
2154 2155
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST &&
                def->source.adapter.type ==
2156 2157 2158 2159 2160 2161 2162
                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 ==
2163 2164
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST &&
                       def->source.adapter.type ==
2165
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
2166 2167
                unsigned int pool_hostnum, def_hostnum;

2168 2169 2170 2171 2172 2173 2174
                if (pool->def->source.adapter.data.scsi_host.has_parent &&
                    def->source.adapter.data.scsi_host.has_parent &&
                    matchSCSIAdapterParent(pool, def)) {
                    matchpool = pool;
                    break;
                }

2175 2176 2177
                if (getSCSIHostNumber(pool->def->source.adapter,
                                      &pool_hostnum) < 0 ||
                    getSCSIHostNumber(def->source.adapter, &def_hostnum) < 0)
2178
                    break;
2179 2180
                if (pool_hostnum == def_hostnum)
                    matchpool = pool;
2181
            }
2182 2183 2184 2185
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2186 2187 2188 2189 2190 2191 2192 2193
                if (matchpool->def->source.nhost == 1 && def->source.nhost == 1) {
                    if (STREQ(matchpool->def->source.hosts[0].name, def->source.hosts[0].name)) {
                        if ((matchpool->def->source.initiator.iqn) && (def->source.initiator.iqn)) {
                            if (STREQ(matchpool->def->source.initiator.iqn, def->source.initiator.iqn))
                                break;
                            matchpool = NULL;
                        }
                        break;
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
                    }
                }
                matchpool = NULL;
            }
            break;
        case VIR_STORAGE_POOL_FS:
        case VIR_STORAGE_POOL_LOGICAL:
        case VIR_STORAGE_POOL_DISK:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            break;
        default:
            break;
        }
        virStoragePoolObjUnlock(pool);
2208 2209 2210

        if (matchpool)
            break;
2211 2212 2213
    }

    if (matchpool) {
2214 2215 2216
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2217 2218 2219 2220
        ret = -1;
    }
    return ret;
}
2221

2222 2223
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2224
{
2225
    virMutexLock(&obj->lock);
2226 2227
}

2228 2229
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2230
{
2231
    virMutexUnlock(&obj->lock);
2232
}
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 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

#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) &&
2284 2285 2286
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
               (poolobj->def->type == VIR_STORAGE_POOL_GLUSTER))))
2287 2288 2289 2290 2291 2292 2293 2294
            return false;
    }

    return true;
}
#undef MATCH

int
2295 2296 2297 2298 2299
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2300 2301 2302 2303 2304
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2305
    size_t i;
2306

2307 2308
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2309 2310 2311 2312

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2313 2314
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2315 2316 2317
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2318 2319
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338
                    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;

2339
 cleanup:
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349
    if (tmp_pools) {
        for (i = 0; i < npools; i++) {
            if (tmp_pools[i])
                virStoragePoolFree(tmp_pools[i]);
        }
    }

    VIR_FREE(tmp_pools);
    return ret;
}