storage_conf.c 68.6 KB
Newer Older
1 2 3
/*
 * storage_conf.c: config handling for storage driver
 *
4
 * Copyright (C) 2006-2013 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
#define DEFAULT_POOL_PERM_MODE 0755
#define DEFAULT_VOL_PERM_MODE  0600
53

54 55 56 57
VIR_ENUM_IMPL(virStoragePool,
              VIR_STORAGE_POOL_LAST,
              "dir", "fs", "netfs",
              "logical", "disk", "iscsi",
58
              "scsi", "mpath", "rbd", "sheepdog")
59 60 61 62 63

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
68
              "auto", "nfs", "glusterfs", "cifs")
69 70 71 72

VIR_ENUM_IMPL(virStoragePoolFormatDisk,
              VIR_STORAGE_POOL_DISK_LAST,
              "unknown", "dos", "dvh", "gpt",
73
              "mac", "bsd", "pc98", "sun", "lvm2")
74 75 76

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
77
              "unknown", "lvm2")
78 79 80 81 82 83 84


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

87 88
VIR_ENUM_IMPL(virStoragePartedFsType,
              VIR_STORAGE_PARTED_FS_TYPE_LAST,
89
              "ext2", "ext2", "fat16",
90 91 92
              "fat32", "linux-swap",
              "ext2", "ext2",
              "extended")
93

94 95 96 97
VIR_ENUM_IMPL(virStoragePoolSourceAdapterType,
              VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_LAST,
              "default", "scsi_host", "fc_host")

98 99 100 101
VIR_ENUM_IMPL(virStoragePoolAuthType,
              VIR_STORAGE_POOL_AUTH_LAST,
              "none", "chap", "ceph")

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

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

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

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

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

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

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

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


static virStoragePoolTypeInfoPtr
269 270
virStoragePoolTypeInfoLookup(int type)
{
271
    size_t i;
272
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo); i++)
273 274 275
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

276 277
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
278 279 280 281
    return NULL;
}

static virStoragePoolOptionsPtr
282 283
virStoragePoolOptionsForPoolType(int type)
{
284 285 286 287 288 289 290
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
291 292
virStorageVolOptionsForPoolType(int type)
{
293 294 295 296 297 298 299
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


300
void
301 302
virStorageVolDefFree(virStorageVolDefPtr def)
{
303
    size_t i;
304 305 306 307

    if (!def)
        return;

308 309
    VIR_FREE(def->name);
    VIR_FREE(def->key);
310

311
    for (i = 0; i < def->source.nextent; i++) {
312
        VIR_FREE(def->source.extents[i].path);
313
    }
314
    VIR_FREE(def->source.extents);
315

316 317
    VIR_FREE(def->target.compat);
    virBitmapFree(def->target.features);
318 319
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
320
    VIR_FREE(def->target.timestamps);
321
    virStorageEncryptionFree(def->target.encryption);
322 323
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
324
    VIR_FREE(def->backingStore.timestamps);
325
    virStorageEncryptionFree(def->backingStore.encryption);
326
    VIR_FREE(def);
327 328
}

329 330 331 332 333 334 335 336 337 338 339 340 341
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);
    }
}

342
void
343 344
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
345
    size_t i;
346

347
    if (!source)
348 349
        return;

350
    for (i = 0; i < source->nhost; i++) {
351 352 353 354
        VIR_FREE(source->hosts[i].name);
    }
    VIR_FREE(source->hosts);

355
    for (i = 0; i < source->ndevice; i++) {
356 357
        VIR_FREE(source->devices[i].freeExtents);
        VIR_FREE(source->devices[i].path);
358
    }
359 360 361
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
362
    virStoragePoolSourceAdapterClear(source->adapter);
D
David Allan 已提交
363
    VIR_FREE(source->initiator.iqn);
364 365
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
366

367
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
368 369
        VIR_FREE(source->auth.chap.username);
        VIR_FREE(source->auth.chap.secret.usage);
370
    }
371 372 373 374 375

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

378 379 380 381 382 383 384
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

385
void
386 387
virStoragePoolDefFree(virStoragePoolDefPtr def)
{
388 389 390 391 392
    if (!def)
        return;

    VIR_FREE(def->name);

393
    virStoragePoolSourceClear(&def->source);
394

395 396 397
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
398 399 400 401
}


void
402 403
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
404 405 406
    if (!obj)
        return;

407 408
    virStoragePoolObjClearVols(obj);

409 410
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
411

412 413
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
414 415 416

    virMutexDestroy(&obj->lock);

417
    VIR_FREE(obj);
418 419
}

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

430
void
431
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
432 433
                        virStoragePoolObjPtr pool)
{
434
    size_t i;
435

436 437
    virStoragePoolObjUnlock(pool);

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

444 445 446
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
447

448 449 450 451
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
452

453 454
            break;
        }
455
        virStoragePoolObjUnlock(pools->objs[i]);
456
    }
457 458
}

459
static int
460 461
virStoragePoolDefParseAuthSecret(xmlXPathContextPtr ctxt,
                                 virStoragePoolAuthSecretPtr secret)
462
{
463
    char *uuid = NULL;
464 465
    int ret = -1;

466
    uuid = virXPathString("string(./auth/secret/@uuid)", ctxt);
467 468
    secret->usage = virXPathString("string(./auth/secret/@usage)", ctxt);
    if (uuid == NULL && secret->usage == NULL) {
469 470
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth secret uuid or usage attribute"));
471 472 473
        return -1;
    }

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

490 491 492 493
    ret = 0;
cleanup:
    VIR_FREE(uuid);
    return ret;
494 495
}

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

    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) {
        virReportError(VIR_ERR_XML_ERROR,
                       _("unknown auth type '%s'"),
                       authType);
        goto cleanup;
    }

519 520 521 522 523 524 525
    username = virXPathString("string(./auth/@username)", ctxt);
    if (username == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth username attribute"));
        goto cleanup;
    }

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

    ret = 0;

cleanup:
    VIR_FREE(authType);
545
    VIR_FREE(username);
546 547 548
    return ret;
}

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

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

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

572
    source->name = virXPathString("string(./name)", ctxt);
573
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
574
        virReportError(VIR_ERR_XML_ERROR, "%s",
575
                       _("element 'name' is mandatory for RBD pool"));
576 577
        goto cleanup;
    }
578 579

    if (options->formatFromString) {
580
        char *format = virXPathString("string(./format/@type)", ctxt);
581 582 583 584 585 586
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
587 588
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown pool format type %s"), format);
589 590 591 592 593 594
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

595 596
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
597

598 599
    if (n) {
        if (VIR_ALLOC_N(source->hosts, n) < 0)
600
            goto cleanup;
601
        source->nhost = n;
602

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

624
    VIR_FREE(nodeset);
625
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
626

627
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
628 629 630
    if (nsource < 0)
        goto cleanup;

631 632 633 634 635 636
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
            goto cleanup;
        }

637
        for (i = 0; i < nsource; i++) {
638
            char *path = virXMLPropString(nodeset[i], "path");
639 640
            if (path == NULL) {
                VIR_FREE(nodeset);
641 642
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source device path"));
643 644
                goto cleanup;
            }
645
            source->devices[i].path = path;
646 647 648 649
        }
        source->ndevice = nsource;
    }

650
    source->dir = virXPathString("string(./dir/@path)", ctxt);
651 652 653 654 655 656 657 658 659 660 661 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

    if ((adapter_type = virXPathString("string(./adapter/@type)", ctxt))) {
        if ((source->adapter.type =
             virStoragePoolSourceAdapterTypeTypeFromString(adapter_type)) <= 0) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("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;
    }
701

702 703
    if (virStoragePoolDefParseAuth(ctxt, source) < 0)
        goto cleanup;
704

705 706 707
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

708 709 710 711
    ret = 0;
cleanup:
    ctxt->node = relnode;

712
    VIR_FREE(port);
713
    VIR_FREE(nodeset);
714
    VIR_FREE(adapter_type);
715 716
    return ret;
}
717

718
virStoragePoolSourcePtr
719
virStoragePoolDefParseSourceString(const char *srcSpec,
720 721 722 723 724 725 726
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

727 728 729
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
730 731
        goto cleanup;

732
    if (VIR_ALLOC(def) < 0)
733 734
        goto cleanup;

735
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
736 737
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
738 739 740
        goto cleanup;
    }

741
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
742 743 744 745 746 747
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
748
    virStoragePoolSourceFree(def);
749 750 751 752 753
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
754

755
static int
756
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
757 758
                        virStoragePermsPtr perms,
                        const char *permxpath,
759 760
                        int defaultmode)
{
761
    char *mode;
762
    long val;
763 764 765
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
766

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

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

780
    mode = virXPathString("string(./mode)", ctxt);
781
    if (!mode) {
782
        perms->mode = defaultmode;
783
    } else {
784 785 786
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
787
            VIR_FREE(mode);
788 789
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
790
            goto error;
791
        }
792
        perms->mode = tmp;
793
        VIR_FREE(mode);
794 795
    }

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

        perms->uid = val;
808 809
    }

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

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

826 827 828 829
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
830 831 832
}

static virStoragePoolDefPtr
833 834
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
835
    virStoragePoolOptionsPtr options;
836
    virStoragePoolDefPtr ret;
837
    xmlNodePtr source_node;
838
    char *type = NULL;
839
    char *uuid = NULL;
840
    char *target_path = NULL;
841

842
    if (VIR_ALLOC(ret) < 0)
843 844
        return NULL;

845
    type = virXPathString("string(./@type)", ctxt);
846 847 848 849 850 851
    if (type == NULL) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("storage pool missing type attribute"));
        goto error;
    }

852
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
O
Osier Yang 已提交
853
        virReportError(VIR_ERR_XML_ERROR,
854
                       _("unknown storage pool type %s"), type);
855
        goto error;
856 857 858
    }

    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
859
        goto error;
860 861
    }

862
    source_node = virXPathNode("./source", ctxt);
863
    if (source_node) {
864
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
865
                                         source_node) < 0)
866
            goto error;
867 868
    }

869
    ret->name = virXPathString("string(./name)", ctxt);
870
    if (ret->name == NULL &&
871
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
872
        ret->name = ret->source.name;
873
    if (ret->name == NULL) {
874 875
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
876
        goto error;
877 878
    }

879
    uuid = virXPathString("string(./uuid)", ctxt);
880 881
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
882 883
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
884
            goto error;
885 886 887
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
888 889
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
890
            goto error;
891 892 893
        }
    }

894
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
895
        if (!ret->source.nhost) {
896
            virReportError(VIR_ERR_XML_ERROR, "%s",
897
                           _("missing storage pool source host name"));
898
            goto error;
899 900 901
        }
    }

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

917
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
918 919 920
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
921
            goto error;
922
        }
923 924 925 926 927 928 929 930

        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'"));
931
                goto error;
932 933 934 935
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
936
                goto error;
937 938 939
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            if (!ret->source.adapter.data.name) {
940 941
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source adapter name"));
942
                goto error;
943 944
            }
        }
945
    }
946

947 948 949
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
950 951
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
952
            goto error;
953 954 955
        }
    }

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

975
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
976 977
                                    "./target/permissions",
                                    DEFAULT_POOL_PERM_MODE) < 0)
978
            goto error;
979
    }
980

981
cleanup:
982
    VIR_FREE(uuid);
983 984 985 986 987
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

error:
988
    virStoragePoolDefFree(ret);
989 990
    ret = NULL;
    goto cleanup;
991 992 993
}

virStoragePoolDefPtr
994
virStoragePoolDefParseNode(xmlDocPtr xml,
995 996
                           xmlNodePtr root)
{
997 998 999
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

1000
    if (!xmlStrEqual(root->name, BAD_CAST "pool")) {
1001
        virReportError(VIR_ERR_XML_ERROR,
1002 1003 1004
                       _("unexpected root element <%s>, "
                         "expecting <pool>"),
                       root->name);
1005 1006 1007 1008 1009
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1010
        virReportOOMError();
1011 1012 1013 1014
        goto cleanup;
    }

    ctxt->node = root;
1015
    def = virStoragePoolDefParseXML(ctxt);
1016 1017 1018 1019 1020 1021
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
1022
virStoragePoolDefParse(const char *xmlStr,
1023 1024
                       const char *filename)
{
1025
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1026
    xmlDocPtr xml;
1027

1028
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
1029 1030
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1031 1032
    }

1033 1034 1035
    return ret;
}

1036
virStoragePoolDefPtr
1037
virStoragePoolDefParseString(const char *xmlStr)
1038
{
1039
    return virStoragePoolDefParse(xmlStr, NULL);
1040 1041 1042
}

virStoragePoolDefPtr
1043
virStoragePoolDefParseFile(const char *filename)
1044
{
1045
    return virStoragePoolDefParse(NULL, filename);
1046 1047
}

1048
static int
1049
virStoragePoolSourceFormat(virBufferPtr buf,
1050
                           virStoragePoolOptionsPtr options,
1051 1052
                           virStoragePoolSourcePtr src)
{
1053
    size_t i, j;
1054
    char uuid[VIR_UUID_STRING_BUFLEN];
1055

E
Eric Blake 已提交
1056
    virBufferAddLit(buf, "  <source>\n");
1057 1058
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
1059 1060
            virBufferEscapeString(buf, "    <host name='%s'",
                                  src->hosts[i].name);
1061 1062 1063 1064
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
1065
    }
1066

1067
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
1068
        src->ndevice) {
1069
        for (i = 0; i < src->ndevice; i++) {
1070
            if (src->devices[i].nfreeExtent) {
1071 1072
                virBufferEscapeString(buf, "    <device path='%s'>\n",
                                      src->devices[i].path);
1073
                for (j = 0; j < src->devices[i].nfreeExtent; j++) {
1074
                    virBufferAsprintf(buf, "    <freeExtent start='%llu' end='%llu'/>\n",
1075 1076 1077
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
E
Eric Blake 已提交
1078
                virBufferAddLit(buf, "    </device>\n");
1079
            } else {
1080 1081
                virBufferEscapeString(buf, "    <device path='%s'/>\n",
                                      src->devices[i].path);
1082
            }
1083 1084
        }
    }
1085

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

1089 1090 1091 1092 1093 1094 1095 1096 1097
    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)
            virBufferAsprintf(buf, "    <adapter type='%s'",
                              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 已提交
1098
            virBufferAsprintf(buf, " wwnn='%s' wwpn='%s'/>\n",
1099 1100 1101 1102
                              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 已提交
1103
            virBufferAsprintf(buf, " name='%s'/>\n", src->adapter.data.name);
1104 1105
        }
    }
1106

1107 1108
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
        virBufferEscapeString(buf, "    <name>%s</name>\n", src->name);
1109

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

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

1129 1130
    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP ||
        src->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
1131 1132 1133 1134 1135 1136
        virBufferAsprintf(buf, "    <auth type='%s' ",
                          virStoragePoolAuthTypeTypeToString(src->authType));
        virBufferEscapeString(buf, "username='%s'>\n",
                              (src->authType == VIR_STORAGE_POOL_AUTH_CHAP ?
                               src->auth.chap.username :
                               src->auth.cephx.username));
1137

E
Eric Blake 已提交
1138
        virBufferAddLit(buf, "      <secret");
1139
        if (src->auth.cephx.secret.uuidUsable) {
1140
            virUUIDFormat(src->auth.cephx.secret.uuid, uuid);
E
Eric Blake 已提交
1141
            virBufferAsprintf(buf, " uuid='%s'", uuid);
1142 1143 1144
        }

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

E
Eric Blake 已提交
1149
        virBufferAddLit(buf, "    </auth>\n");
1150 1151
    }

1152 1153
    virBufferEscapeString(buf, "    <vendor name='%s'/>\n", src->vendor);
    virBufferEscapeString(buf, "    <product name='%s'/>\n", src->product);
1154

E
Eric Blake 已提交
1155
    virBufferAddLit(buf, "  </source>\n");
1156 1157 1158 1159

    return 0;
}

1160 1161

char *
1162 1163
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
1164
    virStoragePoolOptionsPtr options;
1165
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1166 1167 1168
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1169
    options = virStoragePoolOptionsForPoolType(def->type);
1170 1171 1172
    if (options == NULL)
        return NULL;

1173
    type = virStoragePoolTypeToString(def->type);
1174
    if (!type) {
1175 1176
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1177 1178
        goto cleanup;
    }
1179
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
1180
    virBufferEscapeString(&buf, "  <name>%s</name>\n", def->name);
1181 1182

    virUUIDFormat(def->uuid, uuid);
E
Eric Blake 已提交
1183
    virBufferAsprintf(&buf, "  <uuid>%s</uuid>\n", uuid);
1184

E
Eric Blake 已提交
1185
    virBufferAsprintf(&buf, "  <capacity unit='bytes'>%llu</capacity>\n",
1186
                      def->capacity);
E
Eric Blake 已提交
1187
    virBufferAsprintf(&buf, "  <allocation unit='bytes'>%llu</allocation>\n",
1188
                      def->allocation);
E
Eric Blake 已提交
1189
    virBufferAsprintf(&buf, "  <available unit='bytes'>%llu</available>\n",
1190
                      def->available);
1191

1192
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1193
        goto cleanup;
1194

1195 1196 1197 1198
    /* RBD and Sheepdog devices are not local block devs nor files, so it
     * doesn't have a target */
    if (def->type != VIR_STORAGE_POOL_RBD &&
        def->type != VIR_STORAGE_POOL_SHEEPDOG) {
E
Eric Blake 已提交
1199
        virBufferAddLit(&buf, "  <target>\n");
1200

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

E
Eric Blake 已提交
1203 1204
        virBufferAddLit(&buf, "    <permissions>\n");
        virBufferAsprintf(&buf, "      <mode>0%o</mode>\n",
1205
                          def->target.perms.mode);
E
Eric Blake 已提交
1206
        virBufferAsprintf(&buf, "      <owner>%d</owner>\n",
1207
                          (int) def->target.perms.uid);
E
Eric Blake 已提交
1208
        virBufferAsprintf(&buf, "      <group>%d</group>\n",
1209
                          (int) def->target.perms.gid);
1210

1211 1212
        virBufferEscapeString(&buf, "      <label>%s</label>\n",
                              def->target.perms.label);
1213

E
Eric Blake 已提交
1214 1215
        virBufferAddLit(&buf, "    </permissions>\n");
        virBufferAddLit(&buf, "  </target>\n");
1216
    }
