storage_driver.c 92.3 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 240 241 242
        configdir = virGetUserConfigDirectory();
        rundir = virGetUserRuntimeDirectory();
        if (!(configdir && rundir))
            goto error;

        if ((virAsprintf(&driver->configDir,
                        "%s/storage", configdir) < 0) ||
            (virAsprintf(&driver->autostartDir,
                        "%s/storage", configdir) < 0) ||
            (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 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
static int
storageVolDeleteInternal(virStorageVolPtr obj,
                         virStorageBackendPtr backend,
                         virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol,
                         unsigned int flags,
                         bool updateMeta)
{
    size_t i;
    int ret = -1;

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

        goto cleanup;
    }

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

    /* Update pool metadata - don't update meta data from error paths
     * in this module since the allocation/available weren't adjusted yet
     */
    if (updateMeta) {
        pool->def->allocation -= vol->target.allocation;
        pool->def->available += vol->target.allocation;
    }

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


1648 1649 1650 1651
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1652 1653
{
    virStorageVolDefPtr vol = NULL;
1654 1655

    *pool = NULL;
1656

1657
    storageDriverLock();
1658
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1659
    storageDriverUnlock();
1660

1661
    if (!*pool) {
1662 1663 1664
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1665
        return NULL;
1666 1667
    }

1668
    if (!virStoragePoolObjIsActive(*pool)) {
1669
        virReportError(VIR_ERR_OPERATION_INVALID,
1670 1671 1672
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1673 1674
    }

1675
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1676 1677 1678
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1679
        goto error;
1680 1681
    }

1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    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;

1709 1710 1711
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1712 1713 1714 1715 1716 1717 1718
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1719 1720 1721 1722 1723 1724 1725
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1726
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1727 1728 1729 1730
        goto cleanup;

    ret = 0;

1731
 cleanup:
1732
    virStoragePoolObjUnlock(pool);
1733 1734 1735
    return ret;
}

1736

1737
static virStorageVolPtr
1738 1739 1740
storageVolCreateXML(virStoragePoolPtr obj,
                    const char *xmldesc,
                    unsigned int flags)
E
Eric Blake 已提交
1741
{
1742
    virStoragePoolObjPtr pool;
1743
    virStorageBackendPtr backend;
1744 1745
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1746
    virStorageVolDefPtr buildvoldef = NULL;
1747

1748
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1749

1750 1751
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1752 1753

    if (!virStoragePoolObjIsActive(pool)) {
1754
        virReportError(VIR_ERR_OPERATION_INVALID,
1755
                       _("storage pool '%s' is not active"), pool->def->name);
1756
        goto cleanup;
1757 1758 1759
    }

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

1762 1763
    voldef = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_OPT_CAPACITY);
1764
    if (voldef == NULL)
1765
        goto cleanup;
1766

1767 1768 1769 1770 1771 1772 1773
    if (!voldef->target.capacity && !backend->buildVol) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("volume capacity required for this "
                               "storage pool"));
        goto cleanup;
    }

1774 1775 1776
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1777
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1778
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1779
                       _("'%s'"), voldef->name);
1780
        goto cleanup;
1781 1782
    }

1783
    if (VIR_REALLOC_N(pool->volumes.objs,
1784
                      pool->volumes.count+1) < 0)
1785
        goto cleanup;
1786

1787
    if (!backend->createVol) {
1788 1789 1790
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1791
        goto cleanup;
1792 1793
    }

1794 1795 1796
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1797
    if (backend->createVol(obj->conn, pool, voldef) < 0)
1798
        goto cleanup;
1799

1800 1801
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
1802
                              voldef->key, NULL, NULL);
1803 1804 1805 1806
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1807

1808 1809 1810 1811
    if (VIR_ALLOC(buildvoldef) < 0) {
        voldef = NULL;
        goto cleanup;
    }
1812

