storage_driver.c 93.2 KB
Newer Older
1 2 3
/*
 * storage_driver.c: core driver for storage APIs
 *
4
 * Copyright (C) 2006-2014 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 82 83 84 85 86 87 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 125 126 127 128 129 130 131 132 133 134 135
static void
storagePoolUpdateAllState(void)
{
    size_t i;
    bool active;

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

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

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

        /* 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"));
            virStoragePoolObjUnlock(pool);
            continue;
        }

        /* 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"));
                virStoragePoolObjUnlock(pool);
                continue;
            }
        }

        pool->active = active;
        virStoragePoolObjUnlock(pool);
    }
}

136
static void
137
storageDriverAutostart(void)
138
{
139
    size_t i;
140
    char *stateFile = NULL;
141 142 143
    virConnectPtr conn = NULL;

    /* XXX Remove hardcoding of QEMU URI */
144
    if (driver->privileged)
145 146 147 148
        conn = virConnectOpen("qemu:///system");
    else
        conn = virConnectOpen("qemu:///session");
    /* Ignoring NULL conn - let backends decide */
149

150
    for (i = 0; i < driver->pools.count; i++) {
151
        virStoragePoolObjPtr pool = driver->pools.objs[i];
152 153
        virStorageBackendPtr backend;
        bool started = false;
154

155
        virStoragePoolObjLock(pool);
156 157 158 159
        if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
            virStoragePoolObjUnlock(pool);
            continue;
        }
160

161
        if (pool->autostart &&
162
            !virStoragePoolObjIsActive(pool)) {
163
            if (backend->startPool &&
164
                backend->startPool(conn, pool) < 0) {
165
                virErrorPtr err = virGetLastError();
166
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
167
                          pool->def->name, err ? err->message :
168
                          _("no error message found"));
169
                virStoragePoolObjUnlock(pool);
170 171
                continue;
            }
172 173
            started = true;
        }
174

175
        if (started) {
176
            virStoragePoolObjClearVols(pool);
177 178 179 180 181
            stateFile = virFileBuildPath(driver->stateDir,
                                         pool->def->name, ".xml");
            if (!stateFile ||
                virStoragePoolSaveState(stateFile, pool->def) < 0 ||
                backend->refreshPool(conn, pool) < 0) {
182 183
                virErrorPtr err = virGetLastError();
                if (backend->stopPool)
184
                    backend->stopPool(conn, pool);
185
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
186
                          pool->def->name, err ? err->message :
187
                          _("no error message found"));
188
                VIR_FREE(stateFile);
189
                virStoragePoolObjUnlock(pool);
190 191 192 193
                continue;
            }
            pool->active = 1;
        }
194
        virStoragePoolObjUnlock(pool);
195
    }
196

197
    virObjectUnref(conn);
198 199 200 201 202
}

/**
 * virStorageStartup:
 *
203
 * Initialization function for the Storage Driver
204 205
 */
static int
206 207 208
storageStateInitialize(bool privileged,
                       virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                       void *opaque ATTRIBUTE_UNUSED)
209
{
210 211 212
    int ret = -1;
    char *configdir = NULL;
    char *rundir = NULL;
213

214
    if (VIR_ALLOC(driver) < 0)
215
        return ret;
216

217 218
    if (virMutexInit(&driver->lock) < 0) {
        VIR_FREE(driver);
219
        return ret;
220
    }
221
    storageDriverLock();
222

223
    if (privileged) {
224 225 226 227 228 229
        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)
230
            goto error;
231
    } else {
232 233 234 235 236 237 238 239
        configdir = virGetUserConfigDirectory();
        rundir = virGetUserRuntimeDirectory();
        if (!(configdir && rundir))
            goto error;

        if ((virAsprintf(&driver->configDir,
                        "%s/storage", configdir) < 0) ||
            (virAsprintf(&driver->autostartDir,
240
                        "%s/storage/autostart", configdir) < 0) ||
241 242
            (virAsprintf(&driver->stateDir,
                         "%s/storage/run", rundir) < 0))
243
            goto error;
244
    }
245
    driver->privileged = privileged;
246

247 248 249 250 251 252 253 254 255 256 257
    if (virFileMakePath(driver->stateDir) < 0) {
        virReportError(errno,
                       _("cannot create directory %s"),
                       driver->stateDir);
        goto error;
    }

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

258 259 260
    if (virStoragePoolLoadAllConfigs(&driver->pools,
                                     driver->configDir,
                                     driver->autostartDir) < 0)
261
        goto error;
262

263 264
    storagePoolUpdateAllState();

265
    storageDriverUnlock();
266 267 268 269 270 271

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

273
 error:
274
    storageDriverUnlock();
275
    storageStateCleanup();
276
    goto cleanup;
277 278
}

279 280 281 282 283 284 285 286
/**
 * storageStateAutoStart:
 *
 * Function to auto start the storage driver
 */
static void
storageStateAutoStart(void)
{
287
    if (!driver)
288 289
        return;

290 291 292
    storageDriverLock();
    storageDriverAutostart();
    storageDriverUnlock();
293 294
}

295
/**
296
 * storageStateReload:
297 298 299 300 301
 *
 * Function to restart the storage driver, it will recheck the configuration
 * files and update its state
 */
static int
302 303
storageStateReload(void)
{
304
    if (!driver)
305 306
        return -1;

307
    storageDriverLock();
308 309
    virStoragePoolLoadAllState(&driver->pools,
                               driver->stateDir);
310 311 312 313 314
    virStoragePoolLoadAllConfigs(&driver->pools,
                                 driver->configDir,
                                 driver->autostartDir);
    storageDriverAutostart();
    storageDriverUnlock();
315 316 317 318 319 320

    return 0;
}


/**
321
 * storageStateCleanup
322 323 324 325
 *
 * Shutdown the storage driver, it will stop all active storage pools
 */
static int
326 327
storageStateCleanup(void)
{
328
    if (!driver)
329 330
        return -1;

331
    storageDriverLock();
332 333

    /* free inactive pools */
334
    virStoragePoolObjListFree(&driver->pools);
335

336 337
    VIR_FREE(driver->configDir);
    VIR_FREE(driver->autostartDir);
338
    VIR_FREE(driver->stateDir);
339 340 341
    storageDriverUnlock();
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
342 343 344 345 346 347 348 349

    return 0;
}



static virStoragePoolPtr
storagePoolLookupByUUID(virConnectPtr conn,
350 351
                        const unsigned char *uuid)
{
352 353
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
354

355
    storageDriverLock();
356
    pool = virStoragePoolObjFindByUUID(&driver->pools, uuid);
357
    storageDriverUnlock();
358

359
    if (!pool) {
360 361
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
362
        virReportError(VIR_ERR_NO_STORAGE_POOL,
363 364
                       _("no storage pool with matching uuid '%s'"), uuidstr);
        return NULL;
365 366
    }

367 368 369
    if (virStoragePoolLookupByUUIDEnsureACL(conn, pool->def) < 0)
        goto cleanup;

370 371
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
372

373
 cleanup:
374
    virStoragePoolObjUnlock(pool);
375 376 377 378 379
    return ret;
}

