storage_conf.c 65.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 100 101 102 103 104 105 106
typedef const char *(*virStorageVolFormatToString)(int format);
typedef int (*virStorageVolFormatFromString)(const char *format);

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

typedef struct _virStorageVolOptions virStorageVolOptions;
typedef virStorageVolOptions *virStorageVolOptionsPtr;
struct _virStorageVolOptions {
107
    int defaultFormat;
108 109 110 111 112 113
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
};

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

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

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

E
Eric Blake 已提交
140 141 142 143 144 145 146 147 148
static int
virStorageVolumeFormatFromString(const char *format)
{
    int ret = virStorageFileFormatTypeFromString(format);
    if (ret == VIR_STORAGE_FILE_NONE)
        return -1;
    return ret;
}

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


static virStoragePoolTypeInfoPtr
255 256
virStoragePoolTypeInfoLookup(int type)
{
257
    unsigned int i;
258
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo); i++)
259 260 261
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

262 263
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
264 265 266 267
    return NULL;
}

static virStoragePoolOptionsPtr
268 269
virStoragePoolOptionsForPoolType(int type)
{
270 271 272 273 274 275 276
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
277 278
virStorageVolOptionsForPoolType(int type)
{
279 280 281 282 283 284 285
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


286
void
287 288
virStorageVolDefFree(virStorageVolDefPtr def)
{
289
    int i;
290 291 292 293

    if (!def)
        return;

294 295
    VIR_FREE(def->name);
    VIR_FREE(def->key);
296

297
    for (i = 0; i < def->source.nextent; i++) {
298
        VIR_FREE(def->source.extents[i].path);
299
    }
300
    VIR_FREE(def->source.extents);
301

302 303
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
304
    VIR_FREE(def->target.timestamps);
305
    virStorageEncryptionFree(def->target.encryption);
306 307
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
308
    VIR_FREE(def->backingStore.timestamps);
309
    virStorageEncryptionFree(def->backingStore.encryption);
310
    VIR_FREE(def);
311 312
}

313 314 315 316 317 318 319 320 321 322 323 324 325
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);
    }
}

326
void
327 328
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
329 330
    int i;

331
    if (!source)
332 333
        return;

334
    for (i = 0; i < source->nhost; i++) {
335 336 337 338
        VIR_FREE(source->hosts[i].name);
    }
    VIR_FREE(source->hosts);

339
    for (i = 0; i < source->ndevice; i++) {
340 341
        VIR_FREE(source->devices[i].freeExtents);
        VIR_FREE(source->devices[i].path);
342
    }
343 344 345
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
346
    virStoragePoolSourceAdapterClear(source->adapter);
D
David Allan 已提交
347
    VIR_FREE(source->initiator.iqn);
348 349
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
350

351 352 353
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
354
    }
355 356 357 358 359

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

362 363 364 365 366 367 368
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

369
void
370 371
virStoragePoolDefFree(virStoragePoolDefPtr def)
{
372 373 374 375 376
    if (!def)
        return;

    VIR_FREE(def->name);

377
    virStoragePoolSourceClear(&def->source);
378

379 380 381
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
382 383 384 385
}


void
386 387
virStoragePoolObjFree(virStoragePoolObjPtr obj)
{
388 389 390
    if (!obj)
        return;

391 392
    virStoragePoolObjClearVols(obj);

393 394
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
395

396 397
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
398 399 400

    virMutexDestroy(&obj->lock);

401
    VIR_FREE(obj);
402 403
}

404 405
void
virStoragePoolObjListFree(virStoragePoolObjListPtr pools)
406 407
{
    unsigned int i;
408
    for (i = 0; i < pools->count; i++)
409 410 411 412 413
        virStoragePoolObjFree(pools->objs[i]);
    VIR_FREE(pools->objs);
    pools->count = 0;
}

414
void
415
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
416 417
                        virStoragePoolObjPtr pool)
{
418
    unsigned int i;
419

420 421
    virStoragePoolObjUnlock(pool);

422
    for (i = 0; i < pools->count; i++) {
423
        virStoragePoolObjLock(pools->objs[i]);
424
        if (pools->objs[i] == pool) {
425
            virStoragePoolObjUnlock(pools->objs[i]);
426
            virStoragePoolObjFree(pools->objs[i]);
427

428 429 430
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
431

432 433 434 435
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
436

437 438
            break;
        }
439
        virStoragePoolObjUnlock(pools->objs[i]);
440
    }
441 442 443 444
}