E
Eric Blake 已提交
1217
    virBufferAddLit(&buf, "</pool>\n");
1218

1219
    if (virBufferError(&buf))
1220 1221
        goto no_memory;

1222
    return virBufferContentAndReset(&buf);
1223

1224
no_memory:
1225
    virReportOOMError();
1226
cleanup:
1227
    virBufferFreeAndReset(&buf);
1228 1229 1230 1231 1232
    return NULL;
}


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

    return 0;
}

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

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

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

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

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

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

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

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

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

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

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

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

        if (ret->backingStore.format < 0) {
1340 1341
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1342
            VIR_FREE(format);
1343
            goto error;
1344 1345 1346 1347
        }
        VIR_FREE(format);
    }

1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
    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)))
1372
            goto error;
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386

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

            if (f < 0) {
                virReportError(VIR_ERR_XML_ERROR, _("unsupported feature %s"),
                               (const char*)nodes[i]->name);
                goto error;
            }
            ignore_value(virBitmapSetBit(ret->target.features, f));
        }
        VIR_FREE(nodes);
    }

1387
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1388 1389
                                "./backingStore/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1390
        goto error;
1391

1392
cleanup:
1393
    VIR_FREE(nodes);
1394 1395 1396
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1397 1398 1399
    return ret;

error:
1400
    virStorageVolDefFree(ret);
