storage_backend_rbd.c 44.7 KB
Newer Older
1 2 3
/*
 * storage_backend_rbd.c: storage backend for RBD (RADOS Block Device) handling
 *
4
 * Copyright (C) 2013-2016 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17
 * Copyright (C) 2012 Wido den Hollander
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with this library.  If not, see
O
Osier Yang 已提交
19
 * <http://www.gnu.org/licenses/>.
20 21 22 23
 */

#include <config.h>

E
Eric Blake 已提交
24
#include <inttypes.h>
25
#include "datatypes.h"
26
#include "virerror.h"
27 28
#include "storage_backend_rbd.h"
#include "storage_conf.h"
29
#include "viralloc.h"
30
#include "virlog.h"
31
#include "base64.h"
32
#include "viruuid.h"
33
#include "virstring.h"
34
#include "virrandom.h"
35 36
#include "rados/librados.h"
#include "rbd/librbd.h"
37
#include "secret_util.h"
38
#include "storage_util.h"
39 40 41

#define VIR_FROM_THIS VIR_FROM_STORAGE

42 43
VIR_LOG_INIT("storage.storage_backend_rbd");

44 45 46 47 48 49 50
struct _virStorageBackendRBDState {
    rados_t cluster;
    rados_ioctx_t ioctx;
    time_t starttime;
};

typedef struct _virStorageBackendRBDState virStorageBackendRBDState;
E
Eric Blake 已提交
51
typedef virStorageBackendRBDState *virStorageBackendRBDStatePtr;
52

53 54 55 56 57 58 59 60
typedef struct _virStoragePoolRBDConfigOptionsDef virStoragePoolRBDConfigOptionsDef;
typedef virStoragePoolRBDConfigOptionsDef *virStoragePoolRBDConfigOptionsDefPtr;
struct _virStoragePoolRBDConfigOptionsDef {
    size_t noptions;
    char **names;
    char **values;
};

61
#define STORAGE_POOL_RBD_NAMESPACE_HREF "http://libvirt.org/schemas/storagepool/rbd/1.0"
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

static void
virStoragePoolDefRBDNamespaceFree(void *nsdata)
{
    virStoragePoolRBDConfigOptionsDefPtr cmdopts = nsdata;
    size_t i;

    if (!cmdopts)
        return;

    for (i = 0; i < cmdopts->noptions; i++) {
        VIR_FREE(cmdopts->names[i]);
        VIR_FREE(cmdopts->values[i]);
    }
    VIR_FREE(cmdopts->names);
    VIR_FREE(cmdopts->values);

    VIR_FREE(cmdopts);
}


static int
virStoragePoolDefRBDNamespaceParse(xmlXPathContextPtr ctxt,
                                   void **data)
{
    virStoragePoolRBDConfigOptionsDefPtr cmdopts = NULL;
    int nnodes;
    size_t i;
    int ret = -1;
91
    VIR_AUTOFREE(xmlNodePtr *)nodes = NULL;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

    nnodes = virXPathNodeSet("./rbd:config_opts/rbd:option", ctxt, &nodes);
    if (nnodes < 0)
        return -1;

    if (nnodes == 0)
        return 0;

    if (VIR_ALLOC(cmdopts) < 0)
        goto cleanup;

    if (VIR_ALLOC_N(cmdopts->names, nnodes) < 0 ||
        VIR_ALLOC_N(cmdopts->values, nnodes) < 0)
        goto cleanup;

    for (i = 0; i < nnodes; i++) {
        if (!(cmdopts->names[cmdopts->noptions] =
              virXMLPropString(nodes[i], "name"))) {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("no rbd option name specified"));
            goto cleanup;
        }
        if (*cmdopts->names[cmdopts->noptions] == '\0') {
            virReportError(VIR_ERR_XML_ERROR, "%s",
                           _("empty rbd option name specified"));
            goto cleanup;
        }
        if (!(cmdopts->values[cmdopts->noptions] =
              virXMLPropString(nodes[i], "value"))) {
            virReportError(VIR_ERR_XML_ERROR,
                           _("no rbd option value specified for name '%s'"),
                           cmdopts->names[cmdopts->noptions]);
            goto cleanup;
        }
        if (*cmdopts->values[cmdopts->noptions] == '\0') {
            virReportError(VIR_ERR_XML_ERROR,
                           _("empty rbd option value specified for name '%s'"),
                           cmdopts->names[cmdopts->noptions]);
            goto cleanup;
        }
        cmdopts->noptions++;
    }

    VIR_STEAL_PTR(*data, cmdopts);
    ret = 0;

 cleanup:
    virStoragePoolDefRBDNamespaceFree(cmdopts);
    return ret;
}


static int
virStoragePoolDefRBDNamespaceFormatXML(virBufferPtr buf,
                                       void *nsdata)
{
    size_t i;
    virStoragePoolRBDConfigOptionsDefPtr def = nsdata;

    if (!def)
        return 0;

    virBufferAddLit(buf, "<rbd:config_opts>\n");
    virBufferAdjustIndent(buf, 2);

    for (i = 0; i < def->noptions; i++) {
        virBufferEscapeString(buf, "<rbd:option name='%s' ", def->names[i]);
        virBufferEscapeString(buf, "value='%s'/>\n", def->values[i]);
    }

    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</rbd:config_opts>\n");

    return 0;
}


static const char *
virStoragePoolDefRBDNamespaceHref(void)
{
172
    return STORAGE_POOL_RBD_NAMESPACE_HREF;
173 174 175
}


176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
static int
virStorageBackendRBDRADOSConfSet(rados_t cluster,
                                 const char *option,
                                 const char *value)
{
    VIR_DEBUG("Setting RADOS option '%s' to '%s'",
              option, value);
    if (rados_conf_set(cluster, option, value) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to set RADOS option: %s"),
                       option);
        return -1;
    }

    return 0;
}

W
Wido den Hollander 已提交
193 194
static int
virStorageBackendRBDOpenRADOSConn(virStorageBackendRBDStatePtr ptr,
195
                                  virStoragePoolDefPtr def)
