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

#include <config.h>

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

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

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

48 49
#define VIR_FROM_THIS VIR_FROM_STORAGE

50 51
#define DEFAULT_POOL_PERM_MODE 0755
#define DEFAULT_VOL_PERM_MODE  0600
52

53 54
VIR_ENUM_IMPL(virStorageVol,
              VIR_STORAGE_VOL_LAST,
55
              "file", "block", "dir", "network", "netdir")
56

57 58 59 60
VIR_ENUM_IMPL(virStoragePool,
              VIR_STORAGE_POOL_LAST,
              "dir", "fs", "netfs",
              "logical", "disk", "iscsi",
61
              "scsi", "mpath", "rbd", "sheepdog", "gluster")
62 63 64 65 66

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
71
              "auto", "nfs", "glusterfs", "cifs")
72 73 74 75

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

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
80
              "unknown", "lvm2")
81 82 83 84 85 86 87


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

90 91
VIR_ENUM_IMPL(virStoragePartedFsType,
              VIR_STORAGE_PARTED_FS_TYPE_LAST,
92
              "ext2", "ext2", "fat16",
93 94 95
              "fat32", "linux-swap",
              "ext2", "ext2",
              "extended")
96

97 98 99 100
VIR_ENUM_IMPL(virStoragePoolSourceAdapterType,
              VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_LAST,
              "default", "scsi_host", "fc_host")

101 102 103 104
VIR_ENUM_IMPL(virStoragePoolAuthType,
              VIR_STORAGE_POOL_AUTH_LAST,
              "none", "chap", "ceph")

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 261 262
    {.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,
     }
    },
263 264 265 266
    {.poolType = VIR_STORAGE_POOL_MPATH,
     .volOptions = {
         .formatToString = virStoragePoolFormatDiskTypeToString,
     }
267
    },
268 269 270 271 272 273 274 275 276 277 278 279
    {.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,
     },
280 281 282 283 284
    }
};


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

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

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

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


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

    if (!def)
        return;

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

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

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

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

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 378
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
379

380
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
381 382
        VIR_FREE(source->auth.chap.username);
        VIR_FREE(source->auth.chap.secret.usage);
383
    }
384 385 386 387 388

    if (source->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        VIR_FREE(source->auth.cephx.username);
        VIR_FREE(source->auth.cephx.secret.usage);
    }
389 390
}

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

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

    VIR_FREE(def->name);

406
    virStoragePoolSourceClear(&def->source);
407

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


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

420 421
    virStoragePoolObjClearVols(obj);

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

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

    virMutexDestroy(&obj->lock);

430
    VIR_FREE(obj);
431 432
}

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

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

449 450
    virStoragePoolObjUnlock(pool);

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

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

464
static int
465 466
virStoragePoolDefParseAuthSecret(xmlXPathContextPtr ctxt,
                                 virStoragePoolAuthSecretPtr secret)
467
{
468
    char *uuid = NULL;
469 470
    int ret = -1;

471
    uuid = virXPathString("string(./auth/secret/@uuid)", ctxt);
472 473
    secret->usage = virXPathString("string(./auth/secret/@usage)", ctxt);
    if (uuid == NULL && secret->usage == NULL) {
474 475
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth secret uuid or usage attribute"));
476 477 478
        return -1;
    }

479
    if (uuid != NULL) {
480
        if (secret->usage != NULL) {
481 482
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("either auth secret uuid or usage expected"));
483
            goto cleanup;
484
        }
485
        if (virUUIDParse(uuid, secret->uuid) < 0) {
486 487
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid auth secret uuid"));
488
            goto cleanup;
489
        }
490
        secret->uuidUsable = true;
491
    } else {
492
        secret->uuidUsable = false;
493 494
    }

495
    ret = 0;
496
 cleanup:
497 498
    VIR_FREE(uuid);
    return ret;
499 500
}

501 502 503 504 505 506
static int
virStoragePoolDefParseAuth(xmlXPathContextPtr ctxt,
                           virStoragePoolSourcePtr source)
{
    int ret = -1;
    char *authType = NULL;
507
    char *username = NULL;
508 509 510 511 512 513 514 515 516 517

    authType = virXPathString("string(./auth/@type)", ctxt);
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
        ret = 0;
        goto cleanup;
    }

    if ((source->authType =
         virStoragePoolAuthTypeTypeFromString(authType)) < 0) {
518
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
519 520 521 522 523
                       _("unknown auth type '%s'"),
                       authType);
        goto cleanup;
    }

524 525 526 527 528 529 530
    username = virXPathString("string(./auth/@username)", ctxt);
    if (username == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth username attribute"));
        goto cleanup;
    }

