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

#include <config.h>

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

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

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

54 55
#define VIR_FROM_THIS VIR_FROM_STORAGE

56 57
VIR_LOG_INIT("storage.storage_driver");

58
static virStorageDriverStatePtr driver;
59

60
static int storageStateCleanup(void);
61

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

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

static void
78
storageDriverAutostart(void)
79
{
80
    size_t i;
81 82 83
    virConnectPtr conn = NULL;

    /* XXX Remove hardcoding of QEMU URI */
84
    if (driver->privileged)
85 86 87 88
        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(driver) < 0)
159 160
        return -1;

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

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
    driver->privileged = privileged;
176

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

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

188
    VIR_FREE(base);
189

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

195
    storageDriverUnlock();
196 197
    return 0;

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

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

216 217 218
    storageDriverLock();
    storageDriverAutostart();
    storageDriverUnlock();
219 220
}

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
    if (!driver)
231 232
        return -1;

233 234 235 236 237 238
    storageDriverLock();
    virStoragePoolLoadAllConfigs(&driver->pools,
                                 driver->configDir,
                                 driver->autostartDir);
    storageDriverAutostart();
    storageDriverUnlock();
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
    if (!driver)
253 254
        return -1;

255
    storageDriverLock();
256 257

    /* free inactive pools */
258
    virStoragePoolObjListFree(&driver->pools);
259

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

    return 0;
}



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

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

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

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

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

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

static virStoragePoolPtr
storagePoolLookupByName(virConnectPtr conn,
303 304
                        const char *name)
{
305 306
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
307

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

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

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

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

324
 cleanup:
325
    virStoragePoolObjUnlock(pool);
326 327 328 329
    return ret;
}

static virStoragePoolPtr
330 331
storagePoolLookupByVolume(virStorageVolPtr vol)
{
332 333 334
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;

335
    storageDriverLock();
336
    pool = virStoragePoolObjFindByName(&driver->pools, vol->pool);
337
    storageDriverUnlock();
338 339 340 341

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

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

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

351
 cleanup:
352
    virStoragePoolObjUnlock(pool);
353
    return ret;
354 355 356
}

static virDrvOpenStatus
357
storageOpen(virConnectPtr conn ATTRIBUTE_UNUSED,
358
            virConnectAuthPtr auth ATTRIBUTE_UNUSED,
E
Eric Blake 已提交
359 360 361 362
            unsigned int flags)
{
    virCheckFlags(VIR_CONNECT_RO, VIR_DRV_OPEN_ERROR);

363
    if (!driver)
364 365 366 367 368 369
        return VIR_DRV_OPEN_DECLINED;

    return VIR_DRV_OPEN_SUCCESS;
}

static int
370
storageClose(virConnectPtr conn ATTRIBUTE_UNUSED)
371
{
372 373 374 375
    return 0;
}

static int
376 377
storageConnectNumOfStoragePools(virConnectPtr conn)
{
378 379
    size_t i;
    int nactive = 0;
380

381 382 383
    if (virConnectNumOfStoragePoolsEnsureACL(conn) < 0)
        return -1;

384
    storageDriverLock();
385
    for (i = 0; i < driver->pools.count; i++) {
386 387 388
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectNumOfStoragePoolsCheckACL(conn, obj->def) &&
389
            virStoragePoolObjIsActive(obj))
390
            nactive++;
391
        virStoragePoolObjUnlock(obj);
392
    }
393
    storageDriverUnlock();
394 395

    return nactive;
396 397 398
}

static int
399 400
storageConnectListStoragePools(virConnectPtr conn,
                               char **const names,
401 402
                               int nnames)
{
403 404
    int got = 0;
    size_t i;
405

406 407 408
    if (virConnectListStoragePoolsEnsureACL(conn) < 0)
        return -1;

409
    storageDriverLock();
410
    for (i = 0; i < driver->pools.count && got < nnames; i++) {
411 412 413
        virStoragePoolObjPtr obj = driver->pools.objs[i];
        virStoragePoolObjLock(obj);
        if (virConnectListStoragePoolsCheckACL(conn, obj->def) &&
414
            virStoragePoolObjIsActive(obj)) {
415 416
            if (VIR_STRDUP(names[got], obj->def->name) < 0) {
                virStoragePoolObjUnlock(obj);
417 418 419 420
                goto cleanup;
            }
            got++;
        }
421
        virStoragePoolObjUnlock(obj);
422
    }
423
    storageDriverUnlock();
424 425 426
    return got;

 cleanup:
427
    storageDriverUnlock();
428
    for (i = 0; i < got; i++)
429
        VIR_FREE(names[i]);
430
    memset(names, 0, nnames * sizeof(*names));
431 432 433 434
    return -1;
}

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

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

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

    return nactive;
455 456 457
}

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

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

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

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

494 495
/* This method is required to be re-entrant / thread safe, so
   uses no driver lock */
496
static char *
497 498 499 500
storageConnectFindStoragePoolSources(virConnectPtr conn,
                                     const char *type,
                                     const char *srcSpec,
                                     unsigned int flags)
501 502 503
{
    int backend_type;
    virStorageBackendPtr backend;
504
    char *ret = NULL;
505

506 507 508
    if (virConnectFindStoragePoolSourcesEnsureACL(conn) < 0)
        return NULL;

509
    backend_type = virStoragePoolTypeFromString(type);
510
    if (backend_type < 0) {
511 512
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown storage pool type %s"), type);
513
        goto cleanup;
514
    }
515 516 517

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
518
        goto cleanup;
519

520
    if (!backend->findPoolSources) {
521 522 523
        virReportError(VIR_ERR_NO_SUPPORT,
                       _("pool type '%s' does not support source "
                         "discovery"), type);
524 525 526 527
        goto cleanup;
    }

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

529
 cleanup:
530
    return ret;
531 532 533
}


534 535
static virStoragePoolObjPtr
virStoragePoolObjFromStoragePool(virStoragePoolPtr pool)
536
{
537 538
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    virStoragePoolObjPtr ret;
539

540
    storageDriverLock();
541 542 543 544 545
    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);
546
    }
547
    storageDriverUnlock();
548 549 550 551 552 553 554 555 556 557 558 559

    return ret;
}


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

    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
560 561 562 563

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

564 565
    ret = virStoragePoolObjIsActive(obj);

566
 cleanup:
567
    virStoragePoolObjUnlock(obj);
568 569 570
    return ret;
}

571
static int storagePoolIsPersistent(virStoragePoolPtr pool)
572 573 574 575
{
    virStoragePoolObjPtr obj;
    int ret = -1;

576 577
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
578 579 580 581

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

582 583
    ret = obj->configFile ? 1 : 0;

584
 cleanup:
585
    virStoragePoolObjUnlock(obj);
586 587 588 589
    return ret;
}


590
static virStoragePoolPtr
591 592 593
storagePoolCreateXML(virConnectPtr conn,
                     const char *xml,
                     unsigned int flags)
