storage_driver.c 94.0 KB
Newer Older
1 2 3
/*
 * storage_driver.c: core driver for storage APIs
 *
4
 * Copyright (C) 2006-2015 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2006-2008 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23 24 25 26 27 28
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

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

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

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

54 55
#define VIR_FROM_THIS VIR_FROM_STORAGE

56 57
VIR_LOG_INIT("storage.storage_driver");

58
static virStorageDriverStatePtr driver;
59

60
static int storageStateCleanup(void);
61

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

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

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

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

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

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

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

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

133 134 135
    return;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

279 280
    storagePoolUpdateAllState();

281
    storageDriverUnlock();
282 283 284 285 286 287

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

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

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

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

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

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

    return 0;
}


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

347
    storageDriverLock();
348 349

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

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

    return 0;
}



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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    return nactive;
471 472 473
}

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

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

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

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

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

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

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

    return nactive;
530 531 532
}

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

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

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

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

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

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

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

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

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

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

603
 cleanup:
604
    return ret;
605 606 607
}


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

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

    return ret;
}


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

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

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

638 639
    ret = virStoragePoolObjIsActive(obj);

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

J
John Ferlan 已提交
884
    pool->active = true;
885
    ret = 0;
886

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

    unlink(stateFile);
    VIR_FREE(stateFile);

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

    virStoragePoolObjClearVols(pool);

J
John Ferlan 已提交
981
    pool->active = false;
982

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

992
    ret = 0;
993

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

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

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

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

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

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

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

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

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

    unlink(stateFile);
    VIR_FREE(stateFile);

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

1051
    ret = 0;
1052

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


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

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

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

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

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

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

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

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

J
John Ferlan 已提交
1103
        pool->active = false;
1104

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

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


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

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

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

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

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

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

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

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

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

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

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

    ret = virStoragePoolDefFormat(def);
1174

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

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

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    virCheckFlags(0, -1);

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

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

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

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

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

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

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

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

1402
    virStoragePoolObjUnlock(obj);
1403 1404 1405

    return ret;
}
1406 1407

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

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

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

    vol = virStorageVolDefFindByName(pool, name);

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

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

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

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


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

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

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

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

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

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

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

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

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

        virStoragePoolObjLock(pool);
1504

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

1510
        switch ((virStoragePoolType) pool->def->type) {
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
            case VIR_STORAGE_POOL_DIR:
            case VIR_STORAGE_POOL_FS:
            case VIR_STORAGE_POOL_NETFS:
            case VIR_STORAGE_POOL_LOGICAL:
            case VIR_STORAGE_POOL_DISK:
            case VIR_STORAGE_POOL_ISCSI:
            case VIR_STORAGE_POOL_SCSI:
            case VIR_STORAGE_POOL_MPATH:
                stable_path = virStorageBackendStablePath(pool,
                                                          cleanpath,
                                                          false);
                if (stable_path == NULL) {
                    /* Don't break the whole lookup process if it fails on
                     * getting the stable path for some of the pools.
                     */
                    VIR_WARN("Failed to get stable path for pool '%s'",
                             pool->def->name);
                    virStoragePoolObjUnlock(pool);
                    continue;
                }
                break;

            case VIR_STORAGE_POOL_GLUSTER:
            case VIR_STORAGE_POOL_RBD:
            case VIR_STORAGE_POOL_SHEEPDOG:
R
Roman Bogorodskiy 已提交
1536
            case VIR_STORAGE_POOL_ZFS:
1537 1538 1539
            case VIR_STORAGE_POOL_LAST:
                if (VIR_STRDUP(stable_path, path) < 0) {
                     virStoragePoolObjUnlock(pool);
1540
                    goto cleanup;
1541
                }
1542 1543
                break;
        }
1544

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

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

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

        virStoragePoolObjUnlock(pool);
1560 1561
    }

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
    if (!ret) {
        if (STREQ(path, cleanpath)) {
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("no storage vol with matching path '%s'"), path);
        } else {
            virReportError(VIR_ERR_NO_STORAGE_VOL,
                           _("no storage vol with matching path '%s' (%s)"),
                           path, cleanpath);
        }
    }
1572

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

