storage_conf.c 55.3 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 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * 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 "virterror_internal.h"
37
#include "datatypes.h"
38
#include "storage_conf.h"
39
#include "storage_file.h"
40

41 42 43 44
#include "xml.h"
#include "uuid.h"
#include "buf.h"
#include "util.h"
45
#include "memory.h"
E
Eric Blake 已提交
46
#include "virfile.h"
47

48 49
#define VIR_FROM_THIS VIR_FROM_STORAGE

50

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

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
65
              "auto", "nfs", "glusterfs", "cifs")
66 67 68 69

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

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
74
              "unknown", "lvm2")
75 76 77 78 79 80 81


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

84 85
VIR_ENUM_IMPL(virStoragePartedFsType,
              VIR_STORAGE_PARTED_FS_TYPE_LAST,
86
              "ext2", "ext2", "fat16",
87 88 89
              "fat32", "linux-swap",
              "ext2", "ext2",
              "extended")
90 91 92 93 94 95 96 97 98 99

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 {
100
    int defaultFormat;
101 102 103 104 105 106
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
};

/* Flags to indicate mandatory components in the pool source */
enum {
D
David Allan 已提交
107 108 109 110 111 112
    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),
113
    VIR_STORAGE_POOL_SOURCE_NETWORK         = (1<<6),
114 115 116 117 118 119 120
};



typedef struct _virStoragePoolOptions virStoragePoolOptions;
typedef virStoragePoolOptions *virStoragePoolOptionsPtr;
struct _virStoragePoolOptions {
E
Eric Blake 已提交
121
    unsigned int flags;
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    int defaultFormat;
    virStoragePoolFormatToString formatToString;
    virStoragePoolFormatFromString formatFromString;
};

typedef struct _virStoragePoolTypeInfo virStoragePoolTypeInfo;
typedef virStoragePoolTypeInfo *virStoragePoolTypeInfoPtr;

struct _virStoragePoolTypeInfo {
    int poolType;
    virStoragePoolOptions poolOptions;
    virStorageVolOptions volOptions;
};

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 = {
148 149 150
            .defaultFormat = VIR_STORAGE_FILE_RAW,
            .formatFromString = virStorageFileFormatTypeFromString,
            .formatToString = virStorageFileFormatTypeToString,
151 152 153 154 155
        },
    },
    { .poolType = VIR_STORAGE_POOL_FS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
156
            .defaultFormat = VIR_STORAGE_POOL_FS_AUTO,
157 158 159 160
            .formatFromString = virStoragePoolFormatFileSystemTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemTypeToString,
        },
      .volOptions = {
161 162 163
            .defaultFormat = VIR_STORAGE_FILE_RAW,
            .formatFromString = virStorageFileFormatTypeFromString,
            .formatToString = virStorageFileFormatTypeToString,
164 165 166 167 168 169
        },
    },
    { .poolType = VIR_STORAGE_POOL_NETFS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                      VIR_STORAGE_POOL_SOURCE_DIR),
170
            .defaultFormat = VIR_STORAGE_POOL_NETFS_AUTO,
171 172 173 174
            .formatFromString = virStoragePoolFormatFileSystemNetTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemNetTypeToString,
        },
      .volOptions = {
175 176 177
            .defaultFormat = VIR_STORAGE_FILE_RAW,
            .formatFromString = virStorageFileFormatTypeFromString,
            .formatToString = virStorageFileFormatTypeToString,
178 179 180 181 182
        },
    },
    { .poolType = VIR_STORAGE_POOL_ISCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
D
David Allan 已提交
183 184
                      VIR_STORAGE_POOL_SOURCE_DEVICE |
                      VIR_STORAGE_POOL_SOURCE_INITIATOR_IQN),
185 186 187 188 189
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
190 191 192 193 194 195 196 197
    { .poolType = VIR_STORAGE_POOL_SCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_ADAPTER),
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
198 199 200 201 202 203 204 205 206 207 208
    { .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,
        }
    },
D
Dave Allan 已提交
209 210 211 212 213
    { .poolType = VIR_STORAGE_POOL_MPATH,
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
214 215 216 217 218 219 220 221
    { .poolType = VIR_STORAGE_POOL_DISK,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .defaultFormat = VIR_STORAGE_POOL_DISK_UNKNOWN,
            .formatFromString = virStoragePoolFormatDiskTypeFromString,
            .formatToString = virStoragePoolFormatDiskTypeToString,
        },
      .volOptions = {
222
            .defaultFormat = VIR_STORAGE_VOL_DISK_NONE,
223 224 225 226 227 228 229 230 231 232 233 234 235 236
            .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];

237
    virStorageReportError(VIR_ERR_INTERNAL_ERROR,
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
                          _("missing backend for pool type %d"), type);
    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;
}


259 260 261
void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
262 263 264 265

    if (!def)
        return;

266 267
    VIR_FREE(def->name);
    VIR_FREE(def->key);
268 269

    for (i = 0 ; i < def->source.nextent ; i++) {
270
        VIR_FREE(def->source.extents[i].path);
271
    }
272
    VIR_FREE(def->source.extents);
273

274 275
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
276
    virStorageEncryptionFree(def->target.encryption);
277 278
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
279
    virStorageEncryptionFree(def->backingStore.encryption);
280
    VIR_FREE(def);
281 282 283
}

