storage_conf.c 67.6 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",
64
              "scsi", "mpath", "rbd", "sheepdog", "gluster")
65 66 67 68 69

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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


static virStoragePoolTypeInfoPtr
286 287
virStoragePoolTypeInfoLookup(int type)
{
288
    size_t i;
289
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo); i++)
290 291 292
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

293 294
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
295 296 297 298
    return NULL;
}

static virStoragePoolOptionsPtr
299 300
virStoragePoolOptionsForPoolType(int type)
{
301 302 303 304 305 306 307
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
308 309
virStorageVolOptionsForPoolType(int type)
{
310 311 312 313 314 315 316
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


317
void
318 319
virStorageVolDefFree(virStorageVolDefPtr def)
{
320
    size_t i;
321 322 323 324

    if (!def)
        return;

325 326
    VIR_FREE(def->name);
    VIR_FREE(def->key);
327

328
    for (i = 0; i < def->source.nextent; i++) {
329
        VIR_FREE(def->source.extents[i].path);
330
    }
331
    VIR_FREE(def->source.extents);
332

333
    virStorageSourceClear(&def->target);
334
    VIR_FREE(def);
335 336
}

337 338 339 340 341 342 343 344 345
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) {
346
        VIR_FREE(adapter.data.scsi_host.name);
347 348 349
    }
}

350 351 352 353 354 355 356
void
virStoragePoolSourceDeviceClear(virStoragePoolSourceDevicePtr dev)
{
    VIR_FREE(dev->freeExtents);
    VIR_FREE(dev->path);
}

357
void
358 359
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
360
    size_t i;
361

362
    if (!source)
363 364
        return;

365
    for (i = 0; i < source->nhost; i++) {
366 367 368 369
        VIR_FREE(source->hosts[i].name);
    }
    VIR_FREE(source->hosts);

370 371
    for (i = 0; i < source->ndevice; i++)
        virStoragePoolSourceDeviceClear(&source->devices[i]);
372 373 374
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
375
    virStoragePoolSourceAdapterClear(source->adapter);
D
David Allan 已提交
376
    VIR_FREE(source->initiator.iqn);
377
    virStorageAuthDefFree(source->auth);
378 379
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
380 381
}

382 383 384 385 386 387 388
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

389
void
390 391
virStoragePoolDefFree(virStoragePoolDefPtr def)
{
392 393 394 395 396
    if (!def)
        return;

    VIR_FREE(def->name);

397
    virStoragePoolSourceClear(&def->source);
398

399 400 401
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
402 403 404 405
}


void
406 407
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
408 409 410
    if (!obj)
        return;

411 412
    virStoragePoolObjClearVols(obj);

413 414
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
415

416 417
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
418 419 420

    virMutexDestroy(&obj->lock);

421
    VIR_FREE(obj);
422 423
}

424 425
void
virStoragePoolObjListFree(virStoragePoolObjListPtr pools)
426
{
427
    size_t i;
428
    for (i = 0; i < pools->count; i++)
429 430 431 432 433
        virStoragePoolObjFree(pools->objs[i]);
    VIR_FREE(pools->objs);
    pools->count = 0;
}

434
void
435
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
436 437
                        virStoragePoolObjPtr pool)
{
438
    size_t i;
439

440 441
    virStoragePoolObjUnlock(pool);

442
    for (i = 0; i < pools->count; i++) {
443
        virStoragePoolObjLock(pools->objs[i]);
444
        if (pools->objs[i] == pool) {
445
            virStoragePoolObjUnlock(pools->objs[i]);
446
            virStoragePoolObjFree(pools->objs[i]);
447

448
            VIR_DELETE_ELEMENT(pools->objs, i, pools->count);
449 450
            break;
        }
451
        virStoragePoolObjUnlock(pools->objs[i]);
452
    }
453 454
}

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

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

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

479
    source->name = virXPathString("string(./name)", ctxt);
480
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
481
        virReportError(VIR_ERR_XML_ERROR, "%s",
482
                       _("element 'name' is mandatory for RBD pool"));
483 484
        goto cleanup;
    }
485 486

    if (options->formatFromString) {
487
        char *format = virXPathString("string(./format/@type)", ctxt);
488 489 490 491 492 493
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
494
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
495
                           _("unknown pool format type %s"), format);
496 497 498 499 500 501
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

502 503
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
504

505 506
    if (n) {
        if (VIR_ALLOC_N(source->hosts, n) < 0)
507
            goto cleanup;
508
        source->nhost = n;
509

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

531
    VIR_FREE(nodeset);
532
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
533

534
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
535 536 537
    if (nsource < 0)
        goto cleanup;

538 539 540 541 542 543 544
    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"));
545 546 547
            goto cleanup;
        }

