storage_driver.c 56.7 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 525 526 527 528
    pool = virStoragePoolObjFindByUUID(&driver->pools, def->uuid);
    if (!pool)
        pool = virStoragePoolObjFindByName(&driver->pools, def->name);

    if (pool) {
529
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
530
                              "%s", _("storage pool already exists"));
531 532
        virStoragePoolObjUnlock(pool);
        pool = NULL;
533
        goto cleanup;
534 535
    }

536 537
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
538

539
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
540 541
        goto cleanup;
    def = NULL;
542

543
    if (backend->startPool &&
544 545 546
        backend->startPool(conn, pool) < 0) {
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
547
        goto cleanup;
548
    }
549

550 551 552
    if (backend->refreshPool(conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(conn, pool);
553 554
        virStoragePoolObjRemove(&driver->pools, pool);
        pool = NULL;
555
        goto cleanup;
556 557 558 559 560
    }
    pool->active = 1;

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

561 562
cleanup:
    virStoragePoolDefFree(def);
563
    if (pool)
564
        virStoragePoolObjUnlock(pool);
565
    storageDriverUnlock(driver);
566 567 568 569 570 571 572
    return ret;
}

static virStoragePoolPtr
storagePoolDefine(virConnectPtr conn,
                  const char *xml,
                  unsigned int flags ATTRIBUTE_UNUSED) {
573
    virStorageDriverStatePtr driver = conn->storagePrivateData;
574
    virStoragePoolDefPtr def;
575
    virStoragePoolObjPtr pool = NULL;
576
    virStoragePoolPtr ret = NULL;
577

578
    storageDriverLock(driver);
579
    if (!(def = virStoragePoolDefParseString(xml)))
580
        goto cleanup;
581

582
    if (virStorageBackendForType(def->type) == NULL)
583
        goto cleanup;
584

585
    if (!(pool = virStoragePoolObjAssignDef(&driver->pools, def)))
586
        goto cleanup;
587

588
    if (virStoragePoolObjSaveDef(driver, pool, def) < 0) {
589
        virStoragePoolObjRemove(&driver->pools, pool);
590
        def = NULL;
591
        goto cleanup;
592
    }
593
    def = NULL;
594 595

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

cleanup:
    virStoragePoolDefFree(def);
599 600 601
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
602 603 604 605 606
    return ret;
}

static int
storagePoolUndefine(virStoragePoolPtr obj) {
607 608 609
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
610

611
    storageDriverLock(driver);
612
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
613
    if (!pool) {
614
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
615
                              "%s", _("no storage pool with matching uuid"));
616
        goto cleanup;
617 618 619
    }

    if (virStoragePoolObjIsActive(pool)) {
620
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
621
                              "%s", _("pool is still active"));
622
        goto cleanup;
623 624
    }

625
    if (pool->asyncjobs > 0) {
626
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
627 628 629 630 631
                              _("pool '%s' has asynchronous jobs running."),
                              pool->def->name);
        goto cleanup;
    }

632
    if (virStoragePoolObjDeleteDef(pool) < 0)
633
        goto cleanup;
634

635 636
    if (unlink(pool->autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
        char ebuf[1024];
637
        VIR_ERROR(_("Failed to delete autostart link '%s': %s"),
638 639
                   pool->autostartLink, virStrerror(errno, ebuf, sizeof ebuf));
    }
640

641 642
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
643

644
    virStoragePoolObjRemove(&driver->pools, pool);
645
    pool = NULL;
646
    ret = 0;
647

648
cleanup:
649 650 651
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
652
    return ret;
653 654 655 656 657
}

static int
storagePoolStart(virStoragePoolPtr obj,
                 unsigned int flags ATTRIBUTE_UNUSED) {
658 659
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
660
    virStorageBackendPtr backend;
661
    int ret = -1;
662

663
    storageDriverLock(driver);
664
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
665 666
    storageDriverUnlock(driver);

667
    if (!pool) {
668
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
669
                              "%s", _("no storage pool with matching uuid"));
670
        goto cleanup;
671 672
    }

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

    if (virStoragePoolObjIsActive(pool)) {
677
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
678
                              "%s", _("pool already active"));
