storage_conf.c 49.5 KB
Newer Older
1 2 3
/*
 * storage_conf.c: config handling for storage driver
 *
4
 * Copyright (C) 2006-2009 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

40 41 42 43
#include "xml.h"
#include "uuid.h"
#include "buf.h"
#include "util.h"
44
#include "memory.h"
45

46 47
#define VIR_FROM_THIS VIR_FROM_STORAGE

48 49 50 51 52
/* Work around broken limits.h on debian etch */
#if defined __GNUC__ && defined _GCC_LIMITS_H_ && ! defined ULLONG_MAX
# define ULLONG_MAX   ULONG_LONG_MAX
#endif

53 54 55
#define virStorageError(conn, code, fmt...)                             \
            virReportErrorHelper(conn, VIR_FROM_STORAGE, code, __FILE__,\
                                  __FUNCTION__, __LINE__, fmt)
56

57 58 59 60
VIR_ENUM_IMPL(virStoragePool,
              VIR_STORAGE_POOL_LAST,
              "dir", "fs", "netfs",
              "logical", "disk", "iscsi",
61
              "scsi")
62 63 64 65 66

VIR_ENUM_IMPL(virStoragePoolFormatFileSystem,
              VIR_STORAGE_POOL_FS_LAST,
              "auto", "ext2", "ext3",
              "ext4", "ufs", "iso9660", "udf",
67
              "gfs", "gfs2", "vfat", "hfs+", "xfs")
68 69 70

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
71
              "auto", "nfs", "glusterfs")
72 73 74 75

VIR_ENUM_IMPL(virStoragePoolFormatDisk,
              VIR_STORAGE_POOL_DISK_LAST,
              "unknown", "dos", "dvh", "gpt",
76
              "mac", "bsd", "pc98", "sun", "lvm2")
77 78 79

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
80
              "unknown", "lvm2")
81 82 83 84 85 86 87


VIR_ENUM_IMPL(virStorageVolFormatDisk,
              VIR_STORAGE_VOL_DISK_LAST,
              "none", "linux", "fat16",
              "fat32", "linux-swap",
              "linux-lvm", "linux-raid",
88
              "extended")
89 90 91 92 93

VIR_ENUM_IMPL(virStorageVolFormatFileSystem,
              VIR_STORAGE_VOL_FILE_LAST,
              "raw", "dir", "bochs",
              "cloop", "cow", "dmg", "iso",
94
              "qcow", "qcow2", "vmdk", "vpc")
95

96 97
VIR_ENUM_IMPL(virStoragePartedFsType,
              VIR_STORAGE_PARTED_FS_TYPE_LAST,
98
              "ext2", "ext2", "fat16",
99 100 101
              "fat32", "linux-swap",
              "ext2", "ext2",
              "extended")
102 103 104 105 106 107 108 109 110 111

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 {
112
    int defaultFormat;
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 147 148 149 150 151 152 153 154 155 156 157
    virStorageVolFormatToString formatToString;
    virStorageVolFormatFromString formatFromString;
};

/* Flags to indicate mandatory components in the pool source */
enum {
    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),
};



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 = {
158
            .defaultFormat = VIR_STORAGE_VOL_FILE_RAW,
159 160 161 162 163 164 165 166 167 168 169
            .formatFromString = virStorageVolFormatFileSystemTypeFromString,
            .formatToString = virStorageVolFormatFileSystemTypeToString,
        },
    },
    { .poolType = VIR_STORAGE_POOL_FS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .formatFromString = virStoragePoolFormatFileSystemTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemTypeToString,
        },
      .volOptions = {
170
            .defaultFormat = VIR_STORAGE_VOL_FILE_RAW,
171 172 173 174 175 176 177 178 179 180 181 182 183
            .formatFromString = virStorageVolFormatFileSystemTypeFromString,
            .formatToString = virStorageVolFormatFileSystemTypeToString,
        },
    },
    { .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 = {
184
            .defaultFormat = VIR_STORAGE_VOL_FILE_RAW,
185 186 187 188 189 190 191 192 193 194 195 196 197
            .formatFromString = virStorageVolFormatFileSystemTypeFromString,
            .formatToString = virStorageVolFormatFileSystemTypeToString,
        },
    },
    { .poolType = VIR_STORAGE_POOL_ISCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                      VIR_STORAGE_POOL_SOURCE_DEVICE),
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
198 199 200 201 202 203 204 205
    { .poolType = VIR_STORAGE_POOL_SCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_ADAPTER),
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
206 207 208 209 210 211 212 213
    { .poolType = VIR_STORAGE_POOL_DISK,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .defaultFormat = VIR_STORAGE_POOL_DISK_UNKNOWN,
            .formatFromString = virStoragePoolFormatDiskTypeFromString,
            .formatToString = virStoragePoolFormatDiskTypeToString,
        },
      .volOptions = {
214
            .defaultFormat = VIR_STORAGE_VOL_DISK_NONE,
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
            .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];

    virStorageReportError(NULL, VIR_ERR_INTERNAL_ERROR,
                          _("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;
}


251 252 253
void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
254 255 256 257

    if (!def)
        return;

258 259
    VIR_FREE(def->name);
    VIR_FREE(def->key);
260 261

    for (i = 0 ; i < def->source.nextent ; i++) {
262
        VIR_FREE(def->source.extents[i].path);
263
    }
264
    VIR_FREE(def->source.extents);
265

266 267
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
268 269
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
270
    VIR_FREE(def);
271 272 273
}