196 197
{
    int ret = -1;
198
    int r = 0;
199
    virStoragePoolSourcePtr source = &def->source;
200
    virStorageAuthDefPtr authdef = source->auth;
201
    unsigned char *secret_value = NULL;
202
    size_t secret_value_size = 0;
203
    VIR_AUTODISPOSE_STR rados_key = NULL;
204
    virBuffer mon_host = VIR_BUFFER_INITIALIZER;
205
    size_t i;
206 207 208
    const char *client_mount_timeout = "30";
    const char *mon_op_timeout = "30";
    const char *osd_op_timeout = "30";
209
    const char *rbd_default_format = "2";
210
    virConnectPtr conn = NULL;
211
    VIR_AUTOFREE(char *) mon_buff = NULL;
212

213 214
    if (authdef) {
        VIR_DEBUG("Using cephx authorization, username: %s", authdef->username);
W
Wido den Hollander 已提交
215 216

        if ((r = rados_create(&ptr->cluster, authdef->username)) < 0) {
217
            virReportSystemError(-r, "%s", _("failed to initialize RADOS"));
218 219 220
            goto cleanup;
        }

221 222
        conn = virGetConnectSecret();
        if (!conn)
223 224
            return -1;

225 226
        if (virSecretGetSecretString(conn, &authdef->seclookupdef,
                                     VIR_SECRET_USAGE_TYPE_CEPH,
227
                                     &secret_value, &secret_value_size) < 0)
228
            goto cleanup;
229

230
        if (!(rados_key = virStringEncodeBase64(secret_value, secret_value_size)))
231 232
            goto cleanup;

233 234
        if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                             "key", rados_key) < 0)
235 236
            goto cleanup;

237 238
        if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                             "auth_supported", "cephx") < 0)
239 240 241 242
            goto cleanup;
    } else {
        VIR_DEBUG("Not using cephx authorization");
        if (rados_create(&ptr->cluster, NULL) < 0) {
243
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
244
                           _("failed to create the RADOS cluster"));
245 246
            goto cleanup;
        }
247 248
        if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                             "auth_supported", "none") < 0)
249 250 251 252
            goto cleanup;
    }

    VIR_DEBUG("Found %zu RADOS cluster monitors in the pool configuration",
253
              source->nhost);
254

255
    /* combine host and port into portal */
256 257 258
    for (i = 0; i < source->nhost; i++) {
        if (source->hosts[i].name != NULL &&
            !source->hosts[i].port) {
259
            virBufferAsprintf(&mon_host, "%s,",
260 261 262
                              source->hosts[i].name);
        } else if (source->hosts[i].name != NULL &&
            source->hosts[i].port) {
263 264 265
            const char *incFormat;
            if (virSocketAddrNumericFamily(source->hosts[i].name) == AF_INET6) {
                /* IPv6 address must be escaped in brackets on the cmd line */
266
                incFormat = "[%s]:%d,";
267 268
            } else {
                /* listenAddress is a hostname or IPv4 */
269
                incFormat = "%s:%d,";
270 271
            }
            virBufferAsprintf(&mon_host, incFormat,
272 273
                              source->hosts[i].name,
                              source->hosts[i].port);
274
        } else {
275 276
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("received malformed monitor, check the XML definition"));
277 278 279
        }
    }

280 281
    if (virBufferCheckError(&mon_host) < 0)
        goto cleanup;
282 283

    mon_buff = virBufferContentAndReset(&mon_host);
284 285 286
    if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                         "mon_host",
                                         mon_buff) < 0)
287 288
        goto cleanup;

289 290 291 292 293
    /*
     * Set timeout options for librados.
     * In case the Ceph cluster is down libvirt won't block forever.
     * Operations in librados will return -ETIMEDOUT when the timeout is reached.
     */
294 295 296 297
    if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                         "client_mount_timeout",
                                         client_mount_timeout) < 0)
        goto cleanup;
298

299 300 301 302
    if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                         "rados_mon_op_timeout",
                                         mon_op_timeout) < 0)
        goto cleanup;
303

304 305 306 307
    if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                         "rados_osd_op_timeout",
                                         osd_op_timeout) < 0)
        goto cleanup;
308

309 310 311 312 313
    /*
     * Librbd supports creating RBD format 2 images. We no longer have to invoke
     * rbd_create3(), we can tell librbd to default to format 2.
     * This leaves us to simply use rbd_create() and use the default behavior of librbd
     */
314 315 316 317
    if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                         "rbd_default_format",
                                         rbd_default_format) < 0)
        goto cleanup;
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    if (def->namespaceData) {
        virStoragePoolRBDConfigOptionsDefPtr cmdopts = def->namespaceData;
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        for (i = 0; i < cmdopts->noptions; i++) {
            if (virStorageBackendRBDRADOSConfSet(ptr->cluster,
                                                 cmdopts->names[i],
                                                 cmdopts->values[i]) < 0)
                goto cleanup;
        }

        virUUIDFormat(def->uuid, uuidstr);
        VIR_WARN("Storage Pool name='%s' uuid='%s' is tainted by custom "
                 "config_opts from XML", def->name, uuidstr);
    }

335
    ptr->starttime = time(0);
W
Wido den Hollander 已提交
336
    if ((r = rados_connect(ptr->cluster)) < 0) {
337 338
        virReportSystemError(-r, _("failed to connect to the RADOS monitor on: %s"),
                             mon_buff);
339 340 341 342 343
        goto cleanup;
    }

    ret = 0;

344
 cleanup:
345
    VIR_DISPOSE_N(secret_value, secret_value_size);
346

347
    virObjectUnref(conn);
348 349 350 351
    virBufferFreeAndReset(&mon_host);
    return ret;
}

W
Wido den Hollander 已提交
352 353 354
static int
virStorageBackendRBDOpenIoCTX(virStorageBackendRBDStatePtr ptr,
                              virStoragePoolObjPtr pool)
355
{
356 357
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
    int r = rados_ioctx_create(ptr->cluster, def->source.name, &ptr->ioctx);
358 359
    if (r < 0) {
        virReportSystemError(-r, _("failed to create the RBD IoCTX. Does the pool '%s' exist?"),
360
                             def->source.name);
361 362 363 364
    }
    return r;
}

365
static void
W
Wido den Hollander 已提交
366
virStorageBackendRBDCloseRADOSConn(virStorageBackendRBDStatePtr ptr)
367
{
E
Eric Blake 已提交
368
    if (ptr->ioctx != NULL) {
369
        VIR_DEBUG("Closing RADOS IoCTX");
E
Eric Blake 已提交
370
        rados_ioctx_destroy(ptr->ioctx);
371
    }
E
Eric Blake 已提交
372
    ptr->ioctx = NULL;
373

E
Eric Blake 已提交
374
    if (ptr->cluster != NULL) {
375
        VIR_DEBUG("Closing RADOS connection");
E
Eric Blake 已提交
376
        rados_shutdown(ptr->cluster);
377
    }
E
Eric Blake 已提交
378
    ptr->cluster = NULL;
379

380 381
    VIR_DEBUG("RADOS connection existed for %ld seconds",
              time(0) - ptr->starttime);
382 383
}

384 385 386 387 388 389 390 391 392 393 394 395 396 397

static void
virStorageBackendRBDFreeState(virStorageBackendRBDStatePtr *ptr)
{
    if (!*ptr)
        return;

    virStorageBackendRBDCloseRADOSConn(*ptr);

    VIR_FREE(*ptr);
}