679
        goto cleanup;
680 681 682
    }
    if (backend->startPool &&
        backend->startPool(obj->conn, pool) < 0)
683 684
        goto cleanup;

685 686 687
    if (backend->refreshPool(obj->conn, pool) < 0) {
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);
688
        goto cleanup;
689 690 691
    }

    pool->active = 1;
692
    ret = 0;
693

694
cleanup:
695 696
    if (pool)
        virStoragePoolObjUnlock(pool);
697
    return ret;
698 699 700 701 702
}

static int
storagePoolBuild(virStoragePoolPtr obj,
                 unsigned int flags) {
703 704
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
705
    virStorageBackendPtr backend;
706
    int ret = -1;
707

708
    storageDriverLock(driver);
709
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
710 711
    storageDriverUnlock(driver);

712
    if (!pool) {
713
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
714
                              "%s", _("no storage pool with matching uuid"));
715
        goto cleanup;
716 717
    }

718 719
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
720 721

    if (virStoragePoolObjIsActive(pool)) {
722
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
723
                              "%s", _("storage pool is already active"));
724
        goto cleanup;
725 726 727 728
    }

    if (backend->buildPool &&
        backend->buildPool(obj->conn, pool, flags) < 0)
729 730
        goto cleanup;
    ret = 0;
731

732
cleanup:
733 734
    if (pool)
        virStoragePoolObjUnlock(pool);
735
    return ret;
736 737 738 739 740
}


static int
storagePoolDestroy(virStoragePoolPtr obj) {
741 742
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
743
    virStorageBackendPtr backend;
744
    int ret = -1;
745

746
    storageDriverLock(driver);
747
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
748

749
    if (!pool) {
750
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
751
                              "%s", _("no storage pool with matching uuid"));
752
        goto cleanup;
753 754
    }

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

    if (!virStoragePoolObjIsActive(pool)) {
759
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
760
                              "%s", _("storage pool is not active"));
761
        goto cleanup;
762 763
    }

764
    if (pool->asyncjobs > 0) {
765
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
766 767 768 769 770
                              _("pool '%s' has asynchronous jobs running."),
                              pool->def->name);
        goto cleanup;
    }

771 772
    if (backend->stopPool &&
        backend->stopPool(obj->conn, pool) < 0)
773
        goto cleanup;
774 775 776 777 778

    virStoragePoolObjClearVols(pool);

    pool->active = 0;

779
    if (pool->configFile == NULL) {
780
        virStoragePoolObjRemove(&driver->pools, pool);
781 782
        pool = NULL;
    }
783
    ret = 0;
784

785
cleanup:
786 787 788
    if (pool)
        virStoragePoolObjUnlock(pool);
    storageDriverUnlock(driver);
789
    return ret;
790 791 792 793 794 795
}


static int
storagePoolDelete(virStoragePoolPtr obj,
                  unsigned int flags) {
796 797
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
798
    virStorageBackendPtr backend;
799
    int ret = -1;
800

801
    storageDriverLock(driver);
802
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
803 804
    storageDriverUnlock(driver);

805
    if (!pool) {
806
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
807
                              "%s", _("no storage pool with matching uuid"));
808
        goto cleanup;
809 810
    }

811 812
    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
        goto cleanup;
813 814

    if (virStoragePoolObjIsActive(pool)) {
815
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
816
                              "%s", _("storage pool is still active"));
817
        goto cleanup;
818 819
    }

820
    if (pool->asyncjobs > 0) {
821
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
822 823 824 825 826
                              _("pool '%s' has asynchronous jobs running."),
                              pool->def->name);
        goto cleanup;
    }