static int
445
virStoragePoolDefParseAuthChap(xmlXPathContextPtr ctxt,
446 447
                               virStoragePoolAuthChapPtr auth)
{
448
    auth->login = virXPathString("string(./auth/@login)", ctxt);
449
    if (auth->login == NULL) {
450 451
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth login attribute"));
452 453 454
        return -1;
    }

455
    auth->passwd = virXPathString("string(./auth/@passwd)", ctxt);
456
    if (auth->passwd == NULL) {
457 458
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth passwd attribute"));
459 460 461 462 463 464
        return -1;
    }

    return 0;
}

465 466
static int
virStoragePoolDefParseAuthCephx(xmlXPathContextPtr ctxt,
467 468
                                virStoragePoolAuthCephxPtr auth)
{
469
    char *uuid = NULL;
470 471
    int ret = -1;

472 473
    auth->username = virXPathString("string(./auth/@username)", ctxt);
    if (auth->username == NULL) {
474 475
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth username attribute"));
476 477 478 479 480 481
        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) {
482 483
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth secret uuid or usage attribute"));
484 485 486
        return -1;
    }

487 488 489 490
    if (uuid != NULL) {
        if (auth->secret.usage != NULL) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("either auth secret uuid or usage expected"));
491
            goto cleanup;
492 493
        }
        if (virUUIDParse(uuid, auth->secret.uuid) < 0) {
494 495
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("invalid auth secret uuid"));
496
            goto cleanup;
497 498 499 500
        }
        auth->secret.uuidUsable = true;
    } else {
        auth->secret.uuidUsable = false;
501 502
    }

503 504 505 506
    ret = 0;
cleanup:
    VIR_FREE(uuid);
    return ret;
507 508
}

509
static int
510
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
511 512
                             virStoragePoolSourcePtr source,
                             int pool_type,
513 514
                             xmlNodePtr node)
{
515 516 517 518 519
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
    char *authType = NULL;
    int nsource, i;
    virStoragePoolOptionsPtr options;
520
    char *name = NULL;
521
    char *port = NULL;
522
    char *adapter_type = NULL;
523
    int n;
524 525 526 527 528 529 530 531

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

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

532
    source->name = virXPathString("string(./name)", ctxt);
533
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
534
        virReportError(VIR_ERR_XML_ERROR, "%s",
535
                       _("element 'name' is mandatory for RBD pool"));
536 537
        goto cleanup;
    }
538 539

    if (options->formatFromString) {
540
        char *format = virXPathString("string(./format/@type)", ctxt);
541 542 543 544 545 546
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
547 548
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown pool format type %s"), format);
549 550 551 552 553 554
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

555 556 557
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
    source->nhost = n;
558 559 560 561

    if (source->nhost) {
        if (VIR_ALLOC_N(source->hosts, source->nhost) < 0) {
            virReportOOMError();
562 563 564
            goto cleanup;
        }

565
        for (i = 0; i < source->nhost; i++) {
566 567
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
568 569
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool host name"));
570 571 572 573 574 575 576
                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) {
577 578 579
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
580 581 582 583 584
                    goto cleanup;
                }
            }
        }
    }
585

586
    VIR_FREE(nodeset);
587
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
588

589
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
590 591 592
    if (nsource < 0)
        goto cleanup;

593 594 595
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
596
            virReportOOMError();
597 598 599
            goto cleanup;
        }

600
        for (i = 0; i < nsource; i++) {
601
            char *path = virXMLPropString(nodeset[i], "path");
602 603
            if (path == NULL) {
                VIR_FREE(nodeset);
604 605
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source device path"));
606 607
                goto cleanup;
            }
608
            source->devices[i].path = path;
609 610 611 612
        }
        source->ndevice = nsource;
    }

613
    source->dir = virXPathString("string(./dir/@path)", ctxt);
614 615 616 617 618 619 620 621 622 623 624 625 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

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

665
    authType = virXPathString("string(./auth/@type)", ctxt);
