storage_driver.c 93.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
    char *stateFile = NULL;
155 156 157
    virConnectPtr conn = NULL;

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

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

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

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

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

E
Eric Blake 已提交
675 676
    virCheckFlags(0, NULL);

677
    storageDriverLock();
678
    if (!(def = virStoragePoolDefParseString(xml)))
679
        goto cleanup;
680

681 682 683
    if (virStoragePoolCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

684
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 1) < 0)
685
        goto cleanup;
686

687
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
688 689
        goto cleanup;

690 691
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
692

693
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
694 695
        goto cleanup;
    def = NULL;
696

697
    if (backend->startPool &&
698 699 700
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
701
        goto cleanup;
702
    }
703

704 705 706 707 708
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(conn, pool) < 0) {
709 710
        if (stateFile)
            unlink(stateFile);
711 712
        if (backend->stopPool)
            backend->stopPool(conn, pool);
713 714
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
715
        goto cleanup;
716
    }
717
    VIR_INFO("Creating storage pool '%s'", pool->def->name);
718 719
    pool->active = 1;

720 721
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
722

723
 cleanup:
724
    VIR_FREE(stateFile);
725
    virStoragePoolDefFree(def);
726
    if (pool)
727
        virStoragePoolObjUnlock(pool);
728
    storageDriverUnlock();
729 730 731 732
    return ret;
}

static virStoragePoolPtr
733 734 735
storagePoolDefineXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
736
{
737
    virStoragePoolDefPtr def;
738
    virStoragePoolObjPtr pool = NULL;
739
    virStoragePoolPtr ret = NULL;
740

E
Eric Blake 已提交
741 742
    virCheckFlags(0, NULL);

743
    storageDriverLock();
744
    if (!(def = virStoragePoolDefParseString(xml)))
745
        goto cleanup;
746

747 748 749
    if (virStoragePoolDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

750 751 752
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 0) < 0)
        goto cleanup;

753
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
754 755
        goto cleanup;

756
    if (virStorageBackendForType(def->type) == NULL)
757
        goto cleanup;
758

759
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
760
        goto cleanup;
761

762
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
763
        virStoragePoolObjRemove(&driver->pools, pool);
764
        def = NULL;
765
        goto cleanup;
766
    }
767
    def = NULL;
768

769
    VIR_INFO("Defining storage pool '%s'", pool->def->name);
770 771
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
772

773
 cleanup:
774
    virStoragePoolDefFree(def);
775 776
    if (pool)
        virStoragePoolObjUnlock(pool);
777
    storageDriverUnlock();
778 779 780 781
    return ret;
}

static int
782 783
storagePoolUndefine(virStoragePoolPtr obj)
{
784 785
    virStoragePoolObjPtr pool;
    int ret = -1;
786

787
    storageDriverLock();
788 789 790
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
791
        virReportError(VIR_ERR_NO_STORAGE_POOL,
792 793
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
794
        goto cleanup;
795 796
    }

797 798 799
    if (virStoragePoolUndefineEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

800
    if (virStoragePoolObjIsActive(pool)) {
801
        virReportError(VIR_ERR_OPERATION_INVALID,
802 803
                       _("storage pool '%s' is still active"),
                       pool->def->name);
804
        goto cleanup;
805 806
    }

807
    if (pool->asyncjobs > 0) {
808 809 810
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
811 812 813
        goto cleanup;
    }

814
    if (virStoragePoolObjDeleteDef(pool) < 0)
815
        goto cleanup;
816

817 818 819
    if (unlink(pool->autostartLink) < 0 &&
        errno != ENOENT &&
        errno != ENOTDIR) {
820
        char ebuf[1024];
821
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
822
                  pool->autostartLink, virStrerror(errno, ebuf, sizeof(ebuf)));
823
    }
824

825 826
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
827

828
    VIR_INFO("Undefining storage pool '%s'", pool->def->name);
829
    virStoragePoolObjRemove(&driver->pools, pool);
830
    pool = NULL;
831
    ret = 0;
832

833
 cleanup:
834 835
    if (pool)
        virStoragePoolObjUnlock(pool);
836
    storageDriverUnlock();
837
    return ret;
838 839 840
}

static int
841 842
storagePoolCreate(virStoragePoolPtr obj,
                  unsigned int flags)
E
Eric Blake 已提交
843
{
844
    virStoragePoolObjPtr pool;
845
    virStorageBackendPtr backend;
846
    int ret = -1;
847
    char *stateFile = NULL;
848

E
Eric Blake 已提交
849 850
    virCheckFlags(0, -1);

851 852
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
853

854 855 856
    if (virStoragePoolCreateEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

857 858
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
859 860

    if (virStoragePoolObjIsActive(pool)) {
861
        virReportError(VIR_ERR_OPERATION_INVALID,
862 863
                       _("storage pool '%s' is already active"),
                       pool->def->name);
864
        goto cleanup;
865
    }
866 867

    VIR_INFO("Starting up storage pool '%s'", pool->def->name);
868 869
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
870 871
        goto cleanup;

872 873 874 875 876
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(obj->conn, pool) < 0) {
877 878
        if (stateFile)
            unlink(stateFile);
879 880
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
881
        goto cleanup;
882 883 884
    }

    pool->active = 1;
885
    ret = 0;
886

887
 cleanup:
888
    VIR_FREE(stateFile);
889
    virStoragePoolObjUnlock(pool);
890
    return ret;
891 892 893 894
}

