storage_conf.c 66.0 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

48 49
#define VIR_FROM_THIS VIR_FROM_STORAGE

50 51
#define DEFAULT_POOL_PERM_MODE 0755
#define DEFAULT_VOL_PERM_MODE  0600
52

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

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

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

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

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


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

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

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

97 98 99 100 101 102 103 104 105
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 {
106
    int defaultFormat;
107 108 109 110 111 112
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
};

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

typedef struct _virStoragePoolOptions virStoragePoolOptions;
typedef virStoragePoolOptions *virStoragePoolOptionsPtr;
struct _virStoragePoolOptions {
E
Eric Blake 已提交
125
    unsigned int flags;
126 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 150 151 152 153 154 155 156 157 158 159 160
static virStoragePoolTypeInfo poolTypeInfo[] = {
    { .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,
        },
    },
    { .poolType = VIR_STORAGE_POOL_DIR,
      .volOptions = {
161
            .defaultFormat = VIR_STORAGE_FILE_RAW,
E
Eric Blake 已提交
162
            .formatFromString = virStorageVolumeFormatFromString,
163
            .formatToString = virStorageFileFormatTypeToString,
164 165 166 167 168
        },
    },
    { .poolType = VIR_STORAGE_POOL_FS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
169
            .defaultFormat = VIR_STORAGE_POOL_FS_AUTO,
170 171 172 173
            .formatFromString = virStoragePoolFormatFileSystemTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemTypeToString,
        },
      .volOptions = {
174
            .defaultFormat = VIR_STORAGE_FILE_RAW,
E
Eric Blake 已提交
175
            .formatFromString = virStorageVolumeFormatFromString,
176
            .formatToString = virStorageFileFormatTypeToString,
177 178 179 180 181 182
        },
    },
    { .poolType = VIR_STORAGE_POOL_NETFS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                      VIR_STORAGE_POOL_SOURCE_DIR),
183
            .defaultFormat = VIR_STORAGE_POOL_NETFS_AUTO,
184 185 186 187
            .formatFromString = virStoragePoolFormatFileSystemNetTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemNetTypeToString,
        },
      .volOptions = {
188
            .defaultFormat = VIR_STORAGE_FILE_RAW,
E
Eric Blake 已提交
189
            .formatFromString = virStorageVolumeFormatFromString,
190
            .formatToString = virStorageFileFormatTypeToString,
191 192 193 194 195
        },
    },
    { .poolType = VIR_STORAGE_POOL_ISCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
D
David Allan 已提交
196 197
                      VIR_STORAGE_POOL_SOURCE_DEVICE |
                      VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN),
198 199 200 201 202
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
203 204 205 206 207 208 209 210
    { .poolType = VIR_STORAGE_POOL_SCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_ADAPTER),
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
211 212 213 214 215 216 217 218 219 220 221
    { .poolType = VIR_STORAGE_POOL_RBD,
      .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,
        }
    },
222 223 224 225 226 227 228 229 230 231 232
    { .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,
        }
    },
D
Dave Allan 已提交
233 234 235 236 237
    { .poolType = VIR_STORAGE_POOL_MPATH,
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
238 239 240 241 242 243 244 245
    { .poolType = VIR_STORAGE_POOL_DISK,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .defaultFormat = VIR_STORAGE_POOL_DISK_UNKNOWN,
            .formatFromString = virStoragePoolFormatDiskTypeFromString,
            .formatToString = virStoragePoolFormatDiskTypeToString,
        },
      .volOptions = {
246
            .defaultFormat = VIR_STORAGE_VOL_DISK_NONE,
247 248 249 250 251 252 253 254 255 256 257 258 259 260
            .formatFromString = virStorageVolFormatDiskTypeFromString,
            .formatToString = virStorageVolFormatDiskTypeToString,
        },
    }
};


static virStoragePoolTypeInfoPtr
virStoragePoolTypeInfoLookup(int type) {
    unsigned int i;
    for (i = 0; i < ARRAY_CARDINALITY(poolTypeInfo) ; i++)
        if (poolTypeInfo[i].poolType == type)
            return &poolTypeInfo[i];

261 262
    virReportError(VIR_ERR_INTERNAL_ERROR,
                   _("missing backend for pool type %d"), type);
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    return NULL;
}

static virStoragePoolOptionsPtr
virStoragePoolOptionsForPoolType(int type) {
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->poolOptions;
}

static virStorageVolOptionsPtr
virStorageVolOptionsForPoolType(int type) {
    virStoragePoolTypeInfoPtr backend = virStoragePoolTypeInfoLookup(type);
    if (backend == NULL)
        return NULL;
    return &backend->volOptions;
}


283 284 285
void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
286 287 288 289

    if (!def)
        return;

290 291
    VIR_FREE(def->name);
    VIR_FREE(def->key);
292 293

    for (i = 0 ; i < def->source.nextent ; i++) {
294
        VIR_FREE(def->source.extents[i].path);
295
    }
296
    VIR_FREE(def->source.extents);
297

298 299
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
300
    VIR_FREE(def->target.timestamps);
301
    virStorageEncryptionFree(def->target.encryption);
302 303
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
304
    VIR_FREE(def->backingStore.timestamps);
