You need to sign in or sign up before continuing.
storage_conf.c 37.3 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 36 37 38 39 40
/*
 * 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 <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xpath.h>
#include <libxml/uri.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>

41
#include "internal.h"
42 43 44 45 46 47
#include "storage_conf.h"
#include "storage_backend.h"
#include "xml.h"
#include "uuid.h"
#include "buf.h"
#include "util.h"
48
#include "memory.h"
49 50 51 52 53 54

#define virStorageLog(msg...) fprintf(stderr, msg)

void
virStorageVolDefFree(virStorageVolDefPtr def) {
    int i;
55 56
    VIR_FREE(def->name);
    VIR_FREE(def->key);
57 58

    for (i = 0 ; i < def->source.nextent ; i++) {
59
        VIR_FREE(def->source.extents[i].path);
60
    }
61
    VIR_FREE(def->source.extents);
62

63 64 65
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
66 67 68 69 70 71
}

void
virStoragePoolDefFree(virStoragePoolDefPtr def) {
    int i;

72 73
    VIR_FREE(def->name);
    VIR_FREE(def->source.host.name);
74
    for (i = 0 ; i < def->source.ndevice ; i++) {
75 76
        VIR_FREE(def->source.devices[i].freeExtents);
        VIR_FREE(def->source.devices[i].path);
77
    }
78 79
    VIR_FREE(def->source.devices);
    VIR_FREE(def->source.dir);
80
    VIR_FREE(def->source.name);
81 82

    if (def->source.authType == VIR_STORAGE_POOL_AUTH_CHAP) {
83 84
        VIR_FREE(def->source.auth.chap.login);
        VIR_FREE(def->source.auth.chap.passwd);
85 86
    }

87 88 89
    VIR_FREE(def->target.path);
    VIR_FREE(def->target.perms.label);
    VIR_FREE(def);
90 91 92 93 94 95 96 97 98 99
}


void
virStoragePoolObjFree(virStoragePoolObjPtr obj) {
    if (obj->def)
        virStoragePoolDefFree(obj->def);
    if (obj->newDef)
        virStoragePoolDefFree(obj->newDef);

100 101 102
    VIR_FREE(obj->configFile);
    VIR_FREE(obj->autostartLink);
    VIR_FREE(obj);
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
}

void
virStoragePoolObjRemove(virStorageDriverStatePtr driver,
                        virStoragePoolObjPtr pool)
{
    virStoragePoolObjPtr prev = NULL, curr;

    curr = driver->pools;
    while (curr != pool) {
        prev = curr;
        curr = curr->next;
    }

    if (curr) {
        if (prev)
            prev->next = curr->next;
        else
            driver->pools = curr->next;

        driver->ninactivePools--;
    }

    virStoragePoolObjFree(pool);
}


static int
virStoragePoolDefParseAuthChap(virConnectPtr conn,
                               xmlXPathContextPtr ctxt,
                               virStoragePoolAuthChapPtr auth) {
134
    auth->login = virXPathString(conn, "string(/pool/source/auth/@login)", ctxt);
135 136
    if (auth->login == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
137
                              "%s", _("missing auth host attribute"));
138 139 140
        return -1;
    }

141
    auth->passwd = virXPathString(conn, "string(/pool/source/auth/@passwd)", ctxt);
142 143
    if (auth->passwd == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
144
                              "%s", _("missing auth passwd attribute"));
145 146 147 148 149 150 151 152 153 154 155 156 157 158
        return -1;
    }

    return 0;
}


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

159
    mode = virXPathString(conn, "string(/pool/permissions/mode)", ctxt);
160 161 162 163 164 165 166
    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 已提交
167
                                  "%s", _("malformed octal mode"));
168 169 170 171
            return -1;
        }
    }

172
    if (virXPathNode(conn, "/pool/permissions/owner", ctxt) == NULL) {
173 174
        perms->uid = getuid();
    } else {
175
        if (virXPathLong(conn, "number(/pool/permissions/owner)", ctxt, &v) < 0) {
176
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
177
                                  "%s", _("malformed owner element"));
178 179 180 181 182
            return -1;
        }
        perms->uid = (int)v;
    }

183
    if (virXPathNode(conn, "/pool/permissions/group", ctxt) == NULL) {
D
Daniel P. Berrange 已提交
184
        perms->gid = getgid();
185
    } else {
186
        if (virXPathLong(conn, "number(/pool/permissions/group)", ctxt, &v) < 0) {
187
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
188
                                  "%s", _("malformed group element"));
189 190 191 192 193 194
            return -1;
        }
        perms->gid = (int)v;
    }

    /* NB, we're ignoring missing labels here - they'll simply inherit */