1813 1814 1815 1816 1817
    /* 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));
1818

1819 1820
    if (backend->buildVol) {
        int buildret;
1821 1822 1823

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1824
        voldef->building = true;
1825 1826
        virStoragePoolObjUnlock(pool);

1827
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1828

1829
        storageDriverLock();
1830
        virStoragePoolObjLock(pool);
1831
        storageDriverUnlock();
1832

1833
        voldef->building = false;
1834 1835 1836
        pool->asyncjobs--;

        if (buildret < 0) {
1837 1838
            VIR_FREE(buildvoldef);
            storageVolDeleteInternal(volobj, backend, pool, voldef,
1839
                                     0, false);
1840
            voldef = NULL;
1841 1842 1843 1844 1845
            goto cleanup;
        }

    }

1846 1847 1848 1849
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, voldef) < 0)
        goto cleanup;

1850
    /* Update pool metadata */
1851 1852
    pool->def->allocation += buildvoldef->target.allocation;
    pool->def->available -= buildvoldef->target.allocation;
1853

1854
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1855
             volobj->name, pool->def->name);
1856 1857 1858
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1859

1860
 cleanup:
1861
    virObjectUnref(volobj);
1862
    virStorageVolDefFree(voldef);
1863
    VIR_FREE(buildvoldef);
1864 1865
    if (pool)
        virStoragePoolObjUnlock(pool);
1866
    return ret;
1867 1868
}

1869
static virStorageVolPtr
1870 1871 1872 1873
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1874
{
1875 1876 1877 1878
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
    virStorageVolDefPtr origvol = NULL, newvol = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
O
Osier Yang 已提交
1879
    unsigned long long allocation;
1880
    int buildret;
1881

1882 1883 1884
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA |
                  VIR_STORAGE_VOL_CREATE_REFLINK,
                  NULL);
E
Eric Blake 已提交
1885

1886
    storageDriverLock();
1887
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1888
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1889
        virStoragePoolObjUnlock(pool);
1890
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1891
        virStoragePoolObjLock(pool);
1892
    }
1893
    storageDriverUnlock();
1894
    if (!pool) {
1895 1896
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1897
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1898 1899
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1900 1901 1902
        goto cleanup;
    }

1903
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1904 1905 1906
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1907 1908 1909 1910
        goto cleanup;
    }

    if (!virStoragePoolObjIsActive(pool)) {
1911
        virReportError(VIR_ERR_OPERATION_INVALID,
1912
                       _("storage pool '%s' is not active"), pool->def->name);
1913 1914 1915
        goto cleanup;
    }

1916
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1917
        virReportError(VIR_ERR_OPERATION_INVALID,
1918 1919
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1920 1921 1922 1923 1924 1925
        goto cleanup;
    }

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

1926 1927
    origvol = virStorageVolDefFindByName(origpool ?
                                         origpool : pool, vobj->name);
1928
    if (!origvol) {
1929 1930 1931
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1932 1933 1934
        goto cleanup;
    }

1935 1936
    newvol = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_NO_CAPACITY);
1937 1938 1939
    if (newvol == NULL)
        goto cleanup;

1940 1941 1942
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1943
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1944 1945 1946
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1947 1948 1949
        goto cleanup;
    }

1950 1951
    /* Use the original volume's capacity in case the new capacity
     * is less than that, or it was omitted */
1952 1953
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
1954

1955 1956
    /* Make sure allocation is at least as large as the destination cap,
     * to make absolutely sure we copy all possible contents */
1957 1958
    if (newvol->target.allocation < origvol->target.capacity)
        newvol->target.allocation = origvol->target.capacity;
1959

1960
    if (!backend->buildVolFrom) {
1961
        virReportError(VIR_ERR_NO_SUPPORT,
1962 1963
                       "%s", _("storage pool does not support"
                               " volume creation from an existing volume"));
1964 1965 1966 1967
        goto cleanup;
    }

    if (origvol->building) {
1968 1969 1970
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
1971 1972 1973 1974 1975 1976 1977 1978
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
1979
                      pool->volumes.count+1) < 0)
1980 1981
        goto cleanup;