static virStorageBackendRBDStatePtr
398
virStorageBackendRBDNewState(virStoragePoolObjPtr pool)
399 400
{
    virStorageBackendRBDStatePtr ptr;
401
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
402 403 404 405

    if (VIR_ALLOC(ptr) < 0)
        return NULL;

406
    if (virStorageBackendRBDOpenRADOSConn(ptr, def) < 0)
407 408 409 410 411 412 413 414 415 416 417 418 419
        goto error;

    if (virStorageBackendRBDOpenIoCTX(ptr, pool) < 0)
        goto error;

    return ptr;

 error:
    virStorageBackendRBDFreeState(&ptr);
    return NULL;
}


420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
static int
volStorageBackendRBDGetFeatures(rbd_image_t image,
                                const char *volname,
                                uint64_t *features)
{
    int r, ret = -1;

    if ((r = rbd_get_features(image, features)) < 0) {
        virReportSystemError(-r, _("failed to get the features of RBD image "
                                 "%s"), volname);
        goto cleanup;
    }
    ret = 0;

 cleanup:
    return ret;
}

438
#if LIBRBD_VERSION_CODE > 265
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
static int
volStorageBackendRBDGetFlags(rbd_image_t image,
                             const char *volname,
                             uint64_t *flags)
{
    int rc;

    if ((rc = rbd_get_flags(image, flags)) < 0) {
        virReportSystemError(-rc,
                             _("failed to get the flags of RBD image %s"),
                             volname);
        return -1;
    }

    return 0;
}

456
static bool
457
volStorageBackendRBDUseFastDiff(uint64_t features, uint64_t flags)
458
{
459 460
    return (((features & RBD_FEATURE_FAST_DIFF) != 0ULL) &&
            ((flags & RBD_FLAG_FAST_DIFF_INVALID) == 0ULL));
461 462 463 464 465 466 467 468
}

static int
virStorageBackendRBDRefreshVolInfoCb(uint64_t offset ATTRIBUTE_UNUSED,
                                     size_t len,
                                     int exists,
                                     void *arg)
{
P
Peter Krempa 已提交
469
    size_t *used_size = (size_t *)(arg);
470 471 472 473 474 475 476 477 478 479 480 481
    if (exists)
        (*used_size) += len;

    return 0;
}

static int
virStorageBackendRBDSetAllocation(virStorageVolDefPtr vol,
                                  rbd_image_t *image,
                                  rbd_image_info_t *info)
{
    int r, ret = -1;
P
Peter Krempa 已提交
482
    size_t allocation = 0;
483 484 485 486 487 488 489 490 491

    if ((r = rbd_diff_iterate2(image, NULL, 0, info->size, 0, 1,
                               &virStorageBackendRBDRefreshVolInfoCb,
                               &allocation)) < 0) {
        virReportSystemError(-r, _("failed to iterate RBD image '%s'"),
                             vol->name);
        goto cleanup;
    }

P
Peter Krempa 已提交
492
    VIR_DEBUG("Found %zu bytes allocated for RBD image %s",
493 494 495 496 497 498 499 500 501 502 503
              allocation, vol->name);

    vol->target.allocation = allocation;
    ret = 0;

 cleanup:
    return ret;
}

#else
static int
504 505
volStorageBackendRBDGetFlags(rbd_image_t image ATTRIBUTE_UNUSED,
                             const char *volname ATTRIBUTE_UNUSED,
506 507 508 509 510 511 512 513 514
                             uint64_t *flags)
{
    *flags = 0;
    return 0;
}

static int
volStorageBackendRBDUseFastDiff(uint64_t features ATTRIBUTE_UNUSED,
                                uint64_t feature_flags ATTRIBUTE_UNUSED)
515 516 517 518 519 520 521 522 523 524 525 526 527
{
    return false;
}

static int
virStorageBackendRBDSetAllocation(virStorageVolDefPtr vol ATTRIBUTE_UNUSED,
                                  rbd_image_t *image ATTRIBUTE_UNUSED,
                                  rbd_image_info_t *info ATTRIBUTE_UNUSED)
{
    return false;
}
#endif

W
Wido den Hollander 已提交
528 529 530 531
static int
volStorageBackendRBDRefreshVolInfo(virStorageVolDefPtr vol,
                                   virStoragePoolObjPtr pool,
                                   virStorageBackendRBDStatePtr ptr)
532 533
{
    int ret = -1;
534
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
535
    int r = 0;
536
    rbd_image_t image = NULL;
W
Wido den Hollander 已提交
537
    rbd_image_info_t info;
538
    uint64_t features;
539
    uint64_t flags;
540

W
Wido den Hollander 已提交
541
    if ((r = rbd_open_read_only(ptr->ioctx, vol->name, &image, NULL)) < 0) {
542
        ret = -r;
543 544
        virReportSystemError(-r, _("failed to open the RBD image '%s'"),
                             vol->name);
545
        goto cleanup;
546 547
    }

W
Wido den Hollander 已提交
548
    if ((r = rbd_stat(image, &info, sizeof(info))) < 0) {
549
        ret = -r;
550 551
        virReportSystemError(-r, _("failed to stat the RBD image '%s'"),
                             vol->name);
552 553 554
        goto cleanup;
    }

555 556
    if (volStorageBackendRBDGetFeatures(image, vol->name, &features) < 0)
        goto cleanup;
557

558 559 560
    if (volStorageBackendRBDGetFlags(image, vol->name, &flags) < 0)
        goto cleanup;

561
    vol->target.capacity = info.size;
562
    vol->type = VIR_STORAGE_VOL_NETWORK;
563
    vol->target.format = VIR_STORAGE_FILE_RAW;
564

565 566 567
    if (def->refresh &&
        def->refresh->volume.allocation == VIR_STORAGE_VOL_DEF_REFRESH_ALLOCATION_DEFAULT &&
        volStorageBackendRBDUseFastDiff(features, flags)) {
568 569
        VIR_DEBUG("RBD image %s/%s has fast-diff feature enabled. "
                  "Querying for actual allocation",
570
                  def->source.name, vol->name);
571 572 573 574 575 576 577 578

        if (virStorageBackendRBDSetAllocation(vol, image, &info) < 0)
            goto cleanup;
    } else {
        vol->target.allocation = info.obj_size * info.num_objs;
    }

    VIR_DEBUG("Refreshed RBD image %s/%s (capacity: %llu allocation: %llu "
E
Eric Blake 已提交
579
                      "obj_size: %"PRIu64" num_objs: %"PRIu64")",
580
              def->source.name, vol->name, vol->target.capacity,
581 582
              vol->target.allocation, info.obj_size, info.num_objs);

583
    VIR_FREE(vol->target.path);
584
    if (virAsprintf(&vol->target.path, "%s/%s",
585
                    def->source.name, vol->name) < 0)
586 587 588 589
        goto cleanup;

    VIR_FREE(vol->key);
    if (virAsprintf(&vol->key, "%s/%s",
590
                    def->source.name, vol->name) < 0)
591 592 593 594
        goto cleanup;

    ret = 0;

595
 cleanup:
596 597
    if (image)
        rbd_close(image);
598 599 600
    return ret;
}

