storage_conf.c 68.7 KB
Newer Older
1 2 3
/*
 * storage_conf.c: config handling for storage driver
 *
E
Eric Blake 已提交
4
 * Copyright (C) 2006-2012 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
typedef const char *(*virStorageVolFormatToString)(int format);
typedef int (*virStorageVolFormatFromString)(const char *format);
100 101
typedef const char *(*virStorageVolFeatureToString)(int feature);
typedef int (*virStorageVolFeatureFromString)(const char *feature);
102 103 104 105 106 107 108

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

typedef struct _virStorageVolOptions virStorageVolOptions;
typedef virStorageVolOptions *virStorageVolOptionsPtr;
struct _virStorageVolOptions {
109
    int defaultFormat;
110 111
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
112 113
    virStorageVolFeatureToString featureToString;
    virStorageVolFeatureFromString featureFromString;
114 115 116 117
};

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

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

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

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

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


static virStoragePoolTypeInfoPtr
265 266
virStoragePoolTypeInfoLookup(int type)
{
267
    unsigned int i;
268
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo); i++)
269 270 271
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

272 273
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
274 275 276 277
    return NULL;
}

static virStoragePoolOptionsPtr
278 279
virStoragePoolOptionsForPoolType(int type)
{
280 281 282 283 284 285 286
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
287 288
virStorageVolOptionsForPoolType(int type)
{
289 290 291 292 293 294 295
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


296
void
297 298
virStorageVolDefFree(virStorageVolDefPtr def)
{
299
    int i;
300 301 302 303

    if (!def)
        return;

304 305
    VIR_FREE(def->name);
    VIR_FREE(def->key);
306

307
    for (i = 0; i < def->source.nextent; i++) {
308
        VIR_FREE(def->source.extents[i].path);
309
    }
310
    VIR_FREE(def->source.extents);
311

312 313
    VIR_FREE(def->target.compat);
    virBitmapFree(def->target.features);
314 315
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
316
    VIR_FREE(def->target.timestamps);
317
    virStorageEncryptionFree(def->target.encryption);
318 319
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
320
    VIR_FREE(def->backingStore.timestamps);
321
    virStorageEncryptionFree(def->backingStore.encryption);
322
    VIR_FREE(def);
323 324
}

325 326 327 328 329 330 331 332 333 334 335 336 337
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);
    }
}

338
void
339 340
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
341 342
    int i;

343
    if (!source)
344 345
        return;

346
    for (i = 0; i < source->nhost; i++) {
347 348 349 350
        VIR_FREE(source->hosts[i].name);
    }
    VIR_FREE(source->hosts);

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

363 364 365
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
366
    }
367 368 369 370 371

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

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

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

    VIR_FREE(def->name);

389
    virStoragePoolSourceClear(&def->source);
390

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


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

403 404
    virStoragePoolObjClearVols(obj);

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

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

    virMutexDestroy(&obj->lock);

413
    VIR_FREE(obj);
414 415
}

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

426
void
427
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
428 429
                        virStoragePoolObjPtr pool)
{
430
    unsigned int i;
431

432 433
    virStoragePoolObjUnlock(pool);

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

440 441 442
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
443

444 445 446 447
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
448

449 450
            break;
        }
451
        virStoragePoolObjUnlock(pools->objs[i]);
452
    }
453 454 455 456
}


static int
457
virStoragePoolDefParseAuthChap(xmlXPathContextPtr ctxt,
458 459
                               virStoragePoolAuthChapPtr auth)
{
460
    auth->login = virXPathString("string(./auth/@login)", ctxt);
461
    if (auth->login == NULL) {
462 463
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth login attribute"));
464 465 466
        return -1;
    }

467
    auth->passwd = virXPathString("string(./auth/@passwd)", ctxt);
468
    if (auth->passwd == NULL) {
469 470
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth passwd attribute"));
471 472 473 474 475 476
        return -1;
    }

    return 0;
}

477 478
static int
virStoragePoolDefParseAuthCephx(xmlXPathContextPtr ctxt,
479 480
                                virStoragePoolAuthCephxPtr auth)
{
481
    char *uuid = NULL;
482 483
    int ret = -1;

484 485
    auth->username = virXPathString("string(./auth/@username)", ctxt);
    if (auth->username == NULL) {
486 487
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth username attribute"));
488 489 490 491 492 493
        return -1;
    }

    uuid = virXPathString("string(./auth/secret/@uuid)", ctxt);
    auth->secret.usage = virXPathString("string(./auth/secret/@usage)", ctxt);
    if (uuid == NULL && auth->secret.usage == NULL) {
494 495
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth secret uuid or usage attribute"));
496 497 498
        return -1;
    }

499 500 501 502
    if (uuid != NULL) {
        if (auth->secret.usage != NULL) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("either auth secret uuid or usage expected"));
503
            goto cleanup;
504 505
        }
        if (virUUIDParse(uuid, auth->secret.uuid) < 0) {
506 507
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid auth secret uuid"));
508
            goto cleanup;
509 510 511 512
        }
        auth->secret.uuidUsable = true;
    } else {
        auth->secret.uuidUsable = false;
513 514
    }

515 516 517 518
    ret = 0;
cleanup:
    VIR_FREE(uuid);
    return ret;
519 520
}

521
static int
522
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
523 524
                             virStoragePoolSourcePtr source,
                             int pool_type,
525 526
                             xmlNodePtr node)
{
527 528 529 530 531
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
    char *authType = NULL;
    int nsource, i;
    virStoragePoolOptionsPtr options;
532
    char *name = NULL;
533
    char *port = NULL;
534
    char *adapter_type = NULL;
535
    int n;
536 537 538 539 540 541 542 543

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

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

544
    source->name = virXPathString("string(./name)", ctxt);
545
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
546
        virReportError(VIR_ERR_XML_ERROR, "%s",
547
                       _("element 'name' is mandatory for RBD pool"));
548 549
        goto cleanup;
    }
550 551

    if (options->formatFromString) {
552
        char *format = virXPathString("string(./format/@type)", ctxt);
553 554 555 556 557 558
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
559 560
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown pool format type %s"), format);
561 562 563 564 565 566
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

567 568 569
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
    source->nhost = n;
570 571 572 573

    if (source->nhost) {
        if (VIR_ALLOC_N(source->hosts, source->nhost) < 0) {
            virReportOOMError();
574 575 576
            goto cleanup;
        }

577
        for (i = 0; i < source->nhost; i++) {
578 579
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
580 581
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool host name"));
582 583 584 585 586 587 588
                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) {
589 590 591
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
592 593 594 595 596
                    goto cleanup;
                }
            }
        }
    }
597

598
    VIR_FREE(nodeset);
599
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
600

601
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
602 603 604
    if (nsource < 0)
        goto cleanup;

605 606 607
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
608
            virReportOOMError();
609 610 611
            goto cleanup;
        }

612
        for (i = 0; i < nsource; i++) {
613
            char *path = virXMLPropString(nodeset[i], "path");
614 615
            if (path == NULL) {
                VIR_FREE(nodeset);
616 617
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source device path"));
618 619
                goto cleanup;
            }
620
            source->devices[i].path = path;
621 622 623 624
        }
        source->ndevice = nsource;
    }

625
    source->dir = virXPathString("string(./dir/@path)", ctxt);
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 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

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

677
    authType = virXPathString("string(./auth/@type)", ctxt);
678 679 680 681 682
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
683 684
        } else if (STREQ(authType, "ceph")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CEPHX;
685
        } else {
686 687
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown auth type '%s'"),
688
                           authType);
689 690 691 692 693
            goto cleanup;
        }
    }

    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
694
        if (virStoragePoolDefParseAuthChap(ctxt, &source->auth.chap) < 0)
695 696 697
            goto cleanup;
    }

698 699 700 701 702
    if (source->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        if (virStoragePoolDefParseAuthCephx(ctxt, &source->auth.cephx) < 0)
            goto cleanup;
    }

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

706 707 708 709
    ret = 0;
cleanup:
    ctxt->node = relnode;

710
    VIR_FREE(port);
711 712
    VIR_FREE(authType);
    VIR_FREE(nodeset);
713
    VIR_FREE(adapter_type);
714 715
    return ret;
}
716

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

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

    if (VIR_ALLOC(def) < 0) {
732
        virReportOOMError();
733 734 735
        goto cleanup;
    }

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

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

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

    return ret;
}
755

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

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

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

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

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

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

        perms->uid = val;
809 810
    }

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

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

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

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

843
    if (VIR_ALLOC(ret) < 0) {
844
        virReportOOMError();
845
        return NULL;
846
    }
847

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

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

    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
862
        goto error;
863 864
    }

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

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

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

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

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

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

        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'"));
934
                goto error;
935 936 937 938
            }

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

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

959 960 961
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
962
        if (!(target_path = virXPathString("string(./target/path)", ctxt))) {
963 964
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool target path"));
965
            goto error;
966
        }
967
        ret->target.path = virFileSanitizePath(target_path);
968
        if (!ret->target.path)
969
            goto error;
970

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

977
cleanup:
978
    VIR_FREE(uuid);
979 980 981 982 983
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

error:
984
    virStoragePoolDefFree(ret);
985 986
    ret = NULL;
    goto cleanup;
987 988 989
}

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

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

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

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

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

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

1029 1030 1031
    return ret;
}

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

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

1044
static int
1045
virStoragePoolSourceFormat(virBufferPtr buf,
1046
                           virStoragePoolOptionsPtr options,
1047 1048 1049
                           virStoragePoolSourcePtr src)
{
    int i, j;
1050
    char uuid[VIR_UUID_STRING_BUFLEN];
1051 1052

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

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

1081
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
1082
        src->dir)
1083
        virBufferAsprintf(buf,"    <dir path='%s'/>\n", src->dir);
1084

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 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)
            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);
            virBufferAsprintf(buf," wwnn='%s' wwpn='%s'/>\n",
                              src->adapter.data.fchost.wwnn,
                              src->adapter.data.fchost.wwpn);
        } else if (src->adapter.type ==
                 VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            virBufferAsprintf(buf," name='%s'/>\n", src->adapter.data.name);
        }
    }
1102

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

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

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

    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
1126
        virBufferAsprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
1127 1128
                          src->auth.chap.login,
                          src->auth.chap.passwd);
1129

1130 1131 1132 1133
    if (src->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        virBufferAsprintf(buf,"    <auth username='%s' type='ceph'>\n",
                          src->auth.cephx.username);

1134
        virBufferAddLit(buf,"      <secret");
1135
        if (src->auth.cephx.secret.uuidUsable) {
1136 1137 1138 1139 1140 1141 1142
            virUUIDFormat(src->auth.cephx.secret.uuid, uuid);
            virBufferAsprintf(buf," uuid='%s'", uuid);
        }

        if (src->auth.cephx.secret.usage != NULL) {
            virBufferAsprintf(buf," usage='%s'", src->auth.cephx.secret.usage);
        }
1143
        virBufferAddLit(buf,"/>\n");
1144

1145
        virBufferAddLit(buf,"    </auth>\n");
1146 1147
    }

1148 1149 1150 1151 1152 1153 1154 1155
    if (src->vendor != NULL) {
        virBufferEscapeString(buf,"    <vendor name='%s'/>\n", src->vendor);
    }

    if (src->product != NULL) {
        virBufferEscapeString(buf,"    <product name='%s'/>\n", src->product);
    }

1156 1157 1158 1159 1160
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

1161 1162

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

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

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

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

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

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

1196 1197 1198 1199
    /* 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) {
1200
        virBufferAddLit(&buf,"  <target>\n");
1201

1202 1203
        if (def->target.path)
            virBufferAsprintf(&buf,"    <path>%s</path>\n", def->target.path);
1204

1205 1206 1207
        virBufferAddLit(&buf,"    <permissions>\n");
        virBufferAsprintf(&buf,"      <mode>0%o</mode>\n",
                          def->target.perms.mode);
1208 1209 1210 1211
        virBufferAsprintf(&buf,"      <owner>%d</owner>\n",
                          (int) def->target.perms.uid);
        virBufferAsprintf(&buf,"      <group>%d</group>\n",
                          (int) def->target.perms.gid);
1212

1213 1214 1215
        if (def->target.perms.label)
            virBufferAsprintf(&buf,"      <label>%s</label>\n",
                            def->target.perms.label);
1216

1217 1218 1219
        virBufferAddLit(&buf,"    </permissions>\n");
        virBufferAddLit(&buf,"  </target>\n");
    }
1220
    virBufferAddLit(&buf,"</pool>\n");
1221

1222
    if (virBufferError(&buf))
1223 1224
        goto no_memory;

1225
    return virBufferContentAndReset(&buf);
1226

1227
no_memory:
1228
    virReportOOMError();
1229
cleanup:
1230
    virBufferFreeAndReset(&buf);
1231 1232 1233 1234 1235
    return NULL;
}


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

    return 0;
}

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

1266
    options = virStorageVolOptionsForPoolType(pool->type);
1267 1268 1269
    if (options == NULL)
        return NULL;

1270
    if (VIR_ALLOC(ret) < 0) {
1271
        virReportOOMError();
1272
        return NULL;
1273
    }
1274

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

R
Richard W.M. Jones 已提交
1282
    /* Auto-generated so deliberately ignore */
