storage_driver.c 56.4 KB
Newer Older
1 2 3
/*
 * storage_driver.c: core driver for storage APIs
 *
4
 * Copyright (C) 2006-2009 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
 * 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
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * 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 "virterror_internal.h"
40
#include "datatypes.h"
41 42 43 44
#include "driver.h"
#include "util.h"
#include "storage_driver.h"
#include "storage_conf.h"
45
#include "memory.h"
46
#include "storage_backend.h"
47
#include "logging.h"
48

49 50
#define VIR_FROM_THIS VIR_FROM_STORAGE

51 52 53 54
static virStorageDriverStatePtr driverState;

static int storageDriverShutdown(void);

55 56
static void storageDriverLock(virStorageDriverStatePtr driver)
{
57
    virMutexLock(&driver->lock);
58 59 60
}
static void storageDriverUnlock(virStorageDriverStatePtr driver)
{
61
    virMutexUnlock(&driver->lock);
62
}
63 64 65

static void
storageDriverAutostart(virStorageDriverStatePtr driver) {
66
    unsigned int i;
67

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

71
        virStoragePoolObjLock(pool);
72 73 74 75
        if (pool->autostart &&
            !virStoragePoolObjIsActive(pool)) {
            virStorageBackendPtr backend;
            if ((backend = virStorageBackendForType(pool->def->type)) == NULL) {
76
                VIR_ERROR(_("Missing backend %d"), pool->def->type);
77
                virStoragePoolObjUnlock(pool);
78 79 80 81 82 83
                continue;
            }

            if (backend->startPool &&
                backend->startPool(NULL, pool) < 0) {
                virErrorPtr err = virGetLastError();
84
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
85 86
                          pool->def->name, err ? err->message :
                          "no error message found");
87
                virStoragePoolObjUnlock(pool);
88 89 90 91 92 93 94
                continue;
            }

            if (backend->refreshPool(NULL, pool) < 0) {
                virErrorPtr err = virGetLastError();
                if (backend->stopPool)
                    backend->stopPool(NULL, pool);
95
                VIR_ERROR(_("Failed to autostart storage pool '%s': %s"),
96 97
                          pool->def->name, err ? err->message :
                          "no error message found");
98
                virStoragePoolObjUnlock(pool);
99 100 101 102
                continue;
            }
            pool->active = 1;
        }
103
        virStoragePoolObjUnlock(pool);
104 105 106 107 108 109 110 111 112
    }
}

/**
 * virStorageStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
113
storageDriverStartup(int privileged) {
114 115 116
    char *base = NULL;
    char driverConf[PATH_MAX];

117
    if (VIR_ALLOC(driverState) < 0)
118 119
        return -1;

120 121 122 123
    if (virMutexInit(&driverState->lock) < 0) {
        VIR_FREE(driverState);
        return -1;
    }
124 125
    storageDriverLock(driverState);

126
    if (privileged) {
127 128 129
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
            goto out_of_memory;
    } else {
130
        uid_t uid = geteuid();
131
        char *userdir = virGetUserDirectory(uid);
132 133 134

        if (!userdir)
            goto error;
135

136 137
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
138 139
            goto out_of_memory;
        }
140
        VIR_FREE(userdir);
141 142 143 144 145 146 147 148 149 150
    }

    /* Configuration paths are either ~/.libvirt/storage/... (session) or
     * /etc/libvirt/storage/... (system).
     */
    if (snprintf (driverConf, sizeof(driverConf),
                  "%s/storage.conf", base) == -1)
        goto out_of_memory;
    driverConf[sizeof(driverConf)-1] = '\0';

151 152
    if (virAsprintf(&driverState->configDir,
                    "%s/storage", base) == -1)
153 154
        goto out_of_memory;

155 156
    if (virAsprintf(&driverState->autostartDir,
                    "%s/storage/autostart", base) == -1)
157 158
        goto out_of_memory;

159
    VIR_FREE(base);
160 161 162 163 164 165 166 167

    /*
    if (virStorageLoadDriverConfig(driver, driverConf) < 0) {
        virStorageDriverShutdown();
        return -1;
    }
    */

168
    if (virStoragePoolLoadAllConfigs(&driverState->pools,
169
                                     driverState->configDir,
170 171
                                     driverState->autostartDir) < 0)
        goto error;
172 173
    storageDriverAutostart(driverState);

174
    storageDriverUnlock(driverState);
175 176
    return 0;

177
out_of_memory:
178
    virReportOOMError();
179 180 181 182
error:
    VIR_FREE(base);
    storageDriverUnlock(driverState);
    storageDriverShutdown();
183 184 185 186 187 188 189 190 191 192 193
    return -1;
}

/**
 * virStorageReload:
 *
 * Function to restart the storage driver, it will recheck the configuration
 * files and update its state
 */
static int
storageDriverReload(void) {
194 195 196
    if (!driverState)
        return -1;

197
    storageDriverLock(driverState);
198
    virStoragePoolLoadAllConfigs(&driverState->pools,
199 200
                                 driverState->configDir,
                                 driverState->autostartDir);
201
    storageDriverAutostart(driverState);
202
    storageDriverUnlock(driverState);
203 204 205 206 207 208 209 210 211 212 213 214 215

    return 0;
}

/**
 * virStorageActive:
 *
 * Checks if the storage driver is active, i.e. has an active pool
 *
 * Returns 1 if active, 0 otherwise
 */
static int
storageDriverActive(void) {
216
    unsigned int i;
217
    int active = 0;
218 219 220 221

    if (!driverState)
        return 0;

222 223 224 225
    storageDriverLock(driverState);

    for (i = 0 ; i < driverState->pools.count ; i++) {
        virStoragePoolObjLock(driverState->pools.objs[i]);
226
        if (virStoragePoolObjIsActive(driverState->pools.objs[i]))
227 228 229
            active = 1;
        virStoragePoolObjUnlock(driverState->pools.objs[i]);
    }
230

231 232
    storageDriverUnlock(driverState);
    return active;
233 234 235 236 237 238 239 240 241 242 243 244
}

/**
 * virStorageShutdown:
 *
 * Shutdown the storage driver, it will stop all active storage pools
 */
static int
storageDriverShutdown(void) {
    if (!driverState)
        return -1;

245
    storageDriverLock(driverState);
246 247

    /* free inactive pools */
248 249 250 251
    virStoragePoolObjListFree(&driverState->pools);

    VIR_FREE(driverState->configDir);
    VIR_FREE(driverState->autostartDir);
252
    storageDriverUnlock(driverState);
253
    virMutexDestroy(&driverState->lock);
254
    VIR_FREE(driverState);
255 256 257 258 259 260 261 262 263

    return 0;
}



