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

#include <config.h>

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

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

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

54 55
#define VIR_FROM_THIS VIR_FROM_STORAGE

56 57
VIR_LOG_INIT("storage.storage_driver");

58 59
static virStorageDriverStatePtr driverState;

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 69
static void storageDriverLock(virStorageDriverStatePtr driver)
{
70
    virMutexLock(&driver->lock);
71 72 73
}
static void storageDriverUnlock(virStorageDriverStatePtr driver)
{
74
    virMutexUnlock(&driver->lock);
75
}
76 77

static void
78 79
storageDriverAutostart(virStorageDriverStatePtr driver)
{
80
    size_t i;
81 82 83 84 85 86 87 88
    virConnectPtr conn = NULL;

    /* XXX Remove hardcoding of QEMU URI */
    if (driverState->privileged)
        conn = virConnectOpen("qemu:///system");
    else
        conn = virConnectOpen("qemu:///session");
    /* Ignoring NULL conn - let backends decide */
89

90
    for (i = 0; i < driver->pools.count; i++) {
91
        virStoragePoolObjPtr pool = driver->pools.objs[i];
92 93
        virStorageBackendPtr backend;
        bool started = false;
94

95
        virStoragePoolObjLock(pool);
96 97 98 99 100
        if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
            VIR_ERROR(_("Missing backend %d"), pool->def->type);
            virStoragePoolObjUnlock(pool);
            continue;
        }
101

102
        if (backend->checkPool &&
103
            backend->checkPool(conn, pool, &started) < 0) {
104 105 106 107 108 109 110 111 112 113 114
            virErrorPtr err = virGetLastError();
            VIR_ERROR(_("Failed to initialize storage pool '%s': %s"),
                      pool->def->name, err ? err->message :
                      _("no error message found"));
            virStoragePoolObjUnlock(pool);
            continue;
        }

        if (!started &&
            pool->autostart &&
            !virStoragePoolObjIsActive(pool)) {
115
            if (backend->startPool &&
116
                backend->startPool(conn, pool) < 0) {
117
                virErrorPtr err = virGetLastError();
118
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
119
                          pool->def->name, err ? err->message :
120
                          _("no error message found"));
121
                virStoragePoolObjUnlock(pool);
122 123
                continue;
            }
124 125
            started = true;
        }
126

127
        if (started) {
128
            if (backend->refreshPool(conn, pool) < 0) {
129 130
                virErrorPtr err = virGetLastError();
                if (backend->stopPool)
131
                    backend->stopPool(conn, pool);
132
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
133
                          pool->def->name, err ? err->message :
134
                          _("no error message found"));
135
                virStoragePoolObjUnlock(pool);
136 137 138 139
                continue;
            }
            pool->active = 1;
        }
140
        virStoragePoolObjUnlock(pool);
141
    }
142

143
    virObjectUnref(conn);
144 145 146 147 148 149 150 151
}

/**
 * virStorageStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
152 153 154
storageStateInitialize(bool privileged,
                       virStateInhibitCallback callback ATTRIBUTE_UNUSED,
                       void *opaque ATTRIBUTE_UNUSED)
155
{
156 157
    char *base = NULL;

158
    if (VIR_ALLOC(driverState) < 0)
159 160
        return -1;

161 162 163 164
    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        return -1;
    }
165 166
    storageDriverLock(driverState);

167
    if (privileged) {
168 169
        if (VIR_STRDUP(base, SYSCONFDIR "/libvirt") < 0)
            goto error;
170
    } else {
171
        base = virGetUserConfigDirectory();
172
        if (!base)
173
            goto error;
174
    }
175
    driverState->privileged = privileged;
176

177
    /* Configuration paths are either $USER_CONFIG_HOME/libvirt/storage/... (session) or
178 179
     * /etc/libvirt/storage/... (system).
     */
180 181
    if (virAsprintf(&driverState->configDir,
                    "%s/storage", base) == -1)
182
        goto error;
183

184 185
    if (virAsprintf(&driverState->autostartDir,
                    "%s/storage/autostart", base) == -1)
186
        goto error;
187

188
    VIR_FREE(base);
189

190
    if (virStoragePoolLoadAllConfigs(&driverState->pools,
191
                                     driverState->configDir,
192 193
                                     driverState->autostartDir) < 0)
        goto error;
194

195
    storageDriverUnlock(driverState);
196 197
    return 0;

198
 error:
199 200
    VIR_FREE(base);
    storageDriverUnlock(driverState);
201
    storageStateCleanup();
202 203 204
    return -1;
}

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
/**
 * storageStateAutoStart:
 *
 * Function to auto start the storage driver
 */
static void
storageStateAutoStart(void)
{
    if (!driverState)
        return;

    storageDriverLock(driverState);
    storageDriverAutostart(driverState);
    storageDriverUnlock(driverState);
}

221
/**
222
 * storageStateReload:
223 224 225 226 227
 *
 * Function to restart the storage driver, it will recheck the configuration
 * files and update its state
 */
static int
228 229
storageStateReload(void)
{
230 231 232
    if (!driverState)
        return -1;

233
    storageDriverLock(driverState);
234
    virStoragePoolLoadAllConfigs(&driverState->pools,
235 236
                                 driverState->configDir,
                                 driverState->autostartDir);
237
    storageDriverAutostart(driverState);
238
    storageDriverUnlock(driverState);
239 240 241 242 243 244

    return 0;
}


/**
245
 * storageStateCleanup
246 247 248 249
 *
 * Shutdown the storage driver, it will stop all active storage pools
 */
static int
250 251
storageStateCleanup(void)
{
252 253 254
    if (!driverState)
        return -1;

255
    storageDriverLock(driverState);
256 257

    /* free inactive pools */
258 259 260 261
    virStoragePoolObjListFree(&driverState->pools);

    VIR_FREE(driverState->configDir);
    VIR_FREE(driverState->autostartDir);
262
    storageDriverUnlock(driverState);
263
    virMutexDestroy(&driverState->lock);
264
    VIR_FREE(driverState);
265 266 267 268 269 270 271 272

    return 0;
}



static virStoragePoolPtr
storagePoolLookupByUUID(virConnectPtr conn,
273 274
                        const unsigned char *uuid)
{
275 276 277
    virStorageDriverStatePtr driver = conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
278

279
    storageDriverLock(driver);
280
    pool = virStoragePoolObjFindByUUID(&driver->pools, uuid);
281 282
    storageDriverUnlock(driver);

283
    if (!pool) {
284 285
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
286
        virReportError(VIR_ERR_NO_STORAGE_POOL,
287 288
                       _("no storage pool with matching uuid '%s'"), uuidstr);
        return NULL;
289 290
    }

291 292 293
    if (virStoragePoolLookupByUUIDEnsureACL(conn, pool->def) < 0)
        goto cleanup;

294 295
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
296

297
 cleanup:
298
    virStoragePoolObjUnlock(pool);
299 300 301 302 303
    return ret;
}

static virStoragePoolPtr
storagePoolLookupByName(virConnectPtr conn,
304 305
                        const char *name)
{
306 307 308
    virStorageDriverStatePtr driver = conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
309

310
    storageDriverLock(driver);
311
    pool = virStoragePoolObjFindByName(&driver->pools, name);
312 313
    storageDriverUnlock(driver);

314
    if (!pool) {
315
        virReportError(VIR_ERR_NO_STORAGE_POOL,
316
                       _("no storage pool with matching name '%s'"), name);
317
        return NULL;
318 319
    }

320 321 322
    if (virStoragePoolLookupByNameEnsureACL(conn, pool->def) < 0)
        goto cleanup;

323 324
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
325

326
 cleanup:
327
    virStoragePoolObjUnlock(pool);
328 329 330 331
    return ret;
}