548 549 550
        if (VIR_APPEND_ELEMENT(source->devices, source->ndevice, dev) < 0) {
            virStoragePoolSourceDeviceClear(&dev);
            goto cleanup;
551 552 553
        }
    }

554
    source->dir = virXPathString("string(./dir/@path)", ctxt);
555 556 557 558
    /* In gluster, a missing dir defaults to "/" */
    if (!source->dir && pool_type == VIR_STORAGE_POOL_GLUSTER &&
        VIR_STRDUP(source->dir, "/") < 0)
        goto cleanup;
559 560 561

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

        if (source->adapter.type ==
            VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            source->adapter.data.fchost.parent =
                virXPathString("string(./adapter/@parent)", ctxt);
            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) {
579
            source->adapter.data.scsi_host.name =
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
                virXPathString("string(./adapter/@name)", ctxt);
        }
    } else {
        char *wwnn = NULL;
        char *wwpn = NULL;
        char *parent = NULL;

        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 "
                             "requires the 'fc_host' adapter 'type'"));
            goto cleanup;
        }

        /* To keep back-compat, 'type' is not required to specify
         * for scsi_host adapter.
         */
604
        if ((source->adapter.data.scsi_host.name =
605 606 607 608
             virXPathString("string(./adapter/@name)", ctxt)))
            source->adapter.type =
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST;
    }
609

610 611 612 613 614 615 616 617 618 619 620 621
    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;
    }
622

623 624 625
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

626
    ret = 0;
627
 cleanup:
628 629
    ctxt->node = relnode;

630
    VIR_FREE(port);
631
    VIR_FREE(nodeset);
632
    VIR_FREE(adapter_type);
633 634
    return ret;
}
635

636
virStoragePoolSourcePtr
637
virStoragePoolDefParseSourceString(const char *srcSpec,
638 639 640 641 642 643 644
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

645 646 647
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
648 649
        goto cleanup;

650
    if (VIR_ALLOC(def) < 0)
651 652
        goto cleanup;

653
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
654 655
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
656 657 658
        goto cleanup;
    }

659
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
660 661 662 663 664
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
665
 cleanup:
666
    virStoragePoolSourceFree(def);
667 668 669 670 671
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
672

673
static int
674
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
675 676
                        virStoragePermsPtr perms,
                        const char *permxpath,
677 678
                        int defaultmode)
{
679
    char *mode;
680
    long val;
681 682 683
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
684

685
    node = virXPathNode(permxpath, ctxt);
686 687 688
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
P
Philipp Hahn 已提交
689 690
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
691 692 693 694 695 696 697
        perms->label = NULL;
        return 0;
    }

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

698
    mode = virXPathString("string(./mode)", ctxt);
699
    if (!mode) {
700
        perms->mode = defaultmode;
701
    } else {
702 703 704
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
705
            VIR_FREE(mode);
706 707
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
708
            goto error;
709
        }
710
        perms->mode = tmp;
711
        VIR_FREE(mode);
712 713
    }

714
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
715
        perms->uid = (uid_t) -1;
716
    } else {
717 718 719
        if (virXPathLong("number(./owner)", ctxt, &val) < 0 ||
            ((uid_t)val != val &&
             val != -1)) {
720 721
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed owner element"));
722
            goto error;
723
        }
724 725

        perms->uid = val;
726 727
    }

728
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
729
        perms->gid = (gid_t) -1;
730
    } else {
731 732 733
        if (virXPathLong("number(./group)", ctxt, &val) < 0 ||
            ((gid_t) val != val &&
             val != -1)) {
734 735
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed group element"));
736
            goto error;
737
        }
738
        perms->gid = val;
739 740 741
    }

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

744
    ret = 0;
745
 error:
746 747
    ctxt->node = relnode;
    return ret;
748 749 750
}

static virStoragePoolDefPtr
751 752
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
753
    virStoragePoolOptionsPtr options;
754
    virStoragePoolDefPtr ret;
755
    xmlNodePtr source_node;
756
    char *type = NULL;
757
    char *uuid = NULL;
758
    char *target_path = NULL;
759

760
    if (VIR_ALLOC(ret) < 0)
761 762
        return NULL;

763
    type = virXPathString("string(./@type)", ctxt);
764 765 766 767 768 769
    if (type == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("storage pool missing type attribute"));
        goto error;
    }

770
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
771
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
772
                       _("unknown storage pool type %s"), type);
773
        goto error;
774 775 776
    }

    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
777
        goto error;
778 779
    }

780
    source_node = virXPathNode("./source", ctxt);
781
    if (source_node) {
782
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
783
                                         source_node) < 0)