static virStoragePoolPtr
storagePoolLookupByUUID(virConnectPtr conn,
                        const unsigned char *uuid) {
264 265 266
    virStorageDriverStatePtr driver = conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
267

268
    storageDriverLock(driver);
269
    pool = virStoragePoolObjFindByUUID(&driver->pools, uuid);
270 271
    storageDriverUnlock(driver);

272
    if (!pool) {
273
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
274
                              "%s", _("no pool with matching uuid"));
275
        goto cleanup;
276 277 278
    }

    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid);
279 280

cleanup:
281 282
    if (pool)
        virStoragePoolObjUnlock(pool);
283 284 285 286 287 288
    return ret;
}

static virStoragePoolPtr
storagePoolLookupByName(virConnectPtr conn,
                        const char *name) {
289 290 291
    virStorageDriverStatePtr driver = conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    virStoragePoolPtr ret = NULL;
292

293
    storageDriverLock(driver);
294
    pool = virStoragePoolObjFindByName(&driver->pools, name);
295 296
    storageDriverUnlock(driver);

297
    if (!pool) {
298
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
299
                              _("no pool with matching name '%s'"), name);
300
        goto cleanup;
301 302 303
    }

    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid);
304 305

cleanup:
306 307
    if (pool)
        virStoragePoolObjUnlock(pool);
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    return ret;
}

static virStoragePoolPtr
storagePoolLookupByVolume(virStorageVolPtr vol) {
    return storagePoolLookupByName(vol->conn, vol->pool);
}

static virDrvOpenStatus
storageOpen(virConnectPtr conn,
            virConnectAuthPtr auth ATTRIBUTE_UNUSED,
            int flags ATTRIBUTE_UNUSED) {
    if (!driverState)
        return VIR_DRV_OPEN_DECLINED;

    conn->storagePrivateData = driverState;
    return VIR_DRV_OPEN_SUCCESS;
}

static int
storageClose(virConnectPtr conn) {
    conn->storagePrivateData = NULL;
    return 0;
}

static int
storageNumPools(virConnectPtr conn) {
335
    virStorageDriverStatePtr driver = conn->storagePrivateData;
336 337
    unsigned int i, nactive = 0;

338 339 340
    storageDriverLock(driver);
    for (i = 0 ; i < driver->pools.count ; i++) {
        virStoragePoolObjLock(driver->pools.objs[i]);
341 342
        if (virStoragePoolObjIsActive(driver->pools.objs[i]))
            nactive++;
343 344 345
        virStoragePoolObjUnlock(driver->pools.objs[i]);
    }
    storageDriverUnlock(driver);
346 347

    return nactive;
348 349 350 351 352 353
}

static int
storageListPools(virConnectPtr conn,
                 char **const names,
                 int nnames) {
354
    virStorageDriverStatePtr driver = conn->storagePrivateData;
355
    int got = 0, i;
356

357
    storageDriverLock(driver);
358
    for (i = 0 ; i < driver->pools.count && got < nnames ; i++) {
359
        virStoragePoolObjLock(driver->pools.objs[i]);
360 361
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            if (!(names[got] = strdup(driver->pools.objs[i]->def->name))) {
362
                virStoragePoolObjUnlock(driver->pools.objs[i]);
363
                virReportOOMError();
364 365 366 367
                goto cleanup;
            }
            got++;
        }
368
        virStoragePoolObjUnlock(driver->pools.objs[i]);
369
    }
370
    storageDriverUnlock(driver);
371 372 373
    return got;

 cleanup:
374 375 376
    storageDriverUnlock(driver);
    for (i = 0 ; i < got ; i++)
        VIR_FREE(names[i]);
377
    memset(names, 0, nnames * sizeof(*names));
378 379 380 381 382
    return -1;
}

static int
storageNumDefinedPools(virConnectPtr conn) {
383
    virStorageDriverStatePtr driver = conn->storagePrivateData;
384 385
    unsigned int i, nactive = 0;

386 387 388
    storageDriverLock(driver);
    for (i = 0 ; i < driver->pools.count ; i++) {
        virStoragePoolObjLock(driver->pools.objs[i]);
389 390
        if (!virStoragePoolObjIsActive(driver->pools.objs[i]))
            nactive++;
391 392 393
        virStoragePoolObjUnlock(driver->pools.objs[i]);
    }
    storageDriverUnlock(driver);
394 395

    return nactive;
396 397 398 399 400 401
}

static int
storageListDefinedPools(virConnectPtr conn,
                        char **const names,
                        int nnames) {
402
    virStorageDriverStatePtr driver = conn->storagePrivateData;
403
    int got = 0, i;
404

405
    storageDriverLock(driver);
406
    for (i = 0 ; i < driver->pools.count && got < nnames ; i++) {
407
        virStoragePoolObjLock(driver->pools.objs[i]);
408 409
        if (!virStoragePoolObjIsActive(driver->pools.objs[i])) {
            if (!(names[got] = strdup(driver->pools.objs[i]->def->name))) {
410
                virStoragePoolObjUnlock(driver->pools.objs[i]);
411
                virReportOOMError();
412 413 414 415
                goto cleanup;
            }
            got++;
        }
416
        virStoragePoolObjUnlock(driver->pools.objs[i]);
417
    }
418
    storageDriverUnlock(driver);
419 420 421
    return got;

 cleanup:
422
    storageDriverUnlock(driver);
423
    for (i = 0 ; i < got ; i++) {
424
        VIR_FREE(names[i]);
425
    }
426
    memset(names, 0, nnames * sizeof(*names));
427 428 429
    return -1;
}

430 431
/* This method is required to be re-entrant / thread safe, so
   uses no driver lock */
432 433 434 435 436 437 438 439
static char *
storageFindPoolSources(virConnectPtr conn,
                       const char *type,
                       const char *srcSpec,
                       unsigned int flags)
{
    int backend_type;
    virStorageBackendPtr backend;
440
    char *ret = NULL;
441

442
    backend_type = virStoragePoolTypeFromString(type);
443
    if (backend_type < 0) {
444
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
445
                              _("unknown storage pool type %s"), type);
446
        goto cleanup;
447
    }
448 449 450

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
451
        goto cleanup;
452

453
    if (!backend->findPoolSources) {
454
        virStorageReportError(VIR_ERR_NO_SUPPORT,
455 456 457 458 459 460
                              _("pool type '%s' does not support source "
                                "discovery"), type);
        goto cleanup;
    }

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

462 463
cleanup:
    return ret;
464 465 466
}