static virStoragePoolPtr
332 333
storagePoolLookupByVolume(virStorageVolPtr vol)
{
334 335 336 337 338 339 340 341 342 343 344
    virStorageDriverStatePtr driver = vol->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;

    storageDriverLock(driver);
    pool = virStoragePoolObjFindByName(&driver->pools, vol->pool);
    storageDriverUnlock(driver);

    if (!pool) {
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"), vol->pool);
345
        return NULL;
346 347 348 349 350 351 352 353
    }

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

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

354
 cleanup:
355
    virStoragePoolObjUnlock(pool);
356
    return ret;
357 358 359 360 361
}

static virDrvOpenStatus
storageOpen(virConnectPtr conn,
            virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
362 363 364 365
            unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

366 367 368 369 370 371 372 373
    if (!driverState)
        return VIR_DRV_OPEN_DECLINED;

    conn->storagePrivateData = driverState;
    return VIR_DRV_OPEN_SUCCESS;
}

static int
374 375
storageClose(virConnectPtr conn)
{
376 377 378 379 380
    conn->storagePrivateData = NULL;
    return 0;
}

static int
381 382
storageConnectNumOfStoragePools(virConnectPtr conn)
{
383
    virStorageDriverStatePtr driver = conn->storagePrivateData;
384 385
    size_t i;
    int nactive = 0;
386

387 388 389
    if (virConnectNumOfStoragePoolsEnsureACL(conn) < 0)
        return -1;

390
    storageDriverLock(driver);
391
    for (i = 0; i < driver->pools.count; i++) {
392 393 394
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfStoragePoolsCheckACL(conn, obj->def) &&
395
            virStoragePoolObjIsActive(obj))
396
            nactive++;
397
        virStoragePoolObjUnlock(obj);
398 399
    }
    storageDriverUnlock(driver);
400 401

    return nactive;
402 403 404
}

static int
405 406
storageConnectListStoragePools(virConnectPtr conn,
                               char **const names,
407 408
                               int nnames)
{
409
    virStorageDriverStatePtr driver = conn->storagePrivateData;
410 411
    int got = 0;
    size_t i;
412

413 414 415
    if (virConnectListStoragePoolsEnsureACL(conn) < 0)
        return -1;

416
    storageDriverLock(driver);
417
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
418 419 420
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListStoragePoolsCheckACL(conn, obj->def) &&
421
            virStoragePoolObjIsActive(obj)) {
422 423
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
424 425 426 427
                goto cleanup;
            }
            got++;
        }
428
        virStoragePoolObjUnlock(obj);
429
    }
430
    storageDriverUnlock(driver);
431 432 433
    return got;

 cleanup:
434
    storageDriverUnlock(driver);
435
    for (i = 0; i < got; i++)
436
        VIR_FREE(names[i]);
437
    memset(names, 0, nnames * sizeof(*names));
438 439 440 441
    return -1;
}

static int
442 443
storageConnectNumOfDefinedStoragePools(virConnectPtr conn)
{
444
    virStorageDriverStatePtr driver = conn->storagePrivateData;
445 446
    size_t i;
    int nactive = 0;
447

448 449 450
    if (virConnectNumOfDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

451
    storageDriverLock(driver);
452
    for (i = 0; i < driver->pools.count; i++) {
453 454 455
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfDefinedStoragePoolsCheckACL(conn, obj->def) &&
456
            !virStoragePoolObjIsActive(obj))
457
            nactive++;
458
        virStoragePoolObjUnlock(obj);
459 460
    }
    storageDriverUnlock(driver);
461 462

    return nactive;
463 464 465
}

static int
466 467
storageConnectListDefinedStoragePools(virConnectPtr conn,
                                      char **const names,
468 469
                                      int nnames)
{
470
    virStorageDriverStatePtr driver = conn->storagePrivateData;
471 472
    int got = 0;
    size_t i;
473

474 475 476
    if (virConnectListDefinedStoragePoolsEnsureACL(conn) < 0)
        return -1;

477
    storageDriverLock(driver);
478
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
479 480 481
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListDefinedStoragePoolsCheckACL(conn, obj->def) &&
482
            !virStoragePoolObjIsActive(obj)) {
483 484
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
485 486 487 488
                goto cleanup;
            }
            got++;
        }
489
        virStoragePoolObjUnlock(obj);
490
    }
491
    storageDriverUnlock(driver);
492 493 494
    return got;

 cleanup:
495
    storageDriverUnlock(driver);
496
    for (i = 0; i < got; i++) {
497
        VIR_FREE(names[i]);
498
    }
499
    memset(names, 0, nnames * sizeof(*names));
500 501 502
    return -1;
}

503 504
/* This method is required to be re-entrant / thread safe, so
   uses no driver lock */
505
static char *
506 507 508 509
storageConnectFindStoragePoolSources(virConnectPtr conn,
                                     const char *type,
                                     const char *srcSpec,
                                     unsigned int flags)
510 511 512
{
    int backend_type;
    virStorageBackendPtr backend;
513
    char *ret = NULL;
514

515 516 517
    if (virConnectFindStoragePoolSourcesEnsureACL(conn) < 0)
        return NULL;

518
    backend_type = virStoragePoolTypeFromString(type);
519
    if (backend_type < 0) {
520 521
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage pool type %s"), type);
522
        goto cleanup;
523
    }
524 525 526

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
527
        goto cleanup;
528

529
    if (!backend->findPoolSources) {
530 531 532
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("pool type '%s' does not support source "
                         "discovery"), type);
533 534 535 536
        goto cleanup;
    }

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

538
 cleanup:
539
    return ret;
540 541 542
}


543 544
static virStoragePoolObjPtr
virStoragePoolObjFromStoragePool(virStoragePoolPtr pool)
545
{
546
    virStorageDriverStatePtr driver = pool->conn->storagePrivateData;
547 548
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virStoragePoolObjPtr ret;
549 550

    storageDriverLock(driver);
551 552 553 554 555
    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);
556
    }
557 558 559 560 561 562 563 564 565 566 567 568 569
    storageDriverUnlock(driver);

    return ret;
}


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

    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
570 571 572 573

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

574 575
    ret = virStoragePoolObjIsActive(obj);

576
 cleanup:
577
    virStoragePoolObjUnlock(obj);
578 579 580
    return ret;
}

581
static int storagePoolIsPersistent(virStoragePoolPtr pool)
582 583 584 585
{
    virStoragePoolObjPtr obj;
    int ret = -1;

586 587
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
588 589 590 591

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

592 593
    ret = obj->configFile ? 1 : 0;

594
 cleanup:
595
    virStoragePoolObjUnlock(obj);
596 597 598 599
    return ret;
}


600
static virStoragePoolPtr
601 602 603
storagePoolCreateXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
604
{
605
    virStorageDriverStatePtr driver = conn->storagePrivateData;
606
    virStoragePoolDefPtr def;
607
    virStoragePoolObjPtr pool = NULL;
608
    virStoragePoolPtr ret = NULL;
609 610
    virStorageBackendPtr backend;

E
Eric Blake 已提交
611 612
    virCheckFlags(0, NULL);

613
    storageDriverLock(driver);
614
    if (!(def = virStoragePoolDefParseString(xml)))
615
        goto cleanup;
616

617 618 619
    if (virStoragePoolCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

620
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 1) < 0)
621
        goto cleanup;
622

623 624 625
    if (virStoragePoolSourceFindDuplicate(&driver->pools, def) < 0)
        goto cleanup;

626 627
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
628

629
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
630 631
        goto cleanup;
    def = NULL;
632

633
    if (backend->startPool &&
634 635 636
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
637
        goto cleanup;
638
    }
639

640 641 642
    if (backend->refreshPool(conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(conn, pool);
643 644
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
645
        goto cleanup;
646
    }
647
    VIR_INFO("Creating storage pool '%s'", pool->def->name);
648 649
    pool->active = 1;

650 651
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
652

653
 cleanup:
654
    virStoragePoolDefFree(def);
655
    if (pool)
656
        virStoragePoolObjUnlock(pool);
657
    storageDriverUnlock(driver);
658 659 660 661
    return ret;
}

