storage_driver.c 96.0 KB
Newer Older
1 2 3
/*
 * storage_driver.c: core driver for storage APIs
 *
4
 * Copyright (C) 2006-2015 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * 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
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
29 30 31 32
#include <sys/stat.h>
#include <sys/param.h>
#include <fcntl.h>

R
Richard W.M. Jones 已提交
33
#if HAVE_PWD_H
34
# include <pwd.h>
R
Richard W.M. Jones 已提交
35
#endif
36 37 38
#include <errno.h>
#include <string.h>

39
#include "virerror.h"
40
#include "datatypes.h"
41 42 43
#include "driver.h"
#include "storage_driver.h"
#include "storage_conf.h"
44
#include "viralloc.h"
45
#include "storage_backend.h"
46
#include "virlog.h"
E
Eric Blake 已提交
47
#include "virfile.h"
48
#include "fdstream.h"
49
#include "configmake.h"
50
#include "virstring.h"
51
#include "viraccessapicheck.h"
52
#include "dirname.h"
53

54 55
#define VIR_FROM_THIS VIR_FROM_STORAGE

56 57
VIR_LOG_INIT("storage.storage_driver");

58
static virStorageDriverStatePtr driver;
59

60
static int storageStateCleanup(void);
61

62 63 64 65 66 67
typedef struct _virStorageVolStreamInfo virStorageVolStreamInfo;
typedef virStorageVolStreamInfo *virStorageVolStreamInfoPtr;
struct _virStorageVolStreamInfo {
    char *pool_name;
};

68
static void storageDriverLock(void)
69
{
70
    virMutexLock(&driver->lock);
71
}
72
static void storageDriverUnlock(void)
73
{
74
    virMutexUnlock(&driver->lock);
75
}
76

77 78 79 80 81
static void
storagePoolUpdateState(virStoragePoolObjPtr pool)
{
    bool active;
    virStorageBackendPtr backend;
82 83 84 85 86 87
    int ret = -1;
    char *stateFile;

    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name, ".xml")))
        goto error;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
        VIR_ERROR(_("Missing backend %d"), pool->def->type);
        goto error;
    }

    /* Backends which do not support 'checkPool' are considered
     * inactive by default.
     */
    active = false;
    if (backend->checkPool &&
        backend->checkPool(pool, &active) < 0) {
        virErrorPtr err = virGetLastError();
        VIR_ERROR(_("Failed to initialize storage pool '%s': %s"),
                  pool->def->name, err ? err->message :
                  _("no error message found"));
        goto error;
    }

    /* We can pass NULL as connection, most backends do not use
     * it anyway, but if they do and fail, we want to log error and
     * continue with other pools.
     */
    if (active) {
        virStoragePoolObjClearVols(pool);
        if (backend->refreshPool(NULL, pool) < 0) {
            virErrorPtr err = virGetLastError();
            if (backend->stopPool)
                backend->stopPool(NULL, pool);
            VIR_ERROR(_("Failed to restart storage pool '%s': %s"),
                      pool->def->name, err ? err->message :
                      _("no error message found"));
            goto error;
        }
    }

    pool->active = active;
125
    ret = 0;
126
 error:
127 128 129 130 131 132
    if (ret < 0) {
        if (stateFile)
            unlink(stateFile);
    }
    VIR_FREE(stateFile);

133 134 135
    return;
}

136 137 138 139 140 141 142 143 144
static void
storagePoolUpdateAllState(void)
{
    size_t i;

    for (i = 0; i < driver->pools.count; i++) {
        virStoragePoolObjPtr pool = driver->pools.objs[i];

        virStoragePoolObjLock(pool);
145
        storagePoolUpdateState(pool);
146 147 148 149
        virStoragePoolObjUnlock(pool);
    }
}

150
static void
151
storageDriverAutostart(void)
152
{
153
    size_t i;
154 155 156
    virConnectPtr conn = NULL;

    /* XXX Remove hardcoding of QEMU URI */
157
    if (driver->privileged)
158 159 160 161
        conn = virConnectOpen("qemu:///system");
    else
        conn = virConnectOpen("qemu:///session");
    /* Ignoring NULL conn - let backends decide */
162

163
    for (i = 0; i < driver->pools.count; i++) {
164
        virStoragePoolObjPtr pool = driver->pools.objs[i];
165 166
        virStorageBackendPtr backend;
        bool started = false;
167

168
        virStoragePoolObjLock(pool);
169 170 171 172
        if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
            virStoragePoolObjUnlock(pool);
            continue;
        }
173

174
        if (pool->autostart &&
175
            !virStoragePoolObjIsActive(pool)) {
176
            if (backend->startPool &&
177
                backend->startPool(conn, pool) < 0) {
178
                virErrorPtr err = virGetLastError();
179
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
180
                          pool->def->name, err ? err->message :
181
                          _("no error message found"));
182
                virStoragePoolObjUnlock(pool);
183 184
                continue;
            }
185 186
            started = true;
        }
187

188
        if (started) {
189 190
            char *stateFile;

191
            virStoragePoolObjClearVols(pool);
192 193 194 195 196
            stateFile = virFileBuildPath(driver->stateDir,
                                         pool->def->name, ".xml");
            if (!stateFile ||
                virStoragePoolSaveState(stateFile, pool->def) < 0 ||
                backend->refreshPool(conn, pool) < 0) {
197
                virErrorPtr err = virGetLastError();
198 199
                if (stateFile)
                    unlink(stateFile);
200
                if (backend->stopPool)
201
                    backend->stopPool(conn, pool);
202
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
203
                          pool->def->name, err ? err->message :
204
                          _("no error message found"));
205 206
            } else {
                pool->active = true;
207
            }
208
            VIR_FREE(stateFile);
209
        }
210
        virStoragePoolObjUnlock(pool);
211
    }
212

213
    virObjectUnref(conn);
214 215 216 217 218
}

/**
 * virStorageStartup:
 *
219
 * Initialization function for the Storage Driver
220 221
 */
static int
222 223 224
storageStateInitialize(bool privileged,
                       virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                       void *opaque ATTRIBUTE_UNUSED)
225
{
226 227 228
    int ret = -1;
    char *configdir = NULL;
    char *rundir = NULL;
229

230
    if (VIR_ALLOC(driver) < 0)
231
        return ret;
232

233 234
    if (virMutexInit(&driver->lock) < 0) {
        VIR_FREE(driver);
235
        return ret;
236
    }
237
    storageDriverLock();
238

239
    if (privileged) {
240 241 242 243 244 245
        if (VIR_STRDUP(driver->configDir,
                       SYSCONFDIR "/libvirt/storage") < 0 ||
            VIR_STRDUP(driver->autostartDir,
                       SYSCONFDIR "/libvirt/storage/autostart") < 0 ||
            VIR_STRDUP(driver->stateDir,
                       LOCALSTATEDIR "/run/libvirt/storage") < 0)
246
            goto error;
247
    } else {
248 249 250 251 252 253 254 255
        configdir = virGetUserConfigDirectory();
        rundir = virGetUserRuntimeDirectory();
        if (!(configdir && rundir))
            goto error;

        if ((virAsprintf(&driver->configDir,
                        "%s/storage", configdir) < 0) ||
            (virAsprintf(&driver->autostartDir,
256
                        "%s/storage/autostart", configdir) < 0) ||
257 258
            (virAsprintf(&driver->stateDir,
                         "%s/storage/run", rundir) < 0))
259
            goto error;
260
    }
261
    driver->privileged = privileged;
262

263 264 265 266 267 268 269 270 271 272 273
    if (virFileMakePath(driver->stateDir) < 0) {
        virReportError(errno,
                       _("cannot create directory %s"),
                       driver->stateDir);
        goto error;
    }

    if (virStoragePoolLoadAllState(&driver->pools,
                                   driver->stateDir) < 0)
        goto error;

274 275 276
    if (virStoragePoolLoadAllConfigs(&driver->pools,
                                     driver->configDir,
                                     driver->autostartDir) < 0)
277
        goto error;
278

279 280
    storagePoolUpdateAllState();

281
    storageDriverUnlock();
282 283 284 285 286 287

    ret = 0;
 cleanup:
    VIR_FREE(configdir);
    VIR_FREE(rundir);
    return ret;
288

289
 error:
290
    storageDriverUnlock();
291
    storageStateCleanup();
292
    goto cleanup;
293 294
}

295 296 297 298 299 300 301 302
/**
 * storageStateAutoStart:
 *
 * Function to auto start the storage driver
 */
static void
storageStateAutoStart(void)
{
303
    if (!driver)
304 305
        return;

306 307 308
    storageDriverLock();
    storageDriverAutostart();
    storageDriverUnlock();
309 310
}

311
/**
312
 * storageStateReload:
313 314 315 316 317
 *
 * Function to restart the storage driver, it will recheck the configuration
 * files and update its state
 */
static int
318 319
storageStateReload(void)
{
320
    if (!driver)
321 322
        return -1;

323
    storageDriverLock();
324 325
    virStoragePoolLoadAllState(&driver->pools,
                               driver->stateDir);
326 327 328 329 330
    virStoragePoolLoadAllConfigs(&driver->pools,
                                 driver->configDir,
                                 driver->autostartDir);
    storageDriverAutostart();
    storageDriverUnlock();
331 332 333 334 335 336

    return 0;
}


/**
337
 * storageStateCleanup
338 339 340 341
 *
 * Shutdown the storage driver, it will stop all active storage pools
 */
static int
342 343
storageStateCleanup(void)
{
344
    if (!driver)
345 346
        return -1;

347
    storageDriverLock();
348 349

    /* free inactive pools */
350
    virStoragePoolObjListFree(&driver->pools);
351

352 353
    VIR_FREE(driver->configDir);
    VIR_FREE(driver->autostartDir);
354
    VIR_FREE(driver->stateDir);
355 356 357
    storageDriverUnlock();
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
358 359 360 361 362 363 364 365

    return 0;
}



static virStoragePoolPtr
storagePoolLookupByUUID(virConnectPtr conn,
366 367
                        const unsigned char *uuid)
{
368 369
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
370

371
    storageDriverLock();
372
    pool = virStoragePoolObjFindByUUID(&driver->pools, uuid);
373
    storageDriverUnlock();
374

375
    if (!pool) {
376 377
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
378
        virReportError(VIR_ERR_NO_STORAGE_POOL,
379 380
                       _("no storage pool with matching uuid '%s'"), uuidstr);
        return NULL;
381 382
    }

383 384 385
    if (virStoragePoolLookupByUUIDEnsureACL(conn, pool->def) < 0)
        goto cleanup;

386 387
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
388

389
 cleanup:
390
    virStoragePoolObjUnlock(pool);
391 392 393 394 395
    return ret;
}

static virStoragePoolPtr
storagePoolLookupByName(virConnectPtr conn,
396 397
                        const char *name)
{
398 399
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
400

401
    storageDriverLock();
402
    pool = virStoragePoolObjFindByName(&driver->pools, name);
403
    storageDriverUnlock();
404

405
    if (!pool) {
406
        virReportError(VIR_ERR_NO_STORAGE_POOL,
407
                       _("no storage pool with matching name '%s'"), name);
408
        return NULL;
409 410
    }

411 412 413
    if (virStoragePoolLookupByNameEnsureACL(conn, pool->def) < 0)
        goto cleanup;

414 415
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
416

417
 cleanup:
418
    virStoragePoolObjUnlock(pool);
419 420 421 422
    return ret;
}

