storage_conf.c 52.0 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
#include "storage_file.h"
40

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

47 48
#define VIR_FROM_THIS VIR_FROM_STORAGE

49 50 51
#define virStorageError(conn, code, fmt...)                             \
            virReportErrorHelper(conn, VIR_FROM_STORAGE, code, __FILE__,\
                                  __FUNCTION__, __LINE__, fmt)
52

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

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

VIR_ENUM_IMPL(virStoragePoolFormatFileSystemNet,
              VIR_STORAGE_POOL_NETFS_LAST,
67
              "auto", "nfs", "glusterfs")
68 69 70 71

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

VIR_ENUM_IMPL(virStoragePoolFormatLogical,
              VIR_STORAGE_POOL_LOGICAL_LAST,
76
              "unknown", "lvm2")
77 78 79 80 81 82 83


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

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

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 {
102
    int defaultFormat;
103 104 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
    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 = {
148 149 150
            .defaultFormat = VIR_STORAGE_FILE_RAW,
            .formatFromString = virStorageFileFormatTypeFromString,
            .formatToString = virStorageFileFormatTypeToString,
151 152 153 154 155 156 157 158 159
        },
    },
    { .poolType = VIR_STORAGE_POOL_FS,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .formatFromString = virStoragePoolFormatFileSystemTypeFromString,
            .formatToString = virStoragePoolFormatFileSystemTypeToString,
        },
      .volOptions = {
160 161 162
            .defaultFormat = VIR_STORAGE_FILE_RAW,
            .formatFromString = virStorageFileFormatTypeFromString,
            .formatToString = virStorageFileFormatTypeToString,
163 164 165 166 167 168 169 170 171 172 173
        },
    },
    { .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 = {
174 175 176
            .defaultFormat = VIR_STORAGE_FILE_RAW,
            .formatFromString = virStorageFileFormatTypeFromString,
            .formatToString = virStorageFileFormatTypeToString,
177 178 179 180 181 182 183 184 185 186 187
        },
    },
    { .poolType = VIR_STORAGE_POOL_ISCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_HOST |
                      VIR_STORAGE_POOL_SOURCE_DEVICE),
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
188 189 190 191 192 193 194 195
    { .poolType = VIR_STORAGE_POOL_SCSI,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_ADAPTER),
        },
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
D
Dave Allan 已提交
196 197 198 199 200
    { .poolType = VIR_STORAGE_POOL_MPATH,
      .volOptions = {
            .formatToString = virStoragePoolFormatDiskTypeToString,
        }
    },
201 202 203 204 205 206 207 208
    { .poolType = VIR_STORAGE_POOL_DISK,
      .poolOptions = {
            .flags = (VIR_STORAGE_POOL_SOURCE_DEVICE),
            .defaultFormat = VIR_STORAGE_POOL_DISK_UNKNOWN,
            .formatFromString = virStoragePoolFormatDiskTypeFromString,
            .formatToString = virStoragePoolFormatDiskTypeToString,
        },
      .volOptions = {
209
            .defaultFormat = VIR_STORAGE_VOL_DISK_NONE,
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 235 236 237 238 239 240 241 242 243 244 245
            .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;
}


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

    if (!def)
        return;

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

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

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

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

274
    if (!source)
275 276
        return;

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

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

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

    VIR_FREE(def->name);

    virStoragePoolSourceFree(&def->source);
301

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


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

313 314
    virStoragePoolObjClearVols(obj);

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

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

    virMutexDestroy(&obj->lock);

323
    VIR_FREE(obj);
324 325
}

326 327 328 329 330 331 332 333 334
void virStoragePoolObjListFree(virStoragePoolObjListPtr pools)
{
    unsigned int i;
    for (i = 0 ; i < pools->count ; i++)
        virStoragePoolObjFree(pools->objs[i]);
    VIR_FREE(pools->objs);
    pools->count = 0;
}

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

341 342
    virStoragePoolObjUnlock(pool);

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

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

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

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


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

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

    return 0;
}