static virStoragePoolPtr
662 663 664
storagePoolDefineXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
665
{
666
    virStorageDriverStatePtr driver = conn->storagePrivateData;
667
    virStoragePoolDefPtr def;
668
    virStoragePoolObjPtr pool = NULL;
669
    virStoragePoolPtr ret = NULL;
670

E
Eric Blake 已提交
671 672
    virCheckFlags(0, NULL);

673
    storageDriverLock(driver);
674
    if (!(def = virStoragePoolDefParseString(xml)))
675
        goto cleanup;
676

677 678 679
    if (virStoragePoolDefineXMLEnsureACL(conn, def) < 0)
        goto cleanup;

680 681 682
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 0) < 0)
        goto cleanup;

683 684 685
    if (virStoragePoolSourceFindDuplicate(&driver->pools, def) < 0)
        goto cleanup;

686
    if (virStorageBackendForType(def->type) == NULL)
687
        goto cleanup;
688

689
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
690
        goto cleanup;
691

692
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
693
        virStoragePoolObjRemove(&driver->pools, pool);
694
        def = NULL;
695
        goto cleanup;
696
    }
697
    def = NULL;
698

699
    VIR_INFO("Defining storage pool '%s'", pool->def->name);
700 701
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
702

703
 cleanup:
704
    virStoragePoolDefFree(def);
705 706 707
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
708 709 710 711
    return ret;
}