static int
storagePoolBuild(virStoragePoolPtr obj,
895 896
                 unsigned int flags)
{
897
    virStoragePoolObjPtr pool;
898
    virStorageBackendPtr backend;
899
    int ret = -1;
900

901 902
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
903

904 905 906
    if (virStoragePoolBuildEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

907 908
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
909 910

    if (virStoragePoolObjIsActive(pool)) {
911
        virReportError(VIR_ERR_OPERATION_INVALID,
912 913
                       _("storage pool '%s' is already active"),
                       pool->def->name);
914
        goto cleanup;
915 916 917 918
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
919 920
        goto cleanup;
    ret = 0;
921

922
 cleanup:
923
    virStoragePoolObjUnlock(pool);
924
    return ret;
925 926 927 928
}


static int
929 930
storagePoolDestroy(virStoragePoolPtr obj)
{
931
    virStoragePoolObjPtr pool;
932
    virStorageBackendPtr backend;
933
    char *stateFile = NULL;
934
    int ret = -1;
935

936
    storageDriverLock();
937 938 939
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
940
        virReportError(VIR_ERR_NO_STORAGE_POOL,
941 942
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
943
        goto cleanup;
944 945
    }

946 947 948
    if (virStoragePoolDestroyEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

954
    if (!virStoragePoolObjIsActive(pool)) {
955
        virReportError(VIR_ERR_OPERATION_INVALID,
956
                       _("storage pool '%s' is not active"), pool->def->name);
957
        goto cleanup;
958 959
    }

960
    if (pool->asyncjobs > 0) {
961 962 963
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
964 965 966
        goto cleanup;
    }

967 968 969 970 971 972 973 974
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

975 976
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
977
        goto cleanup;
978 979 980 981 982

    virStoragePoolObjClearVols(pool);

    pool->active = 0;

983
    if (pool->configFile == NULL) {
984
        virStoragePoolObjRemove(&driver->pools, pool);
985
        pool = NULL;
986 987 988 989
    } else if (pool->newDef) {
        virStoragePoolDefFree(pool->def);
        pool->def = pool->newDef;
        pool->newDef = NULL;
990
    }
991

992
    ret = 0;
993

994
 cleanup:
995 996
    if (pool)
        virStoragePoolObjUnlock(pool);
997
    storageDriverUnlock();
998
    return ret;
999 1000 1001 1002
}

static int
storagePoolDelete(virStoragePoolPtr obj,
1003 1004
                  unsigned int flags)
{
1005
    virStoragePoolObjPtr pool;
1006
    virStorageBackendPtr backend;
1007
    char *stateFile = NULL;
1008
    int ret = -1;
1009

1010 1011
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1012

1013 1014 1015
    if (virStoragePoolDeleteEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

1021
    if (virStoragePoolObjIsActive(pool)) {
1022
        virReportError(VIR_ERR_OPERATION_INVALID,
1023 1024
                       _("storage pool '%s' is still active"),
                       pool->def->name);
1025
        goto cleanup;
1026 1027
    }

1028
    if (pool->asyncjobs > 0) {
1029 1030
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
1031 1032 1033 1034
                              pool->def->name);
        goto cleanup;
    }

1035 1036 1037 1038 1039 1040 1041 1042
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

1043
    if (!backend->deletePool) {
1044 1045
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("pool does not support pool deletion"));
1046
        goto cleanup;
1047 1048
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
1049
        goto cleanup;
1050

1051
    ret = 0;
1052

1053
 cleanup:
1054
    virStoragePoolObjUnlock(pool);
1055
    return ret;
1056 1057 1058 1059 1060
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
E
Eric Blake 已提交
1061 1062
                   unsigned int flags)
{
1063
    virStoragePoolObjPtr pool;
1064
    virStorageBackendPtr backend;
1065
    int ret = -1;
1066

E
Eric Blake 已提交
1067 1068
    virCheckFlags(0, -1);

1069
    storageDriverLock();
1070 1071 1072
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1073
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1074 1075
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1076
        goto cleanup;
1077 1078
    }

1079 1080 1081
    if (virStoragePoolRefreshEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1082 1083
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
1084 1085

    if (!virStoragePoolObjIsActive(pool)) {
1086
        virReportError(VIR_ERR_OPERATION_INVALID,
1087
                       _("storage pool '%s' is not active"), pool->def->name);
1088
        goto cleanup;
1089 1090
    }

1091
    if (pool->asyncjobs > 0) {
1092 1093 1094
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
1095 1096 1097
        goto cleanup;
    }

1098
    virStoragePoolObjClearVols(pool);
1099
    if (backend->refreshPool(obj->conn, pool) < 0) {
1100 1101 1102 1103 1104
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

1105
        if (pool->configFile == NULL) {
1106
            virStoragePoolObjRemove(&driver->pools, pool);
1107 1108
            pool = NULL;
        }
1109
        goto cleanup;
1110
    }
1111
    ret = 0;
1112

1113
 cleanup:
1114 1115
    if (pool)
        virStoragePoolObjUnlock(pool);
1116
    storageDriverUnlock();
1117 1118 1119 1120 1121 1122
    return ret;
}


static int
storagePoolGetInfo(virStoragePoolPtr obj,
1123 1124
                   virStoragePoolInfoPtr info)
{
1125 1126
    virStoragePoolObjPtr pool;
    int ret = -1;
1127

1128 1129
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1130

1131 1132 1133
    if (virStoragePoolGetInfoEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1134
    if (virStorageBackendForType(pool->def->type) == NULL)
1135
        goto cleanup;
1136 1137 1138 1139 1140 1141 1142 1143 1144

    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;
1145
    ret = 0;
1146

1147
 cleanup:
1148
    virStoragePoolObjUnlock(pool);
1149
    return ret;
1150 1151 1152
}

static char *
1153
storagePoolGetXMLDesc(virStoragePoolPtr obj,
E
Eric Blake 已提交
1154 1155
                      unsigned int flags)
{
1156
    virStoragePoolObjPtr pool;
1157
    virStoragePoolDefPtr def;
1158
    char *ret = NULL;
1159

1160
    virCheckFlags(VIR_STORAGE_XML_INACTIVE, NULL);
E
Eric Blake 已提交
1161

1162 1163
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1164

1165 1166 1167
    if (virStoragePoolGetXMLDescEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1168 1169 1170 1171 1172 1173
    if ((flags & VIR_STORAGE_XML_INACTIVE) && pool->newDef)
        def = pool->newDef;
    else
        def = pool->def;

    ret = virStoragePoolDefFormat(def);
1174

1175
 cleanup:
1176
    virStoragePoolObjUnlock(pool);
1177
    return ret;
1178 1179 1180 1181
}

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
1182 1183
                        int *autostart)
{
1184 1185
    virStoragePoolObjPtr pool;
    int ret = -1;
1186

1187 1188
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1189

1190 1191 1192
    if (virStoragePoolGetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1193 1194 1195 1196 1197
    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
1198
    ret = 0;
1199

1200
 cleanup:
1201
    virStoragePoolObjUnlock(pool);
1202
    return ret;
1203 1204 1205 1206
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
1207 1208
                        int autostart)
{
1209 1210
    virStoragePoolObjPtr pool;
    int ret = -1;
1211

1212
    storageDriverLock();
1213
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1214

1215
    if (!pool) {
1216 1217
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1218
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1219 1220
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1221
        goto cleanup;
1222 1223
    }

1224 1225 1226
    if (virStoragePoolSetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1227
    if (!pool->configFile) {
1228 1229
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("pool has no config file"));
1230
        goto cleanup;
1231 1232 1233 1234
    }

    autostart = (autostart != 0);

1235 1236
    if (pool->autostart != autostart) {
        if (autostart) {
1237 1238
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
1239 1240
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1241 1242
                goto cleanup;
            }
1243

1244
            if (symlink(pool->configFile, pool->autostartLink) < 0) {
1245
                virReportSystemError(errno,
1246 1247
                                     _("Failed to create symlink '%s' to '%s'"),
                                     pool->autostartLink, pool->configFile);
1248 1249 1250 1251 1252
                goto cleanup;
            }
        } else {
            if (unlink(pool->autostartLink) < 0 &&
                errno != ENOENT && errno != ENOTDIR) {
1253
                virReportSystemError(errno,
1254 1255
                                     _("Failed to delete symlink '%s'"),
                                     pool->autostartLink);
1256 1257
                goto cleanup;
            }
1258
        }
1259
        pool->autostart = autostart;
1260
    }
1261
    ret = 0;
1262

1263
 cleanup:
1264 1265
    if (pool)
        virStoragePoolObjUnlock(pool);
1266
    storageDriverUnlock();
1267
    return ret;
1268 1269 1270 1271
}


static int
1272 1273
storagePoolNumOfVolumes(virStoragePoolPtr obj)
{
1274
    virStoragePoolObjPtr pool;
1275 1276
    int ret = -1;
    size_t i;
1277

1278 1279
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1280

1281 1282 1283
    if (virStoragePoolNumOfVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1284
    if (!virStoragePoolObjIsActive(pool)) {
1285
        virReportError(VIR_ERR_OPERATION_INVALID,
1286
                       _("storage pool '%s' is not active"), pool->def->name);
1287
        goto cleanup;
1288
    }
1289 1290 1291 1292 1293 1294
    ret = 0;
    for (i = 0; i < pool->volumes.count; i++) {
        if (virStoragePoolNumOfVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            ret++;
    }
1295

1296
 cleanup:
1297
    virStoragePoolObjUnlock(pool);
1298
    return ret;
1299 1300 1301 1302 1303
}

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
1304 1305
                       int maxnames)
{
1306
    virStoragePoolObjPtr pool;
1307 1308
    size_t i;
    int n = 0;
1309

1310 1311
    memset(names, 0, maxnames * sizeof(*names));

1312 1313
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1314

1315 1316 1317
    if (virStoragePoolListVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1318
    if (!virStoragePoolObjIsActive(pool)) {
1319
        virReportError(VIR_ERR_OPERATION_INVALID,
1320
                       _("storage pool '%s' is not active"), pool->def->name);
1321
        goto cleanup;
1322 1323
    }

1324
    for (i = 0; i < pool->volumes.count && n < maxnames; i++) {
1325 1326 1327
        if (!virStoragePoolListVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            continue;
1328
        if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0)
1329 1330 1331
            goto cleanup;
    }

1332
    virStoragePoolObjUnlock(pool);
1333
    return n;
1334 1335

 cleanup:
1336
    virStoragePoolObjUnlock(pool);
1337
    for (n = 0; n < maxnames; n++)
1338
        VIR_FREE(names[n]);
1339

1340
    memset(names, 0, maxnames * sizeof(*names));
1341 1342 1343
    return -1;
}

1344 1345 1346
static int
storagePoolListAllVolumes(virStoragePoolPtr pool,
                          virStorageVolPtr **vols,
1347 1348
                          unsigned int flags)
{
1349
    virStoragePoolObjPtr obj;
1350
    size_t i;
1351 1352 1353 1354 1355 1356 1357
    virStorageVolPtr *tmp_vols = NULL;
    virStorageVolPtr vol = NULL;
    int nvols = 0;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

1364
    if (!virStoragePoolObjIsActive(obj)) {
1365 1366
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("storage pool '%s' is not active"), obj->def->name);
1367 1368 1369 1370 1371 1372 1373 1374 1375
        goto cleanup;
    }

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

1376
    if (VIR_ALLOC_N(tmp_vols, obj->volumes.count + 1) < 0)
1377
        goto cleanup;
1378

1379
    for (i = 0; i < obj->volumes.count; i++) {
1380 1381 1382
        if (!virStoragePoolListAllVolumesCheckACL(pool->conn, obj->def,
                                                  obj->volumes.objs[i]))
            continue;
1383 1384
        if (!(vol = virGetStorageVol(pool->conn, obj->def->name,
                                     obj->volumes.objs[i]->name,
1385 1386
                                     obj->volumes.objs[i]->key,
                                     NULL, NULL)))
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
            goto cleanup;
        tmp_vols[nvols++] = vol;
    }

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

 cleanup:
    if (tmp_vols) {
1397 1398
        for (i = 0; i < nvols; i++)
            virObjectUnref(tmp_vols[i]);
1399
        VIR_FREE(tmp_vols);
1400 1401
    }

1402
    virStoragePoolObjUnlock(obj);
1403 1404 1405

    return ret;
}
1406 1407

static virStorageVolPtr
1408
storageVolLookupByName(virStoragePoolPtr obj,
1409 1410
                       const char *name)
{
1411
    virStoragePoolObjPtr pool;
1412
    virStorageVolDefPtr vol;
1413
    virStorageVolPtr ret = NULL;
1414

1415 1416
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1417 1418

    if (!virStoragePoolObjIsActive(pool)) {
1419
        virReportError(VIR_ERR_OPERATION_INVALID,
1420
                       _("storage pool '%s' is not active"), pool->def->name);
1421
        goto cleanup;
1422 1423 1424 1425 1426
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1427 1428 1429
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       name);
1430
        goto cleanup;
1431 1432
    }

1433 1434 1435
    if (virStorageVolLookupByNameEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1436 1437
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key,
                           NULL, NULL);
1438

1439
 cleanup:
1440
    virStoragePoolObjUnlock(pool);
1441
    return ret;
1442 1443 1444 1445
}


static virStorageVolPtr
1446
storageVolLookupByKey(virConnectPtr conn,
1447 1448
                      const char *key)
{
1449
    size_t i;
1450
    virStorageVolPtr ret = NULL;
1451

1452
    storageDriverLock();
1453
    for (i = 0; i < driver->pools.count && !ret; i++) {
1454
        virStoragePoolObjLock(driver->pools.objs[i]);
1455 1456 1457
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1458

1459
            if (vol) {
1460 1461
                virStoragePoolDefPtr def = driver->pools.objs[i]->def;
                if (virStorageVolLookupByKeyEnsureACL(conn, def, vol) < 0) {
1462
                    virStoragePoolObjUnlock(driver->pools.objs[i]);
1463
                    goto cleanup;
1464
                }
1465

1466
                ret = virGetStorageVol(conn,
1467
                                       def->name,
1468
                                       vol->name,
1469 1470
                                       vol->key,
                                       NULL, NULL);
1471
            }
1472
        }
1473
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1474 1475
    }

1476
    if (!ret)
1477
        virReportError(VIR_ERR_NO_STORAGE_VOL,
1478
                       _("no storage vol with matching key %s"), key);
1479

1480
 cleanup:
1481
    storageDriverUnlock();
1482
    return ret;
1483 1484 1485
}

static virStorageVolPtr
1486
storageVolLookupByPath(virConnectPtr conn,
1487 1488
                       const char *path)
{
1489
    size_t i;
1490
    virStorageVolPtr ret = NULL;
1491 1492 1493 1494 1495
    char *cleanpath;

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

1497
    storageDriverLock();
1498
    for (i = 0; i < driver->pools.count && !ret; i++) {
1499 1500 1501 1502 1503
        virStoragePoolObjPtr pool = driver->pools.objs[i];
        virStorageVolDefPtr vol;
        char *stable_path = NULL;

        virStoragePoolObjLock(pool);
1504

1505 1506 1507 1508
        if (!virStoragePoolObjIsActive(pool)) {
           virStoragePoolObjUnlock(pool);
           continue;
        }
1509

1510
        switch ((virStoragePoolType) pool->def->type) {
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
            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 已提交
1536
            case VIR_STORAGE_POOL_ZFS:
1537 1538 1539
            case VIR_STORAGE_POOL_LAST:
                if (VIR_STRDUP(stable_path, path) < 0) {
                     virStoragePoolObjUnlock(pool);
1540
                    goto cleanup;
1541
                }
1542 1543
                break;
        }
1544

1545 1546 1547 1548 1549 1550 1551
        vol = virStorageVolDefFindByPath(pool, stable_path);
        VIR_FREE(stable_path);

        if (vol) {
            if (virStorageVolLookupByPathEnsureACL(conn, pool->def, vol) < 0) {
                virStoragePoolObjUnlock(pool);
                goto cleanup;
1552
            }
1553 1554 1555 1556

            ret = virGetStorageVol(conn, pool->def->name,
                                   vol->name, vol->key,
                                   NULL, NULL);
1557
        }
1558 1559

        virStoragePoolObjUnlock(pool);
1560 1561
    }

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
    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);
        }
    }
1572

1573
 cleanup:
1574
    VIR_FREE(cleanpath);
1575
    storageDriverUnlock();
1576
    return ret;
1577 1578
}

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
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;
}