531
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
532 533
        source->auth.chap.username = username;
        username = NULL;
534 535
        if (virStoragePoolDefParseAuthSecret(ctxt,
                                             &source->auth.chap.secret) < 0)
536 537
            goto cleanup;
    }
538 539 540
    else if (source->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        source->auth.cephx.username = username;
        username = NULL;
541 542
        if (virStoragePoolDefParseAuthSecret(ctxt,
                                             &source->auth.cephx.secret) < 0)
543 544 545 546 547
            goto cleanup;
    }

    ret = 0;

548
 cleanup:
549
    VIR_FREE(authType);
550
    VIR_FREE(username);
551 552 553
    return ret;
}

554
static int
555
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
556 557
                             virStoragePoolSourcePtr source,
                             int pool_type,
558 559
                             xmlNodePtr node)
{
560 561
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
562 563
    int nsource;
    size_t i;
564
    virStoragePoolOptionsPtr options;
565
    char *name = NULL;
566
    char *port = NULL;
567
    char *adapter_type = NULL;
568
    int n;
569 570 571 572 573 574 575 576

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

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

577
    source->name = virXPathString("string(./name)", ctxt);
578
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
579
        virReportError(VIR_ERR_XML_ERROR, "%s",
580
                       _("element 'name' is mandatory for RBD pool"));
581 582
        goto cleanup;
    }
583 584

    if (options->formatFromString) {
585
        char *format = virXPathString("string(./format/@type)", ctxt);
586 587 588 589 590 591
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
592
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
593
                           _("unknown pool format type %s"), format);
594 595 596 597 598 599
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

600 601
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
602

603 604
    if (n) {
        if (VIR_ALLOC_N(source->hosts, n) < 0)
605
            goto cleanup;
606
        source->nhost = n;
607

608
        for (i = 0; i < source->nhost; i++) {
609 610
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
611 612
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool host name"));
613 614 615 616 617 618 619
                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) {
620 621 622
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
623 624 625 626 627
                    goto cleanup;
                }
            }
        }
    }
628

629
    VIR_FREE(nodeset);
630
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
631

632
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
633 634 635
    if (nsource < 0)
        goto cleanup;

636 637 638 639 640 641 642
    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"));
643 644 645
            goto cleanup;
        }

646 647 648
        if (VIR_APPEND_ELEMENT(source->devices, source->ndevice, dev) < 0) {
            virStoragePoolSourceDeviceClear(&dev);
            goto cleanup;
649 650 651
        }
    }

652
    source->dir = virXPathString("string(./dir/@path)", ctxt);
653 654 655 656
    /* In gluster, a missing dir defaults to "/" */
    if (!source->dir && pool_type == VIR_STORAGE_POOL_GLUSTER &&
        VIR_STRDUP(source->dir, "/") < 0)
        goto cleanup;
657 658 659 660

    if ((adapter_type = virXPathString("string(./adapter/@type)", ctxt))) {
        if ((source->adapter.type =
             virStoragePoolSourceAdapterTypeTypeFromString(adapter_type)) <= 0) {
661
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
                           _("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) {
            source->adapter.data.name =
                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.
         */
        if ((source->adapter.data.name =
             virXPathString("string(./adapter/@name)", ctxt)))
            source->adapter.type =
                VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST;
    }
707

708 709
    if (virStoragePoolDefParseAuth(ctxt, source) < 0)
        goto cleanup;
710

711 712 713
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

714
    ret = 0;
715
 cleanup:
716 717
    ctxt->node = relnode;

718
    VIR_FREE(port);
719
    VIR_FREE(nodeset);
720
    VIR_FREE(adapter_type);
721 722
    return ret;
}
723

724
virStoragePoolSourcePtr
725
virStoragePoolDefParseSourceString(const char *srcSpec,
726 727 728 729 730 731 732
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

733 734 735
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
736 737
        goto cleanup;

738
    if (VIR_ALLOC(def) < 0)
739 740
        goto cleanup;

741
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
742 743
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
744 745 746
        goto cleanup;
    }

747
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
748 749 750 751 752
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
753
 cleanup:
754
    virStoragePoolSourceFree(def);
755 756 757 758 759
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
760

761
static int
762
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
763 764
                        virStoragePermsPtr perms,
                        const char *permxpath,
765 766
                        int defaultmode)
{
767
    char *mode;
768
    long val;
769 770 771
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
772

773
    node = virXPathNode(permxpath, ctxt);
774 775 776
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
P
Philipp Hahn 已提交
777 778
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
779 780 781 782 783 784 785
        perms->label = NULL;
        return 0;
    }

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