static int
712 713
storagePoolUndefine(virStoragePoolPtr obj)
{
714 715 716
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
717

718
    storageDriverLock(driver);
719 720 721
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
722
        virReportError(VIR_ERR_NO_STORAGE_POOL,
723 724
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
725
        goto cleanup;
726 727
    }

728 729 730
    if (virStoragePoolUndefineEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

731
    if (virStoragePoolObjIsActive(pool)) {
732
        virReportError(VIR_ERR_OPERATION_INVALID,
733 734
                       _("storage pool '%s' is still active"),
                       pool->def->name);
735
        goto cleanup;
736 737
    }

738
    if (pool->asyncjobs > 0) {
739 740 741
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
742 743 744
        goto cleanup;
    }

745
    if (virStoragePoolObjDeleteDef(pool) < 0)
746
        goto cleanup;
747

748 749
    if (unlink(pool->autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
        char ebuf[1024];
750
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
751
                  pool->autostartLink, virStrerror(errno, ebuf, sizeof(ebuf)));
752
    }
753

754 755
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
756

757
    VIR_INFO("Undefining storage pool '%s'", pool->def->name);
758
    virStoragePoolObjRemove(&driver->pools, pool);
759
    pool = NULL;
760
    ret = 0;
761

762
 cleanup:
763 764 765
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
766
    return ret;
767 768 769
}

static int
770 771
storagePoolCreate(virStoragePoolPtr obj,
                  unsigned int flags)
E
Eric Blake 已提交
772
{
773
    virStoragePoolObjPtr pool;
774
    virStorageBackendPtr backend;
775
    int ret = -1;
776

E
Eric Blake 已提交
777 778
    virCheckFlags(0, -1);

779 780
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
781

782 783 784
    if (virStoragePoolCreateEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

785 786
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
787 788

    if (virStoragePoolObjIsActive(pool)) {
789
        virReportError(VIR_ERR_OPERATION_INVALID,
790 791
                       _("storage pool '%s' is already active"),
                       pool->def->name);
792
        goto cleanup;
793 794 795
    }
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
796 797
        goto cleanup;

798 799 800
    if (backend->refreshPool(obj->conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
801
        goto cleanup;
802 803
    }

804
    VIR_INFO("Starting up storage pool '%s'", pool->def->name);
805
    pool->active = 1;
806
    ret = 0;
807

808
 cleanup:
809
    virStoragePoolObjUnlock(pool);
810
    return ret;
811 812 813 814
}

static int
storagePoolBuild(virStoragePoolPtr obj,
815 816
                 unsigned int flags)
{
817
    virStoragePoolObjPtr pool;
818
    virStorageBackendPtr backend;
819
    int ret = -1;
820

821 822
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
823

824 825 826
    if (virStoragePoolBuildEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

827 828
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
829 830

    if (virStoragePoolObjIsActive(pool)) {
831
        virReportError(VIR_ERR_OPERATION_INVALID,
832 833
                       _("storage pool '%s' is already active"),
                       pool->def->name);
834
        goto cleanup;
835 836 837 838
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
839 840
        goto cleanup;
    ret = 0;
841

842
 cleanup:
843
    virStoragePoolObjUnlock(pool);
844
    return ret;
845 846 847 848
}


static int
849 850
storagePoolDestroy(virStoragePoolPtr obj)
{
851 852
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
853
    virStorageBackendPtr backend;
854
    int ret = -1;
855

856
    storageDriverLock(driver);
857 858 859
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
860
        virReportError(VIR_ERR_NO_STORAGE_POOL,
861 862
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
863
        goto cleanup;
864 865
    }

866 867 868
    if (virStoragePoolDestroyEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

869 870
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
871 872

    if (!virStoragePoolObjIsActive(pool)) {
873
        virReportError(VIR_ERR_OPERATION_INVALID,
874
                       _("storage pool '%s' is not active"), pool->def->name);
875
        goto cleanup;
876 877
    }

878
    if (pool->asyncjobs > 0) {
879 880 881
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
882 883 884
        goto cleanup;
    }

885 886
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
887
        goto cleanup;
888 889 890 891

    virStoragePoolObjClearVols(pool);

    pool->active = 0;
892
    VIR_INFO("Shutting down storage pool '%s'", pool->def->name);
893

894
    if (pool->configFile == NULL) {
895
        virStoragePoolObjRemove(&driver->pools, pool);
896
        pool = NULL;
897 898 899 900
    } else if (pool->newDef) {
        virStoragePoolDefFree(pool->def);
        pool->def = pool->newDef;
        pool->newDef = NULL;
901
    }
902
    ret = 0;
903

904
 cleanup:
905 906 907
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
908
    return ret;
909 910 911 912
}

static int
storagePoolDelete(virStoragePoolPtr obj,
913 914
                  unsigned int flags)
{
915
    virStoragePoolObjPtr pool;
916
    virStorageBackendPtr backend;
917
    int ret = -1;
918

919 920
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
921

922 923 924
    if (virStoragePoolDeleteEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

925 926
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
927 928

    if (virStoragePoolObjIsActive(pool)) {
929
        virReportError(VIR_ERR_OPERATION_INVALID,
930 931
                       _("storage pool '%s' is still active"),
                       pool->def->name);
932
        goto cleanup;
933 934
    }

935
    if (pool->asyncjobs > 0) {
936 937
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
938 939 940 941
                              pool->def->name);
        goto cleanup;
    }

942
    if (!backend->deletePool) {
943 944
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("pool does not support pool deletion"));
945
        goto cleanup;
946 947
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
948
        goto cleanup;
949
    VIR_INFO("Deleting storage pool '%s'", pool->def->name);
950
    ret = 0;
951

952
 cleanup:
953
    virStoragePoolObjUnlock(pool);
954
    return ret;
955 956 957 958 959
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
E
Eric Blake 已提交
960 961
                   unsigned int flags)
{
962 963
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
964
    virStorageBackendPtr backend;
965
    int ret = -1;
966

E
Eric Blake 已提交
967 968
    virCheckFlags(0, -1);

969
    storageDriverLock(driver);
970 971 972
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
973
        virReportError(VIR_ERR_NO_STORAGE_POOL,
974 975
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
976
        goto cleanup;
977 978
    }

979 980 981
    if (virStoragePoolRefreshEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

982 983
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
984 985

    if (!virStoragePoolObjIsActive(pool)) {
986
        virReportError(VIR_ERR_OPERATION_INVALID,
987
                       _("storage pool '%s' is not active"), pool->def->name);
988
        goto cleanup;
989 990
    }

991
    if (pool->asyncjobs > 0) {
992 993 994
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
995 996 997
        goto cleanup;
    }

998
    virStoragePoolObjClearVols(pool);
999
    if (backend->refreshPool(obj->conn, pool) < 0) {
1000 1001 1002 1003 1004
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

1005
        if (pool->configFile == NULL) {
1006
            virStoragePoolObjRemove(&driver->pools, pool);
1007 1008
            pool = NULL;
        }
1009
        goto cleanup;
1010
    }
1011
    ret = 0;
1012

1013
 cleanup:
1014 1015
    if (pool)
        virStoragePoolObjUnlock(pool);
1016
    storageDriverUnlock(driver);
1017 1018 1019 1020 1021 1022
    return ret;
}


static int
storagePoolGetInfo(virStoragePoolPtr obj,
1023 1024
                   virStoragePoolInfoPtr info)
{
1025 1026
    virStoragePoolObjPtr pool;
    int ret = -1;
1027

1028 1029
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1030

1031 1032 1033
    if (virStoragePoolGetInfoEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1034
    if (virStorageBackendForType(pool->def->type) == NULL)
1035
        goto cleanup;
1036 1037 1038 1039 1040 1041 1042 1043 1044

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

1047
 cleanup:
1048
    virStoragePoolObjUnlock(pool);
1049
    return ret;
1050 1051 1052
}

static char *
1053
storagePoolGetXMLDesc(virStoragePoolPtr obj,
E
Eric Blake 已提交
1054 1055
                      unsigned int flags)
{
1056
    virStoragePoolObjPtr pool;
1057
    virStoragePoolDefPtr def;
1058
    char *ret = NULL;
1059

1060
    virCheckFlags(VIR_STORAGE_XML_INACTIVE, NULL);
E
Eric Blake 已提交
1061

1062 1063
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1064

1065 1066 1067
    if (virStoragePoolGetXMLDescEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1068 1069 1070 1071 1072 1073
    if ((flags & VIR_STORAGE_XML_INACTIVE) && pool->newDef)
        def = pool->newDef;
    else
        def = pool->def;

    ret = virStoragePoolDefFormat(def);
1074

1075
 cleanup:
1076
    virStoragePoolObjUnlock(pool);
1077
    return ret;
1078 1079 1080 1081
}

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
1082 1083
                        int *autostart)
{
1084 1085
    virStoragePoolObjPtr pool;
    int ret = -1;
1086

1087 1088
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1089

1090 1091 1092
    if (virStoragePoolGetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1093 1094 1095 1096 1097
    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
1098
    ret = 0;
1099

1100
 cleanup:
1101
    virStoragePoolObjUnlock(pool);
1102
    return ret;
1103 1104 1105 1106
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
1107 1108
                        int autostart)
{
1109 1110 1111
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
1112

1113
    storageDriverLock(driver);
1114
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1115

1116
    if (!pool) {
1117 1118
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1119
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1120 1121
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1122
        goto cleanup;
1123 1124
    }

1125 1126 1127
    if (virStoragePoolSetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1128
    if (!pool->configFile) {
1129 1130
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("pool has no config file"));
1131
        goto cleanup;
1132 1133 1134 1135
    }

    autostart = (autostart != 0);

1136 1137
    if (pool->autostart != autostart) {
        if (autostart) {
1138 1139
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
1140 1141
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1142 1143
                goto cleanup;
            }
1144

1145
            if (symlink(pool->configFile, pool->autostartLink) < 0) {
1146
                virReportSystemError(errno,
1147 1148
                                     _("Failed to create symlink '%s' to '%s'"),
                                     pool->autostartLink, pool->configFile);
1149 1150 1151 1152 1153
                goto cleanup;
            }
        } else {
            if (unlink(pool->autostartLink) < 0 &&
                errno != ENOENT && errno != ENOTDIR) {
1154
                virReportSystemError(errno,
1155 1156
                                     _("Failed to delete symlink '%s'"),
                                     pool->autostartLink);
1157 1158
                goto cleanup;
            }
1159
        }
1160
        pool->autostart = autostart;
1161
    }
1162
    ret = 0;
1163

1164
 cleanup:
1165 1166
    if (pool)
        virStoragePoolObjUnlock(pool);
1167
    storageDriverUnlock(driver);
1168
    return ret;
1169 1170 1171 1172
}


static int
1173 1174
storagePoolNumOfVolumes(virStoragePoolPtr obj)
{
1175
    virStoragePoolObjPtr pool;
1176 1177
    int ret = -1;
    size_t i;
1178

1179 1180
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1181

1182 1183 1184
    if (virStoragePoolNumOfVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1185
    if (!virStoragePoolObjIsActive(pool)) {
1186
        virReportError(VIR_ERR_OPERATION_INVALID,
1187
                       _("storage pool '%s' is not active"), pool->def->name);
1188
        goto cleanup;
1189
    }
1190 1191 1192 1193 1194 1195
    ret = 0;
    for (i = 0; i < pool->volumes.count; i++) {
        if (virStoragePoolNumOfVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            ret++;
    }
1196

1197
 cleanup:
1198
    virStoragePoolObjUnlock(pool);
1199
    return ret;
1200 1201 1202 1203 1204
}

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
1205 1206
                       int maxnames)
{
1207
    virStoragePoolObjPtr pool;
1208 1209
    size_t i;
    int n = 0;
1210

1211 1212
    memset(names, 0, maxnames * sizeof(*names));

1213 1214
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1215

1216 1217 1218
    if (virStoragePoolListVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1219
    if (!virStoragePoolObjIsActive(pool)) {
1220
        virReportError(VIR_ERR_OPERATION_INVALID,
1221
                       _("storage pool '%s' is not active"), pool->def->name);
1222
        goto cleanup;
1223 1224
    }

1225
    for (i = 0; i < pool->volumes.count && n < maxnames; i++) {
1226 1227 1228
        if (!virStoragePoolListVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            continue;
1229
        if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0)
1230 1231 1232
            goto cleanup;
    }

1233
    virStoragePoolObjUnlock(pool);
1234
    return n;
1235 1236

 cleanup:
1237
    virStoragePoolObjUnlock(pool);
1238
    for (n = 0; n < maxnames; n++)
1239
        VIR_FREE(names[n]);
1240

1241
    memset(names, 0, maxnames * sizeof(*names));
1242 1243 1244
    return -1;
}

1245 1246 1247
static int
storagePoolListAllVolumes(virStoragePoolPtr pool,
                          virStorageVolPtr **vols,
1248 1249
                          unsigned int flags)
{
1250
    virStoragePoolObjPtr obj;
1251
    size_t i;
1252 1253 1254 1255 1256 1257 1258
    virStorageVolPtr *tmp_vols = NULL;
    virStorageVolPtr vol = NULL;
    int nvols = 0;
    int ret = -1;

    virCheckFlags(0, -1);

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

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

1265
    if (!virStoragePoolObjIsActive(obj)) {
1266 1267
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("storage pool '%s' is not active"), obj->def->name);
1268 1269 1270 1271 1272 1273 1274 1275 1276
        goto cleanup;
    }

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

1277
    if (VIR_ALLOC_N(tmp_vols, obj->volumes.count + 1) < 0)
1278
        goto cleanup;
1279

1280
    for (i = 0; i < obj->volumes.count; i++) {
1281 1282 1283
        if (!virStoragePoolListAllVolumesCheckACL(pool->conn, obj->def,
                                                  obj->volumes.objs[i]))
            continue;
1284 1285
        if (!(vol = virGetStorageVol(pool->conn, obj->def->name,
                                     obj->volumes.objs[i]->name,
1286 1287
                                     obj->volumes.objs[i]->key,
                                     NULL, NULL)))
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
            goto cleanup;
        tmp_vols[nvols++] = vol;
    }

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

 cleanup:
    if (tmp_vols) {
        for (i = 0; i < nvols; i++) {
            if (tmp_vols[i])
                virStorageVolFree(tmp_vols[i]);
        }
1302
        VIR_FREE(tmp_vols);
1303 1304
    }

1305
    virStoragePoolObjUnlock(obj);
1306 1307 1308

    return ret;
}
1309 1310

static virStorageVolPtr
1311
storageVolLookupByName(virStoragePoolPtr obj,
1312 1313
                       const char *name)
{
1314
    virStoragePoolObjPtr pool;
1315
    virStorageVolDefPtr vol;
1316
    virStorageVolPtr ret = NULL;
1317

1318 1319
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1320 1321

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

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1330 1331 1332
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       name);
1333
        goto cleanup;
1334 1335
    }

1336 1337 1338
    if (virStorageVolLookupByNameEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1339 1340
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key,
                           NULL, NULL);
1341

1342
 cleanup:
1343
    virStoragePoolObjUnlock(pool);
1344
    return ret;
1345 1346 1347 1348
}


static virStorageVolPtr
1349
storageVolLookupByKey(virConnectPtr conn,
1350 1351
                      const char *key)
{
1352
    virStorageDriverStatePtr driver = conn->storagePrivateData;
1353
    size_t i;
1354
    virStorageVolPtr ret = NULL;
1355

1356
    storageDriverLock(driver);
1357
    for (i = 0; i < driver->pools.count && !ret; i++) {
1358
        virStoragePoolObjLock(driver->pools.objs[i]);
1359 1360 1361
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1362

1363
            if (vol) {
1364 1365
                if (virStorageVolLookupByKeyEnsureACL(conn, driver->pools.objs[i]->def, vol) < 0) {
                    virStoragePoolObjUnlock(driver->pools.objs[i]);
1366
                    goto cleanup;
1367
                }
1368

1369
                ret = virGetStorageVol(conn,
1370 1371
                                       driver->pools.objs[i]->def->name,
                                       vol->name,
1372 1373
                                       vol->key,
                                       NULL, NULL);
1374
            }
1375
        }
1376
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1377 1378
    }

1379
    if (!ret)
1380
        virReportError(VIR_ERR_NO_STORAGE_VOL,
1381
                       _("no storage vol with matching key %s"), key);
1382

1383
 cleanup:
1384
    storageDriverUnlock(driver);
1385
    return ret;
1386 1387 1388
}

static virStorageVolPtr
1389
storageVolLookupByPath(virConnectPtr conn,
1390 1391
                       const char *path)
{
1392
    virStorageDriverStatePtr driver = conn->storagePrivateData;
1393
    size_t i;
1394
    virStorageVolPtr ret = NULL;
1395 1396 1397 1398 1399
    char *cleanpath;

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

1401
    storageDriverLock(driver);
1402
    for (i = 0; i < driver->pools.count && !ret; i++) {
1403 1404 1405 1406 1407
        virStoragePoolObjPtr pool = driver->pools.objs[i];
        virStorageVolDefPtr vol;
        char *stable_path = NULL;

        virStoragePoolObjLock(pool);
1408

1409 1410 1411 1412
        if (!virStoragePoolObjIsActive(pool)) {
           virStoragePoolObjUnlock(pool);
           continue;
        }
1413

1414
        switch ((virStoragePoolType) pool->def->type) {
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
            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 已提交
1440
            case VIR_STORAGE_POOL_ZFS:
1441 1442 1443
            case VIR_STORAGE_POOL_LAST:
                if (VIR_STRDUP(stable_path, path) < 0) {
                     virStoragePoolObjUnlock(pool);
1444
                    goto cleanup;
1445
                }
1446 1447
                break;
        }
1448

1449 1450 1451 1452 1453 1454 1455
        vol = virStorageVolDefFindByPath(pool, stable_path);
        VIR_FREE(stable_path);

        if (vol) {
            if (virStorageVolLookupByPathEnsureACL(conn, pool->def, vol) < 0) {
                virStoragePoolObjUnlock(pool);
                goto cleanup;
1456
            }
1457 1458 1459 1460

            ret = virGetStorageVol(conn, pool->def->name,
                                   vol->name, vol->key,
                                   NULL, NULL);
1461
        }
1462 1463

        virStoragePoolObjUnlock(pool);
1464 1465
    }

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
    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);
        }
    }
1476

1477
 cleanup:
1478
    VIR_FREE(cleanpath);
1479
    storageDriverUnlock(driver);
1480
    return ret;
1481 1482
}

1483

1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
static int
storageVolDeleteInternal(virStorageVolPtr obj,
                         virStorageBackendPtr backend,
                         virStoragePoolObjPtr pool,
                         virStorageVolDefPtr vol,
                         unsigned int flags,
                         bool updateMeta)
{
    size_t i;
    int ret = -1;

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

        goto cleanup;
    }

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

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

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

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

 cleanup:
    return ret;
}


1530 1531 1532 1533
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1534 1535 1536
{
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStorageVolDefPtr vol = NULL;
1537 1538

    *pool = NULL;
1539 1540

    storageDriverLock(driver);
1541
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1542 1543
    storageDriverUnlock(driver);

1544
    if (!*pool) {
1545 1546 1547
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1548
        return NULL;
1549 1550
    }

1551
    if (!virStoragePoolObjIsActive(*pool)) {
1552
        virReportError(VIR_ERR_OPERATION_INVALID,
1553 1554 1555
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1556 1557
    }

1558
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1559 1560 1561
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1562
        goto error;
1563 1564
    }

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
    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;

1592 1593 1594
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1595 1596 1597 1598 1599 1600 1601
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1602 1603 1604 1605 1606 1607 1608
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1609
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1610 1611 1612 1613
        goto cleanup;

    ret = 0;

1614
 cleanup:
1615
    virStoragePoolObjUnlock(pool);
1616 1617 1618
    return ret;
}

1619

1620
static virStorageVolPtr
1621 1622 1623
storageVolCreateXML(virStoragePoolPtr obj,
                    const char *xmldesc,
                    unsigned int flags)
E
Eric Blake 已提交
1624
{
1625 1626
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1627
    virStorageBackendPtr backend;
1628 1629
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1630
    virStorageVolDefPtr buildvoldef = NULL;
1631

1632
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1633

1634 1635
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1636 1637

    if (!virStoragePoolObjIsActive(pool)) {
1638
        virReportError(VIR_ERR_OPERATION_INVALID,
1639
                       _("storage pool '%s' is not active"), pool->def->name);
1640
        goto cleanup;
1641 1642 1643
    }

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

1646
    voldef = virStorageVolDefParseString(pool->def, xmldesc);
1647
    if (voldef == NULL)
1648
        goto cleanup;
1649

1650 1651 1652
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1653
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1654
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1655
                       _("'%s'"), voldef->name);
1656
        goto cleanup;
1657 1658
    }

1659
    if (VIR_REALLOC_N(pool->volumes.objs,
1660
                      pool->volumes.count+1) < 0)
1661
        goto cleanup;
1662

1663
    if (!backend->createVol) {
1664 1665 1666
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1667
        goto cleanup;
1668 1669
    }

1670 1671 1672
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1673
    if (backend->createVol(obj->conn, pool, voldef) < 0) {
1674
        goto cleanup;
1675 1676
    }

1677 1678
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
1679
                              voldef->key, NULL, NULL);