827
    if (!backend->deletePool) {
828
        virStorageReportError(VIR_ERR_NO_SUPPORT,
829
                              "%s", _("pool does not support pool deletion"));
830
        goto cleanup;
831 832
    }
    if (backend->deletePool(obj->conn, pool, flags) < 0)
833 834
        goto cleanup;
    ret = 0;
835

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


static int
storagePoolRefresh(virStoragePoolPtr obj,
                   unsigned int flags ATTRIBUTE_UNUSED) {
846 847
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
848
    virStorageBackendPtr backend;
849
    int ret = -1;
850

851
    storageDriverLock(driver);
852
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
853

854
    if (!pool) {
855
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
856
                              "%s", _("no storage pool with matching uuid"));
857
        goto cleanup;
858 859
    }

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

    if (!virStoragePoolObjIsActive(pool)) {
864
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
865
                              "%s", _("storage pool is not active"));
866
        goto cleanup;
867 868
    }

869
    if (pool->asyncjobs > 0) {
870
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
871 872 873 874 875
                              _("pool '%s' has asynchronous jobs running."),
                              pool->def->name);
        goto cleanup;
    }

876
    virStoragePoolObjClearVols(pool);
877
    if (backend->refreshPool(obj->conn, pool) < 0) {
878 879 880 881 882
        if (backend->stopPool)
            backend->stopPool(obj->conn, pool);

        pool->active = 0;

883
        if (pool->configFile == NULL) {
884
            virStoragePoolObjRemove(&driver->pools, pool);
885 886
            pool = NULL;
        }
887
        goto cleanup;
888
    }
889
    ret = 0;
890

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


static int
storagePoolGetInfo(virStoragePoolPtr obj,
                   virStoragePoolInfoPtr info) {
902 903 904
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
905

906
    storageDriverLock(driver);
907
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
908 909
    storageDriverUnlock(driver);

910
    if (!pool) {
911
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
912
                              "%s", _("no storage pool with matching uuid"));
913
        goto cleanup;
914 915
    }

916
    if (virStorageBackendForType(pool->def->type) == NULL)
917
        goto cleanup;
918 919 920 921 922 923 924 925 926

    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;
927
    ret = 0;
928

929
cleanup:
930 931
    if (pool)
        virStoragePoolObjUnlock(pool);
932
    return ret;
933 934 935 936 937
}

static char *
storagePoolDumpXML(virStoragePoolPtr obj,
                   unsigned int flags ATTRIBUTE_UNUSED) {
938 939 940
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    char *ret = NULL;
941

942
    storageDriverLock(driver);
943
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
944 945
    storageDriverUnlock(driver);

946
    if (!pool) {
947
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
948
                              "%s", _("no storage pool with matching uuid"));
949
        goto cleanup;
950 951
    }

952
    ret = virStoragePoolDefFormat(pool->def);
953 954

cleanup:
955 956
    if (pool)
        virStoragePoolObjUnlock(pool);
957
    return ret;
958 959 960 961 962
}

static int
storagePoolGetAutostart(virStoragePoolPtr obj,
                        int *autostart) {
963 964 965
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
966

967
    storageDriverLock(driver);
968
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
969 970
    storageDriverUnlock(driver);

971
    if (!pool) {
972
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
973
                              "%s", _("no pool with matching uuid"));
974
        goto cleanup;
975 976 977 978 979 980 981
    }

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

984
cleanup:
985 986
    if (pool)
        virStoragePoolObjUnlock(pool);
987
    return ret;
988 989 990 991 992
}

static int
storagePoolSetAutostart(virStoragePoolPtr obj,
                        int autostart) {
993 994 995
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
996

997
    storageDriverLock(driver);
998
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
999

1000
    if (!pool) {
1001
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1002
                              "%s", _("no pool with matching uuid"));
1003
        goto cleanup;
1004 1005 1006
    }

    if (!pool->configFile) {
1007
        virStorageReportError(VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
1008
                              "%s", _("pool has no config file"));
1009
        goto cleanup;
1010 1011 1012 1013
    }

    autostart = (autostart != 0);