1283
    /* ret->key = virXPathString("string(./key)", ctxt); */
1284

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

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

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

        if (ret->target.format < 0) {
1314 1315
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1316
            VIR_FREE(format);
1317
            goto error;
1318
        }
1319
        VIR_FREE(format);
1320 1321
    }

1322
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
1323 1324
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1325
        goto error;
1326

1327
    node = virXPathNode("./target/encryption", ctxt);
1328
    if (node != NULL) {
1329
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1330 1331
                                                               node);
        if (ret->target.encryption == NULL)
1332
            goto error;
1333 1334
    }

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

        if (ret->backingStore.format < 0) {
1344 1345
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1346
            VIR_FREE(format);
1347
            goto error;
1348 1349 1350 1351
        }
        VIR_FREE(format);
    }

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

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

1391
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1392 1393
                                "./backingStore/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1394
        goto error;
1395

1396
cleanup:
1397
    VIR_FREE(nodes);
1398 1399 1400
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1401 1402
    return ret;

1403 1404
no_memory:
    virReportOOMError();
1405
error:
1406
    virStorageVolDefFree(ret);
1407 1408
    ret = NULL;
    goto cleanup;
1409 1410 1411
}

virStorageVolDefPtr
1412
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1413
                          xmlDocPtr xml,
1414 1415
                          xmlNodePtr root)
{
1416 1417 1418
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1419
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1420
        virReportError(VIR_ERR_XML_ERROR,
1421 1422 1423
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1424 1425 1426 1427 1428
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1429
        virReportOOMError();
1430 1431 1432 1433
        goto cleanup;
    }

    ctxt->node = root;
1434
    def = virStorageVolDefParseXML(pool, ctxt);
1435 1436 1437 1438 1439 1440
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1441
virStorageVolDefParse(virStoragePoolDefPtr pool,
1442
                      const char *xmlStr,
1443 1444
                      const char *filename)
{
1445
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1446
    xmlDocPtr xml;
1447

1448
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1449 1450
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1451 1452 1453 1454 1455
    }

    return ret;
}