void
284 285
virStoragePoolSourceClear(virStoragePoolSourcePtr source)
{
286 287
    int i;

288
    if (!source)
289 290
        return;

291 292 293 294 295
    for (i = 0 ; i < source->nhost ; i++) {
        VIR_FREE(source->hosts[i].name);
    }
    VIR_FREE(source->hosts);

296 297 298
    for (i = 0 ; i < source->ndevice ; i++) {
        VIR_FREE(source->devices[i].freeExtents);
        VIR_FREE(source->devices[i].path);
299
    }
300 301 302
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
303
    VIR_FREE(source->adapter);
D
David Allan 已提交
304
    VIR_FREE(source->initiator.iqn);
305 306
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
307

308 309 310
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
311
    }
312 313 314 315 316

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

319 320 321 322 323 324 325
void
virStoragePoolSourceFree(virStoragePoolSourcePtr source)
{
    virStoragePoolSourceClear(source);
    VIR_FREE(source);
}

326 327 328 329 330 331 332
void
virStoragePoolDefFree(virStoragePoolDefPtr def) {
    if (!def)
        return;

    VIR_FREE(def->name);

333
    virStoragePoolSourceClear(&def->source);
334

335 336 337
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
338 339 340 341 342
}


void
virStoragePoolObjFree(virStoragePoolObjPtr obj) {
343 344 345
    if (!obj)
        return;

346 347
    virStoragePoolObjClearVols(obj);

348 349
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
350

351 352
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
353 354 355

    virMutexDestroy(&obj->lock);

356
    VIR_FREE(obj);
357 358
}

359 360 361 362 363 364 365 366 367
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;
}

368
void
369
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
370 371
                        virStoragePoolObjPtr pool)
{
372
    unsigned int i;
373

374 375
    virStoragePoolObjUnlock(pool);

376
    for (i = 0 ; i < pools->count ; i++) {
377
        virStoragePoolObjLock(pools->objs[i]);
378
        if (pools->objs[i] == pool) {
379
            virStoragePoolObjUnlock(pools->objs[i]);
380
            virStoragePoolObjFree(pools->objs[i]);
381

382 383 384
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
385

386 387 388 389
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
390

391 392
            break;
        }
393
        virStoragePoolObjUnlock(pools->objs[i]);
394
    }
395 396 397 398
}


static int
399
virStoragePoolDefParseAuthChap(xmlXPathContextPtr ctxt,
400
                               virStoragePoolAuthChapPtr auth) {
401
    auth->login = virXPathString("string(./auth/@login)", ctxt);
402
    if (auth->login == NULL) {
403
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
404
                              "%s", _("missing auth host attribute"));
405 406 407
        return -1;
    }

408
    auth->passwd = virXPathString("string(./auth/@passwd)", ctxt);
409
    if (auth->passwd == NULL) {
410
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
411
                              "%s", _("missing auth passwd attribute"));
412 413 414 415 416 417
        return -1;
    }

    return 0;
}

418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
static int
virStoragePoolDefParseAuthCephx(xmlXPathContextPtr ctxt,
                               virStoragePoolAuthCephxPtr auth) {
    char *uuid = NULL;
    auth->username = virXPathString("string(./auth/@username)", ctxt);
    if (auth->username == NULL) {
        virStorageReportError(VIR_ERR_XML_ERROR,
                              "%s", _("missing auth username attribute"));
        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) {
        virStorageReportError(VIR_ERR_XML_ERROR, "%s",
                              _("missing auth secret uuid or usage attribute"));
        return -1;
    }

    if (virUUIDParse(uuid, auth->secret.uuid) < 0) {
        virStorageReportError(VIR_ERR_XML_ERROR,
                              "%s", _("invalid auth secret uuid"));
        return -1;
    }

    return 0;
}

446
static int
447
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
448 449 450 451 452 453 454 455
                             virStoragePoolSourcePtr source,
                             int pool_type,
                             xmlNodePtr node) {
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
    char *authType = NULL;
    int nsource, i;
    virStoragePoolOptionsPtr options;
456
    char *name = NULL;
457
    char *port = NULL;
458 459 460 461 462 463 464 465

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

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

466
    source->name = virXPathString("string(./name)", ctxt);
467 468 469 470 471
    if (pool_type == VIR_STORAGE_POOL_RBD && source->name == NULL) {
        virStorageReportError(VIR_ERR_XML_ERROR, "%s",
                              _("missing mandatory 'name' field for RBD pool name"));
        goto cleanup;
    }
472 473

    if (options->formatFromString) {
474
        char *format = virXPathString("string(./format/@type)", ctxt);
475 476 477 478 479 480
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
481
            virStorageReportError(VIR_ERR_XML_ERROR,
482 483 484 485 486 487 488
                                  _("unknown pool format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

489 490 491 492 493
    source->nhost = virXPathNodeSet("./host", ctxt, &nodeset);

    if (source->nhost) {
        if (VIR_ALLOC_N(source->hosts, source->nhost) < 0) {
            virReportOOMError();
494 495 496
            goto cleanup;
        }

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
        for (i = 0 ; i < source->nhost ; i++) {
            name = virXMLPropString(nodeset[i], "name");
            if (name == NULL) {
                virStorageReportError(VIR_ERR_XML_ERROR,
                        "%s", _("missing storage pool host name"));
                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) {
                    virStorageReportError(VIR_ERR_XML_ERROR,
                                          _("Invalid port number: %s"),
                                          port);
                    goto cleanup;
                }
            }
        }
    }
517

518
    VIR_FREE(nodeset);
519
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
520

521
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
522 523 524
    if (nsource < 0)
        goto cleanup;

525 526 527
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
528
            virReportOOMError();
529 530 531 532
            goto cleanup;
        }

        for (i = 0 ; i < nsource ; i++) {
533
            char *path = virXMLPropString(nodeset[i], "path");
534 535
            if (path == NULL) {
                VIR_FREE(nodeset);
536
                virStorageReportError(VIR_ERR_XML_ERROR,
537 538 539
                        "%s", _("missing storage pool source device path"));
                goto cleanup;
            }
540
            source->devices[i].path = path;
541 542 543 544
        }
        source->ndevice = nsource;
    }

545 546
    source->dir = virXPathString("string(./dir/@path)", ctxt);
    source->adapter = virXPathString("string(./adapter/@name)", ctxt);
547

548
    authType = virXPathString("string(./auth/@type)", ctxt);
549 550 551 552 553
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
554 555
        } else if (STREQ(authType, "ceph")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CEPHX;
556
        } else {
557
            virStorageReportError(VIR_ERR_XML_ERROR,
558 559 560 561 562 563 564
                                  _("unknown auth type '%s'"),
                                  (const char *)authType);
            goto cleanup;
        }
    }

    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