E
Eric Blake 已提交
594
{
595
    virStoragePoolDefPtr def;
596
    virStoragePoolObjPtr pool = NULL;
597
    virStoragePoolPtr ret = NULL;
598 599
    virStorageBackendPtr backend;

E
Eric Blake 已提交
600 601
    virCheckFlags(0, NULL);

602
    storageDriverLock();
603
    if (!(def = virStoragePoolDefParseString(xml)))
604
        goto cleanup;
605

606 607 608
    if (virStoragePoolCreateXMLEnsureACL(conn, def) < 0)
        goto cleanup;

609
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 1) < 0)
610
        goto cleanup;
611

612 613 614
    if (virStoragePoolSourceFindDuplicate(&driver->pools, def) < 0)
        goto cleanup;

615 616
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
617

618
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
619 620
        goto cleanup;
    def = NULL;
621

622
    if (backend->startPool &&
623 624 625
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
626
        goto cleanup;
627
    }
628

629 630 631
    if (backend->refreshPool(conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(conn, pool);
632 633
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
634
        goto cleanup;
635
    }
636
    VIR_INFO("Creating storage pool '%s'", pool->def->name);
637 638
    pool->active = 1;

639 640
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
641

642
 cleanup:
643
    virStoragePoolDefFree(def);
644
    if (pool)
645
        virStoragePoolObjUnlock(pool);
646
    storageDriverUnlock();
647 648 649 650
    return ret;
}

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

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

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

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

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

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

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

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

680
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
681
        virStoragePoolObjRemove(&driver->pools, pool);
682
        def = NULL;
683
        goto cleanup;
684
    }
685
    def = NULL;
686

687
    VIR_INFO("Defining storage pool '%s'", pool->def->name);
688 689
    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid,
                            NULL, NULL);
690

691
 cleanup:
692
    virStoragePoolDefFree(def);
693 694
    if (pool)
        virStoragePoolObjUnlock(pool);
695
    storageDriverUnlock();
696 697 698 699
    return ret;
}