1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
virStoragePoolPtr
storagePoolLookupByTargetPath(virConnectPtr conn,
                              const char *path)
{
    size_t i;
    virStoragePoolPtr ret = NULL;
    char *cleanpath;

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

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

        virStoragePoolObjLock(pool);

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

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

        virStoragePoolObjUnlock(pool);
    }
    storageDriverUnlock();

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

    VIR_FREE(cleanpath);
    return ret;
}

1621

1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
static void
storageVolRemoveFromPool(virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol)
{
    size_t i;

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

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


1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
static int
storageVolDeleteInternal(virStorageVolPtr obj,
                         virStorageBackendPtr backend,
                         virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol,
                         unsigned int flags,
                         bool updateMeta)
{
    int ret = -1;

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

        goto cleanup;
    }

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

    /* Update pool metadata - don't update meta data from error paths
1662 1663
     * in this module since the allocation/available weren't adjusted yet.
     * Ignore the disk backend since it updates the pool values.
1664 1665
     */
    if (updateMeta) {
1666 1667 1668 1669
        if (pool->def->type != VIR_STORAGE_POOL_DISK) {
            pool->def->allocation -= vol->target.allocation;
            pool->def->available += vol->target.allocation;
        }
1670 1671
    }

1672
    storageVolRemoveFromPool(pool, vol);
1673 1674 1675 1676 1677 1678 1679
    ret = 0;

 cleanup:
    return ret;
}


1680 1681 1682 1683
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1684 1685
{
    virStorageVolDefPtr vol = NULL;
1686 1687

    *pool = NULL;
1688

1689
    storageDriverLock();
1690
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1691
    storageDriverUnlock();
1692

1693
    if (!*pool) {
1694 1695 1696
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1697
        return NULL;
1698 1699
    }

1700
    if (!virStoragePoolObjIsActive(*pool)) {
1701
        virReportError(VIR_ERR_OPERATION_INVALID,
1702 1703 1704
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1705 1706
    }

1707
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1708 1709 1710
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1711
        goto error;
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 1737 1738 1739 1740
    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;

1741 1742 1743
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1744 1745 1746 1747 1748 1749 1750
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1751 1752 1753 1754 1755 1756 1757
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1758
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1759 1760 1761 1762
        goto cleanup;

    ret = 0;

1763
 cleanup:
1764
    virStoragePoolObjUnlock(pool);
1765 1766 1767
    return ret;
}

1768

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

1779
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1780

1781 1782
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1783 1784

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

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

1793 1794
    voldef = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_OPT_CAPACITY);
1795
    if (voldef == NULL)
1796
        goto cleanup;
1797

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

1805 1806 1807
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

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

1814 1815 1816
    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count+1) < 0)
        goto cleanup;
1817

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

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

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

1839

1840 1841
    if (backend->buildVol) {
        int buildret;
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853
        virStorageVolDefPtr buildvoldef = NULL;

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

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

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1857
        voldef->building = true;
1858 1859
        virStoragePoolObjUnlock(pool);

1860
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1861

1862 1863
        VIR_FREE(buildvoldef);

1864
        storageDriverLock();
1865
        virStoragePoolObjLock(pool);
1866
        storageDriverUnlock();
1867

1868
        voldef->building = false;
1869 1870
        pool->asyncjobs--;

1871
        if (buildret < 0) {
1872 1873
            /* buildVol handles deleting volume on failure */
            storageVolRemoveFromPool(pool, voldef);
1874
            voldef = NULL;
1875
            goto cleanup;
1876
        }
1877

1878
    }
1879

1880
    if (backend->refreshVol &&
1881 1882 1883 1884
        backend->refreshVol(obj->conn, pool, voldef) < 0) {
        storageVolDeleteInternal(volobj, backend, pool, voldef,
                                 0, false);
        voldef = NULL;
1885
        goto cleanup;
1886
    }
1887

