storage_driver.c 92.7 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
static void
storagePoolUpdateState(virStoragePoolObjPtr pool)
{
    bool active;
    virStorageBackendPtr backend;
82 83 84 85 86 87
    int ret = -1;
    char *stateFile;

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

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

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

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

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

133 134 135
    return;
}

136 137 138 139 140 141 142 143 144 145 146 147 148 149
static void
storagePoolUpdateAllState(void)
{
    size_t i;

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

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

150
        storagePoolUpdateState(pool);
151 152 153 154
        virStoragePoolObjUnlock(pool);
    }
}

155
static void
156
storageDriverAutostart(void)
157
{
158
    size_t i;
159
    char *stateFile = NULL;
160 161 162
    virConnectPtr conn = NULL;

    /* XXX Remove hardcoding of QEMU URI */
163
    if (driver->privileged)
164 165 166 167
        conn = virConnectOpen("qemu:///system");
    else
        conn = virConnectOpen("qemu:///session");
    /* Ignoring NULL conn - let backends decide */
168

169
    for (i = 0; i < driver->pools.count; i++) {
170
        virStoragePoolObjPtr pool = driver->pools.objs[i];
171 172
        virStorageBackendPtr backend;
        bool started = false;
173

174
        virStoragePoolObjLock(pool);
175 176 177 178
        if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
            virStoragePoolObjUnlock(pool);
            continue;
        }
179

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

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

218
    virObjectUnref(conn);
219 220 221 222 223
}

/**
 * virStorageStartup:
 *
224
 * Initialization function for the Storage Driver
225 226
 */
static int
227 228 229
storageStateInitialize(bool privileged,
                       virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                       void *opaque ATTRIBUTE_UNUSED)
230
{
231 232 233
    int ret = -1;
    char *configdir = NULL;
    char *rundir = NULL;
234

235
    if (VIR_ALLOC(driver) < 0)
236
        return ret;
237

238 239
    if (virMutexInit(&driver->lock) < 0) {
        VIR_FREE(driver);
240
        return ret;
241
    }
242
    storageDriverLock();
243

244
    if (privileged) {
245 246 247 248 249 250
        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)
251
            goto error;
252
    } else {
253 254 255 256 257 258 259 260
        configdir = virGetUserConfigDirectory();
        rundir = virGetUserRuntimeDirectory();
        if (!(configdir && rundir))
            goto error;

        if ((virAsprintf(&driver->configDir,
                        "%s/storage", configdir) < 0) ||
            (virAsprintf(&driver->autostartDir,
261
                        "%s/storage/autostart", configdir) < 0) ||
262 263
            (virAsprintf(&driver->stateDir,
                         "%s/storage/run", rundir) < 0))
264
            goto error;
265
    }
266
    driver->privileged = privileged;
267

268 269 270 271 272 273 274 275 276 277 278
    if (virFileMakePath(driver->stateDir) < 0) {
        virReportError(errno,
                       _("cannot create directory %s"),
                       driver->stateDir);
        goto error;
    }

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

279 280 281
    if (virStoragePoolLoadAllConfigs(&driver->pools,
                                     driver->configDir,
                                     driver->autostartDir) < 0)
282
        goto error;
283

284 285
    storagePoolUpdateAllState();

286
    storageDriverUnlock();
287 288 289 290 291 292

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

294
 error:
295
    storageDriverUnlock();
296
    storageStateCleanup();
297
    goto cleanup;
298 299
}

300 301 302 303 304 305 306 307
/**
 * storageStateAutoStart:
 *
 * Function to auto start the storage driver
 */
static void
storageStateAutoStart(void)
{
308
    if (!driver)
309 310
        return;

311 312 313
    storageDriverLock();
    storageDriverAutostart();
    storageDriverUnlock();
314 315
}

316
/**
317
 * storageStateReload:
318 319 320 321 322
 *
 * Function to restart the storage driver, it will recheck the configuration
 * files and update its state
 */
static int
323 324
storageStateReload(void)
{
325
    if (!driver)
326 327
        return -1;

328
    storageDriverLock();
329 330
    virStoragePoolLoadAllState(&driver->pools,
                               driver->stateDir);
331 332 333 334 335
    virStoragePoolLoadAllConfigs(&driver->pools,
                                 driver->configDir,
                                 driver->autostartDir);
    storageDriverAutostart();
    storageDriverUnlock();
336 337 338 339 340 341

    return 0;
}


/**
342
 * storageStateCleanup
343 344 345 346
 *
 * Shutdown the storage driver, it will stop all active storage pools
 */
static int
347 348
storageStateCleanup(void)
{
349
    if (!driver)
350 351
        return -1;

352
    storageDriverLock();
353 354

    /* free inactive pools */
355
    virStoragePoolObjListFree(&driver->pools);
356

357 358
    VIR_FREE(driver->configDir);
    VIR_FREE(driver->autostartDir);
359
    VIR_FREE(driver->stateDir);
360 361 362
    storageDriverUnlock();
    virMutexDestroy(&driver->lock);
    VIR_FREE(driver);
363 364 365 366 367 368 369 370

    return 0;
}