565
        if (virStoragePoolDefParseAuthChap(ctxt, &source->auth.chap) < 0)
566 567 568
            goto cleanup;
    }

569 570 571 572 573
    if (source->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        if (virStoragePoolDefParseAuthCephx(ctxt, &source->auth.cephx) < 0)
            goto cleanup;
    }

574 575 576
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

577 578 579 580
    ret = 0;
cleanup:
    ctxt->node = relnode;

581
    VIR_FREE(port);
582 583 584 585
    VIR_FREE(authType);
    VIR_FREE(nodeset);
    return ret;
}
586

587
virStoragePoolSourcePtr
588
virStoragePoolDefParseSourceString(const char *srcSpec,
589 590 591 592 593 594 595
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

596
    if (!(doc = virXMLParseStringCtxt(srcSpec, _("(storage_source_specification)"), &xpath_ctxt))) {
597 598 599 600
        goto cleanup;
    }

    if (VIR_ALLOC(def) < 0) {
601
        virReportOOMError();
602 603 604
        goto cleanup;
    }

605
    node = virXPathNode("/source", xpath_ctxt);
606
    if (!node) {
607
        virStorageReportError(VIR_ERR_XML_ERROR,
608 609 610 611
                              "%s", _("root element was not source"));
        goto cleanup;
    }

612
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
613 614 615 616 617 618
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
619
    virStoragePoolSourceFree(def);
620 621 622 623 624
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
625
static int
626
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
627 628 629
                        virStoragePermsPtr perms,
                        const char *permxpath,
                        int defaultmode) {
630 631
    char *mode;
    long v;
632 633 634
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
635

636
    node = virXPathNode(permxpath, ctxt);
637 638 639
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
640 641
        perms->uid = -1;
        perms->gid = -1;
642 643 644 645 646 647 648
        perms->label = NULL;
        return 0;
    }

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

649
    mode = virXPathString("string(./mode)", ctxt);
650
    if (!mode) {
651
        perms->mode = defaultmode;
652
    } else {
653 654 655
        int tmp;

        if (virStrToLong_i(mode, NULL, 8, &tmp) < 0 || (tmp & ~0777)) {
656
            VIR_FREE(mode);
657
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
658
                                  "%s", _("malformed octal mode"));
659
            goto error;
660
        }
661
        perms->mode = tmp;
662
        VIR_FREE(mode);
663 664
    }

665
    if (virXPathNode("./owner", ctxt) == NULL) {
666
        perms->uid = -1;
667
    } else {
668
        if (virXPathLong("number(./owner)", ctxt, &v) < 0) {
669
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
670
                                  "%s", _("malformed owner element"));
671
            goto error;
672 673 674 675
        }
        perms->uid = (int)v;
    }

676
    if (virXPathNode("./group", ctxt) == NULL) {
677
        perms->gid = -1;
678
    } else {
679
        if (virXPathLong("number(./group)", ctxt, &v) < 0) {
680
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
681
                                  "%s", _("malformed group element"));
682
            goto error;
683 684 685 686 687
        }
        perms->gid = (int)v;
    }

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

690 691 692 693
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
694 695 696
}

static virStoragePoolDefPtr
697
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt) {
698
    virStoragePoolOptionsPtr options;
699
    virStoragePoolDefPtr ret;
700
    xmlNodePtr source_node;
701
    char *type = NULL;
702
    char *uuid = NULL;
703
    char *tmppath;
704

705
    if (VIR_ALLOC(ret) < 0) {
706
        virReportOOMError();
707
        return NULL;
708
    }
709

710
    type = virXPathString("string(./@type)", ctxt);
711
    if ((ret->type = virStoragePoolTypeFromString((const char *)type)) < 0) {
712
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
713
                              _("unknown storage pool type %s"), (const char*)type);
714
        goto cleanup;
715 716
    }

717 718 719
    xmlFree(type);
    type = NULL;

720
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
721 722 723
        goto cleanup;
    }

724
    source_node = virXPathNode("./source", ctxt);
725
    if (source_node) {
726
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
727 728 729 730
                                         source_node) < 0)
            goto cleanup;
    }