1888 1889 1890 1891
    /* Update pool metadata ignoring the disk backend since
     * it updates the pool values.
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
1892 1893
        pool->def->allocation += voldef->target.allocation;
        pool->def->available -= voldef->target.allocation;
1894
    }
1895

1896
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1897
             volobj->name, pool->def->name);
1898 1899 1900
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1901

1902
 cleanup:
1903
    virObjectUnref(volobj);
1904
    virStorageVolDefFree(voldef);
1905 1906
    if (pool)
        virStoragePoolObjUnlock(pool);
1907
    return ret;
1908 1909
}

1910
static virStorageVolPtr
1911 1912 1913 1914
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1915
{
1916 1917
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
1918
    virStorageVolDefPtr origvol = NULL, newvol = NULL, shadowvol = NULL;
1919
    virStorageVolPtr ret = NULL, volobj = NULL;
1920
    int buildret;
1921

1922 1923 1924
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA |
                  VIR_STORAGE_VOL_CREATE_REFLINK,
                  NULL);
E
Eric Blake 已提交
1925

1926
    storageDriverLock();
1927
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1928
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1929
        virStoragePoolObjUnlock(pool);
1930
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1931
        virStoragePoolObjLock(pool);
1932
    }
1933
    storageDriverUnlock();
1934
    if (!pool) {
1935 1936
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1937
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1938 1939
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1940 1941 1942
        goto cleanup;
    }

1943
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1944 1945 1946
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1947 1948 1949 1950
        goto cleanup;
    }

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

1956
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1957
        virReportError(VIR_ERR_OPERATION_INVALID,
1958 1959
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1960 1961 1962 1963 1964 1965
        goto cleanup;
    }

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

1966 1967
    origvol = virStorageVolDefFindByName(origpool ?
                                         origpool : pool, vobj->name);
1968
    if (!origvol) {
1969 1970 1971
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1972 1973 1974
        goto cleanup;
    }

1975 1976
    newvol = virStorageVolDefParseString(pool->def, xmldesc,
                                         VIR_VOL_XML_PARSE_NO_CAPACITY);
1977 1978 1979
    if (newvol == NULL)
        goto cleanup;

1980 1981 1982
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1983
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1984 1985 1986
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1987 1988 1989
        goto cleanup;
    }

1990 1991
    /* Use the original volume's capacity in case the new capacity
     * is less than that, or it was omitted */
1992 1993
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
1994 1995

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

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

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

    if (VIR_REALLOC_N(pool->volumes.objs,
2014
                      pool->volumes.count+1) < 0)
2015 2016
        goto cleanup;

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

2024 2025 2026 2027 2028 2029 2030 2031 2032
    /* Make a shallow copy of the 'defined' volume definition, since the
     * original allocation value will change as the user polls 'info',
     * but we only need the initial requested values
     */
    if (VIR_ALLOC(shadowvol) < 0)
        goto cleanup;

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

2033 2034
    pool->volumes.objs[pool->volumes.count++] = newvol;
    volobj = virGetStorageVol(obj->conn, pool->def->name, newvol->name,
2035
                              newvol->key, NULL, NULL);
2036 2037 2038 2039
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
2040 2041 2042

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
2043
    newvol->building = true;
2044
    origvol->in_use++;
2045 2046
    virStoragePoolObjUnlock(pool);

2047
    if (origpool) {
2048 2049 2050 2051
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

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

2054
    storageDriverLock();
2055
    virStoragePoolObjLock(pool);
2056
    if (origpool)
2057
        virStoragePoolObjLock(origpool);
2058
    storageDriverUnlock();
2059

2060
    origvol->in_use--;
2061
    newvol->building = false;
2062 2063
    pool->asyncjobs--;

2064
    if (origpool) {
2065 2066 2067 2068 2069
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

2070 2071 2072
    if (buildret < 0 ||
        (backend->refreshVol &&
         backend->refreshVol(obj->conn, pool, newvol) < 0)) {
2073 2074
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
2075 2076 2077
        goto cleanup;
    }

2078 2079 2080 2081
    /* Updating pool metadata ignoring the disk backend since
     * it updates the pool values
     */
    if (pool->def->type != VIR_STORAGE_POOL_DISK) {
2082 2083
        pool->def->allocation += newvol->target.allocation;
        pool->def->available -= newvol->target.allocation;
2084
    }
2085

2086
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
2087
             volobj->name, pool->def->name);
2088 2089
    ret = volobj;
    volobj = NULL;
2090
    newvol = NULL;
2091

2092
 cleanup:
2093
    virObjectUnref(volobj);
2094
    virStorageVolDefFree(newvol);
2095
    VIR_FREE(shadowvol);
2096 2097
    if (pool)
        virStoragePoolObjUnlock(pool);
2098
    if (origpool)
2099 2100 2101 2102
        virStoragePoolObjUnlock(origpool);
    return ret;
}