305
    virStorageEncryptionFree(def->backingStore.encryption);
306
    VIR_FREE(def);
307 308
}

309 310 311 312 313 314 315 316 317 318 319 320 321
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);
    }
}

322
void
323 324
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
325 326
    int i;

327
    if (!source)
328 329
        return;

330 331 332 333 334
    for (i = 0 ; i < source->nhost ; i++) {
        VIR_FREE(source->hosts[i].name);
    }
    VIR_FREE(source->hosts);

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

347 348 349
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
350
    }
351 352 353 354 355

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

358 359 360 361 362 363 364
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

365 366 367 368 369 370 371
void
virStoragePoolDefFree(virStoragePoolDefPtr def) {
    if (!def)
        return;

    VIR_FREE(def->name);

372
    virStoragePoolSourceClear(&def->source);
373

374 375 376
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
377 378 379 380 381
}


void
virStoragePoolObjFree(virStoragePoolObjPtr obj) {
382 383 384
    if (!obj)
        return;

385 386
    virStoragePoolObjClearVols(obj);

387 388
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
389

390 391
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
392 393 394

    virMutexDestroy(&obj->lock);

395
    VIR_FREE(obj);
396 397
}

398 399 400 401 402 403 404 405 406
void virStoragePoolObjListFree(virStoragePoolObjListPtr pools)
{
    unsigned int i;
    for (i = 0 ; i < pools->count ; i++)
        virStoragePoolObjFree(pools->objs[i]);
    VIR_FREE(pools->objs);
    pools->count = 0;
}

407
void
408
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
409 410
                        virStoragePoolObjPtr pool)
{
411
    unsigned int i;
412

413 414
    virStoragePoolObjUnlock(pool);

415
    for (i = 0 ; i < pools->count ; i++) {
416
        virStoragePoolObjLock(pools->objs[i]);
417
        if (pools->objs[i] == pool) {
418
            virStoragePoolObjUnlock(pools->objs[i]);
419
            virStoragePoolObjFree(pools->objs[i]);
420

421 422 423
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
424

425 426 427 428
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
429

430 431
            break;
        }
432
        virStoragePoolObjUnlock(pools->objs[i]);
433
    }
434 435 436 437
}


static int
438
virStoragePoolDefParseAuthChap(xmlXPathContextPtr ctxt,
439
                               virStoragePoolAuthChapPtr auth) {
440
    auth->login = virXPathString("string(./auth/@login)", ctxt);
441
    if (auth->login == NULL) {
442 443
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing auth host attribute"));
444 445 446
        return -1;
    }

447
    auth->passwd = virXPathString("string(./auth/@passwd)", ctxt);
448
    if (auth->passwd == NULL) {
449 450
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing auth passwd attribute"));
451 452 453 454 455 456
        return -1;
    }

    return 0;
}

457 458
static int
virStoragePoolDefParseAuthCephx(xmlXPathContextPtr ctxt,
P
Peter Krempa 已提交
459
                                virStoragePoolAuthCephxPtr auth) {
460 461 462
    char *uuid = NULL;
    auth->username = virXPathString("string(./auth/@username)", ctxt);
    if (auth->username == NULL) {
463 464
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing auth username attribute"));
465 466 467 468 469 470
        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) {
471 472
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing auth secret uuid or usage attribute"));
473 474 475
        return -1;
    }

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

    return 0;
}

495
static int
496
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
497 498 499 500 501 502 503 504
                             virStoragePoolSourcePtr source,
                             int pool_type,
                             xmlNodePtr node) {
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
    char *authType = NULL;
    int nsource, i;
    virStoragePoolOptionsPtr options;
505
    char *name = NULL;
506
    char *port = NULL;
507
    char *adapter_type = NULL;
508
    int n;
509 510 511 512 513 514 515 516

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

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

517
    source->name = virXPathString("string(./name)", ctxt);
518
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
519 520
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("missing mandatory 'name' field for RBD pool name"));
521 522
        goto cleanup;
    }
523 524

    if (options->formatFromString) {
525
        char *format = virXPathString("string(./format/@type)", ctxt);
526 527 528 529 530 531
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
532 533
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown pool format type %s"), format);
534 535 536 537 538 539
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

540 541 542
    if ((n = virXPathNodeSet("./host", ctxt, &nodeset)) < 0)
        goto cleanup;
    source->nhost = n;
543 544 545 546

    if (source->nhost) {
        if (VIR_ALLOC_N(source->hosts, source->nhost) < 0) {
            virReportOOMError();
547 548 549
            goto cleanup;
        }

550 551 552
        for (i = 0 ; i < source->nhost ; i++) {
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
553 554
                virReportError(VIR_ERR_XML_ERROR,
                               "%s", _("missing storage pool host name"));
555 556 557 558 559 560 561
                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) {
562 563 564
                    virReportError(VIR_ERR_XML_ERROR,
                                   _("Invalid port number: %s"),
                                   port);
565 566 567 568 569
                    goto cleanup;
                }
            }
        }
    }
570

571
    VIR_FREE(nodeset);
572
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
573

574
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
575 576 577
    if (nsource < 0)
        goto cleanup;