786
    mode = virXPathString("string(./mode)", ctxt);
787
    if (!mode) {
788
        perms->mode = defaultmode;
789
    } else {
790 791 792
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
793
            VIR_FREE(mode);
794 795
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
796
            goto error;
797
        }
798
        perms->mode = tmp;
799
        VIR_FREE(mode);
800 801
    }

802
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
803
        perms->uid = (uid_t) -1;
804
    } else {
805 806 807
        if (virXPathLong("number(./owner)", ctxt, &val) < 0 ||
            ((uid_t)val != val &&
             val != -1)) {
808 809
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed owner element"));
810
            goto error;
811
        }
812 813

        perms->uid = val;
814 815
    }

816
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
817
        perms->gid = (gid_t) -1;
818
    } else {
819 820 821
        if (virXPathLong("number(./group)", ctxt, &val) < 0 ||
            ((gid_t) val != val &&
             val != -1)) {
822 823
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed group element"));
824
            goto error;
825
        }
826
        perms->gid = val;
827 828 829
    }

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

832
    ret = 0;
833
 error:
834 835
    ctxt->node = relnode;
    return ret;
836 837 838
}

static virStoragePoolDefPtr
839 840
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
841
    virStoragePoolOptionsPtr options;
842
    virStoragePoolDefPtr ret;
843
    xmlNodePtr source_node;
844
    char *type = NULL;
845
    char *uuid = NULL;
846
    char *target_path = NULL;
847

848
    if (VIR_ALLOC(ret) < 0)
849 850
        return NULL;

851
    type = virXPathString("string(./@type)", ctxt);
852 853 854 855 856 857
    if (type == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("storage pool missing type attribute"));
        goto error;
    }

858
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
859
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
860
                       _("unknown storage pool type %s"), type);
861
        goto error;
862 863 864
    }

    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
865
        goto error;
866 867
    }

868
    source_node = virXPathNode("./source", ctxt);
869
    if (source_node) {
870
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
871
                                         source_node) < 0)
872
            goto error;
873 874
    }

875
    ret->name = virXPathString("string(./name)", ctxt);
876
    if (ret->name == NULL &&
877
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
878
        ret->name = ret->source.name;
879
    if (ret->name == NULL) {
880 881
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
882
        goto error;
883 884
    }

885
    uuid = virXPathString("string(./uuid)", ctxt);
886 887
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
888 889
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
890
            goto error;
891 892 893
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
894 895
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
896
            goto error;
897 898 899
        }
    }

900
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
901
        if (!ret->source.nhost) {
902
            virReportError(VIR_ERR_XML_ERROR, "%s",
903
                           _("missing storage pool source host name"));
904
            goto error;
905 906 907
        }
    }

908
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
909
        if (!ret->source.dir) {
910 911
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
912
            goto error;
913 914
        }
    }
915
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
916 917
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
918
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
919
                goto error;
920 921
        }
    }
922

923
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
924 925 926
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
927
            goto error;
928
        }
929 930 931 932 933 934 935 936

        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'"));
937
                goto error;
938 939 940 941
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
942
                goto error;
943 944 945
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            if (!ret->source.adapter.data.name) {
946 947
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source adapter name"));
948
                goto error;
949 950
            }
        }
951
    }
952

953 954 955
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
956 957
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
958
            goto error;
959 960 961
        }
    }

962 963 964
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
965 966 967 968 969 970 971 972 973 974 975
        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;
            }
976
        }
977
        ret->target.path = virFileSanitizePath(target_path);
978
        if (!ret->target.path)
979
            goto error;
980

981
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
982 983
                                    "./target/permissions",
                                    DEFAULT_POOL_PERM_MODE) < 0)
984
            goto error;
985
    }
986

987
 cleanup:
988
    VIR_FREE(uuid);
989 990 991 992
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

993
 error:
994
    virStoragePoolDefFree(ret);
995 996
    ret = NULL;
    goto cleanup;
997 998 999
}

virStoragePoolDefPtr
1000
virStoragePoolDefParseNode(xmlDocPtr xml,
1001 1002
                           xmlNodePtr root)
{
1003 1004 1005
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

1006
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
1007
        virReportError(VIR_ERR_XML_ERROR,
1008 1009 1010
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
1011 1012 1013 1014 1015
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1016
        virReportOOMError();
1017 1018 1019 1020
        goto cleanup;
    }

    ctxt->node = root;
1021
    def = virStoragePoolDefParseXML(ctxt);
1022
 cleanup:
1023 1024 1025 1026 1027
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
1028
virStoragePoolDefParse(const char *xmlStr,
1029 1030
                       const char *filename)
{
1031
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1032
    xmlDocPtr xml;
1033

1034
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
1035 1036
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1037 1038
    }

1039 1040 1041
    return ret;
}