1401 1402
    ret = NULL;
    goto cleanup;
1403 1404 1405
}

virStorageVolDefPtr
1406
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1407
                          xmlDocPtr xml,
1408 1409
                          xmlNodePtr root)
{
1410 1411 1412
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1413
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1414
        virReportError(VIR_ERR_XML_ERROR,
1415 1416 1417
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1418 1419 1420 1421 1422
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1423
        virReportOOMError();
1424 1425 1426 1427
        goto cleanup;
    }

    ctxt->node = root;
1428
    def = virStorageVolDefParseXML(pool, ctxt);
1429 1430 1431 1432 1433 1434
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1435
virStorageVolDefParse(virStoragePoolDefPtr pool,
1436
                      const char *xmlStr,
1437 1438
                      const char *filename)
{
1439
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1440
    xmlDocPtr xml;
1441

1442
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1443 1444
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1445 1446 1447 1448 1449
    }

    return ret;
}

1450
virStorageVolDefPtr
1451
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1452 1453
                            const char *xmlStr)
{
1454
    return virStorageVolDefParse(pool, xmlStr, NULL);
1455 1456 1457
}

virStorageVolDefPtr
1458
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1459 1460
                          const char *filename)
{
1461
    return virStorageVolDefParse(pool, NULL, filename);
1462
}
1463

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
static void
virStorageVolTimestampFormat(virBufferPtr buf, const char *name,
                             struct timespec *ts)
{
    if (ts->tv_nsec < 0)
        return;
    virBufferAsprintf(buf, "      <%s>%llu", name,
                      (unsigned long long) ts->tv_sec);
    if (ts->tv_nsec)
       virBufferAsprintf(buf, ".%09ld", ts->tv_nsec);
    virBufferAsprintf(buf, "</%s>\n", name);
}

