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

47 48
#define VIR_FROM_THIS VIR_FROM_STORAGE

49

50 51 52 53
VIR_ENUM_IMPL(virStoragePool,
              VIR_STORAGE_POOL_LAST,
              "dir", "fs", "netfs",
              "logical", "disk", "iscsi",
D
Dave Allan 已提交
54
              "scsi", "mpath")
55 56 57 58 59

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

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

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

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


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

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

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

/* Flags to indicate mandatory components in the pool source */
enum {
D
David Allan 已提交
106 107 108 109 110 111
    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),
112 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
};



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

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


245 246 247
void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
248 249 250 251

    if (!def)
        return;

252 253
    VIR_FREE(def->name);
    VIR_FREE(def->key);
254 255

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

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

void
270
virStoragePoolSourceFree(virStoragePoolSourcePtr source) {
271 272
    int i;

273
    if (!source)
274 275
        return;

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

287 288 289
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
290
    }
291 292 293 294 295 296 297 298 299 300
}

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

    VIR_FREE(def->name);

    virStoragePoolSourceFree(&def->source);
301

302 303 304
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
305 306 307 308 309
}


void
virStoragePoolObjFree(virStoragePoolObjPtr obj) {
310 311 312
    if (!obj)
        return;

313 314
    virStoragePoolObjClearVols(obj);

315 316
    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
317

318 319
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
320 321 322

    virMutexDestroy(&obj->lock);

323
    VIR_FREE(obj);
324 325
}

326 327 328 329 330 331 332 333 334
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;
}

335
void
336
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
337 338
                        virStoragePoolObjPtr pool)
{
339
    unsigned int i;
340

341 342
    virStoragePoolObjUnlock(pool);

343
    for (i = 0 ; i < pools->count ; i++) {
344
        virStoragePoolObjLock(pools->objs[i]);
345
        if (pools->objs[i] == pool) {
346
            virStoragePoolObjUnlock(pools->objs[i]);
347
            virStoragePoolObjFree(pools->objs[i]);
348

349 350 351
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
352

353 354 355 356
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
357

358 359
            break;
        }
360
        virStoragePoolObjUnlock(pools->objs[i]);
361
    }
362 363 364 365
}


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

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

    return 0;
}

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

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

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

403
    source->name = virXPathString("string(./name)", ctxt);
404 405

    if (options->formatFromString) {
406
        char *format = virXPathString("string(./format/@type)", ctxt);
407 408 409 410 411 412
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

        if (source->format < 0) {
413
            virStorageReportError(VIR_ERR_XML_ERROR,
414 415 416 417 418 419 420
                                  _("unknown pool format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

421 422
    source->host.name = virXPathString("string(./host/@name)", ctxt);
    source->initiator.iqn = virXPathString("string(./initiator/iqn/@name)", ctxt);
423

424
    nsource = virXPathNodeSet("./device", ctxt, &nodeset);
425 426 427
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
428
            virReportOOMError();
429 430 431 432 433 434 435
            goto cleanup;
        }

        for (i = 0 ; i < nsource ; i++) {
            xmlChar *path = xmlGetProp(nodeset[i], BAD_CAST "path");
            if (path == NULL) {
                VIR_FREE(nodeset);
436
                virStorageReportError(VIR_ERR_XML_ERROR,
437 438 439 440 441 442 443 444
                        "%s", _("missing storage pool source device path"));
                goto cleanup;
            }
            source->devices[i].path = (char *)path;
        }
        source->ndevice = nsource;
    }

445 446
    source->dir = virXPathString("string(./dir/@path)", ctxt);
    source->adapter = virXPathString("string(./adapter/@name)", ctxt);
447

448
    authType = virXPathString("string(./auth/@type)", ctxt);
449 450 451 452 453 454
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
        } else {
455
            virStorageReportError(VIR_ERR_XML_ERROR,
456 457 458 459 460 461 462
                                  _("unknown auth type '%s'"),
                                  (const char *)authType);
            goto cleanup;
        }
    }

    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
463
        if (virStoragePoolDefParseAuthChap(ctxt, &source->auth.chap) < 0)
464 465 466 467 468 469 470 471 472 473 474
            goto cleanup;
    }

    ret = 0;
cleanup:
    ctxt->node = relnode;

    VIR_FREE(authType);
    VIR_FREE(nodeset);
    return ret;
}
475