1042
virStoragePoolDefPtr
1043
virStoragePoolDefParseString(const char *xmlStr)
1044
{
1045
    return virStoragePoolDefParse(xmlStr, NULL);
1046 1047 1048
}

virStoragePoolDefPtr
1049
virStoragePoolDefParseFile(const char *filename)
1050
{
1051
    return virStoragePoolDefParse(NULL, filename);
1052 1053
}

1054
static int
1055
virStoragePoolSourceFormat(virBufferPtr buf,
1056
                           virStoragePoolOptionsPtr options,
1057 1058
                           virStoragePoolSourcePtr src)
{
1059
    size_t i, j;
1060
    char uuid[VIR_UUID_STRING_BUFLEN];
1061

1062 1063 1064
    virBufferAddLit(buf, "<source>\n");
    virBufferAdjustIndent(buf, 2);

1065 1066
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
1067
            virBufferEscapeString(buf, "<host name='%s'",
1068
                                  src->hosts[i].name);
1069 1070 1071 1072
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
1073
    }
1074

1075
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
1076
        src->ndevice) {
1077
        for (i = 0; i < src->ndevice; i++) {
1078
            if (src->devices[i].nfreeExtent) {
1079
                virBufferEscapeString(buf, "<device path='%s'>\n",
1080
                                      src->devices[i].path);
1081
                virBufferAdjustIndent(buf, 2);
1082
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
1083
                    virBufferAsprintf(buf, "<freeExtent start='%llu' end='%llu'/>\n",
1084 1085 1086
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
1087 1088
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</device>\n");
1089
            } else {
1090
                virBufferEscapeString(buf, "<device path='%s'/>\n",
1091
                                      src->devices[i].path);
1092
            }
1093 1094
        }
    }
1095

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

1099 1100 1101
    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)
1102
            virBufferAsprintf(buf, "<adapter type='%s'",
1103 1104 1105 1106 1107
                              virStoragePoolSourceAdapterTypeTypeToString(src->adapter.type));

        if (src->adapter.type == VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_FC_HOST) {
            virBufferEscapeString(buf, " parent='%s'",
                                  src->adapter.data.fchost.parent);
E
Eric Blake 已提交
1108
            virBufferAsprintf(buf, " wwnn='%s' wwpn='%s'/>\n",
1109 1110 1111 1112
                              src->adapter.data.fchost.wwnn,
                              src->adapter.data.fchost.wwpn);
        } else if (src->adapter.type ==
                 VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
E
Eric Blake 已提交
1113
            virBufferAsprintf(buf, " name='%s'/>\n", src->adapter.data.name);
1114 1115
        }
    }
1116

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

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

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

1141 1142
    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP ||
        src->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
1143
        virBufferAsprintf(buf, "<auth type='%s' ",
1144 1145 1146 1147 1148
                          virStoragePoolAuthTypeTypeToString(src->authType));
        virBufferEscapeString(buf, "username='%s'>\n",
                              (src->authType == VIR_STORAGE_POOL_AUTH_CHAP ?
                               src->auth.chap.username :
                               src->auth.cephx.username));
1149
        virBufferAdjustIndent(buf, 2);
1150

1151
        virBufferAddLit(buf, "<secret");
1152
        if (src->auth.cephx.secret.uuidUsable) {
1153
            virUUIDFormat(src->auth.cephx.secret.uuid, uuid);
E
Eric Blake 已提交
1154
            virBufferAsprintf(buf, " uuid='%s'", uuid);
1155 1156 1157
        }

        if (src->auth.cephx.secret.usage != NULL) {
E
Eric Blake 已提交
1158
            virBufferAsprintf(buf, " usage='%s'", src->auth.cephx.secret.usage);
1159
        }
E
Eric Blake 已提交
1160
        virBufferAddLit(buf, "/>\n");
1161

1162 1163
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</auth>\n");
1164 1165
    }

1166 1167
    virBufferEscapeString(buf, "<vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "<product name='%s'/>\n", src->product);
1168

1169 1170
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</source>\n");
1171 1172 1173
    return 0;
}

1174 1175

char *
1176 1177
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
1178
    virStoragePoolOptionsPtr options;
1179
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1180 1181 1182
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1183
    options = virStoragePoolOptionsForPoolType(def->type);
1184 1185 1186
    if (options == NULL)
        return NULL;

1187
    type = virStoragePoolTypeToString(def->type);