static int
700 701
storagePoolUndefine(virStoragePoolPtr obj)
{
702 703
    virStoragePoolObjPtr pool;
    int ret = -1;
704

705
    storageDriverLock();
706 707 708
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
709
        virReportError(VIR_ERR_NO_STORAGE_POOL,
710 711
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
712
        goto cleanup;
713 714
    }

715 716 717
    if (virStoragePoolUndefineEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

718
    if (virStoragePoolObjIsActive(pool)) {
719
        virReportError(VIR_ERR_OPERATION_INVALID,
720 721
                       _("storage pool '%s' is still active"),
                       pool->def->name);
722
        goto cleanup;
723 724
    }

725
    if (pool->asyncjobs > 0) {
726 727 728
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
729 730 731
        goto cleanup;
    }

732
    if (virStoragePoolObjDeleteDef(pool) < 0)
733
        goto cleanup;
734

735 736
    if (unlink(pool->autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
        char ebuf[1024];
737
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
738
                  pool->autostartLink, virStrerror(errno, ebuf, sizeof(ebuf)));
739
    }
740

741 742
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
743

744
    VIR_INFO("Undefining storage pool '%s'", pool->def->name);
745
    virStoragePoolObjRemove(&driver->pools, pool);
746
    pool = NULL;
747
    ret = 0;
748

749
 cleanup:
750 751
    if (pool)
        virStoragePoolObjUnlock(pool);
752
    storageDriverUnlock();
753
    return ret;
754 755 756
}

static int
757 758
storagePoolCreate(virStoragePoolPtr obj,
                  unsigned int flags)
E
Eric Blake 已提交
759
{
760
    virStoragePoolObjPtr pool;
761
    virStorageBackendPtr backend;
762
    int ret = -1;
763

E
Eric Blake 已提交
764 765
    virCheckFlags(0, -1);

766 767
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
768

769 770 771
    if (virStoragePoolCreateEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

772 773
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
774 775

    if (virStoragePoolObjIsActive(pool)) {
776
        virReportError(VIR_ERR_OPERATION_INVALID,
777 778
                       _("storage pool '%s' is already active"),
                       pool->def->name);
779
        goto cleanup;
780 781 782
    }
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
783 784
        goto cleanup;

785 786 787
    if (backend->refreshPool(obj->conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
788
        goto cleanup;
789 790
    }

791
    VIR_INFO("Starting up storage pool '%s'", pool->def->name);
792
    pool->active = 1;
793
    ret = 0;
794

795
 cleanup:
796
    virStoragePoolObjUnlock(pool);
797
    return ret;
798 799 800 801
}

static int
storagePoolBuild(virStoragePoolPtr obj,
802 803
                 unsigned int flags)
{
804
    virStoragePoolObjPtr pool;
805
    virStorageBackendPtr backend;
806
    int ret = -1;
807

808 809
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
810

811 812 813
    if (virStoragePoolBuildEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

814 815
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
816 817

    if (virStoragePoolObjIsActive(pool)) {
818
        virReportError(VIR_ERR_OPERATION_INVALID,
819 820
                       _("storage pool '%s' is already active"),
                       pool->def->name);
821
        goto cleanup;
822 823 824 825
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
826 827
        goto cleanup;
    ret = 0;
828

829
 cleanup:
830
    virStoragePoolObjUnlock(pool);
831
    return ret;
832 833 834 835
}


static int
836 837
storagePoolDestroy(virStoragePoolPtr obj)
{
838
    virStoragePoolObjPtr pool;
839
    virStorageBackendPtr backend;
840
    int ret = -1;
841

842
    storageDriverLock();
843 844 845
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
846
        virReportError(VIR_ERR_NO_STORAGE_POOL,
847 848
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
849
        goto cleanup;
850 851
    }

852 853 854
    if (virStoragePoolDestroyEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

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

    if (!virStoragePoolObjIsActive(pool)) {
859
        virReportError(VIR_ERR_OPERATION_INVALID,
860
                       _("storage pool '%s' is not active"), pool->def->name);
861
        goto cleanup;
862 863
    }

864
    if (pool->asyncjobs > 0) {
865 866 867
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
868 869 870
        goto cleanup;
    }

871 872
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
873
        goto cleanup;
874 875 876 877

    virStoragePoolObjClearVols(pool);

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

880
    if (pool->configFile == NULL) {
881
        virStoragePoolObjRemove(&driver->pools, pool);
882
        pool = NULL;
883 884 885 886
    } else if (pool->newDef) {
        virStoragePoolDefFree(pool->def);
        pool->def = pool->newDef;
        pool->newDef = NULL;
887
    }
888
    ret = 0;
889

890
 cleanup:
891 892
    if (pool)
        virStoragePoolObjUnlock(pool);
893
    storageDriverUnlock();
894
    return ret;
895 896 897 898
}

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

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

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

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

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

921
    if (pool->asyncjobs > 0) {
922 923
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
924 925 926 927
                              pool->def->name);
        goto cleanup;
    }

928
    if (!backend->deletePool) {
929 930
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("pool does not support pool deletion"));
931
        goto cleanup;
932 933
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
934
        goto cleanup;
935
    VIR_INFO("Deleting storage pool '%s'", pool->def->name);
936
    ret = 0;
937

938
 cleanup:
939
    virStoragePoolObjUnlock(pool);
940
    return ret;
941 942 943 944 945
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
E
Eric Blake 已提交
946 947
                   unsigned int flags)
{
948
    virStoragePoolObjPtr pool;
949
    virStorageBackendPtr backend;
950
    int ret = -1;
951

E
Eric Blake 已提交
952 953
    virCheckFlags(0, -1);

954
    storageDriverLock();
955 956 957
    if (!(pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid))) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
958
        virReportError(VIR_ERR_NO_STORAGE_POOL,
959 960
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
961
        goto cleanup;
962 963
    }

964 965 966
    if (virStoragePoolRefreshEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

967 968
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
969 970

    if (!virStoragePoolObjIsActive(pool)) {
971
        virReportError(VIR_ERR_OPERATION_INVALID,
972
                       _("storage pool '%s' is not active"), pool->def->name);
973
        goto cleanup;
974 975
    }

976
    if (pool->asyncjobs > 0) {
977 978 979
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("pool '%s' has asynchronous jobs running."),
                       pool->def->name);
980 981 982
        goto cleanup;
    }

983
    virStoragePoolObjClearVols(pool);
984
    if (backend->refreshPool(obj->conn, pool) < 0) {
985 986 987 988 989
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

990
        if (pool->configFile == NULL) {
991
            virStoragePoolObjRemove(&driver->pools, pool);
992 993
            pool = NULL;
        }
994
        goto cleanup;
995
    }
996
    ret = 0;
997

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


static int
storagePoolGetInfo(virStoragePoolPtr obj,
1008 1009
                   virStoragePoolInfoPtr info)
{
1010 1011
    virStoragePoolObjPtr pool;
    int ret = -1;
1012

1013 1014
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1015

1016 1017 1018
    if (virStoragePoolGetInfoEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1019
    if (virStorageBackendForType(pool->def->type) == NULL)
1020
        goto cleanup;
1021 1022 1023 1024 1025 1026 1027 1028 1029

    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;
1030
    ret = 0;
1031

1032
 cleanup:
1033
    virStoragePoolObjUnlock(pool);
1034
    return ret;
1035 1036 1037
}

static char *
1038
storagePoolGetXMLDesc(virStoragePoolPtr obj,
E
Eric Blake 已提交
1039 1040
                      unsigned int flags)
{
1041
    virStoragePoolObjPtr pool;
1042
    virStoragePoolDefPtr def;
1043
    char *ret = NULL;
1044

1045
    virCheckFlags(VIR_STORAGE_XML_INACTIVE, NULL);
E
Eric Blake 已提交
1046

1047 1048
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1049

1050 1051 1052
    if (virStoragePoolGetXMLDescEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1053 1054 1055 1056 1057 1058
    if ((flags & VIR_STORAGE_XML_INACTIVE) && pool->newDef)
        def = pool->newDef;
    else
        def = pool->def;

    ret = virStoragePoolDefFormat(def);
1059

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

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
1067 1068
                        int *autostart)
{
1069 1070
    virStoragePoolObjPtr pool;
    int ret = -1;
1071

1072 1073
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1074

1075 1076 1077
    if (virStoragePoolGetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1078 1079 1080 1081 1082
    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
1083
    ret = 0;
1084

1085
 cleanup:
1086
    virStoragePoolObjUnlock(pool);
1087
    return ret;
1088 1089 1090 1091
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
1092 1093
                        int autostart)
{
1094 1095
    virStoragePoolObjPtr pool;
    int ret = -1;
1096

1097
    storageDriverLock();
1098
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1099

1100
    if (!pool) {
1101 1102
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1103
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1104 1105
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1106
        goto cleanup;
1107 1108
    }

1109 1110 1111
    if (virStoragePoolSetAutostartEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1112
    if (!pool->configFile) {
1113 1114
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("pool has no config file"));
1115
        goto cleanup;
1116 1117 1118 1119
    }

    autostart = (autostart != 0);

1120 1121
    if (pool->autostart != autostart) {
        if (autostart) {
1122 1123
            if (virFileMakePath(driver->autostartDir) < 0) {
                virReportSystemError(errno,
1124 1125
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1126 1127
                goto cleanup;
            }
1128

1129
            if (symlink(pool->configFile, pool->autostartLink) < 0) {
1130
                virReportSystemError(errno,
1131 1132
                                     _("Failed to create symlink '%s' to '%s'"),
                                     pool->autostartLink, pool->configFile);
1133 1134 1135 1136 1137
                goto cleanup;
            }
        } else {
            if (unlink(pool->autostartLink) < 0 &&
                errno != ENOENT && errno != ENOTDIR) {
1138
                virReportSystemError(errno,
1139 1140
                                     _("Failed to delete symlink '%s'"),
                                     pool->autostartLink);
1141 1142
                goto cleanup;
            }
1143
        }
1144
        pool->autostart = autostart;
1145
    }
1146
    ret = 0;
1147

1148
 cleanup:
1149 1150
    if (pool)
        virStoragePoolObjUnlock(pool);
1151
    storageDriverUnlock();
1152
    return ret;
1153 1154 1155 1156
}


static int
1157 1158
storagePoolNumOfVolumes(virStoragePoolPtr obj)
{
1159
    virStoragePoolObjPtr pool;
1160 1161
    int ret = -1;
    size_t i;
1162

1163 1164
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1165

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

1169
    if (!virStoragePoolObjIsActive(pool)) {
1170
        virReportError(VIR_ERR_OPERATION_INVALID,
1171
                       _("storage pool '%s' is not active"), pool->def->name);
1172
        goto cleanup;
1173
    }
1174 1175 1176 1177 1178 1179
    ret = 0;
    for (i = 0; i < pool->volumes.count; i++) {
        if (virStoragePoolNumOfVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            ret++;
    }
1180

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

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
1189 1190
                       int maxnames)
{
1191
    virStoragePoolObjPtr pool;
1192 1193
    size_t i;
    int n = 0;
1194

1195 1196
    memset(names, 0, maxnames * sizeof(*names));

1197 1198
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return -1;
1199

1200 1201 1202
    if (virStoragePoolListVolumesEnsureACL(obj->conn, pool->def) < 0)
        goto cleanup;

1203
    if (!virStoragePoolObjIsActive(pool)) {
1204
        virReportError(VIR_ERR_OPERATION_INVALID,
1205
                       _("storage pool '%s' is not active"), pool->def->name);
1206
        goto cleanup;
1207 1208
    }

1209
    for (i = 0; i < pool->volumes.count && n < maxnames; i++) {
1210 1211 1212
        if (!virStoragePoolListVolumesCheckACL(obj->conn, pool->def,
                                               pool->volumes.objs[i]))
            continue;
1213
        if (VIR_STRDUP(names[n++], pool->volumes.objs[i]->name) < 0)
1214 1215 1216
            goto cleanup;
    }

1217
    virStoragePoolObjUnlock(pool);
1218
    return n;
1219 1220

 cleanup:
1221
    virStoragePoolObjUnlock(pool);
1222
    for (n = 0; n < maxnames; n++)
1223
        VIR_FREE(names[n]);
1224

1225
    memset(names, 0, maxnames * sizeof(*names));
1226 1227 1228
    return -1;
}

1229 1230 1231
static int
storagePoolListAllVolumes(virStoragePoolPtr pool,
                          virStorageVolPtr **vols,
1232 1233
                          unsigned int flags)
{
1234
    virStoragePoolObjPtr obj;
1235
    size_t i;
1236 1237 1238 1239 1240 1241 1242
    virStorageVolPtr *tmp_vols = NULL;
    virStorageVolPtr vol = NULL;
    int nvols = 0;
    int ret = -1;

    virCheckFlags(0, -1);

1243 1244
    if (!(obj = virStoragePoolObjFromStoragePool(pool)))
        return -1;
1245

1246 1247 1248
    if (virStoragePoolListAllVolumesEnsureACL(pool->conn, obj->def) < 0)
        goto cleanup;

1249
    if (!virStoragePoolObjIsActive(obj)) {
1250 1251
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("storage pool '%s' is not active"), obj->def->name);
1252 1253 1254 1255 1256 1257 1258 1259 1260
        goto cleanup;
    }

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

1261
    if (VIR_ALLOC_N(tmp_vols, obj->volumes.count + 1) < 0)
1262
        goto cleanup;
1263

1264
    for (i = 0; i < obj->volumes.count; i++) {
1265 1266 1267
        if (!virStoragePoolListAllVolumesCheckACL(pool->conn, obj->def,
                                                  obj->volumes.objs[i]))
            continue;
1268 1269
        if (!(vol = virGetStorageVol(pool->conn, obj->def->name,
                                     obj->volumes.objs[i]->name,
1270 1271
                                     obj->volumes.objs[i]->key,
                                     NULL, NULL)))
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
            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]);
        }
1286
        VIR_FREE(tmp_vols);
1287 1288
    }

1289
    virStoragePoolObjUnlock(obj);
1290 1291 1292

    return ret;
}
1293 1294

static virStorageVolPtr
1295
storageVolLookupByName(virStoragePoolPtr obj,
1296 1297
                       const char *name)
{
1298
    virStoragePoolObjPtr pool;
1299
    virStorageVolDefPtr vol;
1300
    virStorageVolPtr ret = NULL;
1301

1302 1303
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1304 1305

    if (!virStoragePoolObjIsActive(pool)) {
1306
        virReportError(VIR_ERR_OPERATION_INVALID,
1307
                       _("storage pool '%s' is not active"), pool->def->name);
1308
        goto cleanup;
1309 1310 1311 1312 1313
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1314 1315 1316
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       name);
1317
        goto cleanup;
1318 1319
    }

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

1323 1324
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key,
                           NULL, NULL);
1325

1326
 cleanup:
1327
    virStoragePoolObjUnlock(pool);
1328
    return ret;
1329 1330 1331 1332
}


static virStorageVolPtr
1333
storageVolLookupByKey(virConnectPtr conn,
1334 1335
                      const char *key)
{
1336
    size_t i;
1337
    virStorageVolPtr ret = NULL;
1338

1339
    storageDriverLock();
1340
    for (i = 0; i < driver->pools.count && !ret; i++) {
1341
        virStoragePoolObjLock(driver->pools.objs[i]);
1342 1343 1344
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1345

1346
            if (vol) {
1347 1348
                if (virStorageVolLookupByKeyEnsureACL(conn, driver->pools.objs[i]->def, vol) < 0) {
                    virStoragePoolObjUnlock(driver->pools.objs[i]);
1349
                    goto cleanup;
1350
                }
1351

1352
                ret = virGetStorageVol(conn,
1353 1354
                                       driver->pools.objs[i]->def->name,
                                       vol->name,
1355 1356
                                       vol->key,
                                       NULL, NULL);
1357
            }
1358
        }
1359
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1360 1361
    }

1362
    if (!ret)
1363
        virReportError(VIR_ERR_NO_STORAGE_VOL,
1364
                       _("no storage vol with matching key %s"), key);
1365

1366
 cleanup:
1367
    storageDriverUnlock();
1368
    return ret;
1369 1370 1371
}

static virStorageVolPtr
1372
storageVolLookupByPath(virConnectPtr conn,
1373 1374
                       const char *path)
{
1375
    size_t i;
1376
    virStorageVolPtr ret = NULL;
1377 1378 1379 1380 1381
    char *cleanpath;

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

1383
    storageDriverLock();
1384
    for (i = 0; i < driver->pools.count && !ret; i++) {
1385 1386 1387 1388 1389
        virStoragePoolObjPtr pool = driver->pools.objs[i];
        virStorageVolDefPtr vol;
        char *stable_path = NULL;

        virStoragePoolObjLock(pool);
1390

1391 1392 1393 1394
        if (!virStoragePoolObjIsActive(pool)) {
           virStoragePoolObjUnlock(pool);
           continue;
        }
1395

1396
        switch ((virStoragePoolType) pool->def->type) {
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
            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 已提交
1422
            case VIR_STORAGE_POOL_ZFS:
1423 1424 1425
            case VIR_STORAGE_POOL_LAST:
                if (VIR_STRDUP(stable_path, path) < 0) {
                     virStoragePoolObjUnlock(pool);
1426
                    goto cleanup;
1427
                }
1428 1429
                break;
        }
1430

1431 1432 1433 1434 1435 1436 1437
        vol = virStorageVolDefFindByPath(pool, stable_path);
        VIR_FREE(stable_path);

        if (vol) {
            if (virStorageVolLookupByPathEnsureACL(conn, pool->def, vol) < 0) {
                virStoragePoolObjUnlock(pool);
                goto cleanup;
1438
            }
1439 1440 1441 1442

            ret = virGetStorageVol(conn, pool->def->name,
                                   vol->name, vol->key,
                                   NULL, NULL);
1443
        }
1444 1445

        virStoragePoolObjUnlock(pool);
1446 1447
    }

1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
    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);
        }
    }