731
    ret->name = virXPathString("string(./name)", ctxt);
732
    if (ret->name == NULL &&
733
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
734
        ret->name = ret->source.name;
735
    if (ret->name == NULL) {
736
        virStorageReportError(VIR_ERR_XML_ERROR,
737
                              "%s", _("missing pool source name element"));
738 739 740
        goto cleanup;
    }

741
    uuid = virXPathString("string(./uuid)", ctxt);
742 743
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
744
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
745
                                  "%s", _("unable to generate uuid"));
746 747 748 749
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
750
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
751
                                  "%s", _("malformed uuid element"));
752 753
            goto cleanup;
        }
754
        VIR_FREE(uuid);
755 756
    }

757
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
758
        if (!ret->source.nhost) {
759
            virStorageReportError(VIR_ERR_XML_ERROR,
760 761
                                  "%s",
                                  _("missing storage pool source host name"));
762 763 764 765
            goto cleanup;
        }
    }

766
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
767
        if (!ret->source.dir) {
768
            virStorageReportError(VIR_ERR_XML_ERROR,
769
                                  "%s", _("missing storage pool source path"));
770 771 772
            goto cleanup;
        }
    }
773
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
774 775 776
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
            ret->source.name = strdup(ret->name);
777
            if (ret->source.name == NULL) {
778
                virReportOOMError();
779 780
                goto cleanup;
            }
781 782
        }
    }
783

784
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
785
        if (!ret->source.adapter) {
786
            virStorageReportError(VIR_ERR_XML_ERROR,
787
                                  "%s", _("missing storage pool source adapter name"));
788 789 790
            goto cleanup;
        }
    }
791

792 793 794 795 796 797 798 799 800
    /* If DEVICE is the only source type, then its required */
    if (options->flags == VIR_STORAGE_POOL_SOURCE_DEVICE) {
        if (!ret->source.ndevice) {
            virStorageReportError(VIR_ERR_XML_ERROR,
                                  "%s", _("missing storage pool source device name"));
            goto cleanup;
        }
    }