1188
    if (!type) {
1189 1190
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1191 1192
        goto cleanup;
    }
1193
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
1194 1195
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", def->name);
1196 1197

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

1200
    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1201
                      def->capacity);
1202
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1203
                      def->allocation);
1204
    virBufferAsprintf(&buf, "<available unit='bytes'>%llu</available>\n",
1205
                      def->available);
1206

1207
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1208
        goto cleanup;
1209

1210 1211
    /* RBD, Sheepdog, and Gluster devices are not local block devs nor
     * files, so they don't have a target */
1212
    if (def->type != VIR_STORAGE_POOL_RBD &&
1213 1214
        def->type != VIR_STORAGE_POOL_SHEEPDOG &&
        def->type != VIR_STORAGE_POOL_GLUSTER) {
1215 1216
        virBufferAddLit(&buf, "<target>\n");
        virBufferAdjustIndent(&buf, 2);
1217

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

1220 1221 1222
        virBufferAddLit(&buf, "<permissions>\n");
        virBufferAdjustIndent(&buf, 2);
        virBufferAsprintf(&buf, "<mode>0%o</mode>\n",
1223
                          def->target.perms.mode);
1224
        virBufferAsprintf(&buf, "<owner>%d</owner>\n",
1225
                          (int) def->target.perms.uid);
1226
        virBufferAsprintf(&buf, "<group>%d</group>\n",
1227
                          (int) def->target.perms.gid);
1228

1229
        virBufferEscapeString(&buf, "<label>%s</label>\n",
1230
                              def->target.perms.label);
1231

1232 1233 1234 1235
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</permissions>\n");
        virBufferAdjustIndent(&buf, -2);
        virBufferAddLit(&buf, "</target>\n");
1236
    }
1237
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1238
    virBufferAddLit(&buf, "</pool>\n");
1239

1240
    if (virBufferError(&buf))
1241 1242
        goto no_memory;

1243
    return virBufferContentAndReset(&buf);
1244

1245
 no_memory:
1246
    virReportOOMError();
1247
 cleanup:
1248
    virBufferFreeAndReset(&buf);
1249 1250 1251 1252 1253
    return NULL;
}


static int
1254
virStorageSize(const char *unit,
1255
               const char *val,
1256 1257 1258
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1259 1260
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("malformed capacity element"));
1261 1262
        return -1;
    }
1263 1264 1265 1266
    /* 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;
1267 1268 1269 1270 1271

    return 0;
}

static virStorageVolDefPtr
1272
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1273 1274
                         xmlXPathContextPtr ctxt)
{
1275
    virStorageVolDefPtr ret;
1276
    virStorageVolOptionsPtr options;
1277
    char *type = NULL;
1278 1279 1280
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1281
    xmlNodePtr node;
1282
    xmlNodePtr *nodes = NULL;
1283 1284
    size_t i;
    int n;
1285

1286
    options = virStorageVolOptionsForPoolType(pool->type);
1287 1288 1289
    if (options == NULL)
        return NULL;

1290
    if (VIR_ALLOC(ret) < 0)
1291 1292
        return NULL;

1293
    ret->name = virXPathString("string(./name)", ctxt);
1294
    if (ret->name == NULL) {
1295 1296
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing volume name element"));
1297
        goto error;
1298 1299
    }

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

1303 1304 1305 1306
    /* Technically overridden by pool refresh, but useful for unit tests */
    type = virXPathString("string(./@type)", ctxt);
    if (type) {
        if ((ret->type = virStorageVolTypeFromString(type)) < 0) {
1307
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1308 1309 1310 1311 1312
                           _("unknown volume type '%s'"), type);
            goto error;
        }
    }

1313 1314
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1315
    if (capacity == NULL) {
1316 1317
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing capacity element"));
1318
        goto error;
1319
    }
1320
    if (virStorageSize(unit, capacity, &ret->target.capacity) < 0)
1321
        goto error;
1322
    VIR_FREE(unit);
1323

1324
    allocation = virXPathString("string(./allocation)", ctxt);
1325
    if (allocation) {
1326
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1327
        if (virStorageSize(unit, allocation, &ret->target.allocation) < 0)
1328
            goto error;
1329
    } else {
1330
        ret->target.allocation = ret->target.capacity;
1331 1332
    }

1333
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1334
    if (options->formatFromString) {
1335
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1336 1337 1338 1339 1340 1341
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1342
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1343
                           _("unknown volume format type %s"), format);
1344
            VIR_FREE(format);
1345
            goto error;
1346
        }
1347
        VIR_FREE(format);
1348 1349
    }