467
static int storagePoolIsActive(virStoragePoolPtr pool)
468
{
469
    virStorageDriverStatePtr driver = pool->conn->storagePrivateData;
470 471 472 473
    virStoragePoolObjPtr obj;
    int ret = -1;

    storageDriverLock(driver);
474
    obj = virStoragePoolObjFindByUUID(&driver->pools, pool->uuid);
475 476
    storageDriverUnlock(driver);
    if (!obj) {
477
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL, NULL);
478 479 480 481 482 483 484 485 486 487
        goto cleanup;
    }
    ret = virStoragePoolObjIsActive(obj);

cleanup:
    if (obj)
        virStoragePoolObjUnlock(obj);
    return ret;
}

488
static int storagePoolIsPersistent(virStoragePoolPtr pool)
489
{
490
    virStorageDriverStatePtr driver = pool->conn->storagePrivateData;
491 492 493 494
    virStoragePoolObjPtr obj;
    int ret = -1;

    storageDriverLock(driver);
495
    obj = virStoragePoolObjFindByUUID(&driver->pools, pool->uuid);
496 497
    storageDriverUnlock(driver);
    if (!obj) {
498
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL, NULL);
499 500 501 502 503 504 505 506 507 508 509
        goto cleanup;
    }
    ret = obj->configFile ? 1 : 0;

cleanup:
    if (obj)
        virStoragePoolObjUnlock(obj);
    return ret;
}


510 511 512 513
static virStoragePoolPtr
storagePoolCreate(virConnectPtr conn,
                  const char *xml,
                  unsigned int flags ATTRIBUTE_UNUSED) {
514
    virStorageDriverStatePtr driver = conn->storagePrivateData;
515
    virStoragePoolDefPtr def;
516
    virStoragePoolObjPtr pool = NULL;
517
    virStoragePoolPtr ret = NULL;
518 519
    virStorageBackendPtr backend;

520
    storageDriverLock(driver);
521
    if (!(def = virStoragePoolDefParseString(xml)))
522
        goto cleanup;
523

524
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 1) < 0)
525
        goto cleanup;
526

527 528
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
529

530
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
531 532
        goto cleanup;
    def = NULL;
533

534
    if (backend->startPool &&
535 536 537
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
538
        goto cleanup;
539
    }
540

541 542 543
    if (backend->refreshPool(conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(conn, pool);
544 545
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
546
        goto cleanup;
547 548 549 550 551
    }
    pool->active = 1;

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

552 553
cleanup:
    virStoragePoolDefFree(def);
554
    if (pool)
555
        virStoragePoolObjUnlock(pool);
556
    storageDriverUnlock(driver);
557 558 559 560 561 562 563
    return ret;
}

static virStoragePoolPtr
storagePoolDefine(virConnectPtr conn,
                  const char *xml,
                  unsigned int flags ATTRIBUTE_UNUSED) {
564
    virStorageDriverStatePtr driver = conn->storagePrivateData;
565
    virStoragePoolDefPtr def;
566
    virStoragePoolObjPtr pool = NULL;
567
    virStoragePoolPtr ret = NULL;
568

569
    storageDriverLock(driver);
570
    if (!(def = virStoragePoolDefParseString(xml)))
571
        goto cleanup;
572

573 574 575
    if (virStoragePoolObjIsDuplicate(&driver->pools, def, 0) < 0)
        goto cleanup;

576
    if (virStorageBackendForType(def->type) == NULL)
577
        goto cleanup;
578

579
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
580
        goto cleanup;
581

582
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
583
        virStoragePoolObjRemove(&driver->pools, pool);
584
        def = NULL;
585
        goto cleanup;
586
    }
587
    def = NULL;
588 589

    ret = virGetStoragePool(conn, pool->def->name, pool->def->uuid);
590 591 592

cleanup:
    virStoragePoolDefFree(def);
593 594 595
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
596 597 598 599 600
    return ret;
}

static int
storagePoolUndefine(virStoragePoolPtr obj) {
601 602 603
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
604

605
    storageDriverLock(driver);
606
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
607
    if (!pool) {
608
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
609
                              "%s", _("no storage pool with matching uuid"));
610
        goto cleanup;
611 612 613
    }

    if (virStoragePoolObjIsActive(pool)) {
614
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
615
                              "%s", _("pool is still active"));
616
        goto cleanup;
617 618
    }

619
    if (pool->asyncjobs > 0) {
620
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
621 622 623 624 625
                              _("pool '%s' has asynchronous jobs running."),
                              pool->def->name);
        goto cleanup;
    }

626
    if (virStoragePoolObjDeleteDef(pool) < 0)
627
        goto cleanup;
628

629 630
    if (unlink(pool->autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
        char ebuf[1024];
631
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
632 633
                   pool->autostartLink, virStrerror(errno, ebuf, sizeof ebuf));
    }
634

635 636
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
637

638
    virStoragePoolObjRemove(&driver->pools, pool);
639
    pool = NULL;
640
    ret = 0;
641

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

static int
storagePoolStart(virStoragePoolPtr obj,
                 unsigned int flags ATTRIBUTE_UNUSED) {
652 653
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
654
    virStorageBackendPtr backend;
655
    int ret = -1;
656

657
    storageDriverLock(driver);
658
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
659 660
    storageDriverUnlock(driver);

661
    if (!pool) {
662
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
663
                              "%s", _("no storage pool with matching uuid"));
664
        goto cleanup;
665 666
    }

667 668
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
669 670

    if (virStoragePoolObjIsActive(pool)) {
671
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
672
                              "%s", _("pool already active"));
673
        goto cleanup;
674 675 676
    }
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
677 678
        goto cleanup;

679 680 681
    if (backend->refreshPool(obj->conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
682
        goto cleanup;
683 684 685
    }

    pool->active = 1;
686
    ret = 0;
687

688
cleanup:
689 690
    if (pool)
        virStoragePoolObjUnlock(pool);
691
    return ret;
692 693 694 695 696
}

static int
storagePoolBuild(virStoragePoolPtr obj,
                 unsigned int flags) {
697 698
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
699
    virStorageBackendPtr backend;
700
    int ret = -1;
701

702
    storageDriverLock(driver);
703
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
704 705
    storageDriverUnlock(driver);

706
    if (!pool) {
707
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
708
                              "%s", _("no storage pool with matching uuid"));
709
        goto cleanup;
710 711
    }

712 713
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
714 715

    if (virStoragePoolObjIsActive(pool)) {
716
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
717
                              "%s", _("storage pool is already active"));
718
        goto cleanup;
719 720 721 722
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
723 724
        goto cleanup;
    ret = 0;
725

726
cleanup:
727 728
    if (pool)
        virStoragePoolObjUnlock(pool);
729
    return ret;
730 731 732 733 734
}