1621

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
static int
storageVolDeleteInternal(virStorageVolPtr obj,
                         virStorageBackendPtr backend,
                         virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol,
                         unsigned int flags,
                         bool updateMeta)
{
    size_t i;
    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
1644 1645
     * in this module since the allocation/available weren't adjusted yet.
     * Ignore the disk backend since it updates the pool values.
1646 1647
     */
    if (updateMeta) {
1648 1649 1650 1651
        if (pool->def->type != VIR_STORAGE_POOL_DISK) {
            pool->def->allocation -= vol->target.allocation;
            pool->def->available += vol->target.allocation;
        }
1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    }

    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;
        }
    }
    ret = 0;

 cleanup:
    return ret;
}


1671 1672 1673 1674
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1675 1676
{
    virStorageVolDefPtr vol = NULL;
1677 1678

    *pool = NULL;
1679

1680
    storageDriverLock();
1681
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1682
    storageDriverUnlock();
1683

1684
    if (!*pool) {
1685 1686 1687
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1688
        return NULL;
1689 1690
    }

1691
    if (!virStoragePoolObjIsActive(*pool)) {
1692
        virReportError(VIR_ERR_OPERATION_INVALID,
1693 1694 1695
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1696 1697
    }

1698
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1699 1700 1701
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1702
        goto error;
1703 1704
    }

1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
    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;

1732 1733 1734
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1735 1736 1737 1738 1739 1740 1741
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1742 1743 1744 1745 1746 1747 1748
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1749
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1750 1751 1752 1753
        goto cleanup;

    ret = 0;

1754
 cleanup:
1755
    virStoragePoolObjUnlock(pool);
1756 1757 1758
    return ret;
}