1350 1351 1352
    if (VIR_ALLOC(ret->target.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->target.perms,
1353 1354
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1355
        goto error;
1356

1357
    node = virXPathNode("./target/encryption", ctxt);
1358
    if (node != NULL) {
1359
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1360 1361
                                                               node);
        if (ret->target.encryption == NULL)
1362
            goto error;
1363 1364
    }

1365
    ret->backingStore.path = virXPathString("string(./backingStore/path)", ctxt);
1366
    if (options->formatFromString) {
1367
        char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
1368 1369 1370 1371 1372 1373
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
1374
            virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
1375
                           _("unknown volume format type %s"), format);
1376
            VIR_FREE(format);
1377
            goto error;
1378 1379 1380 1381
        }
        VIR_FREE(format);
    }

1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
    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);
    }

    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)))
1406
            goto error;
1407 1408 1409 1410 1411

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

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

1421 1422 1423
    if (VIR_ALLOC(ret->backingStore.perms) < 0)
        goto error;
    if (virStorageDefParsePerms(ctxt, ret->backingStore.perms,
1424 1425
                                "./backingStore/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1426
        goto error;
1427

1428
 cleanup:
1429
    VIR_FREE(nodes);
1430 1431 1432
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1433
    VIR_FREE(type);
1434 1435
    return ret;

1436
 error:
1437
    virStorageVolDefFree(ret);
1438 1439
    ret = NULL;
    goto cleanup;
1440 1441 1442
}

virStorageVolDefPtr
1443
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1444
                          xmlDocPtr xml,
1445 1446
                          xmlNodePtr root)
{
1447 1448 1449
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1450
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1451
        virReportError(VIR_ERR_XML_ERROR,
1452 1453 1454
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1455 1456 1457 1458 1459
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1460
        virReportOOMError();
1461 1462 1463 1464
        goto cleanup;
    }

    ctxt->node = root;
1465
    def = virStorageVolDefParseXML(pool, ctxt);
1466
 cleanup:
1467 1468 1469 1470 1471
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1472
virStorageVolDefParse(virStoragePoolDefPtr pool,
1473
                      const char *xmlStr,
1474 1475
                      const char *filename)
{
1476
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1477
    xmlDocPtr xml;
1478

1479
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1480 1481
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1482 1483 1484 1485 1486
    }

    return ret;
}

1487
virStorageVolDefPtr
1488
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1489 1490
                            const char *xmlStr)
{
1491
    return virStorageVolDefParse(pool, xmlStr, NULL);
1492 1493 1494
}

virStorageVolDefPtr
1495
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1496 1497
                          const char *filename)
{
1498
    return virStorageVolDefParse(pool, NULL, filename);
1499
}
1500

1501 1502 1503 1504 1505 1506
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
1507
    virBufferAsprintf(buf, "<%s>%llu", name,
1508 1509 1510 1511 1512 1513
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1514
static int
1515
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1516
                             virBufferPtr buf,
1517
                             virStorageSourcePtr def,
1518 1519
                             const char *type)
{
1520 1521
    virBufferAsprintf(buf, "<%s>\n", type);
    virBufferAdjustIndent(buf, 2);
1522

1523
    virBufferEscapeString(buf, "<path>%s</path>\n", def->path);
1524 1525 1526 1527

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1528 1529 1530
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1531 1532
            return -1;
        }
1533
        virBufferAsprintf(buf, "<format type='%s'/>\n", format);
1534 1535
    }

1536 1537 1538 1539
    virBufferAddLit(buf, "<permissions>\n");
    virBufferAdjustIndent(buf, 2);

    virBufferAsprintf(buf, "<mode>0%o</mode>\n",
1540
                      def->perms->mode);
1541
    virBufferAsprintf(buf, "<owner>%u</owner>\n",
1542
                      (unsigned int) def->perms->uid);
1543
    virBufferAsprintf(buf, "<group>%u</group>\n",
1544
                      (unsigned int) def->perms->gid);
1545 1546


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

1550 1551
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</permissions>\n");
1552

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

1564 1565
    if (def->encryption &&
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1566
            return -1;
1567

1568
    virBufferEscapeString(buf, "<compat>%s</compat>\n", def->compat);
1569 1570

    if (options->featureToString && def->features) {
1571
        size_t i;
1572 1573 1574
        bool b;
        bool empty = virBitmapIsAllClear(def->features);

1575 1576 1577 1578 1579 1580
        if (empty) {
            virBufferAddLit(buf, "<features/>\n");
        } else {
            virBufferAddLit(buf, "<features>\n");
            virBufferAdjustIndent(buf, 2);
        }
1581 1582 1583 1584

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

1594 1595
    virBufferAdjustIndent(buf, -2);
    virBufferAsprintf(buf, "</%s>\n", type);
1596 1597
    return 0;
}
1598 1599

char *
1600
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1601 1602
                       virStorageVolDefPtr def)
{
1603
    virStorageVolOptionsPtr options;
1604
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1605

1606
    options = virStorageVolOptionsForPoolType(pool->type);
1607 1608 1609
    if (options == NULL)
        return NULL;

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

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

1628
                virBufferEscapeString(&buf, "<device path='%s'>\n",
1629
                                      def->source.extents[i].path);
1630 1631
            }

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