1014 1015 1016
    if (pool->autostart != autostart) {
        if (autostart) {
            int err;
1017

1018
            if ((err = virFileMakePath(driver->autostartDir))) {
1019
                virReportSystemError(err,
1020 1021
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
1022 1023
                goto cleanup;
            }
1024

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

1044
cleanup:
1045 1046
    if (pool)
        virStoragePoolObjUnlock(pool);
1047
    storageDriverUnlock(driver);
1048
    return ret;
1049 1050 1051 1052 1053
}


static int
storagePoolNumVolumes(virStoragePoolPtr obj) {
1054 1055 1056
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
    int ret = -1;
1057

1058
    storageDriverLock(driver);
1059
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1060 1061
    storageDriverUnlock(driver);

1062
    if (!pool) {
1063
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1064
                              "%s", _("no storage pool with matching uuid"));
1065
        goto cleanup;
1066 1067 1068
    }

    if (!virStoragePoolObjIsActive(pool)) {
1069
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1070
                              "%s", _("storage pool is not active"));
1071
        goto cleanup;
1072
    }
1073
    ret = pool->volumes.count;
1074

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

static int
storagePoolListVolumes(virStoragePoolPtr obj,
                       char **const names,
                       int maxnames) {
1085 1086
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1087
    int i, n = 0;
1088

1089 1090
    memset(names, 0, maxnames * sizeof(*names));

1091
    storageDriverLock(driver);
1092
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1093 1094
    storageDriverUnlock(driver);

1095
    if (!pool) {
1096
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1097
                              "%s", _("no storage pool with matching uuid"));
1098
        goto cleanup;
1099 1100 1101
    }

    if (!virStoragePoolObjIsActive(pool)) {
1102
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1103
                              "%s", _("storage pool is not active"));
1104
        goto cleanup;
1105 1106
    }

1107 1108
    for (i = 0 ; i < pool->volumes.count && n < maxnames ; i++) {
        if ((names[n++] = strdup(pool->volumes.objs[i]->name)) == NULL) {
1109
            virReportOOMError();
1110 1111 1112 1113
            goto cleanup;
        }
    }

1114
    virStoragePoolObjUnlock(pool);
1115
    return n;
1116 1117

 cleanup:
1118 1119
    if (pool)
        virStoragePoolObjUnlock(pool);
1120
    for (n = 0 ; n < maxnames ; n++)
1121
        VIR_FREE(names[n]);
1122

1123
    memset(names, 0, maxnames * sizeof(*names));
1124 1125 1126 1127 1128 1129 1130
    return -1;
}


static virStorageVolPtr
storageVolumeLookupByName(virStoragePoolPtr obj,
                          const char *name) {
1131 1132
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1133
    virStorageVolDefPtr vol;
1134
    virStorageVolPtr ret = NULL;
1135

1136
    storageDriverLock(driver);
1137
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1138 1139
    storageDriverUnlock(driver);

1140
    if (!pool) {
1141
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1142
                              "%s", _("no storage pool with matching uuid"));
1143
        goto cleanup;
1144 1145 1146
    }

    if (!virStoragePoolObjIsActive(pool)) {
1147
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1148
                              "%s", _("storage pool is not active"));
1149
        goto cleanup;
1150 1151 1152 1153 1154
    }

    vol = virStorageVolDefFindByName(pool, name);

    if (!vol) {
1155 1156
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1157
                              name);
1158
        goto cleanup;
1159 1160
    }

1161 1162 1163
    ret = virGetStorageVol(obj->conn, pool->def->name, vol->name, vol->key);

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


