storage_driver.c 56.4 KB
Newer Older
1 2 3
/*
 * storage_driver.c: core driver for storage APIs
 *
4
 * Copyright (C) 2006-2010 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
#include "files.h"
49
#include "configmake.h"
50

51 52
#define VIR_FROM_THIS VIR_FROM_STORAGE

53 54 55 56
static virStorageDriverStatePtr driverState;

static int storageDriverShutdown(void);

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

static void
storageDriverAutostart(virStorageDriverStatePtr driver) {
68
    unsigned int i;
69

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

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

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

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

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

119
    if (VIR_ALLOC(driverState) < 0)
120 121
        return -1;

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

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

        if (!userdir)
            goto error;
137

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

    /* 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';

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

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

161
    VIR_FREE(base);
162 163 164 165 166 167 168 169

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

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

176
    storageDriverUnlock(driverState);
177 178
    return 0;

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

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

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

    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) {
218
    unsigned int i;
219
    int active = 0;
220 221 222 223

    if (!driverState)
        return 0;

224 225 226 227
    storageDriverLock(driverState);

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

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

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

247
    storageDriverLock(driverState);
248 249

    /* free inactive pools */
250 251 252 253
    virStoragePoolObjListFree(&driverState->pools);

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

    return 0;
}



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

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

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

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

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

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

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

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

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

cleanup:
308 309
    if (pool)
        virStoragePoolObjUnlock(pool);
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 335 336
    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) {
337
    virStorageDriverStatePtr driver = conn->storagePrivateData;
338 339
    unsigned int i, nactive = 0;

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

    return nactive;
350 351 352 353 354 355
}

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

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

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

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

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

    return nactive;
398 399 400 401 402 403
}

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

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

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

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

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

    backend = virStorageBackendForType(backend_type);
    if (backend == NULL)
453
        goto cleanup;
454

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

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

464 465
cleanup:
    return ret;
466 467 468
}


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

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

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

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

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

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


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

522
    storageDriverLock(driver);
523
    if (!(def = virStoragePoolDefParseString(xml)))
524
        goto cleanup;
525

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

529 530
    if ((backend = virStorageBackendForType(def->type)) == NULL)
        goto cleanup;
531

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

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

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

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

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

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

571
    storageDriverLock(driver);
572
    if (!(def = virStoragePoolDefParseString(xml)))
573
        goto cleanup;
574

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

578
    if (virStorageBackendForType(def->type) == NULL)
579
        goto cleanup;
580

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

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

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

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

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

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

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

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

628
    if (virStoragePoolObjDeleteDef(pool) < 0)
629
        goto cleanup;
630

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

637 638
    VIR_FREE(pool->configFile);
    VIR_FREE(pool->autostartLink);
639

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

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

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

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

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

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

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

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

    pool->active = 1;
688
    ret = 0;
689

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

    virStoragePoolObjClearVols(pool);

    pool->active = 0;

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

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


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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

        pool->active = 0;

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

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


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

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

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

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

    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;
923
    ret = 0;
924

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

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

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

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

948
    ret = virStoragePoolDefFormat(pool->def);
949 950

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

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

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

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

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

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

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

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

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

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

    autostart = (autostart != 0);

1010 1011 1012
    if (pool->autostart != autostart) {
        if (autostart) {
            int err;
1013

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

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

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


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

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

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

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

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

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

1085 1086
    memset(names, 0, maxnames * sizeof(*names));

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

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

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

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

1110
    virStoragePoolObjUnlock(pool);
1111
    return n;
1112 1113

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

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


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

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

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

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

    vol = virStorageVolDefFindByName(pool, name);

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

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

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


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

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

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

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

    return ret;
1195 1196 1197 1198 1199
}

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

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

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

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

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

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

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

cleanup:
1246
    VIR_FREE(cleanpath);
1247
    storageDriverUnlock(driver);
1248
    return ret;
1249 1250
}

1251 1252
static int storageVolumeDelete(virStorageVolPtr obj, unsigned int flags);

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

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

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

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

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

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

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

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

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

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

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

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

        if (VIR_ALLOC(buildvoldef) < 0) {
1318
            virReportOOMError();
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
            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);

1334
        buildret = backend->buildVol(obj->conn, pool, buildvoldef);
1335

1336
        storageDriverLock(driver);
1337
        virStoragePoolObjLock(pool);
1338 1339
        storageDriverUnlock(driver);

1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        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;
1358

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

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
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;
1378
    int buildret;
1379 1380 1381

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

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

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

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

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

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

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

    if (virStorageVolDefFindByName(pool, newvol->name)) {
1429
        virStorageReportError(VIR_ERR_INTERNAL_ERROR,
1430 1431 1432 1433 1434 1435 1436 1437 1438
                              _("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;

1439 1440 1441 1442 1443
    /* 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;

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

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

1482
    if (origpool) {
1483 1484 1485 1486
        origpool->asyncjobs++;
        virStoragePoolObjUnlock(origpool);
    }

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

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

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

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

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 1560 1561

/* 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 "
1562
                               "path '%s' to %ju bytes"),
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
                             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);

1669
    VIR_FORCE_CLOSE(fd);
1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683

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