1477
static int
1478
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1479 1480
                             virBufferPtr buf,
                             virStorageVolTargetPtr def,
1481 1482
                             const char *type)
{
1483
    virBufferAsprintf(buf, "  <%s>\n", type);
1484

1485
    virBufferEscapeString(buf, "    <path>%s</path>\n", def->path);
1486 1487 1488 1489

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1490 1491 1492
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1493 1494
            return -1;
        }
E
Eric Blake 已提交
1495
        virBufferAsprintf(buf, "    <format type='%s'/>\n", format);
1496 1497
    }

E
Eric Blake 已提交
1498 1499
    virBufferAddLit(buf, "    <permissions>\n");
    virBufferAsprintf(buf, "      <mode>0%o</mode>\n",
1500
                      def->perms.mode);
E
Eric Blake 已提交
1501
    virBufferAsprintf(buf, "      <owner>%u</owner>\n",
E
Eric Blake 已提交
1502
                      (unsigned int) def->perms.uid);
E
Eric Blake 已提交
1503
    virBufferAsprintf(buf, "      <group>%u</group>\n",
E
Eric Blake 已提交
1504
                      (unsigned int) def->perms.gid);
1505 1506


1507
    virBufferEscapeString(buf, "      <label>%s</label>\n",
1508 1509
                          def->perms.label);