1680 1681 1682 1683
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1684

1685 1686 1687 1688
    if (VIR_ALLOC(buildvoldef) < 0) {
        voldef = NULL;
        goto cleanup;
    }
1689

1690 1691 1692 1693 1694
    /* 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));
1695

1696 1697
    if (backend->buildVol) {
        int buildret;
1698 1699 1700

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1701
        voldef->building = true;
1702 1703
        virStoragePoolObjUnlock(pool);

1704
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1705

1706
        storageDriverLock(driver);
1707
        virStoragePoolObjLock(pool);
1708 1709
        storageDriverUnlock(driver);

1710
        voldef->building = false;
1711 1712 1713
        pool->asyncjobs--;

        if (buildret < 0) {
1714 1715
            VIR_FREE(buildvoldef);
            storageVolDeleteInternal(volobj, backend, pool, voldef,
1716
                                     0, false);
1717
            voldef = NULL;
1718 1719 1720 1721 1722
            goto cleanup;
        }

    }

1723
    /* Update pool metadata */
1724 1725
    pool->def->allocation += buildvoldef->target.allocation;
    pool->def->available -= buildvoldef->target.allocation;
1726

1727
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1728
             volobj->name, pool->def->name);
1729 1730 1731
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1732

1733
 cleanup:
1734
    virObjectUnref(volobj);