386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
static int
virStoragePoolDefParseSource(virConnectPtr conn,
                             xmlXPathContextPtr ctxt,
                             virStoragePoolSourcePtr source,
                             int pool_type,
                             xmlNodePtr node) {
    int ret = -1;
    xmlNodePtr relnode, *nodeset = NULL;
    char *authType = NULL;
    int nsource, i;
    virStoragePoolOptionsPtr options;

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

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

    source->name = virXPathString(conn, "string(./name)", ctxt);

    if (options->formatFromString) {
        char *format = virXPathString(conn, "string(./format/@type)", ctxt);
        if (format == NULL)
            source->format = options->defaultFormat;
        else
            source->format = options->formatFromString(format);

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

    source->host.name = virXPathString(conn, "string(./host/@name)", ctxt);

    nsource = virXPathNodeSet(conn, "./device", ctxt, &nodeset);
    if (nsource > 0) {
        if (VIR_ALLOC_N(source->devices, nsource) < 0) {
            VIR_FREE(nodeset);
            virReportOOMError(conn);
            goto cleanup;
        }

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

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

    authType = virXPathString(conn, "string(./auth/@type)", ctxt);
    if (authType == NULL) {
        source->authType = VIR_STORAGE_POOL_AUTH_NONE;
    } else {
        if (STREQ(authType, "chap")) {
            source->authType = VIR_STORAGE_POOL_AUTH_CHAP;
        } else {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown auth type '%s'"),
                                  (const char *)authType);
            goto cleanup;
        }
    }

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

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

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

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
virStoragePoolSourcePtr
virStoragePoolDefParseSourceString(virConnectPtr conn,
                                   const char *srcSpec,
                                   int pool_type)
{
    xmlDocPtr doc = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr xpath_ctxt = NULL;
    virStoragePoolSourcePtr def = NULL, ret = NULL;

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

    if (doc == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
                              "%s", _("bad <source> spec"));
        goto cleanup;
    }

    xpath_ctxt = xmlXPathNewContext(doc);
    if (xpath_ctxt == NULL) {
        virReportOOMError(conn);
        goto cleanup;
    }

    if (VIR_ALLOC(def) < 0) {
        virReportOOMError(conn);
        goto cleanup;
    }

    node = virXPathNode(conn, "/source", xpath_ctxt);
    if (!node) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
                              "%s", _("root element was not source"));
        goto cleanup;
    }

    if (virStoragePoolDefParseSource(conn, xpath_ctxt, def, pool_type,
                                     node) < 0)
        goto cleanup;

    ret = def;
    def = NULL;
cleanup:
    if (def)
        virStoragePoolSourceFree(def);
    xmlFreeDoc(doc);
    xmlXPathFreeContext(xpath_ctxt);

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

541 542 543 544 545 546 547 548 549 550 551 552 553 554
    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);
555
    if (!mode) {
556
        perms->mode = defaultmode;
557
    } else {
558
        char *end = NULL;
559 560
        perms->mode = strtol(mode, &end, 8);
        if (*end || perms->mode < 0 || perms->mode > 0777) {
561
            VIR_FREE(mode);
562
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
563
                                  "%s", _("malformed octal mode"));
564
            goto error;
565
        }
566
        VIR_FREE(mode);
567 568
    }

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

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

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

594 595 596 597
    ret = 0;
error:
    ctxt->node = relnode;
    return ret;
598 599 600
}

static virStoragePoolDefPtr
601 602
virStoragePoolDefParseXML(virConnectPtr conn,
                          xmlXPathContextPtr ctxt) {
603
    virStoragePoolOptionsPtr options;
604
    virStoragePoolDefPtr ret;
605
    xmlNodePtr source_node;
606
    char *type = NULL;
607 608
    char *uuid = NULL;

609
    if (VIR_ALLOC(ret) < 0) {
610
        virReportOOMError(conn);
611
        return NULL;
612
    }
613

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

621 622 623
    xmlFree(type);
    type = NULL;

624
    if ((options = virStoragePoolOptionsForPoolType(ret->type)) == NULL) {
625 626 627
        goto cleanup;
    }

628 629 630 631 632 633 634
    source_node = virXPathNode(conn, "./source", ctxt);
    if (source_node) {
        if (virStoragePoolDefParseSource(conn, ctxt, &ret->source, ret->type,
                                         source_node) < 0)
            goto cleanup;
    }

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

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

661
    if (options->flags & VIR_STORAGE_POOL_SOURCE_HOST) {
662
        if (!ret->source.host.name) {
663
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
664 665
                                  "%s",
                                  _("missing storage pool source host name"));
666 667 668 669
            goto cleanup;
        }
    }

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