static virStoragePoolPtr
storagePoolLookupByName(virConnectPtr conn,
380 381
                        const char *name)
{
382 383
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
384

385
    storageDriverLock();
386
    pool = virStoragePoolObjFindByName(&driver->pools, name);
387
    storageDriverUnlock();
388

389
    if (!pool) {
390
        virReportError(VIR_ERR_NO_STORAGE_POOL,
391
                       _("no storage pool with matching name '%s'"), name);
392
        return NULL;
393 394
    }

395 396 397
    if (virStoragePoolLookupByNameEnsureACL(conn, pool->def) < 0)
        goto cleanup;

398 399
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
400

401
 cleanup:
402
    virStoragePoolObjUnlock(pool);
403 404 405 406
    return ret;
}

static virStoragePoolPtr
407 408
storagePoolLookupByVolume(virStorageVolPtr vol)
{
409 410 411
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;

412
    storageDriverLock();
413
    pool = virStoragePoolObjFindByName(&driver->pools, vol->pool);
414
    storageDriverUnlock();
415 416 417

    if (!pool) {
        virReportError(VIR_ERR_NO_STORAGE_POOL,
418 419
                       _("no storage pool with matching name '%s'"),
                       vol->pool);
420
        return NULL;
421 422 423 424 425 426 427 428
    }

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

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

429
 cleanup:
430
    virStoragePoolObjUnlock(pool);
431
    return ret;
432 433 434
}

static int
435 436
storageConnectNumOfStoragePools(virConnectPtr conn)
{
437 438
    size_t i;
    int nactive = 0;
439

440 441 442
    if (virConnectNumOfStoragePoolsEnsureACL(conn) < 0)
        return -1;

443
    storageDriverLock();
444
    for (i = 0; i < driver->pools.count; i++) {
445 446 447
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfStoragePoolsCheckACL(conn, obj->def) &&
448
            virStoragePoolObjIsActive(obj))
449
            nactive++;
450
        virStoragePoolObjUnlock(obj);
451
    }
452
    storageDriverUnlock();
453 454

    return nactive;
455 456 457
}

static int
458 459
storageConnectListStoragePools(virConnectPtr conn,
                               char **const names,
460 461
                               int nnames)
{
462 463
    int got = 0;
    size_t i;
464

465 466 467
    if (virConnectListStoragePoolsEnsureACL(conn) < 0)
        return -1;

468
    storageDriverLock();
469
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
470 471 472
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListStoragePoolsCheckACL(conn, obj->def) &&
473
            virStoragePoolObjIsActive(obj)) {
474 475
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
476 477 478 479
                goto cleanup;
            }
            got++;
        }
480
        virStoragePoolObjUnlock(obj);
481
    }
482
    storageDriverUnlock();
483 484 485
    return got;

 cleanup:
486
    storageDriverUnlock();
487
    for (i = 0; i < got; i++)
488
        VIR_FREE(names[i]);
489
    memset(names, 0, nnames * sizeof(*names));
490 491 492 493
    return -1;
}

static int
494 495
storageConnectNumOfDefinedStoragePools(virConnectPtr conn)
{
496 497
    size_t i;
    int nactive = 0;
498

499 500 501
    if (virConnectNumOfDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

502
    storageDriverLock();
503
    for (i = 0; i < driver->pools.count; i++) {
504 505 506
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfDefinedStoragePoolsCheckACL(conn, obj->def) &&
507
            !virStoragePoolObjIsActive(obj))
508
            nactive++;
509
        virStoragePoolObjUnlock(obj);
510
    }
511
    storageDriverUnlock();
512 513

    return nactive;
514 515 516
}

static int
517 518
storageConnectListDefinedStoragePools(virConnectPtr conn,
                                      char **const names,
519 520
                                      int nnames)
{
521 522
    int got = 0;
    size_t i;
523

524 525 526
    if (virConnectListDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

527
    storageDriverLock();
528
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
529 530 531
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListDefinedStoragePoolsCheckACL(conn, obj->def) &&
532
            !virStoragePoolObjIsActive(obj)) {
533 534
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
535 536 537 538
                goto cleanup;
            }
            got++;
        }
539
        virStoragePoolObjUnlock(obj);
540
    }
541
    storageDriverUnlock();
542 543 544
    return got;

 cleanup:
545
    storageDriverUnlock();
546
    for (i = 0; i < got; i++)
547
        VIR_FREE(names[i]);
548
    memset(names, 0, nnames * sizeof(*names));
549 550 551
    return -1;
}

552 553
/* This method is required to be re-entrant / thread safe, so
   uses no driver lock */
554
static char *
555 556 557 558
storageConnectFindStoragePoolSources(virConnectPtr conn,
                                     const char *type,
                                     const char *srcSpec,
                                     unsigned int flags)
559 560 561
{
    int backend_type;
    virStorageBackendPtr backend;
562
    char *ret = NULL;
563

564 565 566
    if (virConnectFindStoragePoolSourcesEnsureACL(conn) < 0)
        return NULL;

567
    backend_type = virStoragePoolTypeFromString(type);
568
    if (backend_type < 0) {
569 570
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage pool type %s"), type);
571
        goto cleanup;
572
    }
573 574 575

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
576
        goto cleanup;
577

578
    if (!backend->findPoolSources) {
579 580 581
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("pool type '%s' does not support source "
                         "discovery"), type);
582 583 584 585
        goto cleanup;
    }

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

587
 cleanup:
588
    return ret;
589 590 591
}


592 593
static virStoragePoolObjPtr
virStoragePoolObjFromStoragePool(virStoragePoolPtr pool)
594
{
595 596
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virStoragePoolObjPtr ret;
597

598
    storageDriverLock();
599 600 601 602 603
    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);
604
    }
605
    storageDriverUnlock();
606 607 608 609 610 611 612 613 614 615 616 617

    return ret;
}


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

    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
618 619 620 621

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

622 623
    ret = virStoragePoolObjIsActive(obj);

624
 cleanup:
625
    virStoragePoolObjUnlock(obj);
626 627 628
    return ret;
}

629
static int storagePoolIsPersistent(virStoragePoolPtr pool)
630 631 632 633
{
    virStoragePoolObjPtr obj;
    int ret = -1;

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

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

640 641
    ret = obj->configFile ? 1 : 0;

642
 cleanup:
643
    virStoragePoolObjUnlock(obj);
644 645 646 647
    return ret;
}


648
static virStoragePoolPtr
649 650 651
storagePoolCreateXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
652
{
653
    virStoragePoolDefPtr def;
654
    virStoragePoolObjPtr pool = NULL;
655
    virStoragePoolPtr ret = NULL;
656
    virStorageBackendPtr backend;
657
    char *stateFile = NULL;
658

E
Eric Blake 已提交
659 660
    virCheckFlags(0, NULL);

661
    storageDriverLock();
662
    if (!(def = virStoragePoolDefParseString(xml)))
663
        goto cleanup;
664

665 666 667
    if (virStoragePoolCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

668
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 1) < 0)
669
        goto cleanup;
670