666 667 668 669 670
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
671 672
        } else if (STREQ(authType, "ceph")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CEPHX;
673
        } else {
674 675
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown auth type '%s'"),
676
                           authType);
677 678 679 680 681
            goto cleanup;
        }
    }

    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
682
        if (virStoragePoolDefParseAuthChap(ctxt, &source->auth.chap) < 0)
683 684 685
            goto cleanup;
    }

686 687 688 689 690
    if (source->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        if (virStoragePoolDefParseAuthCephx(ctxt, &source->auth.cephx) < 0)
            goto cleanup;
    }

691 692 693
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

694 695 696 697
    ret = 0;
cleanup:
    ctxt->node = relnode;

698
    VIR_FREE(port);
699 700
    VIR_FREE(authType);
    VIR_FREE(nodeset);
701
    VIR_FREE(adapter_type);
702 703
    return ret;
}
704

705
virStoragePoolSourcePtr
706
virStoragePoolDefParseSourceString(const char *srcSpec,
707 708 709 710 711 712 713
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

714 715 716
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
717 718 719
        goto cleanup;

    if (VIR_ALLOC(def) < 0) {
720
        virReportOOMError();
721 722 723
        goto cleanup;
    }

724
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
725 726
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
727 728 729
        goto cleanup;
    }

730
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
731 732 733 734 735 736
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
737
    virStoragePoolSourceFree(def);
738 739 740 741 742
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
743

744
static int
745
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
746 747
                        virStoragePermsPtr perms,
                        const char *permxpath,
748 749
                        int defaultmode)
{
750
    char *mode;
751
    long val;
752 753 754
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
755

756
    node = virXPathNode(permxpath, ctxt);
757 758 759
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
P
Philipp Hahn 已提交
760 761
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
762 763 764 765 766 767 768
        perms->label = NULL;
        return 0;
    }

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

769
    mode = virXPathString("string(./mode)", ctxt);
770
    if (!mode) {
771
        perms->mode = defaultmode;
772
    } else {
773 774 775
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
776
            VIR_FREE(mode);
777 778
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed octal mode"));
779
            goto error;
780
        }
781
        perms->mode = tmp;
782
        VIR_FREE(mode);
783 784
    }

785
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
786
        perms->uid = (uid_t) -1;
787
    } else {
788 789 790
        if (virXPathLong("number(./owner)", ctxt, &val) < 0 ||
            ((uid_t)val != val &&
             val != -1)) {
791 792
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed owner element"));
793
            goto error;
794
        }
795 796

        perms->uid = val;
797 798
    }

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

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

815 816 817 818
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
819 820 821
}

static virStoragePoolDefPtr
822 823
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt)
{
824
    virStoragePoolOptionsPtr options;
825
    virStoragePoolDefPtr ret;
826
    xmlNodePtr source_node;
827
    char *type = NULL;
828
    char *uuid = NULL;
829
    char *target_path = NULL;
830

831
    if (VIR_ALLOC(ret) < 0) {
832
        virReportOOMError();
833
        return NULL;
834
    }
835

836
    type = virXPathString("string(./@type)", ctxt);
837
    if ((ret->type = virStoragePoolTypeFromString(type)) < 0) {
O
Osier Yang 已提交
838
        virReportError(VIR_ERR_XML_ERROR,
839
                       _("unknown storage pool type %s"), type);
840
        goto error;
841 842 843
    }

    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
844
        goto error;
845 846
    }

847
    source_node = virXPathNode("./source", ctxt);
848
    if (source_node) {
849
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
850
                                         source_node) < 0)
851
            goto error;
852 853
    }

854
    ret->name = virXPathString("string(./name)", ctxt);
855
    if (ret->name == NULL &&
856
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
857
        ret->name = ret->source.name;
858
    if (ret->name == NULL) {
859 860
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing pool source name element"));
861
        goto error;
862 863
    }

864
    uuid = virXPathString("string(./uuid)", ctxt);
865 866
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
867 868
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("unable to generate uuid"));
869
            goto error;
870 871 872
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
873 874
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("malformed uuid element"));
875
            goto error;
876 877 878
        }
    }