2103

2104
static int
2105 2106 2107 2108 2109
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
2110
{
2111
    virStorageBackendPtr backend;
2112 2113 2114 2115 2116 2117
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

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

2121
    if (virStorageVolDownloadEnsureACL(obj->conn, pool->def, vol) < 0)
2122
        goto cleanup;
2123

2124
    if (vol->building) {
2125 2126 2127
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2128
        goto cleanup;
2129 2130
    }

2131 2132 2133
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
2134
        goto cleanup;
2135
    }
2136

2137 2138
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
2139

2140
 cleanup:
2141
    virStoragePoolObjUnlock(pool);
2142 2143 2144 2145 2146

    return ret;
}


2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
/**
 * 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;

2175 2176
    storageDriverLock();
    if (!(pool = virStoragePoolObjFindByName(&driver->pools,
2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189
                                             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);
2190
    storageDriverUnlock();
2191 2192 2193 2194 2195 2196 2197 2198
    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 已提交
2199
 * @opaque Buffer to hold the pool name to be refreshed
2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
 */
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);
}

2219
static int
2220 2221 2222 2223 2224
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2225
{
2226
    virStorageBackendPtr backend;
2227 2228
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2229
    virStorageVolStreamInfoPtr cbdata = NULL;
2230 2231 2232 2233
    int ret = -1;

    virCheckFlags(0, -1);

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

2237
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2238
        goto cleanup;
2239

2240 2241 2242 2243 2244 2245 2246
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2247
    if (vol->building) {
2248 2249 2250
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2251
        goto cleanup;
2252 2253
    }

2254 2255 2256
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2257
        goto cleanup;
2258
    }
2259