601

602 603 604 605 606 607 608 609 610 611 612 613
#ifdef HAVE_RBD_LIST2
static char **
virStorageBackendRBDGetVolNames(virStorageBackendRBDStatePtr ptr)
{
    char **names = NULL;
    size_t nnames = 0;
    int rc;
    rbd_image_spec_t *images = NULL;
    size_t nimages = 16;
    size_t i;

    while (true) {
614
        if (VIR_REALLOC_N(images, nimages) < 0)
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
            goto error;

        rc = rbd_list2(ptr->ioctx, images, &nimages);
        if (rc >= 0)
            break;
        if (rc != -ERANGE) {
            virReportSystemError(-rc, "%s", _("Unable to list RBD images"));
            goto error;
        }
    }

    if (VIR_ALLOC_N(names, nimages + 1) < 0)
        goto error;
    nnames = nimages;

    for (i = 0; i < nimages; i++)
631
        VIR_STEAL_PTR(names[i], images[i].name);
632 633 634 635 636 637 638 639 640 641 642 643

    return names;

 error:
    virStringListFreeCount(names, nnames);
    rbd_image_spec_list_cleanup(images, nimages);
    VIR_FREE(images);
    return NULL;
}

#else /* ! HAVE_RBD_LIST2 */

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
static char **
virStorageBackendRBDGetVolNames(virStorageBackendRBDStatePtr ptr)
{
    char **names = NULL;
    size_t nnames = 0;
    int rc;
    size_t max_size = 1024;
    VIR_AUTOFREE(char *) namebuf = NULL;
    const char *name;

    while (true) {
        if (VIR_ALLOC_N(namebuf, max_size) < 0)
            goto error;

        rc = rbd_list(ptr->ioctx, namebuf, &max_size);
        if (rc >= 0)
            break;
        if (rc != -ERANGE) {
            virReportSystemError(-rc, "%s", _("Unable to list RBD images"));
            goto error;
        }
        VIR_FREE(namebuf);
    }

    for (name = namebuf; name < namebuf + max_size;) {
        VIR_AUTOFREE(char *) namedup = NULL;

        if (STREQ(name, ""))
            break;

        if (VIR_STRDUP(namedup, name) < 0)
            goto error;

        if (VIR_APPEND_ELEMENT(names, nnames, namedup) < 0)
            goto error;

        name += strlen(name) + 1;
    }

    if (VIR_EXPAND_N(names, nnames, 1) < 0)
        goto error;

    return names;

 error:
    virStringListFreeCount(names, nnames);
    return NULL;
}
692
#endif /* ! HAVE_RBD_LIST2 */
693 694


W
Wido den Hollander 已提交
695
static int
696
virStorageBackendRBDRefreshPool(virStoragePoolObjPtr pool)
697 698
{
    int ret = -1;
699
    int r = 0;
700
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
701
    virStorageBackendRBDStatePtr ptr = NULL;
W
Wido den Hollander 已提交
702 703
    struct rados_cluster_stat_t clusterstat;
    struct rados_pool_stat_t poolstat;
704 705
    char **names = NULL;
    size_t i;
706

707
    if (!(ptr = virStorageBackendRBDNewState(pool)))
708 709
        goto cleanup;

710
    if ((r = rados_cluster_stat(ptr->cluster, &clusterstat)) < 0) {
711
        virReportSystemError(-r, "%s", _("failed to stat the RADOS cluster"));
712 713 714
        goto cleanup;
    }

715
    if ((r = rados_ioctx_pool_stat(ptr->ioctx, &poolstat)) < 0) {
716
        virReportSystemError(-r, _("failed to stat the RADOS pool '%s'"),
717
                             def->source.name);
718 719 720
        goto cleanup;
    }

721 722 723
    def->capacity = clusterstat.kb * 1024;
    def->available = clusterstat.kb_avail * 1024;
    def->allocation = poolstat.num_bytes;
724

E
Eric Blake 已提交
725 726
    VIR_DEBUG("Utilization of RBD pool %s: (kb: %"PRIu64" kb_avail: %"PRIu64
              " num_bytes: %"PRIu64")",
727
              def->source.name, clusterstat.kb, clusterstat.kb_avail,
728
              poolstat.num_bytes);
729

730 731
    if (!(names = virStorageBackendRBDGetVolNames(ptr)))
        goto cleanup;
732

733
    for (i = 0; names[i] != NULL; i++) {
734
        VIR_AUTOPTR(virStorageVolDef) vol = NULL;
735

736
        if (VIR_ALLOC(vol) < 0)
737
            goto cleanup;
738

739
        VIR_STEAL_PTR(vol->name, names[i]);
740

741
        r = volStorageBackendRBDRefreshVolInfo(vol, pool, ptr);
742 743 744 745 746 747 748 749 750 751 752 753 754 755

        /* It could be that a volume has been deleted through a different route
         * then libvirt and that will cause a -ENOENT to be returned.
         *
         * Another possibility is that there is something wrong with the placement
         * group (PG) that RBD image's header is in and that causes -ETIMEDOUT
         * to be returned.
         *
         * Do not error out and simply ignore the volume
         */
        if (r < 0) {
            if (r == -ENOENT || r == -ETIMEDOUT)
                continue;

756
            goto cleanup;
757
        }
758

759
        if (virStoragePoolObjAddVol(pool, vol) < 0)
760
            goto cleanup;
761
        vol = NULL;
762 763
    }

764
    VIR_DEBUG("Found %zu images in RBD pool %s",
765
              virStoragePoolObjGetVolumesCount(pool), def->source.name);
766 767 768

    ret = 0;

769
 cleanup:
770
    virStringListFree(names);
771
    virStorageBackendRBDFreeState(&ptr);
772 773 774
    return ret;
}

W
Wido den Hollander 已提交
775 776 777 778
static int
virStorageBackendRBDCleanupSnapshots(rados_ioctx_t ioctx,
                                     virStoragePoolSourcePtr source,
                                     virStorageVolDefPtr vol)
