storage_conf.c 48.0 KB
Newer Older
1 2 3 4 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
/*
 * storage_conf.c: config handling for storage driver
 *
 * Copyright (C) 2006-2008 Red Hat, Inc.
 * 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
#define virStorageLog(msg...) fprintf(stderr, msg)

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

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
69
              "auto", "nfs")
70 71 72 73

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

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
78
              "unknown", "lvm2")
79 80 81 82 83 84 85


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

VIR_ENUM_IMPL(virStorageVolFormatFileSystem,
              VIR_STORAGE_VOL_FILE_LAST,
              "raw", "dir", "bochs",
              "cloop", "cow", "dmg", "iso",
92
              "qcow", "qcow2", "vmdk", "vpc")
93 94 95 96 97 98 99 100 101 102 103


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 {
104
    int defaultFormat;
105 106 107 108 109 110 111 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 146 147 148 149
    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 = {
150
            .defaultFormat = VIR_STORAGE_VOL_FILE_RAW,
151 152 153 154 155 156 157 158 159 160 161
            .formatFromString = virStorageVolFormatFileSystemTypeFromString,
            .formatToString = virStorageVolFormatFileSystemTypeToString,
        },
    },
    { .poolType = VIR_STORAGE_POOL_FS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .formatFromString = virStoragePoolFormatFileSystemTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemTypeToString,
        },
      .volOptions = {
162
            .defaultFormat = VIR_STORAGE_VOL_FILE_RAW,
163 164 165 166 167 168 169 170 171 172 173 174 175
            .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 = {
176
            .defaultFormat = VIR_STORAGE_VOL_FILE_RAW,
177 178 179 180 181 182 183 184 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,
        }
    },
    { .poolType = VIR_STORAGE_POOL_DISK,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .defaultFormat = VIR_STORAGE_POOL_DISK_UNKNOWN,
            .formatFromString = virStoragePoolFormatDiskTypeFromString,
            .formatToString = virStoragePoolFormatDiskTypeToString,
        },
      .volOptions = {
198
            .defaultFormat = VIR_STORAGE_VOL_DISK_NONE,
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
            .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;
}


235 236 237
void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
238 239 240 241

    if (!def)
        return;

242 243
    VIR_FREE(def->name);
    VIR_FREE(def->key);
244 245

    for (i = 0 ; i < def->source.nextent ; i++) {
246
        VIR_FREE(def->source.extents[i].path);
247
    }
248
    VIR_FREE(def->source.extents);
249

250 251
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
252 253
    VIR_FREE(def->backingStore.path);
    VIR_FREE(def->backingStore.perms.label);
254
    VIR_FREE(def);
255 256 257
}

void
258
virStoragePoolSourceFree(virStoragePoolSourcePtr source) {
259 260
    int i;

261
    if (!source)
262 263
        return;

264 265 266 267
    VIR_FREE(source->host.name);
    for (i = 0 ; i < source->ndevice ; i++) {
        VIR_FREE(source->devices[i].freeExtents);
        VIR_FREE(source->devices[i].path);
268
    }
269 270 271
    VIR_FREE(source->devices);
    VIR_FREE(source->dir);
    VIR_FREE(source->name);
272

273 274 275
    if (source->authType == VIR_STORAGE_POOL_AUTH_CHAP) {
        VIR_FREE(source->auth.chap.login);
        VIR_FREE(source->auth.chap.passwd);
276
    }
277 278 279 280 281 282 283 284 285 286
}

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

    VIR_FREE(def->name);

    virStoragePoolSourceFree(&def->source);
287

288 289 290
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
291 292 293 294 295
}


void
virStoragePoolObjFree(virStoragePoolObjPtr obj) {
296 297 298 299 300
    if (!obj)
        return;

    virStoragePoolDefFree(obj->def);
    virStoragePoolDefFree(obj->newDef);
301

302 303
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
304 305 306

    virMutexDestroy(&obj->lock);

307
    VIR_FREE(obj);
308 309
}

310 311 312 313 314 315 316 317 318
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;
}

319
void
320
virStoragePoolObjRemove(virStoragePoolObjListPtr pools,
321 322
                        virStoragePoolObjPtr pool)
{
323
    unsigned int i;
324

325 326
    virStoragePoolObjUnlock(pool);

327
    for (i = 0 ; i < pools->count ; i++) {
328
        virStoragePoolObjLock(pools->objs[i]);
329
        if (pools->objs[i] == pool) {
330
            virStoragePoolObjUnlock(pools->objs[i]);
331
            virStoragePoolObjFree(pools->objs[i]);
332

333 334 335
            if (i < (pools->count - 1))
                memmove(pools->objs + i, pools->objs + i + 1,
                        sizeof(*(pools->objs)) * (pools->count - (i + 1)));
336

337 338 339 340
            if (VIR_REALLOC_N(pools->objs, pools->count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pools->count--;
341

342 343
            break;
        }
344
        virStoragePoolObjUnlock(pools->objs[i]);
345
    }
346 347 348 349 350 351 352
}


static int
virStoragePoolDefParseAuthChap(virConnectPtr conn,
                               xmlXPathContextPtr ctxt,
                               virStoragePoolAuthChapPtr auth) {
353
    auth->login = virXPathString(conn, "string(/pool/source/auth/@login)", ctxt);
354 355
    if (auth->login == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
356
                              "%s", _("missing auth host attribute"));
357 358 359
        return -1;
    }

360
    auth->passwd = virXPathString(conn, "string(/pool/source/auth/@passwd)", ctxt);
361 362
    if (auth->passwd == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
363
                              "%s", _("missing auth passwd attribute"));
364 365 366 367 368 369 370 371 372 373 374 375 376 377
        return -1;
    }

    return 0;
}


static int
virStoragePoolDefParsePerms(virConnectPtr conn,
                            xmlXPathContextPtr ctxt,
                            virStoragePermsPtr perms) {
    char *mode;
    long v;

378
    mode = virXPathString(conn, "string(/pool/permissions/mode)", ctxt);
379 380 381 382 383 384 385
    if (!mode) {
        perms->mode = 0700;
    } else {
        char *end;
        perms->mode = strtol(mode, &end, 8);
        if (*end || perms->mode < 0 || perms->mode > 0777) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
386
                                  "%s", _("malformed octal mode"));
387 388 389 390
            return -1;
        }
    }

391
    if (virXPathNode(conn, "/pool/permissions/owner", ctxt) == NULL) {
392 393
        perms->uid = getuid();
    } else {
394
        if (virXPathLong(conn, "number(/pool/permissions/owner)", ctxt, &v) < 0) {
395
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
396
                                  "%s", _("malformed owner element"));
397 398 399 400 401
            return -1;
        }
        perms->uid = (int)v;
    }

402
    if (virXPathNode(conn, "/pool/permissions/group", ctxt) == NULL) {
D
Daniel P. Berrange 已提交
403
        perms->gid = getgid();
404
    } else {
405
        if (virXPathLong(conn, "number(/pool/permissions/group)", ctxt, &v) < 0) {
406
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
407
                                  "%s", _("malformed group element"));
408 409 410 411 412 413
            return -1;
        }
        perms->gid = (int)v;
    }

    /* NB, we're ignoring missing labels here - they'll simply inherit */