476
virStoragePoolSourcePtr
477
virStoragePoolDefParseSourceString(const char *srcSpec,
478 479 480 481 482 483 484 485 486 487 488 489
                                   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) {
490
        virStorageReportError(VIR_ERR_XML_ERROR,
491 492 493 494 495 496
                              "%s", _("bad <source> spec"));
        goto cleanup;
    }

    xpath_ctxt = xmlXPathNewContext(doc);
    if (xpath_ctxt == NULL) {
497
        virReportOOMError();
498 499 500 501
        goto cleanup;
    }

    if (VIR_ALLOC(def) < 0) {
502
        virReportOOMError();
503 504 505
        goto cleanup;
    }

506
    node = virXPathNode("/source", xpath_ctxt);
507
    if (!node) {
508
        virStorageReportError(VIR_ERR_XML_ERROR,
509 510 511 512
                              "%s", _("root element was not source"));
        goto cleanup;
    }

513
    if (virStoragePoolDefParseSource(xpath_ctxt, def, pool_type,
514 515 516 517 518 519
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
520 521
    virStoragePoolSourceFree(def);
    VIR_FREE(def);
522 523 524 525 526
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

    return ret;
}
527
static int
528
virStorageDefParsePerms(xmlXPathContextPtr ctxt,
529 530 531
                        virStoragePermsPtr perms,
                        const char *permxpath,
                        int defaultmode) {
532 533
    char *mode;
    long v;
534 535 536
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
537

538
    node = virXPathNode(permxpath, ctxt);
539 540 541 542 543 544 545 546 547 548 549 550
    if (node == NULL) {
        /* Set default values if there is not <permissions> element */
        perms->mode = defaultmode;
        perms->uid = getuid();
        perms->gid = getgid();
        perms->label = NULL;
        return 0;
    }

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

551
    mode = virXPathString("string(./mode)", ctxt);
552
    if (!mode) {
553
        perms->mode = defaultmode;
554
    } else {
555
        char *end = NULL;
556 557
        perms->mode = strtol(mode, &end, 8);
        if (*end || perms->mode < 0 || perms->mode > 0777) {
558
            VIR_FREE(mode);
559
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
560
                                  "%s", _("malformed octal mode"));
561
            goto error;
562
        }
563
        VIR_FREE(mode);
564 565
    }

566
    if (virXPathNode("./owner", ctxt) == NULL) {
567 568
        perms->uid = getuid();
    } else {
569
        if (virXPathLong("number(./owner)", ctxt, &v) < 0) {
570
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
571
                                  "%s", _("malformed owner element"));
572
            goto error;
573 574 575 576
        }
        perms->uid = (int)v;
    }

577
    if (virXPathNode("./group", ctxt) == NULL) {
D
Daniel P. Berrange 已提交
578
        perms->gid = getgid();
579
    } else {
580
        if (virXPathLong("number(./group)", ctxt, &v) < 0) {
581
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
582
                                  "%s", _("malformed group element"));
583
            goto error;
584 585 586 587 588
        }
        perms->gid = (int)v;
    }

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

591 592 593 594
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
595 596 597
}

static virStoragePoolDefPtr
598
virStoragePoolDefParseXML(xmlXPathContextPtr ctxt) {
599
    virStoragePoolOptionsPtr options;
600
    virStoragePoolDefPtr ret;
601
    xmlNodePtr source_node;
602
    char *type = NULL;
603 604
    char *uuid = NULL;

605
    if (VIR_ALLOC(ret) < 0) {
606
        virReportOOMError();
607
        return NULL;
608
    }
609

610
    type = virXPathString("string(./@type)", ctxt);
611
    if ((ret->type = virStoragePoolTypeFromString((const char *)type)) < 0) {
612
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
613
                              _("unknown storage pool type %s"), (const char*)type);
614
        goto cleanup;
615 616
    }

617 618 619
    xmlFree(type);
    type = NULL;

620
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
621 622 623
        goto cleanup;
    }

624
    source_node = virXPathNode("./source", ctxt);
625
    if (source_node) {
626
        if (virStoragePoolDefParseSource(ctxt, &ret->source, ret->type,
627 628 629 630
                                         source_node) < 0)
            goto cleanup;
    }

631
    ret->name = virXPathString("string(./name)", ctxt);