801 802 803 804 805 806 807 808 809 810 811 812
    /* 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) {
            virStorageReportError(VIR_ERR_XML_ERROR,
                                  "%s", _("missing storage pool target path"));
            goto cleanup;
        }
        ret->target.path = virFileSanitizePath(tmppath);
        VIR_FREE(tmppath);
        if (!ret->target.path)
            goto cleanup;
813

814 815 816 817
        if (virStorageDefParsePerms(ctxt, &ret->target.perms,
                                    "./target/permissions", 0700) < 0)
            goto cleanup;
    }
818 819 820 821

    return ret;

 cleanup:
822
    VIR_FREE(uuid);
823
    xmlFree(type);
824 825 826 827 828
    virStoragePoolDefFree(ret);
    return NULL;
}

virStoragePoolDefPtr
829
virStoragePoolDefParseNode(xmlDocPtr xml,
830 831 832 833 834
                           xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "pool")) {
835 836
        virStorageReportError(VIR_ERR_XML_ERROR,
                              "%s", _("unknown root element for storage pool"));
837 838 839 840 841
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
842
        virReportOOMError();
843 844 845 846
        goto cleanup;
    }

    ctxt->node = root;
847
    def = virStoragePoolDefParseXML(ctxt);
848 849 850 851 852 853
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
854
virStoragePoolDefParse(const char *xmlStr,
855 856
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
857
    xmlDocPtr xml;
858

859
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_pool_definition)")))) {
J
Jiri Denemark 已提交
860 861
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
862 863
    }

864 865 866
    return ret;
}

867
virStoragePoolDefPtr
868
virStoragePoolDefParseString(const char *xmlStr)
869
{
870
    return virStoragePoolDefParse(xmlStr, NULL);
871 872 873
}

virStoragePoolDefPtr
874
virStoragePoolDefParseFile(const char *filename)
875
{
876
    return virStoragePoolDefParse(NULL, filename);
877 878
}

879
static int
880
virStoragePoolSourceFormat(virBufferPtr buf,
881
                           virStoragePoolOptionsPtr options,
882 883 884
                           virStoragePoolSourcePtr src)
{
    int i, j;
885
    char uuid[VIR_UUID_STRING_BUFLEN];
886 887

    virBufferAddLit(buf,"  <source>\n");
888 889
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) && src->nhost) {
        for (i = 0; i < src->nhost; i++) {
E
Eric Blake 已提交
890
            virBufferAsprintf(buf, "    <host name='%s'", src->hosts[i].name);
891 892 893 894
            if (src->hosts[i].port)
                virBufferAsprintf(buf, " port='%d'", src->hosts[i].port);
            virBufferAddLit(buf, "/>\n");
        }
895
    }
896

897
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
898 899 900
        src->ndevice) {
        for (i = 0 ; i < src->ndevice ; i++) {
            if (src->devices[i].nfreeExtent) {
901
                virBufferAsprintf(buf,"    <device path='%s'>\n",
902 903
                                  src->devices[i].path);
                for (j = 0 ; j < src->devices[i].nfreeExtent ; j++) {
904
                    virBufferAsprintf(buf, "    <freeExtent start='%llu' end='%llu'/>\n",
905 906 907 908 909 910
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
                virBufferAddLit(buf,"    </device>\n");
            }
            else
911
                virBufferAsprintf(buf, "    <device path='%s'/>\n",
912 913 914
                                  src->devices[i].path);
        }
    }
915
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
916
        src->dir)
917
        virBufferAsprintf(buf,"    <dir path='%s'/>\n", src->dir);
918
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
919
        src->adapter)
920
        virBufferAsprintf(buf,"    <adapter name='%s'/>\n", src->adapter);
921
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
922
        src->name)
923
        virBufferAsprintf(buf,"    <name>%s</name>\n", src->name);
924

D
David Allan 已提交
925 926 927 928 929 930 931
    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");
    }

932 933 934
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
935
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
936 937 938 939
                                  _("unknown pool format number %d"),
                                  src->format);
            return -1;
        }
940
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
941 942 943 944
    }


    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
945
        virBufferAsprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
946 947
                          src->auth.chap.login,
                          src->auth.chap.passwd);
948

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
    if (src->authType == VIR_STORAGE_POOL_AUTH_CEPHX) {
        virBufferAsprintf(buf,"    <auth username='%s' type='ceph'>\n",
                          src->auth.cephx.username);

        virBufferAsprintf(buf,"      %s", "<secret");
        if (src->auth.cephx.secret.uuid != NULL) {
            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);
        }
        virBufferAsprintf(buf,"%s", "/>\n");

        virBufferAsprintf(buf,"    %s", "</auth>\n");
    }

967 968 969 970 971 972 973 974
    if (src->vendor != NULL) {
        virBufferEscapeString(buf,"    <vendor name='%s'/>\n", src->vendor);
    }

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

975 976 977 978 979
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

980 981

char *
982
virStoragePoolDefFormat(virStoragePoolDefPtr def) {
983
    virStoragePoolOptionsPtr options;
984
    virBuffer buf = VIR_BUFFER_INITIALIZER;
985 986 987
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

988
    options = virStoragePoolOptionsForPoolType(def->type);
989 990 991
    if (options == NULL)
        return NULL;

992
    type = virStoragePoolTypeToString(def->type);
993
    if (!type) {
994
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
995
                              "%s", _("unexpected pool type"));
996 997
        goto cleanup;
    }
998 999
    virBufferAsprintf(&buf, "<pool type='%s'>\n", type);
    virBufferAsprintf(&buf,"  <name>%s</name>\n", def->name);
1000 1001

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

E
Eric Blake 已提交
1004
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1005
                      def->capacity);
E
Eric Blake 已提交
1006
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1007
                      def->allocation);
E
Eric Blake 已提交
1008
    virBufferAsprintf(&buf,"  <available unit='bytes'>%llu</available>\n",
1009
                      def->available);
1010

1011
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
1012
        goto cleanup;
1013

1014 1015 1016 1017
    /* RBD devices are not local block devs nor files, so it doesn't
     * have a target */
    if (def->type != VIR_STORAGE_POOL_RBD) {
        virBufferAddLit(&buf,"  <target>\n");
1018

1019 1020
        if (def->target.path)
            virBufferAsprintf(&buf,"    <path>%s</path>\n", def->target.path);
1021

1022 1023 1024 1025 1026 1027 1028
        virBufferAddLit(&buf,"    <permissions>\n");
        virBufferAsprintf(&buf,"      <mode>0%o</mode>\n",
                          def->target.perms.mode);
        virBufferAsprintf(&buf,"      <owner>%u</owner>\n",
                          (unsigned int) def->target.perms.uid);
        virBufferAsprintf(&buf,"      <group>%u</group>\n",
                          (unsigned int) def->target.perms.gid);
1029

1030 1031 1032
        if (def->target.perms.label)
            virBufferAsprintf(&buf,"      <label>%s</label>\n",
                            def->target.perms.label);
1033

1034 1035 1036
        virBufferAddLit(&buf,"    </permissions>\n");
        virBufferAddLit(&buf,"  </target>\n");
    }
1037
    virBufferAddLit(&buf,"</pool>\n");
1038

1039
    if (virBufferError(&buf))
1040 1041
        goto no_memory;

1042
    return virBufferContentAndReset(&buf);
1043 1044

 no_memory:
1045
    virReportOOMError();
1046
 cleanup:
1047
    virBufferFreeAndReset(&buf);
1048 1049 1050 1051 1052
    return NULL;
}


static int
1053
virStorageSize(const char *unit,
1054
               const char *val,
1055 1056 1057
               unsigned long long *ret)
{
    if (virStrToLong_ull(val, NULL, 10, ret) < 0) {
1058
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1059
                              "%s", _("malformed capacity element"));
1060 1061
        return -1;
    }