671
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
672 673
        goto cleanup;

674 675
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
676

677
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
678 679
        goto cleanup;
    def = NULL;
680

681
    if (backend->startPool &&
682 683 684
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
685
        goto cleanup;
686
    }
687

688 689 690 691 692
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(conn, pool) < 0) {
693 694
        if (backend->stopPool)
            backend->stopPool(conn, pool);
695 696
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
697
        goto cleanup;
698
    }
699
    VIR_INFO("Creating storage pool '%s'", pool->def->name);
700 701
    pool->active = 1;

702 703
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
704

705
 cleanup:
706
    VIR_FREE(stateFile);
707
    virStoragePoolDefFree(def);
708
    if (pool)
709
        virStoragePoolObjUnlock(pool);
710
    storageDriverUnlock();
711 712 713 714
    return ret;
}

static virStoragePoolPtr
715 716 717
storagePoolDefineXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
718
{
719
    virStoragePoolDefPtr def;
720
    virStoragePoolObjPtr pool = NULL;
721
    virStoragePoolPtr ret = NULL;
722

E
Eric Blake 已提交
723 724
    virCheckFlags(0, NULL);

725
    storageDriverLock();
726
    if (!(def = virStoragePoolDefParseString(xml)))
727
        goto cleanup;
728

729 730 731
    if (virStoragePoolDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

732 733 734
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 0) < 0)
        goto cleanup;

735
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
736 737
        goto cleanup;

738
    if (virStorageBackendForType(def->type) == NULL)
739
        goto cleanup;
740

741
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
742
        goto cleanup;
743

744
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
745
        virStoragePoolObjRemove(&driver->pools, pool);
746
        def = NULL;
747
        goto cleanup;
748
    }
749
    def = NULL;
750

751
    VIR_INFO("Defining storage pool '%s'", pool->def->name);
752 753
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
754

755
 cleanup:
756
    virStoragePoolDefFree(def);
757 758
    if (pool)
        virStoragePoolObjUnlock(pool);
759
    storageDriverUnlock();
760 761 762 763
    return ret;
}

static int
764 765
storagePoolUndefine(virStoragePoolPtr obj)
{
766 767
    virStoragePoolObjPtr pool;
    int ret = -1;
768

769
    storageDriverLock();
770 771 772
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
773
        virReportError(VIR_ERR_NO_STORAGE_POOL,
774 775
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
776
        goto cleanup;
777 778
    }

779 780 781
    if (virStoragePoolUndefineEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

782
    if (virStoragePoolObjIsActive(pool)) {
783
        virReportError(VIR_ERR_OPERATION_INVALID,
784 785
                       _("storage pool '%s' is still active"),
                       pool->def->name);
786
        goto cleanup;
787 788
    }

789
    if (pool->asyncjobs > 0) {
790 791 792
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
793 794 795
        goto cleanup;
    }

796
    if (virStoragePoolObjDeleteDef(pool) < 0)
797
        goto cleanup;
798

799 800 801
    if (unlink(pool->autostartLink) < 0 &&
        errno != ENOENT &&
        errno != ENOTDIR) {
802
        char ebuf[1024];
803
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
804
                  pool->autostartLink, virStrerror(errno, ebuf, sizeof(ebuf)));
805
    }
806

807 808
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
809

810
    VIR_INFO("Undefining storage pool '%s'", pool->def->name);
811
    virStoragePoolObjRemove(&driver->pools, pool);
812
    pool = NULL;
813
    ret = 0;
814

815
 cleanup:
816 817
    if (pool)
        virStoragePoolObjUnlock(pool);
818
    storageDriverUnlock();
819
    return ret;
820 821 822
}

static int
823 824
storagePoolCreate(virStoragePoolPtr obj,
                  unsigned int flags)
E
Eric Blake 已提交
825
{
826
    virStoragePoolObjPtr pool;
827
    virStorageBackendPtr backend;
828
    int ret = -1;
829
    char *stateFile = NULL;
830

E
Eric Blake 已提交
831 832
    virCheckFlags(0, -1);

833 834
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
835

836 837 838
    if (virStoragePoolCreateEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

839 840
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
841 842

    if (virStoragePoolObjIsActive(pool)) {
843
        virReportError(VIR_ERR_OPERATION_INVALID,
844 845
                       _("storage pool '%s' is already active"),
                       pool->def->name);
846
        goto cleanup;
847
    }
848 849

    VIR_INFO("Starting up storage pool '%s'", pool->def->name);
850 851
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
852 853
        goto cleanup;

854 855 856 857 858
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(obj->conn, pool) < 0) {
859 860
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
861
        goto cleanup;
862 863 864
    }

    pool->active = 1;
865
    ret = 0;
866

867
 cleanup:
868
    VIR_FREE(stateFile);
869
    virStoragePoolObjUnlock(pool);
870
    return ret;
871 872 873 874
}