1759

1760
static virStorageVolPtr
1761 1762 1763
storageVolCreateXML(virStoragePoolPtr obj,
                    const char *xmldesc,
                    unsigned int flags)
E
Eric Blake 已提交
1764
{
1765
    virStoragePoolObjPtr pool;
1766
    virStorageBackendPtr backend;
1767 1768
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1769
    virStorageVolDefPtr buildvoldef = NULL;
1770

1771
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1772

1773 1774
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1775 1776

    if (!virStoragePoolObjIsActive(pool)) {
1777
        virReportError(VIR_ERR_OPERATION_INVALID,
1778
                       _("storage pool '%s' is not active"), pool->def->name);
1779
        goto cleanup;
1780 1781 1782
    }

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

1785 1786
    voldef = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_OPT_CAPACITY);
1787
    if (voldef == NULL)
1788
        goto cleanup;
1789

1790 1791 1792 1793 1794 1795 1796
    if (!voldef->target.capacity && !backend->buildVol) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("volume capacity required for this "
                               "storage pool"));
        goto cleanup;
    }

1797 1798 1799
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1800
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1801
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1802
                       _("'%s'"), voldef->name);
1803
        goto cleanup;
1804 1805
    }

1806 1807 1808
    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count+1) < 0)
        goto cleanup;