1062 1063 1064 1065
    /* 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;
1066 1067 1068 1069 1070

    return 0;
}

static virStorageVolDefPtr
1071
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1072
                         xmlXPathContextPtr ctxt) {
1073
    virStorageVolDefPtr ret;
1074
    virStorageVolOptionsPtr options;
1075 1076 1077
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1078
    xmlNodePtr node;
1079

1080
    options = virStorageVolOptionsForPoolType(pool->type);
1081 1082 1083
    if (options == NULL)
        return NULL;

1084
    if (VIR_ALLOC(ret) < 0) {
1085
        virReportOOMError();
1086
        return NULL;
1087
    }
1088

1089
    ret->name = virXPathString("string(./name)", ctxt);
1090
    if (ret->name == NULL) {
1091
        virStorageReportError(VIR_ERR_XML_ERROR,
1092
                              "%s", _("missing volume name element"));
1093 1094 1095
        goto cleanup;
    }

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

1099 1100
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1101
    if (capacity == NULL) {
1102
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1103
                              "%s", _("missing capacity element"));
1104 1105
        goto cleanup;
    }
1106
    if (virStorageSize(unit, capacity, &ret->capacity) < 0)
1107
        goto cleanup;
1108 1109
    VIR_FREE(capacity);
    VIR_FREE(unit);
1110

1111
    allocation = virXPathString("string(./allocation)", ctxt);
1112
    if (allocation) {
1113
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1114
        if (virStorageSize(unit, allocation, &ret->allocation) < 0)
1115
            goto cleanup;
1116 1117
        VIR_FREE(allocation);
        VIR_FREE(unit);
1118 1119 1120 1121
    } else {
        ret->allocation = ret->capacity;
    }

1122
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1123
    if (options->formatFromString) {
1124
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1125 1126 1127 1128 1129 1130
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1131
            virStorageReportError(VIR_ERR_XML_ERROR,
1132
                                  _("unknown volume format type %s"), format);
1133
            VIR_FREE(format);
1134 1135
            goto cleanup;
        }
1136
        VIR_FREE(format);
1137 1138
    }

1139
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
1140
                                "./target/permissions", 0600) < 0)
1141 1142
        goto cleanup;

1143
    node = virXPathNode("./target/encryption", ctxt);
1144
    if (node != NULL) {
1145
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1146 1147 1148 1149 1150
                                                               node);
        if (ret->target.encryption == NULL)
            goto cleanup;
    }

1151 1152


1153
    ret->backingStore.path = virXPathString("string(./backingStore/path)", ctxt);
1154
    if (options->formatFromString) {
1155
        char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
1156 1157 1158 1159 1160 1161
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
1162
            virStorageReportError(VIR_ERR_XML_ERROR,
1163 1164 1165 1166 1167 1168 1169
                                  _("unknown volume format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

1170
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1171
                                "./backingStore/permissions", 0600) < 0)
1172 1173
        goto cleanup;

1174 1175 1176
    return ret;

 cleanup:
1177 1178 1179
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1180 1181 1182 1183 1184
    virStorageVolDefFree(ret);
    return NULL;
}

virStorageVolDefPtr
1185
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1186 1187 1188 1189 1190 1191
                          xmlDocPtr xml,
                          xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "volume")) {
1192
        virStorageReportError(VIR_ERR_XML_ERROR,
1193 1194 1195 1196 1197 1198
                          "%s", _("unknown root element for storage vol"));
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1199
        virReportOOMError();
1200 1201 1202 1203
        goto cleanup;
    }

    ctxt->node = root;
1204
    def = virStorageVolDefParseXML(pool, ctxt);
1205 1206 1207 1208 1209 1210
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1211
virStorageVolDefParse(virStoragePoolDefPtr pool,
1212 1213 1214
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1215
    xmlDocPtr xml;
1216

1217
    if ((xml = virXMLParse(filename, xmlStr, _("(storage_volume_definition)")))) {
J
Jiri Denemark 已提交
1218 1219
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1220 1221 1222 1223 1224
    }

    return ret;
}

1225
virStorageVolDefPtr
1226
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1227 1228
                            const char *xmlStr)
{
1229
    return virStorageVolDefParse(pool, xmlStr, NULL);
1230 1231 1232
}

virStorageVolDefPtr
1233
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1234 1235
                          const char *filename)
{
1236
    return virStorageVolDefParse(pool, NULL, filename);
1237
}
1238

1239
static int
1240
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1241 1242 1243
                             virBufferPtr buf,
                             virStorageVolTargetPtr def,
                             const char *type) {
1244
    virBufferAsprintf(buf, "  <%s>\n", type);
1245 1246

    if (def->path)
1247
        virBufferAsprintf(buf,"    <path>%s</path>\n", def->path);
1248 1249 1250 1251

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1252
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1253 1254 1255 1256
                                  _("unknown volume format number %d"),
                                  def->format);
            return -1;
        }
1257
        virBufferAsprintf(buf,"    <format type='%s'/>\n", format);
1258 1259 1260
    }

    virBufferAddLit(buf,"    <permissions>\n");
1261
    virBufferAsprintf(buf,"      <mode>0%o</mode>\n",
1262
                      def->perms.mode);
E
Eric Blake 已提交
1263 1264 1265 1266
    virBufferAsprintf(buf,"      <owner>%u</owner>\n",
                      (unsigned int) def->perms.uid);
    virBufferAsprintf(buf,"      <group>%u</group>\n",
                      (unsigned int) def->perms.gid);
1267 1268 1269


    if (def->perms.label)
1270
        virBufferAsprintf(buf,"      <label>%s</label>\n",
1271 1272 1273 1274
                          def->perms.label);

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

1275 1276 1277 1278 1279 1280
    if (def->encryption) {
        virBufferAdjustIndent(buf, 4);
        if (virStorageEncryptionFormat(buf, def->encryption) < 0)
            return -1;
        virBufferAdjustIndent(buf, -4);
    }
1281

1282
    virBufferAsprintf(buf, "  </%s>\n", type);
1283 1284 1285

    return 0;
}
1286 1287

char *
1288
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1289
                       virStorageVolDefPtr def) {
1290
    virStorageVolOptionsPtr options;
1291
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1292

1293
    options = virStorageVolOptionsForPoolType(pool->type);
1294 1295 1296
    if (options == NULL)
        return NULL;

1297
    virBufferAddLit(&buf, "<volume>\n");
1298 1299
    virBufferAsprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferAsprintf(&buf,"  <key>%s</key>\n", def->key);
1300
    virBufferAddLit(&buf, "  <source>\n");
1301 1302 1303 1304 1305 1306 1307 1308

    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)
1309 1310
                    virBufferAddLit(&buf, "    </device>\n");

1311
                virBufferAsprintf(&buf, "    <device path='%s'>\n",
1312
                                  def->source.extents[i].path);
1313 1314
            }

1315
            virBufferAsprintf(&buf,
1316 1317 1318
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1319 1320 1321
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1322
            virBufferAddLit(&buf, "    </device>\n");
1323
    }
1324
    virBufferAddLit(&buf, "  </source>\n");
1325

E
Eric Blake 已提交
1326
    virBufferAsprintf(&buf,"  <capacity unit='bytes'>%llu</capacity>\n",
1327
                      def->capacity);
E
Eric Blake 已提交
1328
    virBufferAsprintf(&buf,"  <allocation unit='bytes'>%llu</allocation>\n",
1329
                      def->allocation);
1330

1331
    if (virStorageVolTargetDefFormat(options, &buf,
1332 1333
                                     &def->target, "target") < 0)
        goto cleanup;
1334

1335
    if (def->backingStore.path &&
1336
        virStorageVolTargetDefFormat(options, &buf,
1337 1338
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1339 1340

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

1342
    if (virBufferError(&buf))
1343 1344
        goto no_memory;

1345
    return virBufferContentAndReset(&buf);
1346 1347

 no_memory:
1348
    virReportOOMError();
1349
 cleanup:
1350
    virBufferFreeAndReset(&buf);
1351 1352 1353 1354 1355
    return NULL;
}


virStoragePoolObjPtr
1356
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1357
                            const unsigned char *uuid) {
1358
    unsigned int i;
1359

1360 1361
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1362 1363
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1364 1365
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1366 1367 1368 1369 1370

    return NULL;
}

virStoragePoolObjPtr
1371
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1372
                            const char *name) {
1373
    unsigned int i;
1374

1375 1376
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1377 1378
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1379 1380
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1381 1382 1383 1384

    return NULL;
}

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
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;
}

1400 1401 1402
void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1403 1404 1405 1406 1407 1408
    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;
1409 1410 1411 1412 1413
}

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

1416 1417 1418
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1419 1420 1421 1422 1423 1424 1425

    return NULL;
}

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

1428 1429 1430
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1431 1432 1433 1434 1435 1436 1437

    return NULL;
}

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

1440 1441 1442
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1443 1444 1445 1446 1447

    return NULL;
}

virStoragePoolObjPtr
1448
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1449 1450 1451
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1452
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1453 1454 1455 1456
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1457
            virStoragePoolDefFree(pool->newDef);
1458 1459 1460 1461 1462
            pool->newDef = def;
        }
        return pool;
    }

1463
    if (VIR_ALLOC(pool) < 0) {
1464
        virReportOOMError();
1465 1466 1467
        return NULL;
    }

1468
    if (virMutexInit(&pool->lock) < 0) {
1469
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1470 1471 1472 1473
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(pool);
        return NULL;
    }
1474
    virStoragePoolObjLock(pool);
1475 1476 1477
    pool->active = 0;
    pool->def = def;

1478 1479
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1480
        virStoragePoolObjUnlock(pool);
1481
        virStoragePoolObjFree(pool);
1482
        virReportOOMError();
1483 1484 1485
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1486 1487 1488 1489 1490

    return pool;
}

static virStoragePoolObjPtr
1491
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1492 1493 1494 1495 1496 1497
                      const char *file,
                      const char *path,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1498
    if (!(def = virStoragePoolDefParseFile(path))) {
1499 1500 1501 1502
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1503
        virStorageReportError(VIR_ERR_XML_ERROR,
1504
                              _("Storage pool config filename '%s' does not match pool name '%s'"),
1505
                              path, def->name);
1506 1507 1508 1509
        virStoragePoolDefFree(def);
        return NULL;
    }

1510
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1511 1512 1513 1514
        virStoragePoolDefFree(def);
        return NULL;
    }

1515
    VIR_FREE(pool->configFile);  /* for driver reload */