static int
storagePoolBuild(virStoragePoolPtr obj,
875 876
                 unsigned int flags)
{
877
    virStoragePoolObjPtr pool;
878
    virStorageBackendPtr backend;
879
    int ret = -1;
880

881 882
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
883

884 885 886
    if (virStoragePoolBuildEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
899 900
        goto cleanup;
    ret = 0;
901

902
 cleanup:
903
    virStoragePoolObjUnlock(pool);
904
    return ret;
905 906 907 908
}


static int
909 910
storagePoolDestroy(virStoragePoolPtr obj)
{
911
    virStoragePoolObjPtr pool;
912
    virStorageBackendPtr backend;
913
    char *stateFile = NULL;
914
    int ret = -1;
915

916
    storageDriverLock();
917 918 919
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
920
        virReportError(VIR_ERR_NO_STORAGE_POOL,
921 922
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
923
        goto cleanup;
924 925
    }

926 927 928
    if (virStoragePoolDestroyEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

934
    if (!virStoragePoolObjIsActive(pool)) {
935
        virReportError(VIR_ERR_OPERATION_INVALID,
936
                       _("storage pool '%s' is not active"), pool->def->name);
937
        goto cleanup;
938 939
    }

940
    if (pool->asyncjobs > 0) {
941 942 943
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
944 945 946
        goto cleanup;
    }

947 948 949 950 951 952 953 954
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

955 956
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
957
        goto cleanup;
958 959 960 961 962

    virStoragePoolObjClearVols(pool);

    pool->active = 0;

963
    if (pool->configFile == NULL) {
964
        virStoragePoolObjRemove(&driver->pools, pool);
965
        pool = NULL;
966 967 968 969
    } else if (pool->newDef) {
        virStoragePoolDefFree(pool->def);
        pool->def = pool->newDef;
        pool->newDef = NULL;
970
    }
971

972
    ret = 0;
973

974
 cleanup:
975 976
    if (pool)
        virStoragePoolObjUnlock(pool);
977
    storageDriverUnlock();
978
    return ret;
979 980 981 982
}

static int
storagePoolDelete(virStoragePoolPtr obj,
983 984
                  unsigned int flags)
{
985
    virStoragePoolObjPtr pool;
986
    virStorageBackendPtr backend;
987
    char *stateFile = NULL;
988
    int ret = -1;
989

990 991
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
992

993 994 995
    if (virStoragePoolDeleteEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

1001
    if (virStoragePoolObjIsActive(pool)) {
1002
        virReportError(VIR_ERR_OPERATION_INVALID,
1003 1004
                       _("storage pool '%s' is still active"),
                       pool->def->name);
1005
        goto cleanup;
1006 1007
    }

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

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

    unlink(stateFile);
    VIR_FREE(stateFile);

1023
    if (!backend->deletePool) {
1024 1025
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("pool does not support pool deletion"));
1026
        goto cleanup;
1027 1028
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
1029
        goto cleanup;
1030

1031
    ret = 0;
1032

1033
 cleanup:
1034
    virStoragePoolObjUnlock(pool);
1035
    return ret;
1036 1037 1038 1039 1040
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
E
Eric Blake 已提交
1041 1042
                   unsigned int flags)
{
1043
    virStoragePoolObjPtr pool;
1044
    virStorageBackendPtr backend;
1045
    int ret = -1;
1046

E
Eric Blake 已提交
1047 1048
    virCheckFlags(0, -1);

1049
    storageDriverLock();
1050 1051 1052
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1053
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1054 1055
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1056
        goto cleanup;
1057 1058
    }

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

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

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

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

1078
    virStoragePoolObjClearVols(pool);
1079
    if (backend->refreshPool(obj->conn, pool) < 0) {
1080 1081 1082 1083 1084
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

1085
        if (pool->configFile == NULL) {
1086
            virStoragePoolObjRemove(&driver->pools, pool);
1087 1088
            pool = NULL;
        }
1089
        goto cleanup;
1090
    }
1091
    ret = 0;
1092

1093
 cleanup:
1094 1095
    if (pool)
        virStoragePoolObjUnlock(pool);
1096
    storageDriverUnlock();
1097 1098 1099 1100 1101 1102
    return ret;
}


static int
storagePoolGetInfo(virStoragePoolPtr obj,
1103 1104
                   virStoragePoolInfoPtr info)
{
1105 1106
    virStoragePoolObjPtr pool;
    int ret = -1;
1107

1108 1109
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1110

1111 1112 1113
    if (virStoragePoolGetInfoEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1114
    if (virStorageBackendForType(pool->def->type) == NULL)
1115
        goto cleanup;
1116 1117 1118 1119 1120 1121 1122 1123 1124

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

1127
 cleanup:
1128
    virStoragePoolObjUnlock(pool);
1129
    return ret;
1130 1131 1132
}

static char *
1133
storagePoolGetXMLDesc(virStoragePoolPtr obj,
E
Eric Blake 已提交
1134 1135
                      unsigned int flags)
{
1136
    virStoragePoolObjPtr pool;
1137
    virStoragePoolDefPtr def;
1138
    char *ret = NULL;
1139

1140
    virCheckFlags(VIR_STORAGE_XML_INACTIVE, NULL);
E
Eric Blake 已提交
1141

1142 1143
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1144

1145 1146 1147
    if (virStoragePoolGetXMLDescEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1148 1149 1150 1151 1152 1153
    if ((flags & VIR_STORAGE_XML_INACTIVE) && pool->newDef)
        def = pool->newDef;
    else
        def = pool->def;

    ret = virStoragePoolDefFormat(def);
1154

1155
 cleanup:
1156
    virStoragePoolObjUnlock(pool);
1157
    return ret;
1158 1159 1160 1161
}

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
1162 1163
                        int *autostart)
{
1164 1165
    virStoragePoolObjPtr pool;
    int ret = -1;
1166

1167 1168
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1169

1170 1171 1172
    if (virStoragePoolGetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1173 1174 1175 1176 1177
    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
1178
    ret = 0;
1179

1180
 cleanup:
1181
    virStoragePoolObjUnlock(pool);
1182
    return ret;
1183 1184 1185 1186
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
1187 1188
                        int autostart)
{
1189 1190
    virStoragePoolObjPtr pool;
    int ret = -1;
1191

1192
    storageDriverLock();
1193
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1194

1195
    if (!pool) {
1196 1197
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1198
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1199 1200
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1201
        goto cleanup;
1202 1203
    }

1204 1205 1206
    if (virStoragePoolSetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1207
    if (!pool->configFile) {
1208 1209
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("pool has no config file"));
1210
        goto cleanup;
1211 1212 1213 1214
    }

    autostart = (autostart != 0);

1215 1216
    if (pool->autostart != autostart) {
        if (autostart) {
1217 1218
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
1219 1220
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1221 1222
                goto cleanup;
            }
1223

1224
            if (symlink(pool->configFile, pool->autostartLink) < 0) {
1225
                virReportSystemError(errno,
1226 1227
                                     _("Failed to create symlink '%s' to '%s'"),
                                     pool->autostartLink, pool->configFile);
1228 1229 1230 1231 1232
                goto cleanup;
            }
        } else {
            if (unlink(pool->autostartLink) < 0 &&
                errno != ENOENT && errno != ENOTDIR) {
1233
                virReportSystemError(errno,
1234 1235
                                     _("Failed to delete symlink '%s'"),
                                     pool->autostartLink);
1236 1237
                goto cleanup;
            }
1238
        }
1239
        pool->autostart = autostart;
1240
    }
1241
    ret = 0;
1242

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


static int
1252 1253
storagePoolNumOfVolumes(virStoragePoolPtr obj)
{
1254
    virStoragePoolObjPtr pool;
1255 1256
    int ret = -1;
    size_t i;
1257

1258 1259
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1260

1261 1262 1263
    if (virStoragePoolNumOfVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1264
    if (!virStoragePoolObjIsActive(pool)) {
1265
        virReportError(VIR_ERR_OPERATION_INVALID,
1266
                       _("storage pool '%s' is not active"), pool->def->name);
1267
        goto cleanup;
1268
    }
1269 1270 1271 1272 1273 1274
    ret = 0;
    for (i = 0; i < pool->volumes.count; i++) {
        if (virStoragePoolNumOfVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            ret++;
    }
1275

1276
 cleanup:
1277
    virStoragePoolObjUnlock(pool);
1278
    return ret;
1279 1280 1281 1282 1283
}

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
1284 1285
                       int maxnames)
{
1286
    virStoragePoolObjPtr pool;
1287 1288
    size_t i;
    int n = 0;
1289

1290 1291
    memset(names, 0, maxnames * sizeof(*names));

1292 1293
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1294

1295 1296 1297
    if (virStoragePoolListVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1298
    if (!virStoragePoolObjIsActive(pool)) {
1299
        virReportError(VIR_ERR_OPERATION_INVALID,
1300
                       _("storage pool '%s' is not active"), pool->def->name);
1301
        goto cleanup;
1302 1303
    }

1304
    for (i = 0; i < pool->volumes.count && n < maxnames; i++) {
1305 1306 1307
        if (!virStoragePoolListVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            continue;
1308
        if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0)
1309 1310 1311
            goto cleanup;
    }

1312
    virStoragePoolObjUnlock(pool);
1313
    return n;
1314 1315

 cleanup:
1316
    virStoragePoolObjUnlock(pool);
1317
    for (n = 0; n < maxnames; n++)
1318
        VIR_FREE(names[n]);
1319

1320
    memset(names, 0, maxnames * sizeof(*names));
1321 1322 1323
    return -1;
}

1324 1325 1326
static int
storagePoolListAllVolumes(virStoragePoolPtr pool,
                          virStorageVolPtr **vols,
1327 1328
                          unsigned int flags)
{
1329
    virStoragePoolObjPtr obj;
1330
    size_t i;
1331 1332 1333 1334 1335 1336 1337
    virStorageVolPtr *tmp_vols = NULL;
    virStorageVolPtr vol = NULL;
    int nvols = 0;
    int ret = -1;

    virCheckFlags(0, -1);

1338 1339
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
1340

1341 1342 1343
    if (virStoragePoolListAllVolumesEnsureACL(pool->conn, obj->def) < 0)
        goto cleanup;

1344
    if (!virStoragePoolObjIsActive(obj)) {
1345 1346
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("storage pool '%s' is not active"), obj->def->name);
1347 1348 1349 1350 1351 1352 1353 1354 1355
        goto cleanup;
    }

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

1356
    if (VIR_ALLOC_N(tmp_vols, obj->volumes.count + 1) < 0)
1357
        goto cleanup;
1358

1359
    for (i = 0; i < obj->volumes.count; i++) {
1360 1361 1362
        if (!virStoragePoolListAllVolumesCheckACL(pool->conn, obj->def,
                                                  obj->volumes.objs[i]))
            continue;
1363 1364
        if (!(vol = virGetStorageVol(pool->conn, obj->def->name,
                                     obj->volumes.objs[i]->name,
1365 1366
                                     obj->volumes.objs[i]->key,
                                     NULL, NULL)))
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
            goto cleanup;
        tmp_vols[nvols++] = vol;
    }

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

 cleanup:
    if (tmp_vols) {
1377 1378
        for (i = 0; i < nvols; i++)
            virObjectUnref(tmp_vols[i]);
1379
        VIR_FREE(tmp_vols);
1380 1381
    }

1382
    virStoragePoolObjUnlock(obj);
1383 1384 1385

    return ret;
}
1386 1387

static virStorageVolPtr
1388
storageVolLookupByName(virStoragePoolPtr obj,
1389 1390
                       const char *name)
{
1391
    virStoragePoolObjPtr pool;
1392
    virStorageVolDefPtr vol;
1393
    virStorageVolPtr ret = NULL;
1394

1395 1396
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1397 1398

    if (!virStoragePoolObjIsActive(pool)) {
1399
        virReportError(VIR_ERR_OPERATION_INVALID,
1400
                       _("storage pool '%s' is not active"), pool->def->name);
1401
        goto cleanup;
1402 1403 1404 1405 1406
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1407 1408 1409
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       name);
1410
        goto cleanup;
1411 1412
    }

1413 1414 1415
    if (virStorageVolLookupByNameEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1416 1417
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key,
                           NULL, NULL);
1418

1419
 cleanup:
1420
    virStoragePoolObjUnlock(pool);
1421
    return ret;
1422 1423 1424 1425
}


static virStorageVolPtr
1426
storageVolLookupByKey(virConnectPtr conn,
1427 1428
                      const char *key)
{
1429
    size_t i;
1430
    virStorageVolPtr ret = NULL;
1431

1432
    storageDriverLock();
1433
    for (i = 0; i < driver->pools.count && !ret; i++) {
1434
        virStoragePoolObjLock(driver->pools.objs[i]);
1435 1436 1437
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1438

1439
            if (vol) {
1440 1441
                virStoragePoolDefPtr def = driver->pools.objs[i]->def;
                if (virStorageVolLookupByKeyEnsureACL(conn, def, vol) < 0) {
1442
                    virStoragePoolObjUnlock(driver->pools.objs[i]);
1443
                    goto cleanup;
1444
                }
1445

1446
                ret = virGetStorageVol(conn,
1447
                                       def->name,
1448
                                       vol->name,
1449 1450
                                       vol->key,
                                       NULL, NULL);
1451
            }
1452
        }
1453
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1454 1455
    }

1456
    if (!ret)
1457
        virReportError(VIR_ERR_NO_STORAGE_VOL,
1458
                       _("no storage vol with matching key %s"), key);
1459

1460
 cleanup:
1461
    storageDriverUnlock();
1462
    return ret;
1463 1464 1465
}

static virStorageVolPtr
1466
storageVolLookupByPath(virConnectPtr conn,
1467 1468
                       const char *path)
{
1469
    size_t i;
1470
    virStorageVolPtr ret = NULL;
1471 1472 1473 1474 1475
    char *cleanpath;

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

1477
    storageDriverLock();
1478
    for (i = 0; i < driver->pools.count && !ret; i++) {
1479 1480 1481 1482 1483
        virStoragePoolObjPtr pool = driver->pools.objs[i];
        virStorageVolDefPtr vol;
        char *stable_path = NULL;

        virStoragePoolObjLock(pool);
1484

1485 1486 1487 1488
        if (!virStoragePoolObjIsActive(pool)) {
           virStoragePoolObjUnlock(pool);
           continue;
        }
1489

1490
        switch ((virStoragePoolType) pool->def->type) {
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
            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 已提交
1516
            case VIR_STORAGE_POOL_ZFS:
1517 1518 1519
            case VIR_STORAGE_POOL_LAST:
                if (VIR_STRDUP(stable_path, path) < 0) {
                     virStoragePoolObjUnlock(pool);
1520
                    goto cleanup;
1521
                }
1522 1523
                break;
        }
1524

1525 1526 1527 1528 1529 1530 1531
        vol = virStorageVolDefFindByPath(pool, stable_path);
        VIR_FREE(stable_path);

        if (vol) {
            if (virStorageVolLookupByPathEnsureACL(conn, pool->def, vol) < 0) {
                virStoragePoolObjUnlock(pool);
                goto cleanup;
1532
            }
1533 1534 1535 1536

            ret = virGetStorageVol(conn, pool->def->name,
                                   vol->name, vol->key,
                                   NULL, NULL);
1537
        }
1538 1539

        virStoragePoolObjUnlock(pool);
1540 1541
    }

1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
    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);
        }
    }
1552

1553
 cleanup:
1554
    VIR_FREE(cleanpath);
1555
    storageDriverUnlock();
1556
    return ret;
1557 1558
}