1458

1459
 cleanup:
1460
    VIR_FREE(cleanpath);
1461
    storageDriverUnlock();
1462
    return ret;
1463 1464
}

1465

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


1512 1513 1514 1515
static virStorageVolDefPtr
virStorageVolDefFromVol(virStorageVolPtr obj,
                        virStoragePoolObjPtr *pool,
                        virStorageBackendPtr *backend)
1516 1517
{
    virStorageVolDefPtr vol = NULL;
1518 1519

    *pool = NULL;
1520

1521
    storageDriverLock();
1522
    *pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1523
    storageDriverUnlock();
1524

1525
    if (!*pool) {
1526 1527 1528
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       obj->pool);
1529
        return NULL;
1530 1531
    }

1532
    if (!virStoragePoolObjIsActive(*pool)) {
1533
        virReportError(VIR_ERR_OPERATION_INVALID,
1534 1535 1536
                       _("storage pool '%s' is not active"),
                       (*pool)->def->name);
        goto error;
1537 1538
    }

1539
    if (!(vol = virStorageVolDefFindByName(*pool, obj->name))) {
1540 1541 1542
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       obj->name);
1543
        goto error;
1544 1545
    }

1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    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;

1573 1574 1575
    if (virStorageVolDeleteEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

1576 1577 1578 1579 1580 1581 1582
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

1583 1584 1585 1586 1587 1588 1589
    if (vol->building) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
        goto cleanup;
    }

1590
    if (storageVolDeleteInternal(obj, backend, pool, vol, flags, true) < 0)