1516 1517
    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
1518
        virReportOOMError();
1519 1520 1521
        virStoragePoolDefFree(def);
        return NULL;
    }
1522
    VIR_FREE(pool->autostartLink); /* for driver reload */
1523 1524
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
1525
        virReportOOMError();
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1538
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1539 1540
                             const char *configDir,
                             const char *autostartDir) {
1541 1542 1543
    DIR *dir;
    struct dirent *entry;

1544
    if (!(dir = opendir(configDir))) {
1545 1546
        if (errno == ENOENT)
            return 0;
1547
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1548
                             configDir);
1549 1550 1551 1552
        return -1;
    }

    while ((entry = readdir(dir))) {
1553 1554
        char *path;
        char *autostartLink;
1555
        virStoragePoolObjPtr pool;
1556 1557 1558 1559 1560 1561 1562

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

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

1563
        if (!(path = virFileBuildPath(configDir, entry->d_name, NULL)))
1564 1565
            continue;

1566 1567 1568
        if (!(autostartLink = virFileBuildPath(autostartDir, entry->d_name,
                                               NULL))) {
            VIR_FREE(path);
1569 1570 1571
            continue;
        }

1572
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1573
                                     autostartLink);
1574 1575
        if (pool)
            virStoragePoolObjUnlock(pool);