879
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
880
        if (!ret->source.nhost) {
881
            virReportError(VIR_ERR_XML_ERROR, "%s",
882
                           _("missing storage pool source host name"));
883
            goto error;
884 885 886
        }
    }

887
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
888
        if (!ret->source.dir) {
889 890
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source path"));
891
            goto error;
892 893
        }
    }
894
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
895 896
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
897
            if (VIR_STRDUP(ret->source.name, ret->name) < 0)
898
                goto error;
899 900
        }
    }
901

902
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
903 904 905
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
906
            goto error;
907
        }
908 909 910 911 912 913 914 915

        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'"));
916
                goto error;
917 918 919 920
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
921
                goto error;
922 923 924
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            if (!ret->source.adapter.data.name) {
925 926
                virReportError(VIR_ERR_XML_ERROR, "%s",
                               _("missing storage pool source adapter name"));
927
                goto error;
928 929
            }
        }
930
    }
931

932 933 934
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
935 936
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source device name"));
937
            goto error;
938 939 940
        }
    }

941 942 943
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
944
        if (!(target_path = virXPathString("string(./target/path)", ctxt))) {
945 946
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool target path"));
947
            goto error;
948
        }
949
        ret->target.path = virFileSanitizePath(target_path);
950
        if (!ret->target.path)
951
            goto error;
952

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

    return ret;

961
cleanup:
962
    VIR_FREE(uuid);
963 964 965 966 967
    VIR_FREE(type);
    VIR_FREE(target_path);
    return ret;

error:
968
    virStoragePoolDefFree(ret);
969 970
    ret = NULL;
    goto cleanup;
971 972 973
}

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

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

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

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

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

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

1013 1014 1015
    return ret;
}

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

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

1028
static int
1029
virStoragePoolSourceFormat(virBufferPtr buf,
1030
                           virStoragePoolOptionsPtr options,
1031 1032 1033
                           virStoragePoolSourcePtr src)
{
    int i, j;
1034
    char uuid[VIR_UUID_STRING_BUFLEN];
1035 1036

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

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

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

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    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);
        }
    }
1086

1087
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
1088
        src->name)
1089
        virBufferAsprintf(buf,"    <name>%s</name>\n", src->name);
1090

D
David Allan 已提交
1091 1092 1093 1094 1095 1096 1097
    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");
    }

1098 1099 1100
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
1101 1102 1103
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
1104 1105
            return -1;
        }
1106
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
1107 1108 1109
    }

    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
1110
        virBufferAsprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
1111 1112
                          src->auth.chap.login,
                          src->auth.chap.passwd);
1113

1114 1115 1116 1117
    if (src->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        virBufferAsprintf(buf,"    <auth username='%s' type='ceph'>\n",
                          src->auth.cephx.username);

1118
        virBufferAddLit(buf,"      <secret");
1119
        if (src->auth.cephx.secret.uuidUsable) {
1120 1121 1122 1123 1124 1125 1126
            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);
        }
1127
        virBufferAddLit(buf,"/>\n");
1128

1129
        virBufferAddLit(buf,"    </auth>\n");
1130 1131
    }

1132 1133 1134 1135 1136 1137 1138 1139
    if (src->vendor != NULL) {
        virBufferEscapeString(buf,"    <vendor name='%s'/>\n", src->vendor);
    }

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

1140 1141 1142 1143 1144
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

1145 1146

char *
1147 1148
virStoragePoolDefFormat(virStoragePoolDefPtr def)
{
1149
    virStoragePoolOptionsPtr options;
1150
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1151 1152 1153
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1154
    options = virStoragePoolOptionsForPoolType(def->type);
1155 1156 1157
    if (options == NULL)
        return NULL;

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

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

E
Eric Blake 已提交
1170
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1171
                      def->capacity);
E
Eric Blake 已提交
1172
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1173
                      def->allocation);
E
Eric Blake 已提交
1174
    virBufferAsprintf(&buf,"  <available unit='bytes'>%llu</available>\n",
1175
                      def->available);
1176

1177
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1178
        goto cleanup;
1179