void
274
virStoragePoolSourceFree(virStoragePoolSourcePtr source) {
275 276
    int i;

277
    if (!source)
278 279
        return;

280 281 282 283
    VIR_FREE(source->host.name);
    for (i = 0 ; i < source->ndevice ; i++) {
        VIR_FREE(source->devices[i].freeExtents);
        VIR_FREE(source->devices[i].path);
284
    }
285 286 287
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
288
    VIR_FREE(source->adapter);
289

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

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

    VIR_FREE(def->name);

    virStoragePoolSourceFree(&def->source);
304

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


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

316 317
    virStoragePoolObjClearVols(obj);

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

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

    virMutexDestroy(&obj->lock);

326
    VIR_FREE(obj);
327 328
}

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

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

344 345
    virStoragePoolObjUnlock(pool);

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

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

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

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


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

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

    return 0;
}


static int
391 392 393 394 395
virStorageDefParsePerms(virConnectPtr conn,
                        xmlXPathContextPtr ctxt,
                        virStoragePermsPtr perms,
                        const char *permxpath,
                        int defaultmode) {
396 397
    char *mode;
    long v;
398 399 400
    int ret = -1;
    xmlNodePtr relnode;
    xmlNodePtr node;
401

402 403 404 405 406 407 408 409 410 411 412 413 414 415
    node = virXPathNode(conn, permxpath, ctxt);
    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;

    mode = virXPathString(conn, "string(./mode)", ctxt);
416
    if (!mode) {
417
        perms->mode = defaultmode;
418
    } else {
419
        char *end = NULL;
420 421
        perms->mode = strtol(mode, &end, 8);
        if (*end || perms->mode < 0 || perms->mode > 0777) {
422
            VIR_FREE(mode);
423
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
424
                                  "%s", _("malformed octal mode"));
425
            goto error;
426
        }
427
        VIR_FREE(mode);
428 429
    }

430
    if (virXPathNode(conn, "./owner", ctxt) == NULL) {
431 432
        perms->uid = getuid();
    } else {
433
        if (virXPathLong(conn, "number(./owner)", ctxt, &v) < 0) {
434
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
435
                                  "%s", _("malformed owner element"));
436
            goto error;
437 438 439 440
        }
        perms->uid = (int)v;
    }

441
    if (virXPathNode(conn, "./group", ctxt) == NULL) {
D
Daniel P. Berrange 已提交
442
        perms->gid = getgid();
443
    } else {
444
        if (virXPathLong(conn, "number(./group)", ctxt, &v) < 0) {
445
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
446
                                  "%s", _("malformed group element"));
447
            goto error;
448 449 450 451 452
        }
        perms->gid = (int)v;
    }

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

455 456 457 458
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
459 460 461
}

static virStoragePoolDefPtr
462 463
virStoragePoolDefParseXML(virConnectPtr conn,
                          xmlXPathContextPtr ctxt) {
464
    virStoragePoolOptionsPtr options;
465
    virStoragePoolDefPtr ret;
466
    char *type = NULL;
467 468 469
    char *uuid = NULL;
    char *authType = NULL;

470
    if (VIR_ALLOC(ret) < 0) {
471
        virReportOOMError(conn);
472
        return NULL;
473
    }
474

475
    type = virXPathString(conn, "string(./@type)", ctxt);
476 477 478
    if ((ret->type = virStoragePoolTypeFromString((const char *)type)) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("unknown storage pool type %s"), (const char*)type);
479
        goto cleanup;
480 481
    }