1456
virStorageVolDefPtr
1457
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1458 1459
                            const char *xmlStr)
{
1460
    return virStorageVolDefParse(pool, xmlStr, NULL);
1461 1462 1463
}

virStorageVolDefPtr
1464
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1465 1466
                          const char *filename)
{
1467
    return virStorageVolDefParse(pool, NULL, filename);
1468
}
1469

1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
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);
}

1483
static int
1484
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1485 1486 1487
                             virBufferPtr buf,
                             virStorageVolTargetPtr def,
                             const char *type) {
1488
    virBufferAsprintf(buf, "  <%s>\n", type);
1489 1490

    if (def->path)
1491
        virBufferAsprintf(buf,"    <path>%s</path>\n", def->path);
1492 1493 1494 1495

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1496 1497 1498
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1499 1500
            return -1;
        }
1501
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
1502 1503 1504
    }

    virBufferAddLit(buf,"    <permissions>\n");
1505
    virBufferAsprintf(buf,"      <mode>0%o</mode>\n",
1506
                      def->perms.mode);
E
Eric Blake 已提交
1507 1508 1509 1510
    virBufferAsprintf(buf,"      <owner>%u</owner>\n",
                      (unsigned int) def->perms.uid);
    virBufferAsprintf(buf,"      <group>%u</group>\n",
                      (unsigned int) def->perms.gid);