1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
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;
}

1601

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
static int
storageVolDeleteInternal(virStorageVolPtr obj,
                         virStorageBackendPtr backend,
                         virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol,
                         unsigned int flags,
                         bool updateMeta)
{
    size_t i;
    int ret = -1;
1612
    unsigned long long orig_pool_available, orig_pool_allocation;
1613 1614 1615 1616 1617 1618 1619 1620

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

        goto cleanup;
    }

1621 1622 1623
    orig_pool_available = pool->def->available;
    orig_pool_allocation = pool->def->allocation;

1624 1625 1626 1627 1628 1629 1630
    if (backend->deleteVol(obj->conn, pool, vol, flags) < 0)
        goto cleanup;

    /* Update pool metadata - don't update meta data from error paths
     * in this module since the allocation/available weren't adjusted yet
     */
    if (updateMeta) {
1631 1632 1633 1634
        if (orig_pool_allocation == pool->def->allocation)
            pool->def->allocation -= vol->target.allocation;
        if (orig_pool_available == pool->def->available)
            pool->def->available += vol->target.allocation;
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
    }

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


1654 1655 1656 1657
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1658 1659
{
    virStorageVolDefPtr vol = NULL;
1660 1661

    *pool = NULL;
1662

1663
    storageDriverLock();
1664
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1665
    storageDriverUnlock();
1666

1667
    if (!*pool) {
1668 1669 1670
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1671
        return NULL;
1672 1673
    }

1674
    if (!virStoragePoolObjIsActive(*pool)) {
1675
        virReportError(VIR_ERR_OPERATION_INVALID,
1676 1677 1678
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1679 1680
    }

1681
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1682 1683 1684
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1685
        goto error;
1686 1687
    }

1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
    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;

1715 1716 1717
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1718 1719 1720 1721 1722 1723 1724
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1725 1726 1727 1728 1729 1730 1731
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1732
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1733 1734 1735 1736
        goto cleanup;

    ret = 0;

1737
 cleanup:
1738
    virStoragePoolObjUnlock(pool);
1739 1740 1741
    return ret;
}