1643 1644 1645 1646
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</source>\n");

    virBufferAsprintf(&buf, "<capacity unit='bytes'>%llu</capacity>\n",
1647
                      def->target.capacity);
1648
    virBufferAsprintf(&buf, "<allocation unit='bytes'>%llu</allocation>\n",
1649
                      def->target.allocation);
1650

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

1655
    if (def->backingStore.path &&
1656
        virStorageVolTargetDefFormat(options, &buf,
1657 1658
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1659

1660
    virBufferAdjustIndent(&buf, -2);
E
Eric Blake 已提交
1661
    virBufferAddLit(&buf, "</volume>\n");
1662

1663
    if (virBufferError(&buf))
1664 1665
        goto no_memory;

1666
    return virBufferContentAndReset(&buf);
1667

1668
 no_memory:
1669
    virReportOOMError();
1670
 cleanup:
1671
    virBufferFreeAndReset(&buf);
1672 1673 1674 1675 1676
    return NULL;
}


virStoragePoolObjPtr
1677
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1678 1679
                            const unsigned char *uuid)
{
1680
    size_t i;
1681

1682
    for (i = 0; i < pools->count; i++) {
1683
        virStoragePoolObjLock(pools->objs[i]);
1684 1685
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1686 1687
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1688 1689 1690 1691 1692

    return NULL;
}

virStoragePoolObjPtr
1693
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1694 1695
                            const char *name)
{
1696
    size_t i;
1697

1698
    for (i = 0; i < pools->count; i++) {
1699
        virStoragePoolObjLock(pools->objs[i]);
1700 1701
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1702 1703
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1704 1705 1706 1707

    return NULL;
}

1708 1709
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1710 1711
                                         virStoragePoolDefPtr def)
{
1712
    size_t i, j;
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723

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

1724 1725 1726
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1727
    size_t i;
1728
    for (i = 0; i < pool->volumes.count; i++)
1729 1730 1731 1732
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1733 1734 1735 1736
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1737 1738
                          const char *key)
{
1739
    size_t i;
1740

1741
    for (i = 0; i < pool->volumes.count; i++)
1742 1743
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1744 1745 1746 1747 1748 1749

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1750 1751
                           const char *path)
{
1752
    size_t i;
1753

1754
    for (i = 0; i < pool->volumes.count; i++)
1755 1756
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1757 1758 1759 1760 1761 1762

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1763 1764
                           const char *name)
{
1765
    size_t i;
1766

1767
    for (i = 0; i < pool->volumes.count; i++)
1768 1769
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1770 1771 1772 1773 1774

    return NULL;
}

virStoragePoolObjPtr
1775
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1776 1777
                           virStoragePoolDefPtr def)
{
1778 1779
    virStoragePoolObjPtr pool;

1780
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1781 1782 1783 1784
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1785
            virStoragePoolDefFree(pool->newDef);
1786 1787 1788 1789 1790
            pool->newDef = def;
        }
        return pool;
    }

1791
    if (VIR_ALLOC(pool) < 0)
1792 1793
        return NULL;

1794
    if (virMutexInit(&pool->lock) < 0) {
1795 1796
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1797 1798 1799
        VIR_FREE(pool);
        return NULL;
    }
1800
    virStoragePoolObjLock(pool);
1801 1802
    pool->active = 0;

1803
    if (VIR_APPEND_ELEMENT_COPY(pools->objs, pools->count, pool) < 0) {
1804
        virStoragePoolObjUnlock(pool);
1805 1806 1807
        virStoragePoolObjFree(pool);
        return NULL;
    }
1808
    pool->def = def;
1809 1810 1811 1812 1813

    return pool;
}

static virStoragePoolObjPtr
1814
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1815 1816
                      const char *file,
                      const char *path,
1817 1818
                      const char *autostartLink)
{
1819 1820 1821
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1822
    if (!(def = virStoragePoolDefParseFile(path))) {
1823 1824 1825 1826
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1827
        virReportError(VIR_ERR_XML_ERROR,
1828 1829
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1830
                       path, def->name);
1831 1832 1833 1834
        virStoragePoolDefFree(def);
        return NULL;
    }

1835
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1836 1837 1838 1839
        virStoragePoolDefFree(def);
        return NULL;
    }