414
    perms->label = virXPathString(conn, "string(/pool/permissions/label)", ctxt);
415 416 417 418 419 420 421 422 423

    return 0;
}


static virStoragePoolDefPtr
virStoragePoolDefParseDoc(virConnectPtr conn,
                          xmlXPathContextPtr ctxt,
                          xmlNodePtr root) {
424
    virStoragePoolOptionsPtr options;
425 426 427 428 429
    virStoragePoolDefPtr ret;
    xmlChar *type = NULL;
    char *uuid = NULL;
    char *authType = NULL;

430
    if (VIR_ALLOC(ret) < 0) {
431
        virReportOOMError(conn);
432
        return NULL;
433
    }
434 435 436

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

    type = xmlGetProp(root, BAD_CAST "type");
442 443 444
    if ((ret->type = virStoragePoolTypeFromString((const char *)type)) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("unknown storage pool type %s"), (const char*)type);
445
        goto cleanup;
446 447
    }

448 449 450
    xmlFree(type);
    type = NULL;

451
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
452 453 454
        goto cleanup;
    }

455 456
    ret->name = virXPathString(conn, "string(/pool/name)", ctxt);
    if (ret->name == NULL &&
457
        options->flags & VIR_STORAGE_POOL_SOURCE_NAME)
458 459
        ret->name = virXPathString(conn, "string(/pool/source/name)", ctxt);
    if (ret->name == NULL) {
460
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
461
                              "%s", _("missing pool source name element"));