784
            goto error;
785 786
    }

787
    ret->name = virXPathString("string(./name)", ctxt);
788
    if (ret->name == NULL &&
789
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
790
        ret->name = ret->source.name;
791
    if (ret->name == NULL) {
792 793
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
794
        goto error;
795 796
    }

797
    uuid = virXPathString("string(./uuid)", ctxt);
798 799
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
800 801
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
802
            goto error;
803 804 805
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
806 807
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
808
            goto error;
809 810 811
        }
    }

812
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
813
        if (!ret->source.nhost) {
814
            virReportError(VIR_ERR_XML_ERROR, "%s",
815
                           _("missing storage pool source host name"));
816
            goto error;
817 818 819
        }
    }

820
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
821
        if (!ret->source.dir) {
822 823
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
824
            goto error;
825 826
        }
    }
827
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
828 829
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
830
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
831
                goto error;
832 833
        }
    }
834

835
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
836 837 838
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
839
            goto error;
840
        }
841 842 843 844 845 846 847 848

        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'"));
849
                goto error;
850 851 852 853
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
854
                goto error;
855 856
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
857
            if (!ret->source.adapter.data.scsi_host.name) {
858 859
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source adapter name"));
860
                goto error;
861 862
            }
        }
863
    }
864

865 866 867
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
868 869
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
870
            goto error;
871 872 873
        }
    }

874 875 876
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
877 878 879 880 881 882 883 884 885 886 887
        if (ret->type == VIR_STORAGE_POOL_LOGICAL) {
            if (virAsprintf(&target_path, "/dev/%s", ret->source.name) < 0) {
                goto error;
            }
        } else {
            target_path = virXPathString("string(./target/path)", ctxt);
            if (!target_path) {
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool target path"));
                goto error;
            }
888
        }
889
        ret->target.path = virFileSanitizePath(target_path);
890
        if (!ret->target.path)
891
            goto error;
892

893
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
894 895
                                    "./target/permissions",
                                    DEFAULT_POOL_PERM_MODE) < 0)
896
            goto error;
897
    }
898

899
 cleanup:
900
    VIR_FREE(uuid);
901 902 903 904
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

905
 error:
906
    virStoragePoolDefFree(ret);
907 908
    ret = NULL;
    goto cleanup;
909 910 911
}

virStoragePoolDefPtr
912
virStoragePoolDefParseNode(xmlDocPtr xml,
913 914
                           xmlNodePtr root)
{
915 916 917
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

918
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
919
        virReportError(VIR_ERR_XML_ERROR,
920 921 922
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
923 924 925 926 927
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
928
        virReportOOMError();
929 930 931 932
        goto cleanup;
    }

    ctxt->node = root;
933
    def = virStoragePoolDefParseXML(ctxt);
934
 cleanup:
935 936 937 938 939
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
940
virStoragePoolDefParse(const char *xmlStr,
941 942
                       const char *filename)
{
943
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
944
    xmlDocPtr xml;
945

946
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
947 948
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
949 950
    }

951 952 953
    return ret;
}

954
virStoragePoolDefPtr
955
virStoragePoolDefParseString(const char *xmlStr)
956
{
957
    return virStoragePoolDefParse(xmlStr, NULL);
958 959 960
}

virStoragePoolDefPtr
961
virStoragePoolDefParseFile(const char *filename)
962
{
963
    return virStoragePoolDefParse(NULL, filename);
964 965
}

966
static int
967
virStoragePoolSourceFormat(virBufferPtr buf,
968
                           virStoragePoolOptionsPtr options,
969 970
                           virStoragePoolSourcePtr src)
{
971
    size_t i, j;
972

973 974 975
    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

976 977
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
978
            virBufferEscapeString(buf, "<host name='%s'",
979
                                  src->hosts[i].name);
980 981 982 983
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
984
    }
985

986
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
987
        src->ndevice) {
988
        for (i = 0; i < src->ndevice; i++) {
989
            if (src->devices[i].nfreeExtent) {
990
                virBufferEscapeString(buf, "<device path='%s'>\n",
991
                                      src->devices[i].path);
992
                virBufferAdjustIndent(buf, 2);
993
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
994
                    virBufferAsprintf(buf, "<freeExtent start='%llu' end='%llu'/>\n",
995 996 997
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
998 999
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</device>\n");
1000
            } else {
1001
                virBufferEscapeString(buf, "<device path='%s'/>\n",
1002
                                      src->devices[i].path);
1003
            }
1004 1005
        }
    }
1006

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

1010 1011 1012
    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)
1013
            virBufferAsprintf(buf, "<adapter type='%s'",
1014
                              virStoragePoolSourceAdapterTypeToString(src->adapter.type));