1840
    VIR_FREE(pool->configFile);  /* for driver reload */
1841
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1842 1843 1844
        virStoragePoolDefFree(def);
        return NULL;
    }
1845
    VIR_FREE(pool->autostartLink); /* for driver reload */
1846
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1859
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1860
                             const char *configDir,
1861 1862
                             const char *autostartDir)
{
1863 1864
    DIR *dir;
    struct dirent *entry;
E
Eric Blake 已提交
1865
    int ret;
1866

1867
    if (!(dir = opendir(configDir))) {
1868 1869
        if (errno == ENOENT)
            return 0;
1870
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1871
                             configDir);
1872 1873 1874
        return -1;
    }

E
Eric Blake 已提交
1875
    while ((ret = virDirRead(dir, &entry, configDir)) > 0) {
1876 1877
        char *path;
        char *autostartLink;
1878
        virStoragePoolObjPtr pool;
1879 1880 1881 1882 1883 1884 1885

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

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

1886
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1887 1888
            continue;

1889 1890 1891
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1892 1893 1894
            continue;
        }

1895
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1896
                                     autostartLink);
1897 1898
        if (pool)
            virStoragePoolObjUnlock(pool);
1899 1900 1901

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1902 1903 1904
    }

    closedir(dir);
E
Eric Blake 已提交
1905
    return ret;
1906 1907 1908
}

int
1909
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1910
                         virStoragePoolObjPtr pool,
1911 1912
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1913
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1914
    char *xml;
1915
    int ret = -1;
1916 1917

    if (!pool->configFile) {
1918 1919
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1920 1921
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1922 1923 1924
            return -1;
        }

1925 1926
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1927 1928 1929
            return -1;
        }

1930 1931
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1932
            VIR_FREE(pool->configFile);
1933 1934 1935 1936
            return -1;
        }
    }

1937
    if (!(xml = virStoragePoolDefFormat(def))) {
1938 1939
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
1940 1941 1942
        return -1;
    }

J
Ján Tomko 已提交
1943 1944 1945 1946
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1947
    VIR_FREE(xml);
1948 1949 1950 1951 1952

    return ret;
}

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

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

    return 0;
}
1970

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

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

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

    return source;
}

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

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

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

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

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

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

    if (virBufferError(&buf))
        goto no_memory;
2016 2017

    return virBufferContentAndReset(&buf);
2018

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


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

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

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

2083
 cleanup:
2084 2085 2086 2087 2088
    if (pool)
        virStoragePoolObjUnlock(pool);
    return ret;
}

2089 2090 2091
int
virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                  virStoragePoolDefPtr def)
2092
{
2093
    size_t i;
2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    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;

2104 2105 2106 2107
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2108 2109 2110 2111 2112 2113 2114 2115 2116
        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)) \
2117 2118
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
2119 2120 2121
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
            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){
                if (STREQ(pool->def->source.adapter.data.name,
                          def->source.adapter.data.name))
                    matchpool = pool;
            }
2135 2136 2137 2138
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2139 2140 2141 2142 2143 2144 2145 2146
                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;
2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160
                    }
                }
                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);
2161 2162 2163

        if (matchpool)
            break;
2164 2165 2166
    }

    if (matchpool) {
2167 2168 2169
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2170 2171 2172 2173
        ret = -1;
    }
    return ret;
}
2174

2175 2176
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2177
{
2178
    virMutexLock(&obj->lock);
2179 2180
}

2181 2182
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2183
{
2184
    virMutexUnlock(&obj->lock);
2185
}
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236

#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) &&
2237 2238 2239
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG)) ||
              (MATCH(VIR_CONNECT_LIST_STORAGE_POOLS_GLUSTER) &&
               (poolobj->def->type == VIR_STORAGE_POOL_GLUSTER))))
2240 2241 2242 2243 2244 2245 2246 2247
            return false;
    }

    return true;
}
#undef MATCH

int
2248 2249 2250 2251 2252
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2253 2254 2255 2256 2257
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2258
    size_t i;
2259

2260 2261
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2262 2263 2264 2265

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2266 2267
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2268 2269 2270
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2271 2272
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
                    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;

2292
 cleanup:
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
    if (tmp_pools) {
        for (i = 0; i < npools; i++) {
            if (tmp_pools[i])
                virStoragePoolFree(tmp_pools[i]);
        }
    }

    VIR_FREE(tmp_pools);
    return ret;
}