195
    perms->label = virXPathString(conn, "string(/pool/permissions/label)", ctxt);
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210

    return 0;
}


static virStoragePoolDefPtr
virStoragePoolDefParseDoc(virConnectPtr conn,
                          xmlXPathContextPtr ctxt,
                          xmlNodePtr root) {
    virStorageBackendPoolOptionsPtr options;
    virStoragePoolDefPtr ret;
    xmlChar *type = NULL;
    char *uuid = NULL;
    char *authType = NULL;

211 212 213
    if (VIR_ALLOC(ret) < 0) {
        virStorageReportError(conn, VIR_ERR_NO_MEMORY,
                              "%s", _("cannot allocate storage pool"));
214
        return NULL;
215
    }
216 217 218

    if (STRNEQ((const char *)root->name, "pool")) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
219
                          "%s", _("unknown root elementi for storage pool"));
220 221 222 223 224 225 226 227 228 229 230 231 232
        goto cleanup;
    }

    type = xmlGetProp(root, BAD_CAST "type");
    if ((ret->type = virStorageBackendFromString((const char *)type)) < 0)
        goto cleanup;
    xmlFree(type);
    type = NULL;

    if ((options = virStorageBackendPoolOptionsForType(ret->type)) == NULL) {
        goto cleanup;
    }

233 234 235 236 237
    ret->name = virXPathString(conn, "string(/pool/name)", ctxt);
    if (ret->name == NULL &&
        options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_NAME)
        ret->name = virXPathString(conn, "string(/pool/source/name)", ctxt);
    if (ret->name == NULL) {
238
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
239
                              "%s", _("missing pool source name element"));
240 241 242
        goto cleanup;
    }

243
    uuid = virXPathString(conn, "string(/pool/uuid)", ctxt);
244 245 246
    if (uuid == NULL) {
        if (virUUIDGenerate(ret->uuid) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
247
                                  "%s", _("unable to generate uuid"));
248 249 250 251 252
            goto cleanup;
        }
    } else {
        if (virUUIDParse(uuid, ret->uuid) < 0) {
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
253
                                  "%s", _("malformed uuid element"));
254 255
            goto cleanup;
        }
256
        VIR_FREE(uuid);
257 258 259
    }

    if (options->formatFromString) {
260
        char *format = virXPathString(conn, "string(/pool/source/format/@type)", ctxt);
261
        if ((ret->source.format = (options->formatFromString)(conn, format)) < 0) {
262
            VIR_FREE(format);
263 264
            goto cleanup;
        }
265
        VIR_FREE(format);
266 267 268
    }

    if (options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_HOST) {
269
        if ((ret->source.host.name = virXPathString(conn, "string(/pool/source/host/@name)", ctxt)) == NULL) {
270
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
271
                             "%s", _("missing storage pool source host name"));
272 273 274 275 276 277 278
            goto cleanup;
        }
    }
    if (options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_DEVICE) {
        xmlNodePtr *nodeset = NULL;
        int nsource, i;

279
        if ((nsource = virXPathNodeSet(conn, "/pool/source/device", ctxt, &nodeset)) < 0) {
280
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
281
                        "%s", _("cannot extract storage pool source devices"));
282 283
            goto cleanup;
        }
284 285
        if (VIR_ALLOC_N(ret->source.devices, nsource) < 0) {
            VIR_FREE(nodeset);
J
Jim Meyering 已提交
286
            virStorageReportError(conn, VIR_ERR_NO_MEMORY, "%s", _("device"));
287 288 289 290 291
            goto cleanup;
        }
        for (i = 0 ; i < nsource ; i++) {
            xmlChar *path = xmlGetProp(nodeset[i], BAD_CAST "path");
            if (path == NULL) {
292
                VIR_FREE(nodeset);
293
                virStorageReportError(conn, VIR_ERR_XML_ERROR,
294
                        "%s", _("missing storage pool source device path"));
295 296 297 298
                goto cleanup;
            }
            ret->source.devices[i].path = (char *)path;
        }