1809

1810
    if (!backend->createVol) {
1811 1812 1813
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1814
        goto cleanup;
1815 1816
    }

1817 1818 1819
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1820
    if (backend->createVol(obj->conn, pool, voldef) < 0)
1821
        goto cleanup;
1822

1823 1824 1825 1826 1827 1828 1829 1830
    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;
    }

1831 1832 1833 1834
    if (VIR_ALLOC(buildvoldef) < 0) {
        voldef = NULL;
        goto cleanup;
    }
1835

1836 1837 1838 1839 1840
    /* 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));
1841

1842 1843
    if (backend->buildVol) {
        int buildret;
1844 1845 1846

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1847
        voldef->building = true;
1848 1849
        virStoragePoolObjUnlock(pool);

1850
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1851

1852
        storageDriverLock();
1853
        virStoragePoolObjLock(pool);
1854
        storageDriverUnlock();
1855

1856
        voldef->building = false;
1857 1858
        pool->asyncjobs--;

1859 1860 1861 1862 1863
        if (buildret < 0) {
            VIR_FREE(buildvoldef);
            storageVolDeleteInternal(volobj, backend, pool, voldef,
                                     0, false);
            voldef = NULL;
1864
            goto cleanup;
1865
        }
1866

1867
    }
1868

1869 1870 1871 1872
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, voldef) < 0)
        goto cleanup;

1873 1874 1875 1876 1877 1878 1879
    /* Update pool metadata ignoring the disk backend since
     * it updates the pool values.
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
        pool->def->allocation += buildvoldef->target.allocation;
        pool->def->available -= buildvoldef->target.allocation;
    }
1880

1881
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1882
             volobj->name, pool->def->name);
1883 1884 1885
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1886

1887
 cleanup:
1888
    virObjectUnref(volobj);
1889
    virStorageVolDefFree(voldef);
1890
    VIR_FREE(buildvoldef);
1891 1892
    if (pool)
        virStoragePoolObjUnlock(pool);
1893
    return ret;
1894 1895
}

1896
static virStorageVolPtr
1897 1898 1899 1900
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1901
{
1902 1903
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
1904
    virStorageVolDefPtr origvol = NULL, newvol = NULL, shadowvol = NULL;
1905
    virStorageVolPtr ret = NULL, volobj = NULL;
1906
    int buildret;
1907

1908 1909 1910
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA |
                  VIR_STORAGE_VOL_CREATE_REFLINK,
                  NULL);
E
Eric Blake 已提交
1911

1912
    storageDriverLock();
1913
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1914
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1915
        virStoragePoolObjUnlock(pool);
1916
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1917
        virStoragePoolObjLock(pool);
1918
    }
1919
    storageDriverUnlock();
1920
    if (!pool) {
1921 1922
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1923
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1924 1925
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1926 1927 1928
        goto cleanup;
    }

1929
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1930 1931 1932
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1933 1934 1935 1936
        goto cleanup;
    }

    if (!virStoragePoolObjIsActive(pool)) {
1937
        virReportError(VIR_ERR_OPERATION_INVALID,
1938
                       _("storage pool '%s' is not active"), pool->def->name);
1939 1940 1941
        goto cleanup;
    }

1942
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1943
        virReportError(VIR_ERR_OPERATION_INVALID,
1944 1945
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1946 1947 1948 1949 1950 1951
        goto cleanup;
    }

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

1952 1953
    origvol = virStorageVolDefFindByName(origpool ?
                                         origpool : pool, vobj->name);
1954
    if (!origvol) {
1955 1956 1957
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1958 1959 1960
        goto cleanup;
    }

1961 1962
    newvol = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_NO_CAPACITY);
1963 1964 1965
    if (newvol == NULL)
        goto cleanup;

1966 1967 1968
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1969
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1970 1971 1972
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1973 1974 1975
        goto cleanup;
    }

1976 1977
    /* Use the original volume's capacity in case the new capacity
     * is less than that, or it was omitted */
1978 1979
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
1980 1981

    if (!backend->buildVolFrom) {
1982
        virReportError(VIR_ERR_NO_SUPPORT,
1983 1984
                       "%s", _("storage pool does not support"
                               " volume creation from an existing volume"));
1985 1986 1987 1988
        goto cleanup;
    }

    if (origvol->building) {
1989 1990 1991
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
1992 1993 1994 1995 1996 1997 1998 1999
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
2000
                      pool->volumes.count+1) < 0)