static virStoragePoolPtr
storagePoolLookupByUUID(virConnectPtr conn,
371 372
                        const unsigned char *uuid)
{
373 374
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
375

376
    storageDriverLock();
377
    pool = virStoragePoolObjFindByUUID(&driver->pools, uuid);
378
    storageDriverUnlock();
379

380
    if (!pool) {
381 382
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
383
        virReportError(VIR_ERR_NO_STORAGE_POOL,
384 385
                       _("no storage pool with matching uuid '%s'"), uuidstr);
        return NULL;
386 387
    }

388 389 390
    if (virStoragePoolLookupByUUIDEnsureACL(conn, pool->def) < 0)
        goto cleanup;

391 392
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
393

394
 cleanup:
395
    virStoragePoolObjUnlock(pool);
396 397 398 399 400
    return ret;
}

static virStoragePoolPtr
storagePoolLookupByName(virConnectPtr conn,
401 402
                        const char *name)
{
403 404
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
405

406
    storageDriverLock();
407
    pool = virStoragePoolObjFindByName(&driver->pools, name);
408
    storageDriverUnlock();
409

410
    if (!pool) {
411
        virReportError(VIR_ERR_NO_STORAGE_POOL,
412
                       _("no storage pool with matching name '%s'"), name);
413
        return NULL;
414 415
    }

416 417 418
    if (virStoragePoolLookupByNameEnsureACL(conn, pool->def) < 0)
        goto cleanup;

419 420
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
421

422
 cleanup:
423
    virStoragePoolObjUnlock(pool);
424 425 426 427
    return ret;
}

static virStoragePoolPtr
428 429
storagePoolLookupByVolume(virStorageVolPtr vol)
{
430 431 432
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;

433
    storageDriverLock();
434
    pool = virStoragePoolObjFindByName(&driver->pools, vol->pool);
435
    storageDriverUnlock();
436 437 438

    if (!pool) {
        virReportError(VIR_ERR_NO_STORAGE_POOL,
439 440
                       _("no storage pool with matching name '%s'"),
                       vol->pool);
441
        return NULL;
442 443 444 445 446 447 448 449
    }

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

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

450
 cleanup:
451
    virStoragePoolObjUnlock(pool);
452
    return ret;
453 454 455
}

static int
456 457
storageConnectNumOfStoragePools(virConnectPtr conn)
{
458 459
    size_t i;
    int nactive = 0;
460

461 462 463
    if (virConnectNumOfStoragePoolsEnsureACL(conn) < 0)
        return -1;

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

    return nactive;
476 477 478
}

static int
479 480
storageConnectListStoragePools(virConnectPtr conn,
                               char **const names,
481 482
                               int nnames)
{
483 484
    int got = 0;
    size_t i;
485

486 487 488
    if (virConnectListStoragePoolsEnsureACL(conn) < 0)
        return -1;

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

 cleanup:
507
    storageDriverUnlock();
508
    for (i = 0; i < got; i++)
509
        VIR_FREE(names[i]);
510
    memset(names, 0, nnames * sizeof(*names));
511 512 513 514
    return -1;
}

static int
515 516
storageConnectNumOfDefinedStoragePools(virConnectPtr conn)
{
517 518
    size_t i;
    int nactive = 0;
519

520 521 522
    if (virConnectNumOfDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

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

    return nactive;
535 536 537
}

static int
538 539
storageConnectListDefinedStoragePools(virConnectPtr conn,
                                      char **const names,
540 541
                                      int nnames)
{
542 543
    int got = 0;
    size_t i;
544

545 546 547
    if (virConnectListDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

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

 cleanup:
566
    storageDriverUnlock();
567
    for (i = 0; i < got; i++)
568
        VIR_FREE(names[i]);
569
    memset(names, 0, nnames * sizeof(*names));
570 571 572
    return -1;
}

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

585 586 587
    if (virConnectFindStoragePoolSourcesEnsureACL(conn) < 0)
        return NULL;

588
    backend_type = virStoragePoolTypeFromString(type);
589
    if (backend_type < 0) {
590 591
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage pool type %s"), type);
592
        goto cleanup;
593
    }
594 595 596

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
597
        goto cleanup;
598

599
    if (!backend->findPoolSources) {
600 601 602
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("pool type '%s' does not support source "
                         "discovery"), type);
603 604 605 606
        goto cleanup;
    }

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

608
 cleanup:
609
    return ret;
610 611 612
}


613 614
static virStoragePoolObjPtr
virStoragePoolObjFromStoragePool(virStoragePoolPtr pool)
615
{
616 617
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virStoragePoolObjPtr ret;
618

619
    storageDriverLock();
620 621 622 623 624
    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);
625
    }
626
    storageDriverUnlock();
627 628 629 630 631 632 633 634 635 636 637 638

    return ret;
}


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

    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
639 640 641 642

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

643 644
    ret = virStoragePoolObjIsActive(obj);

645
 cleanup:
646
    virStoragePoolObjUnlock(obj);
647 648 649
    return ret;
}