632
    if (ret->name == NULL &&
633
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
634
        ret->name = ret->source.name;
635
    if (ret->name == NULL) {
636
        virStorageReportError(VIR_ERR_XML_ERROR,
637
                              "%s", _("missing pool source name element"));
638 639 640
        goto cleanup;
    }

641
    uuid = virXPathString("string(./uuid)", ctxt);
642 643
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
644
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
645
                                  "%s", _("unable to generate uuid"));
646 647 648 649
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
650
            virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
651
                                  "%s", _("malformed uuid element"));
652 653
            goto cleanup;
        }
654
        VIR_FREE(uuid);
655 656
    }

657
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
658
        if (!ret->source.host.name) {
659
            virStorageReportError(VIR_ERR_XML_ERROR,
660 661
                                  "%s",
                                  _("missing storage pool source host name"));
662 663 664 665
            goto cleanup;
        }
    }

666
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
667
        if (!ret->source.dir) {
668
            virStorageReportError(VIR_ERR_XML_ERROR,
669
                                  "%s", _("missing storage pool source path"));
670 671 672
            goto cleanup;
        }
    }
673
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
674 675 676
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
            ret->source.name = strdup(ret->name);
677
            if (ret->source.name == NULL) {
678
                virReportOOMError();
679 680
                goto cleanup;
            }
681 682
        }
    }
683

684
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
685
        if (!ret->source.adapter) {
686
            virStorageReportError(VIR_ERR_XML_ERROR,
687
                                  "%s", _("missing storage pool source adapter name"));
688 689 690
            goto cleanup;
        }
    }
691

692 693 694 695 696 697 698 699 700
    /* 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;
        }
    }

701
    if ((ret->target.path = virXPathString("string(./target/path)", ctxt)) == NULL) {
702
        virStorageReportError(VIR_ERR_XML_ERROR,
703
                              "%s", _("missing storage pool target path"));
704 705 706
        goto cleanup;
    }

707
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
708
                                "./target/permissions", 0700) < 0)
709 710 711 712 713
        goto cleanup;

    return ret;

 cleanup:
714
    VIR_FREE(uuid);
715
    xmlFree(type);
716 717 718 719
    virStoragePoolDefFree(ret);
    return NULL;
}

720 721 722 723 724 725 726
/* Called from SAX on parsing errors in the XML. */
static void
catchXMLError (void *ctx, const char *msg ATTRIBUTE_UNUSED, ...)
{
    xmlParserCtxtPtr ctxt = (xmlParserCtxtPtr) ctx;

    if (ctxt) {
727
        if (virGetLastError() == NULL &&
728 729
            ctxt->lastError.level == XML_ERR_FATAL &&
            ctxt->lastError.message != NULL) {
730
            virStorageReportError (VIR_ERR_XML_DETAIL,
731 732 733 734 735 736 737
                                   _("at line %d: %s"),
                                   ctxt->lastError.line,
                                   ctxt->lastError.message);
        }
    }
}

738
virStoragePoolDefPtr
739
virStoragePoolDefParseNode(xmlDocPtr xml,
740 741 742 743 744
                           xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "pool")) {
745 746
        virStorageReportError(VIR_ERR_XML_ERROR,
                              "%s", _("unknown root element for storage pool"));
747 748 749 750 751
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
752
        virReportOOMError();
753 754 755 756
        goto cleanup;
    }

    ctxt->node = root;
757
    def = virStoragePoolDefParseXML(ctxt);
758 759 760 761 762 763
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
764
virStoragePoolDefParse(const char *xmlStr,
765 766
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
767
    xmlParserCtxtPtr pctxt;
768 769 770
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;

771 772 773 774 775 776
    /* Set up a parser context so we can catch the details of XML errors. */
    pctxt = xmlNewParserCtxt ();
    if (!pctxt || !pctxt->sax)
        goto cleanup;
    pctxt->sax->error = catchXMLError;

777 778 779 780 781 782 783 784 785 786 787
    if (filename) {
        xml = xmlCtxtReadFile (pctxt, filename, NULL,
                               XML_PARSE_NOENT | XML_PARSE_NONET |
                               XML_PARSE_NOWARNING);
    } else {
        xml = xmlCtxtReadDoc (pctxt, BAD_CAST xmlStr,
                              "storage.xml", NULL,
                              XML_PARSE_NOENT | XML_PARSE_NONET |
                              XML_PARSE_NOWARNING);
    }

788
    if (!xml) {
789 790 791
        if (virGetLastError() == NULL)
            virStorageReportError(VIR_ERR_XML_ERROR,
                                  "%s",_("failed to parse xml document"));
792 793 794 795 796
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
797
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
798
                              "%s", _("missing root element"));
799 800 801
        goto cleanup;
    }