779 780 781 782 783 784 785
{
    int ret = -1;
    int r = 0;
    int max_snaps = 128;
    int snap_count, protected;
    size_t i;
    rbd_image_t image = NULL;
786
    VIR_AUTOFREE(rbd_snap_info_t *) snaps = NULL;
787

W
Wido den Hollander 已提交
788
    if ((r = rbd_open(ioctx, vol->name, &image, NULL)) < 0) {
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
       virReportSystemError(-r, _("failed to open the RBD image '%s'"),
                            vol->name);
       goto cleanup;
    }

    do {
        if (VIR_ALLOC_N(snaps, max_snaps))
            goto cleanup;

        snap_count = rbd_snap_list(image, snaps, &max_snaps);
        if (snap_count <= 0)
            VIR_FREE(snaps);

    } while (snap_count == -ERANGE);

    VIR_DEBUG("Found %d snapshots for volume %s/%s", snap_count,
              source->name, vol->name);

807 808 809 810 811 812 813
    for (i = 0; i < snap_count; i++) {
        if ((r = rbd_snap_is_protected(image, snaps[i].name, &protected)) < 0) {
            virReportSystemError(-r, _("failed to verify if snapshot '%s/%s@%s' is protected"),
                                 source->name, vol->name,
                                 snaps[i].name);
            goto cleanup;
        }
814

815 816 817 818
        if (protected == 1) {
            VIR_DEBUG("Snapshot %s/%s@%s is protected needs to be "
                      "unprotected", source->name, vol->name,
                      snaps[i].name);
819

820 821
            if ((r = rbd_snap_unprotect(image, snaps[i].name)) < 0) {
                virReportSystemError(-r, _("failed to unprotect snapshot '%s/%s@%s'"),
822 823 824 825 826
                                     source->name, vol->name,
                                     snaps[i].name);
                goto cleanup;
            }
        }
827 828 829 830 831 832 833 834 835 836

        VIR_DEBUG("Removing snapshot %s/%s@%s", source->name,
                  vol->name, snaps[i].name);

        if ((r = rbd_snap_remove(image, snaps[i].name)) < 0) {
            virReportSystemError(-r, _("failed to remove snapshot '%s/%s@%s'"),
                                 source->name, vol->name,
                                 snaps[i].name);
            goto cleanup;
        }
837 838 839 840 841 842 843 844 845 846 847 848 849 850
    }

    ret = 0;

 cleanup:
    if (snaps)
        rbd_snap_list_end(snaps);

    if (image)
        rbd_close(image);

    return ret;
}

W
Wido den Hollander 已提交
851
static int
852
virStorageBackendRBDDeleteVol(virStoragePoolObjPtr pool,
W
Wido den Hollander 已提交
853 854
                              virStorageVolDefPtr vol,
                              unsigned int flags)
855 856
{
    int ret = -1;
857
    int r = 0;
858
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
859
    virStorageBackendRBDStatePtr ptr = NULL;
860

861 862 863
    virCheckFlags(VIR_STORAGE_VOL_DELETE_ZEROED |
                  VIR_STORAGE_VOL_DELETE_WITH_SNAPSHOTS, -1);

864
    VIR_DEBUG("Removing RBD image %s/%s", def->source.name, vol->name);
865

866
    if (flags & VIR_STORAGE_VOL_DELETE_ZEROED)
867
        VIR_WARN("%s", "This storage backend does not support zeroed removal of volumes");
868

869
    if (!(ptr = virStorageBackendRBDNewState(pool)))
870 871
        goto cleanup;

872
    if (flags & VIR_STORAGE_VOL_DELETE_WITH_SNAPSHOTS) {
873
        if (virStorageBackendRBDCleanupSnapshots(ptr->ioctx, &def->source,
874 875 876 877
                                                 vol) < 0)
            goto cleanup;
    }

878
    VIR_DEBUG("Removing volume %s/%s", def->source.name, vol->name);
879

880
    r = rbd_remove(ptr->ioctx, vol->name);
881
    if (r < 0 && (-r) != ENOENT) {
882
        virReportSystemError(-r, _("failed to remove volume '%s/%s'"),
883
                             def->source.name, vol->name);
884 885 886 887 888
        goto cleanup;
    }

    ret = 0;

889
 cleanup:
890
    virStorageBackendRBDFreeState(&ptr);
891 892 893
    return ret;
}

894 895

static int
896
virStorageBackendRBDCreateVol(virStoragePoolObjPtr pool,
897 898
                              virStorageVolDefPtr vol)
{
899 900
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);

901 902
    vol->type = VIR_STORAGE_VOL_NETWORK;

903
    if (vol->target.format != VIR_STORAGE_FILE_RAW) {
R
Richard Laager 已提交
904
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
905
                       _("only RAW volumes are supported by this storage pool"));
R
Richard Laager 已提交
906
        return -1;
907 908
    }

909 910
    VIR_FREE(vol->target.path);
    if (virAsprintf(&vol->target.path, "%s/%s",
911
                    def->source.name, vol->name) < 0)
912 913 914 915
        return -1;

    VIR_FREE(vol->key);
    if (virAsprintf(&vol->key, "%s/%s",
916
                    def->source.name, vol->name) < 0)
917 918 919 920 921
        return -1;

    return 0;
}

922 923 924 925
static int virStorageBackendRBDCreateImage(rados_ioctx_t io,
                                           char *name, long capacity)
{
    int order = 0;
926
    return rbd_create(io, name, capacity, &order);
927
}
928 929

static int
930
virStorageBackendRBDBuildVol(virStoragePoolObjPtr pool,
931 932
                             virStorageVolDefPtr vol,
                             unsigned int flags)
933
{
934
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
935
    virStorageBackendRBDStatePtr ptr = NULL;
936
    int ret = -1;
937
    int r = 0;
938 939

    VIR_DEBUG("Creating RBD image %s/%s with size %llu",
940
              def->source.name, vol->name, vol->target.capacity);
941

942 943
    virCheckFlags(0, -1);

944 945 946 947 948 949
    if (!vol->target.capacity) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("volume capacity required for this storage pool"));
        goto cleanup;
    }

950 951 952 953 954 955
    if (vol->target.format != VIR_STORAGE_FILE_RAW) {
        virReportError(VIR_ERR_NO_SUPPORT, "%s",
                       _("only RAW volumes are supported by this storage pool"));
        goto cleanup;
    }

956
    if (vol->target.encryption != NULL) {
957 958
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
                       _("storage pool does not support encrypted volumes"));
959 960 961
        goto cleanup;
    }

962
    if (!(ptr = virStorageBackendRBDNewState(pool)))
963 964
        goto cleanup;

965
    if ((r = virStorageBackendRBDCreateImage(ptr->ioctx, vol->name,
W
Wido den Hollander 已提交
966
                                             vol->target.capacity)) < 0) {
967
        virReportSystemError(-r, _("failed to create volume '%s/%s'"),
968
                             def->source.name, vol->name);
969 970 971 972 973
        goto cleanup;
    }

    ret = 0;