462 463 464
        goto cleanup;
    }

465
    uuid = virXPathString(conn, "string(/pool/uuid)", ctxt);
466 467 468
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
469
                                  "%s", _("unable to generate uuid"));
470 471 472 473 474
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
475
                                  "%s", _("malformed uuid element"));
476 477
            goto cleanup;
        }
478
        VIR_FREE(uuid);
479 480 481
    }

    if (options->formatFromString) {
482
        char *format = virXPathString(conn, "string(/pool/source/format/@type)", ctxt);
483 484 485 486 487 488
        if (format == NULL)
            ret->source.format = options->defaultFormat;
        else
            ret->source.format = options->formatFromString(format);

        if (ret->source.format < 0) {
489 490
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown pool format type %s"), format);
491
            VIR_FREE(format);
492 493
            goto cleanup;
        }
494
        VIR_FREE(format);
495 496
    }

497
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
498
        if ((ret->source.host.name = virXPathString(conn, "string(/pool/source/host/@name)", ctxt)) == NULL) {
499
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
500
                             "%s", _("missing storage pool source host name"));
501 502 503
            goto cleanup;
        }
    }
504
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) {
505 506 507
        xmlNodePtr *nodeset = NULL;
        int nsource, i;

508
        if ((nsource = virXPathNodeSet(conn, "/pool/source/device", ctxt, &nodeset)) < 0) {
509
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
510
                        "%s", _("cannot extract storage pool source devices"));
511 512
            goto cleanup;
        }
513 514
        if (VIR_ALLOC_N(ret->source.devices, nsource) < 0) {
            VIR_FREE(nodeset);
515
            virReportOOMError(conn);
516 517 518 519 520
            goto cleanup;
        }
        for (i = 0 ; i < nsource ; i++) {
            xmlChar *path = xmlGetProp(nodeset[i], BAD_CAST "path");
            if (path == NULL) {
521
                VIR_FREE(nodeset);
522
                virStorageReportError(conn, VIR_ERR_XML_ERROR,
523
                        "%s", _("missing storage pool source device path"));
524 525 526 527
                goto cleanup;
            }
            ret->source.devices[i].path = (char *)path;
        }
528
        VIR_FREE(nodeset);
529 530
        ret->source.ndevice = nsource;
    }
531
    if (options->flags & VIR_STORAGE_POOL_SOURCE_DIR) {
532
        if ((ret->source.dir = virXPathString(conn, "string(/pool/source/dir/@path)", ctxt)) == NULL) {
533
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
534
                                "%s", _("missing storage pool source path"));
535 536 537
            goto cleanup;
        }
    }
538
    if (options->flags & VIR_STORAGE_POOL_SOURCE_NAME) {
539 540 541 542 543
        ret->source.name = virXPathString(conn, "string(/pool/source/name)",
                                          ctxt);
        if (ret->source.name == NULL) {
            /* source name defaults to pool name */
            ret->source.name = strdup(ret->name);
544
            if (ret->source.name == NULL) {
545
                virReportOOMError(conn);
546 547
                goto cleanup;
            }
548 549
        }
    }
550 551


552
    authType = virXPathString(conn, "string(/pool/source/auth/@type)", ctxt);
553 554 555 556 557 558 559 560 561
    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);
562
            VIR_FREE(authType);
563 564
            goto cleanup;
        }
565
        VIR_FREE(authType);