802
    ret = virStoragePoolDefParseNode(xml, node);
803

804
    xmlFreeParserCtxt (pctxt);
805 806 807 808 809
    xmlFreeDoc(xml);

    return ret;

 cleanup:
810
    xmlFreeParserCtxt (pctxt);
811 812 813 814
    xmlFreeDoc(xml);
    return NULL;
}

815
virStoragePoolDefPtr
816
virStoragePoolDefParseString(const char *xmlStr)
817
{
818
    return virStoragePoolDefParse(xmlStr, NULL);
819 820 821
}

virStoragePoolDefPtr
822
virStoragePoolDefParseFile(const char *filename)
823
{
824
    return virStoragePoolDefParse(NULL, filename);
825 826
}

827
static int
828
virStoragePoolSourceFormat(virBufferPtr buf,
829
                           virStoragePoolOptionsPtr options,
830 831 832 833 834
                           virStoragePoolSourcePtr src)
{
    int i, j;

    virBufferAddLit(buf,"  <source>\n");
835
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) &&
836 837 838
        src->host.name)
        virBufferVSprintf(buf,"    <host name='%s'/>\n", src->host.name);

839
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
        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);
        }
    }
857
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
858 859
        src->dir)
        virBufferVSprintf(buf,"    <dir path='%s'/>\n", src->dir);
860
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
861 862
        src->adapter)
        virBufferVSprintf(buf,"    <adapter name='%s'/>\n", src->adapter);
863
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
864 865 866 867 868 869
        src->name)
        virBufferVSprintf(buf,"    <name>%s</name>\n", src->name);

    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
870
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
871 872 873 874 875 876 877 878 879
                                  _("unknown pool format number %d"),
                                  src->format);
            return -1;
        }
        virBufferVSprintf(buf,"    <format type='%s'/>\n", format);
    }


    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
880
        virBufferVSprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
881 882 883 884 885 886 887
                          src->auth.chap.login,
                          src->auth.chap.passwd);
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

888 889

char *
890
virStoragePoolDefFormat(virStoragePoolDefPtr def) {
891
    virStoragePoolOptionsPtr options;
892
    virBuffer buf = VIR_BUFFER_INITIALIZER;
893 894 895
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

896
    options = virStoragePoolOptionsForPoolType(def->type);
897 898 899
    if (options == NULL)
        return NULL;

900
    type = virStoragePoolTypeToString(def->type);
901
    if (!type) {
902
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
903
                              "%s", _("unexpected pool type"));
904 905
        goto cleanup;
    }
906 907
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
908 909

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

912 913 914 915 916 917
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
    virBufferVSprintf(&buf,"  <available>%llu</available>\n",
                      def->available);
918

919
    if (virStoragePoolSourceFormat(&buf, options, &def->source) < 0)
920
        goto cleanup;
921

922
    virBufferAddLit(&buf,"  <target>\n");
923

924 925
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
926

927 928 929 930 931 932 933
    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);
934

935 936 937
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);
938

939 940 941
    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf,"  </target>\n");
    virBufferAddLit(&buf,"</pool>\n");
942

943
    if (virBufferError(&buf))
944 945
        goto no_memory;

946
    return virBufferContentAndReset(&buf);
947 948

 no_memory:
949
    virReportOOMError();
950
 cleanup:
951
    virBufferFreeAndReset(&buf);
952 953 954 955 956
    return NULL;
}


static int
957
virStorageSize(const char *unit,
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
               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;

992 993
        case 'e':
        case 'E':
994 995 996 997 998
            mult = 1024ull * 1024ull * 1024ull * 1024ull * 1024ull *
                1024ull;
            break;

        default:
999
            virStorageReportError(VIR_ERR_XML_ERROR,
1000 1001 1002 1003 1004 1005
                                  _("unknown size units '%s'"), unit);
            return -1;
        }
    }

    if (virStrToLong_ull (val, &end, 10, ret) < 0) {
1006
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1007
                              "%s", _("malformed capacity element"));