static virStoragePoolPtr
423 424
storagePoolLookupByVolume(virStorageVolPtr vol)
{
425 426 427
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;

428
    storageDriverLock();
429
    pool = virStoragePoolObjFindByName(&driver->pools, vol->pool);
430
    storageDriverUnlock();
431 432 433

    if (!pool) {
        virReportError(VIR_ERR_NO_STORAGE_POOL,
434 435
                       _("no storage pool with matching name '%s'"),
                       vol->pool);
436
        return NULL;
437 438 439 440 441 442 443 444
    }

    if (virStoragePoolLookupByVolumeEnsureACL(vol->conn, pool->def) < 0)
        goto cleanup;

    ret = virGetStoragePool(vol->conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);

445
 cleanup:
446
    virStoragePoolObjUnlock(pool);
447
    return ret;
448 449 450
}

static int
451 452
storageConnectNumOfStoragePools(virConnectPtr conn)
{
453 454
    size_t i;
    int nactive = 0;
455

456 457 458
    if (virConnectNumOfStoragePoolsEnsureACL(conn) < 0)
        return -1;

459
    storageDriverLock();
460
    for (i = 0; i < driver->pools.count; i++) {
461 462 463
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfStoragePoolsCheckACL(conn, obj->def) &&
464
            virStoragePoolObjIsActive(obj))
465
            nactive++;
466
        virStoragePoolObjUnlock(obj);
467
    }
468
    storageDriverUnlock();
469 470

    return nactive;
471 472 473
}

static int
474 475
storageConnectListStoragePools(virConnectPtr conn,
                               char **const names,
476 477
                               int nnames)
{
478 479
    int got = 0;
    size_t i;
480

481 482 483
    if (virConnectListStoragePoolsEnsureACL(conn) < 0)
        return -1;

484
    storageDriverLock();
485
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
486 487 488
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListStoragePoolsCheckACL(conn, obj->def) &&
489
            virStoragePoolObjIsActive(obj)) {
490 491
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
492 493 494 495
                goto cleanup;
            }
            got++;
        }
496
        virStoragePoolObjUnlock(obj);
497
    }
498
    storageDriverUnlock();
499 500 501
    return got;

 cleanup:
502
    storageDriverUnlock();
503
    for (i = 0; i < got; i++)
504
        VIR_FREE(names[i]);
505
    memset(names, 0, nnames * sizeof(*names));
506 507 508 509
    return -1;
}

static int
510 511
storageConnectNumOfDefinedStoragePools(virConnectPtr conn)
{
512 513
    size_t i;
    int nactive = 0;
514

515 516 517
    if (virConnectNumOfDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

518
    storageDriverLock();
519
    for (i = 0; i < driver->pools.count; i++) {
520 521 522
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfDefinedStoragePoolsCheckACL(conn, obj->def) &&
523
            !virStoragePoolObjIsActive(obj))
524
            nactive++;
525
        virStoragePoolObjUnlock(obj);
526
    }
527
    storageDriverUnlock();
528 529

    return nactive;
530 531 532
}

static int
533 534
storageConnectListDefinedStoragePools(virConnectPtr conn,
                                      char **const names,
535 536
                                      int nnames)
{
537 538
    int got = 0;
    size_t i;
539

540 541 542
    if (virConnectListDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

543
    storageDriverLock();
544
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
545 546 547
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListDefinedStoragePoolsCheckACL(conn, obj->def) &&
548
            !virStoragePoolObjIsActive(obj)) {
549 550
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
551 552 553 554
                goto cleanup;
            }
            got++;
        }
555
        virStoragePoolObjUnlock(obj);
556
    }
557
    storageDriverUnlock();
558 559 560
    return got;

 cleanup:
561
    storageDriverUnlock();
562
    for (i = 0; i < got; i++)
563
        VIR_FREE(names[i]);
564
    memset(names, 0, nnames * sizeof(*names));
565 566 567
    return -1;
}

568 569
/* This method is required to be re-entrant / thread safe, so
   uses no driver lock */
570
static char *
571 572 573 574
storageConnectFindStoragePoolSources(virConnectPtr conn,
                                     const char *type,
                                     const char *srcSpec,
                                     unsigned int flags)
575 576 577
{
    int backend_type;
    virStorageBackendPtr backend;
578
    char *ret = NULL;
579

580 581 582
    if (virConnectFindStoragePoolSourcesEnsureACL(conn) < 0)
        return NULL;

583
    backend_type = virStoragePoolTypeFromString(type);
584
    if (backend_type < 0) {
585 586
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage pool type %s"), type);
587
        goto cleanup;
588
    }
589 590 591

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
592
        goto cleanup;
593

594
    if (!backend->findPoolSources) {
595 596 597
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("pool type '%s' does not support source "
                         "discovery"), type);
598 599 600 601
        goto cleanup;
    }

    ret = backend->findPoolSources(conn, srcSpec, flags);
602

603
 cleanup:
604
    return ret;
605 606 607
}


608 609
static virStoragePoolObjPtr
virStoragePoolObjFromStoragePool(virStoragePoolPtr pool)
610
{
611 612
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virStoragePoolObjPtr ret;
613

614
    storageDriverLock();
615 616 617 618 619
    if (!(ret = virStoragePoolObjFindByUUID(&driver->pools, pool->uuid))) {
        virUUIDFormat(pool->uuid, uuidstr);
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, pool->name);
620
    }
621
    storageDriverUnlock();
622 623 624 625 626 627 628 629 630 631 632 633

    return ret;
}


static int storagePoolIsActive(virStoragePoolPtr pool)
{
    virStoragePoolObjPtr obj;
    int ret = -1;

    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
634 635 636 637

    if (virStoragePoolIsActiveEnsureACL(pool->conn, obj->def) < 0)
        goto cleanup;

638 639
    ret = virStoragePoolObjIsActive(obj);

640
 cleanup:
641
    virStoragePoolObjUnlock(obj);
642 643 644
    return ret;
}

645
static int storagePoolIsPersistent(virStoragePoolPtr pool)
646 647 648 649
{
    virStoragePoolObjPtr obj;
    int ret = -1;

650 651
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
652 653 654 655

    if (virStoragePoolIsPersistentEnsureACL(pool->conn, obj->def) < 0)
        goto cleanup;

656 657
    ret = obj->configFile ? 1 : 0;

658
 cleanup:
659
    virStoragePoolObjUnlock(obj);
660 661 662 663
    return ret;
}


664
static virStoragePoolPtr
665 666 667
storagePoolCreateXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
668
{
669
    virStoragePoolDefPtr def;
670
    virStoragePoolObjPtr pool = NULL;
671
    virStoragePoolPtr ret = NULL;
672
    virStorageBackendPtr backend;
673
    char *stateFile = NULL;
674
    unsigned int build_flags = 0;
675

676 677 678 679 680 681
    virCheckFlags(VIR_STORAGE_POOL_CREATE_WITH_BUILD |
                  VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE |
                  VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE, NULL);

    VIR_EXCLUSIVE_FLAGS_RET(VIR_STORAGE_POOL_BUILD_OVERWRITE,
                            VIR_STORAGE_POOL_BUILD_NO_OVERWRITE, NULL);
E
Eric Blake 已提交
682

683
    storageDriverLock();
684
    if (!(def = virStoragePoolDefParseString(xml)))
685
        goto cleanup;
686

687 688 689
    if (virStoragePoolCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

690
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 1) < 0)
691
        goto cleanup;
692

693
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
694 695
        goto cleanup;

696 697
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
698

699
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
700 701
        goto cleanup;
    def = NULL;
702

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    if (backend->buildPool) {
        if (flags & VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE)
            build_flags |= VIR_STORAGE_POOL_BUILD_OVERWRITE;
        else if (flags & VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE)
            build_flags |= VIR_STORAGE_POOL_BUILD_NO_OVERWRITE;

        if (build_flags ||
            (flags & VIR_STORAGE_POOL_CREATE_WITH_BUILD)) {
            if (backend->buildPool(conn, pool, build_flags) < 0) {
                virStoragePoolObjRemove(&driver->pools, pool);
                pool = NULL;
                goto cleanup;
            }
        }
    }

719
    if (backend->startPool &&
720 721 722
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
723
        goto cleanup;
724
    }
725

726 727 728 729 730
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(conn, pool) < 0) {
731 732
        if (stateFile)
            unlink(stateFile);
733 734
        if (backend->stopPool)
            backend->stopPool(conn, pool);
735 736
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
737
        goto cleanup;
738
    }
739
    VIR_INFO("Creating storage pool '%s'", pool->def->name);
J
John Ferlan 已提交
740
    pool->active = true;
741

742 743
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
744

745
 cleanup:
746
    VIR_FREE(stateFile);
747
    virStoragePoolDefFree(def);
748
    if (pool)
749
        virStoragePoolObjUnlock(pool);
750
    storageDriverUnlock();
751 752 753 754
    return ret;
}

static virStoragePoolPtr
755 756 757
storagePoolDefineXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
758
{
759
    virStoragePoolDefPtr def;
760
    virStoragePoolObjPtr pool = NULL;
761
    virStoragePoolPtr ret = NULL;
762

E
Eric Blake 已提交
763 764
    virCheckFlags(0, NULL);

765
    storageDriverLock();
766
    if (!(def = virStoragePoolDefParseString(xml)))
767
        goto cleanup;
768

769 770 771
    if (virStoragePoolDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

772 773 774
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 0) < 0)
        goto cleanup;

775
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
776 777
        goto cleanup;

778
    if (virStorageBackendForType(def->type) == NULL)
779
        goto cleanup;
780

781
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
782
        goto cleanup;
783

784
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
785
        virStoragePoolObjRemove(&driver->pools, pool);
786
        def = NULL;
787
        goto cleanup;
788
    }
789
    def = NULL;
790

791
    VIR_INFO("Defining storage pool '%s'", pool->def->name);
792 793
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
794

795
 cleanup:
796
    virStoragePoolDefFree(def);
797 798
    if (pool)
        virStoragePoolObjUnlock(pool);
799
    storageDriverUnlock();
800 801 802 803
    return ret;
}

static int
804 805
storagePoolUndefine(virStoragePoolPtr obj)
{
806 807
    virStoragePoolObjPtr pool;
    int ret = -1;
808

809
    storageDriverLock();
810 811 812
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
813
        virReportError(VIR_ERR_NO_STORAGE_POOL,
814 815
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
816
        goto cleanup;
817 818
    }

819 820 821
    if (virStoragePoolUndefineEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

822
    if (virStoragePoolObjIsActive(pool)) {
823
        virReportError(VIR_ERR_OPERATION_INVALID,
824 825
                       _("storage pool '%s' is still active"),
                       pool->def->name);
826
        goto cleanup;
827 828
    }

829
    if (pool->asyncjobs > 0) {
830 831 832
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
833 834 835
        goto cleanup;
    }

836
    if (virStoragePoolObjDeleteDef(pool) < 0)
837
        goto cleanup;
838

839 840 841
    if (unlink(pool->autostartLink) < 0 &&
        errno != ENOENT &&
        errno != ENOTDIR) {
842
        char ebuf[1024];
843
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
844
                  pool->autostartLink, virStrerror(errno, ebuf, sizeof(ebuf)));
845
    }
846

847 848
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
849

850
    VIR_INFO("Undefining storage pool '%s'", pool->def->name);
851
    virStoragePoolObjRemove(&driver->pools, pool);
852
    pool = NULL;
853
    ret = 0;
854

855
 cleanup:
856 857
    if (pool)
        virStoragePoolObjUnlock(pool);
858
    storageDriverUnlock();
859
    return ret;
860 861 862
}