1982 1983 1984 1985
    /* '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);
1986
    if (backend->createVol(obj->conn, pool, newvol) < 0)
1987 1988 1989 1990
        goto cleanup;

    pool->volumes.objs[pool->volumes.count++] = newvol;
    volobj = virGetStorageVol(obj->conn, pool->def->name, newvol->name,
1991
                              newvol->key, NULL, NULL);
1992 1993 1994 1995
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1996 1997 1998

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
1999
    newvol->building = true;
2000
    origvol->in_use++;
2001 2002
    virStoragePoolObjUnlock(pool);

2003
    if (origpool) {
2004 2005 2006 2007
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

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

2010
    storageDriverLock();
2011
    virStoragePoolObjLock(pool);
2012
    if (origpool)
2013
        virStoragePoolObjLock(origpool);
2014
    storageDriverUnlock();
2015

2016
    origvol->in_use--;
2017
    newvol->building = false;
2018
    allocation = newvol->target.allocation;
2019 2020
    pool->asyncjobs--;

2021
    if (origpool) {
2022 2023 2024 2025 2026 2027
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
2028 2029
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
2030 2031
        goto cleanup;
    }
2032
    newvol = NULL;
2033

2034
    /* Updating pool metadata */
O
Osier Yang 已提交
2035 2036
    pool->def->allocation += allocation;
    pool->def->available -= allocation;
2037

2038
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
2039
             volobj->name, pool->def->name);
2040 2041 2042
    ret = volobj;
    volobj = NULL;

2043
 cleanup:
2044
    virObjectUnref(volobj);
2045 2046 2047
    virStorageVolDefFree(newvol);
    if (pool)
        virStoragePoolObjUnlock(pool);
2048
    if (origpool)
2049 2050 2051 2052
        virStoragePoolObjUnlock(origpool);
    return ret;
}

2053

2054
static int
2055 2056 2057 2058 2059
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
2060
{
2061
    virStorageBackendPtr backend;
2062 2063 2064 2065 2066 2067
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

2071
    if (virStorageVolDownloadEnsureACL(obj->conn, pool->def, vol) < 0)
2072
        goto cleanup;
2073

2074
    if (vol->building) {
2075 2076 2077
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2078
        goto cleanup;
2079 2080
    }

2081 2082 2083
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
2084
        goto cleanup;
2085
    }
2086

2087 2088
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
2089

2090
 cleanup:
2091
    virStoragePoolObjUnlock(pool);
2092 2093 2094 2095 2096

    return ret;
}


2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
/**
 * 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;

2125 2126
    storageDriverLock();
    if (!(pool = virStoragePoolObjFindByName(&driver->pools,
2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
                                             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);
2140
    storageDriverUnlock();
2141 2142 2143 2144 2145 2146 2147 2148
    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 已提交
2149
 * @opaque Buffer to hold the pool name to be refreshed
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
 */
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);
}

2169
static int
2170 2171 2172 2173 2174
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2175
{
2176
    virStorageBackendPtr backend;
2177 2178
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2179
    virStorageVolStreamInfoPtr cbdata = NULL;
2180 2181 2182 2183
    int ret = -1;

    virCheckFlags(0, -1);

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

2187
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2188
        goto cleanup;
2189

2190 2191 2192 2193 2194 2195 2196
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2197
    if (vol->building) {
2198 2199 2200
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2201
        goto cleanup;
2202 2203
    }

2204 2205 2206
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2207
        goto cleanup;
2208
    }
2209