1008 1009 1010
        return -1;
    }
    if (*ret > (ULLONG_MAX / mult)) {
1011
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1012
                              "%s", _("capacity element value too large"));
1013 1014 1015 1016 1017 1018 1019 1020 1021
            return -1;
    }

    *ret *= mult;

    return 0;
}

static virStorageVolDefPtr
1022
virStorageVolDefParseXML(virStoragePoolDefPtr pool,
1023
                         xmlXPathContextPtr ctxt) {
1024
    virStorageVolDefPtr ret;
1025
    virStorageVolOptionsPtr options;
1026 1027 1028
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1029
    xmlNodePtr node;
1030

1031
    options = virStorageVolOptionsForPoolType(pool->type);
1032 1033 1034
    if (options == NULL)
        return NULL;

1035
    if (VIR_ALLOC(ret) < 0) {
1036
        virReportOOMError();
1037
        return NULL;
1038
    }
1039

1040
    ret->name = virXPathString("string(./name)", ctxt);
1041
    if (ret->name == NULL) {
1042
        virStorageReportError(VIR_ERR_XML_ERROR,
1043
                              "%s", _("missing volume name element"));
1044 1045 1046
        goto cleanup;
    }

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

1050 1051
    capacity = virXPathString("string(./capacity)", ctxt);
    unit = virXPathString("string(./capacity/@unit)", ctxt);
1052
    if (capacity == NULL) {
1053
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1054
                              "%s", _("missing capacity element"));
1055 1056
        goto cleanup;
    }
1057
    if (virStorageSize(unit, capacity, &ret->capacity) < 0)
1058
        goto cleanup;
1059 1060
    VIR_FREE(capacity);
    VIR_FREE(unit);
1061

1062
    allocation = virXPathString("string(./allocation)", ctxt);
1063
    if (allocation) {
1064
        unit = virXPathString("string(./allocation/@unit)", ctxt);
1065
        if (virStorageSize(unit, allocation, &ret->allocation) < 0)
1066
            goto cleanup;
1067 1068
        VIR_FREE(allocation);
        VIR_FREE(unit);
1069 1070 1071 1072
    } else {
        ret->allocation = ret->capacity;
    }

1073
    ret->target.path = virXPathString("string(./target/path)", ctxt);
1074
    if (options->formatFromString) {
1075
        char *format = virXPathString("string(./target/format/@type)", ctxt);
1076 1077 1078 1079 1080 1081
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1082
            virStorageReportError(VIR_ERR_XML_ERROR,
1083
                                  _("unknown volume format type %s"), format);
1084
            VIR_FREE(format);
1085 1086
            goto cleanup;
        }
1087
        VIR_FREE(format);
1088 1089
    }

1090
    if (virStorageDefParsePerms(ctxt, &ret->target.perms,
1091
                                "./target/permissions", 0600) < 0)
1092 1093
        goto cleanup;

1094
    node = virXPathNode("./target/encryption", ctxt);
1095
    if (node != NULL) {
1096
        ret->target.encryption = virStorageEncryptionParseNode(ctxt->doc,
1097 1098 1099 1100 1101
                                                               node);
        if (ret->target.encryption == NULL)
            goto cleanup;
    }

1102 1103


1104
    ret->backingStore.path = virXPathString("string(./backingStore/path)", ctxt);