2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
    /* 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;
    }

2272 2273 2274
    if ((ret = backend->uploadVol(obj->conn, pool, vol, stream,
                                  offset, length, flags)) < 0)
        goto cleanup;
2275

2276 2277 2278 2279 2280 2281 2282 2283 2284 2285
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

2286
 cleanup:
2287
    virStoragePoolObjUnlock(pool);
2288 2289
    if (cbdata)
        virStorageVolPoolRefreshDataFree(cbdata);
2290 2291 2292 2293

    return ret;
}

2294
static int
2295 2296 2297
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2298 2299 2300 2301
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2302
    unsigned long long abs_capacity, delta = 0;
2303 2304
    int ret = -1;

2305
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2306 2307
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2308

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

2312
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2313
        goto cleanup;
2314

2315 2316 2317 2318 2319 2320 2321
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2322
    if (vol->building) {
2323 2324 2325
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2326
        goto cleanup;
2327
    }
2328

2329
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2330 2331 2332 2333
        if (flags & VIR_STORAGE_VOL_RESIZE_SHRINK)
            abs_capacity = vol->target.capacity - MIN(capacity, vol->target.capacity);
        else
            abs_capacity = vol->target.capacity + capacity;
2334 2335 2336 2337 2338
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2339
    if (abs_capacity < vol->target.allocation) {
2340
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2341 2342
                       _("can't shrink capacity below "
                         "existing allocation"));
2343
        goto cleanup;
2344 2345
    }

2346
    if (abs_capacity < vol->target.capacity &&
2347 2348 2349
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
2350
                         "capacity unless shrink flag explicitly specified"));
2351
        goto cleanup;
2352 2353
    }

2354
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE)
2355 2356
        delta = abs_capacity - vol->target.allocation;

2357
    if (delta > pool->def->available) {
2358
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2359
                       _("Not enough space left in storage pool"));
2360
        goto cleanup;
2361 2362 2363
    }

    if (!backend->resizeVol) {
2364
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2365 2366
                       _("storage pool does not support changing of "
                         "volume capacity"));
2367
        goto cleanup;
2368 2369 2370
    }

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

2373
    vol->target.capacity = abs_capacity;
2374 2375 2376 2377 2378
    /* 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) {
2379
        vol->target.allocation = abs_capacity;
2380 2381
        pool->def->allocation += delta;
        pool->def->available -= delta;
2382
    }
2383

O
Osier Yang 已提交
2384
    ret = 0;
2385

2386
 cleanup:
2387
    virStoragePoolObjUnlock(pool);
2388 2389 2390

    return ret;
}
2391

2392 2393

static int
2394 2395 2396
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2397
{
2398
    virStorageBackendPtr backend;
2399 2400 2401 2402
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2403
    virCheckFlags(0, -1);
2404

2405
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2406 2407 2408
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2409 2410 2411
        return -1;
    }

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


2416
    if (virStorageVolWipePatternEnsureACL(obj->conn, pool->def, vol) < 0)
2417
        goto cleanup;
2418

2419 2420 2421 2422 2423 2424 2425
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2426
    if (vol->building) {
2427 2428 2429
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2430
        goto cleanup;
2431 2432
    }

2433 2434 2435
    if (!backend->wipeVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume wiping"));
2436
        goto cleanup;
2437
    }
2438

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

2441
 cleanup:
2442
    virStoragePoolObjUnlock(pool);
2443 2444 2445 2446

    return ret;
}

2447
static int
2448 2449
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2450
{
2451
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2452 2453
}

2454 2455

static int
2456
storageVolGetInfo(virStorageVolPtr obj,
2457 2458
                  virStorageVolInfoPtr info)
{
2459
    virStoragePoolObjPtr pool;
2460 2461
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2462
    int ret = -1;
2463

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

2467 2468 2469
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2470 2471
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2472
        goto cleanup;
2473 2474

    memset(info, 0, sizeof(*info));
2475
    info->type = vol->type;
2476 2477
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2478
    ret = 0;
2479

2480
 cleanup:
2481
    virStoragePoolObjUnlock(pool);
2482
    return ret;
2483 2484 2485
}

static char *
2486 2487
storageVolGetXMLDesc(virStorageVolPtr obj,
                     unsigned int flags)
E
Eric Blake 已提交
2488
{
2489
    virStoragePoolObjPtr pool;
2490 2491
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2492
    char *ret = NULL;
2493

E
Eric Blake 已提交
2494 2495
    virCheckFlags(0, NULL);

2496 2497
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return NULL;
2498

2499 2500 2501
    if (virStorageVolGetXMLDescEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

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

2506
    ret = virStorageVolDefFormat(pool->def, vol);
2507

2508
 cleanup:
2509
    virStoragePoolObjUnlock(pool);
2510

2511
    return ret;
2512 2513 2514
}

static char *
2515 2516
storageVolGetPath(virStorageVolPtr obj)
{
2517
    virStoragePoolObjPtr pool;
2518
    virStorageVolDefPtr vol;
2519
    char *ret = NULL;
2520

2521 2522
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2523

2524 2525 2526
    if (virStorageVolGetPathEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2527
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2528

2529
 cleanup:
2530
    virStoragePoolObjUnlock(pool);
2531 2532 2533
    return ret;
}

2534
static int
2535 2536 2537
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2538 2539 2540 2541 2542
{
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2543 2544 2545
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2546
    storageDriverLock();
2547
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
2548 2549
                                      virConnectListAllStoragePoolsCheckACL,
                                      flags);
2550
    storageDriverUnlock();
2551

2552
 cleanup:
2553 2554 2555
    return ret;
}

2556

2557
static virStorageDriver storageDriver = {
2558
    .name = "storage",
2559 2560 2561 2562 2563 2564
    .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 */
2565 2566 2567
    .storagePoolLookupByName = storagePoolLookupByName, /* 0.4.0 */
    .storagePoolLookupByUUID = storagePoolLookupByUUID, /* 0.4.0 */
    .storagePoolLookupByVolume = storagePoolLookupByVolume, /* 0.4.0 */