578 579 580
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
581
            virReportOOMError();
582 583 584 585
            goto cleanup;
        }

        for (i = 0 ; i < nsource ; i++) {
586
            char *path = virXMLPropString(nodeset[i], "path");
587 588
            if (path == NULL) {
                VIR_FREE(nodeset);
589 590
                virReportError(VIR_ERR_XML_ERROR,
                               "%s", _("missing storage pool source device path"));
591 592
                goto cleanup;
            }
593
            source->devices[i].path = path;
594 595 596 597
        }
        source->ndevice = nsource;
    }

598
    source->dir = virXPathString("string(./dir/@path)", ctxt);
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 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

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

650
    authType = virXPathString("string(./auth/@type)", ctxt);
651 652 653 654 655
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
656 657
        } else if (STREQ(authType, "ceph")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CEPHX;
658
        } else {
659 660 661
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown auth type '%s'"),
                           (const char *)authType);
662 663 664 665 666
            goto cleanup;
        }
    }

    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
667
        if (virStoragePoolDefParseAuthChap(ctxt, &source->auth.chap) < 0)
668 669 670
            goto cleanup;
    }

671 672 673 674 675
    if (source->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        if (virStoragePoolDefParseAuthCephx(ctxt, &source->auth.cephx) < 0)
            goto cleanup;
    }

676 677 678
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

679 680 681 682
    ret = 0;
cleanup:
    ctxt->node = relnode;

683
    VIR_FREE(port);
684 685
    VIR_FREE(authType);
    VIR_FREE(nodeset);
686
    VIR_FREE(adapter_type);
687 688
    return ret;
}
689

690
virStoragePoolSourcePtr
691
virStoragePoolDefParseSourceString(const char *srcSpec,
692 693 694 695 696 697 698
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

699 700 701
    if (!(doc = virXMLParseStringCtxt(srcSpec,
                                      _("(storage_source_specification)"),
                                      &xpath_ctxt)))
702 703 704
        goto cleanup;

    if (VIR_ALLOC(def) < 0) {
705
        virReportOOMError();
706 707 708
        goto cleanup;
    }

709
    if (!(node = virXPathNode("/source", xpath_ctxt))) {
710 711
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("root element was not source"));
712 713 714
        goto cleanup;
    }

715
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
716 717 718 719 720 721
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
722
    virStoragePoolSourceFree(def);
723 724 725 726 727
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
728
static int
729
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
730 731 732
                        virStoragePermsPtr perms,
                        const char *permxpath,
                        int defaultmode) {
733 734
    char *mode;
    long v;
735 736 737
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
738

739
    node = virXPathNode(permxpath, ctxt);
740 741 742
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
P
Philipp Hahn 已提交
743 744
        perms->uid = (uid_t) -1;
        perms->gid = (gid_t) -1;
745 746 747 748 749 750 751
        perms->label = NULL;
        return 0;
    }

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

752
    mode = virXPathString("string(./mode)", ctxt);
753
    if (!mode) {
754
        perms->mode = defaultmode;
755
    } else {
756 757 758
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
759
            VIR_FREE(mode);
760 761
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("malformed octal mode"));
762
            goto error;
763
        }
764
        perms->mode = tmp;
765
        VIR_FREE(mode);
766 767
    }

768
    if (virXPathNode("./owner", ctxt) == NULL) {
P
Philipp Hahn 已提交
769
        perms->uid = (uid_t) -1;
770
    } else {
771
        if (virXPathLong("number(./owner)", ctxt, &v) < 0) {
772 773
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("malformed owner element"));
774
            goto error;
775 776 777 778
        }
        perms->uid = (int)v;
    }

779
    if (virXPathNode("./group", ctxt) == NULL) {
P
Philipp Hahn 已提交
780
        perms->gid = (gid_t) -1;
781
    } else {
782
        if (virXPathLong("number(./group)", ctxt, &v) < 0) {
783 784
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("malformed group element"));
785
            goto error;
786 787 788 789 790
        }
        perms->gid = (int)v;
    }

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

793 794 795 796
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
797 798 799
}

static virStoragePoolDefPtr
800
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt) {
801
    virStoragePoolOptionsPtr options;
802
    virStoragePoolDefPtr ret;
803
    xmlNodePtr source_node;
804
    char *type = NULL;
805
    char *uuid = NULL;
806
    char *tmppath;
807

808
    if (VIR_ALLOC(ret) < 0) {
809
        virReportOOMError();
810
        return NULL;
811
    }
812

813
    type = virXPathString("string(./@type)", ctxt);
814
    if ((ret->type = virStoragePoolTypeFromString((const char *)type)) < 0) {
815 816
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage pool type %s"), (const char*)type);
817
        goto cleanup;
818 819
    }

820 821 822
    xmlFree(type);
    type = NULL;

823
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
824 825 826
        goto cleanup;
    }

827
    source_node = virXPathNode("./source", ctxt);
828
    if (source_node) {
829
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
830 831 832 833
                                         source_node) < 0)
            goto cleanup;
    }

834
    ret->name = virXPathString("string(./name)", ctxt);