static int
863 864
storagePoolCreate(virStoragePoolPtr obj,
                  unsigned int flags)
E
Eric Blake 已提交
865
{
866
    virStoragePoolObjPtr pool;
867
    virStorageBackendPtr backend;
868
    int ret = -1;
869
    char *stateFile = NULL;
870
    unsigned int build_flags = 0;
871

872 873 874 875 876 877
    virCheckFlags(VIR_STORAGE_POOL_CREATE_WITH_BUILD |
                  VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE |
                  VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE, -1);

    VIR_EXCLUSIVE_FLAGS_RET(VIR_STORAGE_POOL_BUILD_OVERWRITE,
                            VIR_STORAGE_POOL_BUILD_NO_OVERWRITE, -1);
E
Eric Blake 已提交
878

879 880
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
881

882 883 884
    if (virStoragePoolCreateEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

885 886
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
887 888

    if (virStoragePoolObjIsActive(pool)) {
889
        virReportError(VIR_ERR_OPERATION_INVALID,
890 891
                       _("storage pool '%s' is already active"),
                       pool->def->name);
892
        goto cleanup;
893
    }
894

895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    if (backend->buildPool) {
        if (flags & VIR_STORAGE_POOL_CREATE_WITH_BUILD_OVERWRITE)
            build_flags |= VIR_STORAGE_POOL_BUILD_OVERWRITE;
        else if (flags & VIR_STORAGE_POOL_CREATE_WITH_BUILD_NO_OVERWRITE)
            build_flags |= VIR_STORAGE_POOL_BUILD_NO_OVERWRITE;

        if (build_flags ||
            (flags & VIR_STORAGE_POOL_CREATE_WITH_BUILD)) {
            if (backend->buildPool(obj->conn, pool, build_flags) < 0) {
                virStoragePoolObjRemove(&driver->pools, pool);
                pool = NULL;
                goto cleanup;
            }
        }
    }

911
    VIR_INFO("Starting up storage pool '%s'", pool->def->name);
912 913
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
914 915
        goto cleanup;

916 917 918 919 920
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(obj->conn, pool) < 0) {
921 922
        if (stateFile)
            unlink(stateFile);
923 924
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
925
        goto cleanup;
926 927
    }

J
John Ferlan 已提交
928
    pool->active = true;
929
    ret = 0;
930

931
 cleanup:
932
    VIR_FREE(stateFile);
933 934
    if (pool)
        virStoragePoolObjUnlock(pool);
935
    return ret;
936 937 938 939
}