static int
storagePoolDestroy(virStoragePoolPtr obj) {
735 736
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
737
    virStorageBackendPtr backend;
738
    int ret = -1;
739

740
    storageDriverLock(driver);
741
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
742

743
    if (!pool) {
744
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
745
                              "%s", _("no storage pool with matching uuid"));
746
        goto cleanup;
747 748
    }

749 750
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
751 752

    if (!virStoragePoolObjIsActive(pool)) {
753
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
754
                              "%s", _("storage pool is not active"));
755
        goto cleanup;
756 757
    }

758
    if (pool->asyncjobs > 0) {
759
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
760 761 762 763 764
                              _("pool '%s' has asynchronous jobs running."),
                              pool->def->name);
        goto cleanup;
    }

765 766
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
767
        goto cleanup;
768 769 770 771 772

    virStoragePoolObjClearVols(pool);

    pool->active = 0;

773
    if (pool->configFile == NULL) {
774
        virStoragePoolObjRemove(&driver->pools, pool);
775 776
        pool = NULL;
    }
777
    ret = 0;
778

779
cleanup:
780 781 782
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
783
    return ret;
784 785 786 787 788 789
}


static int
storagePoolDelete(virStoragePoolPtr obj,
                  unsigned int flags) {
790 791
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
792
    virStorageBackendPtr backend;
793
    int ret = -1;
794

795
    storageDriverLock(driver);
796
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
797 798
    storageDriverUnlock(driver);

799
    if (!pool) {
800
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
801
                              "%s", _("no storage pool with matching uuid"));
802
        goto cleanup;
803 804
    }

805 806
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
807 808

    if (virStoragePoolObjIsActive(pool)) {
809
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
810
                              "%s", _("storage pool is still active"));
811
        goto cleanup;
812 813
    }

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

821
    if (!backend->deletePool) {
822
        virStorageReportError(VIR_ERR_NO_SUPPORT,
823
                              "%s", _("pool does not support pool deletion"));
824
        goto cleanup;
825 826
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
827 828
        goto cleanup;
    ret = 0;
829

830
cleanup:
831 832
    if (pool)
        virStoragePoolObjUnlock(pool);
833
    return ret;
834 835 836 837 838 839
}


static int
storagePoolRefresh(virStoragePoolPtr obj,
                   unsigned int flags ATTRIBUTE_UNUSED) {
840 841
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
842
    virStorageBackendPtr backend;
843
    int ret = -1;
844

845
    storageDriverLock(driver);
846
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
847

848
    if (!pool) {
849
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
850
                              "%s", _("no storage pool with matching uuid"));
851
        goto cleanup;
852 853
    }

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

    if (!virStoragePoolObjIsActive(pool)) {
858
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
859
                              "%s", _("storage pool is not active"));
860
        goto cleanup;
861 862
    }

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

870
    virStoragePoolObjClearVols(pool);
871
    if (backend->refreshPool(obj->conn, pool) < 0) {
872 873 874 875 876
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

877
        if (pool->configFile == NULL) {
878
            virStoragePoolObjRemove(&driver->pools, pool);
879 880
            pool = NULL;
        }
881
        goto cleanup;
882
    }
883
    ret = 0;
884

885
cleanup:
886 887
    if (pool)
        virStoragePoolObjUnlock(pool);
888
    storageDriverUnlock(driver);
889 890 891 892 893 894 895
    return ret;
}


static int
storagePoolGetInfo(virStoragePoolPtr obj,
                   virStoragePoolInfoPtr info) {
896 897 898
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
899

900
    storageDriverLock(driver);
901
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
902 903
    storageDriverUnlock(driver);

904
    if (!pool) {
905
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
906
                              "%s", _("no storage pool with matching uuid"));
907
        goto cleanup;
908 909
    }

910
    if (virStorageBackendForType(pool->def->type) == NULL)
911
        goto cleanup;
912 913 914 915 916 917 918 919 920

    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;
921
    ret = 0;
922

923
cleanup:
924 925
    if (pool)
        virStoragePoolObjUnlock(pool);
926
    return ret;
927 928 929 930 931
}

static char *
storagePoolDumpXML(virStoragePoolPtr obj,
                   unsigned int flags ATTRIBUTE_UNUSED) {
932 933 934
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    char *ret = NULL;
935

936
    storageDriverLock(driver);
937
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
938 939
    storageDriverUnlock(driver);

940
    if (!pool) {
941
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
942
                              "%s", _("no storage pool with matching uuid"));
943
        goto cleanup;
944 945
    }

946
    ret = virStoragePoolDefFormat(pool->def);
947 948

cleanup:
949 950
    if (pool)
        virStoragePoolObjUnlock(pool);
951
    return ret;
952 953 954 955 956
}

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
                        int *autostart) {
957 958 959
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
960

961
    storageDriverLock(driver);
962
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
963 964
    storageDriverUnlock(driver);

965
    if (!pool) {
966
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
967
                              "%s", _("no pool with matching uuid"));
968
        goto cleanup;
969 970 971 972 973 974 975
    }

    if (!pool->configFile) {
        *autostart = 0;
    } else {
        *autostart = pool->autostart;
    }
976
    ret = 0;
977

978
cleanup:
979 980
    if (pool)
        virStoragePoolObjUnlock(pool);
981
    return ret;
982 983 984 985 986
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
                        int autostart) {
987 988 989
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
990

991
    storageDriverLock(driver);
992
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
993

994
    if (!pool) {
995
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
996
                              "%s", _("no pool with matching uuid"));
997
        goto cleanup;
998 999 1000
    }

    if (!pool->configFile) {
1001
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1002
                              "%s", _("pool has no config file"));
1003
        goto cleanup;
1004 1005 1006 1007
    }

    autostart = (autostart != 0);

1008 1009 1010
    if (pool->autostart != autostart) {
        if (autostart) {
            int err;
1011

1012
            if ((err = virFileMakePath(driver->autostartDir))) {
1013
                virReportSystemError(err,
1014 1015
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1016 1017
                goto cleanup;
            }
1018

1019
            if (symlink(pool->configFile, pool->autostartLink) < 0) {
1020
                virReportSystemError(errno,
1021 1022
                                     _("Failed to create symlink '%s' to '%s'"),
                                     pool->autostartLink, pool->configFile);
1023 1024 1025 1026 1027
                goto cleanup;
            }
        } else {
            if (unlink(pool->autostartLink) < 0 &&
                errno != ENOENT && errno != ENOTDIR) {
1028
                virReportSystemError(errno,
1029 1030
                                     _("Failed to delete symlink '%s'"),
                                     pool->autostartLink);
1031 1032
                goto cleanup;
            }
1033
        }
1034
        pool->autostart = autostart;
1035
    }
1036
    ret = 0;
1037

1038
cleanup:
1039 1040
    if (pool)
        virStoragePoolObjUnlock(pool);
1041
    storageDriverUnlock(driver);
1042
    return ret;
1043 1044 1045 1046 1047
}