299
        VIR_FREE(nodeset);
300 301 302
        ret->source.ndevice = nsource;
    }
    if (options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_DIR) {
303
        if ((ret->source.dir = virXPathString(conn, "string(/pool/source/dir/@path)", ctxt)) == NULL) {
304
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
305
                                "%s", _("missing storage pool source path"));
306 307 308
            goto cleanup;
        }
    }
309 310 311 312 313 314
    if (options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_NAME) {
        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);
315 316 317 318 319
            if (ret->source.name == NULL) {
                virStorageReportError(conn, VIR_ERR_NO_MEMORY, "%s",
                                      _("pool name"));
                goto cleanup;
            }
320 321
        }
    }
322 323


324
    authType = virXPathString(conn, "string(/pool/source/auth/@type)", ctxt);
325 326 327 328 329 330 331 332 333
    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);
334
            VIR_FREE(authType);
335 336
            goto cleanup;
        }
337
        VIR_FREE(authType);
338 339 340 341 342 343 344
    }

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

345
    if ((ret->target.path = virXPathString(conn, "string(/pool/target/path)", ctxt)) == NULL) {
346
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
347
                              "%s", _("missing storage pool target path"));
348 349 350 351 352 353 354 355 356
        goto cleanup;
    }

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

    return ret;

 cleanup:
357
    VIR_FREE(uuid);
358
    xmlFree(type);