835
    if (ret->name == NULL &&
836
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
837
        ret->name = ret->source.name;
838
    if (ret->name == NULL) {
839 840
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing pool source name element"));
841 842 843
        goto cleanup;
    }

844
    uuid = virXPathString("string(./uuid)", ctxt);
845 846
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
847 848
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("unable to generate uuid"));
849 850 851 852
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
853 854
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("malformed uuid element"));
855 856
            goto cleanup;
        }
857
        VIR_FREE(uuid);
858 859
    }

860
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
861
        if (!ret->source.nhost) {
862 863 864
            virReportError(VIR_ERR_XML_ERROR,
                           "%s",
                           _("missing storage pool source host name"));
865 866 867 868
            goto cleanup;
        }
    }

869
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
870
        if (!ret->source.dir) {
871 872
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("missing storage pool source path"));
873 874 875
            goto cleanup;
        }
    }
876
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
877 878 879
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
            ret->source.name = strdup(ret->name);
880
            if (ret->source.name == NULL) {
881
                virReportOOMError();
882 883
                goto cleanup;
            }
884 885
        }
    }
886

887
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
888 889 890
        if (!ret->source.adapter.type) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("missing storage pool source adapter"));
891 892
            goto cleanup;
        }
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914

        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'"));
                goto cleanup;
            }

            if (!virValidateWWN(ret->source.adapter.data.fchost.wwnn) ||
                !virValidateWWN(ret->source.adapter.data.fchost.wwpn))
                goto cleanup;
        } else if (ret->source.adapter.type ==
                   VIR_STORAGE_POOL_SOURCE_ADAPTER_TYPE_SCSI_HOST) {
            if (!ret->source.adapter.data.name) {
                virReportError(VIR_ERR_XML_ERROR,
                               "%s", _("missing storage pool source adapter name"));
                goto cleanup;
            }
        }
915
    }
916

917 918 919
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
920 921
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("missing storage pool source device name"));
922 923 924 925
            goto cleanup;
        }
    }

926 927 928 929
    /* When we are working with a virtual disk we can skip the target
     * path and permissions */
    if (!(options->flags & VIR_STORAGE_POOL_SOURCE_NETWORK)) {
        if ((tmppath = virXPathString("string(./target/path)", ctxt)) == NULL) {
930 931
            virReportError(VIR_ERR_XML_ERROR,
                           "%s", _("missing storage pool target path"));
932 933 934 935 936 937
            goto cleanup;
        }
        ret->target.path = virFileSanitizePath(tmppath);
        VIR_FREE(tmppath);
        if (!ret->target.path)
            goto cleanup;
938

939
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
940 941
                                    "./target/permissions",
                                    DEFAULT_POOL_PERM_MODE) < 0)
942 943
            goto cleanup;
    }
944 945 946 947

    return ret;

 cleanup:
948
    VIR_FREE(uuid);
949
    xmlFree(type);
950 951 952 953 954
    virStoragePoolDefFree(ret);
    return NULL;
}

virStoragePoolDefPtr
955
virStoragePoolDefParseNode(xmlDocPtr xml,
956 957 958 959 960
                           xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "pool")) {
961 962
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("unknown root element for storage pool"));
963 964 965 966 967
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
968
        virReportOOMError();
969 970 971 972
        goto cleanup;
    }

    ctxt->node = root;
973
    def = virStoragePoolDefParseXML(ctxt);
974 975 976 977 978 979
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
980
virStoragePoolDefParse(const char *xmlStr,
981 982
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
983
    xmlDocPtr xml;
984

985
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
986 987
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
988 989
    }

990 991 992
    return ret;
}

993
virStoragePoolDefPtr
994
virStoragePoolDefParseString(const char *xmlStr)
995
{
996
    return virStoragePoolDefParse(xmlStr, NULL);
997 998 999
}

virStoragePoolDefPtr
1000
virStoragePoolDefParseFile(const char *filename)
1001
{
1002
    return virStoragePoolDefParse(NULL, filename);
1003 1004
}

1005
static int
1006
virStoragePoolSourceFormat(virBufferPtr buf,
1007
                           virStoragePoolOptionsPtr options,
1008 1009 1010
                           virStoragePoolSourcePtr src)
{
    int i, j;
1011
    char uuid[VIR_UUID_STRING_BUFLEN];
1012 1013

    virBufferAddLit(buf,"  <source>\n");
1014 1015
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
E
Eric Blake 已提交
1016
            virBufferAsprintf(buf, "    <host name='%s'", src->hosts[i].name);
1017 1018 1019 1020
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
1021
    }
1022

1023
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
1024 1025 1026
        src->ndevice) {
        for (i = 0 ; i < src->ndevice ; i++) {
            if (src->devices[i].nfreeExtent) {
1027
                virBufferAsprintf(buf,"    <device path='%s'>\n",
1028 1029
                                  src->devices[i].path);
                for (j = 0 ; j < src->devices[i].nfreeExtent ; j++) {
1030
                    virBufferAsprintf(buf, "    <freeExtent start='%llu' end='%llu'/>\n",
1031 1032 1033 1034 1035 1036
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
                virBufferAddLit(buf,"    </device>\n");
            }
            else
1037
                virBufferAsprintf(buf, "    <device path='%s'/>\n",
1038 1039 1040
                                  src->devices[i].path);
        }
    }
1041
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
1042
        src->dir)
1043
        virBufferAsprintf(buf,"    <dir path='%s'/>\n", src->dir);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    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);
        }
    }