650
static int storagePoolIsPersistent(virStoragePoolPtr pool)
651 652 653 654
{
    virStoragePoolObjPtr obj;
    int ret = -1;

655 656
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
657 658 659 660

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

661 662
    ret = obj->configFile ? 1 : 0;

663
 cleanup:
664
    virStoragePoolObjUnlock(obj);
665 666 667 668
    return ret;
}


669
static virStoragePoolPtr
670 671 672
storagePoolCreateXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
673
{
674
    virStoragePoolDefPtr def;
675
    virStoragePoolObjPtr pool = NULL;
676
    virStoragePoolPtr ret = NULL;
677
    virStorageBackendPtr backend;
678
    char *stateFile = NULL;
679

E
Eric Blake 已提交
680 681
    virCheckFlags(0, NULL);

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

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

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

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

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

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

702
    if (backend->startPool &&
703 704 705
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
706
        goto cleanup;
707
    }
708

709 710 711 712 713
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

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

725 726
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
727

728
 cleanup:
729
    VIR_FREE(stateFile);
730
    virStoragePoolDefFree(def);
731
    if (pool)
732
        virStoragePoolObjUnlock(pool);
733
    storageDriverUnlock();
734 735 736 737
    return ret;
}

static virStoragePoolPtr
738 739 740
storagePoolDefineXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
741
{
742
    virStoragePoolDefPtr def;
743
    virStoragePoolObjPtr pool = NULL;
744
    virStoragePoolPtr ret = NULL;
745

E
Eric Blake 已提交
746 747
    virCheckFlags(0, NULL);

748
    storageDriverLock();
749
    if (!(def = virStoragePoolDefParseString(xml)))
750
        goto cleanup;
751

752 753 754
    if (virStoragePoolDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

755 756 757
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 0) < 0)
        goto cleanup;

758
    if (virStoragePoolSourceFindDuplicate(conn, &driver->pools, def) < 0)
759 760
        goto cleanup;

761
    if (virStorageBackendForType(def->type) == NULL)
762
        goto cleanup;
763

764
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
765
        goto cleanup;
766

767
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
768
        virStoragePoolObjRemove(&driver->pools, pool);
769
        def = NULL;
770
        goto cleanup;
771
    }
772
    def = NULL;
773

774
    VIR_INFO("Defining storage pool '%s'", pool->def->name);
775 776
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
777

778
 cleanup:
779
    virStoragePoolDefFree(def);
780 781
    if (pool)
        virStoragePoolObjUnlock(pool);
782
    storageDriverUnlock();
783 784 785 786
    return ret;
}