359 360 361 362
    virStoragePoolDefFree(ret);
    return NULL;
}

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
/* 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);
        }
    }
}

384 385 386 387 388
virStoragePoolDefPtr
virStoragePoolDefParse(virConnectPtr conn,
                       const char *xmlStr,
                       const char *filename) {
    virStoragePoolDefPtr ret = NULL;
389
    xmlParserCtxtPtr pctxt;
390 391 392 393
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr ctxt = NULL;

394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
    /* 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 已提交
409
                                    "%s",_("failed to parse xml document"));
410 411 412 413 414 415
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virStorageReportError(conn, VIR_ERR_NO_MEMORY,
J
Jim Meyering 已提交
416
                              "%s", _("xmlXPathContext"));
417 418 419 420 421 422
        goto cleanup;
    }

    node = xmlDocGetRootElement(xml);
    if (node == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
423
                              "%s", _("missing root element"));
424 425 426 427 428
        goto cleanup;
    }

    ret = virStoragePoolDefParseDoc(conn, ctxt, node);

429
    xmlFreeParserCtxt (pctxt);
430 431 432 433 434 435
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);

    return ret;

 cleanup:
436
    xmlFreeParserCtxt (pctxt);
437 438 439 440 441 442 443 444 445 446
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    return NULL;
}


char *
virStoragePoolDefFormat(virConnectPtr conn,
                        virStoragePoolDefPtr def) {
    virStorageBackendPoolOptionsPtr options;
447
    virBuffer buf = VIR_BUFFER_INITIALIZER;
448 449 450 451 452 453 454 455 456 457 458
    const char *type;
    char uuid[VIR_UUID_STRING_BUFLEN];
    int i;

    options = virStorageBackendPoolOptionsForType(def->type);
    if (options == NULL)
        return NULL;

    type = virStorageBackendToString(def->type);
    if (!type) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
459
                              "%s", _("unexpected pool type"));
460 461
        goto cleanup;
    }
462 463
    virBufferVSprintf(&buf, "<pool type='%s'>\n", type);
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
464 465

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

468 469 470 471 472 473
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
    virBufferVSprintf(&buf,"  <available>%llu</available>\n",
                      def->available);
474

475
    virBufferAddLit(&buf,"  <source>\n");
476
    if ((options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_HOST) &&
477 478 479
        def->source.host.name)
        virBufferVSprintf(&buf,"    <host name='%s'/>\n", def->source.host.name);

480 481 482
    if ((options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_DEVICE) &&
        def->source.ndevice) {
        for (i = 0 ; i < def->source.ndevice ; i++) {
483
            virBufferVSprintf(&buf,"    <device path='%s'>\n", def->source.devices[i].path);
484 485 486
            if (def->source.devices[i].nfreeExtent) {
                int j;
                for (j = 0 ; j < def->source.devices[i].nfreeExtent ; j++) {
487 488 489
                    virBufferVSprintf(&buf, "    <freeExtent start='%llu' end='%llu'/>\n",
                                      def->source.devices[i].freeExtents[j].start,
                                      def->source.devices[i].freeExtents[j].end);
490 491
                }
            }
492
            virBufferAddLit(&buf,"    </device>\n");
493 494 495
        }
    }
    if ((options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_DIR) &&
496 497
        def->source.dir)
        virBufferVSprintf(&buf,"    <dir path='%s'/>\n", def->source.dir);
498
    if ((options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_ADAPTER) &&
499 500
        def->source.adapter)
        virBufferVSprintf(&buf,"    <adapter name='%s'/>\n", def->source.adapter);
501 502 503
    if ((options->flags & VIR_STORAGE_BACKEND_POOL_SOURCE_NAME) &&
        def->source.name)
        virBufferVSprintf(&buf,"    <name>%s</name>\n", def->source.name);
504 505 506 507 508

    if (options->formatToString) {
        const char *format = (options->formatToString)(conn, def->source.format);
        if (!format)
            goto cleanup;
509
        virBufferVSprintf(&buf,"    <format type='%s'/>\n", format);
510 511 512
    }


513 514
    if (def->source.authType == VIR_STORAGE_POOL_AUTH_CHAP)
        virBufferVSprintf(&buf,"    <auth type='chap' login='%s' passwd='%s'>\n",
515
                          def->source.auth.chap.login,
516 517
                          def->source.auth.chap.passwd);
    virBufferAddLit(&buf,"  </source>\n");
518

519
    virBufferAddLit(&buf,"  <target>\n");
520

521 522
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
523

524 525 526 527 528 529 530
    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);
531

532 533 534
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);
535

536 537 538
    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf,"  </target>\n");
    virBufferAddLit(&buf,"</pool>\n");
539

540
    if (virBufferError(&buf))
541 542
        goto no_memory;

543
    return virBufferContentAndReset(&buf);
544 545

 no_memory:
J
Jim Meyering 已提交
546
    virStorageReportError(conn, VIR_ERR_NO_MEMORY, "%s", _("xml"));
547
 cleanup:
548
    free(virBufferContentAndReset(&buf));
549 550 551 552 553 554 555 556 557 558 559
    return NULL;
}


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

560
    mode = virXPathString(conn, "string(/volume/permissions/mode)", ctxt);
561 562 563 564 565 566 567
    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 已提交
568
                                  "%s", _("malformed octal mode"));
569 570 571 572
            return -1;
        }
    }

573
    if (virXPathNode(conn, "/volume/permissions/owner", ctxt) == NULL) {
574 575
        perms->uid = getuid();
    } else {
576
        if (virXPathLong(conn, "number(/volume/permissions/owner)", ctxt, &v) < 0) {
577
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
578
                                  "%s", _("missing owner element"));
579 580 581 582
            return -1;
        }
        perms->uid = (int)v;
    }
583
    if (virXPathNode(conn, "/volume/permissions/group", ctxt) == NULL) {
584 585
        perms->gid = getgid();
    } else {
586
        if (virXPathLong(conn, "number(/volume/permissions/group)", ctxt, &v) < 0) {
587
            virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
588
                                  "%s", _("missing owner element"));
589 590 591 592 593 594
            return -1;
        }
        perms->gid = (int)v;
    }

    /* NB, we're ignoring missing labels here - they'll simply inherit */
595
    perms->label = virXPathString(conn, "string(/volume/permissions/label)", ctxt);
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

    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 已提交
659
                              "%s", _("malformed capacity element"));
660 661 662 663
        return -1;
    }
    if (*ret > (ULLONG_MAX / mult)) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
664
                              "%s", _("capacity element value too large"));
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
            return -1;
    }

    *ret *= mult;

    return 0;
}