1511 1512 1513


    if (def->perms.label)
1514
        virBufferAsprintf(buf,"      <label>%s</label>\n",
1515 1516 1517 1518
                          def->perms.label);

    virBufferAddLit(buf,"    </permissions>\n");

1519 1520 1521 1522 1523 1524 1525 1526 1527
    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");
    }

1528 1529 1530 1531 1532 1533
    if (def->encryption) {
        virBufferAdjustIndent(buf, 4);
        if (virStorageEncryptionFormat(buf, def->encryption) < 0)
            return -1;
        virBufferAdjustIndent(buf, -4);
    }
1534

1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556
    virBufferEscapeString(buf, "    <compat>%s</compat>\n", def->compat);

    if (options->featureToString && def->features) {
        int i;
        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");
    }

1557
    virBufferAsprintf(buf, "  </%s>\n", type);
1558 1559 1560

    return 0;
}
1561 1562

char *
1563
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1564 1565
                       virStorageVolDefPtr def)
{
1566
    virStorageVolOptionsPtr options;
1567
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1568

1569
    options = virStorageVolOptionsForPoolType(pool->type);
1570 1571 1572
    if (options == NULL)
        return NULL;

1573
    virBufferAddLit(&buf, "<volume>\n");
1574
    virBufferAsprintf(&buf,"  <name>%s</name>\n", def->name);
O
Osier Yang 已提交
1575
    virBufferAsprintf(&buf,"  <key>%s</key>\n", NULLSTR(def->key));
1576
    virBufferAddLit(&buf, "  <source>\n");
1577 1578 1579 1580

    if (def->source.nextent) {
        int i;
        const char *thispath = NULL;
1581
        for (i = 0; i < def->source.nextent; i++) {
1582 1583 1584
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1585 1586
                    virBufferAddLit(&buf, "    </device>\n");

1587
                virBufferAsprintf(&buf, "    <device path='%s'>\n",
1588
                                  def->source.extents[i].path);
1589 1590
            }

1591
            virBufferAsprintf(&buf,
1592 1593 1594
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1595 1596 1597
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1598
            virBufferAddLit(&buf, "    </device>\n");
1599
    }
1600
    virBufferAddLit(&buf, "  </source>\n");
1601

E
Eric Blake 已提交
1602
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1603
                      def->capacity);
E
Eric Blake 已提交
1604
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1605
                      def->allocation);