static int
787 788
storagePoolUndefine(virStoragePoolPtr obj)
{
789 790
    virStoragePoolObjPtr pool;
    int ret = -1;
791

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

802 803 804
    if (virStoragePoolUndefineEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

805
    if (virStoragePoolObjIsActive(pool)) {
806
        virReportError(VIR_ERR_OPERATION_INVALID,
807 808
                       _("storage pool '%s' is still active"),
                       pool->def->name);
809
        goto cleanup;
810 811
    }

812
    if (pool->asyncjobs > 0) {
813 814 815
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
816 817 818
        goto cleanup;
    }

819
    if (virStoragePoolObjDeleteDef(pool) < 0)
820
        goto cleanup;
821

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

830 831
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
832

833
    VIR_INFO("Undefining storage pool '%s'", pool->def->name);
834
    virStoragePoolObjRemove(&driver->pools, pool);
835
    pool = NULL;
836
    ret = 0;
837

838
 cleanup:
839 840
    if (pool)
        virStoragePoolObjUnlock(pool);
841
    storageDriverUnlock();
842
    return ret;
843 844 845
}

static int
846 847
storagePoolCreate(virStoragePoolPtr obj,
                  unsigned int flags)
E
Eric Blake 已提交
848
{
849
    virStoragePoolObjPtr pool;
850
    virStorageBackendPtr backend;
851
    int ret = -1;
852
    char *stateFile = NULL;
853

E
Eric Blake 已提交
854 855
    virCheckFlags(0, -1);

856 857
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
858

859 860 861
    if (virStoragePoolCreateEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

862 863
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
864 865

    if (virStoragePoolObjIsActive(pool)) {
866
        virReportError(VIR_ERR_OPERATION_INVALID,
867 868
                       _("storage pool '%s' is already active"),
                       pool->def->name);
869
        goto cleanup;
870
    }
871 872

    VIR_INFO("Starting up storage pool '%s'", pool->def->name);
873 874
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
875 876
        goto cleanup;

877 878 879 880 881
    stateFile = virFileBuildPath(driver->stateDir,
                                 pool->def->name, ".xml");

    if (!stateFile || virStoragePoolSaveState(stateFile, pool->def) < 0 ||
        backend->refreshPool(obj->conn, pool) < 0) {
882 883
        if (stateFile)
            unlink(stateFile);
884 885
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
886
        goto cleanup;
887 888 889
    }

    pool->active = 1;
890
    ret = 0;
891

892
 cleanup:
893
    VIR_FREE(stateFile);
894
    virStoragePoolObjUnlock(pool);
895
    return ret;
896 897 898 899
}

static int
storagePoolBuild(virStoragePoolPtr obj,
900 901
                 unsigned int flags)
{
902
    virStoragePoolObjPtr pool;
903
    virStorageBackendPtr backend;
904
    int ret = -1;
905

906 907
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
908

909 910 911
    if (virStoragePoolBuildEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

912 913
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
914 915

    if (virStoragePoolObjIsActive(pool)) {
916
        virReportError(VIR_ERR_OPERATION_INVALID,
917 918
                       _("storage pool '%s' is already active"),
                       pool->def->name);
919
        goto cleanup;
920 921 922 923
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
924 925
        goto cleanup;
    ret = 0;
926

927
 cleanup:
928
    virStoragePoolObjUnlock(pool);
929
    return ret;
930 931 932 933
}


static int
934 935
storagePoolDestroy(virStoragePoolPtr obj)
{
936
    virStoragePoolObjPtr pool;
937
    virStorageBackendPtr backend;
938
    char *stateFile = NULL;
939
    int ret = -1;
940

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

951 952 953
    if (virStoragePoolDestroyEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

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

965
    if (pool->asyncjobs > 0) {
966 967 968
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
969 970 971
        goto cleanup;
    }

972 973 974 975 976 977 978 979
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

980 981
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
982
        goto cleanup;
983 984 985 986 987

    virStoragePoolObjClearVols(pool);

    pool->active = 0;

988
    if (pool->configFile == NULL) {
989
        virStoragePoolObjRemove(&driver->pools, pool);
990
        pool = NULL;
991 992 993 994
    } else if (pool->newDef) {
        virStoragePoolDefFree(pool->def);
        pool->def = pool->newDef;
        pool->newDef = NULL;
995
    }
996

997
    ret = 0;
998

999
 cleanup:
1000 1001
    if (pool)
        virStoragePoolObjUnlock(pool);
1002
    storageDriverUnlock();
1003
    return ret;
1004 1005 1006 1007
}

static int
storagePoolDelete(virStoragePoolPtr obj,
1008 1009
                  unsigned int flags)
{
1010
    virStoragePoolObjPtr pool;
1011
    virStorageBackendPtr backend;
1012
    char *stateFile = NULL;
1013
    int ret = -1;
1014

1015 1016
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1017

1018 1019 1020
    if (virStoragePoolDeleteEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

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

1026
    if (virStoragePoolObjIsActive(pool)) {
1027
        virReportError(VIR_ERR_OPERATION_INVALID,
1028 1029
                       _("storage pool '%s' is still active"),
                       pool->def->name);
1030
        goto cleanup;
1031 1032
    }

1033
    if (pool->asyncjobs > 0) {
1034 1035
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
1036 1037 1038 1039
                              pool->def->name);
        goto cleanup;
    }

1040 1041 1042 1043 1044 1045 1046 1047
    if (!(stateFile = virFileBuildPath(driver->stateDir,
                                       pool->def->name,
                                       ".xml")))
        goto cleanup;

    unlink(stateFile);
    VIR_FREE(stateFile);

1048
    if (!backend->deletePool) {
1049 1050
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("pool does not support pool deletion"));
1051
        goto cleanup;
1052 1053
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
1054
        goto cleanup;
1055

1056
    ret = 0;
1057

1058
 cleanup:
1059
    virStoragePoolObjUnlock(pool);
1060
    return ret;
1061 1062 1063 1064 1065
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
E
Eric Blake 已提交
1066 1067
                   unsigned int flags)
{
1068
    virStoragePoolObjPtr pool;
1069
    virStorageBackendPtr backend;
1070
    int ret = -1;
1071

E
Eric Blake 已提交
1072 1073
    virCheckFlags(0, -1);

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

1084 1085 1086
    if (virStoragePoolRefreshEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1087 1088
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
1089 1090

    if (!virStoragePoolObjIsActive(pool)) {
1091
        virReportError(VIR_ERR_OPERATION_INVALID,
1092
                       _("storage pool '%s' is not active"), pool->def->name);
1093
        goto cleanup;
1094 1095
    }

1096
    if (pool->asyncjobs > 0) {
1097 1098 1099
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
1100 1101 1102
        goto cleanup;
    }

1103
    virStoragePoolObjClearVols(pool);
1104
    if (backend->refreshPool(obj->conn, pool) < 0) {
1105 1106 1107 1108 1109
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

1110
        if (pool->configFile == NULL) {
1111
            virStoragePoolObjRemove(&driver->pools, pool);
1112 1113
            pool = NULL;
        }
1114
        goto cleanup;
1115
    }
1116
    ret = 0;
1117

1118
 cleanup:
1119 1120
    if (pool)
        virStoragePoolObjUnlock(pool);
1121
    storageDriverUnlock();
1122 1123 1124 1125 1126 1127
    return ret;
}


static int
storagePoolGetInfo(virStoragePoolPtr obj,
1128 1129
                   virStoragePoolInfoPtr info)
{
1130 1131
    virStoragePoolObjPtr pool;
    int ret = -1;
1132

1133 1134
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1135

1136 1137 1138
    if (virStoragePoolGetInfoEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1139
    if (virStorageBackendForType(pool->def->type) == NULL)
1140
        goto cleanup;
1141 1142 1143 1144 1145 1146 1147 1148 1149

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

1152
 cleanup:
1153
    virStoragePoolObjUnlock(pool);
1154
    return ret;
1155 1156 1157
}

static char *
1158
storagePoolGetXMLDesc(virStoragePoolPtr obj,
E
Eric Blake 已提交
1159 1160
                      unsigned int flags)
{
1161
    virStoragePoolObjPtr pool;
1162
    virStoragePoolDefPtr def;
1163
    char *ret = NULL;
1164

1165
    virCheckFlags(VIR_STORAGE_XML_INACTIVE, NULL);
E
Eric Blake 已提交
1166

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

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

1173 1174 1175 1176 1177 1178
    if ((flags & VIR_STORAGE_XML_INACTIVE) && pool->newDef)
        def = pool->newDef;
    else
        def = pool->def;

    ret = virStoragePoolDefFormat(def);
1179

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

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

1192 1193
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1194

1195 1196 1197
    if (virStoragePoolGetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1198 1199 1200 1201 1202
    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
1203
    ret = 0;
1204

1205
 cleanup:
1206
    virStoragePoolObjUnlock(pool);
1207
    return ret;
1208 1209 1210 1211
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
1212 1213
                        int autostart)
{
1214 1215
    virStoragePoolObjPtr pool;
    int ret = -1;
1216

1217
    storageDriverLock();
1218
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1219

1220
    if (!pool) {
1221 1222
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1223
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1224 1225
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1226
        goto cleanup;
1227 1228
    }

1229 1230 1231
    if (virStoragePoolSetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1232
    if (!pool->configFile) {
1233 1234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("pool has no config file"));
1235
        goto cleanup;
1236 1237 1238 1239
    }

    autostart = (autostart != 0);

1240 1241
    if (pool->autostart != autostart) {
        if (autostart) {
1242 1243
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
1244 1245
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1246 1247
                goto cleanup;
            }
1248

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

1268
 cleanup:
1269 1270
    if (pool)
        virStoragePoolObjUnlock(pool);
1271
    storageDriverUnlock();
1272
    return ret;
1273 1274 1275 1276
}


static int
1277 1278
storagePoolNumOfVolumes(virStoragePoolPtr obj)
{
1279
    virStoragePoolObjPtr pool;
1280 1281
    int ret = -1;
    size_t i;
1282

1283 1284
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1285

1286 1287 1288
    if (virStoragePoolNumOfVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

1301
 cleanup:
1302
    virStoragePoolObjUnlock(pool);
1303
    return ret;
1304 1305 1306 1307 1308
}

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
1309 1310
                       int maxnames)
{
1311
    virStoragePoolObjPtr pool;
1312 1313
    size_t i;
    int n = 0;
1314

1315 1316
    memset(names, 0, maxnames * sizeof(*names));

1317 1318
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1319

1320 1321 1322
    if (virStoragePoolListVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1323
    if (!virStoragePoolObjIsActive(pool)) {
1324
        virReportError(VIR_ERR_OPERATION_INVALID,
1325
                       _("storage pool '%s' is not active"), pool->def->name);
1326
        goto cleanup;
1327 1328
    }

1329
    for (i = 0; i < pool->volumes.count && n < maxnames; i++) {
1330 1331 1332
        if (!virStoragePoolListVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            continue;
1333
        if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0)
1334 1335 1336
            goto cleanup;
    }

1337
    virStoragePoolObjUnlock(pool);
1338
    return n;
1339 1340

 cleanup:
1341
    virStoragePoolObjUnlock(pool);
1342
    for (n = 0; n < maxnames; n++)
1343
        VIR_FREE(names[n]);
1344

1345
    memset(names, 0, maxnames * sizeof(*names));
1346 1347 1348
    return -1;
}

1349 1350 1351
static int
storagePoolListAllVolumes(virStoragePoolPtr pool,
                          virStorageVolPtr **vols,
1352 1353
                          unsigned int flags)
{
1354
    virStoragePoolObjPtr obj;
1355
    size_t i;
1356 1357 1358 1359 1360 1361 1362
    virStorageVolPtr *tmp_vols = NULL;
    virStorageVolPtr vol = NULL;
    int nvols = 0;
    int ret = -1;

    virCheckFlags(0, -1);

1363 1364
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
1365

1366 1367 1368
    if (virStoragePoolListAllVolumesEnsureACL(pool->conn, obj->def) < 0)
        goto cleanup;

1369
    if (!virStoragePoolObjIsActive(obj)) {
1370 1371
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("storage pool '%s' is not active"), obj->def->name);
1372 1373 1374 1375 1376 1377 1378 1379 1380
        goto cleanup;
    }

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

1381
    if (VIR_ALLOC_N(tmp_vols, obj->volumes.count + 1) < 0)
1382
        goto cleanup;
1383

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

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

 cleanup:
    if (tmp_vols) {
1402 1403
        for (i = 0; i < nvols; i++)
            virObjectUnref(tmp_vols[i]);
1404
        VIR_FREE(tmp_vols);
1405 1406
    }

1407
    virStoragePoolObjUnlock(obj);
1408 1409 1410

    return ret;
}
1411 1412

static virStorageVolPtr
1413
storageVolLookupByName(virStoragePoolPtr obj,
1414 1415
                       const char *name)
{
1416
    virStoragePoolObjPtr pool;
1417
    virStorageVolDefPtr vol;
1418
    virStorageVolPtr ret = NULL;
1419

1420 1421
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1422 1423

    if (!virStoragePoolObjIsActive(pool)) {
1424
        virReportError(VIR_ERR_OPERATION_INVALID,
1425
                       _("storage pool '%s' is not active"), pool->def->name);
1426
        goto cleanup;
1427 1428 1429 1430 1431
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1432 1433 1434
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       name);
1435
        goto cleanup;
1436 1437
    }

1438 1439 1440
    if (virStorageVolLookupByNameEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1441 1442
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key,
                           NULL, NULL);
1443

1444
 cleanup:
1445
    virStoragePoolObjUnlock(pool);
1446
    return ret;
1447 1448 1449 1450
}


static virStorageVolPtr
1451
storageVolLookupByKey(virConnectPtr conn,
1452 1453
                      const char *key)
{
1454
    size_t i;
1455
    virStorageVolPtr ret = NULL;
1456

1457
    storageDriverLock();
1458
    for (i = 0; i < driver->pools.count && !ret; i++) {
1459
        virStoragePoolObjLock(driver->pools.objs[i]);
1460 1461 1462
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1463

1464
            if (vol) {
1465 1466
                virStoragePoolDefPtr def = driver->pools.objs[i]->def;
                if (virStorageVolLookupByKeyEnsureACL(conn, def, vol) < 0) {
1467
                    virStoragePoolObjUnlock(driver->pools.objs[i]);
1468
                    goto cleanup;
1469
                }
1470

1471
                ret = virGetStorageVol(conn,
1472
                                       def->name,
1473
                                       vol->name,
1474 1475
                                       vol->key,
                                       NULL, NULL);
1476
            }
1477
        }
1478
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1479 1480
    }

1481
    if (!ret)
1482
        virReportError(VIR_ERR_NO_STORAGE_VOL,
1483
                       _("no storage vol with matching key %s"), key);
1484

1485
 cleanup:
1486
    storageDriverUnlock();
1487
    return ret;
1488 1489 1490
}

static virStorageVolPtr
1491
storageVolLookupByPath(virConnectPtr conn,
1492 1493
                       const char *path)
{
1494
    size_t i;
1495
    virStorageVolPtr ret = NULL;
1496 1497 1498 1499 1500
    char *cleanpath;

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

1502
    storageDriverLock();
1503
    for (i = 0; i < driver->pools.count && !ret; i++) {
1504 1505 1506 1507 1508
        virStoragePoolObjPtr pool = driver->pools.objs[i];
        virStorageVolDefPtr vol;
        char *stable_path = NULL;

        virStoragePoolObjLock(pool);
1509

1510 1511 1512 1513
        if (!virStoragePoolObjIsActive(pool)) {
           virStoragePoolObjUnlock(pool);
           continue;
        }
1514

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

1550 1551 1552 1553 1554 1555 1556
        vol = virStorageVolDefFindByPath(pool, stable_path);
        VIR_FREE(stable_path);

        if (vol) {
            if (virStorageVolLookupByPathEnsureACL(conn, pool->def, vol) < 0) {
                virStoragePoolObjUnlock(pool);
                goto cleanup;
1557
            }
1558 1559 1560 1561

            ret = virGetStorageVol(conn, pool->def->name,
                                   vol->name, vol->key,
                                   NULL, NULL);
1562
        }
1563 1564

        virStoragePoolObjUnlock(pool);
1565 1566
    }

1567 1568 1569 1570 1571 1572 1573 1574 1575 1576
    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);
        }
    }
1577

1578
 cleanup:
1579
    VIR_FREE(cleanpath);
1580
    storageDriverUnlock();
1581
    return ret;
1582 1583
}

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

1626

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648
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
1649 1650
     * in this module since the allocation/available weren't adjusted yet.
     * Ignore the disk backend since it updates the pool values.
1651 1652
     */
    if (updateMeta) {
1653 1654 1655 1656
        if (pool->def->type != VIR_STORAGE_POOL_DISK) {
            pool->def->allocation -= vol->target.allocation;
            pool->def->available += vol->target.allocation;
        }
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
    }

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


1676 1677 1678 1679
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1680 1681
{
    virStorageVolDefPtr vol = NULL;
1682 1683

    *pool = NULL;
1684

1685
    storageDriverLock();
1686
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1687
    storageDriverUnlock();
1688

1689
    if (!*pool) {
1690 1691 1692
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1693
        return NULL;
1694 1695
    }

1696
    if (!virStoragePoolObjIsActive(*pool)) {
1697
        virReportError(VIR_ERR_OPERATION_INVALID,
1698 1699 1700
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1701 1702
    }

1703
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1704 1705 1706
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1707
        goto error;
1708 1709
    }

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
    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;

1737 1738 1739
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1740 1741 1742 1743 1744 1745 1746
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1747 1748 1749 1750 1751 1752 1753
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1754
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1755 1756 1757 1758
        goto cleanup;

    ret = 0;

1759
 cleanup:
1760
    virStoragePoolObjUnlock(pool);
1761 1762 1763
    return ret;
}

1764

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

1776
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1777

1778 1779
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1780 1781

    if (!virStoragePoolObjIsActive(pool)) {
1782
        virReportError(VIR_ERR_OPERATION_INVALID,
1783
                       _("storage pool '%s' is not active"), pool->def->name);
1784
        goto cleanup;
1785 1786 1787
    }

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

1790 1791
    voldef = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_OPT_CAPACITY);
1792
    if (voldef == NULL)
1793
        goto cleanup;
1794

1795 1796 1797 1798 1799 1800 1801
    if (!voldef->target.capacity && !backend->buildVol) {
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("volume capacity required for this "
                               "storage pool"));
        goto cleanup;
    }

1802 1803 1804
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1805
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1806
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1807
                       _("'%s'"), voldef->name);
1808
        goto cleanup;
1809 1810
    }