static virStorageVolPtr
storageVolumeLookupByKey(virConnectPtr conn,
                         const char *key) {
1173
    virStorageDriverStatePtr driver = conn->storagePrivateData;
1174
    unsigned int i;
1175
    virStorageVolPtr ret = NULL;
1176

1177 1178 1179
    storageDriverLock(driver);
    for (i = 0 ; i < driver->pools.count && !ret ; i++) {
        virStoragePoolObjLock(driver->pools.objs[i]);
1180 1181 1182
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
            virStorageVolDefPtr vol =
                virStorageVolDefFindByKey(driver->pools.objs[i], key);
1183

1184
            if (vol)
1185
                ret = virGetStorageVol(conn,
1186 1187 1188
                                       driver->pools.objs[i]->def->name,
                                       vol->name,
                                       vol->key);
1189
        }
1190
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1191
    }
1192
    storageDriverUnlock(driver);
1193

1194
    if (!ret)
1195
        virStorageReportError(VIR_ERR_INVALID_STORAGE_VOL,
1196 1197 1198
                              "%s", _("no storage vol with matching key"));

    return ret;
1199 1200 1201 1202 1203
}

static virStorageVolPtr
storageVolumeLookupByPath(virConnectPtr conn,
                          const char *path) {
1204
    virStorageDriverStatePtr driver = conn->storagePrivateData;
1205
    unsigned int i;
1206
    virStorageVolPtr ret = NULL;
1207 1208 1209 1210 1211
    char *cleanpath;

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

1213 1214 1215
    storageDriverLock(driver);
    for (i = 0 ; i < driver->pools.count && !ret ; i++) {
        virStoragePoolObjLock(driver->pools.objs[i]);
1216
        if (virStoragePoolObjIsActive(driver->pools.objs[i])) {
1217
            virStorageVolDefPtr vol;
1218 1219
            const char *stable_path;

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

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

1236
            if (vol)
1237 1238 1239 1240
                ret = virGetStorageVol(conn,
                                       driver->pools.objs[i]->def->name,
                                       vol->name,
                                       vol->key);
1241
        }
1242
        virStoragePoolObjUnlock(driver->pools.objs[i]);
1243 1244
    }

1245
    if (!ret)
1246
        virStorageReportError(VIR_ERR_INVALID_STORAGE_VOL,
1247 1248 1249
                              "%s", _("no storage vol with matching path"));

cleanup:
1250
    VIR_FREE(cleanpath);
1251
    storageDriverUnlock(driver);
1252
    return ret;
1253 1254
}

1255 1256
static int storageVolumeDelete(virStorageVolPtr obj, unsigned int flags);

1257 1258 1259 1260
static virStorageVolPtr
storageVolumeCreateXML(virStoragePoolPtr obj,
                       const char *xmldesc,
                       unsigned int flags ATTRIBUTE_UNUSED) {
1261 1262
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1263
    virStorageBackendPtr backend;
1264 1265
    virStorageVolDefPtr voldef = NULL;
    virStorageVolPtr ret = NULL, volobj = NULL;
1266

1267
    storageDriverLock(driver);
1268
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1269 1270
    storageDriverUnlock(driver);

1271
    if (!pool) {
1272
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1273
                              "%s", _("no storage pool with matching uuid"));
1274
        goto cleanup;
1275 1276 1277
    }

    if (!virStoragePoolObjIsActive(pool)) {
1278
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1279
                              "%s", _("storage pool is not active"));
1280
        goto cleanup;
1281 1282 1283
    }

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

1286
    voldef = virStorageVolDefParseString(pool->def, xmldesc);
1287
    if (voldef == NULL)
1288
        goto cleanup;
1289

1290
    if (virStorageVolDefFindByName(pool, voldef->name)) {
1291
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1292
                              "%s", _("storage vol already exists"));
1293
        goto cleanup;
1294 1295
    }

1296 1297
    if (VIR_REALLOC_N(pool->volumes.objs,
                      pool->volumes.count+1) < 0) {
1298
        virReportOOMError();
1299
        goto cleanup;
1300 1301
    }