static int
storagePoolBuild(virStoragePoolPtr obj,
940 941
                 unsigned int flags)
{
942
    virStoragePoolObjPtr pool;
943
    virStorageBackendPtr backend;
944
    int ret = -1;
945

946 947
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
948

949 950 951
    if (virStoragePoolBuildEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

952 953
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
954 955

    if (virStoragePoolObjIsActive(pool)) {
956
        virReportError(VIR_ERR_OPERATION_INVALID,
957 958
                       _("storage pool '%s' is already active"),
                       pool->def->name);
959
        goto cleanup;
960 961 962 963
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
964 965
        goto cleanup;
    ret = 0;
966

967
 cleanup:
968
    virStoragePoolObjUnlock(pool);
969
    return ret;
970 971 972 973
}


static int
974 975
storagePoolDestroy(virStoragePoolPtr obj)
{
976
    virStoragePoolObjPtr pool;
977
    virStorageBackendPtr backend;
978
    char *stateFile = NULL;
979
    int ret = -1;
980

981
    storageDriverLock();
982 983 984
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
985
        virReportError(VIR_ERR_NO_STORAGE_POOL,
986 987
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
988
        goto cleanup;
989 990
    }

991 992 993
    if (virStoragePoolDestroyEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

994 995
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
996

997 998
    VIR_INFO("Destroying storage pool '%s'", pool->def->name);

999
    if (!virStoragePoolObjIsActive(pool)) {
1000
        virReportError(VIR_ERR_OPERATION_INVALID,
1001
                       _("storage pool '%s' is not active"), pool->def->name);
1002
        goto cleanup;
1003 1004
    }

1005
    if (pool->asyncjobs > 0) {
1006 1007 1008
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
1009 1010 1011
        goto cleanup;
    }

1012 1013 1014 1015 1016 1017 1018 1019
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

1020 1021
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
1022
        goto cleanup;
1023 1024 1025

    virStoragePoolObjClearVols(pool);

J
John Ferlan 已提交
1026
    pool->active = false;
1027

1028
    if (pool->configFile == NULL) {
1029
        virStoragePoolObjRemove(&driver->pools, pool);
1030
        pool = NULL;
1031 1032 1033 1034
    } else if (pool->newDef) {
        virStoragePoolDefFree(pool->def);
        pool->def = pool->newDef;
        pool->newDef = NULL;
1035
    }
1036

1037
    ret = 0;
1038

1039
 cleanup:
1040 1041
    if (pool)
        virStoragePoolObjUnlock(pool);
1042
    storageDriverUnlock();
1043
    return ret;
1044 1045 1046 1047
}

static int
storagePoolDelete(virStoragePoolPtr obj,
1048 1049
                  unsigned int flags)
{
1050
    virStoragePoolObjPtr pool;
1051
    virStorageBackendPtr backend;
1052
    char *stateFile = NULL;
1053
    int ret = -1;
1054

1055 1056
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1057

1058 1059 1060
    if (virStoragePoolDeleteEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1061 1062
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
1063

1064 1065
    VIR_INFO("Deleting storage pool '%s'", pool->def->name);

1066
    if (virStoragePoolObjIsActive(pool)) {
1067
        virReportError(VIR_ERR_OPERATION_INVALID,
1068 1069
                       _("storage pool '%s' is still active"),
                       pool->def->name);
1070
        goto cleanup;
1071 1072
    }

1073
    if (pool->asyncjobs > 0) {
1074 1075
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
1076 1077 1078 1079
                              pool->def->name);
        goto cleanup;
    }

1080 1081 1082 1083 1084 1085 1086 1087
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

1088
    if (!backend->deletePool) {
1089 1090
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("pool does not support pool deletion"));
1091
        goto cleanup;
1092 1093
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
1094
        goto cleanup;
1095

1096
    ret = 0;
1097

1098
 cleanup:
1099
    virStoragePoolObjUnlock(pool);
1100
    return ret;
1101 1102 1103 1104 1105
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
E
Eric Blake 已提交
1106 1107
                   unsigned int flags)
{
1108
    virStoragePoolObjPtr pool;
1109
    virStorageBackendPtr backend;
1110
    int ret = -1;
1111

E
Eric Blake 已提交
1112 1113
    virCheckFlags(0, -1);

1114
    storageDriverLock();
1115 1116 1117
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1118
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1119 1120
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1121
        goto cleanup;
1122 1123
    }

1124 1125 1126
    if (virStoragePoolRefreshEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1127 1128
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
1129 1130

    if (!virStoragePoolObjIsActive(pool)) {
1131
        virReportError(VIR_ERR_OPERATION_INVALID,
1132
                       _("storage pool '%s' is not active"), pool->def->name);
1133
        goto cleanup;
1134 1135
    }

1136
    if (pool->asyncjobs > 0) {
1137 1138 1139
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
1140 1141 1142
        goto cleanup;
    }

1143
    virStoragePoolObjClearVols(pool);
1144
    if (backend->refreshPool(obj->conn, pool) < 0) {
1145 1146 1147
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

J
John Ferlan 已提交
1148
        pool->active = false;
1149

1150
        if (pool->configFile == NULL) {
1151
            virStoragePoolObjRemove(&driver->pools, pool);
1152 1153
            pool = NULL;
        }
1154
        goto cleanup;
1155
    }
1156
    ret = 0;
1157

1158
 cleanup:
1159 1160
    if (pool)
        virStoragePoolObjUnlock(pool);
1161
    storageDriverUnlock();
1162 1163 1164 1165 1166 1167
    return ret;
}


static int
storagePoolGetInfo(virStoragePoolPtr obj,
1168 1169
                   virStoragePoolInfoPtr info)
{
1170 1171
    virStoragePoolObjPtr pool;
    int ret = -1;
1172

1173 1174
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1175

1176 1177 1178
    if (virStoragePoolGetInfoEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1179
    if (virStorageBackendForType(pool->def->type) == NULL)
1180
        goto cleanup;
1181 1182 1183 1184 1185 1186 1187 1188 1189

    memset(info, 0, sizeof(virStoragePoolInfo));
    if (pool->active)
        info->state = VIR_STORAGE_POOL_RUNNING;
    else
        info->state = VIR_STORAGE_POOL_INACTIVE;
    info->capacity = pool->def->capacity;
    info->allocation = pool->def->allocation;
    info->available = pool->def->available;
1190
    ret = 0;
1191

1192
 cleanup:
1193
    virStoragePoolObjUnlock(pool);
1194
    return ret;
1195 1196 1197
}

static char *
1198
storagePoolGetXMLDesc(virStoragePoolPtr obj,
E
Eric Blake 已提交
1199 1200
                      unsigned int flags)
{
1201
    virStoragePoolObjPtr pool;
1202
    virStoragePoolDefPtr def;
1203
    char *ret = NULL;
1204

1205
    virCheckFlags(VIR_STORAGE_XML_INACTIVE, NULL);
E
Eric Blake 已提交
1206

1207 1208
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1209

1210 1211 1212
    if (virStoragePoolGetXMLDescEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1213 1214 1215 1216 1217 1218
    if ((flags & VIR_STORAGE_XML_INACTIVE) && pool->newDef)
        def = pool->newDef;
    else
        def = pool->def;

    ret = virStoragePoolDefFormat(def);
1219

1220
 cleanup:
1221
    virStoragePoolObjUnlock(pool);
1222
    return ret;
1223 1224 1225 1226
}

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
1227 1228
                        int *autostart)
{
1229 1230
    virStoragePoolObjPtr pool;
    int ret = -1;
1231

1232 1233
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1234

1235 1236 1237
    if (virStoragePoolGetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1238 1239 1240 1241 1242
    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
1243
    ret = 0;
1244

1245
 cleanup:
1246
    virStoragePoolObjUnlock(pool);
1247
    return ret;
1248 1249 1250 1251
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
1252 1253
                        int autostart)
{
1254 1255
    virStoragePoolObjPtr pool;
    int ret = -1;
1256

1257
    storageDriverLock();
1258
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1259

1260
    if (!pool) {
1261 1262
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1263
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1264 1265
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1266
        goto cleanup;
1267 1268
    }

1269 1270 1271
    if (virStoragePoolSetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1272
    if (!pool->configFile) {
1273 1274
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("pool has no config file"));
1275
        goto cleanup;
1276 1277 1278 1279
    }

    autostart = (autostart != 0);

1280 1281
    if (pool->autostart != autostart) {
        if (autostart) {
1282 1283
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
1284 1285
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1286 1287
                goto cleanup;
            }
1288

1289
            if (symlink(pool->configFile, pool->autostartLink) < 0) {
1290
                virReportSystemError(errno,
1291 1292
                                     _("Failed to create symlink '%s' to '%s'"),
                                     pool->autostartLink, pool->configFile);
1293 1294 1295 1296 1297
                goto cleanup;
            }
        } else {
            if (unlink(pool->autostartLink) < 0 &&
                errno != ENOENT && errno != ENOTDIR) {
1298
                virReportSystemError(errno,
1299 1300
                                     _("Failed to delete symlink '%s'"),
                                     pool->autostartLink);
1301 1302
                goto cleanup;
            }
1303
        }
1304
        pool->autostart = autostart;
1305
    }
1306
    ret = 0;
1307

1308
 cleanup:
1309 1310
    if (pool)
        virStoragePoolObjUnlock(pool);
1311
    storageDriverUnlock();
1312
    return ret;
1313 1314 1315 1316
}


static int
1317 1318
storagePoolNumOfVolumes(virStoragePoolPtr obj)
{
1319
    virStoragePoolObjPtr pool;
1320 1321
    int ret = -1;
    size_t i;
1322

1323 1324
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1325

1326 1327 1328
    if (virStoragePoolNumOfVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1329
    if (!virStoragePoolObjIsActive(pool)) {
1330
        virReportError(VIR_ERR_OPERATION_INVALID,
1331
                       _("storage pool '%s' is not active"), pool->def->name);
1332
        goto cleanup;
1333
    }
1334 1335 1336 1337 1338 1339
    ret = 0;
    for (i = 0; i < pool->volumes.count; i++) {
        if (virStoragePoolNumOfVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            ret++;
    }
1340

1341
 cleanup:
1342
    virStoragePoolObjUnlock(pool);
1343
    return ret;
1344 1345 1346 1347 1348
}

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
1349 1350
                       int maxnames)
{
1351
    virStoragePoolObjPtr pool;
1352 1353
    size_t i;
    int n = 0;
1354

1355 1356
    memset(names, 0, maxnames * sizeof(*names));

1357 1358
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1359

1360 1361 1362
    if (virStoragePoolListVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1363
    if (!virStoragePoolObjIsActive(pool)) {
1364
        virReportError(VIR_ERR_OPERATION_INVALID,
1365
                       _("storage pool '%s' is not active"), pool->def->name);
1366
        goto cleanup;
1367 1368
    }

1369
    for (i = 0; i < pool->volumes.count && n < maxnames; i++) {
1370 1371 1372
        if (!virStoragePoolListVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            continue;
1373
        if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0)
1374 1375 1376
            goto cleanup;
    }

1377
    virStoragePoolObjUnlock(pool);
1378
    return n;
1379 1380

 cleanup:
1381
    virStoragePoolObjUnlock(pool);
1382
    for (n = 0; n < maxnames; n++)
1383
        VIR_FREE(names[n]);
1384

1385
    memset(names, 0, maxnames * sizeof(*names));
1386 1387 1388
    return -1;
}

1389 1390 1391
static int
storagePoolListAllVolumes(virStoragePoolPtr pool,
                          virStorageVolPtr **vols,
1392 1393
                          unsigned int flags)
{
1394
    virStoragePoolObjPtr obj;
1395
    size_t i;
1396 1397 1398 1399 1400 1401 1402
    virStorageVolPtr *tmp_vols = NULL;
    virStorageVolPtr vol = NULL;
    int nvols = 0;
    int ret = -1;

    virCheckFlags(0, -1);

1403 1404
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
1405

1406 1407 1408
    if (virStoragePoolListAllVolumesEnsureACL(pool->conn, obj->def) < 0)
        goto cleanup;

1409
    if (!virStoragePoolObjIsActive(obj)) {
1410 1411
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("storage pool '%s' is not active"), obj->def->name);
1412 1413 1414 1415 1416 1417 1418 1419 1420
        goto cleanup;
    }

     /* Just returns the volumes count */
    if (!vols) {
        ret = obj->volumes.count;
        goto cleanup;
    }

1421
    if (VIR_ALLOC_N(tmp_vols, obj->volumes.count + 1) < 0)
1422
        goto cleanup;
1423

1424
    for (i = 0; i < obj->volumes.count; i++) {
1425 1426 1427
        if (!virStoragePoolListAllVolumesCheckACL(pool->conn, obj->def,
                                                  obj->volumes.objs[i]))
            continue;
1428 1429
        if (!(vol = virGetStorageVol(pool->conn, obj->def->name,
                                     obj->volumes.objs[i]->name,
1430 1431
                                     obj->volumes.objs[i]->key,
                                     NULL, NULL)))
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
            goto cleanup;
        tmp_vols[nvols++] = vol;
    }

    *vols = tmp_vols;
    tmp_vols = NULL;
    ret = nvols;

 cleanup:
    if (tmp_vols) {
1442 1443
        for (i = 0; i < nvols; i++)
            virObjectUnref(tmp_vols[i]);
1444
        VIR_FREE(tmp_vols);
1445 1446
    }

1447
    virStoragePoolObjUnlock(obj);
1448 1449 1450

    return ret;
}
1451 1452

static virStorageVolPtr
1453
storageVolLookupByName(virStoragePoolPtr obj,
1454 1455
                       const char *name)
{
1456
    virStoragePoolObjPtr pool;
1457
    virStorageVolDefPtr vol;
1458
    virStorageVolPtr ret = NULL;
1459

1460 1461
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1462 1463

    if (!virStoragePoolObjIsActive(pool)) {
1464
        virReportError(VIR_ERR_OPERATION_INVALID,
1465
                       _("storage pool '%s' is not active"), pool->def->name);
1466
        goto cleanup;
1467 1468 1469 1470 1471
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1472 1473 1474
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       name);
1475
        goto cleanup;
1476 1477
    }

1478 1479 1480
    if (virStorageVolLookupByNameEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1481 1482
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key,
                           NULL, NULL);
1483

1484
 cleanup:
1485
    virStoragePoolObjUnlock(pool);
1486
    return ret;
1487 1488 1489 1490
}


static virStorageVolPtr
1491
storageVolLookupByKey(virConnectPtr conn,
1492 1493
                      const char *key)
{
1494
    size_t i;
1495
    virStorageVolPtr ret = NULL;
1496

1497
    storageDriverLock();
1498
    for (i = 0; i < driver->pools.count && !ret; i++) {
1499
        virStoragePoolObjLock(driver->pools.objs[i]);
1500 1501 1502
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1503

1504
            if (vol) {
1505 1506
                virStoragePoolDefPtr def = driver->pools.objs[i]->def;
                if (virStorageVolLookupByKeyEnsureACL(conn, def, vol) < 0) {
1507
                    virStoragePoolObjUnlock(driver->pools.objs[i]);
1508
                    goto cleanup;
1509
                }
1510

1511
                ret = virGetStorageVol(conn,
1512
                                       def->name,
1513
                                       vol->name,
1514 1515
                                       vol->key,
                                       NULL, NULL);
1516
            }
1517
        }
1518
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1519 1520
    }

1521
    if (!ret)
1522
        virReportError(VIR_ERR_NO_STORAGE_VOL,
1523
                       _("no storage vol with matching key %s"), key);
1524

1525
 cleanup:
1526
    storageDriverUnlock();
1527
    return ret;
1528 1529 1530
}

static virStorageVolPtr
1531
storageVolLookupByPath(virConnectPtr conn,
1532 1533
                       const char *path)
{
1534
    size_t i;
1535
    virStorageVolPtr ret = NULL;
1536 1537 1538 1539 1540
    char *cleanpath;

    cleanpath = virFileSanitizePath(path);
    if (!cleanpath)
        return NULL;
1541

1542
    storageDriverLock();
1543
    for (i = 0; i < driver->pools.count && !ret; i++) {
1544 1545 1546 1547 1548
        virStoragePoolObjPtr pool = driver->pools.objs[i];
        virStorageVolDefPtr vol;
        char *stable_path = NULL;

        virStoragePoolObjLock(pool);
1549

1550 1551 1552 1553
        if (!virStoragePoolObjIsActive(pool)) {
           virStoragePoolObjUnlock(pool);
           continue;
        }
1554

1555
        switch ((virStoragePoolType) pool->def->type) {
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
            case VIR_STORAGE_POOL_DIR:
            case VIR_STORAGE_POOL_FS:
            case VIR_STORAGE_POOL_NETFS:
            case VIR_STORAGE_POOL_LOGICAL:
            case VIR_STORAGE_POOL_DISK:
            case VIR_STORAGE_POOL_ISCSI:
            case VIR_STORAGE_POOL_SCSI:
            case VIR_STORAGE_POOL_MPATH:
                stable_path = virStorageBackendStablePath(pool,
                                                          cleanpath,
                                                          false);
                if (stable_path == NULL) {
                    /* Don't break the whole lookup process if it fails on
                     * getting the stable path for some of the pools.
                     */
                    VIR_WARN("Failed to get stable path for pool '%s'",
                             pool->def->name);
                    virStoragePoolObjUnlock(pool);
                    continue;
                }
                break;

            case VIR_STORAGE_POOL_GLUSTER:
            case VIR_STORAGE_POOL_RBD:
            case VIR_STORAGE_POOL_SHEEPDOG:
R
Roman Bogorodskiy 已提交
1581
            case VIR_STORAGE_POOL_ZFS:
1582 1583 1584
            case VIR_STORAGE_POOL_LAST:
                if (VIR_STRDUP(stable_path, path) < 0) {
                     virStoragePoolObjUnlock(pool);
1585
                    goto cleanup;
1586
                }
1587 1588
                break;
        }
1589

1590 1591 1592 1593 1594 1595 1596
        vol = virStorageVolDefFindByPath(pool, stable_path);
        VIR_FREE(stable_path);

        if (vol) {
            if (virStorageVolLookupByPathEnsureACL(conn, pool->def, vol) < 0) {
                virStoragePoolObjUnlock(pool);
                goto cleanup;
1597
            }
1598 1599 1600 1601

            ret = virGetStorageVol(conn, pool->def->name,
                                   vol->name, vol->key,
                                   NULL, NULL);
1602
        }
1603 1604

        virStoragePoolObjUnlock(pool);
1605 1606
    }

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
    if (!ret) {
        if (STREQ(path, cleanpath)) {
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("no storage vol with matching path '%s'"), path);
        } else {
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("no storage vol with matching path '%s' (%s)"),
                           path, cleanpath);
        }
    }
1617

1618
 cleanup:
1619
    VIR_FREE(cleanpath);
1620
    storageDriverUnlock();
1621
    return ret;
1622 1623
}

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
virStoragePoolPtr
storagePoolLookupByTargetPath(virConnectPtr conn,
                              const char *path)
{
    size_t i;
    virStoragePoolPtr ret = NULL;
    char *cleanpath;

    cleanpath = virFileSanitizePath(path);
    if (!cleanpath)
        return NULL;

    storageDriverLock();
    for (i = 0; i < driver->pools.count && !ret; i++) {
        virStoragePoolObjPtr pool = driver->pools.objs[i];

        virStoragePoolObjLock(pool);

        if (!virStoragePoolObjIsActive(pool)) {
            virStoragePoolObjUnlock(pool);
            continue;
        }

        if (STREQ(path, pool->def->target.path)) {
            ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                                    NULL, NULL);
        }

        virStoragePoolObjUnlock(pool);
    }
    storageDriverUnlock();

    if (!ret) {
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage pool with matching target path '%s'"),
                       path);
    }

    VIR_FREE(cleanpath);
    return ret;
}

1666

1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685
static void
storageVolRemoveFromPool(virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol)
{
    size_t i;

    for (i = 0; i < pool->volumes.count; i++) {
        if (pool->volumes.objs[i] == vol) {
            VIR_INFO("Deleting volume '%s' from storage pool '%s'",
                     vol->name, pool->def->name);
            virStorageVolDefFree(vol);

            VIR_DELETE_ELEMENT(pool->volumes.objs, i, pool->volumes.count);
            break;
        }
    }
}