1591 1592 1593 1594
        goto cleanup;

    ret = 0;

1595
 cleanup:
1596
    virStoragePoolObjUnlock(pool);
1597 1598 1599
    return ret;
}

1600

1601
static virStorageVolPtr
1602 1603 1604
storageVolCreateXML(virStoragePoolPtr obj,
                    const char *xmldesc,
                    unsigned int flags)
E
Eric Blake 已提交
1605
{
1606
    virStoragePoolObjPtr pool;
1607
    virStorageBackendPtr backend;
1608 1609
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1610
    virStorageVolDefPtr buildvoldef = NULL;
1611

1612
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1613

1614 1615
    if (!(pool = virStoragePoolObjFromStoragePool(obj)))
        return NULL;
1616 1617

    if (!virStoragePoolObjIsActive(pool)) {
1618
        virReportError(VIR_ERR_OPERATION_INVALID,
1619
                       _("storage pool '%s' is not active"), pool->def->name);
1620
        goto cleanup;
1621 1622 1623
    }

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

1626
    voldef = virStorageVolDefParseString(pool->def, xmldesc);
1627
    if (voldef == NULL)
1628
        goto cleanup;
1629

1630 1631 1632
    if (virStorageVolCreateXMLEnsureACL(obj->conn, pool->def, voldef) < 0)
        goto cleanup;

1633
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1634
        virReportError(VIR_ERR_STORAGE_VOL_EXIST,
1635
                       _("'%s'"), voldef->name);
1636
        goto cleanup;
1637 1638
    }

1639
    if (VIR_REALLOC_N(pool->volumes.objs,
1640
                      pool->volumes.count+1) < 0)
1641
        goto cleanup;
1642

1643
    if (!backend->createVol) {
1644 1645 1646
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume "
                               "creation"));
1647
        goto cleanup;
1648 1649
    }

1650 1651 1652
    /* Wipe any key the user may have suggested, as volume creation
     * will generate the canonical key.  */
    VIR_FREE(voldef->key);
1653
    if (backend->createVol(obj->conn, pool, voldef) < 0) {
1654
        goto cleanup;
1655 1656
    }

1657 1658
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
1659
                              voldef->key, NULL, NULL);
1660 1661 1662 1663
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1664

1665 1666 1667 1668
    if (VIR_ALLOC(buildvoldef) < 0) {
        voldef = NULL;
        goto cleanup;
    }
1669

1670 1671 1672 1673 1674
    /* 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));
1675

1676 1677
    if (backend->buildVol) {
        int buildret;
1678 1679 1680

        /* Drop the pool lock during volume allocation */
        pool->asyncjobs++;
1681
        voldef->building = true;
1682 1683
        virStoragePoolObjUnlock(pool);

1684
        buildret = backend->buildVol(obj->conn, pool, buildvoldef, flags);
1685

1686
        storageDriverLock();
1687
        virStoragePoolObjLock(pool);
1688
        storageDriverUnlock();
1689

1690
        voldef->building = false;
1691 1692 1693
        pool->asyncjobs--;

        if (buildret < 0) {
1694 1695
            VIR_FREE(buildvoldef);
            storageVolDeleteInternal(volobj, backend, pool, voldef,
1696
                                     0, false);
1697
            voldef = NULL;
1698 1699 1700 1701 1702
            goto cleanup;
        }

    }

1703
    /* Update pool metadata */
1704 1705
    pool->def->allocation += buildvoldef->target.allocation;
    pool->def->available -= buildvoldef->target.allocation;
1706

1707
    VIR_INFO("Creating volume '%s' in storage pool '%s'",
1708
             volobj->name, pool->def->name);
1709 1710 1711
    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1712

1713
 cleanup:
1714
    virObjectUnref(volobj);
1715
    virStorageVolDefFree(voldef);
1716
    VIR_FREE(buildvoldef);
1717 1718
    if (pool)
        virStoragePoolObjUnlock(pool);
1719
    return ret;
1720 1721
}

1722
static virStorageVolPtr
1723 1724 1725 1726
storageVolCreateXMLFrom(virStoragePoolPtr obj,
                        const char *xmldesc,
                        virStorageVolPtr vobj,
                        unsigned int flags)
E
Eric Blake 已提交
1727
{
1728 1729 1730 1731
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
    virStorageVolDefPtr origvol = NULL, newvol = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
O
Osier Yang 已提交
1732
    unsigned long long allocation;
1733
    int buildret;
1734

1735
    virCheckFlags(VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA, NULL);
E
Eric Blake 已提交
1736

1737
    storageDriverLock();
1738
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1739
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1740
        virStoragePoolObjUnlock(pool);
1741
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1742
        virStoragePoolObjLock(pool);
1743
    }
1744
    storageDriverUnlock();
1745
    if (!pool) {
1746 1747
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(obj->uuid, uuidstr);
1748
        virReportError(VIR_ERR_NO_STORAGE_POOL,
1749 1750
                       _("no storage pool with matching uuid '%s' (%s)"),
                       uuidstr, obj->name);
1751 1752 1753
        goto cleanup;
    }

1754
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1755 1756 1757
        virReportError(VIR_ERR_NO_STORAGE_POOL,
                       _("no storage pool with matching name '%s'"),
                       vobj->pool);
1758 1759 1760 1761
        goto cleanup;
    }

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

1767
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1768
        virReportError(VIR_ERR_OPERATION_INVALID,
1769 1770
                       _("storage pool '%s' is not active"),
                       origpool->def->name);
1771 1772 1773 1774 1775 1776
        goto cleanup;
    }

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

1777
    origvol = virStorageVolDefFindByName(origpool ? origpool : pool, vobj->name);
1778
    if (!origvol) {
1779 1780 1781
        virReportError(VIR_ERR_NO_STORAGE_VOL,
                       _("no storage vol with matching name '%s'"),
                       vobj->name);
1782 1783 1784
        goto cleanup;
    }

1785
    newvol = virStorageVolDefParseString(pool->def, xmldesc);
1786 1787 1788
    if (newvol == NULL)
        goto cleanup;

1789 1790 1791
    if (virStorageVolCreateXMLFromEnsureACL(obj->conn, pool->def, newvol) < 0)
        goto cleanup;

1792
    if (virStorageVolDefFindByName(pool, newvol->name)) {
1793 1794 1795
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("storage volume name '%s' already in use."),
                       newvol->name);
1796 1797 1798 1799
        goto cleanup;
    }

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

1803 1804
    /* Make sure allocation is at least as large as the destination cap,
     * to make absolutely sure we copy all possible contents */
1805 1806
    if (newvol->target.allocation < origvol->target.capacity)
        newvol->target.allocation = origvol->target.capacity;
1807

1808
    if (!backend->buildVolFrom) {
1809 1810
        virReportError(VIR_ERR_NO_SUPPORT,
                       "%s", _("storage pool does not support volume creation from an existing volume"));
1811 1812 1813 1814
        goto cleanup;
    }

    if (origvol->building) {
1815 1816 1817
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       origvol->name);
1818 1819 1820 1821 1822 1823 1824 1825
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
1826
                      pool->volumes.count+1) < 0)
1827 1828
        goto cleanup;