1302
    if (!backend->createVol) {
1303
        virStorageReportError(VIR_ERR_NO_SUPPORT,
1304 1305
                              "%s", _("storage pool does not support volume "
                                      "creation"));
1306
        goto cleanup;
1307 1308
    }

1309
    if (backend->createVol(obj->conn, pool, voldef) < 0) {
1310
        goto cleanup;
1311 1312
    }

1313 1314 1315
    pool->volumes.objs[pool->volumes.count++] = voldef;
    volobj = virGetStorageVol(obj->conn, pool->def->name, voldef->name,
                              voldef->key);
1316

1317 1318 1319 1320 1321
    if (volobj && backend->buildVol) {
        int buildret;
        virStorageVolDefPtr buildvoldef = NULL;

        if (VIR_ALLOC(buildvoldef) < 0) {
1322
            virReportOOMError();
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
            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);

1338
        buildret = backend->buildVol(obj->conn, pool, buildvoldef);
1339

1340
        storageDriverLock(driver);
1341
        virStoragePoolObjLock(pool);
1342 1343
        storageDriverUnlock(driver);

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
        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;
1362

1363
cleanup:
1364 1365 1366
    if (volobj)
        virUnrefStorageVol(volobj);
    virStorageVolDefFree(voldef);
1367 1368
    if (pool)
        virStoragePoolObjUnlock(pool);
1369
    return ret;
1370 1371
}

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
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;
1382
    int buildret;
1383 1384 1385

    storageDriverLock(driver);
    pool = virStoragePoolObjFindByUUID(&driver->pools, obj->uuid);
1386
    if (pool && STRNEQ(obj->name, vobj->pool)) {
1387
        virStoragePoolObjUnlock(pool);
1388
        origpool = virStoragePoolObjFindByName(&driver->pools, vobj->pool);
1389
        virStoragePoolObjLock(pool);
1390
    }
1391 1392
    storageDriverUnlock(driver);
    if (!pool) {
1393
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
1394 1395 1396 1397
                              "%s", _("no storage pool with matching uuid"));
        goto cleanup;
    }

1398
    if (STRNEQ(obj->name, vobj->pool) && !origpool) {
1399 1400
        virStorageReportError(VIR_ERR_NO_STORAGE_POOL,
                              _("no storage pool with matching name '%s'"),
1401
                              vobj->pool);
1402 1403 1404 1405
        goto cleanup;
    }

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

1411
    if (origpool && !virStoragePoolObjIsActive(origpool)) {
1412
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1413 1414 1415 1416 1417 1418 1419
                              "%s", _("storage pool is not active"));
        goto cleanup;
    }

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

1420
    origvol = virStorageVolDefFindByName(origpool ? origpool : pool, vobj->name);
1421
    if (!origvol) {
1422 1423
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1424
                              vobj->name);
1425 1426 1427
        goto cleanup;
    }

1428
    newvol = virStorageVolDefParseString(pool->def, xmldesc);