1061
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
1062
        src->name)
1063
        virBufferAsprintf(buf,"    <name>%s</name>\n", src->name);
1064

D
David Allan 已提交
1065 1066 1067 1068 1069 1070 1071
    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");
    }

1072 1073 1074
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
1075 1076 1077
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown pool format number %d"),
                           src->format);
1078 1079
            return -1;
        }
1080
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
1081 1082 1083 1084
    }


    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
1085
        virBufferAsprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
1086 1087
                          src->auth.chap.login,
                          src->auth.chap.passwd);
1088

1089 1090 1091 1092
    if (src->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        virBufferAsprintf(buf,"    <auth username='%s' type='ceph'>\n",
                          src->auth.cephx.username);

1093
        virBufferAddLit(buf,"      <secret");
1094
        if (src->auth.cephx.secret.uuidUsable) {
1095 1096 1097 1098 1099 1100 1101
            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);
        }
1102
        virBufferAddLit(buf,"/>\n");
1103

1104
        virBufferAddLit(buf,"    </auth>\n");
1105 1106
    }

1107 1108 1109 1110 1111 1112 1113 1114
    if (src->vendor != NULL) {
        virBufferEscapeString(buf,"    <vendor name='%s'/>\n", src->vendor);
    }

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

1115 1116 1117 1118 1119
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

1120 1121

char *
1122
virStoragePoolDefFormat(virStoragePoolDefPtr def) {
1123
    virStoragePoolOptionsPtr options;
1124
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1125 1126 1127
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

1128
    options = virStoragePoolOptionsForPoolType(def->type);
1129 1130 1131
    if (options == NULL)
        return NULL;

1132
    type = virStoragePoolTypeToString(def->type);
1133
    if (!type) {
1134 1135
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unexpected pool type"));
1136 1137
        goto cleanup;
    }
1138 1139
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
    virBufferAsprintf(&buf,"  <name>%s</name>\n", def->name);
1140 1141

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

E
Eric Blake 已提交
1144
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1145
                      def->capacity);
E
Eric Blake 已提交
1146
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1147
                      def->allocation);
E
Eric Blake 已提交
1148
    virBufferAsprintf(&buf,"  <available unit='bytes'>%llu</available>\n",
1149
                      def->available);
1150

1151
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1152
        goto cleanup;
1153

1154
    /* RBD and Sheepdog devices are not local block devs nor files, so it doesn't
1155
     * have a target */
1156
    if (def->type != VIR_STORAGE_POOL_RBD && def->type != VIR_STORAGE_POOL_SHEEPDOG) {
1157
        virBufferAddLit(&buf,"  <target>\n");
1158

1159 1160
        if (def->target.path)
            virBufferAsprintf(&buf,"    <path>%s</path>\n", def->target.path);
1161

1162 1163 1164
        virBufferAddLit(&buf,"    <permissions>\n");
        virBufferAsprintf(&buf,"      <mode>0%o</mode>\n",
                          def->target.perms.mode);
1165 1166 1167 1168
        virBufferAsprintf(&buf,"      <owner>%d</owner>\n",
                          (int) def->target.perms.uid);
        virBufferAsprintf(&buf,"      <group>%d</group>\n",
                          (int) def->target.perms.gid);
1169

1170 1171 1172
        if (def->target.perms.label)
            virBufferAsprintf(&buf,"      <label>%s</label>\n",
                            def->target.perms.label);
1173

1174 1175 1176
        virBufferAddLit(&buf,"    </permissions>\n");
        virBufferAddLit(&buf,"  </target>\n");
    }
1177
    virBufferAddLit(&buf,"</pool>\n");
1178

1179
    if (virBufferError(&buf))
1180 1181
        goto no_memory;

1182
    return virBufferContentAndReset(&buf);
1183 1184

 no_memory:
1185
    virReportOOMError();
1186
 cleanup:
1187
    virBufferFreeAndReset(&buf);
1188 1189 1190 1191 1192
    return NULL;
}


static int
1193
virStorageSize(const char *unit,
1194
               const char *val,
1195 1196 1197
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1198 1199
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("malformed capacity element"));
1200 1201
        return -1;
    }