static int
storagePoolNumVolumes(virStoragePoolPtr obj) {
1048 1049 1050
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
1051

1052
    storageDriverLock(driver);
1053
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1054 1055
    storageDriverUnlock(driver);

1056
    if (!pool) {
1057
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1058
                              "%s", _("no storage pool with matching uuid"));
1059
        goto cleanup;
1060 1061 1062
    }

    if (!virStoragePoolObjIsActive(pool)) {
1063
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1064
                              "%s", _("storage pool is not active"));
1065
        goto cleanup;
1066
    }
1067
    ret = pool->volumes.count;
1068

1069
cleanup:
1070 1071
    if (pool)
        virStoragePoolObjUnlock(pool);
1072
    return ret;
1073 1074 1075 1076 1077 1078
}

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
                       int maxnames) {
1079 1080
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1081
    int i, n = 0;
1082

1083 1084
    memset(names, 0, maxnames * sizeof(*names));

1085
    storageDriverLock(driver);
1086
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1087 1088
    storageDriverUnlock(driver);

1089
    if (!pool) {
1090
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1091
                              "%s", _("no storage pool with matching uuid"));
1092
        goto cleanup;
1093 1094 1095
    }

    if (!virStoragePoolObjIsActive(pool)) {
1096
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1097
                              "%s", _("storage pool is not active"));
1098
        goto cleanup;
1099 1100
    }

1101 1102
    for (i = 0 ; i < pool->volumes.count && n < maxnames ; i++) {
        if ((names[n++] = strdup(pool->volumes.objs[i]->name)) == NULL) {
1103
            virReportOOMError();
1104 1105 1106 1107
            goto cleanup;
        }
    }

1108
    virStoragePoolObjUnlock(pool);
1109
    return n;
1110 1111

 cleanup:
1112 1113
    if (pool)
        virStoragePoolObjUnlock(pool);
1114
    for (n = 0 ; n < maxnames ; n++)
1115
        VIR_FREE(names[n]);
1116

1117
    memset(names, 0, maxnames * sizeof(*names));
1118 1119 1120 1121 1122 1123 1124
    return -1;
}


static virStorageVolPtr
storageVolumeLookupByName(virStoragePoolPtr obj,
                          const char *name) {
1125 1126
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1127
    virStorageVolDefPtr vol;
1128
    virStorageVolPtr ret = NULL;
1129

1130
    storageDriverLock(driver);
1131
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1132 1133
    storageDriverUnlock(driver);

1134
    if (!pool) {
1135
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1136
                              "%s", _("no storage pool with matching uuid"));
1137
        goto cleanup;
1138 1139 1140
    }

    if (!virStoragePoolObjIsActive(pool)) {
1141
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1142
                              "%s", _("storage pool is not active"));
1143
        goto cleanup;
1144 1145 1146 1147 1148
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1149 1150
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1151
                              name);
1152
        goto cleanup;
1153 1154
    }

1155 1156 1157
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key);

cleanup:
1158 1159
    if (pool)
        virStoragePoolObjUnlock(pool);
1160
    return ret;
1161 1162 1163 1164 1165 1166
}


static virStorageVolPtr
storageVolumeLookupByKey(virConnectPtr conn,
                         const char *key) {
1167
    virStorageDriverStatePtr driver = conn->storagePrivateData;
1168
    unsigned int i;
1169
    virStorageVolPtr ret = NULL;
1170

1171 1172 1173
    storageDriverLock(driver);
    for (i = 0 ; i < driver->pools.count && !ret ; i++) {
        virStoragePoolObjLock(driver->pools.objs[i]);
1174 1175 1176
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1177

1178
            if (vol)
1179
                ret = virGetStorageVol(conn,
1180 1181 1182
                                       driver->pools.objs[i]->def->name,
                                       vol->name,
                                       vol->key);
1183
        }
1184
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1185
    }
1186
    storageDriverUnlock(driver);
1187

1188
    if (!ret)
1189
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
1190 1191 1192
                              "%s", _("no storage vol with matching key"));

    return ret;
1193 1194 1195 1196 1197
}

static virStorageVolPtr
storageVolumeLookupByPath(virConnectPtr conn,
                          const char *path) {
1198
    virStorageDriverStatePtr driver = conn->storagePrivateData;
1199
    unsigned int i;
1200
    virStorageVolPtr ret = NULL;
1201 1202 1203 1204 1205
    char *cleanpath;

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

1207 1208 1209
    storageDriverLock(driver);
    for (i = 0 ; i < driver->pools.count && !ret ; i++) {
        virStoragePoolObjLock(driver->pools.objs[i]);
1210
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
1211
            virStorageVolDefPtr vol;
1212 1213
            const char *stable_path;

1214
            stable_path = virStorageBackendStablePath(driver->pools.objs[i],
1215
                                                      cleanpath);
1216 1217 1218 1219 1220
            /*
             * virStorageBackendStablePath already does
             * virStorageReportError if it fails; we just need to keep
             * propagating the return code
             */
1221 1222
            if (stable_path == NULL) {
                virStoragePoolObjUnlock(driver->pools.objs[i]);
1223
                goto cleanup;
1224
            }
1225 1226 1227 1228

            vol = virStorageVolDefFindByPath(driver->pools.objs[i],
                                             stable_path);
            VIR_FREE(stable_path);
1229

1230
            if (vol)
1231 1232 1233 1234
                ret = virGetStorageVol(conn,
                                       driver->pools.objs[i]->def->name,
                                       vol->name,
                                       vol->key);
1235
        }
1236
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1237 1238
    }

1239
    if (!ret)
1240
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
1241 1242 1243
                              "%s", _("no storage vol with matching path"));

cleanup:
1244
    VIR_FREE(cleanpath);
1245
    storageDriverUnlock(driver);
1246
    return ret;
1247 1248
}

1249 1250
static int storageVolumeDelete(virStorageVolPtr obj, unsigned int flags);

1251 1252 1253 1254
static virStorageVolPtr
storageVolumeCreateXML(virStoragePoolPtr obj,
                       const char *xmldesc,
                       unsigned int flags ATTRIBUTE_UNUSED) {
1255 1256
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1257
    virStorageBackendPtr backend;
1258 1259
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1260

1261
    storageDriverLock(driver);
1262
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1263 1264
    storageDriverUnlock(driver);

1265
    if (!pool) {
1266
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1267
                              "%s", _("no storage pool with matching uuid"));
1268
        goto cleanup;
1269 1270 1271
    }

    if (!virStoragePoolObjIsActive(pool)) {
1272
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1273
                              "%s", _("storage pool is not active"));
1274
        goto cleanup;