1429 1430 1431 1432
    if (newvol == NULL)
        goto cleanup;

    if (virStorageVolDefFindByName(pool, newvol->name)) {
1433
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
1434 1435 1436 1437 1438 1439 1440 1441 1442
                              _("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;

1443 1444 1445 1446 1447
    /* 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;

1448
    if (!backend->buildVolFrom) {
1449
        virStorageReportError(VIR_ERR_NO_SUPPORT,
1450 1451 1452 1453 1454
                              "%s", _("storage pool does not support volume creation from an existing volume"));
        goto cleanup;
    }

    if (origvol->building) {
1455
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                              _("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) {
1467
        virReportOOMError();
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
        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);

1486
    if (origpool) {
1487 1488 1489 1490
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

1491
    buildret = backend->buildVolFrom(obj->conn, pool, newvol, origvol, flags);
1492 1493 1494

    storageDriverLock(driver);
    virStoragePoolObjLock(pool);
1495
    if (origpool)
1496 1497 1498 1499 1500 1501 1502 1503
        virStoragePoolObjLock(origpool);
    storageDriverUnlock(driver);

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

1504
    if (origpool) {
1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
        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);
1526
    if (origpool)
1527 1528 1529 1530
        virStoragePoolObjUnlock(origpool);
    return ret;
}

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 1560 1561 1562 1563 1564 1565

/* 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 "
1566
                               "path '%s' to %ju bytes"),
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 1684 1685 1686 1687 1688 1689
                             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;

1690
    virCheckFlags(0, -1);
1691 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 1733 1734 1735 1736 1737 1738

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

    if (!pool) {
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
                              "%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;

}

1739 1740 1741
static int
storageVolumeDelete(virStorageVolPtr obj,
                    unsigned int flags) {
1742 1743
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1744
    virStorageBackendPtr backend;
1745
    virStorageVolDefPtr vol = NULL;
1746
    unsigned int i;
1747
    int ret = -1;
1748

1749
    storageDriverLock(driver);
1750
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1751 1752
    storageDriverUnlock(driver);

1753
    if (!pool) {
1754
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1755
                              "%s", _("no storage pool with matching uuid"));
1756
        goto cleanup;
1757 1758 1759
    }

    if (!virStoragePoolObjIsActive(pool)) {
1760
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1761
                              "%s", _("storage pool is not active"));
1762
        goto cleanup;
1763 1764 1765
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
1766
        goto cleanup;
1767 1768 1769 1770

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

    if (!vol) {
1771
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
1772 1773
                             _("no storage vol with matching name '%s'"),
                              obj->name);
1774
        goto cleanup;
1775 1776
    }

1777
    if (vol->building) {
1778
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1779 1780 1781 1782 1783
                              _("volume '%s' is still being allocated."),
                              vol->name);
        goto cleanup;
    }

1784
    if (!backend->deleteVol) {
1785
        virStorageReportError(VIR_ERR_NO_SUPPORT,
J
Jim Meyering 已提交
1786
                              "%s", _("storage pool does not support vol deletion"));
1787

1788
        goto cleanup;
1789 1790
    }

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

1794 1795 1796
    for (i = 0 ; i < pool->volumes.count ; i++) {
        if (pool->volumes.objs[i] == vol) {
            virStorageVolDefFree(vol);
1797
            vol = NULL;
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

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

1808 1809 1810
            break;
        }
    }
1811
    ret = 0;
1812

1813
cleanup:
1814 1815
    if (pool)
        virStoragePoolObjUnlock(pool);
1816
    return ret;
1817 1818 1819 1820 1821
}

static int
storageVolumeGetInfo(virStorageVolPtr obj,
                     virStorageVolInfoPtr info) {
1822 1823
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1824 1825
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
1826
    int ret = -1;
1827

1828
    storageDriverLock(driver);
1829
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1830 1831
    storageDriverUnlock(driver);

1832
    if (!pool) {
1833
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1834
                              "%s", _("no storage pool with matching uuid"));
1835
        goto cleanup;
1836 1837 1838
    }

    if (!virStoragePoolObjIsActive(pool)) {
1839
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1840
                              "%s", _("storage pool is not active"));
1841
        goto cleanup;
1842 1843 1844 1845 1846
    }

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

    if (!vol) {
1847 1848
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1849
                              obj->name);
1850
        goto cleanup;
1851 1852 1853
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
1854
        goto cleanup;
1855 1856 1857

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

    memset(info, 0, sizeof(*info));
1861
    info->type = vol->type;
1862 1863
    info->capacity = vol->capacity;
    info->allocation = vol->allocation;
1864
    ret = 0;
1865

1866
cleanup:
1867 1868
    if (pool)
        virStoragePoolObjUnlock(pool);
1869
    return ret;
1870 1871 1872 1873 1874
}

static char *
storageVolumeGetXMLDesc(virStorageVolPtr obj,
                        unsigned int flags ATTRIBUTE_UNUSED) {
1875 1876
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
    virStoragePoolObjPtr pool;
1877 1878
    virStorageBackendPtr backend;
    virStorageVolDefPtr vol;
1879
    char *ret = NULL;
1880

1881
    storageDriverLock(driver);
1882
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
1883 1884
    storageDriverUnlock(driver);

1885
    if (!pool) {
1886
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1887
                              "%s", _("no storage pool with matching uuid"));
1888
        goto cleanup;
1889 1890 1891
    }

    if (!virStoragePoolObjIsActive(pool)) {
1892
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1893
                              "%s", _("storage pool is not active"));
1894
        goto cleanup;
1895 1896 1897 1898 1899
    }

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

    if (!vol) {
1900
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
1901 1902
                             _("no storage vol with matching name '%s'"),
                              obj->name);
1903
        goto cleanup;
1904 1905 1906
    }

    if ((backend = virStorageBackendForType(pool->def->type)) == NULL)
1907
        goto cleanup;
1908 1909 1910 1911

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

1913
    ret = virStorageVolDefFormat(pool->def, vol);
1914 1915

cleanup:
1916 1917 1918
    if (pool)
        virStoragePoolObjUnlock(pool);

1919
    return ret;
1920 1921 1922 1923
}

static char *
storageVolumeGetPath(virStorageVolPtr obj) {
1924
    virStorageDriverStatePtr driver = obj->conn->storagePrivateData;
1925
    virStoragePoolObjPtr pool;
1926
    virStorageVolDefPtr vol;
1927
    char *ret = NULL;
1928

1929 1930 1931
    storageDriverLock(driver);
    pool = virStoragePoolObjFindByName(&driver->pools, obj->pool);
    storageDriverUnlock(driver);
1932
    if (!pool) {
1933
        virStorageReportError(VIR_ERR_INVALID_STORAGE_POOL,
J
Jim Meyering 已提交
1934
                              "%s", _("no storage pool with matching uuid"));
1935
        goto cleanup;
1936 1937 1938
    }

    if (!virStoragePoolObjIsActive(pool)) {
1939
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
J
Jim Meyering 已提交
1940
                              "%s", _("storage pool is not active"));
1941
        goto cleanup;
1942 1943 1944 1945 1946
    }

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

    if (!vol) {
1947 1948
        virStorageReportError(VIR_ERR_NO_STORAGE_VOL,
                              _("no storage vol with matching name '%s'"),
1949
                              obj->name);
1950
        goto cleanup;
1951 1952 1953
    }

    ret = strdup(vol->target.path);
1954
    if (ret == NULL)
1955
        virReportOOMError();
1956 1957

cleanup:
1958 1959
    if (pool)
        virStoragePoolObjUnlock(pool);
1960 1961 1962 1963
    return ret;
}

static virStorageDriver storageDriver = {
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993
    .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,
1994
    .volCreateXMLFrom = storageVolumeCreateXMLFrom,
1995
    .volDelete = storageVolumeDelete,
1996
    .volWipe = storageVolumeWipe,
1997 1998 1999
    .volGetInfo = storageVolumeGetInfo,
    .volGetXMLDesc = storageVolumeGetXMLDesc,
    .volGetPath = storageVolumeGetPath,
2000 2001 2002

    .poolIsActive = storagePoolIsActive,
    .poolIsPersistent = storagePoolIsPersistent,
2003 2004 2005 2006
};


static virStateDriver stateDriver = {
2007
    .name = "Storage",
2008 2009 2010 2011
    .initialize = storageDriverStartup,
    .cleanup = storageDriverShutdown,
    .reload = storageDriverReload,
    .active = storageDriverActive,
2012 2013 2014 2015 2016 2017 2018
};

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