482 483 484
    xmlFree(type);
    type = NULL;

485
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
486 487 488
        goto cleanup;
    }

489
    ret->name = virXPathString(conn, "string(./name)", ctxt);
490
    if (ret->name == NULL &&
491
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
492
        ret->name = virXPathString(conn, "string(./source/name)", ctxt);
493
    if (ret->name == NULL) {
494
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
495
                              "%s", _("missing pool source name element"));
496 497 498
        goto cleanup;
    }

499
    uuid = virXPathString(conn, "string(./uuid)", ctxt);
500 501 502
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
503
                                  "%s", _("unable to generate uuid"));
504 505 506 507 508
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
509
                                  "%s", _("malformed uuid element"));
510 511
            goto cleanup;
        }
512
        VIR_FREE(uuid);
513 514 515
    }

    if (options->formatFromString) {
516
        char *format = virXPathString(conn, "string(./source/format/@type)", ctxt);
517 518 519 520 521 522
        if (format == NULL)
            ret->source.format = options->defaultFormat;
        else
            ret->source.format = options->formatFromString(format);

        if (ret->source.format < 0) {
523 524
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown pool format type %s"), format);
525
            VIR_FREE(format);
526 527
            goto cleanup;
        }
528
        VIR_FREE(format);
529 530
    }

531
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
532
        if ((ret->source.host.name = virXPathString(conn, "string(./source/host/@name)", ctxt)) == NULL) {
533
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
534
                             "%s", _("missing storage pool source host name"));
535 536 537
            goto cleanup;
        }
    }
538
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) {
539 540 541
        xmlNodePtr *nodeset = NULL;
        int nsource, i;

542
        if ((nsource = virXPathNodeSet(conn, "./source/device", ctxt, &nodeset)) < 0) {
543
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
544
                        "%s", _("cannot extract storage pool source devices"));
545 546
            goto cleanup;
        }
547 548
        if (VIR_ALLOC_N(ret->source.devices, nsource) < 0) {
            VIR_FREE(nodeset);
549
            virReportOOMError(conn);
550 551 552 553 554
            goto cleanup;
        }
        for (i = 0 ; i < nsource ; i++) {
            xmlChar *path = xmlGetProp(nodeset[i], BAD_CAST "path");
            if (path == NULL) {
555
                VIR_FREE(nodeset);
556
                virStorageReportError(conn, VIR_ERR_XML_ERROR,
557
                        "%s", _("missing storage pool source device path"));
558 559 560 561
                goto cleanup;
            }
            ret->source.devices[i].path = (char *)path;
        }
562
        VIR_FREE(nodeset);
563 564
        ret->source.ndevice = nsource;
    }
565
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
566
        if ((ret->source.dir = virXPathString(conn, "string(./source/dir/@path)", ctxt)) == NULL) {
567
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
568
                                "%s", _("missing storage pool source path"));
569 570 571
            goto cleanup;
        }
    }
572
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
573
        ret->source.name = virXPathString(conn, "string(./source/name)",
574 575 576 577
                                          ctxt);
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
            ret->source.name = strdup(ret->name);
578
            if (ret->source.name == NULL) {
579
                virReportOOMError(conn);
580 581
                goto cleanup;
            }
582 583
        }
    }
584

585 586
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
        if ((ret->source.adapter = virXPathString(conn,
587
                                                  "string(./source/adapter/@name)",
588 589 590 591 592 593
                                                  ctxt)) == NULL) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                             "%s", _("missing storage pool source adapter name"));
            goto cleanup;
        }
    }
594

595
    authType = virXPathString(conn, "string(./source/auth/@type)", ctxt);
596 597 598 599 600 601 602 603 604
    if (authType == NULL) {
        ret->source.authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            ret->source.authType = VIR_STORAGE_POOL_AUTH_CHAP;
        } else {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown auth type '%s'"),
                                  (const char *)authType);
605
            VIR_FREE(authType);
606 607
            goto cleanup;
        }
608
        VIR_FREE(authType);
609 610 611 612 613 614 615
    }

    if (ret->source.authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        if (virStoragePoolDefParseAuthChap(conn, ctxt, &ret->source.auth.chap) < 0)
            goto cleanup;
    }

616
    if ((ret->target.path = virXPathString(conn, "string(./target/path)", ctxt)) == NULL) {
617
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
618
                              "%s", _("missing storage pool target path"));
619 620 621
        goto cleanup;
    }

622
    if (virStorageDefParsePerms(conn, ctxt, &ret->target.perms,
623
                                "./target/permissions", 0700) < 0)