1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
static int
storageVolDeleteInternal(virStorageVolPtr obj,
                         virStorageBackendPtr backend,
                         virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol,
                         unsigned int flags,
                         bool updateMeta)
{
    int ret = -1;

    if (!backend->deleteVol) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support vol deletion"));

        goto cleanup;
    }

    if (backend->deleteVol(obj->conn, pool, vol, flags) < 0)
        goto cleanup;

    /* Update pool metadata - don't update meta data from error paths
1707 1708
     * in this module since the allocation/available weren't adjusted yet.
     * Ignore the disk backend since it updates the pool values.
1709 1710
     */
    if (updateMeta) {
1711 1712 1713 1714
        if (pool->def->type != VIR_STORAGE_POOL_DISK) {
            pool->def->allocation -= vol->target.allocation;
            pool->def->available += vol->target.allocation;
        }
1715 1716
    }

1717
    storageVolRemoveFromPool(pool, vol);
1718 1719 1720 1721 1722 1723 1724
    ret = 0;

 cleanup:
    return ret;
}


1725 1726 1727 1728
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1729 1730
{
    virStorageVolDefPtr vol = NULL;
1731 1732

    *pool = NULL;
1733

1734
    storageDriverLock();
1735
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1736
    storageDriverUnlock();
1737

1738
    if (!*pool) {
1739 1740 1741
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1742
        return NULL;
1743 1744
    }

1745
    if (!virStoragePoolObjIsActive(*pool)) {
1746
        virReportError(VIR_ERR_OPERATION_INVALID,
1747 1748 1749
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1750 1751
    }

1752
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1753 1754 1755
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1756
        goto error;
1757 1758
    }

1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
    if (backend) {
        if (!(*backend = virStorageBackendForType((*pool)->def->type)))
            goto error;
    }

    return vol;

 error:
    virStoragePoolObjUnlock(*pool);
    *pool = NULL;

    return NULL;
}


static int
storageVolDelete(virStorageVolPtr obj,
                 unsigned int flags)
{
    virStoragePoolObjPtr pool;
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return -1;

1786 1787 1788
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1789 1790 1791 1792 1793 1794 1795
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1796 1797 1798 1799 1800 1801 1802
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1803
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1804 1805 1806 1807
        goto cleanup;

    ret = 0;

1808
 cleanup:
1809
    virStoragePoolObjUnlock(pool);
1810 1811 1812
    return ret;
}

1813

1814
static virStorageVolPtr
1815 1816 1817
storageVolCreateXML(virStoragePoolPtr obj,
                    const char *xmldesc,
                    unsigned int flags)
E
Eric Blake 已提交
1818
{
1819
    virStoragePoolObjPtr pool;
1820
    virStorageBackendPtr backend;
1821 1822
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1823

1824
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1825

1826 1827
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1828 1829

    if (!virStoragePoolObjIsActive(pool)) {
1830
        virReportError(VIR_ERR_OPERATION_INVALID,
1831
                       _("storage pool '%s' is not active"), pool->def->name);
1832
        goto cleanup;
1833 1834 1835
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
1836
        goto cleanup;
1837

1838 1839
    voldef = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_OPT_CAPACITY);
1840
    if (voldef == NULL)
1841
        goto cleanup;
1842

1843 1844 1845 1846 1847 1848 1849
    if (!voldef->target.capacity && !backend->buildVol) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("volume capacity required for this "
                               "storage pool"));
        goto cleanup;
    }

1850 1851 1852
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1853
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1854
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1855
                       _("'%s'"), voldef->name);
1856
        goto cleanup;
1857 1858 1859
    }

    if (!backend->createVol) {
1860 1861 1862
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1863
        goto cleanup;
1864 1865
    }

1866 1867 1868 1869
    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count+1) < 0)
        goto cleanup;

1870 1871 1872
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1873
    if (backend->createVol(obj->conn, pool, voldef) < 0)
1874
        goto cleanup;
1875

1876 1877 1878 1879 1880 1881 1882 1883
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
                              voldef->key, NULL, NULL);
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }

1884

1885 1886
    if (backend->buildVol) {
        int buildret;
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898
        virStorageVolDefPtr buildvoldef = NULL;

        if (VIR_ALLOC(buildvoldef) < 0) {
            voldef = NULL;
            goto cleanup;
        }

        /* Make a shallow copy of the 'defined' volume definition, since the
         * original allocation value will change as the user polls 'info',
         * but we only need the initial requested values
         */
        memcpy(buildvoldef, voldef, sizeof(*voldef));
1899 1900 1901

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1902
        voldef->building = true;
1903 1904
        virStoragePoolObjUnlock(pool);

1905
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1906

1907 1908
        VIR_FREE(buildvoldef);

1909
        storageDriverLock();
1910
        virStoragePoolObjLock(pool);
1911
        storageDriverUnlock();
1912

1913
        voldef->building = false;
1914 1915
        pool->asyncjobs--;

1916
        if (buildret < 0) {
1917 1918
            /* buildVol handles deleting volume on failure */
            storageVolRemoveFromPool(pool, voldef);
1919
            voldef = NULL;
1920
            goto cleanup;
1921
        }
1922

1923
    }
1924

1925
    if (backend->refreshVol &&
1926 1927 1928 1929
        backend->refreshVol(obj->conn, pool, voldef) < 0) {
        storageVolDeleteInternal(volobj, backend, pool, voldef,
                                 0, false);
        voldef = NULL;
1930
        goto cleanup;
1931
    }
1932

1933 1934 1935 1936
    /* Update pool metadata ignoring the disk backend since
     * it updates the pool values.
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
1937 1938
        pool->def->allocation += voldef->target.allocation;
        pool->def->available -= voldef->target.allocation;
1939
    }
1940

1941
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1942
             volobj->name, pool->def->name);
1943 1944 1945
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1946

1947
 cleanup:
1948
    virObjectUnref(volobj);
1949
    virStorageVolDefFree(voldef);
1950 1951
    if (pool)
        virStoragePoolObjUnlock(pool);
1952
    return ret;
1953 1954
}

1955
static virStorageVolPtr
1956 1957 1958 1959
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1960
{
1961 1962
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
1963
    virStorageVolDefPtr origvol = NULL, newvol = NULL, shadowvol = NULL;
1964
    virStorageVolPtr ret = NULL, volobj = NULL;
1965
    int buildret;
1966

1967 1968 1969
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA |
                  VIR_STORAGE_VOL_CREATE_REFLINK,
                  NULL);
E
Eric Blake 已提交
1970

1971
    storageDriverLock();
1972
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1973
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1974
        virStoragePoolObjUnlock(pool);
1975
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1976
        virStoragePoolObjLock(pool);
1977
    }
1978
    storageDriverUnlock();
1979
    if (!pool) {
1980 1981
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1982
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1983 1984
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1985 1986 1987
        goto cleanup;
    }

1988
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1989 1990 1991
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1992 1993 1994 1995
        goto cleanup;
    }

    if (!virStoragePoolObjIsActive(pool)) {
1996
        virReportError(VIR_ERR_OPERATION_INVALID,
1997
                       _("storage pool '%s' is not active"), pool->def->name);
1998 1999 2000
        goto cleanup;
    }

2001
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
2002
        virReportError(VIR_ERR_OPERATION_INVALID,
2003 2004
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
2005 2006 2007 2008 2009 2010
        goto cleanup;
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;

2011 2012
    origvol = virStorageVolDefFindByName(origpool ?
                                         origpool : pool, vobj->name);
2013
    if (!origvol) {
2014 2015 2016
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
2017 2018 2019
        goto cleanup;
    }

2020 2021
    newvol = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_NO_CAPACITY);
2022 2023 2024
    if (newvol == NULL)
        goto cleanup;

2025 2026 2027
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

2028
    if (virStorageVolDefFindByName(pool, newvol->name)) {
2029 2030 2031
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
2032 2033 2034
        goto cleanup;
    }

2035 2036
    /* Use the original volume's capacity in case the new capacity
     * is less than that, or it was omitted */
2037 2038
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
2039 2040

    if (!backend->buildVolFrom) {
2041
        virReportError(VIR_ERR_NO_SUPPORT,
2042 2043
                       "%s", _("storage pool does not support"
                               " volume creation from an existing volume"));
2044 2045 2046 2047
        goto cleanup;
    }

    if (origvol->building) {
2048 2049 2050
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
2051 2052 2053 2054 2055 2056 2057 2058
        goto cleanup;
    }

    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, origvol) < 0)
        goto cleanup;

    if (VIR_REALLOC_N(pool->volumes.objs,
2059
                      pool->volumes.count+1) < 0)
2060 2061
        goto cleanup;

2062 2063 2064 2065
    /* 'Define' the new volume so we get async progress reporting.
     * Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(newvol->key);
2066
    if (backend->createVol(obj->conn, pool, newvol) < 0)
2067 2068
        goto cleanup;

2069 2070 2071 2072 2073 2074 2075 2076 2077
    /* Make a shallow copy of the 'defined' volume definition, since the
     * original allocation value will change as the user polls 'info',
     * but we only need the initial requested values
     */
    if (VIR_ALLOC(shadowvol) < 0)
        goto cleanup;

    memcpy(shadowvol, newvol, sizeof(*newvol));

2078 2079
    pool->volumes.objs[pool->volumes.count++] = newvol;
    volobj = virGetStorageVol(obj->conn, pool->def->name, newvol->name,
2080
                              newvol->key, NULL, NULL);
2081 2082 2083 2084
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
2085 2086 2087

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
2088
    newvol->building = true;
2089
    origvol->in_use++;
2090 2091
    virStoragePoolObjUnlock(pool);