974
 cleanup:
975
    virStorageBackendRBDFreeState(&ptr);
976 977 978
    return ret;
}

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
static int
virStorageBackendRBDImageInfo(rbd_image_t image,
                              char *volname,
                              uint64_t *features,
                              uint64_t *stripe_unit,
                              uint64_t *stripe_count)
{
    int ret = -1;
    int r = 0;
    uint8_t oldformat;

    if ((r = rbd_get_old_format(image, &oldformat)) < 0) {
        virReportSystemError(-r, _("failed to get the format of RBD image %s"),
                             volname);
        goto cleanup;
    }

    if (oldformat != 0) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("RBD image %s is old format. Does not support "
                         "extended features and striping"),
                       volname);
        goto cleanup;
    }

1004
    if (volStorageBackendRBDGetFeatures(image, volname, features) < 0)
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
        goto cleanup;

    if ((r = rbd_get_stripe_unit(image, stripe_unit)) < 0) {
        virReportSystemError(-r, _("failed to get the stripe unit of RBD image %s"),
                             volname);
        goto cleanup;
    }

    if ((r = rbd_get_stripe_count(image, stripe_count)) < 0) {
        virReportSystemError(-r, _("failed to get the stripe count of RBD image %s"),
                             volname);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    return ret;
}

/* Callback function for rbd_diff_iterate() */
static int
virStorageBackendRBDIterateCb(uint64_t offset ATTRIBUTE_UNUSED,
                              size_t length ATTRIBUTE_UNUSED,
                              int exists ATTRIBUTE_UNUSED,
                              void *arg)
{
    /*
     * Just set that there is a diff for this snapshot, we do not care where
     *
     * When it returns a negative number the rbd_diff_iterate() function will stop
     *
     * That's why we return -1, meaning that there is a difference and we can stop
     * searching any further.
     */
    *(int*) arg = 1;
    return -1;
}

static int
virStorageBackendRBDSnapshotFindNoDiff(rbd_image_t image,
                                       char *imgname,
                                       virBufferPtr snapname)
{
    int r = -1;
    int ret = -1;
    int snap_count;
    int max_snaps = 128;
    size_t i;
    int diff;
    rbd_image_info_t info;
1056
    VIR_AUTOFREE(rbd_snap_info_t *) snaps = NULL;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092

    if ((r = rbd_stat(image, &info, sizeof(info))) < 0) {
        virReportSystemError(-r, _("failed to stat the RBD image %s"),
                             imgname);
        goto cleanup;
    }

    do {
        if (VIR_ALLOC_N(snaps, max_snaps))
            goto cleanup;

        snap_count = rbd_snap_list(image, snaps, &max_snaps);
        if (snap_count <= 0)
            VIR_FREE(snaps);

    } while (snap_count == -ERANGE);

    if (snap_count <= 0) {
        if (snap_count == 0)
            ret = 0;
        goto cleanup;
    }

    VIR_DEBUG("Found %d snapshots for RBD image %s", snap_count, imgname);

    for (i = 0; i < snap_count; i++) {
        VIR_DEBUG("Querying diff for RBD snapshot %s@%s", imgname,
                  snaps[i].name);

        /* The callback will set diff to non-zero if there is a diff */
        diff = 0;

/*
 * rbd_diff_iterate2() is available in versions above Ceph 0.94 (Hammer)
 * It uses a object map inside Ceph which is faster than rbd_diff_iterate()
 * which iterates all objects.
1093 1094
 * LIBRBD_VERSION_CODE for Ceph 0.94 is 265. In 266 and upwards diff_iterate2
 * is available
1095
 */
1096
#if LIBRBD_VERSION_CODE > 265
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
        r = rbd_diff_iterate2(image, snaps[i].name, 0, info.size, 0, 1,
                              virStorageBackendRBDIterateCb, (void *)&diff);
#else
        r = rbd_diff_iterate(image, snaps[i].name, 0, info.size,
                             virStorageBackendRBDIterateCb, (void *)&diff);
#endif

        if (r < 0) {
            virReportSystemError(-r, _("failed to iterate RBD snapshot %s@%s"),
                                 imgname, snaps[i].name);
            goto cleanup;
        }

        /* If diff is still set to zero we found a snapshot without deltas */
        if (diff == 0) {
            VIR_DEBUG("RBD snapshot %s@%s has no delta", imgname,
                      snaps[i].name);
            virBufferAsprintf(snapname, "%s", snaps[i].name);
            ret = 0;
            goto cleanup;
        }

        VIR_DEBUG("RBD snapshot %s@%s has deltas. Continuing search.",
                  imgname, snaps[i].name);
    }

    ret = 0;

 cleanup:
    if (snaps)
        rbd_snap_list_end(snaps);

    return ret;
}