1180 1181 1182 1183
    /* 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) {
1184
        virBufferAddLit(&buf,"  <target>\n");
1185

1186 1187
        if (def->target.path)
            virBufferAsprintf(&buf,"    <path>%s</path>\n", def->target.path);
1188

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

1197 1198 1199
        if (def->target.perms.label)
            virBufferAsprintf(&buf,"      <label>%s</label>\n",
                            def->target.perms.label);
1200

1201 1202 1203
        virBufferAddLit(&buf,"    </permissions>\n");
        virBufferAddLit(&buf,"  </target>\n");
    }
1204
    virBufferAddLit(&buf,"</pool>\n");
1205

1206
    if (virBufferError(&buf))
1207 1208
        goto no_memory;

1209
    return virBufferContentAndReset(&buf);
1210

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


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

    return 0;
}

static virStorageVolDefPtr
1238
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1239 1240
                         xmlXPathContextPtr ctxt)
{
1241
    virStorageVolDefPtr ret;
1242
    virStorageVolOptionsPtr options;
1243 1244 1245
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1246
    xmlNodePtr node;
1247

1248
    options = virStorageVolOptionsForPoolType(pool->type);
1249 1250 1251
    if (options == NULL)
        return NULL;

1252
    if (VIR_ALLOC(ret) < 0) {
1253
        virReportOOMError();
1254
        return NULL;
1255
    }
1256

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

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

1267 1268
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1269
    if (capacity == NULL) {
1270 1271
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing capacity element"));
1272
        goto error;
1273
    }
1274
    if (virStorageSize(unit, capacity, &ret->capacity) < 0)
1275
        goto error;
1276
    VIR_FREE(unit);
1277

1278
    allocation = virXPathString("string(./allocation)", ctxt);
1279
    if (allocation) {
1280
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1281
        if (virStorageSize(unit, allocation, &ret->allocation) < 0)
1282
            goto error;
1283 1284 1285 1286
    } else {
        ret->allocation = ret->capacity;
    }

1287
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1288
    if (options->formatFromString) {
1289
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1290 1291 1292 1293 1294 1295
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1296 1297
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1298
            VIR_FREE(format);
1299
            goto error;
1300
        }
1301
        VIR_FREE(format);
1302 1303
    }

1304
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
1305 1306
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1307
        goto error;
1308

1309
    node = virXPathNode("./target/encryption", ctxt);
1310
    if (node != NULL) {
1311
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1312 1313
                                                               node);
        if (ret->target.encryption == NULL)
1314
            goto error;
1315 1316
    }

1317
    ret->backingStore.path = virXPathString("string(./backingStore/path)", ctxt);
1318
    if (options->formatFromString) {
1319
        char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
1320 1321 1322 1323 1324 1325
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
1326 1327
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1328
            VIR_FREE(format);
1329
            goto error;
1330 1331 1332 1333
        }
        VIR_FREE(format);
    }

1334
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1335 1336
                                "./backingStore/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1337
        goto error;
1338

1339
cleanup:
1340 1341 1342
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1343 1344 1345
    return ret;

error:
1346
    virStorageVolDefFree(ret);
1347 1348
    ret = NULL;
    goto cleanup;
1349 1350 1351
}

virStorageVolDefPtr
1352
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1353
                          xmlDocPtr xml,
1354 1355
                          xmlNodePtr root)
{
1356 1357 1358
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

1359
    if (!xmlStrEqual(root->name, BAD_CAST "volume")) {
1360
        virReportError(VIR_ERR_XML_ERROR,
1361 1362 1363
                       _("unexpected root element <%s>, "
                         "expecting <volume>"),
                       root->name);
1364 1365 1366 1367 1368
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1369
        virReportOOMError();
1370 1371 1372 1373
        goto cleanup;
    }

    ctxt->node = root;
1374
    def = virStorageVolDefParseXML(pool, ctxt);
1375 1376 1377 1378 1379 1380
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1381
virStorageVolDefParse(virStoragePoolDefPtr pool,
1382
                      const char *xmlStr,
1383 1384
                      const char *filename)
{
1385
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1386
    xmlDocPtr xml;
1387

1388
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1389 1390
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1391 1392 1393 1394 1395
    }

    return ret;
}

1396
virStorageVolDefPtr
1397
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1398 1399
                            const char *xmlStr)
{
1400
    return virStorageVolDefParse(pool, xmlStr, NULL);
1401 1402 1403
}

virStorageVolDefPtr
1404
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1405 1406
                          const char *filename)
{
1407
    return virStorageVolDefParse(pool, NULL, filename);
1408
}
1409

1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
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);
}

1423
static int
1424
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1425 1426 1427
                             virBufferPtr buf,
                             virStorageVolTargetPtr def,
                             const char *type) {
1428
    virBufferAsprintf(buf, "  <%s>\n", type);
1429 1430

    if (def->path)
1431
        virBufferAsprintf(buf,"    <path>%s</path>\n", def->path);
1432 1433 1434 1435

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1436 1437 1438
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1439 1440
            return -1;
        }
1441
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
1442 1443 1444
    }

    virBufferAddLit(buf,"    <permissions>\n");
1445
    virBufferAsprintf(buf,"      <mode>0%o</mode>\n",
1446
                      def->perms.mode);
E
Eric Blake 已提交
1447 1448 1449 1450
    virBufferAsprintf(buf,"      <owner>%u</owner>\n",
                      (unsigned int) def->perms.uid);
    virBufferAsprintf(buf,"      <group>%u</group>\n",
                      (unsigned int) def->perms.gid);
1451 1452 1453


    if (def->perms.label)
1454
        virBufferAsprintf(buf,"      <label>%s</label>\n",
1455 1456 1457 1458
                          def->perms.label);

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

1459 1460 1461 1462 1463 1464 1465 1466 1467
    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");
    }

1468 1469 1470 1471 1472 1473
    if (def->encryption) {
        virBufferAdjustIndent(buf, 4);
        if (virStorageEncryptionFormat(buf, def->encryption) < 0)
            return -1;
        virBufferAdjustIndent(buf, -4);
    }
1474

1475
    virBufferAsprintf(buf, "  </%s>\n", type);
1476 1477 1478

    return 0;
}
1479 1480

char *
1481
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1482 1483
                       virStorageVolDefPtr def)
{
1484
    virStorageVolOptionsPtr options;
1485
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1486

1487
    options = virStorageVolOptionsForPoolType(pool->type);
1488 1489 1490
    if (options == NULL)
        return NULL;

1491
    virBufferAddLit(&buf, "<volume>\n");
1492
    virBufferAsprintf(&buf,"  <name>%s</name>\n", def->name);
O
Osier Yang 已提交
1493
    virBufferAsprintf(&buf,"  <key>%s</key>\n", NULLSTR(def->key));
1494
    virBufferAddLit(&buf, "  <source>\n");
1495 1496 1497 1498

    if (def->source.nextent) {
        int i;
        const char *thispath = NULL;
1499
        for (i = 0; i < def->source.nextent; i++) {
1500 1501 1502
            if (thispath == NULL ||
                STRNEQ(thispath, def->source.extents[i].path)) {
                if (thispath != NULL)
1503 1504
                    virBufferAddLit(&buf, "    </device>\n");

1505
                virBufferAsprintf(&buf, "    <device path='%s'>\n",
1506
                                  def->source.extents[i].path);
1507 1508
            }

1509
            virBufferAsprintf(&buf,
1510 1511 1512
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1513 1514 1515
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1516
            virBufferAddLit(&buf, "    </device>\n");
1517
    }
1518
    virBufferAddLit(&buf, "  </source>\n");
1519

E
Eric Blake 已提交
1520
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1521
                      def->capacity);
E
Eric Blake 已提交
1522
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1523
                      def->allocation);
1524

1525
    if (virStorageVolTargetDefFormat(options, &buf,
1526 1527
                                     &def->target, "target") < 0)
        goto cleanup;
1528

1529
    if (def->backingStore.path &&
1530
        virStorageVolTargetDefFormat(options, &buf,
1531 1532
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1533 1534

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

1536
    if (virBufferError(&buf))
1537 1538
        goto no_memory;

1539
    return virBufferContentAndReset(&buf);
1540

1541
no_memory:
1542
    virReportOOMError();
1543
cleanup:
1544
    virBufferFreeAndReset(&buf);
1545 1546 1547 1548 1549
    return NULL;
}


virStoragePoolObjPtr
1550
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1551 1552
                            const unsigned char *uuid)
{
1553
    unsigned int i;
1554

1555
    for (i = 0; i < pools->count; i++) {
1556
        virStoragePoolObjLock(pools->objs[i]);
1557 1558
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1559 1560
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1561 1562 1563 1564 1565

    return NULL;
}

virStoragePoolObjPtr
1566
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1567 1568
                            const char *name)
{
1569
    unsigned int i;
1570

1571
    for (i = 0; i < pools->count; i++) {
1572
        virStoragePoolObjLock(pools->objs[i]);
1573 1574
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1575 1576
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1577 1578 1579 1580

    return NULL;
}

1581 1582
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
1583 1584
                                         virStoragePoolDefPtr def)
{
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
    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;
}

1597 1598 1599
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1600
    unsigned int i;
1601
    for (i = 0; i < pool->volumes.count; i++)
1602 1603 1604 1605
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1606 1607 1608 1609
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
1610 1611
                          const char *key)
{
1612
    unsigned int i;
1613

1614
    for (i = 0; i < pool->volumes.count; i++)
1615 1616
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1617 1618 1619 1620 1621 1622

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
1623 1624
                           const char *path)
{
1625
    unsigned int i;
1626

1627
    for (i = 0; i < pool->volumes.count; i++)
1628 1629
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1630 1631 1632 1633 1634 1635

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
1636 1637
                           const char *name)
{
1638
    unsigned int i;
1639

1640
    for (i = 0; i < pool->volumes.count; i++)
1641 1642
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1643 1644 1645 1646 1647

    return NULL;
}

virStoragePoolObjPtr
1648
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1649 1650
                           virStoragePoolDefPtr def)
{
1651 1652
    virStoragePoolObjPtr pool;

1653
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1654 1655 1656 1657
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1658
            virStoragePoolDefFree(pool->newDef);
1659 1660 1661 1662 1663
            pool->newDef = def;
        }
        return pool;
    }

1664
    if (VIR_ALLOC(pool) < 0) {
1665
        virReportOOMError();
1666 1667 1668
        return NULL;
    }

1669
    if (virMutexInit(&pool->lock) < 0) {
1670 1671
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("cannot initialize mutex"));
1672 1673 1674
        VIR_FREE(pool);
        return NULL;
    }
1675
    virStoragePoolObjLock(pool);
1676 1677 1678
    pool->active = 0;
    pool->def = def;

1679 1680
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1681
        virStoragePoolObjUnlock(pool);
1682
        virStoragePoolObjFree(pool);
1683
        virReportOOMError();
1684 1685 1686
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1687 1688 1689 1690 1691

    return pool;
}

static virStoragePoolObjPtr
1692
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1693 1694
                      const char *file,
                      const char *path,
1695 1696
                      const char *autostartLink)
{
1697 1698 1699
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1700
    if (!(def = virStoragePoolDefParseFile(path))) {
1701 1702 1703 1704
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1705
        virReportError(VIR_ERR_XML_ERROR,
1706 1707
                       _("Storage pool config filename '%s' does "
                         "not match pool name '%s'"),
1708
                       path, def->name);
1709 1710 1711 1712
        virStoragePoolDefFree(def);
        return NULL;
    }

1713
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1714 1715 1716 1717
        virStoragePoolDefFree(def);
        return NULL;
    }

1718
    VIR_FREE(pool->configFile);  /* for driver reload */