2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    /* 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;
    }

2222 2223 2224
    if ((ret = backend->uploadVol(obj->conn, pool, vol, stream,
                                  offset, length, flags)) < 0)
        goto cleanup;
2225

2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

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

    return ret;
}

2244
static int
2245 2246 2247
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2248 2249 2250 2251
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2252
    unsigned long long abs_capacity, delta;
2253 2254
    int ret = -1;

2255
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2256 2257
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2258

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

2262
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2263
        goto cleanup;
2264

2265 2266 2267 2268 2269 2270 2271
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2272
    if (vol->building) {
2273 2274 2275
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2276
        goto cleanup;
2277
    }
2278

2279
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2280
        abs_capacity = vol->target.capacity + capacity;
2281 2282 2283 2284 2285
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2286
    if (abs_capacity < vol->target.allocation) {
2287
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2288 2289
                       _("can't shrink capacity below "
                         "existing allocation"));
2290
        goto cleanup;
2291 2292
    }

2293
    if (abs_capacity < vol->target.capacity &&
2294 2295 2296
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
2297
                         "capacity unless shrink flag explicitly specified"));
2298
        goto cleanup;
2299 2300
    }

2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312
    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) {
2313
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2314
                       _("Not enough space left in storage pool"));
2315
        goto cleanup;
2316 2317 2318
    }

    if (!backend->resizeVol) {
2319
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2320 2321
                       _("storage pool does not support changing of "
                         "volume capacity"));
2322
        goto cleanup;
2323 2324 2325
    }

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

2328
    vol->target.capacity = abs_capacity;
2329 2330 2331 2332 2333
    /* 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) {
2334
        vol->target.allocation = abs_capacity;
2335

2336 2337 2338 2339 2340 2341 2342 2343 2344
        /* 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;
        }
    }
2345

O
Osier Yang 已提交
2346
    ret = 0;
2347

2348
 cleanup:
2349
    virStoragePoolObjUnlock(pool);
2350 2351 2352

    return ret;
}
2353

2354 2355

static int
2356 2357 2358
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2359
{
2360
    virStorageBackendPtr backend;
2361 2362 2363 2364
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2365
    virCheckFlags(0, -1);
2366

2367
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2368 2369 2370
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2371 2372 2373
        return -1;
    }

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


2378
    if (virStorageVolWipePatternEnsureACL(obj->conn, pool->def, vol) < 0)
2379
        goto cleanup;
2380

2381 2382 2383 2384 2385 2386 2387
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2388
    if (vol->building) {
2389 2390 2391
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2392
        goto cleanup;
2393 2394
    }

2395 2396 2397
    if (!backend->wipeVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume wiping"));
2398
        goto cleanup;
2399
    }
2400

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

2403
 cleanup:
2404
    virStoragePoolObjUnlock(pool);
2405 2406 2407 2408

    return ret;
}

2409
static int
2410 2411
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2412
{
2413
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2414 2415
}

2416 2417

static int
2418
storageVolGetInfo(virStorageVolPtr obj,
2419 2420
                  virStorageVolInfoPtr info)
{
2421
    virStoragePoolObjPtr pool;
2422 2423
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2424
    int ret = -1;
2425

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

2429 2430 2431
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2432 2433
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2434
        goto cleanup;
2435 2436

    memset(info, 0, sizeof(*info));
2437
    info->type = vol->type;
2438 2439
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2440
    ret = 0;
2441

2442
 cleanup:
2443
    virStoragePoolObjUnlock(pool);
2444
    return ret;
2445 2446 2447
}

static char *
2448 2449
storageVolGetXMLDesc(virStorageVolPtr obj,
                     unsigned int flags)
E
Eric Blake 已提交
2450
{
2451
    virStoragePoolObjPtr pool;
2452 2453
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2454
    char *ret = NULL;
2455

E
Eric Blake 已提交
2456 2457
    virCheckFlags(0, NULL);

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

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

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

2468
    ret = virStorageVolDefFormat(pool->def, vol);
2469

2470
 cleanup:
2471
    virStoragePoolObjUnlock(pool);
2472

2473
    return ret;
2474 2475 2476
}

static char *
2477 2478
storageVolGetPath(virStorageVolPtr obj)
{
2479
    virStoragePoolObjPtr pool;
2480
    virStorageVolDefPtr vol;
2481
    char *ret = NULL;
2482

2483 2484
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2485

2486 2487 2488
    if (virStorageVolGetPathEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2489
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2490

2491
 cleanup:
2492
    virStoragePoolObjUnlock(pool);
2493 2494 2495
    return ret;
}

2496
static int
2497 2498 2499
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2500 2501 2502 2503 2504
{
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2505 2506 2507
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2508
    storageDriverLock();
2509
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
2510 2511
                                      virConnectListAllStoragePoolsCheckACL,
                                      flags);
2512
    storageDriverUnlock();
2513

2514
 cleanup:
2515 2516 2517
    return ret;
}

2518

2519
static virStorageDriver storageDriver = {
2520
    .name = "storage",
2521 2522 2523 2524 2525 2526
    .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 */