1811
    if (VIR_REALLOC_N(pool->volumes.objs,
1812
                      pool->volumes.count+1) < 0)
1813
        goto cleanup;
1814

1815
    if (!backend->createVol) {
1816 1817 1818
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1819
        goto cleanup;
1820 1821
    }

1822 1823 1824
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1825
    if (backend->createVol(obj->conn, pool, voldef) < 0)
1826
        goto cleanup;
1827

1828 1829
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
1830
                              voldef->key, NULL, NULL);
1831 1832 1833 1834
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1835

1836 1837 1838 1839
    if (VIR_ALLOC(buildvoldef) < 0) {
        voldef = NULL;
        goto cleanup;
    }
1840

1841 1842 1843 1844 1845
    /* 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));
1846

1847 1848
    if (backend->buildVol) {
        int buildret;
1849 1850 1851

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1852
        voldef->building = true;
1853 1854
        virStoragePoolObjUnlock(pool);

1855
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1856

1857
        storageDriverLock();
1858
        virStoragePoolObjLock(pool);
1859
        storageDriverUnlock();
1860

1861
        voldef->building = false;
1862 1863 1864
        pool->asyncjobs--;

        if (buildret < 0) {
1865 1866
            VIR_FREE(buildvoldef);
            storageVolDeleteInternal(volobj, backend, pool, voldef,
1867
                                     0, false);
1868
            voldef = NULL;
1869 1870 1871 1872 1873
            goto cleanup;
        }

    }

1874 1875 1876 1877
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, voldef) < 0)
        goto cleanup;

1878 1879 1880 1881 1882 1883 1884
    /* Update pool metadata ignoring the disk backend since
     * it updates the pool values.
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
        pool->def->allocation += buildvoldef->target.allocation;
        pool->def->available -= buildvoldef->target.allocation;
    }
1885

1886
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1887
             volobj->name, pool->def->name);
1888 1889 1890
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1891

1892
 cleanup:
1893
    virObjectUnref(volobj);
1894
    virStorageVolDefFree(voldef);
1895
    VIR_FREE(buildvoldef);
1896 1897
    if (pool)
        virStoragePoolObjUnlock(pool);
1898
    return ret;
1899 1900
}

1901
static virStorageVolPtr
1902 1903 1904 1905
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1906
{
1907 1908 1909 1910
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
    virStorageVolDefPtr origvol = NULL, newvol = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
O
Osier Yang 已提交
1911
    unsigned long long allocation;
1912
    int buildret;
1913

1914 1915 1916
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA |
                  VIR_STORAGE_VOL_CREATE_REFLINK,
                  NULL);
E
Eric Blake 已提交
1917

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

1935
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1936 1937 1938
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1939 1940 1941 1942
        goto cleanup;
    }

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

1948
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1949
        virReportError(VIR_ERR_OPERATION_INVALID,
1950 1951
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1952 1953 1954 1955 1956 1957
        goto cleanup;
    }

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

1958 1959
    origvol = virStorageVolDefFindByName(origpool ?
                                         origpool : pool, vobj->name);
1960
    if (!origvol) {
1961 1962 1963
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1964 1965 1966
        goto cleanup;
    }

1967 1968
    newvol = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_NO_CAPACITY);
1969 1970 1971
    if (newvol == NULL)
        goto cleanup;

1972 1973 1974
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1975
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1976 1977 1978
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1979 1980 1981
        goto cleanup;
    }

1982 1983
    /* Use the original volume's capacity in case the new capacity
     * is less than that, or it was omitted */