2568 2569
    .storagePoolCreateXML = storagePoolCreateXML, /* 0.4.0 */
    .storagePoolDefineXML = storagePoolDefineXML, /* 0.4.0 */
2570 2571
    .storagePoolBuild = storagePoolBuild, /* 0.4.0 */
    .storagePoolUndefine = storagePoolUndefine, /* 0.4.0 */
2572
    .storagePoolCreate = storagePoolCreate, /* 0.4.0 */
2573 2574 2575 2576 2577 2578 2579
    .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 */
2580
    .storagePoolNumOfVolumes = storagePoolNumOfVolumes, /* 0.4.0 */
2581 2582 2583
    .storagePoolListVolumes = storagePoolListVolumes, /* 0.4.0 */
    .storagePoolListAllVolumes = storagePoolListAllVolumes, /* 0.10.2 */

2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
    .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 */
2598 2599 2600

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2601 2602 2603 2604
};


static virStateDriver stateDriver = {
2605
    .name = "storage",
2606
    .stateInitialize = storageStateInitialize,
2607
    .stateAutoStart = storageStateAutoStart,
2608 2609
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2610 2611
};

2612 2613
int storageRegister(void)
{
2614
    if (virSetSharedStorageDriver(&storageDriver) < 0)
2615
        return -1;
2616 2617
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2618 2619
    return 0;
}
2620 2621 2622


/* ----------- file handlers cooperating with storage driver --------------- */
2623 2624 2625
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2626
    return src && src->drv;
2627 2628
}

2629 2630 2631 2632

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2633
    int actualType;
2634 2635 2636 2637
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2638
    actualType = virStorageSourceGetActualType(src);
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653

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

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

2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665

/**
 * 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)
{
2666
    int actualType;
2667 2668 2669 2670
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2671
    actualType = virStorageSourceGetActualType(src);
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685

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

    return !!backend->storageFileChown;
}


2686
void
2687
virStorageFileDeinit(virStorageSourcePtr src)
2688
{
2689
    if (!virStorageFileIsInitialized(src))
2690 2691
        return;

2692 2693 2694
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2695

2696
    VIR_FREE(src->drv);
2697 2698 2699
}


2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712
/**
 * 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.
 */
2713
int
2714 2715
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
2716
{
2717 2718 2719
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;
2720

2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
    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;

2731 2732
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2733 2734
        goto error;

2735 2736
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2737 2738
        goto error;

2739
    return 0;
2740

2741
 error:
2742 2743
    VIR_FREE(src->drv);
    return -1;
2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
2757 2758 2759 2760 2761 2762
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
2763
 * @src: file structure pointing to the file
2764 2765 2766 2767 2768
 *
 * 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
2769
virStorageFileCreate(virStorageSourcePtr src)
2770
{
2771 2772
    int ret;

2773 2774
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2775 2776 2777 2778
        errno = ENOSYS;
        return -2;
    }

2779 2780 2781 2782 2783 2784
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2785 2786 2787 2788 2789 2790
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
2791
 * @src: file structure pointing to the file
2792 2793 2794 2795 2796 2797 2798
 *
 * 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
2799
virStorageFileUnlink(virStorageSourcePtr src)
2800
{
2801 2802
    int ret;

2803 2804
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2805 2806 2807 2808
        errno = ENOSYS;
        return -2;
    }

2809 2810 2811 2812 2813 2814
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2815 2816 2817 2818 2819 2820
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
2821
 * @src: file structure pointing to the file
2822 2823 2824 2825 2826 2827
 * @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
2828
virStorageFileStat(virStorageSourcePtr src,
2829 2830
                   struct stat *st)
{
2831 2832
    int ret;

2833 2834
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2835 2836 2837 2838
        errno = ENOSYS;
        return -2;
    }

2839 2840 2841 2842 2843 2844
    ret = src->drv->backend->storageFileStat(src, st);

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

    return ret;
2845
}
2846 2847 2848 2849 2850 2851 2852 2853 2854 2855


/**
 * 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
2856 2857
 * function isn't supported by the backend.
 * Libvirt error is reported on failure.
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874
 */
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 "
2875
                         "storage type %s (protocol: %s)"),
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886
                       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;
}
2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916