1829 1830 1831 1832
    /* '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);
1833 1834 1835 1836 1837 1838
    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,
1839
                              newvol->key, NULL, NULL);
1840 1841 1842 1843
    if (!volobj) {
        pool->volumes.count--;
        goto cleanup;
    }
1844 1845 1846

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
1847
    newvol->building = true;
1848
    origvol->in_use++;
1849 1850
    virStoragePoolObjUnlock(pool);

1851
    if (origpool) {
1852 1853 1854 1855
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

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

1858
    storageDriverLock();
1859
    virStoragePoolObjLock(pool);
1860
    if (origpool)
1861
        virStoragePoolObjLock(origpool);
1862
    storageDriverUnlock();
1863

1864
    origvol->in_use--;
1865
    newvol->building = false;
1866
    allocation = newvol->target.allocation;
1867 1868
    pool->asyncjobs--;

1869
    if (origpool) {
1870 1871 1872 1873 1874 1875
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
1876 1877
        storageVolDeleteInternal(volobj, backend, pool, newvol, 0, false);
        newvol = NULL;
1878 1879
        goto cleanup;
    }
1880
    newvol = NULL;
1881

1882
    /* Updating pool metadata */
O
Osier Yang 已提交
1883 1884
    pool->def->allocation += allocation;
    pool->def->available -= allocation;
1885

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

1891
 cleanup:
1892
    virObjectUnref(volobj);
1893 1894 1895
    virStorageVolDefFree(newvol);
    if (pool)
        virStoragePoolObjUnlock(pool);
1896
    if (origpool)
1897 1898 1899 1900
        virStoragePoolObjUnlock(origpool);
    return ret;
}

1901

1902
static int
1903 1904 1905 1906 1907
storageVolDownload(virStorageVolPtr obj,
                   virStreamPtr stream,
                   unsigned long long offset,
                   unsigned long long length,
                   unsigned int flags)
1908
{
1909
    virStorageBackendPtr backend;
1910 1911 1912 1913 1914 1915
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

    virCheckFlags(0, -1);

1916
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
1917
        return -1;
1918

1919
    if (virStorageVolDownloadEnsureACL(obj->conn, pool->def, vol) < 0)
1920
        goto cleanup;
1921

1922
    if (vol->building) {
1923 1924 1925
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
1926
        goto cleanup;
1927 1928
    }

1929 1930 1931
    if (!backend->downloadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume download"));
1932
        goto cleanup;
1933
    }
1934

1935 1936
    ret = backend->downloadVol(obj->conn, pool, vol, stream,
                               offset, length, flags);
1937

1938
 cleanup:
1939
    virStoragePoolObjUnlock(pool);
1940 1941 1942 1943 1944

    return ret;
}


1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
/**
 * 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;

1973 1974
    storageDriverLock();
    if (!(pool = virStoragePoolObjFindByName(&driver->pools,
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
                                             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);
1988
    storageDriverUnlock();
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
    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);
}

2017
static int
2018 2019 2020 2021 2022
storageVolUpload(virStorageVolPtr obj,
                 virStreamPtr stream,
                 unsigned long long offset,
                 unsigned long long length,
                 unsigned int flags)
2023
{
2024
    virStorageBackendPtr backend;
2025 2026
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
2027
    virStorageVolStreamInfoPtr cbdata = NULL;
2028 2029 2030 2031
    int ret = -1;

    virCheckFlags(0, -1);

2032
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
2033
        return -1;
2034

2035
    if (virStorageVolUploadEnsureACL(obj->conn, pool->def, vol) < 0)
2036
        goto cleanup;
2037

2038 2039 2040 2041 2042 2043 2044
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2045
    if (vol->building) {
2046 2047 2048
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2049
        goto cleanup;
2050 2051
    }

2052 2053 2054
    if (!backend->uploadVol) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("storage pool doesn't support volume upload"));
2055
        goto cleanup;
2056
    }
2057

2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
    /* 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;
    }

2070 2071
    ret = backend->uploadVol(obj->conn, pool, vol, stream,
                             offset, length, flags);
2072

2073 2074 2075 2076 2077 2078 2079 2080 2081 2082
    /* Add cleanup callback - call after uploadVol since the stream
     * is then fully set up
     */
    if (cbdata) {
        virFDStreamSetInternalCloseCb(stream,
                                      virStorageVolFDStreamCloseCb,
                                      cbdata, NULL);
        cbdata = NULL;
    }

2083
 cleanup:
2084
    virStoragePoolObjUnlock(pool);
2085 2086
    if (cbdata)
        virStorageVolPoolRefreshDataFree(cbdata);
2087 2088 2089 2090

    return ret;
}

2091
static int
2092 2093 2094
storageVolResize(virStorageVolPtr obj,
                 unsigned long long capacity,
                 unsigned int flags)
2095 2096 2097 2098 2099 2100 2101
{
    virStorageBackendPtr backend;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    unsigned long long abs_capacity;
    int ret = -1;

2102
    virCheckFlags(VIR_STORAGE_VOL_RESIZE_ALLOCATE |
2103 2104
                  VIR_STORAGE_VOL_RESIZE_DELTA |
                  VIR_STORAGE_VOL_RESIZE_SHRINK, -1);
2105

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

2109
    if (virStorageVolResizeEnsureACL(obj->conn, pool->def, vol) < 0)
2110
        goto cleanup;
2111

2112 2113 2114 2115 2116 2117 2118
    if (vol->in_use) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still in use."),
                       vol->name);
        goto cleanup;
    }

2119
    if (vol->building) {
2120 2121 2122
        virReportError(VIR_ERR_OPERATION_INVALID,
                       _("volume '%s' is still being allocated."),
                       vol->name);
2123
        goto cleanup;
2124
    }
2125

2126
    if (flags & VIR_STORAGE_VOL_RESIZE_DELTA) {
2127
        abs_capacity = vol->target.capacity + capacity;
2128 2129 2130 2131 2132
        flags &= ~VIR_STORAGE_VOL_RESIZE_DELTA;
    } else {
        abs_capacity = capacity;
    }

2133
    if (abs_capacity < vol->target.allocation) {
2134
        virReportError(VIR_ERR_INVALID_ARG, "%s",
2135 2136
                       _("can't shrink capacity below "
                         "existing allocation"));
2137
        goto cleanup;
2138 2139
    }

2140
    if (abs_capacity < vol->target.capacity &&
2141 2142 2143 2144
        !(flags & VIR_STORAGE_VOL_RESIZE_SHRINK)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Can't shrink capacity below current "
                         "capacity with shrink flag explicitly specified"));
2145
        goto cleanup;
2146 2147
    }

2148
    if (abs_capacity > vol->target.capacity + pool->def->available) {
2149
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
2150
                       _("Not enough space left on storage pool"));
2151
        goto cleanup;
2152 2153 2154
    }

    if (!backend->resizeVol) {
2155
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
2156 2157
                       _("storage pool does not support changing of "
                         "volume capacity"));
2158
        goto cleanup;
2159 2160 2161
    }

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

2164
    vol->target.capacity = abs_capacity;
2165
    if (flags & VIR_STORAGE_VOL_RESIZE_ALLOCATE)
2166
        vol->target.allocation = abs_capacity;
2167 2168

    /* Update pool metadata */