1742

1743
static virStorageVolPtr
1744 1745 1746
storageVolCreateXML(virStoragePoolPtr obj,
                    const char *xmldesc,
                    unsigned int flags)
E
Eric Blake 已提交
1747
{
1748
    virStoragePoolObjPtr pool;
1749
    virStorageBackendPtr backend;
1750 1751
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1752
    virStorageVolDefPtr buildvoldef = NULL;
1753
    unsigned long long orig_pool_available, orig_pool_allocation;
1754

1755
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1756

1757 1758
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1759 1760

    if (!virStoragePoolObjIsActive(pool)) {
1761
        virReportError(VIR_ERR_OPERATION_INVALID,
1762
                       _("storage pool '%s' is not active"), pool->def->name);
1763
        goto cleanup;
1764 1765 1766
    }

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

1769 1770
    voldef = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_OPT_CAPACITY);
1771
    if (voldef == NULL)
1772
        goto cleanup;
1773

1774 1775 1776 1777 1778 1779 1780
    if (!voldef->target.capacity && !backend->buildVol) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("volume capacity required for this "
                               "storage pool"));
        goto cleanup;
    }

1781 1782 1783
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1784
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1785
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1786
                       _("'%s'"), voldef->name);
1787
        goto cleanup;
1788 1789
    }

1790
    if (VIR_REALLOC_N(pool->volumes.objs,
1791
                      pool->volumes.count+1) < 0)
1792
        goto cleanup;
1793

1794
    if (!backend->createVol) {
1795 1796 1797
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1798
        goto cleanup;
1799 1800
    }

1801 1802 1803
    orig_pool_available = pool->def->available;
    orig_pool_allocation = pool->def->allocation;

1804 1805 1806
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1807
    if (backend->createVol(obj->conn, pool, voldef) < 0)
1808
        goto cleanup;
1809

1810 1811
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
1812
                              voldef->key, NULL, NULL);
1813 1814 1815 1816
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1817

1818 1819 1820 1821
    if (VIR_ALLOC(buildvoldef) < 0) {
        voldef = NULL;
        goto cleanup;
    }
1822

1823 1824 1825 1826 1827
    /* 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));
1828

1829 1830
    if (backend->buildVol) {
        int buildret;
1831 1832 1833

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1834
        voldef->building = true;
1835 1836
        virStoragePoolObjUnlock(pool);

1837
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1838

1839
        storageDriverLock();
1840
        virStoragePoolObjLock(pool);
1841
        storageDriverUnlock();
1842

1843
        voldef->building = false;
1844 1845 1846
        pool->asyncjobs--;

        if (buildret < 0) {
1847 1848
            VIR_FREE(buildvoldef);
            storageVolDeleteInternal(volobj, backend, pool, voldef,
1849
                                     0, false);
1850
            voldef = NULL;
1851 1852 1853 1854 1855
            goto cleanup;
        }

    }

1856 1857 1858 1859
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, voldef) < 0)
        goto cleanup;

1860
    /* Update pool metadata */
1861 1862 1863 1864
    if (orig_pool_allocation == pool->def->allocation)
        pool->def->allocation += buildvoldef->target.allocation;
    if (orig_pool_available == pool->def->available)
        pool->def->available -= buildvoldef->target.allocation;
1865

1866
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1867
             volobj->name, pool->def->name);
1868 1869 1870
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1871

1872
 cleanup:
1873
    virObjectUnref(volobj);
1874
    virStorageVolDefFree(voldef);
1875
    VIR_FREE(buildvoldef);
1876 1877
    if (pool)
        virStoragePoolObjUnlock(pool);
1878
    return ret;
1879 1880
}

1881
static virStorageVolPtr
1882 1883 1884 1885
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1886
{
1887 1888 1889 1890
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
    virStorageVolDefPtr origvol = NULL, newvol = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
O
Osier Yang 已提交
1891
    unsigned long long allocation;
1892
    unsigned long long orig_pool_available, orig_pool_allocation;
1893
    int buildret;
1894

1895 1896 1897
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA |
                  VIR_STORAGE_VOL_CREATE_REFLINK,
                  NULL);
E
Eric Blake 已提交
1898

1899
    storageDriverLock();
1900
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1901
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1902
        virStoragePoolObjUnlock(pool);
1903
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1904
        virStoragePoolObjLock(pool);
1905
    }
1906
    storageDriverUnlock();
1907
    if (!pool) {
1908 1909
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1910
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1911 1912
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1913 1914 1915
        goto cleanup;
    }

1916
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1917 1918 1919
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1920 1921 1922 1923
        goto cleanup;
    }

    if (!virStoragePoolObjIsActive(pool)) {
1924
        virReportError(VIR_ERR_OPERATION_INVALID,
1925
                       _("storage pool '%s' is not active"), pool->def->name);
1926 1927 1928
        goto cleanup;
    }

1929
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1930
        virReportError(VIR_ERR_OPERATION_INVALID,
1931 1932
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1933 1934 1935 1936 1937 1938
        goto cleanup;
    }

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

1939 1940
    origvol = virStorageVolDefFindByName(origpool ?
                                         origpool : pool, vobj->name);
1941
    if (!origvol) {
1942 1943 1944
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1945 1946 1947
        goto cleanup;
    }

1948 1949
    newvol = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_NO_CAPACITY);
1950 1951 1952
    if (newvol == NULL)
        goto cleanup;

1953 1954 1955
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1956
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1957 1958 1959
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1960 1961 1962
        goto cleanup;
    }

1963 1964
    /* Use the original volume's capacity in case the new capacity
     * is less than that, or it was omitted */
1965 1966
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
1967

1968 1969
    /* Make sure allocation is at least as large as the destination cap,
     * to make absolutely sure we copy all possible contents */