1576 1577 1578

        VIR_FREE(path);
        VIR_FREE(autostartLink);
1579 1580 1581 1582 1583 1584 1585 1586
    }

    closedir(dir);

    return 0;
}

int
1587
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1588
                         virStoragePoolObjPtr pool,
1589 1590
                         virStoragePoolDefPtr def)
{
1591
    char *xml;
1592
    int ret = -1;
1593 1594

    if (!pool->configFile) {
1595 1596
        if (virFileMakePath(driver->configDir) < 0) {
            virReportSystemError(errno,
C
Cole Robinson 已提交
1597 1598
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1599 1600 1601
            return -1;
        }

1602 1603
        if (!(pool->configFile = virFileBuildPath(driver->configDir,
                                                  def->name, ".xml"))) {
1604 1605 1606
            return -1;
        }

1607 1608
        if (!(pool->autostartLink = virFileBuildPath(driver->autostartDir,
                                                     def->name, ".xml"))) {
1609
            VIR_FREE(pool->configFile);
1610 1611 1612 1613
            return -1;
        }
    }

1614 1615
    if (!(xml = virStoragePoolDefFormat(def))) {
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1616
                              "%s", _("failed to generate XML"));
1617 1618 1619
        return -1;
    }

1620
    ret = virXMLSaveFile(pool->configFile, def->name, "pool-edit", xml);
1621
    VIR_FREE(xml);
1622 1623 1624 1625 1626

    return ret;
}

int
1627
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool) {
1628
    if (!pool->configFile) {
1629
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1630 1631 1632 1633 1634
                              _("no config file for %s"), pool->def->name);
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1635
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1636 1637 1638 1639 1640 1641 1642
                              _("cannot remove config for %s"),
                              pool->def->name);
        return -1;
    }

    return 0;
}
1643

1644
virStoragePoolSourcePtr
1645
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1646 1647 1648 1649
{
    virStoragePoolSourcePtr source;

    if (VIR_REALLOC_N(list->sources, list->nsources+1) < 0) {
1650
        virReportOOMError();
1651 1652 1653 1654 1655 1656 1657 1658 1659
        return NULL;
    }

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

    return source;
}

1660
char *virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1661
{
1662
    virStoragePoolOptionsPtr options;
1663
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1664 1665
    const char *type;
    int i;
1666

1667
    options = virStoragePoolOptionsForPoolType(def->type);
1668 1669 1670
    if (options == NULL)
        return NULL;

1671
    type = virStoragePoolTypeToString(def->type);
1672
    if (!type) {
1673
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1674 1675 1676 1677 1678
                              "%s", _("unexpected pool type"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1679 1680

    for (i = 0; i < def->nsources; i++) {
1681
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1682 1683
    }

1684 1685 1686 1687
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1688 1689

    return virBufferContentAndReset(&buf);
1690 1691

 no_memory:
1692
    virReportOOMError();
1693
 cleanup:
1694
    virBufferFreeAndReset(&buf);
1695
    return NULL;
1696
}
D
Daniel P. Berrange 已提交
1697 1698


1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760
/*
 * 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);
            virStorageReportError(VIR_ERR_OPERATION_FAILED,
                                  _("pool '%s' is already defined with uuid %s"),
                                  pool->def->name, uuidstr);
            goto cleanup;
        }

        if (check_active) {
            /* UUID & name match, but if Pool is already active, refuse it */
            if (virStoragePoolObjIsActive(pool)) {
                virStorageReportError(VIR_ERR_OPERATION_INVALID,
                                      _("pool is already active as '%s'"),
                                      pool->def->name);
                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);
            virStorageReportError(VIR_ERR_OPERATION_FAILED,
                                  _("pool '%s' already exists with uuid %s"),
                                  def->name, uuidstr);
            goto cleanup;
        }
    }

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

1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
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;

1775 1776 1777 1778
        /* Don't mach against ourself if re-defining existing pool ! */
        if (STREQ(pool->def->name, def->name))
            continue;

1779 1780 1781 1782 1783 1784 1785 1786 1787
        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)) \
1788 1789
                && (pool->def->source.nhost == 1 && def->source.nhost == 1) \
                && (STREQ(pool->def->source.hosts[0].name, def->source.hosts[0].name)))
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_SCSI:
            if (STREQ(pool->def->source.adapter, def->source.adapter))
                matchpool = pool;
            break;
        case VIR_STORAGE_POOL_ISCSI:
        {
            matchpool = virStoragePoolSourceFindDuplicateDevices(pool, def);
            if (matchpool) {
1800 1801 1802 1803 1804 1805 1806 1807
                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;
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
                    }
                }
                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);
1823 1824 1825

        if (matchpool)
            break;
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
    }

    if (matchpool) {
        virStorageReportError(VIR_ERR_OPERATION_FAILED,
                              _("Storage source conflict with pool: '%s'"),
                              matchpool->def->name);
        ret = -1;
    }
    return ret;
}
1836

1837 1838
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
1839
    virMutexLock(&obj->lock);
1840 1841 1842 1843
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
1844
    virMutexUnlock(&obj->lock);
1845
}