1105
    if (options->formatFromString) {
1106
        char *format = virXPathString("string(./backingStore/format/@type)", ctxt);
1107 1108 1109 1110 1111 1112
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
1113
            virStorageReportError(VIR_ERR_XML_ERROR,
1114 1115 1116 1117 1118 1119 1120
                                  _("unknown volume format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

1121
    if (virStorageDefParsePerms(ctxt, &ret->backingStore.perms,
1122
                                "./backingStore/permissions", 0600) < 0)
1123 1124
        goto cleanup;

1125 1126 1127
    return ret;

 cleanup:
1128 1129 1130
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1131 1132 1133 1134 1135
    virStorageVolDefFree(ret);
    return NULL;
}

virStorageVolDefPtr
1136
virStorageVolDefParseNode(virStoragePoolDefPtr pool,
1137 1138 1139 1140 1141 1142
                          xmlDocPtr xml,
                          xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "volume")) {
1143
        virStorageReportError(VIR_ERR_XML_ERROR,
1144 1145 1146 1147 1148 1149
                          "%s", _("unknown root element for storage vol"));
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1150
        virReportOOMError();
1151 1152 1153 1154
        goto cleanup;
    }

    ctxt->node = root;
1155
    def = virStorageVolDefParseXML(pool, ctxt);
1156 1157 1158 1159 1160 1161
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1162
virStorageVolDefParse(virStoragePoolDefPtr pool,
1163 1164 1165
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
1166
    xmlParserCtxtPtr pctxt;
1167 1168 1169
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;

1170 1171 1172 1173 1174
    /* Set up a parser context so we can catch the details of XML errors. */
    pctxt = xmlNewParserCtxt ();
    if (!pctxt || !pctxt->sax)
        goto cleanup;
    pctxt->sax->error = catchXMLError;
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186

    if (filename) {
        xml = xmlCtxtReadFile (pctxt, filename, NULL,
                               XML_PARSE_NOENT | XML_PARSE_NONET |
                               XML_PARSE_NOWARNING);
    } else {
        xml = xmlCtxtReadDoc (pctxt, BAD_CAST xmlStr,
                              "storage.xml", NULL,
                              XML_PARSE_NOENT | XML_PARSE_NONET |
                              XML_PARSE_NOWARNING);
    }

1187
    if (!xml) {
1188 1189 1190
        if (virGetLastError() == NULL)
            virStorageReportError(VIR_ERR_XML_ERROR,
                                  "%s", _("failed to parse xml document"));
1191 1192 1193 1194 1195
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
1196
        virStorageReportError(VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1197
                              "%s", _("missing root element"));
1198 1199 1200
        goto cleanup;
    }

1201
    ret = virStorageVolDefParseNode(pool, xml, node);
1202

1203
    xmlFreeParserCtxt (pctxt);
1204 1205 1206 1207 1208
    xmlFreeDoc(xml);

    return ret;

 cleanup:
1209
    xmlFreeParserCtxt (pctxt);
1210 1211 1212 1213
    xmlFreeDoc(xml);
    return NULL;
}

1214
virStorageVolDefPtr
1215
virStorageVolDefParseString(virStoragePoolDefPtr pool,
1216 1217
                            const char *xmlStr)
{
1218
    return virStorageVolDefParse(pool, xmlStr, NULL);
1219 1220 1221
}

virStorageVolDefPtr
1222
virStorageVolDefParseFile(virStoragePoolDefPtr pool,
1223 1224
                          const char *filename)
{
1225
    return virStorageVolDefParse(pool, NULL, filename);
1226
}
1227

1228
static int
1229
virStorageVolTargetDefFormat(virStorageVolOptionsPtr options,
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
                             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) {
1241
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
                                  _("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");

1264
    if (def->encryption != NULL &&
1265
        virStorageEncryptionFormat(buf, def->encryption) < 0)
1266 1267
        return -1;

1268 1269 1270 1271
    virBufferVSprintf(buf, "  </%s>\n", type);

    return 0;
}
1272 1273

char *
1274
virStorageVolDefFormat(virStoragePoolDefPtr pool,
1275
                       virStorageVolDefPtr def) {
1276
    virStorageVolOptionsPtr options;
1277
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1278

1279
    options = virStorageVolOptionsForPoolType(pool->type);
1280 1281 1282
    if (options == NULL)
        return NULL;

1283 1284 1285 1286
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferVSprintf(&buf,"  <key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "  <source>\n");
1287 1288 1289 1290 1291 1292 1293 1294

    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)
1295 1296 1297 1298
                    virBufferAddLit(&buf, "    </device>\n");

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

1301 1302 1303 1304
            virBufferVSprintf(&buf,
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1305 1306 1307
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1308
            virBufferAddLit(&buf, "    </device>\n");
1309
    }
1310
    virBufferAddLit(&buf, "  </source>\n");
1311

1312 1313 1314 1315
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
1316

1317
    if (virStorageVolTargetDefFormat(options, &buf,
1318 1319
                                     &def->target, "target") < 0)
        goto cleanup;
1320

1321
    if (def->backingStore.path &&
1322
        virStorageVolTargetDefFormat(options, &buf,
1323 1324
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1325 1326

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

1328
    if (virBufferError(&buf))
1329 1330
        goto no_memory;

1331
    return virBufferContentAndReset(&buf);
1332 1333

 no_memory:
1334
    virReportOOMError();
1335
 cleanup:
1336
    virBufferFreeAndReset(&buf);
1337 1338 1339 1340 1341
    return NULL;
}


virStoragePoolObjPtr
1342
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1343
                            const unsigned char *uuid) {
1344
    unsigned int i;
1345

1346 1347
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1348 1349
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1350 1351
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1352 1353 1354 1355 1356

    return NULL;
}

virStoragePoolObjPtr
1357
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1358
                            const char *name) {
1359
    unsigned int i;
1360

1361 1362
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1363 1364
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1365 1366
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1367 1368 1369 1370 1371 1372 1373

    return NULL;
}

void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1374 1375 1376 1377 1378 1379
    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;
1380 1381 1382 1383 1384
}

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