1202 1203 1204 1205
    /* 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;
1206 1207 1208 1209 1210

    return 0;
}

static virStorageVolDefPtr
1211
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1212
                         xmlXPathContextPtr ctxt) {
1213
    virStorageVolDefPtr ret;
1214
    virStorageVolOptionsPtr options;
1215 1216 1217
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1218
    xmlNodePtr node;
1219

1220
    options = virStorageVolOptionsForPoolType(pool->type);
1221 1222 1223
    if (options == NULL)
        return NULL;

1224
    if (VIR_ALLOC(ret) < 0) {
1225
        virReportOOMError();
1226
        return NULL;
1227
    }
1228

1229
    ret->name = virXPathString("string(./name)", ctxt);
1230
    if (ret->name == NULL) {
1231 1232
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing volume name element"));
1233 1234 1235
        goto cleanup;
    }

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

1239 1240
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1241
    if (capacity == NULL) {
1242 1243
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("missing capacity element"));
1244 1245
        goto cleanup;
    }
1246
    if (virStorageSize(unit, capacity, &ret->capacity) < 0)
1247
        goto cleanup;
1248 1249
    VIR_FREE(capacity);
    VIR_FREE(unit);
1250

1251
    allocation = virXPathString("string(./allocation)", ctxt);
1252
    if (allocation) {
1253
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1254
        if (virStorageSize(unit, allocation, &ret->allocation) < 0)
1255
            goto cleanup;
1256 1257
        VIR_FREE(allocation);
        VIR_FREE(unit);
1258 1259 1260 1261
    } else {
        ret->allocation = ret->capacity;
    }

1262
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1263
    if (options->formatFromString) {
1264
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1265 1266 1267 1268 1269 1270
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1271 1272
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1273
            VIR_FREE(format);
1274 1275
            goto cleanup;
        }
1276
        VIR_FREE(format);
1277 1278
    }

1279
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
1280 1281
                                "./target/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1282 1283
        goto cleanup;

1284
    node = virXPathNode("./target/encryption", ctxt);
1285
    if (node != NULL) {
1286
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1287 1288 1289 1290 1291
                                                               node);
        if (ret->target.encryption == NULL)
            goto cleanup;
    }

1292 1293


1294
    ret->backingStore.path = virXPathString("string(./backingStore/path)", ctxt);
1295
    if (options->formatFromString) {
1296
        char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
1297 1298 1299 1300 1301 1302
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
1303 1304
            virReportError(VIR_ERR_XML_ERROR,
                           _("unknown volume format type %s"), format);
1305 1306 1307 1308 1309 1310
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

1311
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1312 1313
                                "./backingStore/permissions",
                                DEFAULT_VOL_PERM_MODE) < 0)
1314 1315
        goto cleanup;

1316 1317 1318
    return ret;

 cleanup:
1319 1320 1321
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1322 1323 1324 1325 1326
    virStorageVolDefFree(ret);
    return NULL;
}

virStorageVolDefPtr
1327
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1328 1329 1330 1331 1332 1333
                          xmlDocPtr xml,
                          xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "volume")) {
1334 1335
        virReportError(VIR_ERR_XML_ERROR,
                       "%s", _("unknown root element for storage vol"));
1336 1337 1338 1339 1340
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1341
        virReportOOMError();
1342 1343 1344 1345
        goto cleanup;
    }

    ctxt->node = root;
1346
    def = virStorageVolDefParseXML(pool, ctxt);
1347 1348 1349 1350 1351 1352
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1353
virStorageVolDefParse(virStoragePoolDefPtr pool,
1354 1355 1356
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1357
    xmlDocPtr xml;
1358

1359
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1360 1361
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1362 1363 1364 1365 1366
    }

    return ret;
}

1367
virStorageVolDefPtr
1368
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1369 1370
                            const char *xmlStr)
{
1371
    return virStorageVolDefParse(pool, xmlStr, NULL);
1372 1373 1374
}

virStorageVolDefPtr
1375
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1376 1377
                          const char *filename)
{
1378
    return virStorageVolDefParse(pool, NULL, filename);
1379
}
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
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);
}

1394
static int
1395
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1396 1397 1398
                             virBufferPtr buf,
                             virStorageVolTargetPtr def,
                             const char *type) {
1399
    virBufferAsprintf(buf, "  <%s>\n", type);
1400 1401

    if (def->path)
1402
        virBufferAsprintf(buf,"    <path>%s</path>\n", def->path);
1403 1404 1405 1406

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1407 1408 1409
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unknown volume format number %d"),
                           def->format);
1410 1411
            return -1;
        }
1412
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
1413 1414 1415
    }

    virBufferAddLit(buf,"    <permissions>\n");
1416
    virBufferAsprintf(buf,"      <mode>0%o</mode>\n",
1417
                      def->perms.mode);
E
Eric Blake 已提交
1418 1419 1420 1421
    virBufferAsprintf(buf,"      <owner>%u</owner>\n",
                      (unsigned int) def->perms.uid);
    virBufferAsprintf(buf,"      <group>%u</group>\n",
                      (unsigned int) def->perms.gid);
1422 1423 1424


    if (def->perms.label)
1425
        virBufferAsprintf(buf,"      <label>%s</label>\n",
1426 1427 1428 1429
                          def->perms.label);

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

1430 1431 1432 1433 1434 1435 1436 1437 1438
    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");
    }

1439 1440 1441 1442 1443 1444
    if (def->encryption) {
        virBufferAdjustIndent(buf, 4);
        if (virStorageEncryptionFormat(buf, def->encryption) < 0)
            return -1;
        virBufferAdjustIndent(buf, -4);
    }
1445

1446
    virBufferAsprintf(buf, "  </%s>\n", type);
1447 1448 1449

    return 0;
}
1450 1451

char *
1452
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1453
                       virStorageVolDefPtr def) {
1454
    virStorageVolOptionsPtr options;
1455
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1456

1457
    options = virStorageVolOptionsForPoolType(pool->type);
1458 1459 1460
    if (options == NULL)
        return NULL;

1461
    virBufferAddLit(&buf, "<volume>\n");
1462
    virBufferAsprintf(&buf,"  <name>%s</name>\n", def->name);
1463
    virBufferAsprintf(&buf,"  <key>%s</key>\n", def->key ? def->key : "(null)");
1464
    virBufferAddLit(&buf, "  <source>\n");
1465 1466 1467 1468 1469 1470 1471 1472

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

1475
                virBufferAsprintf(&buf, "    <device path='%s'>\n",
1476
                                  def->source.extents[i].path);
1477 1478
            }

1479
            virBufferAsprintf(&buf,
1480 1481 1482
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1483 1484 1485
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1486
            virBufferAddLit(&buf, "    </device>\n");
1487
    }
1488
    virBufferAddLit(&buf, "  </source>\n");
1489

E
Eric Blake 已提交
1490
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1491
                      def->capacity);
E
Eric Blake 已提交
1492
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1493
                      def->allocation);
1494

1495
    if (virStorageVolTargetDefFormat(options, &buf,
1496 1497
                                     &def->target, "target") < 0)
        goto cleanup;
1498

1499
    if (def->backingStore.path &&
1500
        virStorageVolTargetDefFormat(options, &buf,
1501 1502
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1503 1504

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

1506
    if (virBufferError(&buf))
1507 1508
        goto no_memory;

1509
    return virBufferContentAndReset(&buf);
1510 1511

 no_memory:
1512
    virReportOOMError();
1513
 cleanup:
1514
    virBufferFreeAndReset(&buf);
1515 1516 1517 1518 1519
    return NULL;
}


virStoragePoolObjPtr
1520
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1521
                            const unsigned char *uuid) {
1522
    unsigned int i;
1523

1524 1525
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1526 1527
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1528 1529
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1530 1531 1532 1533 1534

    return NULL;
}

virStoragePoolObjPtr
1535
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1536
                            const char *name) {
1537
    unsigned int i;
1538

1539 1540
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1541 1542
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1543 1544
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1545 1546 1547 1548

    return NULL;
}

1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
virStoragePoolObjPtr
virStoragePoolSourceFindDuplicateDevices(virStoragePoolObjPtr pool,
                                         virStoragePoolDefPtr def) {
    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;
}

1564 1565 1566
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1567 1568 1569 1570 1571 1572
    unsigned int i;
    for (i = 0 ; i < pool->volumes.count ; i++)
        virStorageVolDefFree(pool->volumes.objs[i]);

    VIR_FREE(pool->volumes.objs);
    pool->volumes.count = 0;
1573 1574 1575 1576 1577
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
                          const char *key) {
1578
    unsigned int i;
1579

1580 1581 1582
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1583 1584 1585 1586 1587 1588 1589

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
                           const char *path) {
1590
    unsigned int i;
1591

1592 1593 1594
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1595 1596 1597 1598 1599 1600 1601

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
                           const char *name) {
1602
    unsigned int i;
1603

1604 1605 1606
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1607 1608 1609 1610 1611

    return NULL;
}

virStoragePoolObjPtr
1612
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1613 1614 1615
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1616
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1617 1618 1619 1620
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1621
            virStoragePoolDefFree(pool->newDef);
1622 1623 1624 1625 1626
            pool->newDef = def;
        }
        return pool;
    }

1627
    if (VIR_ALLOC(pool) < 0) {
1628
        virReportOOMError();
1629 1630 1631
        return NULL;
    }

1632
    if (virMutexInit(&pool->lock) < 0) {
1633 1634
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("cannot initialize mutex"));
1635 1636 1637
        VIR_FREE(pool);
        return NULL;
    }
1638
    virStoragePoolObjLock(pool);
1639 1640 1641
    pool->active = 0;
    pool->def = def;

1642 1643
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1644
        virStoragePoolObjUnlock(pool);
1645
        virStoragePoolObjFree(pool);
1646
        virReportOOMError();
1647 1648 1649
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1650 1651 1652 1653 1654

    return pool;
}

static virStoragePoolObjPtr
1655
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1656 1657 1658 1659 1660 1661
                      const char *file,
                      const char *path,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1662
    if (!(def = virStoragePoolDefParseFile(path))) {
1663 1664 1665 1666
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1667 1668 1669
        virReportError(VIR_ERR_XML_ERROR,
                       _("Storage pool config filename '%s' does not match pool name '%s'"),
                       path, def->name);
1670 1671 1672 1673
        virStoragePoolDefFree(def);
        return NULL;
    }

1674
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1675 1676 1677 1678
        virStoragePoolDefFree(def);
        return NULL;
    }

1679
    VIR_FREE(pool->configFile);  /* for driver reload */