1970 1971
    if (newvol->target.allocation < origvol->target.capacity)
        newvol->target.allocation = origvol->target.capacity;
1972

1973
    if (!backend->buildVolFrom) {
1974
        virReportError(VIR_ERR_NO_SUPPORT,
1975 1976
                       "%s", _("storage pool does not support"
                               " volume creation from an existing volume"));
1977 1978 1979 1980
        goto cleanup;
    }

    if (origvol->building) {
1981 1982 1983
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
1984 1985 1986 1987 1988 1989 1990 1991
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
1992
                      pool->volumes.count+1) < 0)
1993 1994
        goto cleanup;

1995 1996 1997
    orig_pool_available = pool->def->available;
    orig_pool_allocation = pool->def->allocation;

1998 1999 2000 2001
    /* '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);
2002
    if (backend->createVol(obj->conn, pool, newvol) < 0)
2003 2004 2005 2006
        goto cleanup;

    pool->volumes.objs[pool->volumes.count++] = newvol;
    volobj = virGetStorageVol(obj->conn, pool->def->name, newvol->name,
2007
                              newvol->key, NULL, NULL);
2008 2009 2010 2011
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
2012 2013 2014

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
2015
    newvol->building = true;
2016
    origvol->in_use++;
2017 2018
    virStoragePoolObjUnlock(pool);

2019
    if (origpool) {
2020 2021 2022 2023
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

2024
    buildret = backend->buildVolFrom(obj->conn, pool, newvol, origvol, flags);
2025

2026
    storageDriverLock();
2027
    virStoragePoolObjLock(pool);
2028
    if (origpool)
2029
        virStoragePoolObjLock(origpool);
2030
    storageDriverUnlock();
2031

2032
    origvol->in_use--;
2033
    newvol->building = false;
2034
    allocation = newvol->target.allocation;
2035 2036
    pool->asyncjobs--;

2037
    if (origpool) {
2038 2039 2040 2041 2042 2043
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
2044 2045
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
2046 2047
        goto cleanup;
    }
2048
    newvol = NULL;
2049

2050
    /* Updating pool metadata */
2051 2052 2053 2054
    if (orig_pool_allocation == pool->def->allocation)
        pool->def->allocation += allocation;
    if (orig_pool_available == pool->def->available)
        pool->def->available -= allocation;
2055

2056
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
2057
             volobj->name, pool->def->name);
2058 2059 2060
    ret = volobj;
    volobj = NULL;

2061
 cleanup:
2062
    virObjectUnref(volobj);
2063 2064 2065
    virStorageVolDefFree(newvol);
    if (pool)
        virStoragePoolObjUnlock(pool);
2066
    if (origpool)
2067 2068 2069 2070
        virStoragePoolObjUnlock(origpool);
    return ret;
}

2071

2072
static int
2073 2074 2075 2076 2077
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
2078
{
2079
    virStorageBackendPtr backend;
2080 2081 2082 2083 2084 2085
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

2089
    if (virStorageVolDownloadEnsureACL(obj->conn, pool->def, vol) < 0)
2090
        goto cleanup;
2091

2092
    if (vol->building) {
2093 2094 2095
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2096
        goto cleanup;
2097 2098
    }

2099 2100 2101
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
2102
        goto cleanup;
2103
    }
2104

2105 2106
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
2107

2108
 cleanup:
2109
    virStoragePoolObjUnlock(pool);
2110 2111 2112 2113 2114

    return ret;
}


2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
/**
 * 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;

2143 2144
    storageDriverLock();
    if (!(pool = virStoragePoolObjFindByName(&driver->pools,
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157
                                             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);
2158
    storageDriverUnlock();
2159 2160 2161 2162 2163 2164 2165 2166
    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 已提交
2167
 * @opaque Buffer to hold the pool name to be refreshed
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186
 */
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);
}

2187
static int
2188 2189 2190 2191 2192
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2193
{
2194
    virStorageBackendPtr backend;
2195 2196
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2197
    virStorageVolStreamInfoPtr cbdata = NULL;
2198 2199 2200 2201
    int ret = -1;

    virCheckFlags(0, -1);

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

2205
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2206
        goto cleanup;
2207

2208 2209 2210 2211 2212 2213 2214
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2215
    if (vol->building) {
2216 2217 2218
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2219
        goto cleanup;
2220 2221
    }

2222 2223 2224
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2225
        goto cleanup;
2226
    }
2227

2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
    /* 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;
    }

2240 2241 2242
    if ((ret = backend->uploadVol(obj->conn, pool, vol, stream,
                                  offset, length, flags)) < 0)
        goto cleanup;
2243

2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

2254
 cleanup:
2255
    virStoragePoolObjUnlock(pool);
2256 2257
    if (cbdata)
        virStorageVolPoolRefreshDataFree(cbdata);
2258 2259 2260 2261

    return ret;
}

2262
static int
2263 2264 2265
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2266 2267 2268 2269
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2270
    unsigned long long abs_capacity, delta;
2271 2272
    int ret = -1;

2273
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2274 2275
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2276

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

2280
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2281
        goto cleanup;
2282

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

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

2297
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2298
        abs_capacity = vol->target.capacity + capacity;
2299 2300 2301 2302 2303
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2304
    if (abs_capacity < vol->target.allocation) {
2305
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2306 2307
                       _("can't shrink capacity below "
                         "existing allocation"));
2308
        goto cleanup;
2309 2310
    }

2311
    if (abs_capacity < vol->target.capacity &&
2312 2313 2314
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
2315
                         "capacity unless shrink flag explicitly specified"));
2316
        goto cleanup;
2317 2318
    }

2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
    if (flags & VIR_STORAGE_VOL_RESIZE_SHRINK)
        delta = vol->target.allocation - abs_capacity;
    else
        delta = abs_capacity - vol->target.allocation;

    /* If the operation is going to increase the allocation value and not
     * just the capacity value, then let's make sure there's enough space
     * in the pool in order to perform that operation
     */
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE &&
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK) &&
        delta > pool->def->available) {
2331
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2332
                       _("Not enough space left in storage pool"));
2333
        goto cleanup;
2334 2335 2336
    }

    if (!backend->resizeVol) {
2337
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2338 2339
                       _("storage pool does not support changing of "
                         "volume capacity"));
2340
        goto cleanup;
2341 2342 2343
    }

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

2346
    vol->target.capacity = abs_capacity;
2347 2348 2349 2350 2351
    /* 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) {
2352
        vol->target.allocation = abs_capacity;
2353

2354 2355 2356 2357 2358 2359 2360 2361 2362
        /* Update pool metadata */
        if (flags & VIR_STORAGE_VOL_RESIZE_SHRINK) {
           pool->def->allocation -= delta;
           pool->def->available += delta;
        } else {
           pool->def->allocation += delta;
           pool->def->available -= delta;
        }
    }
2363

O
Osier Yang 已提交
2364
    ret = 0;
2365

2366
 cleanup:
2367
    virStoragePoolObjUnlock(pool);
2368 2369 2370

    return ret;
}
2371