1387 1388 1389
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1390 1391 1392 1393 1394 1395 1396

    return NULL;
}

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

1399 1400 1401
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1402 1403 1404 1405 1406 1407 1408

    return NULL;
}

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

1411 1412 1413
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1414 1415 1416 1417 1418

    return NULL;
}

virStoragePoolObjPtr
1419
virStoragePoolObjAssignDef(virStoragePoolObjListPtr pools,
1420 1421 1422
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1423
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
            if (pool->newDef)
                virStoragePoolDefFree(pool->newDef);
            pool->newDef = def;
        }
        return pool;
    }

1435
    if (VIR_ALLOC(pool) < 0) {
1436
        virReportOOMError();
1437 1438 1439
        return NULL;
    }

1440
    if (virMutexInit(&pool->lock) < 0) {
1441
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1442 1443 1444 1445
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(pool);
        return NULL;
    }
1446
    virStoragePoolObjLock(pool);
1447 1448 1449
    pool->active = 0;
    pool->def = def;

1450 1451
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1452
        virStoragePoolObjUnlock(pool);
1453
        virStoragePoolObjFree(pool);
1454
        virReportOOMError();
1455 1456 1457
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1458 1459 1460 1461 1462

    return pool;
}

static virStoragePoolObjPtr
1463
virStoragePoolObjLoad(virStoragePoolObjListPtr pools,
1464 1465 1466 1467 1468 1469
                      const char *file,
                      const char *path,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1470
    if (!(def = virStoragePoolDefParseFile(path))) {
1471 1472 1473 1474
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1475
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
1476
                              _("Storage pool config filename '%s' does not match pool name '%s'"),
1477
                              path, def->name);
1478 1479 1480 1481
        virStoragePoolDefFree(def);
        return NULL;
    }

1482
    if (!(pool = virStoragePoolObjAssignDef(pools, def))) {
1483 1484 1485 1486 1487 1488
        virStoragePoolDefFree(def);
        return NULL;
    }

    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
1489
        virReportOOMError();
1490 1491 1492 1493 1494
        virStoragePoolDefFree(def);
        return NULL;
    }
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
1495
        virReportOOMError();
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1508
virStoragePoolLoadAllConfigs(virStoragePoolObjListPtr pools,
1509 1510
                             const char *configDir,
                             const char *autostartDir) {
1511 1512 1513
    DIR *dir;
    struct dirent *entry;

1514
    if (!(dir = opendir(configDir))) {
1515 1516
        if (errno == ENOENT)
            return 0;
1517
        virReportSystemError(errno, _("Failed to open dir '%s'"),
1518
                             configDir);
1519 1520 1521 1522 1523 1524
        return -1;
    }

    while ((entry = readdir(dir))) {
        char path[PATH_MAX];
        char autostartLink[PATH_MAX];
1525
        virStoragePoolObjPtr pool;
1526 1527 1528 1529 1530 1531 1532

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

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

1533
        if (virFileBuildPath(configDir, entry->d_name,
1534
                             NULL, path, PATH_MAX) < 0) {
1535
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1536
                                  _("Config filename '%s/%s' is too long"),
1537
                                  configDir, entry->d_name);
1538 1539 1540
            continue;
        }

1541
        if (virFileBuildPath(autostartDir, entry->d_name,
1542
                             NULL, autostartLink, PATH_MAX) < 0) {
1543
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1544
                                  _("Autostart link path '%s/%s' is too long"),
1545
                                  autostartDir, entry->d_name);
1546 1547 1548
            continue;
        }