1719
    if (VIR_STRDUP(pool->configFile, path) < 0) {
1720 1721 1722
        virStoragePoolDefFree(def);
        return NULL;
    }
1723
    VIR_FREE(pool->autostartLink); /* for driver reload */
1724
    if (VIR_STRDUP(pool->autostartLink, autostartLink) < 0) {
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1737
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1738
                             const char *configDir,
1739 1740
                             const char *autostartDir)
{
1741 1742 1743
    DIR *dir;
    struct dirent *entry;

1744
    if (!(dir = opendir(configDir))) {
1745 1746
        if (errno == ENOENT)
            return 0;
1747
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1748
                             configDir);
1749 1750 1751 1752
        return -1;
    }

    while ((entry = readdir(dir))) {
1753 1754
        char *path;
        char *autostartLink;
1755
        virStoragePoolObjPtr pool;
1756 1757 1758 1759 1760 1761 1762

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

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

1763
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1764 1765
            continue;

1766 1767 1768
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1769 1770 1771
            continue;
        }

1772
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1773
                                     autostartLink);
1774 1775
        if (pool)
            virStoragePoolObjUnlock(pool);
1776 1777 1778

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1779 1780 1781 1782 1783 1784 1785 1786
    }

    closedir(dir);

    return 0;
}

int
1787
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1788
                         virStoragePoolObjPtr pool,