2169 2170
    pool->def->allocation += (abs_capacity - vol->target.capacity);
    pool->def->available -= (abs_capacity - vol->target.capacity);
2171

O
Osier Yang 已提交
2172
    ret = 0;
2173

2174
 cleanup:
2175
    virStoragePoolObjUnlock(pool);
2176 2177 2178

    return ret;
}
2179

2180 2181

static int
2182 2183 2184
storageVolWipePattern(virStorageVolPtr obj,
                      unsigned int algorithm,
                      unsigned int flags)
2185
{
2186
    virStorageBackendPtr backend;
2187 2188 2189 2190
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

2191
    virCheckFlags(0, -1);
2192

2193
    if (algorithm >= VIR_STORAGE_VOL_WIPE_ALG_LAST) {
2194 2195 2196
        virReportError(VIR_ERR_INVALID_ARG,
                       _("wiping algorithm %d not supported"),
                       algorithm);
2197 2198 2199
        return -1;
    }

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


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

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

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

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

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

2229
 cleanup:
2230
    virStoragePoolObjUnlock(pool);
2231 2232 2233 2234

    return ret;
}

2235
static int
2236 2237
storageVolWipe(virStorageVolPtr obj,
               unsigned int flags)
2238
{
2239
    return storageVolWipePattern(obj, VIR_STORAGE_VOL_WIPE_ALG_ZERO, flags);
2240 2241
}

2242 2243

static int
2244
storageVolGetInfo(virStorageVolPtr obj,
2245 2246
                  virStorageVolInfoPtr info)
{
2247
    virStoragePoolObjPtr pool;
2248 2249
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2250
    int ret = -1;
2251

2252 2253
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return -1;
2254

2255 2256 2257
    if (virStorageVolGetInfoEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2258 2259
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
2260
        goto cleanup;
2261 2262

    memset(info, 0, sizeof(*info));
2263
    info->type = vol->type;
2264 2265
    info->capacity = vol->target.capacity;
    info->allocation = vol->target.allocation;
2266
    ret = 0;
2267

2268
 cleanup:
2269
    virStoragePoolObjUnlock(pool);
2270
    return ret;
2271 2272 2273
}

static char *
2274 2275
storageVolGetXMLDesc(virStorageVolPtr obj,
                     unsigned int flags)
E
Eric Blake 已提交
2276
{
2277
    virStoragePoolObjPtr pool;
2278 2279
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
2280
    char *ret = NULL;
2281

E
Eric Blake 已提交
2282 2283
    virCheckFlags(0, NULL);

2284 2285
    if (!(vol = virStorageVolDefFromVol(obj, &pool, &backend)))
        return NULL;
2286

2287 2288 2289
    if (virStorageVolGetXMLDescEnsureACL(obj->conn, pool->def, vol) < 0)
        goto cleanup;

2290 2291 2292
    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
        goto cleanup;
2293

2294
    ret = virStorageVolDefFormat(pool->def, vol);
2295

2296
 cleanup:
2297
    virStoragePoolObjUnlock(pool);
2298

2299
    return ret;
2300 2301 2302
}

static char *
2303 2304
storageVolGetPath(virStorageVolPtr obj)
{
2305
    virStoragePoolObjPtr pool;
2306
    virStorageVolDefPtr vol;
2307
    char *ret = NULL;
2308

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

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

2315
    ignore_value(VIR_STRDUP(ret, vol->target.path));
2316

2317
 cleanup:
2318
    virStoragePoolObjUnlock(pool);
2319 2320 2321
    return ret;
}

2322
static int
2323 2324 2325
storageConnectListAllStoragePools(virConnectPtr conn,
                                  virStoragePoolPtr **pools,
                                  unsigned int flags)
2326 2327 2328 2329 2330
{
    int ret = -1;

    virCheckFlags(VIR_CONNECT_LIST_STORAGE_POOLS_FILTERS_ALL, -1);

2331 2332 2333
    if (virConnectListAllStoragePoolsEnsureACL(conn) < 0)
        goto cleanup;

2334
    storageDriverLock();
2335 2336
    ret = virStoragePoolObjListExport(conn, driver->pools, pools,
                                      virConnectListAllStoragePoolsCheckACL, flags);
2337
    storageDriverUnlock();
2338

2339
 cleanup:
2340 2341 2342
    return ret;
}

2343

2344
static virStorageDriver storageDriver = {
2345
    .name = "storage",
2346 2347
    .storageOpen = storageOpen, /* 0.4.0 */
    .storageClose = storageClose, /* 0.4.0 */
2348 2349 2350 2351 2352 2353
    .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 */
2354 2355 2356
    .storagePoolLookupByName = storagePoolLookupByName, /* 0.4.0 */
    .storagePoolLookupByUUID = storagePoolLookupByUUID, /* 0.4.0 */
    .storagePoolLookupByVolume = storagePoolLookupByVolume, /* 0.4.0 */
2357 2358
    .storagePoolCreateXML = storagePoolCreateXML, /* 0.4.0 */
    .storagePoolDefineXML = storagePoolDefineXML, /* 0.4.0 */
2359 2360
    .storagePoolBuild = storagePoolBuild, /* 0.4.0 */
    .storagePoolUndefine = storagePoolUndefine, /* 0.4.0 */
2361
    .storagePoolCreate = storagePoolCreate, /* 0.4.0 */
2362 2363 2364 2365 2366 2367 2368
    .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 */
2369
    .storagePoolNumOfVolumes = storagePoolNumOfVolumes, /* 0.4.0 */
2370 2371 2372
    .storagePoolListVolumes = storagePoolListVolumes, /* 0.4.0 */
    .storagePoolListAllVolumes = storagePoolListAllVolumes, /* 0.10.2 */

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
    .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 */
2387 2388 2389

    .storagePoolIsActive = storagePoolIsActive, /* 0.7.3 */
    .storagePoolIsPersistent = storagePoolIsPersistent, /* 0.7.3 */
2390 2391 2392 2393
};


static virStateDriver stateDriver = {
2394
    .name = "Storage",
2395
    .stateInitialize = storageStateInitialize,
2396
    .stateAutoStart = storageStateAutoStart,
2397 2398
    .stateCleanup = storageStateCleanup,
    .stateReload = storageStateReload,
2399 2400
};

2401 2402 2403 2404
int storageRegister(void)
{
    if (virRegisterStorageDriver(&storageDriver) < 0)
        return -1;
2405 2406
    if (virRegisterStateDriver(&stateDriver) < 0)
        return -1;
2407 2408
    return 0;
}
2409 2410 2411


/* ----------- file handlers cooperating with storage driver --------------- */
2412 2413 2414
static bool
virStorageFileIsInitialized(virStorageSourcePtr src)
{
2415
    return src && src->drv;
2416 2417
}

2418 2419 2420 2421

static bool
virStorageFileSupportsBackingChainTraversal(virStorageSourcePtr src)
{
2422
    int actualType;
2423 2424 2425 2426
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2427
    actualType = virStorageSourceGetActualType(src);
2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442

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

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

2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454

/**
 * 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)
{
2455
    int actualType;
2456 2457 2458 2459
    virStorageFileBackendPtr backend;

    if (!src)
        return false;
2460
    actualType = virStorageSourceGetActualType(src);
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474

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

    return !!backend->storageFileChown;
}


2475
void
2476
virStorageFileDeinit(virStorageSourcePtr src)
2477
{
2478
    if (!virStorageFileIsInitialized(src))
2479 2480
        return;

2481 2482 2483
    if (src->drv->backend &&
        src->drv->backend->backendDeinit)
        src->drv->backend->backendDeinit(src);
2484

2485
    VIR_FREE(src->drv);
2486 2487 2488
}


2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501
/**
 * 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.
 */
2502
int
2503 2504
virStorageFileInitAs(virStorageSourcePtr src,
                     uid_t uid, gid_t gid)
2505
{
2506 2507 2508
    int actualType = virStorageSourceGetActualType(src);
    if (VIR_ALLOC(src->drv) < 0)
        return -1;
2509

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519
    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;

2520 2521
    if (!(src->drv->backend = virStorageFileBackendForType(actualType,
                                                           src->protocol)))
2522 2523
        goto error;

2524 2525
    if (src->drv->backend->backendInit &&
        src->drv->backend->backendInit(src) < 0)
2526 2527
        goto error;

2528
    return 0;
2529

2530
 error:
2531 2532
    VIR_FREE(src->drv);
    return -1;
2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545
}


/**
 * virStorageFileInit:
 *
 * See virStorageFileInitAs. The file is initialized to be accessed by the
 * current user.
 */
int
virStorageFileInit(virStorageSourcePtr src)
{
    return virStorageFileInitAs(src, -1, -1);
2546 2547 2548 2549 2550 2551
}


/**
 * virStorageFileCreate: Creates an empty storage file via storage driver
 *
2552
 * @src: file structure pointing to the file
2553 2554 2555 2556 2557
 *
 * 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
2558
virStorageFileCreate(virStorageSourcePtr src)
2559
{
2560 2561
    int ret;

2562 2563
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileCreate) {
2564 2565 2566 2567
        errno = ENOSYS;
        return -2;
    }

2568 2569 2570 2571 2572 2573
    ret = src->drv->backend->storageFileCreate(src);

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

    return ret;
2574 2575 2576 2577 2578 2579
}


/**
 * virStorageFileUnlink: Unlink storage file via storage driver
 *
2580
 * @src: file structure pointing to the file
2581 2582 2583 2584 2585 2586 2587
 *
 * 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
2588
virStorageFileUnlink(virStorageSourcePtr src)
2589
{
2590 2591
    int ret;

2592 2593
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileUnlink) {
2594 2595 2596 2597
        errno = ENOSYS;
        return -2;
    }

2598 2599 2600 2601 2602 2603
    ret = src->drv->backend->storageFileUnlink(src);

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

    return ret;
2604 2605 2606 2607 2608 2609
}


/**
 * virStorageFileStat: returns stat struct of a file via storage driver
 *
2610
 * @src: file structure pointing to the file
2611 2612 2613 2614 2615 2616
 * @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
2617
virStorageFileStat(virStorageSourcePtr src,
2618 2619
                   struct stat *st)
{
2620 2621
    int ret;

2622 2623
    if (!virStorageFileIsInitialized(src) ||
        !src->drv->backend->storageFileStat) {
2624 2625 2626 2627
        errno = ENOSYS;
        return -2;
    }

2628 2629 2630 2631 2632 2633
    ret = src->drv->backend->storageFileStat(src, st);

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

    return ret;
2634
}
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662


/**
 * 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 "
2663
                         "storage type %s (protocol: %s)"),
2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
                       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;
}
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704


/*
 * 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);
}
2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728


/**
 * 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);
}
2729 2730


2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758
/**
 * 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);
}


2759 2760 2761
/* Recursive workhorse for virStorageFileGetMetadata.  */
static int
virStorageFileGetMetadataRecurse(virStorageSourcePtr src,
2762
                                 virStorageSourcePtr parent,
2763 2764
                                 uid_t uid, gid_t gid,
                                 bool allow_probe,
2765
                                 bool report_broken,
2766 2767 2768
                                 virHashTablePtr cycle)
{
    int ret = -1;
2769
    const char *uniqueName;
2770 2771
    char *buf = NULL;
    ssize_t headerLen;
2772 2773 2774
    virStorageSourcePtr backingStore = NULL;
    int backingFormat;

2775 2776
    VIR_DEBUG("path=%s format=%d uid=%d gid=%d probe=%d",
              src->path, src->format,
2777 2778
              (int)uid, (int)gid, allow_probe);

2779 2780 2781 2782 2783
    /* exit if we can't load information about the current image */
    if (!virStorageFileSupportsBackingChainTraversal(src))
        return 0;

    if (virStorageFileInitAs(src, uid, gid) < 0)
2784
        return -1;
2785

2786
    if (virStorageFileAccess(src, F_OK) < 0) {
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798
        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);
        }

2799 2800 2801
        goto cleanup;
    }

2802 2803 2804 2805 2806 2807 2808 2809
    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;
2810 2811
    }