/*
 * 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);
}
2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940


/**
 * 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);
}
2941 2942


2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964
/**
 * 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;
    }

2965 2966
    VIR_DEBUG("chown of storage file %p to %u:%u",
              src, (unsigned int)uid, (unsigned int)gid);
2967 2968 2969 2970 2971

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


2972 2973 2974
/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
2975
                                 virStorageSourcePtr parent,
2976 2977
                                 uid_t uid, gid_t gid,
                                 bool allow_probe,
2978
                                 bool report_broken,
2979 2980 2981
                                 virHashTablePtr cycle)
{
    int ret = -1;
2982
    const char *uniqueName;
2983 2984
    char *buf = NULL;
    ssize_t headerLen;
2985 2986 2987
    virStorageSourcePtr backingStore = NULL;
    int backingFormat;

2988
    VIR_DEBUG("path=%s format=%d uid=%u gid=%u probe=%d",
2989
              src->path, src->format,
2990
              (unsigned int)uid, (unsigned int)gid, allow_probe);
2991

2992 2993 2994 2995 2996
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
2997
        return -1;
2998

2999
    if (virStorageFileAccess(src, F_OK) < 0) {
3000 3001 3002
        if (src == parent) {
            virReportSystemError(errno,
                                 _("Cannot access storage file '%s' "
3003 3004 3005
                                   "(as uid:%u, gid:%u)"),
                                 src->path, (unsigned int)uid,
                                 (unsigned int)gid);
3006 3007 3008
        } else {
            virReportSystemError(errno,
                                 _("Cannot access backing file '%s' "
3009 3010 3011
                                   "of storage file '%s' (as uid:%u, gid:%u)"),
                                 src->path, parent->path,
                                 (unsigned int)uid, (unsigned int)gid);
3012 3013
        }

3014 3015 3016
        goto cleanup;
    }

3017 3018 3019 3020 3021 3022 3023 3024
    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;
3025 3026
    }

3027 3028
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
3029

3030 3031 3032
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
3033

3034 3035
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
3036
        goto cleanup;
3037 3038

    /* check whether we need to go deeper */
3039 3040 3041 3042
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
3043

3044
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
3045
        goto cleanup;
3046 3047 3048 3049 3050 3051 3052 3053

    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;

3054
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
3055 3056 3057 3058 3059 3060
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

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

 cleanup:
3072
    VIR_FREE(buf);
3073
    virStorageFileDeinit(src);
3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
    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.
 *
3094 3095 3096
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
3097 3098 3099 3100 3101
 * Caller MUST free result after use via virStorageSourceFree.
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
3102 3103
                          bool allow_probe,
                          bool report_broken)
3104
{
3105 3106
    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,
3107
              allow_probe, report_broken);
3108 3109 3110 3111 3112 3113 3114 3115

    virHashTablePtr cycle = NULL;
    int ret = -1;

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

    if (src->format <= VIR_STORAGE_FILE_NONE)
3116 3117
        src->format = allow_probe ?
            VIR_STORAGE_FILE_AUTO : VIR_STORAGE_FILE_RAW;
3118

3119
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
3120
                                           allow_probe, report_broken, cycle);
3121 3122 3123 3124

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


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;
3203 3204
    /* A <disk> doesn't use <auth type='%s', so clear that out for the disk */
    def->src->auth->authType = VIR_STORAGE_AUTH_TYPE_NONE;
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 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
    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;

3333 3334
           if (virStorageTranslateDiskSourcePoolAuth(def,
                                                     &pooldef->source) < 0)
3335 3336
               goto cleanup;

3337 3338 3339 3340 3341 3342 3343 3344 3345 3346
           /* Source pool may not fill in the secrettype field,
            * so we need to do so here
            */
           if (def->src->auth && !def->src->auth->secrettype) {
               const char *secrettype =
                   virSecretUsageTypeToString(VIR_SECRET_USAGE_TYPE_ISCSI);
               if (VIR_STRDUP(def->src->auth->secrettype, secrettype) < 0)
                   goto cleanup;
           }

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
           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:
3367
    virObjectUnref(pool);
3368
    virObjectUnref(vol);
3369 3370 3371 3372
    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}
3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393


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

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