1735
    virStorageVolDefFree(voldef);
1736
    VIR_FREE(buildvoldef);
1737 1738
    if (pool)
        virStoragePoolObjUnlock(pool);
1739
    return ret;
1740 1741
}

1742
static virStorageVolPtr
1743 1744 1745 1746
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1747
{
1748 1749 1750 1751 1752
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
    virStorageVolDefPtr origvol = NULL, newvol = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
O
Osier Yang 已提交
1753
    unsigned long long allocation;
1754
    int buildret;
1755

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

1758 1759
    storageDriverLock(driver);
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1760
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1761
        virStoragePoolObjUnlock(pool);
1762
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1763
        virStoragePoolObjLock(pool);
1764
    }
1765 1766
    storageDriverUnlock(driver);
    if (!pool) {
1767 1768
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1769
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1770 1771
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1772 1773 1774
        goto cleanup;
    }

1775
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1776 1777 1778
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1779 1780 1781 1782
        goto cleanup;
    }

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

1788
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1789
        virReportError(VIR_ERR_OPERATION_INVALID,
1790 1791
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1792 1793 1794 1795 1796 1797
        goto cleanup;
    }

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

1798
    origvol = virStorageVolDefFindByName(origpool ? origpool : pool, vobj->name);
1799
    if (!origvol) {
1800 1801 1802
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1803 1804 1805
        goto cleanup;
    }

1806
    newvol = virStorageVolDefParseString(pool->def, xmldesc);
1807 1808 1809
    if (newvol == NULL)
        goto cleanup;

1810 1811 1812
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1813
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1814 1815 1816
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1817 1818 1819 1820
        goto cleanup;
    }

    /* Is there ever a valid case for this? */
1821 1822
    if (newvol->target.capacity < origvol->target.capacity)
        newvol->target.capacity = origvol->target.capacity;
1823

1824 1825
    /* Make sure allocation is at least as large as the destination cap,
     * to make absolutely sure we copy all possible contents */
1826 1827
    if (newvol->target.allocation < origvol->target.capacity)
        newvol->target.allocation = origvol->target.capacity;
1828

1829
    if (!backend->buildVolFrom) {
1830 1831
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume creation from an existing volume"));
1832 1833 1834 1835
        goto cleanup;
    }

    if (origvol->building) {
1836 1837 1838
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
1839 1840 1841 1842 1843 1844 1845 1846
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
1847
                      pool->volumes.count+1) < 0)
1848 1849
        goto cleanup;

1850 1851 1852 1853
    /* '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);
1854 1855 1856 1857 1858 1859
    if (backend->createVol(obj->conn, pool, newvol) < 0) {
        goto cleanup;
    }

    pool->volumes.objs[pool->volumes.count++] = newvol;
    volobj = virGetStorageVol(obj->conn, pool->def->name, newvol->name,
1860
                              newvol->key, NULL, NULL);
1861 1862 1863 1864
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1865 1866 1867

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
1868
    newvol->building = true;
1869
    origvol->in_use++;
1870 1871
    virStoragePoolObjUnlock(pool);

1872
    if (origpool) {
1873 1874 1875 1876
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

1877
    buildret = backend->buildVolFrom(obj->conn, pool, newvol, origvol, flags);
1878 1879 1880

    storageDriverLock(driver);
    virStoragePoolObjLock(pool);
1881
    if (origpool)
1882 1883 1884
        virStoragePoolObjLock(origpool);
    storageDriverUnlock(driver);

1885
    origvol->in_use--;
1886
    newvol->building = false;
1887
    allocation = newvol->target.allocation;
1888 1889
    pool->asyncjobs--;

1890
    if (origpool) {
1891 1892 1893 1894 1895 1896
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
1897 1898
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
1899 1900
        goto cleanup;
    }
1901
    newvol = NULL;
1902

1903
    /* Updating pool metadata */
O
Osier Yang 已提交
1904 1905
    pool->def->allocation += allocation;
    pool->def->available -= allocation;
1906

1907
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1908
             volobj->name, pool->def->name);
1909 1910 1911
    ret = volobj;
    volobj = NULL;

1912
 cleanup:
1913
    virObjectUnref(volobj);
1914 1915 1916
    virStorageVolDefFree(newvol);
    if (pool)
        virStoragePoolObjUnlock(pool);
1917
    if (origpool)
1918 1919 1920 1921
        virStoragePoolObjUnlock(origpool);
    return ret;
}

1922

1923
static int
1924 1925 1926 1927 1928
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
1929
{
1930
    virStorageBackendPtr backend;
1931 1932 1933 1934 1935 1936
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

1937
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
1938
        return -1;
1939

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

1943
    if (vol->building) {
1944 1945 1946
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
1947
        goto cleanup;
1948 1949
    }

1950 1951 1952
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
1953
        goto cleanup;
1954
    }
1955

1956 1957
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
1958

1959
 cleanup:
1960
    virStoragePoolObjUnlock(pool);
1961 1962 1963 1964 1965

    return ret;
}


1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
/**
 * 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;

    storageDriverLock(driverState);
    if (!(pool = virStoragePoolObjFindByName(&driverState->pools,
                                             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);
    storageDriverUnlock(driverState);
    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.
 * @opaque Buffer to hold the pool name to be rereshed
 */
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);
}

2038
static int
2039 2040 2041 2042 2043
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2044
{
2045
    virStorageBackendPtr backend;
2046 2047
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2048
    virStorageVolStreamInfoPtr cbdata = NULL;
2049 2050 2051 2052
    int ret = -1;

    virCheckFlags(0, -1);

2053
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
2054
        return -1;
2055

2056
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2057
        goto cleanup;
2058

2059 2060 2061 2062 2063 2064 2065
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2066
    if (vol->building) {
2067 2068 2069
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2070
        goto cleanup;
2071 2072
    }

2073 2074 2075
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2076
        goto cleanup;
2077
    }
2078