688
    if (options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) {
689
        if (!ret->source.adapter) {
690
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
691
                                  "%s", _("missing storage pool source adapter name"));
692 693 694
            goto cleanup;
        }
    }
695

696
    if ((ret->target.path = virXPathString(conn, "string(./target/path)", ctxt)) == NULL) {
697
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
698
                              "%s", _("missing storage pool target path"));
699 700 701
        goto cleanup;
    }

702
    if (virStorageDefParsePerms(conn, ctxt, &ret->target.perms,
703
                                "./target/permissions", 0700) < 0)
704 705 706 707 708
        goto cleanup;

    return ret;

 cleanup:
709
    VIR_FREE(uuid);
710
    xmlFree(type);
711 712 713 714
    virStoragePoolDefFree(ret);
    return NULL;
}

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
/* 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);
        }
    }
}

736
virStoragePoolDefPtr
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
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
763 764 765 766
virStoragePoolDefParse(virConnectPtr conn,
                       const char *xmlStr,
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
767
    xmlParserCtxtPtr pctxt;
768 769 770
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;

771 772 773 774 775 776 777 778
    /* 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);
779 780 781 782 783 784 785 786 787 788 789
    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);
    }

790 791 792
    if (!xml) {
        if (conn && conn->err.code == VIR_ERR_NONE)
              virStorageReportError(conn, VIR_ERR_XML_ERROR,
D
Daniel P. Berrange 已提交
793
                                    "%s",_("failed to parse xml document"));
794 795 796 797 798 799
        goto cleanup;
    }

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

804
    ret = virStoragePoolDefParseNode(conn, xml, node);
805

806
    xmlFreeParserCtxt (pctxt);
807 808 809 810 811
    xmlFreeDoc(xml);

    return ret;

 cleanup:
812
    xmlFreeParserCtxt (pctxt);
813 814 815 816
    xmlFreeDoc(xml);
    return NULL;
}

817 818 819 820 821 822 823 824 825 826 827 828 829 830
virStoragePoolDefPtr
virStoragePoolDefParseString(virConnectPtr conn,
                             const char *xmlStr)
{
    return virStoragePoolDefParse(conn, xmlStr, NULL);
}

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

831 832 833
static int
virStoragePoolSourceFormat(virConnectPtr conn,
                           virBufferPtr buf,
834
                           virStoragePoolOptionsPtr options,
835 836 837 838 839
                           virStoragePoolSourcePtr src)
{
    int i, j;

    virBufferAddLit(buf,"  <source>\n");
840
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_HOST) &&
841 842 843
        src->host.name)
        virBufferVSprintf(buf,"    <host name='%s'/>\n", src->host.name);

844
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DEVICE) &&
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
        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);
        }
    }
862
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_DIR) &&
863 864
        src->dir)
        virBufferVSprintf(buf,"    <dir path='%s'/>\n", src->dir);
865
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_ADAPTER) &&
866 867
        src->adapter)
        virBufferVSprintf(buf,"    <adapter name='%s'/>\n", src->adapter);
868
    if ((options->flags & VIR_STORAGE_POOL_SOURCE_NAME) &&
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
        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)
885
        virBufferVSprintf(buf,"    <auth type='chap' login='%s' passwd='%s'/>\n",
886 887 888 889 890 891 892
                          src->auth.chap.login,
                          src->auth.chap.passwd);
    virBufferAddLit(buf,"  </source>\n");

    return 0;
}

893 894 895 896

char *
virStoragePoolDefFormat(virConnectPtr conn,
                        virStoragePoolDefPtr def) {
897
    virStoragePoolOptionsPtr options;
898
    virBuffer buf = VIR_BUFFER_INITIALIZER;
899 900 901
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];

902
    options = virStoragePoolOptionsForPoolType(def->type);
903 904 905
    if (options == NULL)
        return NULL;

906
    type = virStoragePoolTypeToString(def->type);
907 908
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
909
                              "%s", _("unexpected pool type"));
910 911
        goto cleanup;
    }
912 913
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
914 915

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

918 919 920 921 922 923
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
    virBufferVSprintf(&buf,"  <available>%llu</available>\n",
                      def->available);
924

925 926
    if (virStoragePoolSourceFormat(conn, &buf, options, &def->source) < 0)
        goto cleanup;
927

928
    virBufferAddLit(&buf,"  <target>\n");
929

930 931
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
932

933 934 935 936 937 938 939
    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);
940

941 942 943
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);
944

945 946 947
    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf,"  </target>\n");
    virBufferAddLit(&buf,"</pool>\n");
948

949
    if (virBufferError(&buf))
950 951
        goto no_memory;

952
    return virBufferContentAndReset(&buf);
953 954

 no_memory:
955
    virReportOOMError(conn);
956
 cleanup:
957
    free(virBufferContentAndReset(&buf));
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    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;

        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 已提交
1014
                              "%s", _("malformed capacity element"));
1015 1016 1017 1018
        return -1;
    }
    if (*ret > (ULLONG_MAX / mult)) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1019
                              "%s", _("capacity element value too large"));
1020 1021 1022 1023 1024 1025 1026 1027 1028
            return -1;
    }

    *ret *= mult;

    return 0;
}

static virStorageVolDefPtr
1029
virStorageVolDefParseXML(virConnectPtr conn,
1030
                         virStoragePoolDefPtr pool,
1031
                         xmlXPathContextPtr ctxt) {
1032
    virStorageVolDefPtr ret;
1033
    virStorageVolOptionsPtr options;
1034 1035 1036
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;
1037
    xmlNodePtr node;
1038

1039
    options = virStorageVolOptionsForPoolType(pool->type);
1040 1041 1042
    if (options == NULL)
        return NULL;

1043
    if (VIR_ALLOC(ret) < 0) {
1044
        virReportOOMError(conn);
1045
        return NULL;
1046
    }
1047

1048
    ret->name = virXPathString(conn, "string(./name)", ctxt);
1049 1050
    if (ret->name == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
1051
                              "%s", _("missing volume name element"));
1052 1053 1054
        goto cleanup;
    }

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

1058 1059
    capacity = virXPathString(conn, "string(./capacity)", ctxt);
    unit = virXPathString(conn, "string(./capacity/@unit)", ctxt);
1060 1061
    if (capacity == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1062
                              "%s", _("missing capacity element"));
1063 1064 1065 1066
        goto cleanup;
    }
    if (virStorageSize(conn, unit, capacity, &ret->capacity) < 0)
        goto cleanup;
1067 1068
    VIR_FREE(capacity);
    VIR_FREE(unit);
1069

1070
    allocation = virXPathString(conn, "string(./allocation)", ctxt);
1071
    if (allocation) {
1072
        unit = virXPathString(conn, "string(./allocation/@unit)", ctxt);
1073 1074
        if (virStorageSize(conn, unit, allocation, &ret->allocation) < 0)
            goto cleanup;
1075 1076
        VIR_FREE(allocation);
        VIR_FREE(unit);
1077 1078 1079 1080
    } else {
        ret->allocation = ret->capacity;
    }

1081
    ret->target.path = virXPathString(conn, "string(./target/path)", ctxt);
1082
    if (options->formatFromString) {
1083
        char *format = virXPathString(conn, "string(./target/format/@type)", ctxt);
1084 1085 1086 1087 1088 1089
        if (format == NULL)
            ret->target.format = options->defaultFormat;
        else
            ret->target.format = (options->formatFromString)(format);

        if (ret->target.format < 0) {
1090 1091
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
                                  _("unknown volume format type %s"), format);
1092
            VIR_FREE(format);
1093 1094
            goto cleanup;
        }
1095
        VIR_FREE(format);
1096 1097
    }

1098
    if (virStorageDefParsePerms(conn, ctxt, &ret->target.perms,
1099
                                "./target/permissions", 0600) < 0)
1100 1101
        goto cleanup;

1102 1103 1104 1105 1106 1107 1108 1109
    node = virXPathNode(conn, "./target/encryption", ctxt);
    if (node != NULL) {
        ret->target.encryption = virStorageEncryptionParseNode(conn, ctxt->doc,
                                                               node);
        if (ret->target.encryption == NULL)
            goto cleanup;
    }

1110 1111


1112
    ret->backingStore.path = virXPathString(conn, "string(./backingStore/path)", ctxt);
1113
    if (options->formatFromString) {
1114
        char *format = virXPathString(conn, "string(./backingStore/format/@type)", ctxt);
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
        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);
    }

1129
    if (virStorageDefParsePerms(conn, ctxt, &ret->backingStore.perms,
1130
                                "./backingStore/permissions", 0600) < 0)
1131 1132
        goto cleanup;

1133 1134 1135
    return ret;

 cleanup:
1136 1137 1138
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
1139 1140 1141 1142 1143
    virStorageVolDefFree(ret);
    return NULL;
}

virStorageVolDefPtr
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
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
1171 1172 1173 1174 1175
virStorageVolDefParse(virConnectPtr conn,
                      virStoragePoolDefPtr pool,
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
1176
    xmlParserCtxtPtr pctxt;
1177 1178 1179
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;

1180 1181 1182 1183 1184 1185 1186 1187
    /* 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);
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199

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

1200 1201 1202
    if (!xml) {
        if (conn && conn->err.code == VIR_ERR_NONE)
              virStorageReportError(conn, VIR_ERR_XML_ERROR,
D
Daniel P. Berrange 已提交
1203
                                    "%s", _("failed to parse xml document"));
1204 1205 1206 1207 1208 1209
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
1210
                              "%s", _("missing root element"));
1211 1212 1213
        goto cleanup;
    }

1214
    ret = virStorageVolDefParseNode(conn, pool, xml, node);
1215

1216
    xmlFreeParserCtxt (pctxt);
1217 1218 1219 1220 1221
    xmlFreeDoc(xml);

    return ret;

 cleanup:
1222
    xmlFreeParserCtxt (pctxt);
1223 1224 1225 1226
    xmlFreeDoc(xml);
    return NULL;
}

1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
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);
}
1242

1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
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");

1280 1281 1282 1283
    if (def->encryption != NULL &&
        virStorageEncryptionFormat(conn, buf, def->encryption) < 0)
        return -1;

1284 1285 1286 1287
    virBufferVSprintf(buf, "  </%s>\n", type);

    return 0;
}
1288 1289 1290 1291 1292

char *
virStorageVolDefFormat(virConnectPtr conn,
                       virStoragePoolDefPtr pool,
                       virStorageVolDefPtr def) {
1293
    virStorageVolOptionsPtr options;
1294
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1295
    char *tmp;
1296

1297
    options = virStorageVolOptionsForPoolType(pool->type);
1298 1299 1300
    if (options == NULL)
        return NULL;

1301 1302 1303 1304
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferVSprintf(&buf,"  <key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "  <source>\n");
1305 1306 1307 1308 1309 1310 1311 1312

    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)
1313 1314 1315 1316
                    virBufferAddLit(&buf, "    </device>\n");

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

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

1330 1331 1332 1333
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
1334

1335 1336 1337
    if (virStorageVolTargetDefFormat(conn, options, &buf,
                                     &def->target, "target") < 0)
        goto cleanup;
1338

1339 1340 1341 1342
    if (def->backingStore.path &&
        virStorageVolTargetDefFormat(conn, options, &buf,
                                     &def->backingStore, "backingStore") < 0)
        goto cleanup;
1343 1344

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

1346
    if (virBufferError(&buf))
1347 1348
        goto no_memory;

1349
    return virBufferContentAndReset(&buf);
1350 1351

 no_memory:
1352
    virReportOOMError(conn);
1353
 cleanup:
1354 1355
    tmp = virBufferContentAndReset(&buf);
    VIR_FREE(tmp);
1356 1357 1358 1359 1360
    return NULL;
}


virStoragePoolObjPtr
1361
virStoragePoolObjFindByUUID(virStoragePoolObjListPtr pools,
1362
                            const unsigned char *uuid) {
1363
    unsigned int i;
1364

1365 1366
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1367 1368
        if (!memcmp(pools->objs[i]->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pools->objs[i];
1369 1370
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1371 1372 1373 1374 1375

    return NULL;
}

virStoragePoolObjPtr
1376
virStoragePoolObjFindByName(virStoragePoolObjListPtr pools,
1377
                            const char *name) {
1378
    unsigned int i;
1379

1380 1381
    for (i = 0 ; i < pools->count ; i++) {
        virStoragePoolObjLock(pools->objs[i]);
1382 1383
        if (STREQ(pools->objs[i]->def->name, name))
            return pools->objs[i];
1384 1385
        virStoragePoolObjUnlock(pools->objs[i]);
    }
1386 1387 1388 1389 1390 1391 1392

    return NULL;
}

void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
1393 1394 1395 1396 1397 1398
    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;
1399 1400 1401 1402 1403
}

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

1406 1407 1408
    for (i = 0 ; i < pool->volumes.count ; i++)
        if (STREQ(pool->volumes.objs[i]->key, key))
            return pool->volumes.objs[i];
1409 1410 1411 1412 1413 1414 1415

    return NULL;
}

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

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

    return NULL;
}

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

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

    return NULL;
}

virStoragePoolObjPtr
virStoragePoolObjAssignDef(virConnectPtr conn,
1439
                           virStoragePoolObjListPtr pools,
1440 1441 1442
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

1443
    if ((pool = virStoragePoolObjFindByName(pools, def->name))) {
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
            if (pool->newDef)
                virStoragePoolDefFree(pool->newDef);
            pool->newDef = def;
        }
        return pool;
    }

1455
    if (VIR_ALLOC(pool) < 0) {
1456
        virReportOOMError(conn);
1457 1458 1459
        return NULL;
    }

1460 1461 1462 1463 1464 1465
    if (virMutexInit(&pool->lock) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              "%s", _("cannot initialize mutex"));
        VIR_FREE(pool);
        return NULL;
    }
1466
    virStoragePoolObjLock(pool);
1467 1468 1469
    pool->active = 0;
    pool->def = def;

1470 1471
    if (VIR_REALLOC_N(pools->objs, pools->count+1) < 0) {
        pool->def = NULL;
1472
        virStoragePoolObjUnlock(pool);
1473
        virStoragePoolObjFree(pool);
1474
        virReportOOMError(conn);
1475 1476 1477
        return NULL;
    }
    pools->objs[pools->count++] = pool;
1478 1479 1480 1481 1482

    return pool;
}

static virStoragePoolObjPtr
1483 1484
virStoragePoolObjLoad(virConnectPtr conn,
                      virStoragePoolObjListPtr pools,
1485 1486 1487 1488 1489 1490
                      const char *file,
                      const char *path,
                      const char *autostartLink) {
    virStoragePoolDefPtr def;
    virStoragePoolObjPtr pool;

1491
    if (!(def = virStoragePoolDefParseFile(conn, path))) {
1492 1493 1494 1495
        return NULL;
    }

    if (!virFileMatchesNameSuffix(file, def->name, ".xml")) {
1496 1497
        virStorageError(conn, VIR_ERR_INVALID_STORAGE_POOL,
            "Storage pool config filename '%s' does not match pool name '%s'",
1498 1499 1500 1501 1502
                      path, def->name);
        virStoragePoolDefFree(def);
        return NULL;
    }

1503
    if (!(pool = virStoragePoolObjAssignDef(conn, pools, def))) {
1504 1505 1506 1507 1508 1509
        virStoragePoolDefFree(def);
        return NULL;
    }

    pool->configFile = strdup(path);
    if (pool->configFile == NULL) {
1510
        virReportOOMError(conn);
1511 1512 1513 1514 1515
        virStoragePoolDefFree(def);
        return NULL;
    }
    pool->autostartLink = strdup(autostartLink);
    if (pool->autostartLink == NULL) {
1516
        virReportOOMError(conn);
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
        virStoragePoolDefFree(def);
        return NULL;
    }

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

    return pool;
}


int
1529 1530 1531 1532
virStoragePoolLoadAllConfigs(virConnectPtr conn,
                             virStoragePoolObjListPtr pools,
                             const char *configDir,
                             const char *autostartDir) {
1533 1534 1535
    DIR *dir;
    struct dirent *entry;

1536
    if (!(dir = opendir(configDir))) {
1537 1538
        if (errno == ENOENT)
            return 0;
1539 1540
        virReportSystemError(conn, errno, _("Failed to open dir '%s'"),
                             configDir);
1541 1542 1543 1544 1545 1546
        return -1;
    }

    while ((entry = readdir(dir))) {
        char path[PATH_MAX];
        char autostartLink[PATH_MAX];
1547
        virStoragePoolObjPtr pool;
1548 1549 1550 1551 1552 1553 1554

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

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

1555
        if (virFileBuildPath(configDir, entry->d_name,
1556
                             NULL, path, PATH_MAX) < 0) {
1557 1558 1559
            virStorageError(conn, VIR_ERR_INTERNAL_ERROR,
                            "Config filename '%s/%s' is too long",
                            configDir, entry->d_name);
1560 1561 1562
            continue;
        }

1563
        if (virFileBuildPath(autostartDir, entry->d_name,
1564
                             NULL, autostartLink, PATH_MAX) < 0) {
1565 1566 1567
            virStorageError(conn, VIR_ERR_INTERNAL_ERROR,
                            "Autostart link path '%s/%s' is too long",
                            autostartDir, entry->d_name);
1568 1569 1570
            continue;
        }

1571 1572
        pool = virStoragePoolObjLoad(conn, pools, entry->d_name, path,
                                     autostartLink);
1573 1574
        if (pool)
            virStoragePoolObjUnlock(pool);
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595
    }

    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))) {
C
Cole Robinson 已提交
1596 1597 1598
            virReportSystemError(conn, err,
                                 _("cannot create config directory %s"),
                                 driver->configDir);
1599 1600 1601 1602 1603 1604
            return -1;
        }

        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1605
                                  "%s", _("cannot construct config file path"));
1606 1607 1608
            return -1;
        }
        if (!(pool->configFile = strdup(path))) {
1609
            virReportOOMError(conn);
1610 1611 1612 1613 1614 1615
            return -1;
        }

        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1616 1617
                                  "%s", _("cannot construct "
                                          "autostart link path"));
1618
            VIR_FREE(pool->configFile);
1619 1620 1621
            return -1;
        }
        if (!(pool->autostartLink = strdup(path))) {
1622
            virReportOOMError(conn);
1623
            VIR_FREE(pool->configFile);
1624 1625 1626 1627 1628 1629
            return -1;
        }
    }

    if (!(xml = virStoragePoolDefFormat(conn, def))) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1630
                              "%s", _("failed to generate XML"));
1631 1632 1633 1634 1635 1636
        return -1;
    }

    if ((fd = open(pool->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
1637 1638 1639
        virReportSystemError(conn, errno,
                             _("cannot create config file %s"),
                             pool->configFile);
1640 1641 1642 1643 1644
        goto cleanup;
    }

    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) != towrite) {
1645 1646 1647
        virReportSystemError(conn, errno,
                             _("cannot write config file %s"),
                             pool->configFile);
1648 1649 1650 1651
        goto cleanup;
    }

    if (close(fd) < 0) {
1652 1653 1654
        virReportSystemError(conn, errno,
                             _("cannot save config file %s"),
                             pool->configFile);
1655 1656 1657 1658 1659 1660 1661 1662 1663
        goto cleanup;
    }

    ret = 0;

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

1664
    VIR_FREE(xml);
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686

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

1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
virStoragePoolSourcePtr
virStoragePoolSourceListNewSource(virConnectPtr conn,
                                  virStoragePoolSourceListPtr list)
{
    virStoragePoolSourcePtr source;

    if (VIR_ALLOC(source) < 0) {
        virReportOOMError(conn);
        return NULL;
    }

    if (VIR_REALLOC_N(list->sources, list->nsources+1) < 0) {
        virReportOOMError(conn);
        return NULL;
    }

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

    return source;
}

1710
char *virStoragePoolSourceListFormat(virConnectPtr conn,
1711 1712
                                     virStoragePoolSourceListPtr def)
{
1713
    virStoragePoolOptionsPtr options;
1714
    virBuffer buf = VIR_BUFFER_INITIALIZER;
1715 1716
    const char *type;
    int i;
1717

1718
    options = virStoragePoolOptionsForPoolType(def->type);
1719 1720 1721
    if (options == NULL)
        return NULL;

1722
    type = virStoragePoolTypeToString(def->type);
1723 1724 1725 1726 1727 1728 1729
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              "%s", _("unexpected pool type"));
        goto cleanup;
    }

    virBufferAddLit(&buf, "<sources>\n");
1730 1731

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

1735 1736 1737 1738
    virBufferAddLit(&buf, "</sources>\n");

    if (virBufferError(&buf))
        goto no_memory;
1739 1740

    return virBufferContentAndReset(&buf);
1741 1742

 no_memory:
1743
    virReportOOMError(conn);
1744 1745 1746
 cleanup:
    free(virBufferContentAndReset(&buf));
    return NULL;
1747
}
D
Daniel P. Berrange 已提交
1748 1749


1750 1751
void virStoragePoolObjLock(virStoragePoolObjPtr obj)
{
1752
    virMutexLock(&obj->lock);
1753 1754 1755 1756
}

void virStoragePoolObjUnlock(virStoragePoolObjPtr obj)
{
1757
    virMutexUnlock(&obj->lock);
1758
}