1549
        pool = virStoragePoolObjLoad(pools, entry->d_name, path,
1550
                                     autostartLink);
1551 1552
        if (pool)
            virStoragePoolObjUnlock(pool);
1553 1554 1555 1556 1557 1558 1559 1560
    }

    closedir(dir);

    return 0;
}

int
1561
virStoragePoolObjSaveDef(virStorageDriverStatePtr driver,
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
                         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))) {
1573
            virReportSystemError(err,
C
Cole Robinson 已提交
1574 1575
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1576 1577 1578 1579 1580
            return -1;
        }

        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
1581
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1582
                                  "%s", _("cannot construct config file path"));
1583 1584 1585
            return -1;
        }
        if (!(pool->configFile = strdup(path))) {
1586
            virReportOOMError();
1587 1588 1589 1590 1591
            return -1;
        }

        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
1592
            virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1593 1594
                                  "%s", _("cannot construct "
                                          "autostart link path"));
1595
            VIR_FREE(pool->configFile);
1596 1597 1598
            return -1;
        }
        if (!(pool->autostartLink = strdup(path))) {
1599
            virReportOOMError();
1600
            VIR_FREE(pool->configFile);
1601 1602 1603 1604
            return -1;
        }
    }

1605 1606
    if (!(xml = virStoragePoolDefFormat(def))) {
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1607
                              "%s", _("failed to generate XML"));
1608 1609 1610 1611 1612 1613
        return -1;
    }

    if ((fd = open(pool->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1614
        virReportSystemError(errno,
1615 1616
                             _("cannot create config file %s"),
                             pool->configFile);
1617 1618 1619 1620 1621
        goto cleanup;
    }

    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) != towrite) {
1622
        virReportSystemError(errno,
1623 1624
                             _("cannot write config file %s"),
                             pool->configFile);
1625 1626 1627 1628
        goto cleanup;
    }

    if (close(fd) < 0) {
1629
        virReportSystemError(errno,
1630 1631
                             _("cannot save config file %s"),
                             pool->configFile);
1632 1633 1634 1635 1636 1637 1638 1639 1640
        goto cleanup;
    }

    ret = 0;

 cleanup:
    if (fd != -1)
        close(fd);

1641
    VIR_FREE(xml);
1642 1643 1644 1645 1646

    return ret;
}

int
1647
virStoragePoolObjDeleteDef(virStoragePoolObjPtr pool) {
1648
    if (!pool->configFile) {
1649
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1650 1651 1652 1653 1654
                              _("no config file for %s"), pool->def->name);
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
1655
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1656 1657 1658 1659 1660 1661 1662
                              _("cannot remove config for %s"),
                              pool->def->name);
        return -1;
    }

    return 0;
}
1663

1664
virStoragePoolSourcePtr
1665
virStoragePoolSourceListNewSource(virStoragePoolSourceListPtr list)
1666 1667 1668 1669
{
    virStoragePoolSourcePtr source;

    if (VIR_REALLOC_N(list->sources, list->nsources+1) < 0) {
1670
        virReportOOMError();
1671 1672 1673 1674 1675 1676 1677 1678 1679
        return NULL;
    }

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

    return source;
}

1680
char *virStoragePoolSourceListFormat(virStoragePoolSourceListPtr def)
1681
{
1682
    virStoragePoolOptionsPtr options;
1683
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1684 1685
    const char *type;
    int i;
1686

1687
    options = virStoragePoolOptionsForPoolType(def->type);
1688 1689 1690
    if (options == NULL)
        return NULL;

1691
    type = virStoragePoolTypeToString(def->type);
1692
    if (!type) {
1693
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1694 1695 1696 1697 1698
                              "%s", _("unexpected pool type"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1699 1700

    for (i = 0; i < def->nsources; i++) {
1701
        virStoragePoolSourceFormat(&buf, options, &def->sources[i]);
1702 1703
    }

1704 1705 1706 1707
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1708 1709

    return virBufferContentAndReset(&buf);
1710 1711

 no_memory:
1712
    virReportOOMError();
1713
 cleanup:
1714
    virBufferFreeAndReset(&buf);
1715
    return NULL;
1716
}
D
Daniel P. Berrange 已提交
1717 1718


1719 1720
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
1721
    virMutexLock(&obj->lock);
1722 1723 1724 1725
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
1726
    virMutexUnlock(&obj->lock);
1727
}