static virStorageVolDefPtr
virStorageVolDefParseDoc(virConnectPtr conn,
                         virStoragePoolDefPtr pool,
                         xmlXPathContextPtr ctxt,
                         xmlNodePtr root) {
    virStorageVolDefPtr ret;
    virStorageBackendVolOptionsPtr options;
    char *allocation = NULL;
    char *capacity = NULL;
    char *unit = NULL;

    options = virStorageBackendVolOptionsForType(pool->type);
    if (options == NULL)
        return NULL;

688 689 690
    if (VIR_ALLOC(ret) < 0) {
        virStorageReportError(conn, VIR_ERR_NO_MEMORY,
                              "%s", _("cannot allocate storage vol"));
691
        return NULL;
692
    }
693 694 695

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

700
    ret->name = virXPathString(conn, "string(/volume/name)", ctxt);
701 702
    if (ret->name == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
703
                              "%s", _("missing volume name element"));
704 705 706
        goto cleanup;
    }

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

710 711
    capacity = virXPathString(conn, "string(/volume/capacity)", ctxt);
    unit = virXPathString(conn, "string(/volume/capacity/@unit)", ctxt);
712 713
    if (capacity == NULL) {
        virStorageReportError(conn, VIR_ERR_XML_ERROR,
J
Jim Meyering 已提交
714
                              "%s", _("missing capacity element"));
715 716 717 718
        goto cleanup;
    }
    if (virStorageSize(conn, unit, capacity, &ret->capacity) < 0)
        goto cleanup;
719 720
    VIR_FREE(capacity);
    VIR_FREE(unit);
721

722
    allocation = virXPathString(conn, "string(/volume/allocation)", ctxt);
723
    if (allocation) {
724
        unit = virXPathString(conn, "string(/volume/allocation/@unit)", ctxt);
725 726
        if (virStorageSize(conn, unit, allocation, &ret->allocation) < 0)
            goto cleanup;
727 728
        VIR_FREE(allocation);
        VIR_FREE(unit);
729 730 731 732
    } else {
        ret->allocation = ret->capacity;
    }

733
    ret->target.path = virXPathString(conn, "string(/volume/target/path)", ctxt);
734
    if (options->formatFromString) {
735
        char *format = virXPathString(conn, "string(/volume/target/format/@type)", ctxt);
736
        if ((ret->target.format = (options->formatFromString)(conn, format)) < 0) {
737
            VIR_FREE(format);
738 739
            goto cleanup;
        }
740
        VIR_FREE(format);
741 742 743 744 745 746 747 748
    }

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

    return ret;

 cleanup:
749 750 751
    VIR_FREE(allocation);
    VIR_FREE(capacity);
    VIR_FREE(unit);
752 753 754 755 756 757 758 759 760 761 762
    virStorageVolDefFree(ret);
    return NULL;
}