1275 1276 1277
    }

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

1280
    voldef = virStorageVolDefParseString(pool->def, xmldesc);
1281
    if (voldef == NULL)
1282
        goto cleanup;
1283

1284
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1285
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
J
Jim Meyering 已提交
1286
                              "%s", _("storage vol already exists"));
1287
        goto cleanup;
1288 1289
    }

1290 1291
    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count+1) < 0) {
1292
        virReportOOMError();
1293
        goto cleanup;
1294 1295
    }

1296
    if (!backend->createVol) {
1297
        virStorageReportError(VIR_ERR_NO_SUPPORT,
1298 1299
                              "%s", _("storage pool does not support volume "
                                      "creation"));
1300
        goto cleanup;
1301 1302
    }

1303
    if (backend->createVol(obj->conn, pool, voldef) < 0) {
1304
        goto cleanup;
1305 1306
    }

1307 1308 1309
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
                              voldef->key);
1310

1311 1312 1313 1314 1315
    if (volobj && backend->buildVol) {
        int buildret;
        virStorageVolDefPtr buildvoldef = NULL;

        if (VIR_ALLOC(buildvoldef) < 0) {
1316
            virReportOOMError();
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
            voldef = NULL;
            goto cleanup;
        }

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

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

1332
        buildret = backend->buildVol(obj->conn, pool, buildvoldef);
1333

1334
        storageDriverLock(driver);
1335
        virStoragePoolObjLock(pool);
1336 1337
        storageDriverUnlock(driver);

1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
        voldef->building = 0;
        pool->asyncjobs--;

        voldef = NULL;
        VIR_FREE(buildvoldef);

        if (buildret < 0) {
            virStoragePoolObjUnlock(pool);
            storageVolumeDelete(volobj, 0);
            pool = NULL;
            goto cleanup;
        }

    }

    ret = volobj;
    volobj = NULL;
    voldef = NULL;
1356

1357
cleanup:
1358 1359 1360
    if (volobj)
        virUnrefStorageVol(volobj);
    virStorageVolDefFree(voldef);
1361 1362
    if (pool)
        virStoragePoolObjUnlock(pool);
1363
    return ret;
1364 1365
}

1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
static virStorageVolPtr
storageVolumeCreateXMLFrom(virStoragePoolPtr obj,
                           const char *xmldesc,
                           virStorageVolPtr vobj,
                           unsigned int flags ATTRIBUTE_UNUSED) {
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool, origpool = NULL;
    virStorageBackendPtr backend;
    virStorageVolDefPtr origvol = NULL, newvol = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1376
    int buildret;
1377 1378 1379

    storageDriverLock(driver);
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1380
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1381
        virStoragePoolObjUnlock(pool);
1382
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1383
        virStoragePoolObjLock(pool);
1384
    }
1385 1386
    storageDriverUnlock(driver);
    if (!pool) {
1387
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
1388 1389 1390 1391
                              "%s", _("no storage pool with matching uuid"));
        goto cleanup;
    }

1392
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1393 1394
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
                              _("no storage pool with matching name '%s'"),
1395
                              vobj->pool);
1396 1397 1398 1399
        goto cleanup;
    }

    if (!virStoragePoolObjIsActive(pool)) {
1400
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1401 1402 1403 1404
                              "%s", _("storage pool is not active"));
        goto cleanup;
    }

1405
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1406
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1407 1408 1409 1410 1411 1412 1413
                              "%s", _("storage pool is not active"));
        goto cleanup;
    }

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

1414
    origvol = virStorageVolDefFindByName(origpool ? origpool : pool, vobj->name);
1415
    if (!origvol) {
1416 1417
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1418
                              vobj->name);
1419 1420 1421
        goto cleanup;
    }

1422
    newvol = virStorageVolDefParseString(pool->def, xmldesc);
1423 1424 1425 1426
    if (newvol == NULL)
        goto cleanup;

    if (virStorageVolDefFindByName(pool, newvol->name)) {
1427
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1428 1429 1430 1431 1432 1433 1434 1435 1436
                              _("storage volume name '%s' already in use."),
                              newvol->name);
        goto cleanup;
    }

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

1437 1438 1439 1440 1441
    /* Make sure allocation is at least as large as the destination cap,
     * to make absolutely sure we copy all possible contents */
    if (newvol->allocation < origvol->capacity)
        newvol->allocation = origvol->capacity;

1442
    if (!backend->buildVolFrom) {
1443
        virStorageReportError(VIR_ERR_NO_SUPPORT,
1444 1445 1446 1447 1448
                              "%s", _("storage pool does not support volume creation from an existing volume"));
        goto cleanup;
    }

    if (origvol->building) {
1449
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
                              _("volume '%s' is still being allocated."),
                              origvol->name);
        goto cleanup;
    }

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

    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count+1) < 0) {
1461
        virReportOOMError();
1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
        goto cleanup;
    }

    /* 'Define' the new volume so we get async progress reporting */
    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,
                              newvol->key);

    /* Drop the pool lock during volume allocation */
    pool->asyncjobs++;
    origvol->building = 1;
    newvol->building = 1;
    virStoragePoolObjUnlock(pool);

1480
    if (origpool) {
1481 1482 1483 1484
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

1485
    buildret = backend->buildVolFrom(obj->conn, pool, newvol, origvol, flags);
1486 1487 1488

    storageDriverLock(driver);
    virStoragePoolObjLock(pool);
1489
    if (origpool)
1490 1491 1492 1493 1494 1495 1496 1497
        virStoragePoolObjLock(origpool);
    storageDriverUnlock(driver);

    origvol->building = 0;
    newvol->building = 0;
    newvol = NULL;
    pool->asyncjobs--;

1498
    if (origpool) {
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519
        origpool->asyncjobs--;
        virStoragePoolObjUnlock(origpool);
        origpool = NULL;
    }

    if (buildret < 0) {
        virStoragePoolObjUnlock(pool);
        storageVolumeDelete(volobj, 0);
        pool = NULL;
        goto cleanup;
    }

    ret = volobj;
    volobj = NULL;

cleanup:
    if (volobj)
        virUnrefStorageVol(volobj);
    virStorageVolDefFree(newvol);
    if (pool)
        virStoragePoolObjUnlock(pool);
1520
    if (origpool)
1521 1522 1523 1524
        virStoragePoolObjUnlock(origpool);
    return ret;
}

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

/* If the volume we're wiping is already a sparse file, we simply
 * truncate and extend it to its original size, filling it with
 * zeroes.  This behavior is guaranteed by POSIX:
 *
 * http://www.opengroup.org/onlinepubs/9699919799/functions/ftruncate.html
 *
 * If fildes refers to a regular file, the ftruncate() function shall
 * cause the size of the file to be truncated to length. If the size
 * of the file previously exceeded length, the extra data shall no
 * longer be available to reads on the file. If the file previously
 * was smaller than this size, ftruncate() shall increase the size of
 * the file. If the file size is increased, the extended area shall
 * appear as if it were zero-filled.
 */