1015 1016 1017 1018

        if (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            virBufferEscapeString(buf, " parent='%s'",
                                  src->adapter.data.fchost.parent);
E
Eric Blake 已提交
1019
            virBufferAsprintf(buf, " wwnn='%s' wwpn='%s'/>\n",
1020 1021 1022 1023
                              src->adapter.data.fchost.wwnn,
                              src->adapter.data.fchost.wwpn);
        } else if (src->adapter.type ==
                 VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
1024 1025
            virBufferAsprintf(buf, " name='%s'/>\n",
                              src->adapter.data.scsi_host.name);
1026 1027
        }
    }
1028

1029
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
1030
        virBufferEscapeString(buf, "<name>%s</name>\n", src->name);
1031

D
David Allan 已提交
1032 1033
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN) &&
        src->initiator.iqn) {
1034 1035 1036
        virBufferAddLit(buf, "<initiator>\n");
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<iqn name='%s'/>\n",
E
Eric Blake 已提交
1037
                              src->initiator.iqn);
1038 1039
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</initiator>\n");
D
David Allan 已提交
1040 1041
    }

1042 1043 1044
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
1045 1046 1047
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
1048 1049
            return -1;
        }
1050
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1051 1052
    }

1053 1054 1055
    if (src->auth) {
        if (virStorageAuthDefFormat(buf, src->auth) < 0)
            return -1;
1056 1057
    }

1058 1059
    virBufferEscapeString(buf, "<vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "<product name='%s'/>\n", src->product);
1060

1061 1062
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
1063 1064 1065
    return 0;
}

1066 1067

char *
1068 1069
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
1070
    virStoragePoolOptionsPtr options;
1071
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1072 1073 1074
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1075
    options = virStoragePoolOptionsForPoolType(def->type);
1076 1077 1078
    if (options == NULL)
        return NULL;

1079
    type = virStoragePoolTypeToString(def->type);
1080
    if (!type) {
1081 1082
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1083 1084
        goto cleanup;
    }
1085
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
1086 1087
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
1088 1089

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

1092
    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1093
                      def->capacity);
1094
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1095
                      def->allocation);
1096
    virBufferAsprintf(&buf, "<available unit='bytes'>%llu</available>\n",
1097
                      def->available);
1098

1099
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1100
        goto cleanup;
1101

1102 1103
    /* RBD, Sheepdog, and Gluster devices are not local block devs nor
     * files, so they don't have a target */
1104
    if (def->type != VIR_STORAGE_POOL_RBD &&
1105 1106
        def->type != VIR_STORAGE_POOL_SHEEPDOG &&
        def->type != VIR_STORAGE_POOL_GLUSTER) {
1107 1108
        virBufferAddLit(&buf, "<target>\n");
        virBufferAdjustIndent(&buf, 2);
1109

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

1112 1113 1114
        virBufferAddLit(&buf, "<permissions>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<mode>0%o</mode>\n",
1115
                          def->target.perms.mode);
1116
        virBufferAsprintf(&buf, "<owner>%d</owner>\n",
1117
                          (int) def->target.perms.uid);
1118
        virBufferAsprintf(&buf, "<group>%d</group>\n",
1119
                          (int) def->target.perms.gid);
1120

1121
        virBufferEscapeString(&buf, "<label>%s</label>\n",
1122
                              def->target.perms.label);
1123

1124 1125 1126 1127
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</permissions>\n");
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</target>\n");
1128
    }
1129
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1130
    virBufferAddLit(&buf, "</pool>\n");
1131

1132 1133
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1134

1135
    return virBufferContentAndReset(&buf);
1136

1137
 cleanup:
1138
    virBufferFreeAndReset(&buf);
1139 1140 1141 1142 1143
    return NULL;
}


static int
1144
virStorageSize(const char *unit,
1145
               const char *val,
1146 1147 1148
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1149 1150
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("malformed capacity element"));
1151 1152
        return -1;
    }
1153 1154 1155 1156
    /* 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;
1157 1158 1159 1160 1161

    return 0;
}

static virStorageVolDefPtr
1162
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1163 1164
                         xmlXPathContextPtr ctxt)
{
1165
    virStorageVolDefPtr ret;
1166
    virStorageVolOptionsPtr options;
1167
    char *type = NULL;
1168 1169 1170
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1171
    char *backingStore = NULL;
1172
    xmlNodePtr node;
1173
    xmlNodePtr *nodes = NULL;
1174 1175
    size_t i;
    int n;
1176

1177
    options = virStorageVolOptionsForPoolType(pool->type);
1178 1179 1180
    if (options == NULL)
        return NULL;

1181
    if (VIR_ALLOC(ret) < 0)
1182 1183
        return NULL;

1184
    ret->name = virXPathString("string(./name)", ctxt);
1185
    if (ret->name == NULL) {
1186 1187
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing volume name element"));
1188
        goto error;
1189 1190
    }

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

1194 1195 1196 1197
    /* Technically overridden by pool refresh, but useful for unit tests */
    type = virXPathString("string(./@type)", ctxt);
    if (type) {
        if ((ret->type = virStorageVolTypeFromString(type)) < 0) {
1198
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1199 1200 1201 1202 1203
                           _("unknown volume type '%s'"), type);
            goto error;
        }
    }