virStorageVolDefPtr
virStorageVolDefParse(virConnectPtr conn,
                      virStoragePoolDefPtr pool,
                      const char *xmlStr,
                      const char *filename) {
    virStorageVolDefPtr ret = NULL;
763
    xmlParserCtxtPtr pctxt;
764 765 766 767
    xmlDocPtr xml = NULL;
    xmlNodePtr node = NULL;
    xmlXPathContextPtr ctxt = NULL;

768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
    /* 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 已提交
783
                                    "%s", _("failed to parse xml document"));
784 785 786 787 788 789
        goto cleanup;
    }

    ctxt = xmlXPathNewContext(xml);
    if (ctxt == NULL) {
        virStorageReportError(conn, VIR_ERR_NO_MEMORY,
J
Jim Meyering 已提交
790
                              "%s", _("xmlXPathContext"));
791 792 793 794 795 796
        goto cleanup;
    }

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

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

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

    return ret;

 cleanup:
810
    xmlFreeParserCtxt (pctxt);
811 812 813 814 815 816 817 818 819 820 821 822
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(xml);
    return NULL;
}



char *
virStorageVolDefFormat(virConnectPtr conn,
                       virStoragePoolDefPtr pool,
                       virStorageVolDefPtr def) {
    virStorageBackendVolOptionsPtr options;
823
    virBuffer buf = VIR_BUFFER_INITIALIZER;
824
    char *tmp;
825 826 827 828 829

    options = virStorageBackendVolOptionsForType(pool->type);
    if (options == NULL)
        return NULL;

830 831 832 833
    virBufferAddLit(&buf, "<volume>\n");
    virBufferVSprintf(&buf,"  <name>%s</name>\n", def->name);
    virBufferVSprintf(&buf,"  <key>%s</key>\n", def->key);
    virBufferAddLit(&buf, "  <source>\n");
834 835 836 837 838 839 840 841

    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)
842 843 844 845
                    virBufferAddLit(&buf, "    </device>\n");

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

848 849 850 851
            virBufferVSprintf(&buf,
                              "      <extent start='%llu' end='%llu'/>\n",
                              def->source.extents[i].start,
                              def->source.extents[i].end);
852 853 854
            thispath = def->source.extents[i].path;
        }
        if (thispath != NULL)
855
            virBufferAddLit(&buf, "    </device>\n");
856
    }
857
    virBufferAddLit(&buf, "  </source>\n");
858

859 860 861 862
    virBufferVSprintf(&buf,"  <capacity>%llu</capacity>\n",
                      def->capacity);
    virBufferVSprintf(&buf,"  <allocation>%llu</allocation>\n",
                      def->allocation);
863

864
    virBufferAddLit(&buf, "  <target>\n");
865

866 867
    if (def->target.path)
        virBufferVSprintf(&buf,"    <path>%s</path>\n", def->target.path);
868 869 870 871 872 873

    if (options->formatToString) {
        const char *format = (options->formatToString)(conn,
                                                       def->target.format);
        if (!format)
            goto cleanup;
874
        virBufferVSprintf(&buf,"    <format type='%s'/>\n", format);
875 876
    }

877 878 879 880 881 882 883
    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);
884 885


886 887 888 889 890 891 892
    if (def->target.perms.label)
        virBufferVSprintf(&buf,"      <label>%s</label>\n",
                          def->target.perms.label);

    virBufferAddLit(&buf,"    </permissions>\n");
    virBufferAddLit(&buf, "  </target>\n");
    virBufferAddLit(&buf,"</volume>\n");
893

894
    if (virBufferError(&buf))
895 896
        goto no_memory;

897
    return virBufferContentAndReset(&buf);
898 899

 no_memory:
J
Jim Meyering 已提交
900
    virStorageReportError(conn, VIR_ERR_NO_MEMORY, "%s", _("xml"));
901
 cleanup:
902 903
    tmp = virBufferContentAndReset(&buf);
    VIR_FREE(tmp);
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 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
    return NULL;
}


virStoragePoolObjPtr
virStoragePoolObjFindByUUID(virStorageDriverStatePtr driver,
                            const unsigned char *uuid) {
    virStoragePoolObjPtr pool = driver->pools;

    while (pool) {
        if (!memcmp(pool->def->uuid, uuid, VIR_UUID_BUFLEN))
            return pool;
        pool = pool->next;
    }

    return NULL;
}

virStoragePoolObjPtr
virStoragePoolObjFindByName(virStorageDriverStatePtr driver,
                            const char *name) {
    virStoragePoolObjPtr pool = driver->pools;

    while (pool) {
        if (STREQ(pool->def->name, name))
            return pool;
        pool = pool->next;
    }

    return NULL;
}

void
virStoragePoolObjClearVols(virStoragePoolObjPtr pool)
{
    virStorageVolDefPtr vol = pool->volumes;
    while (vol) {
        virStorageVolDefPtr next = vol->next;
        virStorageVolDefFree(vol);
        vol = next;
    }
    pool->volumes = NULL;
    pool->nvolumes = 0;
}

virStorageVolDefPtr
virStorageVolDefFindByKey(virStoragePoolObjPtr pool,
                          const char *key) {
    virStorageVolDefPtr vol = pool->volumes;

    while (vol) {
        if (STREQ(vol->key, key))
            return vol;
        vol = vol->next;
    }

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByPath(virStoragePoolObjPtr pool,
                           const char *path) {
    virStorageVolDefPtr vol = pool->volumes;

    while (vol) {
        if (STREQ(vol->target.path, path))
            return vol;
        vol = vol->next;
    }

    return NULL;
}

virStorageVolDefPtr
virStorageVolDefFindByName(virStoragePoolObjPtr pool,
                           const char *name) {
    virStorageVolDefPtr vol = pool->volumes;

    while (vol) {
        if (STREQ(vol->name, name))
            return vol;
        vol = vol->next;
    }

    return NULL;
}

virStoragePoolObjPtr
virStoragePoolObjAssignDef(virConnectPtr conn,
                           virStorageDriverStatePtr driver,
                           virStoragePoolDefPtr def) {
    virStoragePoolObjPtr pool;

    if ((pool = virStoragePoolObjFindByName(driver, def->name))) {
        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolDefFree(pool->def);
            pool->def = def;
        } else {
            if (pool->newDef)
                virStoragePoolDefFree(pool->newDef);
            pool->newDef = def;
        }
        return pool;
    }

1009
    if (VIR_ALLOC(pool) < 0) {
1010
        virStorageReportError(conn, VIR_ERR_NO_MEMORY,
J
Jim Meyering 已提交
1011
                              "%s", _("pool"));
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 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
        return NULL;
    }

    pool->active = 0;
    pool->def = def;
    pool->next = driver->pools;

    driver->pools = pool;
    driver->ninactivePools++;

    return pool;
}

static virStoragePoolObjPtr
virStoragePoolObjLoad(virStorageDriverStatePtr driver,
                      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",
                      path, err->message);
        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;
    }

    if (!(pool = virStoragePoolObjAssignDef(NULL, driver, def))) {
        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
virStoragePoolObjScanConfigs(virStorageDriverStatePtr driver) {
    DIR *dir;
    struct dirent *entry;

    if (!(dir = opendir(driver->configDir))) {
        if (errno == ENOENT)
            return 0;
        virStorageLog("Failed to open dir '%s': %s",
                      driver->configDir, strerror(errno));
        return -1;
    }

    while ((entry = readdir(dir))) {
        char *xml = NULL;
        char path[PATH_MAX];
        char autostartLink[PATH_MAX];

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

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

        if (virFileBuildPath(driver->configDir, entry->d_name,
                             NULL, path, PATH_MAX) < 0) {
            virStorageLog("Config filename '%s/%s' is too long",
                          driver->configDir, entry->d_name);
            continue;
        }

        if (virFileBuildPath(driver->autostartDir, entry->d_name,
                             NULL, autostartLink, PATH_MAX) < 0) {
            virStorageLog("Autostart link path '%s/%s' is too long",
                          driver->autostartDir, entry->d_name);
            continue;
        }

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

        virStoragePoolObjLoad(driver, entry->d_name, path, xml, autostartLink);

1117
        VIR_FREE(xml);
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
    }

    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))) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                                  _("cannot create config directory %s: %s"),
                                  driver->configDir, strerror(err));
            return -1;
        }

        if (virFileBuildPath(driver->configDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1148
                                  "%s", _("cannot construct config file path"));
1149 1150 1151 1152
            return -1;
        }
        if (!(pool->configFile = strdup(path))) {
            virStorageReportError(conn, VIR_ERR_NO_MEMORY,
J
Jim Meyering 已提交
1153
                                  "%s", _("configFile"));
1154 1155 1156 1157 1158 1159
            return -1;
        }

        if (virFileBuildPath(driver->autostartDir, def->name, ".xml",
                             path, sizeof(path)) < 0) {
            virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1160 1161
                                  "%s", _("cannot construct "
                                          "autostart link path"));
1162
            VIR_FREE(pool->configFile);
1163 1164 1165 1166
            return -1;
        }
        if (!(pool->autostartLink = strdup(path))) {
            virStorageReportError(conn, VIR_ERR_NO_MEMORY,
J
Jim Meyering 已提交
1167
                                  "%s", _("config file"));
1168
            VIR_FREE(pool->configFile);
1169 1170 1171 1172 1173 1174
            return -1;
        }
    }

    if (!(xml = virStoragePoolDefFormat(conn, def))) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1175
                              "%s", _("failed to generate XML"));
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
        return -1;
    }

    if ((fd = open(pool->configFile,
                   O_WRONLY | O_CREAT | O_TRUNC,
                   S_IRUSR | S_IWUSR )) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("cannot create config file %s: %s"),
                              pool->configFile, strerror(errno));
        goto cleanup;
    }

    towrite = strlen(xml);
    if (safewrite(fd, xml, towrite) != towrite) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("cannot write config file %s: %s"),
                              pool->configFile, strerror(errno));
        goto cleanup;
    }

    if (close(fd) < 0) {
        virStorageReportError(conn, VIR_ERR_INTERNAL_ERROR,
                              _("cannot save config file %s: %s"),
                              pool->configFile, strerror(errno));
        goto cleanup;
    }

    ret = 0;

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

1209
    VIR_FREE(xml);
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231

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