2092
    if (origpool) {
2093 2094 2095 2096
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

2097
    buildret = backend->buildVolFrom(obj->conn, pool, shadowvol, origvol, flags);
2098

2099
    storageDriverLock();
2100
    virStoragePoolObjLock(pool);
2101
    if (origpool)
2102
        virStoragePoolObjLock(origpool);
2103
    storageDriverUnlock();
2104

2105
    origvol->in_use--;
2106
    newvol->building = false;
2107 2108
    pool->asyncjobs--;

2109
    if (origpool) {
2110 2111 2112 2113 2114
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

2115 2116 2117
    if (buildret < 0 ||
        (backend->refreshVol &&
         backend->refreshVol(obj->conn, pool, newvol) < 0)) {
2118 2119
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
2120 2121 2122
        goto cleanup;
    }

2123 2124 2125 2126
    /* Updating pool metadata ignoring the disk backend since
     * it updates the pool values
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
2127 2128
        pool->def->allocation += newvol->target.allocation;
        pool->def->available -= newvol->target.allocation;
2129
    }
2130

2131
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
2132
             volobj->name, pool->def->name);
2133 2134
    ret = volobj;
    volobj = NULL;
2135
    newvol = NULL;
2136

2137
 cleanup:
2138
    virObjectUnref(volobj);
2139
    virStorageVolDefFree(newvol);
2140
    VIR_FREE(shadowvol);
2141 2142
    if (pool)
        virStoragePoolObjUnlock(pool);
2143
    if (origpool)
2144 2145 2146 2147
        virStoragePoolObjUnlock(origpool);
    return ret;
}

2148

2149
static int
2150 2151 2152 2153 2154
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
2155
{
2156
    virStorageBackendPtr backend;
2157 2158 2159 2160 2161 2162
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

2163
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
2164
        return -1;
2165

2166
    if (virStorageVolDownloadEnsureACL(obj->conn, pool->def, vol) < 0)
2167
        goto cleanup;
2168

2169
    if (vol->building) {
2170 2171 2172
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2173
        goto cleanup;
2174 2175
    }

2176 2177 2178
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
2179
        goto cleanup;
2180
    }
2181

2182 2183
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
2184

2185
 cleanup:
2186
    virStoragePoolObjUnlock(pool);
2187 2188 2189 2190 2191

    return ret;
}


2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219
/**
 * Frees opaque data.
 *
 * @opaque Data to be freed.
 */
static void
virStorageVolPoolRefreshDataFree(void *opaque)
{
    virStorageVolStreamInfoPtr cbdata = opaque;

    VIR_FREE(cbdata->pool_name);
    VIR_FREE(cbdata);
}

/**
 * Thread to handle the pool refresh
 *
 * @st Pointer to stream being closed.
 * @opaque Domain's device information structure.
 */
static void
virStorageVolPoolRefreshThread(void *opaque)
{

    virStorageVolStreamInfoPtr cbdata = opaque;
    virStoragePoolObjPtr pool = NULL;
    virStorageBackendPtr backend;

2220 2221
    storageDriverLock();
    if (!(pool = virStoragePoolObjFindByName(&driver->pools,
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234
                                             cbdata->pool_name)))
        goto cleanup;

    if (!(backend = virStorageBackendForType(pool->def->type)))
        goto cleanup;

    virStoragePoolObjClearVols(pool);
    if (backend->refreshPool(NULL, pool) < 0)
        VIR_DEBUG("Failed to refresh storage pool");

 cleanup:
    if (pool)
        virStoragePoolObjUnlock(pool);
2235
    storageDriverUnlock();
2236 2237 2238 2239 2240 2241 2242 2243
    virStorageVolPoolRefreshDataFree(cbdata);
}

/**
 * Callback being called if a FDstream is closed. Will spin off a thread
 * to perform a pool refresh.
 *
 * @st Pointer to stream being closed.
C
Chen Hanxiao 已提交
2244
 * @opaque Buffer to hold the pool name to be refreshed
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
 */
static void
virStorageVolFDStreamCloseCb(virStreamPtr st ATTRIBUTE_UNUSED,
                             void *opaque)
{
    virThread thread;

    if (virThreadCreate(&thread, false, virStorageVolPoolRefreshThread,
                        opaque) < 0) {
        /* Not much else can be done */
        VIR_ERROR(_("Failed to create thread to handle pool refresh"));
        goto error;
    }
    return; /* Thread will free opaque data */

 error:
    virStorageVolPoolRefreshDataFree(opaque);
}

2264
static int
2265 2266 2267 2268 2269
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2270
{
2271
    virStorageBackendPtr backend;
2272 2273
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2274
    virStorageVolStreamInfoPtr cbdata = NULL;
2275 2276 2277 2278
    int ret = -1;

    virCheckFlags(0, -1);

2279
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
2280
        return -1;
2281

2282
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2283
        goto cleanup;
2284

2285 2286 2287 2288 2289 2290 2291
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2292
    if (vol->building) {
2293 2294 2295
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2296
        goto cleanup;
2297 2298
    }

2299 2300 2301
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2302
        goto cleanup;
2303
    }
2304

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
    /* If we have a refreshPool, use the callback routine in order to
     * refresh the pool after the volume upload stream closes. This way
     * we make sure the volume and pool data are refreshed without user
     * interaction and we can just lookup the backend in the callback
     * routine in order to call the refresh API.
     */
    if (backend->refreshPool) {
        if (VIR_ALLOC(cbdata) < 0 ||
            VIR_STRDUP(cbdata->pool_name, pool->def->name) < 0)
            goto cleanup;
    }

2317 2318 2319
    if ((ret = backend->uploadVol(obj->conn, pool, vol, stream,
                                  offset, length, flags)) < 0)
        goto cleanup;
2320

2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

2331
 cleanup:
2332
    virStoragePoolObjUnlock(pool);
2333 2334
    if (cbdata)
        virStorageVolPoolRefreshDataFree(cbdata);
2335 2336 2337 2338

    return ret;
}

2339
static int
2340 2341 2342
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2343 2344 2345 2346
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2347
    unsigned long long abs_capacity, delta = 0;
2348 2349
    int ret = -1;

2350
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2351 2352
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2353

2354 2355
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return -1;
2356

2357
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2358
        goto cleanup;
2359

2360 2361 2362 2363 2364 2365 2366
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2367
    if (vol->building) {
2368 2369 2370
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2371
        goto cleanup;
2372
    }
2373

2374
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2375 2376 2377 2378
        if (flags & VIR_STORAGE_VOL_RESIZE_SHRINK)
            abs_capacity = vol->target.capacity - MIN(capacity, vol->target.capacity);
        else
            abs_capacity = vol->target.capacity + capacity;
2379 2380 2381 2382 2383
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2384
    if (abs_capacity < vol->target.allocation) {
2385
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2386 2387
                       _("can't shrink capacity below "
                         "existing allocation"));
2388
        goto cleanup;
2389 2390
    }

2391
    if (abs_capacity < vol->target.capacity &&
2392 2393 2394
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
2395
                         "capacity unless shrink flag explicitly specified"));
2396
        goto cleanup;
2397 2398
    }

2399
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE)
2400 2401
        delta = abs_capacity - vol->target.allocation;

2402
    if (delta > pool->def->available) {
2403
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2404
                       _("Not enough space left in storage pool"));
2405
        goto cleanup;
2406 2407 2408
    }

    if (!backend->resizeVol) {
2409
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2410 2411
                       _("storage pool does not support changing of "
                         "volume capacity"));
2412
        goto cleanup;
2413 2414 2415
    }

    if (backend->resizeVol(obj->conn, pool, vol, abs_capacity, flags) < 0)
2416
        goto cleanup;
2417

2418
    vol->target.capacity = abs_capacity;
2419 2420 2421 2422 2423
    /* Only update the allocation and pool values if we actually did the
     * allocation; otherwise, this is akin to a create operation with a
     * capacity value different and potentially much larger than available
     */
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE) {
2424
        vol->target.allocation = abs_capacity;
2425 2426
        pool->def->allocation += delta;
        pool->def->available -= delta;
2427
    }
2428

O
Osier Yang 已提交
2429
    ret = 0;
2430

2431
 cleanup:
2432
    virStoragePoolObjUnlock(pool);
2433 2434 2435

    return ret;
}
2436

2437 2438

static int
2439 2440 2441
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2442
{
2443
    virStorageBackendPtr backend;
2444 2445 2446 2447
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2448
    virCheckFlags(0, -1);
2449

2450
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2451 2452 2453
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2454 2455 2456
        return -1;
    }

2457
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
2458
        return -1;
2459 2460


2461
    if (virStorageVolWipePatternEnsureACL(obj->conn, pool->def, vol) < 0)
2462
        goto cleanup;
2463

2464 2465 2466 2467 2468 2469 2470
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2471
    if (vol->building) {
2472 2473 2474
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2475
        goto cleanup;
2476 2477
    }

2478 2479 2480
    if (!backend->wipeVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume wiping"));
2481
        goto cleanup;
2482
    }
2483

2484 2485 2486 2487 2488 2489 2490 2491
    if (backend->wipeVol(obj->conn, pool, vol, algorithm, flags) < 0)
        goto cleanup;

    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
        goto cleanup;

    ret = 0;
2492

2493
 cleanup:
2494
    virStoragePoolObjUnlock(pool);
2495 2496 2497 2498

    return ret;
}

2499
static int
2500 2501
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2502
{
2503
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2504 2505
}

2506 2507

static int
2508
storageVolGetInfo(virStorageVolPtr obj,
2509 2510
                  virStorageVolInfoPtr info)
{
2511
    virStoragePoolObjPtr pool;
2512 2513
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2514
    int ret = -1;
2515

2516 2517
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return -1;
2518

2519 2520 2521
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2522 2523
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2524
        goto cleanup;
2525 2526

    memset(info, 0, sizeof(*info));
2527
    info->type = vol->type;
2528 2529
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2530
    ret = 0;
2531

2532
 cleanup:
2533
    virStoragePoolObjUnlock(pool);
2534
    return ret;
2535 2536 2537
}

static char *
2538 2539
storageVolGetXMLDesc(virStorageVolPtr obj,
                     unsigned int flags)
E
Eric Blake 已提交
2540
{
2541
    virStoragePoolObjPtr pool;
2542 2543
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2544
    char *ret = NULL;
2545

E
Eric Blake 已提交
2546 2547
    virCheckFlags(0, NULL);

2548 2549
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return NULL;
2550

2551 2552 2553
    if (virStorageVolGetXMLDescEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2554 2555 2556
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
        goto cleanup;
2557

2558
    ret = virStorageVolDefFormat(pool->def, vol);
2559

2560
 cleanup:
2561
    virStoragePoolObjUnlock(pool);
2562

2563
    return ret;
2564 2565 2566
}

static char *
2567 2568
storageVolGetPath(virStorageVolPtr obj)
{
2569
    virStoragePoolObjPtr pool;
2570
    virStorageVolDefPtr vol;
2571
    char *ret = NULL;
2572

2573 2574
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2575

2576 2577 2578
    if (virStorageVolGetPathEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2579
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2580

2581
 cleanup:
2582
    virStoragePoolObjUnlock(pool);
2583 2584 2585
    return ret;
}

2586
static int
2587 2588 2589
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2590 2591 2592 2593 2594
{
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2595 2596 2597
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2598
    storageDriverLock();
2599
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
2600 2601
                                      virConnectListAllStoragePoolsCheckACL,
                                      flags);
2602
    storageDriverUnlock();
2603

2604
 cleanup:
2605 2606 2607
    return ret;
}

2608

2609
static virStorageDriver storageDriver = {
2610
    .name = "storage",
2611 2612 2613 2614 2615 2616
    .connectNumOfStoragePools = storageConnectNumOfStoragePools, /* 0.4.0 */
    .connectListStoragePools = storageConnectListStoragePools, /* 0.4.0 */
    .connectNumOfDefinedStoragePools = storageConnectNumOfDefinedStoragePools, /* 0.4.0 */
    .connectListDefinedStoragePools = storageConnectListDefinedStoragePools, /* 0.4.0 */
    .connectListAllStoragePools = storageConnectListAllStoragePools, /* 0.10.2 */
    .connectFindStoragePoolSources = storageConnectFindStoragePoolSources, /* 0.4.0 */
2617 2618 2619
    .storagePoolLookupByName = storagePoolLookupByName, /* 0.4.0 */
    .storagePoolLookupByUUID = storagePoolLookupByUUID, /* 0.4.0 */
    .storagePoolLookupByVolume = storagePoolLookupByVolume, /* 0.4.0 */
2620 2621
    .storagePoolCreateXML = storagePoolCreateXML, /* 0.4.0 */
    .storagePoolDefineXML = storagePoolDefineXML, /* 0.4.0 */
2622 2623
    .storagePoolBuild = storagePoolBuild, /* 0.4.0 */
    .storagePoolUndefine = storagePoolUndefine, /* 0.4.0 */
2624
    .storagePoolCreate = storagePoolCreate, /* 0.4.0 */
2625 2626 2627 2628 2629 2630 2631
    .storagePoolDestroy = storagePoolDestroy, /* 0.4.0 */
    .storagePoolDelete = storagePoolDelete, /* 0.4.0 */
    .storagePoolRefresh = storagePoolRefresh, /* 0.4.0 */
    .storagePoolGetInfo = storagePoolGetInfo, /* 0.4.0 */
    .storagePoolGetXMLDesc = storagePoolGetXMLDesc, /* 0.4.0 */
    .storagePoolGetAutostart = storagePoolGetAutostart, /* 0.4.0 */
    .storagePoolSetAutostart = storagePoolSetAutostart, /* 0.4.0 */
2632
    .storagePoolNumOfVolumes = storagePoolNumOfVolumes, /* 0.4.0 */
2633 2634 2635
    .storagePoolListVolumes = storagePoolListVolumes, /* 0.4.0 */
    .storagePoolListAllVolumes = storagePoolListAllVolumes, /* 0.10.2 */

2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649
    .storageVolLookupByName = storageVolLookupByName, /* 0.4.0 */
    .storageVolLookupByKey = storageVolLookupByKey, /* 0.4.0 */
    .storageVolLookupByPath = storageVolLookupByPath, /* 0.4.0 */
    .storageVolCreateXML = storageVolCreateXML, /* 0.4.0 */
    .storageVolCreateXMLFrom = storageVolCreateXMLFrom, /* 0.6.4 */
    .storageVolDownload = storageVolDownload, /* 0.9.0 */
    .storageVolUpload = storageVolUpload, /* 0.9.0 */
    .storageVolDelete = storageVolDelete, /* 0.4.0 */
    .storageVolWipe = storageVolWipe, /* 0.8.0 */
    .storageVolWipePattern = storageVolWipePattern, /* 0.9.10 */
    .storageVolGetInfo = storageVolGetInfo, /* 0.4.0 */
    .storageVolGetXMLDesc = storageVolGetXMLDesc, /* 0.4.0 */
    .storageVolGetPath = storageVolGetPath, /* 0.4.0 */
    .storageVolResize = storageVolResize, /* 0.9.10 */
2650 2651 2652

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2653 2654 2655 2656
};


static virStateDriver stateDriver = {
2657
    .name = "storage",
2658
    .stateInitialize = storageStateInitialize,
2659
    .stateAutoStart = storageStateAutoStart,
2660 2661
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2662 2663
};

2664 2665
int storageRegister(void)
{
2666
    if (virSetSharedStorageDriver(&storageDriver) < 0)
2667
        return -1;
2668 2669
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2670 2671
    return 0;
}
2672 2673 2674


/* ----------- file handlers cooperating with storage driver --------------- */
2675 2676 2677
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2678
    return src && src->drv;
2679 2680
}