E
Eric Blake 已提交
1510
    virBufferAddLit(buf, "    </permissions>\n");
1511

1512 1513 1514 1515 1516 1517 1518 1519 1520
    if (def->timestamps) {
        virBufferAddLit(buf, "    <timestamps>\n");
        virStorageVolTimestampFormat(buf, "atime", &def->timestamps->atime);
        virStorageVolTimestampFormat(buf, "mtime", &def->timestamps->mtime);
        virStorageVolTimestampFormat(buf, "ctime", &def->timestamps->ctime);
        virStorageVolTimestampFormat(buf, "btime", &def->timestamps->btime);
        virBufferAddLit(buf, "    </timestamps>\n");
    }

1521 1522 1523 1524 1525 1526
    if (def->encryption) {
        virBufferAdjustIndent(buf, 4);
        if (virStorageEncryptionFormat(buf, def->encryption) < 0)
            return -1;
        virBufferAdjustIndent(buf, -4);
    }
1527

1528 1529 1530
    virBufferEscapeString(buf, "    <compat>%s</compat>\n", def->compat);

    if (options->featureToString && def->features) {
1531
        size_t i;
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549
        bool b;
        bool empty = virBitmapIsAllClear(def->features);

        if (empty)
            virBufferAddLit(buf, "    <features/>\n");
        else
            virBufferAddLit(buf, "    <features>\n");

        for (i = 0; i < VIR_STORAGE_FILE_FEATURE_LAST; i++) {
            ignore_value(virBitmapGetBit(def->features, i, &b));
            if (b)
                virBufferAsprintf(buf, "      <%s/>\n",
                                  options->featureToString(i));
        }
        if (!empty)
            virBufferAddLit(buf, "    </features>\n");
    }