2001 2002
        goto cleanup;

2003 2004 2005 2006
    /* '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);
2007
    if (backend->createVol(obj->conn, pool, newvol) < 0)
2008 2009
        goto cleanup;

2010 2011 2012 2013 2014 2015 2016 2017 2018
    /* 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));

2019 2020
    pool->volumes.objs[pool->volumes.count++] = newvol;
    volobj = virGetStorageVol(obj->conn, pool->def->name, newvol->name,
2021
                              newvol->key, NULL, NULL);
2022 2023 2024 2025
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
2026 2027 2028

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
2029
    newvol->building = true;
2030
    origvol->in_use++;
2031 2032
    virStoragePoolObjUnlock(pool);

2033
    if (origpool) {
2034 2035 2036 2037
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

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

2040
    storageDriverLock();
2041
    virStoragePoolObjLock(pool);
2042
    if (origpool)
2043
        virStoragePoolObjLock(origpool);
2044
    storageDriverUnlock();
2045

2046
    origvol->in_use--;
2047
    newvol->building = false;
2048 2049
    pool->asyncjobs--;

2050
    if (origpool) {
2051 2052 2053 2054 2055 2056
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
2057 2058
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
2059 2060
        goto cleanup;
    }
2061
    newvol = NULL;
2062

2063 2064 2065 2066
    /* Updating pool metadata ignoring the disk backend since
     * it updates the pool values
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
2067 2068
        pool->def->allocation += shadowvol->target.allocation;
        pool->def->available -= shadowvol->target.allocation;
2069
    }
2070

2071
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
2072
             volobj->name, pool->def->name);
2073 2074 2075
    ret = volobj;
    volobj = NULL;

2076
 cleanup:
2077
    virObjectUnref(volobj);
2078
    virStorageVolDefFree(newvol);
2079
    VIR_FREE(shadowvol);
2080 2081
    if (pool)
        virStoragePoolObjUnlock(pool);
2082
    if (origpool)
2083 2084 2085 2086
        virStoragePoolObjUnlock(origpool);
    return ret;
}

2087

2088
static int
2089 2090 2091 2092 2093
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
2094
{
2095
    virStorageBackendPtr backend;
2096 2097 2098 2099 2100 2101
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

2105
    if (virStorageVolDownloadEnsureACL(obj->conn, pool->def, vol) < 0)
2106
        goto cleanup;
2107

2108
    if (vol->building) {
2109 2110 2111
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2112
        goto cleanup;
2113 2114
    }

2115 2116 2117
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
2118
        goto cleanup;
2119
    }
2120

2121 2122
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
2123

2124
 cleanup:
2125
    virStoragePoolObjUnlock(pool);
2126 2127 2128 2129 2130

    return ret;
}


2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
/**
 * 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;

2159 2160
    storageDriverLock();
    if (!(pool = virStoragePoolObjFindByName(&driver->pools,
2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173
                                             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);
2174
    storageDriverUnlock();
2175 2176 2177 2178 2179 2180 2181 2182
    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 已提交
2183
 * @opaque Buffer to hold the pool name to be refreshed
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
 */
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);
}

2203
static int
2204 2205 2206 2207 2208
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2209
{
2210
    virStorageBackendPtr backend;
2211 2212
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2213
    virStorageVolStreamInfoPtr cbdata = NULL;
2214 2215 2216 2217
    int ret = -1;

    virCheckFlags(0, -1);

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

2221
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2222
        goto cleanup;
2223

2224 2225 2226 2227 2228 2229 2230
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2231
    if (vol->building) {
2232 2233 2234
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2235
        goto cleanup;
2236 2237
    }

2238 2239 2240
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2241
        goto cleanup;
2242
    }
2243