2812 2813
    if (virHashAddEntry(cycle, uniqueName, (void *)1) < 0)
        goto cleanup;
2814

2815 2816 2817
    if ((headerLen = virStorageFileReadHeader(src, VIR_STORAGE_MAX_HEADER,
                                              &buf)) < 0)
        goto cleanup;
2818

2819 2820
    if (virStorageFileGetMetadataInternal(src, buf, headerLen,
                                          &backingFormat) < 0)
2821
        goto cleanup;
2822 2823

    /* check whether we need to go deeper */
2824 2825 2826 2827
    if (!src->backingStoreRaw) {
        ret = 0;
        goto cleanup;
    }
2828

2829
    if (!(backingStore = virStorageSourceNewFromBacking(src)))
2830
        goto cleanup;
2831 2832 2833 2834 2835 2836 2837 2838

    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;

2839
    if ((ret = virStorageFileGetMetadataRecurse(backingStore, parent,
2840 2841 2842 2843 2844 2845
                                                uid, gid,
                                                allow_probe, report_broken,
                                                cycle)) < 0) {
        if (report_broken)
            goto cleanup;

2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
        /* if we fail somewhere midway, just accept and return a
         * broken chain */
        ret = 0;
        goto cleanup;
    }

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

 cleanup:
2857
    VIR_FREE(buf);
2858
    virStorageFileDeinit(src);
2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878
    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.
 *
2879 2880 2881
 * If @report_broken is true, the whole function fails with a possibly sane
 * error instead of just returning a broken chain.
 *
2882 2883 2884 2885 2886
 * Caller MUST free result after use via virStorageSourceFree.
 */
int
virStorageFileGetMetadata(virStorageSourcePtr src,
                          uid_t uid, gid_t gid,
2887 2888
                          bool allow_probe,
                          bool report_broken)
2889
{
2890 2891 2892
    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);
2893 2894 2895 2896 2897 2898 2899 2900 2901 2902

    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;

2903
    ret = virStorageFileGetMetadataRecurse(src, src, uid, gid,
2904
                                           allow_probe, report_broken, cycle);
2905 2906 2907 2908

    virHashFree(cycle);
    return ret;
}
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 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


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