1550
    virBufferAsprintf(buf, "  </%s>\n", type);
1551 1552 1553

    return 0;
}
1554 1555

char *
1556
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1557 1558
                       virStorageVolDefPtr def)
{
1559
    virStorageVolOptionsPtr options;
1560
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1561

1562
    options = virStorageVolOptionsForPoolType(pool->type);
1563 1564 1565
    if (options == NULL)
        return NULL;

1566
    virBufferAddLit(&buf, "<volume>\n");
1567 1568
    virBufferEscapeString(&buf, "  <name>%s</name>\n", def->name);
    virBufferEscapeString(&buf, "  <key>%s</key>\n", def->key);
1569
    virBufferAddLit(&buf, "  <source>\n");
1570 1571

    if (def->source.nextent) {
1572
        size_t i;
1573
        const char *thispath = NULL;
1574
        for (i = 0; i < def->source.nextent; i++) {
1575 1576 1577
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1578 1579
                    virBufferAddLit(&buf, "    </device>\n");

1580 1581
                virBufferEscapeString(&buf, "    <device path='%s'>\n",
                                      def->source.extents[i].path);
1582 1583
            }

1584
            virBufferAsprintf(&buf,
1585 1586 1587
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1588 1589 1590
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1591
            virBufferAddLit(&buf, "    </device>\n");
1592
    }
1593
    virBufferAddLit(&buf, "  </source>\n");
1594

E
Eric Blake 已提交
1595
    virBufferAsprintf(&buf, "  <capacity unit='bytes'>%llu</capacity>\n",
1596
                      def->capacity);
E
Eric Blake 已提交
1597
    virBufferAsprintf(&buf, "  <allocation unit='bytes'>%llu</allocation>\n",
1598
                      def->allocation);
1599

1600
    if (virStorageVolTargetDefFormat(options, &buf,
1601 1602
                                     &def->target, "target") < 0)
        goto cleanup;
1603

1604
    if (def->backingStore.path &&
1605
        virStorageVolTargetDefFormat(options, &buf,
1606 1607
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1608

E
Eric Blake 已提交
1609
    virBufferAddLit(&buf, "</volume>\n");
1610

1611
    if (virBufferError(&buf))
1612 1613
        goto no_memory;

1614
    return virBufferContentAndReset(&buf);
1615

1616
no_memory:
1617
    virReportOOMError();
1618
cleanup:
1619
    virBufferFreeAndReset(&buf);
1620 1621 1622 1623 1624
    return NULL;
}


virStoragePoolObjPtr
1625
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1626 1627
                            const unsigned char *uuid)
{
1628
    size_t i;
1629

1630
    for (i = 0; i < pools->count; i++) {
1631
        virStoragePoolObjLock(pools->objs[i]);
1632 1633
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1634 1635
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1636 1637 1638 1639 1640

    return NULL;
}

virStoragePoolObjPtr
1641
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1642 1643
                            const char *name)
{
1644
    size_t i;
1645

1646
    for (i = 0; i < pools->count; i++) {
1647
        virStoragePoolObjLock(pools->objs[i]);
1648 1649
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1650 1651
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1652 1653 1654 1655

    return NULL;
}

1656 1657
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1658 1659
                                         virStoragePoolDefPtr def)
{
1660
    size_t i, j;
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671

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

1672 1673 1674
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1675
    size_t i;
1676
    for (i = 0; i < pool->volumes.count; i++)
1677 1678 1679 1680
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1681 1682 1683 1684
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1685 1686
                          const char *key)
{
1687
    size_t i;
1688

1689
    for (i = 0; i < pool->volumes.count; i++)
1690 1691
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1692 1693 1694 1695 1696 1697

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1698 1699
                           const char *path)
{
1700
    size_t i;
1701

1702
    for (i = 0; i < pool->volumes.count; i++)
1703 1704
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1705 1706 1707 1708 1709 1710

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1711 1712
                           const char *name)
{
1713
    size_t i;
1714

1715
    for (i = 0; i < pool->volumes.count; i++)
1716 1717
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1718 1719 1720 1721 1722

    return NULL;
}

virStoragePoolObjPtr
1723
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1724 1725
                           virStoragePoolDefPtr def)
{
1726 1727
    virStoragePoolObjPtr pool;

1728
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1729 1730 1731 1732
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1733
            virStoragePoolDefFree(pool->newDef);
1734 1735 1736 1737 1738
            pool->newDef = def;
        }
        return pool;
    }