1204 1205
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1206
    if (capacity == NULL) {
1207 1208
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing capacity element"));
1209
        goto error;
1210
    }
1211
    if (virStorageSize(unit, capacity, &ret->target.capacity) < 0)
1212
        goto error;
1213
    VIR_FREE(unit);
1214

1215
    allocation = virXPathString("string(./allocation)", ctxt);
1216
    if (allocation) {
1217
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1218
        if (virStorageSize(unit, allocation, &ret->target.allocation) < 0)
1219
            goto error;
1220
    } else {
1221
        ret->target.allocation = ret->target.capacity;
1222 1223
    }

1224
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1225
    if (options->formatFromString) {
1226
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1227 1228 1229 1230 1231 1232
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1233
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1234
                           _("unknown volume format type %s"), format);
1235
            VIR_FREE(format);
1236
            goto error;
1237
        }
1238
        VIR_FREE(format);
1239 1240
    }

1241 1242 1243
    if (VIR_ALLOC(ret->target.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->target.perms,
1244 1245
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1246
        goto error;
1247

1248
    node = virXPathNode("./target/encryption", ctxt);
1249
    if (node != NULL) {
1250
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1251 1252
                                                               node);
        if (ret->target.encryption == NULL)
1253
            goto error;
1254 1255
    }

1256 1257 1258
    if ((backingStore = virXPathString("string(./backingStore/path)", ctxt))) {
        if (VIR_ALLOC(ret->target.backingStore) < 0)
            goto error;
1259

1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        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;
            }
1276 1277
            VIR_FREE(format);
        }
1278 1279 1280 1281 1282 1283 1284

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

1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
    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 已提交
1303 1304 1305
    if (virXPathNode("./target/nocow", ctxt))
        ret->target.nocow = true;

1306 1307 1308 1309 1310 1311 1312 1313
    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)))
1314
            goto error;
1315 1316 1317 1318 1319

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

            if (f < 0) {
1320
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("unsupported feature %s"),
1321 1322 1323 1324 1325 1326 1327 1328
                               (const char*)nodes[i]->name);
                goto error;
            }
            ignore_value(virBitmapSetBit(ret->target.features, f));
        }
        VIR_FREE(nodes);
    }

1329
 cleanup:
1330
    VIR_FREE(nodes);
1331 1332 1333
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1334
    VIR_FREE(type);
1335
    VIR_FREE(backingStore);
1336 1337
    return ret;

1338
 error:
1339
    virStorageVolDefFree(ret);
1340 1341
    ret = NULL;
    goto cleanup;
1342 1343 1344
}

virStorageVolDefPtr
1345
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1346
                          xmlDocPtr xml,
1347 1348
                          xmlNodePtr root)
{
1349 1350 1351
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1352
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1353
        virReportError(VIR_ERR_XML_ERROR,
1354 1355 1356
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1357 1358 1359 1360 1361
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1362
        virReportOOMError();
1363 1364 1365 1366
        goto cleanup;
    }

    ctxt->node = root;
1367
    def = virStorageVolDefParseXML(pool, ctxt);
1368
 cleanup:
1369 1370 1371 1372 1373
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1374
virStorageVolDefParse(virStoragePoolDefPtr pool,
1375
                      const char *xmlStr,
1376 1377
                      const char *filename)
{
1378
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1379
    xmlDocPtr xml;
1380

1381
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1382 1383
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1384 1385 1386 1387 1388
    }

    return ret;
}

1389
virStorageVolDefPtr
1390
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1391 1392
                            const char *xmlStr)
{
1393
    return virStorageVolDefParse(pool, xmlStr, NULL);
1394 1395 1396
}

virStorageVolDefPtr
1397
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1398 1399
                          const char *filename)
{
1400
    return virStorageVolDefParse(pool, NULL, filename);
1401
}
1402