2681 2682 2683 2684

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2685
    int actualType;
2686 2687 2688 2689
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2690
    actualType = virStorageSourceGetActualType(src);
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705

    if (src->drv) {
        backend = src->drv->backend;
    } else {
        if (!(backend = virStorageFileBackendForTypeInternal(actualType,
                                                             src->protocol,
                                                             false)))
            return false;
    }

    return backend->storageFileGetUniqueIdentifier &&
           backend->storageFileReadHeader &&
           backend->storageFileAccess;
}

2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717

/**
 * virStorageFileSupportsSecurityDriver:
 *
 * @src: a storage file structure
 *
 * Check if a storage file supports operations needed by the security
 * driver to perform labelling
 */
bool
virStorageFileSupportsSecurityDriver(virStorageSourcePtr src)
{
2718
    int actualType;
2719 2720 2721 2722
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2723
    actualType = virStorageSourceGetActualType(src);
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737

    if (src->drv) {
        backend = src->drv->backend;
    } else {
        if (!(backend = virStorageFileBackendForTypeInternal(actualType,
                                                             src->protocol,
                                                             false)))
            return false;
    }

    return !!backend->storageFileChown;
}


2738
void
2739
virStorageFileDeinit(virStorageSourcePtr src)
2740
{
2741
    if (!virStorageFileIsInitialized(src))
2742 2743
        return;

2744 2745 2746
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2747

2748
    VIR_FREE(src->drv);
2749 2750 2751
}


2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
/**
 * virStorageFileInitAs:
 *
 * @src: storage source definition
 * @uid: uid used to access the file, or -1 for current uid
 * @gid: gid used to access the file, or -1 for current gid
 *
 * Initialize a storage source to be used with storage driver. Use the provided
 * uid and gid if possible for the operations.
 *
 * Returns 0 if the storage file was successfully initialized, -1 if the
 * initialization failed. Libvirt error is reported.
 */
2765
int
2766 2767
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
2768
{
2769 2770 2771
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;
2772

2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
    if (uid == (uid_t) -1)
        src->drv->uid = geteuid();
    else
        src->drv->uid = uid;

    if (gid == (gid_t) -1)
        src->drv->gid = getegid();
    else
        src->drv->gid = gid;

2783 2784
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2785 2786
        goto error;

2787 2788
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2789 2790
        goto error;

2791
    return 0;
2792

2793
 error:
2794 2795
    VIR_FREE(src->drv);
    return -1;
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
2809 2810 2811 2812 2813 2814
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
2815
 * @src: file structure pointing to the file
2816 2817 2818 2819 2820
 *
 * Returns 0 on success, -2 if the function isn't supported by the backend,
 * -1 on other failure. Errno is set in case of failure.
 */
int
2821
virStorageFileCreate(virStorageSourcePtr src)
2822
{
2823 2824
    int ret;

2825 2826
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2827 2828 2829 2830
        errno = ENOSYS;
        return -2;
    }

2831 2832 2833 2834 2835 2836
    ret = src->drv->backend->storageFileCreate(src);

    VIR_DEBUG("created storage file %p: ret=%d, errno=%d",
              src, ret, errno);

    return ret;
2837 2838 2839 2840 2841 2842
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
2843
 * @src: file structure pointing to the file
2844 2845 2846 2847 2848 2849 2850
 *
 * Unlinks the file described by the @file structure.
 *
 * Returns 0 on success, -2 if the function isn't supported by the backend,
 * -1 on other failure. Errno is set in case of failure.
 */
int
2851
virStorageFileUnlink(virStorageSourcePtr src)
2852
{
2853 2854
    int ret;

2855 2856
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2857 2858 2859 2860
        errno = ENOSYS;
        return -2;
    }

2861 2862 2863 2864 2865 2866
    ret = src->drv->backend->storageFileUnlink(src);

    VIR_DEBUG("unlinked storage file %p: ret=%d, errno=%d",
              src, ret, errno);

    return ret;
2867 2868 2869 2870 2871 2872
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
2873
 * @src: file structure pointing to the file
2874 2875 2876 2877 2878 2879
 * @stat: stat structure to return data
 *
 * Returns 0 on success, -2 if the function isn't supported by the backend,
 * -1 on other failure. Errno is set in case of failure.
*/
int
2880
virStorageFileStat(virStorageSourcePtr src,
2881 2882
                   struct stat *st)
{
2883 2884
    int ret;

2885 2886
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2887 2888 2889 2890
        errno = ENOSYS;
        return -2;
    }

2891 2892 2893 2894 2895 2896
    ret = src->drv->backend->storageFileStat(src, st);

    VIR_DEBUG("stat of storage file %p: ret=%d, errno=%d",
              src, ret, errno);

    return ret;
2897
}
2898 2899 2900 2901 2902 2903 2904 2905 2906 2907


/**
 * virStorageFileReadHeader: read the beginning bytes of a file into a buffer
 *
 * @src: file structure pointing to the file
 * @max_len: maximum number of bytes read from the storage file
 * @buf: buffer to read the data into. buffer shall be freed by caller)
 *
 * Returns the count of bytes read on success and -1 on failure, -2 if the
2908 2909
 * function isn't supported by the backend.
 * Libvirt error is reported on failure.
2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926
 */
ssize_t
virStorageFileReadHeader(virStorageSourcePtr src,
                         ssize_t max_len,
                         char **buf)
{
    ssize_t ret;

    if (!virStorageFileIsInitialized(src)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("storage file backend not initialized"));
        return -1;
    }

    if (!src->drv->backend->storageFileReadHeader) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage file header reading is not supported for "
2927
                         "storage type %s (protocol: %s)"),
2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938
                       virStorageTypeToString(src->type),
                       virStorageNetProtocolTypeToString(src->protocol));
        return -2;
    }

    ret = src->drv->backend->storageFileReadHeader(src, max_len, buf);

    VIR_DEBUG("read of storage header %p: ret=%zd", src, ret);

    return ret;
}
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968


/*
 * virStorageFileGetUniqueIdentifier: Get a unique string describing the volume
 *
 * @src: file structure pointing to the file
 *
 * Returns a string uniquely describing a single volume (canonical path).
 * The string shall not be freed and is valid until the storage file is
 * deinitialized. Returns NULL on error and sets a libvirt error code */
const char *
virStorageFileGetUniqueIdentifier(virStorageSourcePtr src)
{
    if (!virStorageFileIsInitialized(src)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("storage file backend not initialized"));
        return NULL;
    }

    if (!src->drv->backend->storageFileGetUniqueIdentifier) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unique storage file identifier not implemented for "
                          "storage type %s (protocol: %s)'"),
                       virStorageTypeToString(src->type),
                       virStorageNetProtocolTypeToString(src->protocol));
        return NULL;
    }

    return src->drv->backend->storageFileGetUniqueIdentifier(src);
}
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992


/**
 * virStorageFileAccess: Check accessibility of a storage file
 *
 * @src: storage file to check access permissions
 * @mode: accessibility check options (see man 2 access)
 *
 * Returns 0 on success, -1 on error and sets errno. No libvirt
 * error is reported. Returns -2 if the operation isn't supported
 * by libvirt storage backend.
 */
int
virStorageFileAccess(virStorageSourcePtr src,
                     int mode)
{
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileAccess) {
        errno = ENOSYS;
        return -2;
    }

    return src->drv->backend->storageFileAccess(src, mode);
}
2993 2994


2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
/**
 * virStorageFileChown: Change owner of a storage file
 *
 * @src: storage file to change owner of
 * @uid: new owner id
 * @gid: new group id
 *
 * Returns 0 on success, -1 on error and sets errno. No libvirt
 * error is reported. Returns -2 if the operation isn't supported
 * by libvirt storage backend.
 */
int
virStorageFileChown(virStorageSourcePtr src,
                    uid_t uid,
                    gid_t gid)
{
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileChown) {
        errno = ENOSYS;
        return -2;
    }

3017 3018
    VIR_DEBUG("chown of storage file %p to %u:%u",
              src, (unsigned int)uid, (unsigned int)gid);
3019 3020 3021 3022 3023

    return src->drv->backend->storageFileChown(src, uid, gid);
}


3024 3025 3026
/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
3027
                                 virStorageSourcePtr parent,
3028 3029
                                 uid_t uid, gid_t gid,
                                 bool allow_probe,
3030
                                 bool report_broken,
3031 3032 3033
                                 virHashTablePtr cycle)
{
    int ret = -1;
3034
    const char *uniqueName;
3035 3036
    char *buf = NULL;
    ssize_t headerLen;
3037 3038 3039
    virStorageSourcePtr backingStore = NULL;
    int backingFormat;

3040
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u probe=%d",
3041
              src->path, src->format,
3042
              (unsigned int)uid, (unsigned int)gid, allow_probe);
3043

3044 3045 3046 3047 3048
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
3049
        return -1;
3050

3051
    if (virStorageFileAccess(src, F_OK) < 0) {
3052 3053 3054
        if (src == parent) {
            virReportSystemError(errno,
                                 _("Cannot access storage file '%s' "
3055 3056 3057
                                   "(as uid:%u, gid:%u)"),
                                 src->path, (unsigned int)uid,
                                 (unsigned int)gid);
3058 3059 3060
        } else {
            virReportSystemError(errno,
                                 _("Cannot access backing file '%s' "
3061 3062 3063
                                   "of storage file '%s' (as uid:%u, gid:%u)"),
                                 src->path, parent->path,
                                 (unsigned int)uid, (unsigned int)gid);
3064 3065
        }

3066 3067 3068
        goto cleanup;
    }