static int
storageVolumeZeroSparseFile(virStorageVolDefPtr vol,
                            off_t size,
                            int fd)
{
    int ret = -1;

    ret = ftruncate(fd, 0);
    if (ret == -1) {
        virReportSystemError(errno,
                             _("Failed to truncate volume with "
                               "path '%s' to 0 bytes"),
                             vol->target.path);
        goto out;
    }

    ret = ftruncate(fd, size);
    if (ret == -1) {
        virReportSystemError(errno,
                             _("Failed to truncate volume with "
1560
                               "path '%s' to %ju bytes"),
1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
                             vol->target.path, (intmax_t)size);
    }

out:
    return ret;
}


static int
storageWipeExtent(virStorageVolDefPtr vol,
                  int fd,
                  off_t extent_start,
                  off_t extent_length,
                  char *writebuf,
                  size_t writebuf_length,
                  size_t *bytes_wiped)
{
    int ret = -1, written = 0;
    off_t remaining = 0;
    size_t write_size = 0;

    VIR_DEBUG("extent logical start: %ju len: %ju",
              (intmax_t)extent_start, (intmax_t)extent_length);

    if ((ret = lseek(fd, extent_start, SEEK_SET)) < 0) {
        virReportSystemError(errno,
                             _("Failed to seek to position %ju in volume "
                               "with path '%s'"),
                             (intmax_t)extent_start, vol->target.path);
        goto out;
    }

    remaining = extent_length;
    while (remaining > 0) {

        write_size = (writebuf_length < remaining) ? writebuf_length : remaining;
        written = safewrite(fd, writebuf, write_size);
        if (written < 0) {
            virReportSystemError(errno,
                                 _("Failed to write %zu bytes to "
                                   "storage volume with path '%s'"),
                                 write_size, vol->target.path);

            goto out;
        }

        *bytes_wiped += written;
        remaining -= written;
    }

    VIR_DEBUG("Wrote %zu bytes to volume with path '%s'",
              *bytes_wiped, vol->target.path);

    ret = 0;

out:
    return ret;
}


static int
storageVolumeWipeInternal(virStorageVolDefPtr def)
{
    int ret = -1, fd = -1;
    struct stat st;
    char *writebuf = NULL;
    size_t bytes_wiped = 0;

    VIR_DEBUG("Wiping volume with path '%s'", def->target.path);

    fd = open(def->target.path, O_RDWR);
    if (fd == -1) {
        virReportSystemError(errno,
                             _("Failed to open storage volume with path '%s'"),
                             def->target.path);
        goto out;
    }

    if (fstat(fd, &st) == -1) {
        virReportSystemError(errno,
                             _("Failed to stat storage volume with path '%s'"),
                             def->target.path);
        goto out;
    }

    if (S_ISREG(st.st_mode) && st.st_blocks < (st.st_size / DEV_BSIZE)) {
        ret = storageVolumeZeroSparseFile(def, st.st_size, fd);
    } else {

        if (VIR_ALLOC_N(writebuf, st.st_blksize) != 0) {
            virReportOOMError();
            goto out;
        }

        ret = storageWipeExtent(def,
                                fd,
                                0,
                                def->allocation,
                                writebuf,
                                st.st_blksize,
                                &bytes_wiped);
    }

out:
    VIR_FREE(writebuf);

    if (fd != -1) {
        close(fd);
    }

    return ret;
}


static int
storageVolumeWipe(virStorageVolPtr obj,
                  unsigned int flags)
{
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool = NULL;
    virStorageVolDefPtr vol = NULL;
    int ret = -1;

1684
    virCheckFlags(0, -1);
1685 1686 1687 1688 1689 1690

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

    if (!pool) {
1691
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
                              "%s", _("no storage pool with matching uuid"));
        goto out;
    }

    if (!virStoragePoolObjIsActive(pool)) {
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
                              "%s", _("storage pool is not active"));
        goto out;
    }

    vol = virStorageVolDefFindByName(pool, obj->name);

    if (vol == NULL) {
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                             _("no storage vol with matching name '%s'"),
                              obj->name);
        goto out;
    }

    if (vol->building) {
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
                              _("volume '%s' is still being allocated."),
                              vol->name);
        goto out;
    }

    if (storageVolumeWipeInternal(vol) == -1) {
        goto out;
    }

    ret = 0;

out:
    if (pool) {
        virStoragePoolObjUnlock(pool);
    }

    return ret;

}

1733 1734 1735
static int
storageVolumeDelete(virStorageVolPtr obj,
                    unsigned int flags) {
1736 1737
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1738
    virStorageBackendPtr backend;
1739
    virStorageVolDefPtr vol = NULL;
1740
    unsigned int i;
1741
    int ret = -1;
1742

1743
    storageDriverLock(driver);
1744
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1745 1746
    storageDriverUnlock(driver);

1747
    if (!pool) {
1748
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1749
                              "%s", _("no storage pool with matching uuid"));
1750
        goto cleanup;
1751 1752 1753
    }

    if (!virStoragePoolObjIsActive(pool)) {
1754
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1755
                              "%s", _("storage pool is not active"));
1756
        goto cleanup;
1757 1758 1759
    }

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

    vol = virStorageVolDefFindByName(pool, obj->name);

    if (!vol) {
1765
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
1766 1767
                             _("no storage vol with matching name '%s'"),
                              obj->name);
1768
        goto cleanup;
1769 1770
    }

1771
    if (vol->building) {
1772
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1773 1774 1775 1776 1777
                              _("volume '%s' is still being allocated."),
                              vol->name);
        goto cleanup;
    }

1778
    if (!backend->deleteVol) {
1779
        virStorageReportError(VIR_ERR_NO_SUPPORT,
J
Jim Meyering 已提交
1780
                              "%s", _("storage pool does not support vol deletion"));
1781

1782
        goto cleanup;
1783 1784
    }

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

1788 1789 1790
    for (i = 0 ; i < pool->volumes.count ; i++) {
        if (pool->volumes.objs[i] == vol) {
            virStorageVolDefFree(vol);
1791
            vol = NULL;
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801

            if (i < (pool->volumes.count - 1))
                memmove(pool->volumes.objs + i, pool->volumes.objs + i + 1,
                        sizeof(*(pool->volumes.objs)) * (pool->volumes.count - (i + 1)));

            if (VIR_REALLOC_N(pool->volumes.objs, pool->volumes.count - 1) < 0) {
                ; /* Failure to reduce memory allocation isn't fatal */
            }
            pool->volumes.count--;

1802 1803 1804
            break;
        }
    }