1606

1607
    if (virStorageVolTargetDefFormat(options, &buf,
1608 1609
                                     &def->target, "target") < 0)
        goto cleanup;
1610

1611
    if (def->backingStore.path &&
1612
        virStorageVolTargetDefFormat(options, &buf,
1613 1614
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1615 1616

    virBufferAddLit(&buf,"</volume>\n");
1617

1618
    if (virBufferError(&buf))
1619 1620
        goto no_memory;

1621
    return virBufferContentAndReset(&buf);
1622

1623
no_memory:
1624
    virReportOOMError();
1625
cleanup:
1626
    virBufferFreeAndReset(&buf);
1627 1628 1629 1630 1631
    return NULL;
}


virStoragePoolObjPtr
1632
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1633 1634
                            const unsigned char *uuid)
{
1635
    unsigned int i;
1636

1637
    for (i = 0; i < pools->count; i++) {
1638
        virStoragePoolObjLock(pools->objs[i]);
1639 1640
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1641 1642
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1643 1644 1645 1646 1647

    return NULL;
}

virStoragePoolObjPtr
1648
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1649 1650
                            const char *name)
{
1651
    unsigned int i;
1652

1653
    for (i = 0; i < pools->count; i++) {
1654
        virStoragePoolObjLock(pools->objs[i]);
1655 1656
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1657 1658
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1659 1660 1661 1662

    return NULL;
}

1663 1664
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1665 1666
                                         virStoragePoolDefPtr def)
{
1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678
    unsigned int i, j;

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

1679 1680 1681
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1682
    unsigned int i;
1683
    for (i = 0; i < pool->volumes.count; i++)
1684 1685 1686 1687
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1688 1689 1690 1691
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1692 1693
                          const char *key)
{
1694
    unsigned int i;
1695

1696
    for (i = 0; i < pool->volumes.count; i++)
1697 1698
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1699 1700 1701 1702 1703 1704

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1705 1706
                           const char *path)
{
1707
    unsigned int i;
1708

1709
    for (i = 0; i < pool->volumes.count; i++)
1710 1711
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1712 1713 1714 1715 1716 1717

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1718 1719
                           const char *name)
{
1720
    unsigned int i;
1721

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

    return NULL;
}