2527 2528 2529
    .storagePoolLookupByName = storagePoolLookupByName, /* 0.4.0 */
    .storagePoolLookupByUUID = storagePoolLookupByUUID, /* 0.4.0 */
    .storagePoolLookupByVolume = storagePoolLookupByVolume, /* 0.4.0 */
2530 2531
    .storagePoolCreateXML = storagePoolCreateXML, /* 0.4.0 */
    .storagePoolDefineXML = storagePoolDefineXML, /* 0.4.0 */
2532 2533
    .storagePoolBuild = storagePoolBuild, /* 0.4.0 */
    .storagePoolUndefine = storagePoolUndefine, /* 0.4.0 */
2534
    .storagePoolCreate = storagePoolCreate, /* 0.4.0 */
2535 2536 2537 2538 2539 2540 2541
    .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 */
2542
    .storagePoolNumOfVolumes = storagePoolNumOfVolumes, /* 0.4.0 */
2543 2544 2545
    .storagePoolListVolumes = storagePoolListVolumes, /* 0.4.0 */
    .storagePoolListAllVolumes = storagePoolListAllVolumes, /* 0.10.2 */

2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559
    .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 */
2560 2561 2562

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2563 2564 2565 2566
};


static virStateDriver stateDriver = {
2567
    .name = "storage",
2568
    .stateInitialize = storageStateInitialize,
2569
    .stateAutoStart = storageStateAutoStart,
2570 2571
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2572 2573
};

2574 2575
int storageRegister(void)
{
2576
    if (virSetSharedStorageDriver(&storageDriver) < 0)
2577
        return -1;
2578 2579
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2580 2581
    return 0;
}
2582 2583 2584


/* ----------- file handlers cooperating with storage driver --------------- */
2585 2586 2587
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2588
    return src && src->drv;
2589 2590
}

2591 2592 2593 2594

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2595
    int actualType;
2596 2597 2598 2599
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2600
    actualType = virStorageSourceGetActualType(src);
2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615

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

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

2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627

/**
 * 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)
{
2628
    int actualType;
2629 2630 2631 2632
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2633
    actualType = virStorageSourceGetActualType(src);
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647

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

    return !!backend->storageFileChown;
}


2648
void
2649
virStorageFileDeinit(virStorageSourcePtr src)
2650
{
2651
    if (!virStorageFileIsInitialized(src))
2652 2653
        return;

2654 2655 2656
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2657

2658
    VIR_FREE(src->drv);
2659 2660 2661
}


2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
/**
 * 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.
 */
2675
int
2676 2677
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
2678
{
2679 2680 2681
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;
2682

2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
    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;

2693 2694
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2695 2696
        goto error;

2697 2698
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2699 2700
        goto error;

2701
    return 0;
2702

2703
 error:
2704 2705
    VIR_FREE(src->drv);
    return -1;
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
2719 2720 2721 2722 2723 2724
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
2725
 * @src: file structure pointing to the file
2726 2727 2728 2729 2730
 *
 * 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
2731
virStorageFileCreate(virStorageSourcePtr src)
2732
{
2733 2734
    int ret;

2735 2736
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2737 2738 2739 2740
        errno = ENOSYS;
        return -2;
    }

2741 2742 2743 2744 2745 2746
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2747 2748 2749 2750 2751 2752
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
2753
 * @src: file structure pointing to the file
2754 2755 2756 2757 2758 2759 2760
 *
 * 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
2761
virStorageFileUnlink(virStorageSourcePtr src)
2762
{
2763 2764
    int ret;

2765 2766
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2767 2768 2769 2770
        errno = ENOSYS;
        return -2;
    }

2771 2772 2773 2774 2775 2776
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2777 2778 2779 2780 2781 2782
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
2783
 * @src: file structure pointing to the file
2784 2785 2786 2787 2788 2789
 * @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
2790
virStorageFileStat(virStorageSourcePtr src,
2791 2792
                   struct stat *st)
{
2793 2794
    int ret;

2795 2796
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2797 2798 2799 2800
        errno = ENOSYS;
        return -2;
    }

2801 2802 2803 2804 2805 2806
    ret = src->drv->backend->storageFileStat(src, st);

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

    return ret;
2807
}
2808 2809 2810 2811 2812 2813 2814 2815 2816 2817