2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090
    /* 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;
    }

2091 2092
    ret = backend->uploadVol(obj->conn, pool, vol, stream,
                             offset, length, flags);
2093

2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

2104
 cleanup:
2105
    virStoragePoolObjUnlock(pool);
2106 2107
    if (cbdata)
        virStorageVolPoolRefreshDataFree(cbdata);
2108 2109 2110 2111

    return ret;
}

2112
static int
2113 2114 2115
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2116 2117 2118 2119 2120 2121 2122
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    unsigned long long abs_capacity;
    int ret = -1;

2123
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2124 2125
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2126

2127 2128
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return -1;
2129

2130
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2131
        goto cleanup;
2132

2133 2134 2135 2136 2137 2138 2139
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2140
    if (vol->building) {
2141 2142 2143
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2144
        goto cleanup;
2145
    }
2146

2147
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2148
        abs_capacity = vol->target.capacity + capacity;
2149 2150 2151 2152 2153
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2154
    if (abs_capacity < vol->target.allocation) {
2155
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2156 2157
                       _("can't shrink capacity below "
                         "existing allocation"));
2158
        goto cleanup;
2159 2160
    }

2161
    if (abs_capacity < vol->target.capacity &&
2162 2163 2164 2165
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
                         "capacity with shrink flag explicitly specified"));
2166
        goto cleanup;
2167 2168
    }

2169
    if (abs_capacity > vol->target.capacity + pool->def->available) {
2170
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2171
                       _("Not enough space left on storage pool"));
2172
        goto cleanup;
2173 2174 2175
    }

    if (!backend->resizeVol) {
2176
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2177 2178
                       _("storage pool does not support changing of "
                         "volume capacity"));
2179
        goto cleanup;
2180 2181 2182
    }

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

2185
    vol->target.capacity = abs_capacity;
2186
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE)
2187
        vol->target.allocation = abs_capacity;
2188 2189

    /* Update pool metadata */
2190 2191
    pool->def->allocation += (abs_capacity - vol->target.capacity);
    pool->def->available -= (abs_capacity - vol->target.capacity);
2192

O
Osier Yang 已提交
2193
    ret = 0;
2194

2195
 cleanup:
2196
    virStoragePoolObjUnlock(pool);
2197 2198 2199

    return ret;
}
2200

2201 2202

static int
2203 2204 2205
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2206
{
2207
    virStorageBackendPtr backend;
2208 2209 2210 2211
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2212
    virCheckFlags(0, -1);
2213

2214
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2215 2216 2217
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2218 2219 2220
        return -1;
    }

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


2225
    if (virStorageVolWipePatternEnsureACL(obj->conn, pool->def, vol) < 0)
2226
        goto cleanup;
2227

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

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

2242 2243 2244
    if (!backend->wipeVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume wiping"));
2245
        goto cleanup;
2246
    }
2247

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

2250
 cleanup:
2251
    virStoragePoolObjUnlock(pool);
2252 2253 2254 2255

    return ret;
}

2256
static int
2257 2258
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2259
{
2260
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2261 2262
}

2263 2264

static int
2265
storageVolGetInfo(virStorageVolPtr obj,
2266 2267
                  virStorageVolInfoPtr info)
{
2268
    virStoragePoolObjPtr pool;
2269 2270
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2271
    int ret = -1;
2272

2273 2274
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return -1;
2275

2276 2277 2278
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2279 2280
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2281
        goto cleanup;
2282 2283

    memset(info, 0, sizeof(*info));
2284
    info->type = vol->type;
2285 2286
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2287
    ret = 0;
2288

2289
 cleanup:
2290
    virStoragePoolObjUnlock(pool);
2291
    return ret;
2292 2293 2294
}

static char *
2295 2296
storageVolGetXMLDesc(virStorageVolPtr obj,
                     unsigned int flags)
E
Eric Blake 已提交
2297
{
2298
    virStoragePoolObjPtr pool;
2299 2300
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2301
    char *ret = NULL;
2302

E
Eric Blake 已提交
2303 2304
    virCheckFlags(0, NULL);

2305 2306
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return NULL;
2307

2308 2309 2310
    if (virStorageVolGetXMLDescEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2311 2312 2313
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
        goto cleanup;
2314

2315
    ret = virStorageVolDefFormat(pool->def, vol);
2316

2317
 cleanup:
2318
    virStoragePoolObjUnlock(pool);
2319

2320
    return ret;
2321 2322 2323
}

static char *
2324 2325
storageVolGetPath(virStorageVolPtr obj)
{
2326
    virStoragePoolObjPtr pool;
2327
    virStorageVolDefPtr vol;
2328
    char *ret = NULL;
2329

2330 2331
    if (!(vol = virStorageVolDefFromVol(obj, &pool, NULL)))
        return NULL;
2332

2333 2334 2335
    if (virStorageVolGetPathEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2336
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2337

2338
 cleanup:
2339
    virStoragePoolObjUnlock(pool);
2340 2341 2342
    return ret;
}

2343
static int
2344 2345 2346
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2347 2348 2349 2350 2351 2352
{
    virStorageDriverStatePtr driver = conn->storagePrivateData;
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2353 2354 2355
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2356
    storageDriverLock(driver);
2357 2358
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
                                      virConnectListAllStoragePoolsCheckACL, flags);
2359 2360
    storageDriverUnlock(driver);

2361
 cleanup:
2362 2363 2364
    return ret;
}

2365

2366
static virStorageDriver storageDriver = {
2367
    .name = "storage",
2368 2369
    .storageOpen = storageOpen, /* 0.4.0 */
    .storageClose = storageClose, /* 0.4.0 */
2370 2371 2372 2373 2374 2375
    .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 */
2376 2377 2378
    .storagePoolLookupByName = storagePoolLookupByName, /* 0.4.0 */
    .storagePoolLookupByUUID = storagePoolLookupByUUID, /* 0.4.0 */
    .storagePoolLookupByVolume = storagePoolLookupByVolume, /* 0.4.0 */
2379 2380
    .storagePoolCreateXML = storagePoolCreateXML, /* 0.4.0 */
    .storagePoolDefineXML = storagePoolDefineXML, /* 0.4.0 */
2381 2382
    .storagePoolBuild = storagePoolBuild, /* 0.4.0 */
    .storagePoolUndefine = storagePoolUndefine, /* 0.4.0 */
2383
    .storagePoolCreate = storagePoolCreate, /* 0.4.0 */
2384 2385 2386 2387 2388 2389 2390
    .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 */
2391
    .storagePoolNumOfVolumes = storagePoolNumOfVolumes, /* 0.4.0 */
2392 2393 2394
    .storagePoolListVolumes = storagePoolListVolumes, /* 0.4.0 */
    .storagePoolListAllVolumes = storagePoolListAllVolumes, /* 0.10.2 */

2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408
    .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 */
2409 2410 2411

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2412 2413 2414 2415
};


static virStateDriver stateDriver = {
2416
    .name = "Storage",
2417
    .stateInitialize = storageStateInitialize,
2418
    .stateAutoStart = storageStateAutoStart,
2419 2420
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2421 2422
};

2423 2424 2425 2426
int storageRegister(void)
{
    if (virRegisterStorageDriver(&storageDriver) < 0)
        return -1;
2427 2428
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2429 2430
    return 0;
}
2431 2432 2433


/* ----------- file handlers cooperating with storage driver --------------- */
2434 2435 2436
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2437
    return src && src->drv;
2438 2439
}

2440 2441 2442 2443

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2444
    int actualType;
2445 2446 2447 2448
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2449
    actualType = virStorageSourceGetActualType(src);
2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464

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

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

2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476

/**
 * 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)
{
2477
    int actualType;
2478 2479 2480 2481
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2482
    actualType = virStorageSourceGetActualType(src);
2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496

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

    return !!backend->storageFileChown;
}


2497
void
2498
virStorageFileDeinit(virStorageSourcePtr src)
2499
{
2500
    if (!virStorageFileIsInitialized(src))
2501 2502
        return;

2503 2504 2505
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2506

2507
    VIR_FREE(src->drv);
2508 2509 2510
}


2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523
/**
 * 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.
 */