1680 1681
    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
1682
        virReportOOMError();
1683 1684 1685
        virStoragePoolDefFree(def);
        return NULL;
    }
1686
    VIR_FREE(pool->autostartLink); /* for driver reload */
1687 1688
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
1689
        virReportOOMError();
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1702
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1703 1704
                             const char *configDir,
                             const char *autostartDir) {
1705 1706 1707
    DIR *dir;
    struct dirent *entry;

1708
    if (!(dir = opendir(configDir))) {
1709 1710
        if (errno == ENOENT)
            return 0;
1711
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1712
                             configDir);
1713 1714 1715 1716
        return -1;
    }

    while ((entry = readdir(dir))) {
1717 1718
        char *path;
        char *autostartLink;
1719
        virStoragePoolObjPtr pool;
1720 1721 1722 1723 1724 1725 1726

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

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

1727
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1728 1729
            continue;

1730 1731 1732
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1733 1734 1735
            continue;
        }

1736
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1737
                                     autostartLink);
1738 1739
        if (pool)
            virStoragePoolObjUnlock(pool);
1740 1741 1742

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1743 1744 1745 1746 1747 1748 1749 1750
    }

    closedir(dir);

    return 0;
}

int
1751
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1752
                         virStoragePoolObjPtr pool,
1753 1754
                         virStoragePoolDefPtr def)
{
J
Ján Tomko 已提交
1755
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1756
    char *xml;
1757
    int ret = -1;
1758 1759

    if (!pool->configFile) {
1760 1761
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1762 1763
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1764 1765 1766
            return -1;
        }

1767 1768
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1769 1770 1771
            return -1;
        }