624 625 626 627 628
        goto cleanup;

    return ret;

 cleanup:
629
    VIR_FREE(uuid);
630
    xmlFree(type);
631 632 633 634
    virStoragePoolDefFree(ret);
    return NULL;
}

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
/* 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) {
        virConnectPtr conn = ctxt->_private;

        if (conn &&
            conn->err.code == VIR_ERR_NONE &&
            ctxt->lastError.level == XML_ERR_FATAL &&
            ctxt->lastError.message != NULL) {
            virStorageReportError (conn, VIR_ERR_XML_DETAIL,
                                   _("at line %d: %s"),
                                   ctxt->lastError.line,
                                   ctxt->lastError.message);
        }
    }
}

656
virStoragePoolDefPtr
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
virStoragePoolDefParseNode(virConnectPtr conn,
                           xmlDocPtr xml,
                           xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStoragePoolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "pool")) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
                          "%s", _("unknown root element for storage pool"));
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virReportOOMError(conn);
        goto cleanup;
    }

    ctxt->node = root;
    def = virStoragePoolDefParseXML(conn, ctxt);
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStoragePoolDefPtr
683 684 685 686
virStoragePoolDefParse(virConnectPtr conn,
                       const char *xmlStr,
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
687
    xmlParserCtxtPtr pctxt;
688 689 690
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;

691 692 693 694 695 696 697 698
    /* 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;
    pctxt->_private = conn;

    if (conn) virResetError (&conn->err);
699 700 701 702 703 704 705 706 707 708 709
    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);
    }

710 711 712
    if (!xml) {
        if (conn && conn->err.code == VIR_ERR_NONE)
              virStorageReportError(conn, VIR_ERR_XML_ERROR,
D
Daniel P. Berrange 已提交
713
                                    "%s",_("failed to parse xml document"));
714 715 716 717 718 719
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
720
                              "%s", _("missing root element"));
721 722 723
        goto cleanup;
    }

724
    ret = virStoragePoolDefParseNode(conn, xml, node);
725

726
    xmlFreeParserCtxt (pctxt);
727 728 729 730 731
    xmlFreeDoc(xml);

    return ret;

 cleanup:
732
    xmlFreeParserCtxt (pctxt);
733 734 735 736
    xmlFreeDoc(xml);
    return NULL;
}

737 738 739 740 741 742 743 744 745 746 747 748 749 750
virStoragePoolDefPtr
virStoragePoolDefParseString(virConnectPtr conn,
                             const char *xmlStr)
{
    return virStoragePoolDefParse(conn, xmlStr, NULL);
}

virStoragePoolDefPtr
virStoragePoolDefParseFile(virConnectPtr conn,
                           const char *filename)
{
    return virStoragePoolDefParse(conn, NULL, filename);
}

751 752 753
static int
virStoragePoolSourceFormat(virConnectPtr conn,
                           virBufferPtr buf,
754
                           virStoragePoolOptionsPtr options,
755 756 757 758 759
                           virStoragePoolSourcePtr src)
{
    int i, j;

    virBufferAddLit(buf,"  <source>\n");
760
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) &&
761 762 763
        src->host.name)
        virBufferVSprintf(buf,"    <host name='%s'/>\n", src->host.name);

764
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
        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);
        }
    }
782
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
783 784
        src->dir)
        virBufferVSprintf(buf,"    <dir path='%s'/>\n", src->dir);
785
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
786 787
        src->adapter)
        virBufferVSprintf(buf,"    <adapter name='%s'/>\n", src->adapter);
788
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
        src->name)
        virBufferVSprintf(buf,"    <name>%s</name>\n", src->name);

    if (options->formatToString) {
        const char *format = (options->formatToString)(src->format);
        if (!format) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                                  _("unknown pool format number %d"),
                                  src->format);
            return -1;
        }
        virBufferVSprintf(buf,"    <format type='%s'/>\n", format);
    }


    if (src->authType == VIR_STORAGE_POOL_AUTH_CHAP)
        virBufferVSprintf(buf,"    <auth type='chap' login='%s' passwd='%s'>\n",
                          src->auth.chap.login,
                          src->auth.chap.passwd);
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

813 814 815 816

char *
virStoragePoolDefFormat(virConnectPtr conn,
                        virStoragePoolDefPtr def) {
817
    virStoragePoolOptionsPtr options;
818
    virBuffer buf = VIR_BUFFER_INITIALIZER;
819 820 821
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

822
    options = virStoragePoolOptionsForPoolType(def->type);
823 824 825
    if (options == NULL)
        return NULL;

826
    type = virStoragePoolTypeToString(def->type);
827 828
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
829
                              "%s", _("unexpected pool type"));
830 831
        goto cleanup;
    }
832 833
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
834 835

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

838 839 840 841 842 843
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
    virBufferVSprintf(&buf,"  <available>%llu</available>\n",
                      def->available);
844

845 846
    if (virStoragePoolSourceFormat(conn, &buf, options, &def->source) < 0)
        goto cleanup;
847

848
    virBufferAddLit(&buf,"  <target>\n");
849

850 851
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
852

853 854 855 856 857 858 859
    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);
860

861 862 863
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);
864

865 866 867
    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf,"  </target>\n");
    virBufferAddLit(&buf,"</pool>\n");
868

869
    if (virBufferError(&buf))
870 871
        goto no_memory;

872
    return virBufferContentAndReset(&buf);
873 874

 no_memory:
875
    virReportOOMError(conn);
876
 cleanup:
877
    free(virBufferContentAndReset(&buf));
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
    return NULL;
}


static int
virStorageSize(virConnectPtr conn,
               const char *unit,
               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;

        case 'y':
        case 'Y':
            mult = 1024ull * 1024ull * 1024ull * 1024ull * 1024ull *
                1024ull;
            break;

        case 'z':
        case 'Z':
            mult = 1024ull * 1024ull * 1024ull * 1024ull * 1024ull *
                1024ull * 1024ull;
            break;

        default:
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown size units '%s'"), unit);
            return -1;
        }
    }

    if (virStrToLong_ull (val, &end, 10, ret) < 0) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
940
                              "%s", _("malformed capacity element"));
941 942 943 944
        return -1;
    }
    if (*ret > (ULLONG_MAX / mult)) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
945
                              "%s", _("capacity element value too large"));
946 947 948 949 950 951 952 953 954
            return -1;
    }

    *ret *= mult;

    return 0;
}

static virStorageVolDefPtr
955
virStorageVolDefParseXML(virConnectPtr conn,
956
                         virStoragePoolDefPtr pool,
957
                         xmlXPathContextPtr ctxt) {
958
    virStorageVolDefPtr ret;
959
    virStorageVolOptionsPtr options;
960 961 962 963
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;

964
    options = virStorageVolOptionsForPoolType(pool->type);
965 966 967
    if (options == NULL)
        return NULL;

968
    if (VIR_ALLOC(ret) < 0) {
969
        virReportOOMError(conn);
970
        return NULL;
971
    }
972

973
    ret->name = virXPathString(conn, "string(./name)", ctxt);
974 975
    if (ret->name == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
976
                              "%s", _("missing volume name element"));
977 978 979
        goto cleanup;
    }

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

983 984
    capacity = virXPathString(conn, "string(./capacity)", ctxt);
    unit = virXPathString(conn, "string(./capacity/@unit)", ctxt);
985 986
    if (capacity == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
987
                              "%s", _("missing capacity element"));
988 989 990 991
        goto cleanup;
    }
    if (virStorageSize(conn, unit, capacity, &ret->capacity) < 0)
        goto cleanup;
992 993
    VIR_FREE(capacity);
    VIR_FREE(unit);
994

995
    allocation = virXPathString(conn, "string(./allocation)", ctxt);
996
    if (allocation) {
997
        unit = virXPathString(conn, "string(./allocation/@unit)", ctxt);
998 999
        if (virStorageSize(conn, unit, allocation, &ret->allocation) < 0)
            goto cleanup;
1000 1001
        VIR_FREE(allocation);
        VIR_FREE(unit);
1002 1003 1004 1005
    } else {
        ret->allocation = ret->capacity;
    }

1006
    ret->target.path = virXPathString(conn, "string(./target/path)", ctxt);
1007
    if (options->formatFromString) {
1008
        char *format = virXPathString(conn, "string(./target/format/@type)", ctxt);
1009 1010 1011 1012 1013 1014
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1015 1016
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown volume format type %s"), format);
1017
            VIR_FREE(format);
1018 1019
            goto cleanup;
        }
1020
        VIR_FREE(format);
1021 1022
    }

1023
    if (virStorageDefParsePerms(conn, ctxt, &ret->target.perms,
1024
                                "./target/permissions", 0600) < 0)
1025 1026
        goto cleanup;

1027 1028


1029
    ret->backingStore.path = virXPathString(conn, "string(./backingStore/path)", ctxt);
1030
    if (options->formatFromString) {
1031
        char *format = virXPathString(conn, "string(./backingStore/format/@type)", ctxt);
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
        if (format == NULL)
            ret->backingStore.format = options->defaultFormat;
        else
            ret->backingStore.format = (options->formatFromString)(format);

        if (ret->backingStore.format < 0) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown volume format type %s"), format);
            VIR_FREE(format);
            goto cleanup;
        }
        VIR_FREE(format);
    }

1046
    if (virStorageDefParsePerms(conn, ctxt, &ret->backingStore.perms,
1047
                                "./backingStore/permissions", 0600) < 0)
1048 1049
        goto cleanup;

1050 1051 1052
    return ret;

 cleanup:
1053 1054 1055
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1056 1057 1058 1059 1060
    virStorageVolDefFree(ret);
    return NULL;
}

virStorageVolDefPtr
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
virStorageVolDefParseNode(virConnectPtr conn,
                          virStoragePoolDefPtr pool,
                          xmlDocPtr xml,
                          xmlNodePtr root) {
    xmlXPathContextPtr ctxt = NULL;
    virStorageVolDefPtr def = NULL;

    if (STRNEQ((const char *)root->name, "volume")) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
                          "%s", _("unknown root element for storage vol"));
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virReportOOMError(conn);
        goto cleanup;
    }

    ctxt->node = root;
    def = virStorageVolDefParseXML(conn, pool, ctxt);
cleanup:
    xmlXPathFreeContext(ctxt);
    return def;
}

static virStorageVolDefPtr
1088 1089 1090 1091 1092
virStorageVolDefParse(virConnectPtr conn,
                      virStoragePoolDefPtr pool,
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
1093
    xmlParserCtxtPtr pctxt;
1094 1095 1096
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;

1097 1098 1099 1100 1101 1102 1103 1104
    /* 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;
    pctxt->_private = conn;

    if (conn) virResetError (&conn->err);
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116

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

1117 1118 1119
    if (!xml) {
        if (conn && conn->err.code == VIR_ERR_NONE)
              virStorageReportError(conn, VIR_ERR_XML_ERROR,
D
Daniel P. Berrange 已提交
1120
                                    "%s", _("failed to parse xml document"));
1121 1122 1123 1124 1125 1126
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1127
                              "%s", _("missing root element"));
1128 1129 1130
        goto cleanup;
    }

1131
    ret = virStorageVolDefParseNode(conn, pool, xml, node);
1132

1133
    xmlFreeParserCtxt (pctxt);
1134 1135 1136 1137 1138
    xmlFreeDoc(xml);

    return ret;

 cleanup:
1139
    xmlFreeParserCtxt (pctxt);
1140 1141 1142 1143
    xmlFreeDoc(xml);
    return NULL;
}

1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
virStorageVolDefPtr
virStorageVolDefParseString(virConnectPtr conn,
                            virStoragePoolDefPtr pool,
                            const char *xmlStr)
{
    return virStorageVolDefParse(conn, pool, xmlStr, NULL);
}

virStorageVolDefPtr
virStorageVolDefParseFile(virConnectPtr conn,
                          virStoragePoolDefPtr pool,
                          const char *filename)
{
    return virStorageVolDefParse(conn, pool, NULL, filename);
}
1159

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
static int
virStorageVolTargetDefFormat(virConnectPtr conn,
                             virStorageVolOptionsPtr options,
                             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) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                                  _("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");

    virBufferVSprintf(buf, "  </%s>\n", type);

    return 0;
}
1201 1202 1203 1204 1205

char *
virStorageVolDefFormat(virConnectPtr conn,
                       virStoragePoolDefPtr pool,
                       virStorageVolDefPtr def) {
1206
    virStorageVolOptionsPtr options;
1207
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1208
    char *tmp;
1209

1210
    options = virStorageVolOptionsForPoolType(pool->type);
1211 1212 1213
    if (options == NULL)
        return NULL;

1214 1215 1216 1217
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferVSprintf(&buf,"  <key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "  <source>\n");
1218 1219 1220 1221 1222 1223 1224 1225

    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)
1226 1227 1228 1229
                    virBufferAddLit(&buf, "    </device>\n");

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

1232 1233 1234 1235
            virBufferVSprintf(&buf,
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1236 1237 1238
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1239
            virBufferAddLit(&buf, "    </device>\n");
1240
    }
1241
    virBufferAddLit(&buf, "  </source>\n");
1242

1243 1244 1245 1246
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
1247

1248 1249 1250
    if (virStorageVolTargetDefFormat(conn, options, &buf,
                                     &def->target, "target") < 0)
        goto cleanup;
1251

1252 1253 1254 1255
    if (def->backingStore.path &&
        virStorageVolTargetDefFormat(conn, options, &buf,
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1256 1257

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

1259
    if (virBufferError(&buf))
1260 1261
        goto no_memory;

1262
    return virBufferContentAndReset(&buf);
1263 1264

 no_memory:
1265
    virReportOOMError(conn);
1266
 cleanup:
1267 1268
    tmp = virBufferContentAndReset(&buf);
    VIR_FREE(tmp);
1269 1270 1271 1272 1273
    return NULL;
}


virStoragePoolObjPtr
1274
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1275
                            const unsigned char *uuid) {
1276
    unsigned int i;
1277

1278 1279
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1280 1281
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1282 1283
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1284 1285 1286 1287 1288

    return NULL;
}

virStoragePoolObjPtr
1289
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1290
                            const char *name) {
1291
    unsigned int i;
1292

1293 1294
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1295 1296
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1297 1298
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1299 1300 1301 1302 1303 1304 1305

    return NULL;
}

void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1306 1307 1308 1309 1310 1311
    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;
1312 1313 1314 1315 1316
}

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

1319 1320 1321
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1322 1323 1324 1325 1326 1327 1328

    return NULL;
}

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

1331 1332 1333
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1334 1335 1336 1337 1338 1339 1340

    return NULL;
}

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

1343 1344 1345
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1346 1347 1348 1349 1350 1351

    return NULL;
}

virStoragePoolObjPtr
virStoragePoolObjAssignDef(virConnectPtr conn,
1352
                           virStoragePoolObjListPtr pools,
1353 1354 1355
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1356
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
            if (pool->newDef)
                virStoragePoolDefFree(pool->newDef);
            pool->newDef = def;
        }
        return pool;
    }

1368
    if (VIR_ALLOC(pool) < 0) {
1369
        virReportOOMError(conn);
1370 1371 1372
        return NULL;
    }

1373 1374 1375 1376 1377 1378
    if (virMutexInit(&pool->lock) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(pool);
        return NULL;
    }
1379
    virStoragePoolObjLock(pool);
1380 1381 1382
    pool->active = 0;
    pool->def = def;

1383 1384
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1385
        virStoragePoolObjUnlock(pool);
1386
        virStoragePoolObjFree(pool);
1387
        virReportOOMError(conn);
1388 1389 1390
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1391 1392 1393 1394 1395

    return pool;
}

static virStoragePoolObjPtr
1396 1397
virStoragePoolObjLoad(virConnectPtr conn,
                      virStoragePoolObjListPtr pools,
1398 1399 1400 1401 1402 1403
                      const char *file,
                      const char *path,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1404
    if (!(def = virStoragePoolDefParseFile(conn, path))) {
1405 1406 1407 1408
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1409 1410
        virStorageError(conn, VIR_ERR_INVALID_STORAGE_POOL,
            "Storage pool config filename '%s' does not match pool name '%s'",
1411 1412 1413 1414 1415
                      path, def->name);
        virStoragePoolDefFree(def);
        return NULL;
    }

1416
    if (!(pool = virStoragePoolObjAssignDef(conn, pools, def))) {
1417 1418 1419 1420 1421 1422
        virStoragePoolDefFree(def);
        return NULL;
    }

    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
1423
        virReportOOMError(conn);
1424 1425 1426 1427 1428
        virStoragePoolDefFree(def);
        return NULL;
    }
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
1429
        virReportOOMError(conn);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1442 1443 1444 1445
virStoragePoolLoadAllConfigs(virConnectPtr conn,
                             virStoragePoolObjListPtr pools,
                             const char *configDir,
                             const char *autostartDir) {
1446 1447 1448
    DIR *dir;
    struct dirent *entry;

1449
    if (!(dir = opendir(configDir))) {
1450 1451
        if (errno == ENOENT)
            return 0;
1452 1453
        virReportSystemError(conn, errno, _("Failed to open dir '%s'"),
                             configDir);
1454 1455 1456 1457 1458 1459
        return -1;
    }

    while ((entry = readdir(dir))) {
        char path[PATH_MAX];
        char autostartLink[PATH_MAX];
1460
        virStoragePoolObjPtr pool;
1461 1462 1463 1464 1465 1466 1467

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

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

1468
        if (virFileBuildPath(configDir, entry->d_name,
1469
                             NULL, path, PATH_MAX) < 0) {
1470 1471 1472
            virStorageError(conn, VIR_ERR_INTERNAL_ERROR,
                            "Config filename '%s/%s' is too long",
                            configDir, entry->d_name);
1473 1474 1475
            continue;
        }

1476
        if (virFileBuildPath(autostartDir, entry->d_name,
1477
                             NULL, autostartLink, PATH_MAX) < 0) {
1478 1479 1480
            virStorageError(conn, VIR_ERR_INTERNAL_ERROR,
                            "Autostart link path '%s/%s' is too long",
                            autostartDir, entry->d_name);
1481 1482 1483
            continue;
        }

1484 1485
        pool = virStoragePoolObjLoad(conn, pools, entry->d_name, path,
                                     autostartLink);
1486 1487
        if (pool)
            virStoragePoolObjUnlock(pool);
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
    }

    closedir(dir);

    return 0;
}

int
virStoragePoolObjSaveDef(virConnectPtr conn,
                         virStorageDriverStatePtr driver,
                         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))) {
1509 1510 1511
            virStorageReportError(conn, err,
                                  _("cannot create config directory %s"),
                                  driver->configDir);
1512 1513 1514 1515 1516 1517
            return -1;
        }

        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1518
                                  "%s", _("cannot construct config file path"));
1519 1520 1521
            return -1;
        }
        if (!(pool->configFile = strdup(path))) {
1522
            virReportOOMError(conn);
1523 1524 1525 1526 1527 1528
            return -1;
        }

        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1529 1530
                                  "%s", _("cannot construct "
                                          "autostart link path"));
1531
            VIR_FREE(pool->configFile);
1532 1533 1534
            return -1;
        }
        if (!(pool->autostartLink = strdup(path))) {
1535
            virReportOOMError(conn);
1536
            VIR_FREE(pool->configFile);
1537 1538 1539 1540 1541 1542
            return -1;
        }
    }

    if (!(xml = virStoragePoolDefFormat(conn, def))) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1543
                              "%s", _("failed to generate XML"));
1544 1545 1546 1547 1548 1549
        return -1;
    }

    if ((fd = open(pool->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1550 1551 1552
        virReportSystemError(conn, errno,
                             _("cannot create config file %s"),
                             pool->configFile);
1553 1554 1555 1556 1557
        goto cleanup;
    }

    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) != towrite) {
1558 1559 1560
        virReportSystemError(conn, errno,
                             _("cannot write config file %s"),
                             pool->configFile);
1561 1562 1563 1564
        goto cleanup;
    }

    if (close(fd) < 0) {
1565 1566 1567
        virReportSystemError(conn, errno,
                             _("cannot save config file %s"),
                             pool->configFile);
1568 1569 1570 1571 1572 1573 1574 1575 1576
        goto cleanup;
    }

    ret = 0;

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

1577
    VIR_FREE(xml);
1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599

    return ret;
}

int
virStoragePoolObjDeleteDef(virConnectPtr conn,
                           virStoragePoolObjPtr pool) {
    if (!pool->configFile) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("no config file for %s"), pool->def->name);
        return -1;
    }

    if (unlink(pool->configFile) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("cannot remove config for %s"),
                              pool->def->name);
        return -1;
    }

    return 0;
}
1600

1601
char *virStoragePoolSourceListFormat(virConnectPtr conn,
1602 1603
                                     virStoragePoolSourceListPtr def)
{
1604
    virStoragePoolOptionsPtr options;
1605
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1606 1607
    const char *type;
    int i;
1608

1609
    options = virStoragePoolOptionsForPoolType(def->type);
1610 1611 1612
    if (options == NULL)
        return NULL;

1613
    type = virStoragePoolTypeToString(def->type);
1614 1615 1616 1617 1618 1619 1620
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              "%s", _("unexpected pool type"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1621 1622

    for (i = 0; i < def->nsources; i++) {
1623
        virStoragePoolSourceFormat(conn, &buf, options, &def->sources[i]);
1624 1625
    }

1626 1627 1628 1629
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1630 1631

    return virBufferContentAndReset(&buf);
1632 1633

 no_memory:
1634
    virReportOOMError(conn);
1635 1636 1637
 cleanup:
    free(virBufferContentAndReset(&buf));
    return NULL;
1638
}
D
Daniel P. Berrange 已提交
1639 1640


1641 1642
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
1643
    virMutexLock(&obj->lock);
1644 1645 1646 1647
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
1648
    virMutexUnlock(&obj->lock);
1649
}