1805
    ret = 0;
1806

1807
cleanup:
1808 1809
    if (pool)
        virStoragePoolObjUnlock(pool);
1810
    return ret;
1811 1812 1813 1814 1815
}

static int
storageVolumeGetInfo(virStorageVolPtr obj,
                     virStorageVolInfoPtr info) {
1816 1817
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1818 1819
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
1820
    int ret = -1;
1821

1822
    storageDriverLock(driver);
1823
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1824 1825
    storageDriverUnlock(driver);

1826
    if (!pool) {
1827
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1828
                              "%s", _("no storage pool with matching uuid"));
1829
        goto cleanup;
1830 1831 1832
    }

    if (!virStoragePoolObjIsActive(pool)) {
1833
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1834
                              "%s", _("storage pool is not active"));
1835
        goto cleanup;
1836 1837 1838 1839 1840
    }

    vol = virStorageVolDefFindByName(pool, obj->name);

    if (!vol) {
1841 1842
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1843
                              obj->name);
1844
        goto cleanup;
1845 1846 1847
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
1848
        goto cleanup;
1849 1850 1851

    if (backend->refreshVol &&
        backend->refreshVol(obj->conn, pool, vol) < 0)
1852
        goto cleanup;
1853 1854

    memset(info, 0, sizeof(*info));
1855
    info->type = vol->type;
1856 1857
    info->capacity = vol->capacity;
    info->allocation = vol->allocation;
1858
    ret = 0;
1859

1860
cleanup:
1861 1862
    if (pool)
        virStoragePoolObjUnlock(pool);
1863
    return ret;
1864 1865 1866 1867 1868
}

static char *
storageVolumeGetXMLDesc(virStorageVolPtr obj,
                        unsigned int flags ATTRIBUTE_UNUSED) {
1869 1870
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1871 1872
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
1873
    char *ret = NULL;
1874

1875
    storageDriverLock(driver);
1876
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1877 1878
    storageDriverUnlock(driver);

1879
    if (!pool) {
1880
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1881
                              "%s", _("no storage pool with matching uuid"));
1882
        goto cleanup;
1883 1884 1885
    }

    if (!virStoragePoolObjIsActive(pool)) {
1886
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1887
                              "%s", _("storage pool is not active"));
1888
        goto cleanup;
1889 1890 1891 1892 1893
    }

    vol = virStorageVolDefFindByName(pool, obj->name);

    if (!vol) {
1894
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
1895 1896
                             _("no storage vol with matching name '%s'"),
                              obj->name);
1897
        goto cleanup;
1898 1899 1900
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
1901
        goto cleanup;
1902 1903 1904 1905

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

1907
    ret = virStorageVolDefFormat(pool->def, vol);
1908 1909

cleanup:
1910 1911 1912
    if (pool)
        virStoragePoolObjUnlock(pool);

1913
    return ret;
1914 1915 1916 1917
}

static char *
storageVolumeGetPath(virStorageVolPtr obj) {
1918
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
1919
    virStoragePoolObjPtr pool;
1920
    virStorageVolDefPtr vol;
1921
    char *ret = NULL;
1922

1923 1924 1925
    storageDriverLock(driver);
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
    storageDriverUnlock(driver);
1926
    if (!pool) {
1927
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
J
Jim Meyering 已提交
1928
                              "%s", _("no storage pool with matching uuid"));
1929
        goto cleanup;
1930 1931 1932
    }

    if (!virStoragePoolObjIsActive(pool)) {
1933
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1934
                              "%s", _("storage pool is not active"));
1935
        goto cleanup;
1936 1937 1938 1939 1940
    }

    vol = virStorageVolDefFindByName(pool, obj->name);

    if (!vol) {
1941 1942
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1943
                              obj->name);
1944
        goto cleanup;
1945 1946 1947
    }

    ret = strdup(vol->target.path);
1948
    if (ret == NULL)
1949
        virReportOOMError();
1950 1951

cleanup:
1952 1953
    if (pool)
        virStoragePoolObjUnlock(pool);
1954 1955 1956 1957
    return ret;
}

static virStorageDriver storageDriver = {
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
    .name = "storage",
    .open = storageOpen,
    .close = storageClose,
    .numOfPools = storageNumPools,
    .listPools = storageListPools,
    .numOfDefinedPools = storageNumDefinedPools,
    .listDefinedPools = storageListDefinedPools,
    .findPoolSources = storageFindPoolSources,
    .poolLookupByName = storagePoolLookupByName,
    .poolLookupByUUID = storagePoolLookupByUUID,
    .poolLookupByVolume = storagePoolLookupByVolume,
    .poolCreateXML = storagePoolCreate,
    .poolDefineXML = storagePoolDefine,
    .poolBuild = storagePoolBuild,
    .poolUndefine = storagePoolUndefine,
    .poolCreate = storagePoolStart,
    .poolDestroy = storagePoolDestroy,
    .poolDelete = storagePoolDelete,
    .poolRefresh = storagePoolRefresh,
    .poolGetInfo = storagePoolGetInfo,
    .poolGetXMLDesc = storagePoolDumpXML,
    .poolGetAutostart = storagePoolGetAutostart,
    .poolSetAutostart = storagePoolSetAutostart,
    .poolNumOfVolumes = storagePoolNumVolumes,
    .poolListVolumes = storagePoolListVolumes,

    .volLookupByName = storageVolumeLookupByName,
    .volLookupByKey = storageVolumeLookupByKey,
    .volLookupByPath = storageVolumeLookupByPath,
    .volCreateXML = storageVolumeCreateXML,
1988
    .volCreateXMLFrom = storageVolumeCreateXMLFrom,
1989
    .volDelete = storageVolumeDelete,
1990
    .volWipe = storageVolumeWipe,
1991 1992 1993
    .volGetInfo = storageVolumeGetInfo,
    .volGetXMLDesc = storageVolumeGetXMLDesc,
    .volGetPath = storageVolumeGetPath,
1994 1995 1996

    .poolIsActive = storagePoolIsActive,
    .poolIsPersistent = storagePoolIsPersistent,
1997 1998 1999 2000
};


static virStateDriver stateDriver = {
2001
    .name = "Storage",
2002 2003 2004 2005
    .initialize = storageDriverStartup,
    .cleanup = storageDriverShutdown,
    .reload = storageDriverReload,
    .active = storageDriverActive,
2006 2007 2008 2009 2010 2011 2012
};

int storageRegister(void) {
    virRegisterStorageDriver(&storageDriver);
    virRegisterStateDriver(&stateDriver);
    return 0;
}