1739
    if (VIR_ALLOC(pool) < 0)
1740 1741
        return NULL;

1742
    if (virMutexInit(&pool->lock) < 0) {
1743 1744
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1745 1746 1747
        VIR_FREE(pool);
        return NULL;
    }
1748
    virStoragePoolObjLock(pool);
1749 1750 1751
    pool->active = 0;
    pool->def = def;

1752 1753
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1754
        virStoragePoolObjUnlock(pool);
1755 1756 1757 1758
        virStoragePoolObjFree(pool);
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1759 1760 1761 1762 1763

    return pool;
}

static virStoragePoolObjPtr
1764
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1765 1766
                      const char *file,
                      const char *path,
1767 1768
                      const char *autostartLink)
{
1769 1770 1771
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1772
    if (!(def = virStoragePoolDefParseFile(path))) {
1773 1774 1775 1776
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1777
        virReportError(VIR_ERR_XML_ERROR,
1778 1779
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1780
                       path, def->name);
1781 1782 1783 1784
        virStoragePoolDefFree(def);
        return NULL;
    }

1785
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1786 1787 1788 1789
        virStoragePoolDefFree(def);
        return NULL;
    }

1790
    VIR_FREE(pool->configFile);  /* for driver reload */
1791
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1792 1793 1794
        virStoragePoolDefFree(def);
        return NULL;
    }
1795
    VIR_FREE(pool->autostartLink); /* for driver reload */
1796
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1809
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1810
                             const char *configDir,
1811 1812
                             const char *autostartDir)
{
1813 1814 1815
    DIR *dir;
    struct dirent *entry;

1816
    if (!(dir = opendir(configDir))) {
1817 1818
        if (errno == ENOENT)
            return 0;
1819
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1820
                             configDir);
1821 1822 1823 1824
        return -1;
    }

    while ((entry = readdir(dir))) {
1825 1826
        char *path;
        char *autostartLink;
1827
        virStoragePoolObjPtr pool;
1828 1829 1830 1831 1832 1833 1834

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

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

1835
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1836 1837
            continue;

1838 1839 1840
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1841 1842 1843
            continue;
        }

1844
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1845
                                     autostartLink);
1846 1847
        if (pool)
            virStoragePoolObjUnlock(pool);
1848 1849 1850

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1851 1852 1853 1854 1855 1856 1857 1858
    }

    closedir(dir);

    return 0;
}

int
1859
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1860
                         virStoragePoolObjPtr pool,
1861 1862
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1863
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1864
    char *xml;