static int
virStorageBackendRBDSnapshotCreate(rbd_image_t image,
                                   char *imgname,
                                   char *snapname)
{
    int ret = -1;
    int r = -1;

    VIR_DEBUG("Creating RBD snapshot %s@%s", imgname, snapname);

    if ((r = rbd_snap_create(image, snapname)) < 0) {
        virReportSystemError(-r, _("failed to create RBD snapshot %s@%s"),
                                   imgname, snapname);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    return ret;
}

static int
virStorageBackendRBDSnapshotProtect(rbd_image_t image,
                                    char *imgname,
                                    char *snapname)
{
    int r = -1;
    int ret = -1;
    int protected;

    VIR_DEBUG("Querying if RBD snapshot %s@%s is protected", imgname, snapname);

    if ((r = rbd_snap_is_protected(image, snapname, &protected)) < 0) {
C
Chen Hanxiao 已提交
1166
        virReportSystemError(-r, _("failed to verify if RBD snapshot %s@%s "
1167 1168 1169 1170 1171 1172 1173 1174 1175
                                   "is protected"), imgname, snapname);
        goto cleanup;
    }

    if (protected == 0) {
        VIR_DEBUG("RBD Snapshot %s@%s is not protected, protecting",
                  imgname, snapname);

        if ((r = rbd_snap_protect(image, snapname)) < 0) {
C
Chen Hanxiao 已提交
1176
            virReportSystemError(-r, _("failed to protect RBD snapshot %s@%s"),
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                                       imgname, snapname);
            goto cleanup;
        }
    } else {
        VIR_DEBUG("RBD Snapshot %s@%s is already protected", imgname, snapname);
    }

    ret = 0;

 cleanup:
    return ret;
}

static int
virStorageBackendRBDCloneImage(rados_ioctx_t io,
                               char *origvol,
                               char *newvol)
{
    int r = -1;
    int ret = -1;
    int order = 0;
    uint64_t features;
    uint64_t stripe_count;
    uint64_t stripe_unit;
    virBuffer snapname = VIR_BUFFER_INITIALIZER;
    rbd_image_t image = NULL;
1203
    VIR_AUTOFREE(char *) snapname_buff = NULL;
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281

    if ((r = rbd_open(io, origvol, &image, NULL)) < 0) {
        virReportSystemError(-r, _("failed to open the RBD image %s"),
                             origvol);
        goto cleanup;
    }

    if ((virStorageBackendRBDImageInfo(image, origvol, &features, &stripe_unit,
                                       &stripe_count)) < 0)
        goto cleanup;

    /*
     * First we attempt to find a snapshot which has no differences between
     * the current state of the RBD image.
     *
     * This prevents us from creating a new snapshot for every clone operation
     * while it could be that the original volume has not changed
     */
    if (virStorageBackendRBDSnapshotFindNoDiff(image, origvol, &snapname) < 0)
        goto cleanup;

    /*
     * the virBuffer snapname will contain a snapshot's name if one without
     * deltas has been found.
     *
     * If it's NULL we have to create a new snapshot and clone from there
     */
    snapname_buff = virBufferContentAndReset(&snapname);

    if (snapname_buff == NULL) {
        VIR_DEBUG("No RBD snapshot with zero delta could be found for image %s",
                  origvol);

        virBufferAsprintf(&snapname, "libvirt-%d", (int)virRandomInt(65534));

        if (virBufferCheckError(&snapname) < 0)
            goto cleanup;

        snapname_buff = virBufferContentAndReset(&snapname);

        if (virStorageBackendRBDSnapshotCreate(image, origvol, snapname_buff) < 0)
            goto cleanup;

    }

    VIR_DEBUG("Using snapshot name %s for cloning RBD image %s to %s",
              snapname_buff, origvol, newvol);

    /*
     * RBD snapshots have to be 'protected' before they can be used
     * as a parent snapshot for a child image
     */
    if ((r = virStorageBackendRBDSnapshotProtect(image, origvol, snapname_buff)) < 0)
        goto cleanup;

    VIR_DEBUG("Performing RBD clone from %s to %s", origvol, newvol);

    if ((r = rbd_clone2(io, origvol, snapname_buff, io, newvol, features,
                        &order, stripe_unit, stripe_count)) < 0) {
        virReportSystemError(-r, _("failed to clone RBD volume %s to %s"),
                             origvol, newvol);
        goto cleanup;
    }

    VIR_DEBUG("Cloned RBD image %s to %s", origvol, newvol);

    ret = 0;

 cleanup:
    virBufferFreeAndReset(&snapname);

    if (image)
        rbd_close(image);

    return ret;
}

static int
1282
virStorageBackendRBDBuildVolFrom(virStoragePoolObjPtr pool,
1283 1284 1285 1286
                                 virStorageVolDefPtr newvol,
                                 virStorageVolDefPtr origvol,
                                 unsigned int flags)
{
1287
    virStoragePoolDefPtr def = virStoragePoolObjGetDef(pool);
1288
    virStorageBackendRBDStatePtr ptr = NULL;
1289 1290 1291
    int ret = -1;

    VIR_DEBUG("Creating clone of RBD image %s/%s with name %s",
1292
              def->source.name, origvol->name, newvol->name);
1293 1294 1295

    virCheckFlags(0, -1);

1296
    if (!(ptr = virStorageBackendRBDNewState(pool)))
1297 1298
        goto cleanup;

1299 1300
    if ((virStorageBackendRBDCloneImage(ptr->ioctx, origvol->name,
                                        newvol->name)) < 0)
1301 1302 1303 1304 1305
        goto cleanup;

    ret = 0;

 cleanup:
1306
    virStorageBackendRBDFreeState(&ptr);
1307 1308 1309
    return ret;
}

W
Wido den Hollander 已提交
1310
static int
1311
virStorageBackendRBDRefreshVol(virStoragePoolObjPtr pool,
W
Wido den Hollander 已提交
1312
                               virStorageVolDefPtr vol)
1313
{
1314
    virStorageBackendRBDStatePtr ptr = NULL;
1315 1316
    int ret = -1;

1317
    if (!(ptr = virStorageBackendRBDNewState(pool)))
1318 1319
        goto cleanup;

1320
    if (volStorageBackendRBDRefreshVolInfo(vol, pool, ptr) < 0)
1321 1322 1323 1324
        goto cleanup;

    ret = 0;

1325
 cleanup:
1326
    virStorageBackendRBDFreeState(&ptr);
1327 1328 1329
    return ret;
}

W
Wido den Hollander 已提交
1330
static int
1331
virStorageBackendRBDResizeVol(virStoragePoolObjPtr pool,
W
Wido den Hollander 已提交
1332 1333 1334
                              virStorageVolDefPtr vol,
                              unsigned long long capacity,
                              unsigned int flags)
1335
{
1336
    virStorageBackendRBDStatePtr ptr = NULL;
1337 1338
    rbd_image_t image = NULL;
    int ret = -1;
1339
    int r = 0;
1340 1341 1342

    virCheckFlags(0, -1);

1343
    if (!(ptr = virStorageBackendRBDNewState(pool)))
1344 1345
        goto cleanup;

1346
    if ((r = rbd_open(ptr->ioctx, vol->name, &image, NULL)) < 0) {
1347 1348
       virReportSystemError(-r, _("failed to open the RBD image '%s'"),
                            vol->name);
1349 1350 1351
       goto cleanup;
    }

W
Wido den Hollander 已提交
1352
    if ((r = rbd_resize(image, capacity)) < 0) {
1353 1354
        virReportSystemError(-r, _("failed to resize the RBD image '%s'"),
                             vol->name);
1355 1356 1357 1358 1359
        goto cleanup;
    }

    ret = 0;

1360
 cleanup:
1361 1362
    if (image != NULL)
       rbd_close(image);
1363
    virStorageBackendRBDFreeState(&ptr);
1364 1365 1366
    return ret;
}

1367 1368 1369 1370 1371 1372 1373
static int
virStorageBackendRBDVolWipeZero(rbd_image_t image,
                                char *imgname,
                                rbd_image_info_t *info,
                                uint64_t stripe_count)
{
    int r = -1;
E
Eric Blake 已提交
1374 1375
    unsigned long long offset = 0;
    unsigned long long length;
1376
    VIR_AUTOFREE(char *) writebuf = NULL;
1377 1378

    if (VIR_ALLOC_N(writebuf, info->obj_size * stripe_count) < 0)
1379
        return -1;
1380 1381 1382 1383 1384

    while (offset < info->size) {
        length = MIN((info->size - offset), (info->obj_size * stripe_count));

        if ((r = rbd_write(image, offset, length, writebuf)) < 0) {
E
Eric Blake 已提交
1385 1386
            virReportSystemError(-r, _("writing %llu bytes failed on "
                                       "RBD image %s at offset %llu"),
1387
                                       length, imgname, offset);
1388
            return -1;
1389 1390
        }

E
Eric Blake 已提交
1391
        VIR_DEBUG("Wrote %llu bytes to RBD image %s at offset %llu",
1392 1393 1394 1395 1396
                  length, imgname, offset);

        offset += length;
    }

1397
    return 0;
1398 1399
}

1400 1401 1402 1403 1404 1405 1406 1407
static int
virStorageBackendRBDVolWipeDiscard(rbd_image_t image,
                                   char *imgname,
                                   rbd_image_info_t *info,
                                   uint64_t stripe_count)
{
    int r = -1;
    int ret = -1;
E
Eric Blake 已提交
1408 1409
    unsigned long long offset = 0;
    unsigned long long length;
1410 1411 1412 1413 1414 1415 1416

    VIR_DEBUG("Wiping RBD %s volume using discard)", imgname);

    while (offset < info->size) {
        length = MIN((info->size - offset), (info->obj_size * stripe_count));

        if ((r = rbd_discard(image, offset, length)) < 0) {
E
Eric Blake 已提交
1417 1418
            virReportSystemError(-r, _("discarding %llu bytes failed on "
                                       "RBD image %s at offset %llu"),
1419 1420 1421 1422
                                     length, imgname, offset);
            goto cleanup;
        }

E
Eric Blake 已提交
1423
        VIR_DEBUG("Discarded %llu bytes of RBD image %s at offset %llu",
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
                  length, imgname, offset);

        offset += length;
    }

    ret = 0;

 cleanup:
    return ret;
}

1435
static int
1436
virStorageBackendRBDVolWipe(virStoragePoolObjPtr pool,
1437 1438 1439 1440
                            virStorageVolDefPtr vol,
                            unsigned int algorithm,
                            unsigned int flags)
{
1441
    virStorageBackendRBDStatePtr ptr = NULL;
1442
    virStoragePoolDefPtr def;
1443 1444 1445 1446 1447 1448 1449 1450
    rbd_image_t image = NULL;
    rbd_image_info_t info;
    uint64_t stripe_count;
    int r = -1;
    int ret = -1;

    virCheckFlags(0, -1);

1451 1452
    virObjectLock(pool);
    def = virStoragePoolObjGetDef(pool);
1453
    VIR_DEBUG("Wiping RBD image %s/%s", def->source.name, vol->name);
1454 1455
    ptr = virStorageBackendRBDNewState(pool);
    virObjectUnlock(pool);
1456

1457
    if (!ptr)
1458 1459
        goto cleanup;

1460
    if ((r = rbd_open(ptr->ioctx, vol->name, &image, NULL)) < 0) {
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
        virReportSystemError(-r, _("failed to open the RBD image %s"),
                             vol->name);
        goto cleanup;
    }

    if ((r = rbd_stat(image, &info, sizeof(info))) < 0) {
        virReportSystemError(-r, _("failed to stat the RBD image %s"),
                             vol->name);
        goto cleanup;
    }

    if ((r = rbd_get_stripe_count(image, &stripe_count)) < 0) {
        virReportSystemError(-r, _("failed to get stripe count of RBD image %s"),
                             vol->name);
        goto cleanup;
    }

E
Eric Blake 已提交
1478
    VIR_DEBUG("Need to wipe %"PRIu64" bytes from RBD image %s/%s",
1479
              info.size, def->source.name, vol->name);
1480 1481 1482 1483 1484

    switch ((virStorageVolWipeAlgorithm) algorithm) {
    case VIR_STORAGE_VOL_WIPE_ALG_ZERO:
        r = virStorageBackendRBDVolWipeZero(image, vol->name,
                                            &info, stripe_count);
1485 1486 1487 1488
            break;
    case VIR_STORAGE_VOL_WIPE_ALG_TRIM:
        r = virStorageBackendRBDVolWipeDiscard(image, vol->name,
                                               &info, stripe_count);
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
        break;
    case VIR_STORAGE_VOL_WIPE_ALG_NNSA:
    case VIR_STORAGE_VOL_WIPE_ALG_DOD:
    case VIR_STORAGE_VOL_WIPE_ALG_BSI:
    case VIR_STORAGE_VOL_WIPE_ALG_GUTMANN:
    case VIR_STORAGE_VOL_WIPE_ALG_SCHNEIER:
    case VIR_STORAGE_VOL_WIPE_ALG_PFITZNER7:
    case VIR_STORAGE_VOL_WIPE_ALG_PFITZNER33:
    case VIR_STORAGE_VOL_WIPE_ALG_RANDOM:
    case VIR_STORAGE_VOL_WIPE_ALG_LAST:
        virReportError(VIR_ERR_INVALID_ARG, _("unsupported algorithm %d"),
                       algorithm);
        goto cleanup;
    }

    if (r < 0) {
        virReportSystemError(-r, _("failed to wipe RBD image %s"),
                             vol->name);
        goto cleanup;
    }

    ret = 0;

 cleanup:
    if (image)
        rbd_close(image);

1516
    virStorageBackendRBDFreeState(&ptr);
1517 1518 1519 1520

    return ret;
}

1521

1522 1523 1524 1525 1526
virStorageBackend virStorageBackendRBD = {
    .type = VIR_STORAGE_POOL_RBD,

    .refreshPool = virStorageBackendRBDRefreshPool,
    .createVol = virStorageBackendRBDCreateVol,
1527
    .buildVol = virStorageBackendRBDBuildVol,
1528
    .buildVolFrom = virStorageBackendRBDBuildVolFrom,
1529 1530 1531
    .refreshVol = virStorageBackendRBDRefreshVol,
    .deleteVol = virStorageBackendRBDDeleteVol,
    .resizeVol = virStorageBackendRBDResizeVol,
1532
    .wipeVol = virStorageBackendRBDVolWipe
1533
};
1534 1535


1536
static virXMLNamespace virStoragePoolRBDXMLNamespace = {
1537 1538 1539
    .parse = virStoragePoolDefRBDNamespaceParse,
    .free = virStoragePoolDefRBDNamespaceFree,
    .format = virStoragePoolDefRBDNamespaceFormatXML,
1540
    .prefix = "rbd",
1541 1542 1543 1544
    .href = virStoragePoolDefRBDNamespaceHref,
};


1545 1546 1547
int
virStorageBackendRBDRegister(void)
{
1548 1549 1550 1551 1552
    if (virStorageBackendRegister(&virStorageBackendRBD) < 0)
        return -1;

    return virStorageBackendNamespaceInit(VIR_STORAGE_POOL_RBD,
                                          &virStoragePoolRBDXMLNamespace);
1553
}