1789 1790
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1791
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1792
    char *xml;
1793
    int ret = -1;
1794 1795

    if (!pool->configFile) {
1796 1797
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1798 1799
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1800 1801 1802
            return -1;
        }

1803 1804
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1805 1806 1807
            return -1;
        }

1808 1809
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1810
            VIR_FREE(pool->configFile);
1811 1812 1813 1814
            return -1;
        }
    }

1815
    if (!(xml = virStoragePoolDefFormat(def))) {
1816 1817
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("failed to generate XML"));
1818 1819 1820
        return -1;
    }

J
Ján Tomko 已提交
1821 1822 1823 1824
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1825
    VIR_FREE(xml);
1826 1827 1828 1829 1830

    return ret;
}

int
1831 1832
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool)
{
1833
    if (!pool->configFile) {
1834 1835
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1836 1837 1838 1839
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1840 1841 1842
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1843 1844 1845 1846 1847
        return -1;
    }

    return 0;
}
1848

1849
virStoragePoolSourcePtr
1850
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1851 1852 1853
{
    virStoragePoolSourcePtr source;

1854
    if (VIR_REALLOC_N(list->sources, list->nsources + 1) < 0) {
1855
        virReportOOMError();
1856 1857 1858 1859 1860 1861 1862 1863 1864
        return NULL;
    }

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

    return source;
}