1403 1404 1405 1406 1407 1408
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
1409
    virBufferAsprintf(buf, "<%s>%llu", name,
1410 1411 1412 1413 1414 1415
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1416
static int
1417
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1418
                             virBufferPtr buf,
1419
                             virStorageSourcePtr def,
1420 1421
                             const char *type)
{
1422 1423
    virBufferAsprintf(buf, "<%s>\n", type);
    virBufferAdjustIndent(buf, 2);
1424

1425
    virBufferEscapeString(buf, "<path>%s</path>\n", def->path);
1426 1427 1428 1429

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1430 1431 1432
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1433 1434
            return -1;
        }
1435
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1436 1437
    }

1438 1439 1440
    if (def->perms) {
        virBufferAddLit(buf, "<permissions>\n");
        virBufferAdjustIndent(buf, 2);
1441

1442 1443 1444 1445 1446 1447
        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);
1448 1449


1450 1451
        virBufferEscapeString(buf, "<label>%s</label>\n",
                              def->perms->label);
1452

1453 1454 1455
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</permissions>\n");
    }
1456

1457
    if (def->timestamps) {
1458 1459
        virBufferAddLit(buf, "<timestamps>\n");
        virBufferAdjustIndent(buf, 2);
1460 1461 1462 1463
        virStorageVolTimestampFormat(buf, "atime", &def->timestamps->atime);
        virStorageVolTimestampFormat(buf, "mtime", &def->timestamps->mtime);
        virStorageVolTimestampFormat(buf, "ctime", &def->timestamps->ctime);
        virStorageVolTimestampFormat(buf, "btime", &def->timestamps->btime);
1464 1465
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</timestamps>\n");
1466 1467
    }

1468 1469
    if (def->encryption &&
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1470
            return -1;
1471

1472
    virBufferEscapeString(buf, "<compat>%s</compat>\n", def->compat);
1473 1474

    if (options->featureToString && def->features) {
1475
        size_t i;
1476 1477 1478
        bool b;
        bool empty = virBitmapIsAllClear(def->features);

1479 1480 1481 1482 1483 1484
        if (empty) {
            virBufferAddLit(buf, "<features/>\n");
        } else {
            virBufferAddLit(buf, "<features>\n");
            virBufferAdjustIndent(buf, 2);
        }
1485 1486 1487 1488

        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
            ignore_value(virBitmapGetBit(def->features, i, &b));
            if (b)
1489
                virBufferAsprintf(buf, "<%s/>\n",
1490 1491
                                  options->featureToString(i));
        }
1492 1493 1494 1495
        if (!empty) {
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</features>\n");
        }
1496 1497
    }

1498 1499
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", type);
1500 1501
    return 0;
}
1502 1503

char *
1504
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1505 1506
                       virStorageVolDefPtr def)
{
1507
    virStorageVolOptionsPtr options;
1508
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1509

1510
    options = virStorageVolOptionsForPoolType(pool->type);
1511 1512 1513
    if (options == NULL)
        return NULL;

1514 1515
    virBufferAsprintf(&buf, "<volume type='%s'>\n",
                      virStorageVolTypeToString(def->type));
1516 1517 1518 1519 1520 1521
    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);
1522 1523

    if (def->source.nextent) {
1524
        size_t i;
1525
        const char *thispath = NULL;
1526
        for (i = 0; i < def->source.nextent; i++) {
1527 1528 1529
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1530
                    virBufferAddLit(&buf, "</device>\n");
1531

1532
                virBufferEscapeString(&buf, "<device path='%s'>\n",
1533
                                      def->source.extents[i].path);
1534 1535
            }

1536 1537
            virBufferAdjustIndent(&buf, 2);
            virBufferAsprintf(&buf, "<extent start='%llu' end='%llu'/>\n",
1538 1539
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1540
            virBufferAdjustIndent(&buf, -2);
1541 1542 1543
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1544
            virBufferAddLit(&buf, "</device>\n");
1545 1546
    }

1547 1548 1549 1550
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</source>\n");

    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1551
                      def->target.capacity);
1552
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1553
                      def->target.allocation);
1554

1555
    if (virStorageVolTargetDefFormat(options, &buf,
1556 1557
                                     &def->target, "target") < 0)
        goto cleanup;
1558

1559
    if (def->target.backingStore &&
1560
        virStorageVolTargetDefFormat(options, &buf,
1561 1562
                                     def->target.backingStore,
                                     "backingStore") < 0)
1563
        goto cleanup;
1564

1565
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1566
    virBufferAddLit(&buf, "</volume>\n");
1567

1568 1569
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1570

1571
    return virBufferContentAndReset(&buf);
1572

1573
 cleanup:
1574
    virBufferFreeAndReset(&buf);
1575 1576 1577 1578 1579
    return NULL;
}