/**
 * 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
2818 2819
 * function isn't supported by the backend.
 * Libvirt error is reported on failure.
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
 */
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 "
2837
                         "storage type %s (protocol: %s)"),
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
                       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;
}
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878


/*
 * 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);
}
2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902


/**
 * 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);
}
2903 2904


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

2927 2928
    VIR_DEBUG("chown of storage file %p to %u:%u",
              src, (unsigned int)uid, (unsigned int)gid);
2929 2930 2931 2932 2933

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


2934 2935 2936
/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
2937
                                 virStorageSourcePtr parent,
2938 2939
                                 uid_t uid, gid_t gid,
                                 bool allow_probe,
2940
                                 bool report_broken,
2941 2942 2943
                                 virHashTablePtr cycle)
{
    int ret = -1;
2944
    const char *uniqueName;
2945 2946
    char *buf = NULL;
    ssize_t headerLen;
2947 2948 2949
    virStorageSourcePtr backingStore = NULL;
    int backingFormat;

2950
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u probe=%d",
2951
              src->path, src->format,
2952
              (unsigned int)uid, (unsigned int)gid, allow_probe);
2953

2954 2955 2956 2957 2958
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
2959
        return -1;
2960

2961
    if (virStorageFileAccess(src, F_OK) < 0) {
2962 2963 2964
        if (src == parent) {
            virReportSystemError(errno,
                                 _("Cannot access storage file '%s' "
2965 2966 2967
                                   "(as uid:%u, gid:%u)"),
                                 src->path, (unsigned int)uid,
                                 (unsigned int)gid);
2968 2969 2970
        } else {
            virReportSystemError(errno,
                                 _("Cannot access backing file '%s' "
2971 2972 2973
                                   "of storage file '%s' (as uid:%u, gid:%u)"),
                                 src->path, parent->path,
                                 (unsigned int)uid, (unsigned int)gid);
2974 2975
        }

2976 2977 2978
        goto cleanup;
    }

2979 2980 2981 2982 2983 2984 2985 2986
    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;
2987 2988
    }

2989 2990
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
2991

2992 2993 2994
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
2995

2996 2997
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
2998
        goto cleanup;
2999 3000

    /* check whether we need to go deeper */
3001 3002 3003 3004
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
3005

3006
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
3007
        goto cleanup;
3008 3009 3010 3011 3012 3013 3014 3015

    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;

3016
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
3017 3018 3019 3020 3021 3022
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

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

 cleanup:
3034
    VIR_FREE(buf);
3035
    virStorageFileDeinit(src);
3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
    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.
 *
3056 3057 3058
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
3059 3060 3061 3062 3063
 * Caller MUST free result after use via virStorageSourceFree.
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
3064 3065
                          bool allow_probe,
                          bool report_broken)
3066
{
3067 3068
    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,
3069
              allow_probe, report_broken);
3070 3071 3072 3073 3074 3075 3076 3077

    virHashTablePtr cycle = NULL;
    int ret = -1;

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

    if (src->format <= VIR_STORAGE_FILE_NONE)
3078 3079
        src->format = allow_probe ?
            VIR_STORAGE_FILE_AUTO : VIR_STORAGE_FILE_RAW;
3080

3081
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
3082
                                           allow_probe, report_broken, cycle);
3083 3084 3085 3086

    virHashFree(cycle);
    return ret;
}
3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 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


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;

3293 3294
           if (virStorageTranslateDiskSourcePoolAuth(def,
                                                     &pooldef->source) < 0)
3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316
               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:
3317
    virObjectUnref(pool);
3318
    virObjectUnref(vol);
3319 3320 3321 3322
    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}