virStoragePoolObjPtr
1730
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1731 1732
                           virStoragePoolDefPtr def)
{
1733 1734
    virStoragePoolObjPtr pool;

1735
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1736 1737 1738 1739
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1740
            virStoragePoolDefFree(pool->newDef);
1741 1742 1743 1744 1745
            pool->newDef = def;
        }
        return pool;
    }

1746
    if (VIR_ALLOC(pool) < 0) {
1747
        virReportOOMError();
1748 1749 1750
        return NULL;
    }

1751
    if (virMutexInit(&pool->lock) < 0) {
1752 1753
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1754 1755 1756
        VIR_FREE(pool);
        return NULL;
    }
1757
    virStoragePoolObjLock(pool);
1758 1759 1760
    pool->active = 0;
    pool->def = def;

1761 1762
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1763
        virStoragePoolObjUnlock(pool);
1764
        virStoragePoolObjFree(pool);
1765
        virReportOOMError();
1766 1767 1768
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1769 1770 1771 1772 1773

    return pool;
}

static virStoragePoolObjPtr
1774
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1775 1776
                      const char *file,
                      const char *path,
1777 1778
                      const char *autostartLink)
{
1779 1780 1781
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1782
    if (!(def = virStoragePoolDefParseFile(path))) {
1783 1784 1785 1786
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1787
        virReportError(VIR_ERR_XML_ERROR,
1788 1789
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1790
                       path, def->name);
1791 1792 1793 1794
        virStoragePoolDefFree(def);
        return NULL;
    }

1795
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1796 1797 1798 1799
        virStoragePoolDefFree(def);
        return NULL;
    }

1800
    VIR_FREE(pool->configFile);  /* for driver reload */
1801
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1802 1803 1804
        virStoragePoolDefFree(def);
        return NULL;
    }
1805
    VIR_FREE(pool->autostartLink); /* for driver reload */
1806
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1819
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1820
                             const char *configDir,
1821 1822
                             const char *autostartDir)
{
1823 1824 1825
    DIR *dir;
    struct dirent *entry;

1826
    if (!(dir = opendir(configDir))) {
1827 1828
        if (errno == ENOENT)
            return 0;
1829
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1830
                             configDir);
1831 1832 1833 1834
        return -1;
    }

    while ((entry = readdir(dir))) {
1835 1836
        char *path;
        char *autostartLink;
1837
        virStoragePoolObjPtr pool;
1838 1839 1840 1841 1842 1843 1844

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

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

1845
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1846 1847
            continue;

1848 1849 1850
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1851 1852 1853
            continue;
        }

1854
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1855
                                     autostartLink);
1856 1857
        if (pool)
            virStoragePoolObjUnlock(pool);
1858 1859 1860

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1861 1862 1863 1864 1865 1866 1867 1868
    }

    closedir(dir);

    return 0;
}

int
1869
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1870
                         virStoragePoolObjPtr pool,
1871 1872
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1873
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1874
    char *xml;
1875
    int ret = -1;
1876 1877

    if (!pool->configFile) {
1878 1879
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1880 1881
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1882 1883 1884
            return -1;
        }

1885 1886
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1887 1888 1889
            return -1;
        }