1865
    int ret = -1;
1866 1867

    if (!pool->configFile) {
1868 1869
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1870 1871
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1872 1873 1874
            return -1;
        }

1875 1876
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1877 1878 1879
            return -1;
        }

1880 1881
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1882
            VIR_FREE(pool->configFile);
1883 1884 1885 1886
            return -1;
        }
    }

1887
    if (!(xml = virStoragePoolDefFormat(def))) {
1888 1889
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
1890 1891 1892
        return -1;
    }

J
Ján Tomko 已提交
1893 1894 1895 1896
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1897
    VIR_FREE(xml);
1898 1899 1900 1901 1902

    return ret;
}

int
1903 1904
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
1905
    if (!pool->configFile) {
1906 1907
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1908 1909 1910 1911
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1912 1913 1914
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1915 1916 1917 1918 1919
        return -1;
    }

    return 0;
}
1920

1921
virStoragePoolSourcePtr
1922
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1923 1924 1925
{
    virStoragePoolSourcePtr source;

1926
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0)
1927 1928 1929 1930 1931 1932 1933 1934
        return NULL;

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

    return source;
}

1935 1936
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1937
{
1938
    virStoragePoolOptionsPtr options;
1939
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1940
    const char *type;
1941
    size_t i;
1942

1943
    options = virStoragePoolOptionsForPoolType(def->type);
1944 1945 1946
    if (options == NULL)
        return NULL;

1947
    type = virStoragePoolTypeToString(def->type);
1948
    if (!type) {
1949 1950
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1951 1952 1953 1954
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1955 1956

    for (i = 0; i < def->nsources; i++) {
1957
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1958 1959
    }

1960 1961 1962 1963
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1964 1965

    return virBufferContentAndReset(&buf);
1966

1967
no_memory:
1968
    virReportOOMError();
1969
cleanup:
1970
    virBufferFreeAndReset(&buf);
1971
    return NULL;
1972
}
D
Daniel P. Berrange 已提交
1973 1974


1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
/*
 * 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
 */
1985 1986 1987 1988
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
{
    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);
2000 2001 2002
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
2003 2004 2005 2006 2007 2008
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
2009 2010 2011
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
2012 2013 2014 2015
                goto cleanup;
            }
        }

J
Ján Tomko 已提交
2016
        ret = 1;
2017 2018 2019 2020 2021 2022
    } 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);
2023 2024 2025
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2026 2027
            goto cleanup;
        }
J
Ján Tomko 已提交
2028
        ret = 0;
2029 2030 2031 2032 2033 2034 2035 2036
    }

cleanup:
    if (pool)
        virStoragePoolObjUnlock(pool);
    return ret;
}

2037 2038 2039
int
virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                  virStoragePoolDefPtr def)
2040
{
2041
    size_t i;
2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
    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;

2052 2053 2054 2055
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2056 2057 2058 2059 2060 2061 2062 2063 2064
        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)) \
2065 2066
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
2067 2068 2069
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
            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;
            }
2083 2084 2085 2086
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2087 2088 2089 2090 2091 2092 2093 2094
                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;
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
                    }
                }
                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);
2109 2110 2111

        if (matchpool)
            break;
2112 2113 2114
    }

    if (matchpool) {
2115 2116 2117
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2118 2119 2120 2121
        ret = -1;
    }
    return ret;
}
2122

2123 2124
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2125
{
2126
    virMutexLock(&obj->lock);
2127 2128
}

2129 2130
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2131
{
2132
    virMutexUnlock(&obj->lock);
2133
}
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193

#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) &&
               (poolobj->def->type == VIR_STORAGE_POOL_SHEEPDOG))))
            return false;
    }

    return true;
}
#undef MATCH

int
2194 2195 2196 2197 2198
virStoragePoolObjListExport(virConnectPtr conn,
                            virStoragePoolObjList poolobjs,
                            virStoragePoolPtr **pools,
                            virStoragePoolObjListFilter filter,
                            unsigned int flags)
2199 2200 2201 2202 2203
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
2204
    size_t i;
2205

2206 2207
    if (pools && VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0)
        goto cleanup;
2208 2209 2210 2211

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
2212 2213
        if ((!filter || filter(conn, poolobj->def)) &&
            virStoragePoolMatch(poolobj, flags)) {
2214 2215 2216
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2217 2218
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248
                    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;

cleanup:
    if (tmp_pools) {
        for (i = 0; i < npools; i++) {
            if (tmp_pools[i])
                virStoragePoolFree(tmp_pools[i]);
        }
    }

    VIR_FREE(tmp_pools);
    return ret;
}