566 567 568 569 570 571 572
    }

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

573
    if ((ret->target.path = virXPathString(conn, "string(/pool/target/path)", ctxt)) == NULL) {
574
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
575
                              "%s", _("missing storage pool target path"));
576 577 578 579 580 581 582 583 584
        goto cleanup;
    }

    if (virStoragePoolDefParsePerms(conn, ctxt, &ret->target.perms) < 0)
        goto cleanup;

    return ret;

 cleanup:
585
    VIR_FREE(uuid);
586
    xmlFree(type);
587 588 589 590
    virStoragePoolDefFree(ret);
    return NULL;
}

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
/* 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);
        }
    }
}

612 613 614 615 616
virStoragePoolDefPtr
virStoragePoolDefParse(virConnectPtr conn,
                       const char *xmlStr,
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
617
    xmlParserCtxtPtr pctxt;
618 619 620 621
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr ctxt = NULL;

622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    /* 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);
    xml = xmlCtxtReadDoc (pctxt, BAD_CAST xmlStr,
                          filename ? filename : "storage.xml", NULL,
                          XML_PARSE_NOENT | XML_PARSE_NONET |
                          XML_PARSE_NOWARNING);
    if (!xml) {
        if (conn && conn->err.code == VIR_ERR_NONE)
              virStorageReportError(conn, VIR_ERR_XML_ERROR,
D
Daniel P. Berrange 已提交
637
                                    "%s",_("failed to parse xml document"));
638 639 640 641 642
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
643
        virReportOOMError(conn);
644 645 646 647 648 649
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
650
                              "%s", _("missing root element"));
651 652 653 654 655
        goto cleanup;
    }

    ret = virStoragePoolDefParseDoc(conn, ctxt, node);

656
    xmlFreeParserCtxt (pctxt);
657 658 659 660 661 662
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);

    return ret;

 cleanup:
663
    xmlFreeParserCtxt (pctxt);
664 665 666 667 668
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    return NULL;
}

669 670 671
static int
virStoragePoolSourceFormat(virConnectPtr conn,
                           virBufferPtr buf,
672
                           virStoragePoolOptionsPtr options,
673 674 675 676 677
                           virStoragePoolSourcePtr src)
{
    int i, j;

    virBufferAddLit(buf,"  <source>\n");
678
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) &&
679 680 681
        src->host.name)
        virBufferVSprintf(buf,"    <host name='%s'/>\n", src->host.name);

682
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
        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);
        }
    }
700
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
701 702
        src->dir)
        virBufferVSprintf(buf,"    <dir path='%s'/>\n", src->dir);
703
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
704 705
        src->adapter)
        virBufferVSprintf(buf,"    <adapter name='%s'/>\n", src->adapter);
706
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
        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;
}

731 732 733 734

char *
virStoragePoolDefFormat(virConnectPtr conn,
                        virStoragePoolDefPtr def) {
735
    virStoragePoolOptionsPtr options;
736
    virBuffer buf = VIR_BUFFER_INITIALIZER;
737 738 739
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

740
    options = virStoragePoolOptionsForPoolType(def->type);
741 742 743
    if (options == NULL)
        return NULL;

744
    type = virStoragePoolTypeToString(def->type);
745 746
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
747
                              "%s", _("unexpected pool type"));
748 749
        goto cleanup;
    }
750 751
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
752 753

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

756 757 758 759 760 761
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
    virBufferVSprintf(&buf,"  <available>%llu</available>\n",
                      def->available);
762

763 764
    if (virStoragePoolSourceFormat(conn, &buf, options, &def->source) < 0)
        goto cleanup;
765

766
    virBufferAddLit(&buf,"  <target>\n");
767

768 769
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
770

771 772 773 774 775 776 777
    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);
778

779 780 781
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);
782

783 784 785
    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf,"  </target>\n");
    virBufferAddLit(&buf,"</pool>\n");
786

787
    if (virBufferError(&buf))
788 789
        goto no_memory;

790
    return virBufferContentAndReset(&buf);
791 792

 no_memory:
793
    virReportOOMError(conn);
794
 cleanup:
795
    free(virBufferContentAndReset(&buf));
796 797 798 799 800 801 802 803 804 805 806
    return NULL;
}


static int
virStorageVolDefParsePerms(virConnectPtr conn,
                           xmlXPathContextPtr ctxt,
                           virStoragePermsPtr perms) {
    char *mode;
    long v;

807
    mode = virXPathString(conn, "string(/volume/permissions/mode)", ctxt);
808 809 810 811 812 813 814
    if (!mode) {
        perms->mode = 0600;
    } else {
        char *end = NULL;
        perms->mode = strtol(mode, &end, 8);
        if (*end || perms->mode < 0 || perms->mode > 0777) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
815
                                  "%s", _("malformed octal mode"));
816 817 818 819
            return -1;
        }
    }

820
    if (virXPathNode(conn, "/volume/permissions/owner", ctxt) == NULL) {
821 822
        perms->uid = getuid();
    } else {
823
        if (virXPathLong(conn, "number(/volume/permissions/owner)", ctxt, &v) < 0) {
824
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
825
                                  "%s", _("missing owner element"));
826 827 828 829
            return -1;
        }
        perms->uid = (int)v;
    }
830
    if (virXPathNode(conn, "/volume/permissions/group", ctxt) == NULL) {
831 832
        perms->gid = getgid();
    } else {
833
        if (virXPathLong(conn, "number(/volume/permissions/group)", ctxt, &v) < 0) {
834
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
835
                                  "%s", _("missing owner element"));
836 837 838 839 840 841
            return -1;
        }
        perms->gid = (int)v;
    }

    /* NB, we're ignoring missing labels here - they'll simply inherit */