1890 1891
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1892
            VIR_FREE(pool->configFile);
1893 1894 1895 1896
            return -1;
        }
    }

1897
    if (!(xml = virStoragePoolDefFormat(def))) {
1898 1899
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
1900 1901 1902
        return -1;
    }

J
Ján Tomko 已提交
1903 1904 1905 1906
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1907
    VIR_FREE(xml);
1908 1909 1910 1911 1912

    return ret;
}

int
1913 1914
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
1915
    if (!pool->configFile) {
1916 1917
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1918 1919 1920 1921
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1922 1923 1924
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1925 1926 1927 1928 1929
        return -1;
    }

    return 0;
}
1930

1931
virStoragePoolSourcePtr
1932
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1933 1934 1935
{
    virStoragePoolSourcePtr source;

1936
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0) {
1937
        virReportOOMError();
1938 1939 1940 1941 1942 1943 1944 1945 1946
        return NULL;
    }

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

    return source;
}

1947 1948
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1949
{
1950
    virStoragePoolOptionsPtr options;
1951
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1952 1953
    const char *type;
    int i;
1954

1955
    options = virStoragePoolOptionsForPoolType(def->type);
1956 1957 1958
    if (options == NULL)
        return NULL;

1959
    type = virStoragePoolTypeToString(def->type);
1960
    if (!type) {
1961 1962
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1963 1964 1965 1966
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1967 1968

    for (i = 0; i < def->nsources; i++) {
1969
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1970 1971
    }

1972 1973 1974 1975
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1976 1977

    return virBufferContentAndReset(&buf);
1978

1979
no_memory:
1980
    virReportOOMError();
1981
cleanup:
1982
    virBufferFreeAndReset(&buf);
1983
    return NULL;
1984
}
D
Daniel P. Berrange 已提交
1985 1986


1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
/*
 * 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
 */
1997 1998 1999 2000
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
{
    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);
2012 2013 2014
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
2015 2016 2017 2018 2019 2020
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
2021 2022 2023
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
2024 2025 2026 2027
                goto cleanup;
            }
        }

J
Ján Tomko 已提交
2028
        ret = 1;
2029 2030 2031 2032 2033 2034
    } 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);
2035 2036 2037
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
2038 2039
            goto cleanup;
        }
J
Ján Tomko 已提交
2040
        ret = 0;
2041 2042 2043 2044 2045 2046 2047 2048
    }

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

2049 2050 2051
int
virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                  virStoragePoolDefPtr def)
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063
{
    int i;
    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;

2064 2065 2066 2067
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

2068 2069 2070 2071 2072 2073 2074 2075 2076
        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)) \
2077 2078
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
2079 2080 2081
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
            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;
            }
2095 2096 2097 2098
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2099 2100 2101 2102 2103 2104 2105 2106
                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;
2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120
                    }
                }
                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);
2121 2122 2123

        if (matchpool)
            break;
2124 2125 2126
    }

    if (matchpool) {
2127 2128 2129
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2130 2131 2132 2133
        ret = -1;
    }
    return ret;
}
2134

2135 2136
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2137
{
2138
    virMutexLock(&obj->lock);
2139 2140
}

2141 2142
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2143
{
2144
    virMutexUnlock(&obj->lock);
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 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

#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
virStoragePoolList(virConnectPtr conn,
                   virStoragePoolObjList poolobjs,
                   virStoragePoolPtr **pools,
                   unsigned int flags)
{
    virStoragePoolPtr *tmp_pools = NULL;
    virStoragePoolPtr pool = NULL;
    int npools = 0;
    int ret = -1;
    int i;

    if (pools) {
        if (VIR_ALLOC_N(tmp_pools, poolobjs.count + 1) < 0) {
            virReportOOMError();
            goto cleanup;
        }
    }

    for (i = 0; i < poolobjs.count; i++) {
        virStoragePoolObjPtr poolobj = poolobjs.objs[i];
        virStoragePoolObjLock(poolobj);
        if (virStoragePoolMatch(poolobj, flags)) {
            if (pools) {
                if (!(pool = virGetStoragePool(conn,
                                               poolobj->def->name,
2231 2232
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262
                    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;
}