2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
    /* 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;
    }

2256 2257 2258
    if ((ret = backend->uploadVol(obj->conn, pool, vol, stream,
                                  offset, length, flags)) < 0)
        goto cleanup;
2259

2260 2261 2262 2263 2264 2265 2266 2267 2268 2269
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

2270
 cleanup:
2271
    virStoragePoolObjUnlock(pool);
2272 2273
    if (cbdata)
        virStorageVolPoolRefreshDataFree(cbdata);
2274 2275 2276 2277

    return ret;
}

2278
static int
2279 2280 2281
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2282 2283 2284 2285
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2286
    unsigned long long abs_capacity, delta = 0;
2287 2288
    int ret = -1;

2289
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2290 2291
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2292

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

2296
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2297
        goto cleanup;
2298

2299 2300 2301 2302 2303 2304 2305
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2306
    if (vol->building) {
2307 2308 2309
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2310
        goto cleanup;
2311
    }
2312

2313
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2314 2315 2316 2317
        if (flags & VIR_STORAGE_VOL_RESIZE_SHRINK)
            abs_capacity = vol->target.capacity - MIN(capacity, vol->target.capacity);
        else
            abs_capacity = vol->target.capacity + capacity;
2318 2319 2320 2321 2322
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2323
    if (abs_capacity < vol->target.allocation) {
2324
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2325 2326
                       _("can't shrink capacity below "
                         "existing allocation"));
2327
        goto cleanup;
2328 2329
    }

2330
    if (abs_capacity < vol->target.capacity &&
2331 2332 2333
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
2334
                         "capacity unless shrink flag explicitly specified"));
2335
        goto cleanup;
2336 2337
    }

2338
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE)
2339 2340
        delta = abs_capacity - vol->target.allocation;

2341
    if (delta > pool->def->available) {
2342
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2343
                       _("Not enough space left in storage pool"));
2344
        goto cleanup;
2345 2346 2347
    }

    if (!backend->resizeVol) {
2348
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2349 2350
                       _("storage pool does not support changing of "
                         "volume capacity"));
2351
        goto cleanup;
2352 2353 2354
    }

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

2357
    vol->target.capacity = abs_capacity;
2358 2359 2360 2361 2362
    /* 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) {
2363
        vol->target.allocation = abs_capacity;
2364 2365
        pool->def->allocation += delta;
        pool->def->available -= delta;
2366
    }
2367

O
Osier Yang 已提交
2368
    ret = 0;
2369

2370
 cleanup:
2371
    virStoragePoolObjUnlock(pool);
2372 2373 2374

    return ret;
}
2375

2376 2377

static int
2378 2379 2380
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2381
{
2382
    virStorageBackendPtr backend;
2383 2384 2385 2386
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2387
    virCheckFlags(0, -1);
2388

2389
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2390 2391 2392
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2393 2394 2395
        return -1;
    }

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


2400
    if (virStorageVolWipePatternEnsureACL(obj->conn, pool->def, vol) < 0)
2401
        goto cleanup;
2402

2403 2404 2405 2406 2407 2408 2409
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2410
    if (vol->building) {
2411 2412 2413
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2414
        goto cleanup;
2415 2416
    }

2417 2418 2419
    if (!backend->wipeVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume wiping"));
2420
        goto cleanup;
2421
    }
2422

2423
    ret = backend->wipeVol(obj->conn, pool, vol, algorithm, flags);
2424

2425
 cleanup:
2426
    virStoragePoolObjUnlock(pool);
2427 2428 2429 2430

    return ret;
}

2431
static int
2432 2433
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2434
{
2435
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2436 2437
}

2438 2439

static int
2440
storageVolGetInfo(virStorageVolPtr obj,
2441 2442
                  virStorageVolInfoPtr info)
{
2443
    virStoragePoolObjPtr pool;
2444 2445
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2446
    int ret = -1;
2447

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

2451 2452 2453
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2454 2455
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2456
        goto cleanup;
2457 2458

    memset(info, 0, sizeof(*info));
2459
    info->type = vol->type;
2460 2461
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2462
    ret = 0;
2463

2464
 cleanup:
2465
    virStoragePoolObjUnlock(pool);
2466
    return ret;
2467 2468 2469
}

static char *
2470 2471
storageVolGetXMLDesc(virStorageVolPtr obj,
                     unsigned int flags)
E
Eric Blake 已提交
2472
{
2473
    virStoragePoolObjPtr pool;
2474 2475
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2476
    char *ret = NULL;
2477

E
Eric Blake 已提交
2478 2479
    virCheckFlags(0, NULL);

2480 2481
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return NULL;
2482

2483 2484 2485
    if (virStorageVolGetXMLDescEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

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

2490
    ret = virStorageVolDefFormat(pool->def, vol);
2491

2492
 cleanup:
2493
    virStoragePoolObjUnlock(pool);
2494

2495
    return ret;
2496 2497 2498
}

static char *
2499 2500
storageVolGetPath(virStorageVolPtr obj)
{
2501
    virStoragePoolObjPtr pool;
2502
    virStorageVolDefPtr vol;
2503
    char *ret = NULL;
2504

2505 2506
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2507

2508 2509 2510
    if (virStorageVolGetPathEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2511
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2512

2513
 cleanup:
2514
    virStoragePoolObjUnlock(pool);
2515 2516 2517
    return ret;
}

2518
static int
2519 2520 2521
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2522 2523 2524 2525 2526
{
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2527 2528 2529
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2530
    storageDriverLock();
2531
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
2532 2533
                                      virConnectListAllStoragePoolsCheckACL,
                                      flags);
2534
    storageDriverUnlock();
2535

2536
 cleanup:
2537 2538 2539
    return ret;
}

2540

2541
static virStorageDriver storageDriver = {
2542
    .name = "storage",
2543 2544 2545 2546 2547 2548
    .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 */
2549 2550 2551
    .storagePoolLookupByName = storagePoolLookupByName, /* 0.4.0 */
    .storagePoolLookupByUUID = storagePoolLookupByUUID, /* 0.4.0 */
    .storagePoolLookupByVolume = storagePoolLookupByVolume, /* 0.4.0 */
2552 2553
    .storagePoolCreateXML = storagePoolCreateXML, /* 0.4.0 */
    .storagePoolDefineXML = storagePoolDefineXML, /* 0.4.0 */
2554 2555
    .storagePoolBuild = storagePoolBuild, /* 0.4.0 */
    .storagePoolUndefine = storagePoolUndefine, /* 0.4.0 */
2556
    .storagePoolCreate = storagePoolCreate, /* 0.4.0 */
2557 2558 2559 2560 2561 2562 2563
    .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 */
2564
    .storagePoolNumOfVolumes = storagePoolNumOfVolumes, /* 0.4.0 */
2565 2566 2567
    .storagePoolListVolumes = storagePoolListVolumes, /* 0.4.0 */
    .storagePoolListAllVolumes = storagePoolListAllVolumes, /* 0.10.2 */

2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581
    .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 */
2582 2583 2584

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2585 2586 2587 2588
};


static virStateDriver stateDriver = {
2589
    .name = "storage",
2590
    .stateInitialize = storageStateInitialize,
2591
    .stateAutoStart = storageStateAutoStart,
2592 2593
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2594 2595
};

2596 2597
int storageRegister(void)
{
2598
    if (virSetSharedStorageDriver(&storageDriver) < 0)
2599
        return -1;
2600 2601
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2602 2603
    return 0;
}
2604 2605 2606


/* ----------- file handlers cooperating with storage driver --------------- */
2607 2608 2609
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2610
    return src && src->drv;
2611 2612
}

2613 2614 2615 2616

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2617
    int actualType;
2618 2619 2620 2621
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2622
    actualType = virStorageSourceGetActualType(src);
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637

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

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

2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649