842
    perms->label = virXPathString(conn, "string(/volume/permissions/label)", ctxt);
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 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

    return 0;
}


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 已提交
906
                              "%s", _("malformed capacity element"));
907 908 909 910
        return -1;
    }
    if (*ret > (ULLONG_MAX / mult)) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
911
                              "%s", _("capacity element value too large"));
912 913 914 915 916 917 918 919 920 921 922 923 924 925
            return -1;
    }

    *ret *= mult;

    return 0;
}

static virStorageVolDefPtr
virStorageVolDefParseDoc(virConnectPtr conn,
                         virStoragePoolDefPtr pool,
                         xmlXPathContextPtr ctxt,
                         xmlNodePtr root) {
    virStorageVolDefPtr ret;
926
    virStorageVolOptionsPtr options;
927 928 929 930
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;

931
    options = virStorageVolOptionsForPoolType(pool->type);
932 933 934
    if (options == NULL)
        return NULL;

935
    if (VIR_ALLOC(ret) < 0) {
936
        virReportOOMError(conn);
937
        return NULL;
938
    }
939 940 941

    if (STRNEQ((const char *)root->name, "volume")) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
942
                              "%s", _("unknown root element"));
943 944 945
        goto cleanup;
    }

946
    ret->name = virXPathString(conn, "string(/volume/name)", ctxt);
947 948
    if (ret->name == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
949
                              "%s", _("missing volume name element"));
950 951 952
        goto cleanup;
    }

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

956 957
    capacity = virXPathString(conn, "string(/volume/capacity)", ctxt);
    unit = virXPathString(conn, "string(/volume/capacity/@unit)", ctxt);
958 959
    if (capacity == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
960
                              "%s", _("missing capacity element"));
961 962 963 964
        goto cleanup;
    }
    if (virStorageSize(conn, unit, capacity, &ret->capacity) < 0)
        goto cleanup;
965 966
    VIR_FREE(capacity);
    VIR_FREE(unit);
967

968
    allocation = virXPathString(conn, "string(/volume/allocation)", ctxt);
969
    if (allocation) {
970
        unit = virXPathString(conn, "string(/volume/allocation/@unit)", ctxt);
971 972
        if (virStorageSize(conn, unit, allocation, &ret->allocation) < 0)
            goto cleanup;
973 974
        VIR_FREE(allocation);
        VIR_FREE(unit);
975 976 977 978
    } else {
        ret->allocation = ret->capacity;
    }