virStoragePoolObjPtr
1580
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1581 1582
                            const unsigned char *uuid)
{
1583
    size_t i;
1584

1585
    for (i = 0; i < pools->count; i++) {
1586
        virStoragePoolObjLock(pools->objs[i]);
1587 1588
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1589 1590
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1591 1592 1593 1594 1595

    return NULL;
}

virStoragePoolObjPtr
1596
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1597 1598
                            const char *name)
{
1599
    size_t i;
1600

1601
    for (i = 0; i < pools->count; i++) {
1602
        virStoragePoolObjLock(pools->objs[i]);
1603 1604
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1605 1606
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1607 1608 1609 1610

    return NULL;
}

1611 1612
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1613 1614
                                         virStoragePoolDefPtr def)
{
1615
    size_t i, j;
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626

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

1627 1628 1629
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1630
    size_t i;
1631
    for (i = 0; i < pool->volumes.count; i++)
1632 1633 1634 1635
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1636 1637 1638 1639
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1640 1641
                          const char *key)
{
1642
    size_t i;
1643

1644
    for (i = 0; i < pool->volumes.count; i++)
1645 1646
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1647 1648 1649 1650 1651 1652

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1653 1654
                           const char *path)
{
1655
    size_t i;
1656

1657
    for (i = 0; i < pool->volumes.count; i++)
1658 1659
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1660 1661 1662 1663 1664 1665

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1666 1667
                           const char *name)
{
1668
    size_t i;
1669

1670
    for (i = 0; i < pool->volumes.count; i++)
1671 1672
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1673 1674 1675 1676 1677

    return NULL;
}

virStoragePoolObjPtr
1678
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1679 1680
                           virStoragePoolDefPtr def)
{
1681 1682
    virStoragePoolObjPtr pool;

1683
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1684 1685 1686 1687
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1688
            virStoragePoolDefFree(pool->newDef);
1689 1690 1691 1692 1693
            pool->newDef = def;
        }
        return pool;
    }

1694
    if (VIR_ALLOC(pool) < 0)
1695 1696
        return NULL;

1697
    if (virMutexInit(&pool->lock) < 0) {
1698 1699
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1700 1701 1702
        VIR_FREE(pool);
        return NULL;
    }
1703
    virStoragePoolObjLock(pool);
1704 1705
    pool->active = 0;

1706
    if (VIR_APPEND_ELEMENT_COPY(pools->objs, pools->count, pool) < 0) {
1707
        virStoragePoolObjUnlock(pool);
1708 1709 1710
        virStoragePoolObjFree(pool);
        return NULL;
    }
1711
    pool->def = def;
1712 1713 1714 1715 1716

    return pool;
}

static virStoragePoolObjPtr
1717
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1718 1719
                      const char *file,
                      const char *path,
1720 1721
                      const char *autostartLink)
{
1722 1723 1724
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1725
    if (!(def = virStoragePoolDefParseFile(path))) {
1726 1727 1728 1729
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1730
        virReportError(VIR_ERR_XML_ERROR,
1731 1732
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1733
                       path, def->name);
1734 1735 1736 1737
        virStoragePoolDefFree(def);
        return NULL;
    }

1738
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1739 1740 1741 1742
        virStoragePoolDefFree(def);
        return NULL;
    }

1743
    VIR_FREE(pool->configFile);  /* for driver reload */
1744
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1745 1746 1747
        virStoragePoolDefFree(def);
        return NULL;
    }
1748
    VIR_FREE(pool->autostartLink); /* for driver reload */
1749
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1762
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1763
                             const char *configDir,
1764 1765
                             const char *autostartDir)
{
1766 1767
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
1768
    int ret;
1769

1770
    if (!(dir = opendir(configDir))) {
1771 1772
        if (errno == ENOENT)
            return 0;
1773
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1774
                             configDir);
1775 1776 1777
        return -1;
    }

E
Eric Blake 已提交
1778
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
1779 1780
        char *path;
        char *autostartLink;
1781
        virStoragePoolObjPtr pool;
1782 1783 1784 1785 1786 1787 1788

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

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

1789
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1790 1791
            continue;

1792 1793 1794
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1795 1796 1797
            continue;
        }

1798
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1799
                                     autostartLink);
1800 1801
        if (pool)
            virStoragePoolObjUnlock(pool);
1802 1803 1804

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1805 1806 1807
    }

    closedir(dir);
E
Eric Blake 已提交
1808
    return ret;
1809 1810 1811
}

int
1812
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1813
                         virStoragePoolObjPtr pool,
1814 1815
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1816
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1817
    char *xml;
1818
    int ret = -1;
1819 1820

    if (!pool->configFile) {
1821 1822
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1823 1824
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1825 1826 1827
            return -1;
        }

1828 1829
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1830 1831 1832
            return -1;
        }