1865 1866
char *
virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1867
{
1868
    virStoragePoolOptionsPtr options;
1869
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1870 1871
    const char *type;
    int i;
1872

1873
    options = virStoragePoolOptionsForPoolType(def->type);
1874 1875 1876
    if (options == NULL)
        return NULL;

1877
    type = virStoragePoolTypeToString(def->type);
1878
    if (!type) {
1879 1880
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unexpected pool type"));
1881 1882 1883 1884
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1885 1886

    for (i = 0; i < def->nsources; i++) {
1887
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1888 1889
    }

1890 1891 1892 1893
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1894 1895

    return virBufferContentAndReset(&buf);
1896

1897
no_memory:
1898
    virReportOOMError();
1899
cleanup:
1900
    virBufferFreeAndReset(&buf);
1901
    return NULL;
1902
}
D
Daniel P. Berrange 已提交
1903 1904


1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
/*
 * 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
 */
1915 1916 1917 1918
int
virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                             virStoragePoolDefPtr def,
                             unsigned int check_active)
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
{
    int ret = -1;
    int dupPool = 0;
    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);
1931 1932 1933
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
1934 1935 1936 1937 1938 1939
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
1940 1941 1942
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
                goto cleanup;
            }
        }

        dupPool = 1;
    } 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);
1954 1955 1956
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
            goto cleanup;
        }
    }

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

1968 1969 1970
int
virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                  virStoragePoolDefPtr def)
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
{
    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;

1983 1984 1985 1986
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

1987 1988 1989 1990 1991 1992 1993 1994 1995
        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)) \
1996 1997
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
1998 1999 2000
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
            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;
            }
2014 2015 2016 2017
            break;
        case VIR_STORAGE_POOL_ISCSI:
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
2018 2019 2020 2021 2022 2023 2024 2025
                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;
2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
                    }
                }
                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);
2040 2041 2042

        if (matchpool)
            break;
2043 2044 2045
    }

    if (matchpool) {
2046 2047 2048
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2049 2050 2051 2052
        ret = -1;
    }
    return ret;
}
2053

2054 2055
void
virStoragePoolObjLock(virStoragePoolObjPtr obj)
2056
{
2057
    virMutexLock(&obj->lock);
2058 2059
}

2060 2061
void
virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
2062
{
2063
    virMutexUnlock(&obj->lock);
2064
}
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149

#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,
2150 2151
                                               poolobj->def->uuid,
                                               NULL, NULL))) {
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
                    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;
}