1772 1773
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1774
            VIR_FREE(pool->configFile);
1775 1776 1777 1778
            return -1;
        }
    }

1779
    if (!(xml = virStoragePoolDefFormat(def))) {
1780 1781
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("failed to generate XML"));
1782 1783 1784
        return -1;
    }

J
Ján Tomko 已提交
1785 1786 1787 1788
    virUUIDFormat(def->uuid, uuidstr);
    ret = virXMLSaveFile(pool->configFile,
                         virXMLPickShellSafeComment(def->name, uuidstr),
                         "pool-edit", xml);
1789
    VIR_FREE(xml);
1790 1791 1792 1793 1794

    return ret;
}

int
1795
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool) {
1796
    if (!pool->configFile) {
1797 1798
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("no config file for %s"), pool->def->name);
1799 1800 1801 1802
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1803 1804 1805
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot remove config for %s"),
                       pool->def->name);
1806 1807 1808 1809 1810
        return -1;
    }

    return 0;
}
1811

1812
virStoragePoolSourcePtr
1813
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1814 1815 1816 1817
{
    virStoragePoolSourcePtr source;

    if (VIR_REALLOC_N(list->sources, list->nsources+1) < 0) {
1818
        virReportOOMError();
1819 1820 1821 1822 1823 1824 1825 1826 1827
        return NULL;
    }

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

    return source;
}

1828
char *virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1829
{
1830
    virStoragePoolOptionsPtr options;
1831
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1832 1833
    const char *type;
    int i;
1834

1835
    options = virStoragePoolOptionsForPoolType(def->type);
1836 1837 1838
    if (options == NULL)
        return NULL;

1839
    type = virStoragePoolTypeToString(def->type);
1840
    if (!type) {
1841 1842
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("unexpected pool type"));
1843 1844 1845 1846
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1847 1848

    for (i = 0; i < def->nsources; i++) {
1849
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1850 1851
    }

1852 1853 1854 1855
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1856 1857

    return virBufferContentAndReset(&buf);
1858 1859

 no_memory:
1860
    virReportOOMError();
1861
 cleanup:
1862
    virBufferFreeAndReset(&buf);
1863
    return NULL;
1864
}
D
Daniel P. Berrange 已提交
1865 1866


1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
/*
 * 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
 */
int virStoragePoolObjIsDuplicate(virStoragePoolObjListPtr pools,
                                 virStoragePoolDefPtr def,
                                 unsigned int check_active)
{
    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);
1892 1893 1894
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' is already defined with uuid %s"),
                           pool->def->name, uuidstr);
1895 1896 1897 1898 1899 1900
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
1901 1902 1903
                virReportError(VIR_ERR_OPERATION_INVALID,
                               _("pool is already active as '%s'"),
                               pool->def->name);
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
                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);
1915 1916 1917
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("pool '%s' already exists with uuid %s"),
                           def->name, uuidstr);
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
            goto cleanup;
        }
    }

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

1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942
int virStoragePoolSourceFindDuplicate(virStoragePoolObjListPtr pools,
                                      virStoragePoolDefPtr def)
{
    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;

1943 1944 1945 1946
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

1947 1948 1949 1950 1951 1952 1953 1954 1955
        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)) \
1956 1957
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
1958 1959 1960
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973
            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;
            }
1974 1975 1976 1977 1978
            break;
        case VIR_STORAGE_POOL_ISCSI:
        {
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
1979 1980 1981 1982 1983 1984 1985 1986
                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;
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
                    }
                }
                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);
2002 2003 2004

        if (matchpool)
            break;
2005 2006 2007
    }

    if (matchpool) {
2008 2009 2010
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Storage source conflict with pool: '%s'"),
                       matchpool->def->name);
2011 2012 2013 2014
        ret = -1;
    }
    return ret;
}
2015

2016 2017
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
2018
    virMutexLock(&obj->lock);
2019 2020 2021 2022
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
2023
    virMutexUnlock(&obj->lock);
2024
}
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 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

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