3069 3070 3071 3072 3073 3074 3075 3076
    if (!(uniqueName = virStorageFileGetUniqueIdentifier(src)))
        goto cleanup;

    if (virHashLookup(cycle, uniqueName)) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("backing store for %s (%s) is self-referential"),
                       src->path, uniqueName);
        goto cleanup;
3077 3078
    }

3079 3080
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
3081

3082 3083 3084
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
3085

3086 3087
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
3088
        goto cleanup;
3089 3090

    /* check whether we need to go deeper */
3091 3092 3093 3094
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
3095

3096
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
3097
        goto cleanup;
3098 3099 3100 3101 3102 3103 3104 3105

    if (backingFormat == VIR_STORAGE_FILE_AUTO && !allow_probe)
        backingStore->format = VIR_STORAGE_FILE_RAW;
    else if (backingFormat == VIR_STORAGE_FILE_AUTO_SAFE)
        backingStore->format = VIR_STORAGE_FILE_AUTO;
    else
        backingStore->format = backingFormat;

3106
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
3107 3108 3109 3110 3111 3112
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

    src->backingStore = backingStore;
    backingStore = NULL;
    ret = 0;

 cleanup:
3124
    VIR_FREE(buf);
3125
    virStorageFileDeinit(src);
3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145
    virStorageSourceFree(backingStore);
    return ret;
}


/**
 * virStorageFileGetMetadata:
 *
 * Extract metadata about the storage volume with the specified
 * image format. If image format is VIR_STORAGE_FILE_AUTO, it
 * will probe to automatically identify the format.  Recurses through
 * the entire chain.
 *
 * Open files using UID and GID (or pass -1 for the current user/group).
 * Treat any backing files without explicit type as raw, unless ALLOW_PROBE.
 *
 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a
 * format, since a malicious guest can turn a raw file into any
 * other non-raw format at will.
 *
3146 3147 3148
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
3149 3150 3151 3152 3153
 * Caller MUST free result after use via virStorageSourceFree.
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
3154 3155
                          bool allow_probe,
                          bool report_broken)
3156
{
3157 3158
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u probe=%d, report_broken=%d",
              src->path, src->format, (unsigned int)uid, (unsigned int)gid,
3159
              allow_probe, report_broken);
3160 3161 3162 3163 3164 3165 3166 3167

    virHashTablePtr cycle = NULL;
    int ret = -1;

    if (!(cycle = virHashCreate(5, NULL)))
        return -1;

    if (src->format <= VIR_STORAGE_FILE_NONE)
3168 3169
        src->format = allow_probe ?
            VIR_STORAGE_FILE_AUTO : VIR_STORAGE_FILE_RAW;
3170

3171
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
3172
                                           allow_probe, report_broken, cycle);
3173 3174 3175 3176

    virHashFree(cycle);
    return ret;
}
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211


static int
virStorageAddISCSIPoolSourceHost(virDomainDiskDefPtr def,
                                 virStoragePoolDefPtr pooldef)
{
    int ret = -1;
    char **tokens = NULL;

    /* Only support one host */
    if (pooldef->source.nhost != 1) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Expected exactly 1 host for the storage pool"));
        goto cleanup;
    }

    /* iscsi pool only supports one host */
    def->src->nhosts = 1;

    if (VIR_ALLOC_N(def->src->hosts, def->src->nhosts) < 0)
        goto cleanup;

    if (VIR_STRDUP(def->src->hosts[0].name, pooldef->source.hosts[0].name) < 0)
        goto cleanup;

    if (virAsprintf(&def->src->hosts[0].port, "%d",
                    pooldef->source.hosts[0].port ?
                    pooldef->source.hosts[0].port :
                    3260) < 0)
        goto cleanup;

    /* iscsi volume has name like "unit:0:0:1" */
    if (!(tokens = virStringSplit(def->src->srcpool->volume, ":", 0)))
        goto cleanup;

3212
    if (virStringListLength((const char * const *)tokens) != 4) {
3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected iscsi volume name '%s'"),
                       def->src->srcpool->volume);
        goto cleanup;
    }

    /* iscsi pool has only one source device path */
    if (virAsprintf(&def->src->path, "%s/%s",
                    pooldef->source.devices[0].path,
                    tokens[3]) < 0)
        goto cleanup;

    /* Storage pool have not supported these 2 attributes yet,
     * use the defaults.
     */
    def->src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
    def->src->hosts[0].socket = NULL;

    def->src->protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;

    ret = 0;

 cleanup:
    virStringFreeList(tokens);
    return ret;
}


static int
virStorageTranslateDiskSourcePoolAuth(virDomainDiskDefPtr def,
                                      virStoragePoolSourcePtr source)
{
    int ret = -1;

    /* Only necessary when authentication set */
    if (!source->auth) {
        ret = 0;
        goto cleanup;
    }
    def->src->auth = virStorageAuthDefCopy(source->auth);
    if (!def->src->auth)
        goto cleanup;
3255 3256
    /* A <disk> doesn't use <auth type='%s', so clear that out for the disk */
    def->src->auth->authType = VIR_STORAGE_AUTH_TYPE_NONE;
3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384
    ret = 0;

 cleanup:
    return ret;
}


int
virStorageTranslateDiskSourcePool(virConnectPtr conn,
                                  virDomainDiskDefPtr def)
{
    virStoragePoolDefPtr pooldef = NULL;
    virStoragePoolPtr pool = NULL;
    virStorageVolPtr vol = NULL;
    char *poolxml = NULL;
    virStorageVolInfo info;
    int ret = -1;

    if (def->src->type != VIR_STORAGE_TYPE_VOLUME)
        return 0;

    if (!def->src->srcpool)
        return 0;

    if (!(pool = virStoragePoolLookupByName(conn, def->src->srcpool->pool)))
        return -1;

    if (virStoragePoolIsActive(pool) != 1) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("storage pool '%s' containing volume '%s' "
                         "is not active"),
                       def->src->srcpool->pool, def->src->srcpool->volume);
        goto cleanup;
    }

    if (!(vol = virStorageVolLookupByName(pool, def->src->srcpool->volume)))
        goto cleanup;

    if (virStorageVolGetInfo(vol, &info) < 0)
        goto cleanup;

    if (!(poolxml = virStoragePoolGetXMLDesc(pool, 0)))
        goto cleanup;

    if (!(pooldef = virStoragePoolDefParseString(poolxml)))
        goto cleanup;

    def->src->srcpool->pooltype = pooldef->type;
    def->src->srcpool->voltype = info.type;

    if (def->src->srcpool->mode && pooldef->type != VIR_STORAGE_POOL_ISCSI) {
        virReportError(VIR_ERR_XML_ERROR, "%s",
                       _("disk source mode is only valid when "
                         "storage pool is of iscsi type"));
        goto cleanup;
    }

    VIR_FREE(def->src->path);
    virStorageNetHostDefFree(def->src->nhosts, def->src->hosts);
    virStorageAuthDefFree(def->src->auth);

    switch ((virStoragePoolType) pooldef->type) {
    case VIR_STORAGE_POOL_DIR:
    case VIR_STORAGE_POOL_FS:
    case VIR_STORAGE_POOL_NETFS:
    case VIR_STORAGE_POOL_LOGICAL:
    case VIR_STORAGE_POOL_DISK:
    case VIR_STORAGE_POOL_SCSI:
    case VIR_STORAGE_POOL_ZFS:
        if (!(def->src->path = virStorageVolGetPath(vol)))
            goto cleanup;

        if (def->startupPolicy && info.type != VIR_STORAGE_VOL_FILE) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("'startupPolicy' is only valid for "
                             "'file' type volume"));
            goto cleanup;
        }


        switch (info.type) {
        case VIR_STORAGE_VOL_FILE:
            def->src->srcpool->actualtype = VIR_STORAGE_TYPE_FILE;
            break;

        case VIR_STORAGE_VOL_DIR:
            def->src->srcpool->actualtype = VIR_STORAGE_TYPE_DIR;
            break;

        case VIR_STORAGE_VOL_BLOCK:
            def->src->srcpool->actualtype = VIR_STORAGE_TYPE_BLOCK;
            break;

        case VIR_STORAGE_VOL_NETWORK:
        case VIR_STORAGE_VOL_NETDIR:
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unexpected storage volume type '%s' "
                             "for storage pool type '%s'"),
                           virStorageVolTypeToString(info.type),
                           virStoragePoolTypeToString(pooldef->type));
            goto cleanup;
        }

        break;

    case VIR_STORAGE_POOL_ISCSI:
        if (def->startupPolicy) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("'startupPolicy' is only valid for "
                             "'file' type volume"));
            goto cleanup;
        }

       switch (def->src->srcpool->mode) {
       case VIR_STORAGE_SOURCE_POOL_MODE_DEFAULT:
       case VIR_STORAGE_SOURCE_POOL_MODE_LAST:
           def->src->srcpool->mode = VIR_STORAGE_SOURCE_POOL_MODE_HOST;
           /* fallthrough */
       case VIR_STORAGE_SOURCE_POOL_MODE_HOST:
           def->src->srcpool->actualtype = VIR_STORAGE_TYPE_BLOCK;
           if (!(def->src->path = virStorageVolGetPath(vol)))
               goto cleanup;
           break;

       case VIR_STORAGE_SOURCE_POOL_MODE_DIRECT:
           def->src->srcpool->actualtype = VIR_STORAGE_TYPE_NETWORK;
           def->src->protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;

3385 3386
           if (virStorageTranslateDiskSourcePoolAuth(def,
                                                     &pooldef->source) < 0)
3387 3388
               goto cleanup;

3389 3390 3391 3392 3393 3394 3395 3396 3397 3398
           /* Source pool may not fill in the secrettype field,
            * so we need to do so here
            */
           if (def->src->auth && !def->src->auth->secrettype) {
               const char *secrettype =
                   virSecretUsageTypeToString(VIR_SECRET_USAGE_TYPE_ISCSI);
               if (VIR_STRDUP(def->src->auth->secrettype, secrettype) < 0)
                   goto cleanup;
           }

3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
           if (virStorageAddISCSIPoolSourceHost(def, pooldef) < 0)
               goto cleanup;
           break;
       }
       break;

    case VIR_STORAGE_POOL_MPATH:
    case VIR_STORAGE_POOL_RBD:
    case VIR_STORAGE_POOL_SHEEPDOG:
    case VIR_STORAGE_POOL_GLUSTER:
    case VIR_STORAGE_POOL_LAST:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("using '%s' pools for backing 'volume' disks "
                         "isn't yet supported"),
                       virStoragePoolTypeToString(pooldef->type));
        goto cleanup;
    }

    ret = 0;
 cleanup:
3419
    virObjectUnref(pool);
3420
    virObjectUnref(vol);
3421 3422 3423 3424
    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445


/*
 * virStoragePoolObjFindPoolByUUID
 * @uuid: The uuid to lookup
 *
 * Using the passed @uuid, search the driver pools for a matching uuid.
 * If found, then lock the pool
 *
 * Returns NULL if pool is not found or a locked pool object pointer
 */
virStoragePoolObjPtr
virStoragePoolObjFindPoolByUUID(const unsigned char *uuid)
{
    virStoragePoolObjPtr pool;

    storageDriverLock();
    pool = virStoragePoolObjFindByUUID(&driver->pools, uuid);
    storageDriverUnlock();
    return pool;
}