2524
int
2525 2526
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
2527
{
2528 2529 2530
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;
2531

2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
    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;

2542 2543
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2544 2545
        goto error;

2546 2547
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2548 2549
        goto error;

2550
    return 0;
2551

2552
 error:
2553 2554
    VIR_FREE(src->drv);
    return -1;
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
2568 2569 2570 2571 2572 2573
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
2574
 * @src: file structure pointing to the file
2575 2576 2577 2578 2579
 *
 * 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
2580
virStorageFileCreate(virStorageSourcePtr src)
2581
{
2582 2583
    int ret;

2584 2585
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2586 2587 2588 2589
        errno = ENOSYS;
        return -2;
    }

2590 2591 2592 2593 2594 2595
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2596 2597 2598 2599 2600 2601
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
2602
 * @src: file structure pointing to the file
2603 2604 2605 2606 2607 2608 2609
 *
 * 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
2610
virStorageFileUnlink(virStorageSourcePtr src)
2611
{
2612 2613
    int ret;

2614 2615
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2616 2617 2618 2619
        errno = ENOSYS;
        return -2;
    }

2620 2621 2622 2623 2624 2625
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2626 2627 2628 2629 2630 2631
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
2632
 * @src: file structure pointing to the file
2633 2634 2635 2636 2637 2638
 * @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
2639
virStorageFileStat(virStorageSourcePtr src,
2640 2641
                   struct stat *st)
{
2642 2643
    int ret;

2644 2645
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2646 2647 2648 2649
        errno = ENOSYS;
        return -2;
    }

2650 2651 2652 2653 2654 2655
    ret = src->drv->backend->storageFileStat(src, st);

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

    return ret;
2656
}
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684


/**
 * 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
 * function isn't supported by the backend. Libvirt error is reported on failure.
 */
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 "
2685
                         "storage type %s (protocol: %s)"),
2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
                       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;
}
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726


/*
 * 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);
}
2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750


/**
 * 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);
}
2751 2752


2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780
/**
 * 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;
    }

    VIR_DEBUG("chown of storage file %p to %d:%d", src, uid, gid);

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


2781 2782 2783
/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
2784
                                 virStorageSourcePtr parent,
2785 2786
                                 uid_t uid, gid_t gid,
                                 bool allow_probe,
2787
                                 bool report_broken,
2788 2789 2790
                                 virHashTablePtr cycle)
{
    int ret = -1;
2791
    const char *uniqueName;
2792 2793
    char *buf = NULL;
    ssize_t headerLen;
2794 2795 2796
    virStorageSourcePtr backingStore = NULL;
    int backingFormat;

2797 2798
    VIR_DEBUG("path=%s format=%d uid=%d gid=%d probe=%d",
              src->path, src->format,
2799 2800
              (int)uid, (int)gid, allow_probe);

2801 2802 2803 2804 2805
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
2806
        return -1;
2807

2808
    if (virStorageFileAccess(src, F_OK) < 0) {
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
        if (src == parent) {
            virReportSystemError(errno,
                                 _("Cannot access storage file '%s' "
                                   "(as uid:%d, gid:%d)"),
                                 src->path, (int)uid, (int)gid);
        } else {
            virReportSystemError(errno,
                                 _("Cannot access backing file '%s' "
                                   "of storage file '%s' (as uid:%d, gid:%d)"),
                                 src->path, parent->path, (int)uid, (int)gid);
        }

2821 2822 2823
        goto cleanup;
    }

2824 2825 2826 2827 2828 2829 2830 2831
    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;
2832 2833
    }

2834 2835
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
2836

2837 2838 2839
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
2840

2841 2842
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
2843
        goto cleanup;
2844 2845

    /* check whether we need to go deeper */
2846 2847 2848 2849
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
2850

2851
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
2852
        goto cleanup;
2853 2854 2855 2856 2857 2858 2859 2860

    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;

2861
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
2862 2863 2864 2865 2866 2867
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

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

 cleanup:
2879
    VIR_FREE(buf);
2880
    virStorageFileDeinit(src);
2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
    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.
 *
2901 2902 2903
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
2904 2905 2906 2907 2908
 * Caller MUST free result after use via virStorageSourceFree.
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
2909 2910
                          bool allow_probe,
                          bool report_broken)
2911
{
2912 2913 2914
    VIR_DEBUG("path=%s format=%d uid=%d gid=%d probe=%d, report_broken=%d",
              src->path, src->format, (int)uid, (int)gid,
              allow_probe, report_broken);
2915 2916 2917 2918 2919 2920 2921 2922 2923 2924

    virHashTablePtr cycle = NULL;
    int ret = -1;

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

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

2925
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
2926
                                           allow_probe, report_broken, cycle);
2927 2928 2929 2930

    virHashFree(cycle);
    return ret;
}
2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175


static int
virStorageAddISCSIPoolSourceHost(virDomainDiskDefPtr def,
                                 virStoragePoolDefPtr pooldef)
{
    int ret = -1;
    char **tokens = NULL;

    /* Only support one host */
    if (pooldef->source.nhost != 1) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("Expected exactly 1 host for the storage pool"));
        goto cleanup;
    }

    /* iscsi pool only supports one host */
    def->src->nhosts = 1;

    if (VIR_ALLOC_N(def->src->hosts, def->src->nhosts) < 0)
        goto cleanup;

    if (VIR_STRDUP(def->src->hosts[0].name, pooldef->source.hosts[0].name) < 0)
        goto cleanup;

    if (virAsprintf(&def->src->hosts[0].port, "%d",
                    pooldef->source.hosts[0].port ?
                    pooldef->source.hosts[0].port :
                    3260) < 0)
        goto cleanup;

    /* iscsi volume has name like "unit:0:0:1" */
    if (!(tokens = virStringSplit(def->src->srcpool->volume, ":", 0)))
        goto cleanup;

    if (virStringListLength(tokens) != 4) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unexpected iscsi volume name '%s'"),
                       def->src->srcpool->volume);
        goto cleanup;
    }

    /* iscsi pool has only one source device path */
    if (virAsprintf(&def->src->path, "%s/%s",
                    pooldef->source.devices[0].path,
                    tokens[3]) < 0)
        goto cleanup;

    /* Storage pool have not supported these 2 attributes yet,
     * use the defaults.
     */
    def->src->hosts[0].transport = VIR_STORAGE_NET_HOST_TRANS_TCP;
    def->src->hosts[0].socket = NULL;

    def->src->protocol = VIR_STORAGE_NET_PROTOCOL_ISCSI;

    ret = 0;

 cleanup:
    virStringFreeList(tokens);
    return ret;
}


static int
virStorageTranslateDiskSourcePoolAuth(virDomainDiskDefPtr def,
                                      virStoragePoolSourcePtr source)
{
    int ret = -1;

    /* Only necessary when authentication set */
    if (!source->auth) {
        ret = 0;
        goto cleanup;
    }
    def->src->auth = virStorageAuthDefCopy(source->auth);
    if (!def->src->auth)
        goto cleanup;
    ret = 0;

 cleanup:
    return ret;
}


int
virStorageTranslateDiskSourcePool(virConnectPtr conn,
                                  virDomainDiskDefPtr def)
{
    virStoragePoolDefPtr pooldef = NULL;
    virStoragePoolPtr pool = NULL;
    virStorageVolPtr vol = NULL;
    char *poolxml = NULL;
    virStorageVolInfo info;
    int ret = -1;
    virErrorPtr savedError = NULL;

    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;

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

           if (virStorageAddISCSIPoolSourceHost(def, pooldef) < 0)
               goto cleanup;
           break;
       }
       break;

    case VIR_STORAGE_POOL_MPATH:
    case VIR_STORAGE_POOL_RBD:
    case VIR_STORAGE_POOL_SHEEPDOG:
    case VIR_STORAGE_POOL_GLUSTER:
    case VIR_STORAGE_POOL_LAST:
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("using '%s' pools for backing 'volume' disks "
                         "isn't yet supported"),
                       virStoragePoolTypeToString(pooldef->type));
        goto cleanup;
    }

    ret = 0;
 cleanup:
    if (ret < 0)
        savedError = virSaveLastError();
    if (pool)
        virStoragePoolFree(pool);
    if (vol)
        virStorageVolFree(vol);
    if (savedError) {
        virSetError(savedError);
        virFreeError(savedError);
    }

    VIR_FREE(poolxml);
    virStoragePoolDefFree(pooldef);
    return ret;
}