979
    ret->target.path = virXPathString(conn, "string(/volume/target/path)", ctxt);
980
    if (options->formatFromString) {
981
        char *format = virXPathString(conn, "string(/volume/target/format/@type)", ctxt);
982 983 984 985 986 987
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
988 989
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown volume format type %s"), format);
990
            VIR_FREE(format);
991 992
            goto cleanup;
        }
993
        VIR_FREE(format);
994 995 996 997 998
    }

    if (virStorageVolDefParsePerms(conn, ctxt, &ret->target.perms) < 0)
        goto cleanup;

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020


    ret->backingStore.path = virXPathString(conn, "string(/volume/backingStore/path)", ctxt);
    if (options->formatFromString) {
        char *format = virXPathString(conn, "string(/volume/backingStore/format/@type)", ctxt);
        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);
    }

    if (virStorageVolDefParsePerms(conn, ctxt, &ret->backingStore.perms) < 0)
        goto cleanup;

1021 1022 1023
    return ret;

 cleanup:
1024 1025 1026
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    virStorageVolDefFree(ret);
    return NULL;
}


virStorageVolDefPtr
virStorageVolDefParse(virConnectPtr conn,
                      virStoragePoolDefPtr pool,
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
1038
    xmlParserCtxtPtr pctxt;
1039 1040 1041 1042
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr ctxt = NULL;

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
    /* 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);
    xml = xmlCtxtReadDoc (pctxt, BAD_CAST xmlStr,
                          filename ? filename : "storage.xml", NULL,
                          XML_PARSE_NOENT | XML_PARSE_NONET |
                          XML_PARSE_NOWARNING);
    if (!xml) {
        if (conn && conn->err.code == VIR_ERR_NONE)
              virStorageReportError(conn, VIR_ERR_XML_ERROR,
D
Daniel P. Berrange 已提交
1058
                                    "%s", _("failed to parse xml document"));
1059 1060 1061 1062 1063
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
1064
        virReportOOMError(conn);
1065 1066 1067 1068 1069 1070
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1071
                              "%s", _("missing root element"));
1072 1073 1074 1075 1076
        goto cleanup;
    }

    ret = virStorageVolDefParseDoc(conn, pool, ctxt, node);

1077
    xmlFreeParserCtxt (pctxt);
1078 1079 1080 1081 1082 1083
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);

    return ret;

 cleanup:
1084
    xmlFreeParserCtxt (pctxt);
1085 1086 1087 1088 1089 1090
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    return NULL;
}


1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
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;
}
1132 1133 1134 1135 1136

char *
virStorageVolDefFormat(virConnectPtr conn,
                       virStoragePoolDefPtr pool,
                       virStorageVolDefPtr def) {
1137
    virStorageVolOptionsPtr options;
1138
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1139
    char *tmp;
1140

1141
    options = virStorageVolOptionsForPoolType(pool->type);
1142 1143 1144
    if (options == NULL)
        return NULL;

1145 1146 1147 1148
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferVSprintf(&buf,"  <key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "  <source>\n");
1149 1150 1151 1152 1153 1154 1155 1156

    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)
1157 1158 1159 1160
                    virBufferAddLit(&buf, "    </device>\n");

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

1163 1164 1165 1166
            virBufferVSprintf(&buf,
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
1167 1168 1169
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
1170
            virBufferAddLit(&buf, "    </device>\n");
1171
    }
1172
    virBufferAddLit(&buf, "  </source>\n");
1173

1174 1175 1176 1177
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
1178

1179 1180 1181
    if (virStorageVolTargetDefFormat(conn, options, &buf,
                                     &def->target, "target") < 0)
        goto cleanup;
1182

1183 1184 1185 1186
    if (def->backingStore.path &&
        virStorageVolTargetDefFormat(conn, options, &buf,
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1187 1188

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

1190
    if (virBufferError(&buf))
1191 1192
        goto no_memory;

1193
    return virBufferContentAndReset(&buf);
1194 1195

 no_memory:
1196
    virReportOOMError(conn);
1197
 cleanup:
1198 1199
    tmp = virBufferContentAndReset(&buf);
    VIR_FREE(tmp);
1200 1201 1202 1203 1204
    return NULL;
}


virStoragePoolObjPtr
1205
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1206
                            const unsigned char *uuid) {
1207
    unsigned int i;
1208

1209 1210
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1211 1212
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1213 1214
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1215 1216 1217 1218 1219

    return NULL;
}

virStoragePoolObjPtr
1220
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1221
                            const char *name) {
1222
    unsigned int i;
1223

1224 1225
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1226 1227
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1228 1229
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1230 1231 1232 1233 1234 1235 1236

    return NULL;
}

void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1237 1238 1239 1240 1241 1242
    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;
1243 1244 1245 1246 1247
}

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

1250 1251 1252
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1253 1254 1255 1256 1257 1258 1259

    return NULL;
}

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

1262 1263 1264
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->target.path, path))
            return pool->volumes.objs[i];
1265 1266 1267 1268 1269 1270 1271

    return NULL;
}

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

1274 1275 1276
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->name, name))
            return pool->volumes.objs[i];
1277 1278 1279 1280 1281 1282

    return NULL;
}

virStoragePoolObjPtr
virStoragePoolObjAssignDef(virConnectPtr conn,
1283
                           virStoragePoolObjListPtr pools,
1284 1285 1286
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1287
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
            if (pool->newDef)
                virStoragePoolDefFree(pool->newDef);
            pool->newDef = def;
        }
        return pool;
    }

1299
    if (VIR_ALLOC(pool) < 0) {
1300
        virReportOOMError(conn);
1301 1302 1303
        return NULL;
    }

1304 1305 1306 1307 1308 1309
    if (virMutexInit(&pool->lock) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(pool);
        return NULL;
    }
1310
    virStoragePoolObjLock(pool);
1311 1312 1313
    pool->active = 0;
    pool->def = def;

1314 1315
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1316
        virStoragePoolObjUnlock(pool);
1317
        virStoragePoolObjFree(pool);
1318
        virReportOOMError(conn);
1319 1320 1321
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1322 1323 1324 1325 1326

    return pool;
}

static virStoragePoolObjPtr
1327 1328
virStoragePoolObjLoad(virConnectPtr conn,
                      virStoragePoolObjListPtr pools,
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
                      const char *file,
                      const char *path,
                      const char *xml,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

    if (!(def = virStoragePoolDefParse(NULL, xml, file))) {
        virErrorPtr err = virGetLastError();
        virStorageLog("Error parsing storage pool config '%s' : %s",
1339
                      path, err ? err->message : NULL);
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
        virStorageLog("Storage pool config filename '%s' does not match pool name '%s'",
                      path, def->name);
        virStoragePoolDefFree(def);
        return NULL;
    }

1350
    if (!(pool = virStoragePoolObjAssignDef(conn, pools, def))) {
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
        virStorageLog("Failed to load storage pool config '%s': out of memory", path);
        virStoragePoolDefFree(def);
        return NULL;
    }

    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
        virStorageLog("Failed to load storage pool config '%s': out of memory", path);
        virStoragePoolDefFree(def);
        return NULL;
    }
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
        virStorageLog("Failed to load storage pool config '%s': out of memory", path);
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1377 1378 1379 1380
virStoragePoolLoadAllConfigs(virConnectPtr conn,
                             virStoragePoolObjListPtr pools,
                             const char *configDir,
                             const char *autostartDir) {
1381 1382 1383
    DIR *dir;
    struct dirent *entry;

1384
    if (!(dir = opendir(configDir))) {
1385 1386 1387
        if (errno == ENOENT)
            return 0;
        virStorageLog("Failed to open dir '%s': %s",
1388
                      configDir, strerror(errno));
1389 1390 1391 1392 1393 1394 1395
        return -1;
    }

    while ((entry = readdir(dir))) {
        char *xml = NULL;
        char path[PATH_MAX];
        char autostartLink[PATH_MAX];
1396
        virStoragePoolObjPtr pool;
1397 1398 1399 1400 1401 1402 1403

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

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

1404
        if (virFileBuildPath(configDir, entry->d_name,
1405 1406
                             NULL, path, PATH_MAX) < 0) {
            virStorageLog("Config filename '%s/%s' is too long",
1407
                          configDir, entry->d_name);
1408 1409 1410
            continue;
        }

1411
        if (virFileBuildPath(autostartDir, entry->d_name,
1412 1413
                             NULL, autostartLink, PATH_MAX) < 0) {
            virStorageLog("Autostart link path '%s/%s' is too long",
1414
                          autostartDir, entry->d_name);
1415 1416 1417 1418 1419 1420
            continue;
        }

        if (virFileReadAll(path, 8192, &xml) < 0)
            continue;

1421 1422 1423
        pool = virStoragePoolObjLoad(conn, pools, entry->d_name, path, xml, autostartLink);
        if (pool)
            virStoragePoolObjUnlock(pool);
1424

1425
        VIR_FREE(xml);
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
    }

    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))) {
1447 1448 1449
            virStorageReportError(conn, err,
                                  _("cannot create config directory %s"),
                                  driver->configDir);
1450 1451 1452 1453 1454 1455
            return -1;
        }

        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1456
                                  "%s", _("cannot construct config file path"));
1457 1458 1459
            return -1;
        }
        if (!(pool->configFile = strdup(path))) {
1460
            virReportOOMError(conn);
1461 1462 1463 1464 1465 1466
            return -1;
        }

        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1467 1468
                                  "%s", _("cannot construct "
                                          "autostart link path"));
1469
            VIR_FREE(pool->configFile);
1470 1471 1472
            return -1;
        }
        if (!(pool->autostartLink = strdup(path))) {
1473
            virReportOOMError(conn);
1474
            VIR_FREE(pool->configFile);
1475 1476 1477 1478 1479 1480
            return -1;
        }
    }

    if (!(xml = virStoragePoolDefFormat(conn, def))) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1481
                              "%s", _("failed to generate XML"));
1482 1483 1484 1485 1486 1487
        return -1;
    }

    if ((fd = open(pool->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1488 1489 1490
        virReportSystemError(conn, errno,
                             _("cannot create config file %s"),
                             pool->configFile);
1491 1492 1493 1494 1495
        goto cleanup;
    }

    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) != towrite) {
1496 1497 1498
        virReportSystemError(conn, errno,
                             _("cannot write config file %s"),
                             pool->configFile);
1499 1500 1501 1502
        goto cleanup;
    }

    if (close(fd) < 0) {
1503 1504 1505
        virReportSystemError(conn, errno,
                             _("cannot save config file %s"),
                             pool->configFile);
1506 1507 1508 1509 1510 1511 1512 1513 1514
        goto cleanup;
    }

    ret = 0;

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

1515
    VIR_FREE(xml);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537

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

1539
char *virStoragePoolSourceListFormat(virConnectPtr conn,
1540 1541
                                     virStoragePoolSourceListPtr def)
{
1542
    virStoragePoolOptionsPtr options;
1543
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1544 1545
    const char *type;
    int i;
1546

1547
    options = virStoragePoolOptionsForPoolType(def->type);
1548 1549 1550
    if (options == NULL)
        return NULL;

1551
    type = virStoragePoolTypeToString(def->type);
1552 1553 1554 1555 1556 1557 1558
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              "%s", _("unexpected pool type"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1559 1560

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

1564 1565 1566 1567
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1568 1569

    return virBufferContentAndReset(&buf);
1570 1571

 no_memory:
1572
    virReportOOMError(conn);
1573 1574 1575
 cleanup:
    free(virBufferContentAndReset(&buf));
    return NULL;
1576
}
D
Daniel P. Berrange 已提交
1577 1578


1579 1580
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
1581
    virMutexLock(&obj->lock);
1582 1583 1584 1585
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
1586
    virMutexUnlock(&obj->lock);
1587
}