2372 2373

static int
2374 2375 2376
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2377
{
2378
    virStorageBackendPtr backend;
2379 2380 2381 2382
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2383
    virCheckFlags(0, -1);
2384

2385
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2386 2387 2388
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2389 2390 2391
        return -1;
    }

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


2396
    if (virStorageVolWipePatternEnsureACL(obj->conn, pool->def, vol) < 0)
2397
        goto cleanup;
2398

2399 2400 2401 2402 2403 2404 2405
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2406
    if (vol->building) {
2407 2408 2409
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2410
        goto cleanup;
2411 2412
    }

2413 2414 2415
    if (!backend->wipeVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume wiping"));
2416
        goto cleanup;
2417
    }
2418

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

2421
 cleanup:
2422
    virStoragePoolObjUnlock(pool);
2423 2424 2425 2426

    return ret;
}

2427
static int
2428 2429
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2430
{
2431
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2432 2433
}

2434 2435

static int
2436
storageVolGetInfo(virStorageVolPtr obj,
2437 2438
                  virStorageVolInfoPtr info)
{
2439
    virStoragePoolObjPtr pool;
2440 2441
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2442
    int ret = -1;
2443

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

2447 2448 2449
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2450 2451
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2452
        goto cleanup;
2453 2454

    memset(info, 0, sizeof(*info));
2455
    info->type = vol->type;
2456 2457
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2458
    ret = 0;
2459

2460
 cleanup:
2461
    virStoragePoolObjUnlock(pool);
2462
    return ret;
2463 2464 2465
}

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

E
Eric Blake 已提交
2474 2475
    virCheckFlags(0, NULL);

2476 2477
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return NULL;
2478

2479 2480 2481
    if (virStorageVolGetXMLDescEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

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

2486
    ret = virStorageVolDefFormat(pool->def, vol);
2487

2488
 cleanup:
2489
    virStoragePoolObjUnlock(pool);
2490

2491
    return ret;
2492 2493 2494
}

static char *
2495 2496
storageVolGetPath(virStorageVolPtr obj)
{
2497
    virStoragePoolObjPtr pool;
2498
    virStorageVolDefPtr vol;
2499
    char *ret = NULL;
2500

2501 2502
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2503

2504 2505 2506
    if (virStorageVolGetPathEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2507
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2508

2509
 cleanup:
2510
    virStoragePoolObjUnlock(pool);
2511 2512 2513
    return ret;
}

2514
static int
2515 2516 2517
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2518 2519 2520 2521 2522
{
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2523 2524 2525
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2526
    storageDriverLock();
2527
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
2528 2529
                                      virConnectListAllStoragePoolsCheckACL,
                                      flags);
2530
    storageDriverUnlock();
2531

2532
 cleanup:
2533 2534 2535
    return ret;
}

2536

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

2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
    .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 */
2578 2579 2580

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2581 2582 2583 2584
};


static virStateDriver stateDriver = {
2585
    .name = "storage",
2586
    .stateInitialize = storageStateInitialize,
2587
    .stateAutoStart = storageStateAutoStart,
2588 2589
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2590 2591
};

2592 2593
int storageRegister(void)
{
2594
    if (virSetSharedStorageDriver(&storageDriver) < 0)
2595
        return -1;
2596 2597
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2598 2599
    return 0;
}
2600 2601 2602


/* ----------- file handlers cooperating with storage driver --------------- */
2603 2604 2605
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2606
    return src && src->drv;
2607 2608
}

2609 2610 2611 2612

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2613
    int actualType;
2614 2615 2616 2617
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2618
    actualType = virStorageSourceGetActualType(src);
2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633

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

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

2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645

/**
 * 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)
{
2646
    int actualType;
2647 2648 2649 2650
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2651
    actualType = virStorageSourceGetActualType(src);
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665

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

    return !!backend->storageFileChown;
}


2666
void
2667
virStorageFileDeinit(virStorageSourcePtr src)
2668
{
2669
    if (!virStorageFileIsInitialized(src))
2670 2671
        return;

2672 2673 2674
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2675

2676
    VIR_FREE(src->drv);
2677 2678 2679
}


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

2701 2702 2703 2704 2705 2706 2707 2708 2709 2710
    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;

2711 2712
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2713 2714
        goto error;

2715 2716
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2717 2718
        goto error;

2719
    return 0;
2720

2721
 error:
2722 2723
    VIR_FREE(src->drv);
    return -1;
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
}


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


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

2753 2754
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2755 2756 2757 2758
        errno = ENOSYS;
        return -2;
    }

2759 2760 2761 2762 2763 2764
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2765 2766 2767 2768 2769 2770
}


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

2783 2784
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2785 2786 2787 2788
        errno = ENOSYS;
        return -2;
    }

2789 2790 2791 2792 2793 2794
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2795 2796 2797 2798 2799 2800
}


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

2813 2814
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2815 2816 2817 2818
        errno = ENOSYS;
        return -2;
    }

2819 2820 2821 2822 2823 2824
    ret = src->drv->backend->storageFileStat(src, st);

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

    return ret;
2825
}
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835


/**
 * 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
2836 2837
 * function isn't supported by the backend.
 * Libvirt error is reported on failure.
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854
 */
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 "
2855
                         "storage type %s (protocol: %s)"),
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
                       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;
}
2867 2868 2869 2870 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


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


/**
 * 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);
}
2921 2922


2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
/**
 * 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;
    }

2945 2946
    VIR_DEBUG("chown of storage file %p to %u:%u",
              src, (unsigned int)uid, (unsigned int)gid);
2947 2948 2949 2950 2951

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


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

2968
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u probe=%d",
2969
              src->path, src->format,
2970
              (unsigned int)uid, (unsigned int)gid, allow_probe);
2971

2972 2973 2974 2975 2976
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
2977
        return -1;
2978

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

2994 2995 2996
        goto cleanup;
    }

2997 2998 2999 3000 3001 3002 3003 3004
    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;
3005 3006
    }

3007 3008
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
3009

3010 3011 3012
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
3013

3014 3015
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
3016
        goto cleanup;
3017 3018

    /* check whether we need to go deeper */
3019 3020 3021 3022
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
3023

3024
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
3025
        goto cleanup;
3026 3027 3028 3029 3030 3031 3032 3033

    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;

3034
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
3035 3036 3037 3038 3039 3040
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

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

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

    virHashTablePtr cycle = NULL;
    int ret = -1;

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

    if (src->format <= VIR_STORAGE_FILE_NONE)
3096 3097
        src->format = allow_probe ?
            VIR_STORAGE_FILE_AUTO : VIR_STORAGE_FILE_RAW;
3098

3099
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
3100
                                           allow_probe, report_broken, cycle);
3101 3102 3103 3104

    virHashFree(cycle);
    return ret;
}
3105 3106 3107 3108 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


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;

3311 3312
           if (virStorageTranslateDiskSourcePoolAuth(def,
                                                     &pooldef->source) < 0)
3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334
               goto cleanup;

           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:
3335
    virObjectUnref(pool);
3336
    virObjectUnref(vol);
3337 3338 3339 3340
    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}