1833 1834
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1835
            VIR_FREE(pool->configFile);
1836 1837 1838 1839
            return -1;
        }
    }

1840
    if (!(xml = virStoragePoolDefFormat(def))) {
1841 1842
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
1843 1844 1845
        return -1;
    }

J
Ján Tomko 已提交
1846 1847 1848 1849
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1850
    VIR_FREE(xml);
1851 1852 1853 1854 1855

    return ret;
}

int
1856 1857
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
1858
    if (!pool->configFile) {
1859 1860
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1861 1862 1863 1864
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1865 1866 1867
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1868 1869 1870 1871 1872
        return -1;
    }

    return 0;
}
1873

1874
virStoragePoolSourcePtr
1875
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1876 1877 1878
{
    virStoragePoolSourcePtr source;

1879
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0)
1880 1881 1882 1883 1884 1885 1886 1887
        return NULL;

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

    return source;
}

1888 1889
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1890
{
1891
    virStoragePoolOptionsPtr options;
1892
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1893
    const char *type;
1894
    size_t i;
1895

1896
    options = virStoragePoolOptionsForPoolType(def->type);
1897 1898 1899
    if (options == NULL)
        return NULL;

1900
    type = virStoragePoolTypeToString(def->type);
1901
    if (!type) {
1902 1903
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1904 1905 1906 1907
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1908
    virBufferAdjustIndent(&buf, 2);
1909 1910

    for (i = 0; i < def->nsources; i++) {
1911
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1912 1913
    }

1914
    virBufferAdjustIndent(&buf, -2);
1915 1916
    virBufferAddLit(&buf, "</sources>\n");

1917 1918
    if (virBufferCheckError(&buf) < 0)
        goto cleanup;
1919 1920

    return virBufferContentAndReset(&buf);
1921

1922
 cleanup:
1923
    virBufferFreeAndReset(&buf);
1924
    return NULL;
1925
}
D
Daniel P. Berrange 已提交
1926 1927


1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
/*
 * 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
 */
1938 1939 1940 1941
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
{
    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);
1953 1954 1955
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
1956 1957 1958 1959 1960 1961
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
1962 1963 1964
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
1965 1966 1967 1968
                goto cleanup;
            }
        }

J
Ján Tomko 已提交
1969
        ret = 1;
1970 1971 1972 1973 1974 1975
    } 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);
1976 1977 1978
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
1979 1980
            goto cleanup;
        }
J
Ján Tomko 已提交
1981
        ret = 0;
1982 1983
    }

1984
 cleanup:
1985 1986 1987 1988 1989
    if (pool)
        virStoragePoolObjUnlock(pool);
    return ret;
}

1990 1991 1992
int
virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                  virStoragePoolDefPtr def)
1993
{
1994
    size_t i;
1995 1996 1997 1998 1999 2000 2001 2002 2003 2004
    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;

2005 2006 2007 2008
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2009 2010 2011 2012 2013 2014 2015 2016 2017
        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)) \
2018 2019
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
2020 2021 2022
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2023 2024 2025 2026 2027 2028 2029 2030 2031
            if (pool->def->source.adapter.type ==
                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 ==
                       VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST){
2032 2033
                if (STREQ(pool->def->source.adapter.data.scsi_host.name,
                          def->source.adapter.data.scsi_host.name))
2034 2035
                    matchpool = pool;
            }
2036 2037 2038 2039
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2040 2041 2042 2043 2044 2045 2046 2047
                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;
2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
                    }
                }
                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);
2062 2063 2064

        if (matchpool)
            break;
2065 2066 2067
    }

    if (matchpool) {
2068 2069 2070
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2071 2072 2073 2074
        ret = -1;
    }
    return ret;
}
2075

2076 2077
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2078
{
2079
    virMutexLock(&obj->lock);
2080 2081
}

2082 2083
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2084
{
2085
    virMutexUnlock(&obj->lock);
2086
}
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137

#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) &&
2138 2139 2140
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
               (poolobj->def->type == VIR_STORAGE_POOL_GLUSTER))))
2141 2142 2143 2144 2145 2146 2147 2148
            return false;
    }

    return true;
}
#undef MATCH

int
2149 2150 2151 2152 2153
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2154 2155 2156 2157 2158
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2159
    size_t i;
2160

2161 2162
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2163 2164 2165 2166

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2167 2168
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2169 2170 2171
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2172 2173
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
                    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;

2193
 cleanup:
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
    if (tmp_pools) {
        for (i = 0; i < npools; i++) {
            if (tmp_pools[i])
                virStoragePoolFree(tmp_pools[i]);
        }
    }

    VIR_FREE(tmp_pools);
    return ret;
}