1984 1985
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
1986

1987 1988
    /* Make sure allocation is at least as large as the destination cap,
     * to make absolutely sure we copy all possible contents */
1989 1990
    if (newvol->target.allocation < origvol->target.capacity)
        newvol->target.allocation = origvol->target.capacity;
1991

1992
    if (!backend->buildVolFrom) {
1993
        virReportError(VIR_ERR_NO_SUPPORT,
1994 1995
                       "%s", _("storage pool does not support"
                               " volume creation from an existing volume"));
1996 1997 1998 1999
        goto cleanup;
    }

    if (origvol->building) {
2000 2001 2002
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
2003 2004 2005 2006 2007 2008 2009 2010
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
2011
                      pool->volumes.count+1) < 0)
2012 2013
        goto cleanup;

2014 2015 2016 2017
    /* '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);
2018
    if (backend->createVol(obj->conn, pool, newvol) < 0)
2019 2020 2021 2022
        goto cleanup;

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

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

2035
    if (origpool) {
2036 2037 2038 2039
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

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

2042
    storageDriverLock();
2043
    virStoragePoolObjLock(pool);
2044
    if (origpool)
2045
        virStoragePoolObjLock(origpool);
2046
    storageDriverUnlock();
2047

2048
    origvol->in_use--;
2049
    newvol->building = false;
2050
    allocation = newvol->target.allocation;
2051 2052
    pool->asyncjobs--;

2053
    if (origpool) {
2054 2055 2056 2057 2058 2059
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
2060 2061
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
2062 2063
        goto cleanup;
    }
2064
    newvol = NULL;
2065

2066 2067 2068 2069 2070 2071 2072
    /* Updating pool metadata ignoring the disk backend since
     * it updates the pool values
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
        pool->def->allocation += allocation;
        pool->def->available -= allocation;
    }
2073

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

2079
 cleanup:
2080
    virObjectUnref(volobj);
2081 2082 2083
    virStorageVolDefFree(newvol);
    if (pool)
        virStoragePoolObjUnlock(pool);
2084
    if (origpool)
2085 2086 2087 2088
        virStoragePoolObjUnlock(origpool);
    return ret;
}

2089

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

    virCheckFlags(0, -1);

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

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

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

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

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

2126
 cleanup:
2127
    virStoragePoolObjUnlock(pool);
2128 2129 2130 2131 2132

    return ret;
}


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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

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

    return ret;
}

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

2291
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2292 2293
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2294

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

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

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

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

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

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

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

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

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

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

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

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

O
Osier Yang 已提交
2370
    ret = 0;
2371

2372
 cleanup:
2373
    virStoragePoolObjUnlock(pool);
2374 2375 2376

    return ret;
}
2377

2378 2379

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

2389
    virCheckFlags(0, -1);
2390

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

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


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

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

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

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

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

2427
 cleanup:
2428
    virStoragePoolObjUnlock(pool);
2429 2430 2431 2432

    return ret;
}

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

2440 2441

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

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

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

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

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

2466
 cleanup:
2467
    virStoragePoolObjUnlock(pool);
2468
    return ret;
2469 2470 2471
}

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

E
Eric Blake 已提交
2480 2481
    virCheckFlags(0, NULL);

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

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

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

2492
    ret = virStorageVolDefFormat(pool->def, vol);
2493

2494
 cleanup:
2495
    virStoragePoolObjUnlock(pool);
2496

2497
    return ret;
2498 2499 2500
}

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

2507 2508
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2509

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

2513
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2514

2515
 cleanup:
2516
    virStoragePoolObjUnlock(pool);
2517 2518 2519
    return ret;
}

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

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2529 2530 2531
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

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

2538
 cleanup:
2539 2540 2541
    return ret;
}

2542

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

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

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2587 2588 2589 2590
};


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

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


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

2615 2616 2617 2618

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

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

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

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

2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651

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

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

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

    return !!backend->storageFileChown;
}


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

2678 2679 2680
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2681

2682
    VIR_FREE(src->drv);
2683 2684 2685
}


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

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

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

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

2725
    return 0;
2726

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


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


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

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

2765 2766 2767 2768 2769 2770
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2771 2772 2773 2774 2775 2776
}


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

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

2795 2796 2797 2798 2799 2800
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2801 2802 2803 2804 2805 2806
}


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

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

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

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

    return ret;
2831
}
2832 2833 2834 2835 2836 2837 2838 2839 2840 2841


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


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


/**
 * 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);
}
2927 2928


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

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

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


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

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

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

    if (virStorageFileInitAs(src, uid, gid) < 0)
2983
        return -1;
2984

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

3000 3001 3002
        goto cleanup;
    }

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

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

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

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

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

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

    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;

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

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

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

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

    virHashTablePtr cycle = NULL;
    int ret = -1;

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

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

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

    virHashFree(cycle);
    return ret;
}
3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316


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;

3317 3318
           if (virStorageTranslateDiskSourcePoolAuth(def,
                                                     &pooldef->source) < 0)
3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340
               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:
3341
    virObjectUnref(pool);
3342
    virObjectUnref(vol);
3343 3344 3345 3346
    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}