storage_conf.c 50.9 KB
Newer Older
1 2 3
/*
 * storage_conf.c: config handling for storage driver
 *
4
 * Copyright (C) 2006-2010 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"
46
#include "files.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",
D
Dave Allan 已提交
55
              "scsi", "mpath")
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 114 115 116 117 118 119 120 121 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
};



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

225
    virStorageReportError(VIR_ERR_INTERNAL_ERROR,
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
                          _("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;
}


247 248 249
void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
250 251 252 253

    if (!def)
        return;

254 255
    VIR_FREE(def->name);
    VIR_FREE(def->key);
256 257

    for (i = 0 ; i < def->source.nextent ; i++) {
258
        VIR_FREE(def->source.extents[i].path);
259
    }
260
    VIR_FREE(def->source.extents);
261

262 263
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
264
    virStorageEncryptionFree(def->target.encryption);
265 266
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
267
    virStorageEncryptionFree(def->backingStore.encryption);
268
    VIR_FREE(def);
269 270 271
}

void
272
virStoragePoolSourceFree(virStoragePoolSourcePtr source) {
273 274
    int i;

275
    if (!source)
276 277
        return;

278 279 280 281
    VIR_FREE(source->host.name);
    for (i = 0 ; i < source->ndevice ; i++) {
        VIR_FREE(source->devices[i].freeExtents);
        VIR_FREE(source->devices[i].path);
282
    }
283 284 285
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
286
    VIR_FREE(source->adapter);
D
David Allan 已提交
287
    VIR_FREE(source->initiator.iqn);
288 289
    VIR_FREE(source->vendor);
    VIR_FREE(source->product);
290

291 292 293
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
294
    }
295 296 297 298 299 300 301 302 303 304
}

void
virStoragePoolDefFree(virStoragePoolDefPtr def) {
    if (!def)
        return;

    VIR_FREE(def->name);

    virStoragePoolSourceFree(&def->source);
305

306 307 308
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
309 310 311 312 313
}


void
virStoragePoolObjFree(virStoragePoolObjPtr obj) {
314 315 316
    if (!obj)
        return;

317 318
    virStoragePoolObjClearVols(obj);

319 320
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
321

322 323
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
324 325 326

    virMutexDestroy(&obj->lock);

327
    VIR_FREE(obj);
328 329
}

330 331 332 333 334 335 336 337 338
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;
}

339
void
340
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
341 342
                        virStoragePoolObjPtr pool)
{
343
    unsigned int i;
344

345 346
    virStoragePoolObjUnlock(pool);

347
    for (i = 0 ; i < pools->count ; i++) {
348
        virStoragePoolObjLock(pools->objs[i]);
349
        if (pools->objs[i] == pool) {
350
            virStoragePoolObjUnlock(pools->objs[i]);
351
            virStoragePoolObjFree(pools->objs[i]);
352

353 354 355
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
356

357 358 359 360
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
361

362 363
            break;
        }
364
        virStoragePoolObjUnlock(pools->objs[i]);
365
    }
366 367 368 369
}


static int
370
virStoragePoolDefParseAuthChap(xmlXPathContextPtr ctxt,
371
                               virStoragePoolAuthChapPtr auth) {
372
    auth->login = virXPathString("string(./auth/@login)", ctxt);
373
    if (auth->login == NULL) {
374
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
375
                              "%s", _("missing auth host attribute"));
376 377 378
        return -1;
    }

379
    auth->passwd = virXPathString("string(./auth/@passwd)", ctxt);
380
    if (auth->passwd == NULL) {
381
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
382
                              "%s", _("missing auth passwd attribute"));
383 384 385 386 387 388
        return -1;
    }

    return 0;
}

389
static int
390
virStoragePoolDefParseSource(xmlXPathContextPtr ctxt,
391 392 393 394 395 396 397 398
                             virStoragePoolSourcePtr source,
                             int pool_type,
                             xmlNodePtr node) {
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
    char *authType = NULL;
    int nsource, i;
    virStoragePoolOptionsPtr options;
399
    char *port;
400 401 402 403 404 405 406 407

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

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

408
    source->name = virXPathString("string(./name)", ctxt);
409 410

    if (options->formatFromString) {
411
        char *format = virXPathString("string(./format/@type)", ctxt);
412 413 414 415 416 417
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
418
            virStorageReportError(VIR_ERR_XML_ERROR,
419 420 421 422 423 424 425
                                  _("unknown pool format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

426
    source->host.name = virXPathString("string(./host/@name)", ctxt);
427 428 429 430 431 432 433 434 435 436 437
    port = virXPathString("string(./host/@port)", ctxt);
    if (port) {
        if (virStrToLong_i(port, NULL, 10, &source->host.port) < 0) {
            virStorageReportError(VIR_ERR_XML_ERROR,
                                  _("Invalid port number: %s"),
                                  port);
            goto cleanup;
        }
    }


438
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
439

440
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
441 442 443
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
444
            virReportOOMError();
445 446 447 448
            goto cleanup;
        }

        for (i = 0 ; i < nsource ; i++) {
449
            char *path = virXMLPropString(nodeset[i], "path");
450 451
            if (path == NULL) {
                VIR_FREE(nodeset);
452
                virStorageReportError(VIR_ERR_XML_ERROR,
453 454 455
                        "%s", _("missing storage pool source device path"));
                goto cleanup;
            }
456
            source->devices[i].path = path;
457 458 459 460
        }
        source->ndevice = nsource;
    }

461 462
    source->dir = virXPathString("string(./dir/@path)", ctxt);
    source->adapter = virXPathString("string(./adapter/@name)", ctxt);
463

464
    authType = virXPathString("string(./auth/@type)", ctxt);
465 466 467 468 469 470
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
        } else {
471
            virStorageReportError(VIR_ERR_XML_ERROR,
472 473 474 475 476 477 478
                                  _("unknown auth type '%s'"),
                                  (const char *)authType);
            goto cleanup;
        }
    }

    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
479
        if (virStoragePoolDefParseAuthChap(ctxt, &source->auth.chap) < 0)
480 481 482
            goto cleanup;
    }

483 484 485
    source->vendor = virXPathString("string(./vendor/@name)", ctxt);
    source->product = virXPathString("string(./product/@name)", ctxt);

486 487 488 489
    ret = 0;
cleanup:
    ctxt->node = relnode;

490
    VIR_FREE(port);
491 492 493 494
    VIR_FREE(authType);
    VIR_FREE(nodeset);
    return ret;
}
495

496
virStoragePoolSourcePtr
497
virStoragePoolDefParseSourceString(const char *srcSpec,
498 499 500 501 502 503 504 505 506 507 508 509
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

    doc = xmlReadDoc((const xmlChar *)srcSpec, "srcSpec.xml", NULL,
                     XML_PARSE_NOENT | XML_PARSE_NONET |
                     XML_PARSE_NOERROR | XML_PARSE_NOWARNING);

    if (doc == NULL) {
510
        virStorageReportError(VIR_ERR_XML_ERROR,
511 512 513 514 515 516
                              "%s", _("bad <source> spec"));
        goto cleanup;
    }

    xpath_ctxt = xmlXPathNewContext(doc);
    if (xpath_ctxt == NULL) {
517
        virReportOOMError();
518 519 520 521
        goto cleanup;
    }

    if (VIR_ALLOC(def) < 0) {
522
        virReportOOMError();
523 524 525
        goto cleanup;
    }

526
    node = virXPathNode("/source", xpath_ctxt);
527
    if (!node) {
528
        virStorageReportError(VIR_ERR_XML_ERROR,
529 530 531 532
                              "%s", _("root element was not source"));
        goto cleanup;
    }

533
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
534 535 536 537 538 539
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
540 541
    virStoragePoolSourceFree(def);
    VIR_FREE(def);
542 543 544 545 546
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
547
static int
548
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
549 550 551
                        virStoragePermsPtr perms,
                        const char *permxpath,
                        int defaultmode) {
552 553
    char *mode;
    long v;
554 555 556
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
557

558
    node = virXPathNode(permxpath, ctxt);
559 560 561
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
562 563
        perms->uid = -1;
        perms->gid = -1;
564 565 566 567 568 569 570
        perms->label = NULL;
        return 0;
    }

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

571
    mode = virXPathString("string(./mode)", ctxt);
572
    if (!mode) {
573
        perms->mode = defaultmode;
574
    } else {
575
        char *end = NULL;
576 577
        perms->mode = strtol(mode, &end, 8);
        if (*end || perms->mode < 0 || perms->mode > 0777) {
578
            VIR_FREE(mode);
579
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
580
                                  "%s", _("malformed octal mode"));
581
            goto error;
582
        }
583
        VIR_FREE(mode);
584 585
    }

586
    if (virXPathNode("./owner", ctxt) == NULL) {
587
        perms->uid = -1;
588
    } else {
589
        if (virXPathLong("number(./owner)", ctxt, &v) < 0) {
590
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
591
                                  "%s", _("malformed owner element"));
592
            goto error;
593 594 595 596
        }
        perms->uid = (int)v;
    }

597
    if (virXPathNode("./group", ctxt) == NULL) {
598
        perms->gid = -1;
599
    } else {
600
        if (virXPathLong("number(./group)", ctxt, &v) < 0) {
601
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
602
                                  "%s", _("malformed group element"));
603
            goto error;
604 605 606 607 608
        }
        perms->gid = (int)v;
    }

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

611 612 613 614
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
615 616 617
}

static virStoragePoolDefPtr
618
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt) {
619
    virStoragePoolOptionsPtr options;
620
    virStoragePoolDefPtr ret;
621
    xmlNodePtr source_node;
622
    char *type = NULL;
623
    char *uuid = NULL;
624
    char *tmppath;
625

626
    if (VIR_ALLOC(ret) < 0) {
627
        virReportOOMError();
628
        return NULL;
629
    }
630

631
    type = virXPathString("string(./@type)", ctxt);
632
    if ((ret->type = virStoragePoolTypeFromString((const char *)type)) < 0) {
633
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
634
                              _("unknown storage pool type %s"), (const char*)type);
635
        goto cleanup;
636 637
    }

638 639 640
    xmlFree(type);
    type = NULL;

641
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
642 643 644
        goto cleanup;
    }

645
    source_node = virXPathNode("./source", ctxt);
646
    if (source_node) {
647
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
648 649 650 651
                                         source_node) < 0)
            goto cleanup;
    }

652
    ret->name = virXPathString("string(./name)", ctxt);
653
    if (ret->name == NULL &&
654
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
655
        ret->name = ret->source.name;
656
    if (ret->name == NULL) {
657
        virStorageReportError(VIR_ERR_XML_ERROR,
658
                              "%s", _("missing pool source name element"));
659 660 661
        goto cleanup;
    }

662
    uuid = virXPathString("string(./uuid)", ctxt);
663 664
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
665
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
666
                                  "%s", _("unable to generate uuid"));
667 668 669 670
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
671
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
672
                                  "%s", _("malformed uuid element"));
673 674
            goto cleanup;
        }
675
        VIR_FREE(uuid);
676 677
    }

678
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
679
        if (!ret->source.host.name) {
680
            virStorageReportError(VIR_ERR_XML_ERROR,
681 682
                                  "%s",
                                  _("missing storage pool source host name"));
683 684 685 686
            goto cleanup;
        }
    }

687
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
688
        if (!ret->source.dir) {
689
            virStorageReportError(VIR_ERR_XML_ERROR,
690
                                  "%s", _("missing storage pool source path"));
691 692 693
            goto cleanup;
        }
    }
694
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
695 696 697
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
            ret->source.name = strdup(ret->name);
698
            if (ret->source.name == NULL) {
699
                virReportOOMError();
700 701
                goto cleanup;
            }
702 703
        }
    }
704

705
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
706
        if (!ret->source.adapter) {
707
            virStorageReportError(VIR_ERR_XML_ERROR,
708
                                  "%s", _("missing storage pool source adapter name"));
709 710 711
            goto cleanup;
        }
    }
712

713 714 715 716 717 718 719 720 721
    /* 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;
        }
    }

722
    if ((tmppath = virXPathString("string(./target/path)", ctxt)) == NULL) {
723
        virStorageReportError(VIR_ERR_XML_ERROR,
724
                              "%s", _("missing storage pool target path"));
725 726
        goto cleanup;
    }
727 728 729 730 731
    ret->target.path = virFileSanitizePath(tmppath);
    VIR_FREE(tmppath);
    if (!ret->target.path)
        goto cleanup;

732

733
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
734
                                "./target/permissions", 0700) < 0)
735 736 737 738 739
        goto cleanup;

    return ret;

 cleanup:
740
    VIR_FREE(uuid);
741
    xmlFree(type);
742 743 744 745 746
    virStoragePoolDefFree(ret);
    return NULL;
}

virStoragePoolDefPtr
747
virStoragePoolDefParseNode(xmlDocPtr xml,
748 749 750 751 752
                           xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "pool")) {
753 754
        virStorageReportError(VIR_ERR_XML_ERROR,
                              "%s", _("unknown root element for storage pool"));
755 756 757 758 759
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
760
        virReportOOMError();
761 762 763 764
        goto cleanup;
    }

    ctxt->node = root;
765
    def = virStoragePoolDefParseXML(ctxt);
766 767 768 769 770 771
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
772
virStoragePoolDefParse(const char *xmlStr,
773 774
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
J
Jiri Denemark 已提交
775
    xmlDocPtr xml;
776

J
Jiri Denemark 已提交
777 778 779
    if ((xml = virXMLParse(filename, xmlStr, "storage.xml"))) {
        ret = virStoragePoolDefParseNode(xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
780 781
    }

782 783 784
    return ret;
}

785
virStoragePoolDefPtr
786
virStoragePoolDefParseString(const char *xmlStr)
787
{
788
    return virStoragePoolDefParse(xmlStr, NULL);
789 790 791
}

virStoragePoolDefPtr
792
virStoragePoolDefParseFile(const char *filename)
793
{
794
    return virStoragePoolDefParse(NULL, filename);
795 796
}

797
static int
798
virStoragePoolSourceFormat(virBufferPtr buf,
799
                           virStoragePoolOptionsPtr options,
800 801 802 803 804
                           virStoragePoolSourcePtr src)
{
    int i, j;

    virBufferAddLit(buf,"  <source>\n");
805
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) &&
806 807 808 809 810 811
        src->host.name) {
        virBufferVSprintf(buf, "    <host name='%s'", src->host.name);
        if (src->host.port)
            virBufferVSprintf(buf, " port='%d'", src->host.port);
        virBufferAddLit(buf, "/>\n");
    }
812

813
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830
        src->ndevice) {
        for (i = 0 ; i < src->ndevice ; i++) {
            if (src->devices[i].nfreeExtent) {
                virBufferVSprintf(buf,"    <device path='%s'>\n",
                                  src->devices[i].path);
                for (j = 0 ; j < src->devices[i].nfreeExtent ; j++) {
                    virBufferVSprintf(buf, "    <freeExtent start='%llu' end='%llu'/>\n",
                                      src->devices[i].freeExtents[j].start,
                                      src->devices[i].freeExtents[j].end);
                }
                virBufferAddLit(buf,"    </device>\n");
            }
            else
                virBufferVSprintf(buf, "    <device path='%s'/>\n",
                                  src->devices[i].path);
        }
    }
831
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
832 833
        src->dir)
        virBufferVSprintf(buf,"    <dir path='%s'/>\n", src->dir);
834
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
835 836
        src->adapter)
        virBufferVSprintf(buf,"    <adapter name='%s'/>\n", src->adapter);
837
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
838 839 840
        src->name)
        virBufferVSprintf(buf,"    <name>%s</name>\n", src->name);

D
David Allan 已提交
841 842 843 844 845 846 847
    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");
    }

848 849 850
    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
851
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
852 853 854 855 856 857 858 859 860
                                  _("unknown pool format number %d"),
                                  src->format);
            return -1;
        }
        virBufferVSprintf(buf,"    <format type='%s'/>\n", format);
    }


    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
861
        virBufferVSprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
862 863
                          src->auth.chap.login,
                          src->auth.chap.passwd);
864 865 866 867 868 869 870 871 872

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

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

873 874 875 876 877
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

878 879

char *
880
virStoragePoolDefFormat(virStoragePoolDefPtr def) {
881
    virStoragePoolOptionsPtr options;
882
    virBuffer buf = VIR_BUFFER_INITIALIZER;
883 884 885
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

886
    options = virStoragePoolOptionsForPoolType(def->type);
887 888 889
    if (options == NULL)
        return NULL;

890
    type = virStoragePoolTypeToString(def->type);
891
    if (!type) {
892
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
893
                              "%s", _("unexpected pool type"));
894 895
        goto cleanup;
    }
896 897
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
898 899

    virUUIDFormat(def->uuid, uuid);
900
    virBufferVSprintf(&buf,"  <uuid>%s</uuid>\n", uuid);
901

902 903 904 905 906 907
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
    virBufferVSprintf(&buf,"  <available>%llu</available>\n",
                      def->available);
908

909
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
910
        goto cleanup;
911

912
    virBufferAddLit(&buf,"  <target>\n");
913

914 915
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
916

917 918 919 920 921 922 923
    virBufferAddLit(&buf,"    <permissions>\n");
    virBufferVSprintf(&buf,"      <mode>0%o</mode>\n",
                      def->target.perms.mode);
    virBufferVSprintf(&buf,"      <owner>%d</owner>\n",
                      def->target.perms.uid);
    virBufferVSprintf(&buf,"      <group>%d</group>\n",
                      def->target.perms.gid);
924

925 926 927
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);
928

929 930 931
    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf,"  </target>\n");
    virBufferAddLit(&buf,"</pool>\n");
932

933
    if (virBufferError(&buf))
934 935
        goto no_memory;

936
    return virBufferContentAndReset(&buf);
937 938

 no_memory:
939
    virReportOOMError();
940
 cleanup:
941
    virBufferFreeAndReset(&buf);
942 943 944 945 946
    return NULL;
}


static int
947
virStorageSize(const char *unit,
948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
               const char *val,
               unsigned long long *ret) {
    unsigned long long mult;
    char *end;

    if (!unit) {
        mult = 1;
    } else {
        switch (unit[0]) {
        case 'k':
        case 'K':
            mult = 1024ull;
            break;

        case 'm':
        case 'M':
            mult = 1024ull * 1024ull;
            break;

        case 'g':
        case 'G':
            mult = 1024ull * 1024ull * 1024ull;
            break;

        case 't':
        case 'T':
            mult = 1024ull * 1024ull * 1024ull * 1024ull;
            break;

        case 'p':
        case 'P':
            mult = 1024ull * 1024ull * 1024ull * 1024ull * 1024ull;
            break;

982 983
        case 'e':
        case 'E':
984 985 986 987 988
            mult = 1024ull * 1024ull * 1024ull * 1024ull * 1024ull *
                1024ull;
            break;

        default:
989
            virStorageReportError(VIR_ERR_XML_ERROR,
990 991 992 993 994 995
                                  _("unknown size units '%s'"), unit);
            return -1;
        }
    }

    if (virStrToLong_ull (val, &end, 10, ret) < 0) {
996
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
997
                              "%s", _("malformed capacity element"));
998 999 1000
        return -1;
    }
    if (*ret > (ULLONG_MAX / mult)) {
1001
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1002
                              "%s", _("capacity element value too large"));
1003 1004 1005 1006 1007 1008 1009 1010 1011
            return -1;
    }

    *ret *= mult;

    return 0;
}

static virStorageVolDefPtr
1012
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1013
                         xmlXPathContextPtr ctxt) {
1014
    virStorageVolDefPtr ret;
1015
    virStorageVolOptionsPtr options;
1016 1017 1018
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1019
    xmlNodePtr node;
1020

1021
    options = virStorageVolOptionsForPoolType(pool->type);
1022 1023 1024
    if (options == NULL)
        return NULL;

1025
    if (VIR_ALLOC(ret) < 0) {
1026
        virReportOOMError();
1027
        return NULL;
1028
    }
1029

1030
    ret->name = virXPathString("string(./name)", ctxt);
1031
    if (ret->name == NULL) {
1032
        virStorageReportError(VIR_ERR_XML_ERROR,
1033
                              "%s", _("missing volume name element"));
1034 1035 1036
        goto cleanup;
    }

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

1040 1041
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1042
    if (capacity == NULL) {
1043
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1044
                              "%s", _("missing capacity element"));
1045 1046
        goto cleanup;
    }
1047
    if (virStorageSize(unit, capacity, &ret->capacity) < 0)
1048
        goto cleanup;
1049 1050
    VIR_FREE(capacity);
    VIR_FREE(unit);
1051

1052
    allocation = virXPathString("string(./allocation)", ctxt);
1053
    if (allocation) {
1054
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1055
        if (virStorageSize(unit, allocation, &ret->allocation) < 0)
1056
            goto cleanup;
1057 1058
        VIR_FREE(allocation);
        VIR_FREE(unit);
1059 1060 1061 1062
    } else {
        ret->allocation = ret->capacity;
    }

1063
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1064
    if (options->formatFromString) {
1065
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1066 1067 1068 1069 1070 1071
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1072
            virStorageReportError(VIR_ERR_XML_ERROR,
1073
                                  _("unknown volume format type %s"), format);
1074
            VIR_FREE(format);
1075 1076
            goto cleanup;
        }
1077
        VIR_FREE(format);
1078 1079
    }

1080
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
1081
                                "./target/permissions", 0600) < 0)
1082 1083
        goto cleanup;

1084
    node = virXPathNode("./target/encryption", ctxt);
1085
    if (node != NULL) {
1086
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1087 1088 1089 1090 1091
                                                               node);
        if (ret->target.encryption == NULL)
            goto cleanup;
    }

1092 1093


1094
    ret->backingStore.path = virXPathString("string(./backingStore/path)", ctxt);
1095
    if (options->formatFromString) {
1096
        char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
1097 1098 1099 1100 1101 1102
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
1103
            virStorageReportError(VIR_ERR_XML_ERROR,
1104 1105 1106 1107 1108 1109 1110
                                  _("unknown volume format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

1111
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1112
                                "./backingStore/permissions", 0600) < 0)
1113 1114
        goto cleanup;

1115 1116 1117
    return ret;

 cleanup:
1118 1119 1120
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1121 1122 1123 1124 1125
    virStorageVolDefFree(ret);
    return NULL;
}

virStorageVolDefPtr
1126
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1127 1128 1129 1130 1131 1132
                          xmlDocPtr xml,
                          xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "volume")) {
1133
        virStorageReportError(VIR_ERR_XML_ERROR,
1134 1135 1136 1137 1138 1139
                          "%s", _("unknown root element for storage vol"));
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1140
        virReportOOMError();
1141 1142 1143 1144
        goto cleanup;
    }

    ctxt->node = root;
1145
    def = virStorageVolDefParseXML(pool, ctxt);
1146 1147 1148 1149 1150 1151
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1152
virStorageVolDefParse(virStoragePoolDefPtr pool,
1153 1154 1155
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
J
Jiri Denemark 已提交
1156
    xmlDocPtr xml;
1157

J
Jiri Denemark 已提交
1158 1159 1160
    if ((xml = virXMLParse(filename, xmlStr, "storage.xml"))) {
        ret = virStorageVolDefParseNode(pool, xml, xmlDocGetRootElement(xml));
        xmlFreeDoc(xml);
1161 1162 1163 1164 1165
    }

    return ret;
}

1166
virStorageVolDefPtr
1167
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1168 1169
                            const char *xmlStr)
{
1170
    return virStorageVolDefParse(pool, xmlStr, NULL);
1171 1172 1173
}

virStorageVolDefPtr
1174
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1175 1176
                          const char *filename)
{
1177
    return virStorageVolDefParse(pool, NULL, filename);
1178
}
1179

1180
static int
1181
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
                             virBufferPtr buf,
                             virStorageVolTargetPtr def,
                             const char *type) {
    virBufferVSprintf(buf, "  <%s>\n", type);

    if (def->path)
        virBufferVSprintf(buf,"    <path>%s</path>\n", def->path);

    if (options->formatToString) {
        const char *format = (options->formatToString)(def->format);
        if (!format) {
1193
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
                                  _("unknown volume format number %d"),
                                  def->format);
            return -1;
        }
        virBufferVSprintf(buf,"    <format type='%s'/>\n", format);
    }

    virBufferAddLit(buf,"    <permissions>\n");
    virBufferVSprintf(buf,"      <mode>0%o</mode>\n",
                      def->perms.mode);
    virBufferVSprintf(buf,"      <owner>%d</owner>\n",
                      def->perms.uid);
    virBufferVSprintf(buf,"      <group>%d</group>\n",
                      def->perms.gid);


    if (def->perms.label)
        virBufferVSprintf(buf,"      <label>%s</label>\n",
                          def->perms.label);

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

1216
    if (def->encryption != NULL &&
1217
        virStorageEncryptionFormat(buf, def->encryption, 4) < 0)
1218 1219
        return -1;

1220 1221 1222 1223
    virBufferVSprintf(buf, "  </%s>\n", type);

    return 0;
}
1224 1225

char *
1226
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1227
                       virStorageVolDefPtr def) {
1228
    virStorageVolOptionsPtr options;
1229
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1230

1231
    options = virStorageVolOptionsForPoolType(pool->type);
1232 1233 1234
    if (options == NULL)
        return NULL;

1235 1236 1237 1238
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferVSprintf(&buf,"  <key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "  <source>\n");
1239 1240 1241 1242 1243 1244 1245 1246

    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)
1247 1248 1249 1250
                    virBufferAddLit(&buf, "    </device>\n");

                virBufferVSprintf(&buf, "    <device path='%s'>\n",
                                  def->source.extents[i].path);
1251 1252
            }

1253 1254 1255 1256
            virBufferVSprintf(&buf,
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1257 1258 1259
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1260
            virBufferAddLit(&buf, "    </device>\n");
1261
    }
1262
    virBufferAddLit(&buf, "  </source>\n");
1263

1264 1265 1266 1267
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
1268

1269
    if (virStorageVolTargetDefFormat(options, &buf,
1270 1271
                                     &def->target, "target") < 0)
        goto cleanup;
1272

1273
    if (def->backingStore.path &&
1274
        virStorageVolTargetDefFormat(options, &buf,
1275 1276
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1277 1278

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

1280
    if (virBufferError(&buf))
1281 1282
        goto no_memory;

1283
    return virBufferContentAndReset(&buf);
1284 1285

 no_memory:
1286
    virReportOOMError();
1287
 cleanup:
1288
    virBufferFreeAndReset(&buf);
1289 1290 1291 1292 1293
    return NULL;
}


virStoragePoolObjPtr
1294
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1295
                            const unsigned char *uuid) {
1296
    unsigned int i;
1297

1298 1299
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1300 1301
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1302 1303
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1304 1305 1306 1307 1308

    return NULL;
}

virStoragePoolObjPtr
1309
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1310
                            const char *name) {
1311
    unsigned int i;
1312

1313 1314
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1315 1316
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1317 1318
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1319 1320 1321 1322 1323 1324 1325

    return NULL;
}

void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1326 1327 1328 1329 1330 1331
    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;
1332 1333 1334 1335 1336
}

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

1339 1340 1341
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1342 1343 1344 1345 1346 1347 1348

    return NULL;
}

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

1351 1352 1353
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1354 1355 1356 1357 1358 1359 1360

    return NULL;
}

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

1363 1364 1365
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1366 1367 1368 1369 1370

    return NULL;
}

virStoragePoolObjPtr
1371
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1372 1373 1374
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1375
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1376 1377 1378 1379
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
1380
            virStoragePoolDefFree(pool->newDef);
1381 1382 1383 1384 1385
            pool->newDef = def;
        }
        return pool;
    }

1386
    if (VIR_ALLOC(pool) < 0) {
1387
        virReportOOMError();
1388 1389 1390
        return NULL;
    }

1391
    if (virMutexInit(&pool->lock) < 0) {
1392
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1393 1394 1395 1396
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(pool);
        return NULL;
    }
1397
    virStoragePoolObjLock(pool);
1398 1399 1400
    pool->active = 0;
    pool->def = def;

1401 1402
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1403
        virStoragePoolObjUnlock(pool);
1404
        virStoragePoolObjFree(pool);
1405
        virReportOOMError();
1406 1407 1408
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1409 1410 1411 1412 1413

    return pool;
}

static virStoragePoolObjPtr
1414
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1415 1416 1417 1418 1419 1420
                      const char *file,
                      const char *path,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1421
    if (!(def = virStoragePoolDefParseFile(path))) {
1422 1423 1424 1425
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1426
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
1427
                              _("Storage pool config filename '%s' does not match pool name '%s'"),
1428
                              path, def->name);
1429 1430 1431 1432
        virStoragePoolDefFree(def);
        return NULL;
    }

1433
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1434 1435 1436 1437
        virStoragePoolDefFree(def);
        return NULL;
    }

1438
    VIR_FREE(pool->configFile);  // for driver reload
1439 1440
    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
1441
        virReportOOMError();
1442 1443 1444
        virStoragePoolDefFree(def);
        return NULL;
    }
1445
    VIR_FREE(pool->autostartLink); // for driver reload
1446 1447
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
1448
        virReportOOMError();
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1461
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1462 1463
                             const char *configDir,
                             const char *autostartDir) {
1464 1465 1466
    DIR *dir;
    struct dirent *entry;

1467
    if (!(dir = opendir(configDir))) {
1468 1469
        if (errno == ENOENT)
            return 0;
1470
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1471
                             configDir);
1472 1473 1474 1475 1476 1477
        return -1;
    }

    while ((entry = readdir(dir))) {
        char path[PATH_MAX];
        char autostartLink[PATH_MAX];
1478
        virStoragePoolObjPtr pool;
1479 1480 1481 1482 1483 1484 1485

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

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

1486
        if (virFileBuildPath(configDir, entry->d_name,
1487
                             NULL, path, PATH_MAX) < 0) {
1488
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1489
                                  _("Config filename '%s/%s' is too long"),
1490
                                  configDir, entry->d_name);
1491 1492 1493
            continue;
        }

1494
        if (virFileBuildPath(autostartDir, entry->d_name,
1495
                             NULL, autostartLink, PATH_MAX) < 0) {
1496
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1497
                                  _("Autostart link path '%s/%s' is too long"),
1498
                                  autostartDir, entry->d_name);
1499 1500 1501
            continue;
        }

1502
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1503
                                     autostartLink);
1504 1505
        if (pool)
            virStoragePoolObjUnlock(pool);
1506 1507 1508 1509 1510 1511 1512 1513
    }

    closedir(dir);

    return 0;
}

int
1514
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
                         virStoragePoolObjPtr pool,
                         virStoragePoolDefPtr def) {
    char *xml;
    int fd = -1, ret = -1;
    ssize_t towrite;

    if (!pool->configFile) {
        int err;
        char path[PATH_MAX];

        if ((err = virFileMakePath(driver->configDir))) {
1526
            virReportSystemError(err,
C
Cole Robinson 已提交
1527 1528
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1529 1530 1531 1532 1533
            return -1;
        }

        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
1534
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1535
                                  "%s", _("cannot construct config file path"));
1536 1537 1538
            return -1;
        }
        if (!(pool->configFile = strdup(path))) {
1539
            virReportOOMError();
1540 1541 1542 1543 1544
            return -1;
        }

        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
1545
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1546 1547
                                  "%s", _("cannot construct "
                                          "autostart link path"));
1548
            VIR_FREE(pool->configFile);
1549 1550 1551
            return -1;
        }
        if (!(pool->autostartLink = strdup(path))) {
1552
            virReportOOMError();
1553
            VIR_FREE(pool->configFile);
1554 1555 1556 1557
            return -1;
        }
    }

1558 1559
    if (!(xml = virStoragePoolDefFormat(def))) {
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1560
                              "%s", _("failed to generate XML"));
1561 1562 1563 1564 1565 1566
        return -1;
    }

    if ((fd = open(pool->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1567
        virReportSystemError(errno,
1568 1569
                             _("cannot create config file %s"),
                             pool->configFile);
1570 1571 1572 1573 1574
        goto cleanup;
    }

    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) != towrite) {
1575
        virReportSystemError(errno,
1576 1577
                             _("cannot write config file %s"),
                             pool->configFile);
1578 1579 1580
        goto cleanup;
    }

1581
    if (VIR_CLOSE(fd) < 0) {
1582
        virReportSystemError(errno,
1583 1584
                             _("cannot save config file %s"),
                             pool->configFile);
1585 1586 1587 1588 1589 1590
        goto cleanup;
    }

    ret = 0;

 cleanup:
1591
    VIR_FORCE_CLOSE(fd);
1592
    VIR_FREE(xml);
1593 1594 1595 1596 1597

    return ret;
}

int
1598
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool) {
1599
    if (!pool->configFile) {
1600
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1601 1602 1603 1604 1605
                              _("no config file for %s"), pool->def->name);
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1606
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1607 1608 1609 1610 1611 1612 1613
                              _("cannot remove config for %s"),
                              pool->def->name);
        return -1;
    }

    return 0;
}
1614

1615
virStoragePoolSourcePtr
1616
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1617 1618 1619 1620
{
    virStoragePoolSourcePtr source;

    if (VIR_REALLOC_N(list->sources, list->nsources+1) < 0) {
1621
        virReportOOMError();
1622 1623 1624 1625 1626 1627 1628 1629 1630
        return NULL;
    }

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

    return source;
}

1631
char *virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1632
{
1633
    virStoragePoolOptionsPtr options;
1634
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1635 1636
    const char *type;
    int i;
1637

1638
    options = virStoragePoolOptionsForPoolType(def->type);
1639 1640 1641
    if (options == NULL)
        return NULL;

1642
    type = virStoragePoolTypeToString(def->type);
1643
    if (!type) {
1644
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1645 1646 1647 1648 1649
                              "%s", _("unexpected pool type"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1650 1651

    for (i = 0; i < def->nsources; i++) {
1652
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1653 1654
    }

1655 1656 1657 1658
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1659 1660

    return virBufferContentAndReset(&buf);
1661 1662

 no_memory:
1663
    virReportOOMError();
1664
 cleanup:
1665
    virBufferFreeAndReset(&buf);
1666
    return NULL;
1667
}
D
Daniel P. Berrange 已提交
1668 1669


1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 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
/*
 * 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;
}


1733 1734
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
1735
    virMutexLock(&obj->lock);
1736 1737 1738 1739
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
1740
    virMutexUnlock(&obj->lock);
1741
}