/**
 * 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)
{
2650
    int actualType;
2651 2652 2653 2654
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2655
    actualType = virStorageSourceGetActualType(src);
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669

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

    return !!backend->storageFileChown;
}


2670
void
2671
virStorageFileDeinit(virStorageSourcePtr src)
2672
{
2673
    if (!virStorageFileIsInitialized(src))
2674 2675
        return;

2676 2677 2678
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2679

2680
    VIR_FREE(src->drv);
2681 2682 2683
}


2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
/**
 * 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.
 */
2697
int
2698 2699
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
2700
{
2701 2702 2703
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;
2704

2705 2706 2707 2708 2709 2710 2711 2712 2713 2714
    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;

2715 2716
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2717 2718
        goto error;

2719 2720
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2721 2722
        goto error;

2723
    return 0;
2724

2725
 error:
2726 2727
    VIR_FREE(src->drv);
    return -1;
2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
2741 2742 2743 2744 2745 2746
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
2747
 * @src: file structure pointing to the file
2748 2749 2750 2751 2752
 *
 * 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
2753
virStorageFileCreate(virStorageSourcePtr src)
2754
{
2755 2756
    int ret;

2757 2758
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2759 2760 2761 2762
        errno = ENOSYS;
        return -2;
    }

2763 2764 2765 2766 2767 2768
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2769 2770 2771 2772 2773 2774
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
2775
 * @src: file structure pointing to the file
2776 2777 2778 2779 2780 2781 2782
 *
 * 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
2783
virStorageFileUnlink(virStorageSourcePtr src)
2784
{
2785 2786
    int ret;

2787 2788
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2789 2790 2791 2792
        errno = ENOSYS;
        return -2;
    }

2793 2794 2795 2796 2797 2798
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2799 2800 2801 2802 2803 2804
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
2805
 * @src: file structure pointing to the file
2806 2807 2808 2809 2810 2811
 * @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
2812
virStorageFileStat(virStorageSourcePtr src,
2813 2814
                   struct stat *st)
{
2815 2816
    int ret;

2817 2818
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2819 2820 2821 2822
        errno = ENOSYS;
        return -2;
    }

2823 2824 2825 2826 2827 2828
    ret = src->drv->backend->storageFileStat(src, st);

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

    return ret;
2829
}
2830 2831 2832 2833 2834 2835 2836 2837 2838 2839


/**
 * 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
2840 2841
 * function isn't supported by the backend.
 * Libvirt error is reported on failure.
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858
 */
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 "
2859
                         "storage type %s (protocol: %s)"),
2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
                       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;
}
2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900


/*
 * 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);
}
2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924


/**
 * 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);
}
2925 2926


2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
/**
 * 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;
    }

2949 2950
    VIR_DEBUG("chown of storage file %p to %u:%u",
              src, (unsigned int)uid, (unsigned int)gid);
2951 2952 2953 2954 2955

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


2956 2957 2958
/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
2959
                                 virStorageSourcePtr parent,
2960 2961
                                 uid_t uid, gid_t gid,
                                 bool allow_probe,
2962
                                 bool report_broken,
2963 2964 2965
                                 virHashTablePtr cycle)
{
    int ret = -1;
2966
    const char *uniqueName;
2967 2968
    char *buf = NULL;
    ssize_t headerLen;
2969 2970 2971
    virStorageSourcePtr backingStore = NULL;
    int backingFormat;

2972
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u probe=%d",
2973
              src->path, src->format,
2974
              (unsigned int)uid, (unsigned int)gid, allow_probe);
2975

2976 2977 2978 2979 2980
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
2981
        return -1;
2982

2983
    if (virStorageFileAccess(src, F_OK) < 0) {
2984 2985 2986
        if (src == parent) {
            virReportSystemError(errno,
                                 _("Cannot access storage file '%s' "
2987 2988 2989
                                   "(as uid:%u, gid:%u)"),
                                 src->path, (unsigned int)uid,
                                 (unsigned int)gid);
2990 2991 2992
        } else {
            virReportSystemError(errno,
                                 _("Cannot access backing file '%s' "
2993 2994 2995
                                   "of storage file '%s' (as uid:%u, gid:%u)"),
                                 src->path, parent->path,
                                 (unsigned int)uid, (unsigned int)gid);
2996 2997
        }

2998 2999 3000
        goto cleanup;
    }

3001 3002 3003 3004 3005 3006 3007 3008
    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;
3009 3010
    }

3011 3012
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
3013

3014 3015 3016
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
3017

3018 3019
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
3020
        goto cleanup;
3021 3022

    /* check whether we need to go deeper */
3023 3024 3025 3026
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
3027

3028
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
3029
        goto cleanup;
3030 3031 3032 3033 3034 3035 3036 3037

    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;

3038
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
3039 3040 3041 3042 3043 3044
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

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

 cleanup:
3056
    VIR_FREE(buf);
3057
    virStorageFileDeinit(src);
3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077
    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.
 *
3078 3079 3080
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
3081 3082 3083 3084 3085
 * Caller MUST free result after use via virStorageSourceFree.
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
3086 3087
                          bool allow_probe,
                          bool report_broken)
3088
{
3089 3090
    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,
3091
              allow_probe, report_broken);
3092 3093 3094 3095 3096 3097 3098 3099

    virHashTablePtr cycle = NULL;
    int ret = -1;

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

    if (src->format <= VIR_STORAGE_FILE_NONE)
3100 3101
        src->format = allow_probe ?
            VIR_STORAGE_FILE_AUTO : VIR_STORAGE_FILE_RAW;
3102

3103
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
3104
                                           allow_probe, report_broken, cycle);
3105 3106 3107 3108

    virHashFree(cycle);
    return ret;
}
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 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 3212 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 3255 3256 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


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;

    if (virStringListLength(tokens) != 4) {
        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;
    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;

3315 3316
           if (virStorageTranslateDiskSourcePoolAuth(def,
                                                     &pooldef->source) < 0)
3317 3318
               goto cleanup;

3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
           /* 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;
           }

3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
           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:
3349
    virObjectUnref(pool);
3350
    virObjectUnref(vol);
3351 3352 3353 3354
    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}