qemu_block.c 31.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/*
 * qemu_block.c: helper functions for QEMU block subsystem
 *
 * 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, see
 * <http://www.gnu.org/licenses/>.
 */

#include <config.h>

#include "qemu_block.h"
#include "qemu_domain.h"
23
#include "qemu_alias.h"
24 25 26 27 28 29 30

#include "viralloc.h"
#include "virstring.h"

#define VIR_FROM_THIS VIR_FROM_QEMU


31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
static int
qemuBlockNamedNodesArrayToHash(size_t pos ATTRIBUTE_UNUSED,
                               virJSONValuePtr item,
                               void *opaque)
{
    virHashTablePtr table = opaque;
    const char *name;

    if (!(name = virJSONValueObjectGetString(item, "node-name")))
        return 1;

    if (virHashAddEntry(table, name, item) < 0)
        return -1;

    return 0;
}


49 50 51 52 53 54 55 56 57 58
static void
qemuBlockNodeNameBackingChainDataFree(qemuBlockNodeNameBackingChainDataPtr data)
{
    if (!data)
        return;

    VIR_FREE(data->nodeformat);
    VIR_FREE(data->nodestorage);

    VIR_FREE(data->qemufilename);
59

60 61 62
    VIR_FREE(data->drvformat);
    VIR_FREE(data->drvstorage);

63
    qemuBlockNodeNameBackingChainDataFree(data->backing);
64 65 66 67 68 69 70 71 72 73 74 75 76

    VIR_FREE(data);
}


static void
qemuBlockNodeNameBackingChainDataHashEntryFree(void *opaque,
                                               const void *name ATTRIBUTE_UNUSED)
{
    qemuBlockNodeNameBackingChainDataFree(opaque);
}


77 78 79 80
/* list of driver names of layers that qemu automatically adds into the
 * backing chain */
static const char *qemuBlockDriversBlockjob[] = {
    "mirror_top", "commit_top", NULL };
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

static bool
qemuBlockDriverMatch(const char *drvname,
                     const char **drivers)
{
    while (*drivers) {
        if (STREQ(drvname, *drivers))
            return true;

        drivers++;
    }

    return false;
}


97 98 99 100 101 102
struct qemuBlockNodeNameGetBackingChainData {
    virHashTablePtr nodenamestable;
    virHashTablePtr disks;
};


103
static int
104 105 106
qemuBlockNodeNameGetBackingChainBacking(virJSONValuePtr next,
                                        virHashTablePtr nodenamestable,
                                        qemuBlockNodeNameBackingChainDataPtr *nodenamedata)
107
{
108 109 110 111 112 113 114
    qemuBlockNodeNameBackingChainDataPtr data = NULL;
    qemuBlockNodeNameBackingChainDataPtr backingdata = NULL;
    virJSONValuePtr backing = virJSONValueObjectGetObject(next, "backing");
    virJSONValuePtr parent = virJSONValueObjectGetObject(next, "parent");
    virJSONValuePtr parentnodedata;
    virJSONValuePtr nodedata;
    const char *nodename = virJSONValueObjectGetString(next, "node-name");
115 116
    const char *drvname = NULL;
    const char *drvparent = NULL;
117 118 119
    const char *parentnodename = NULL;
    const char *filename = NULL;
    int ret = -1;
120

121
    if (!nodename)
122 123
        return 0;

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
    if ((nodedata = virHashLookup(nodenamestable, nodename)) &&
        (drvname = virJSONValueObjectGetString(nodedata, "drv"))) {

        /* qemu 2.9 reports layers in the backing chain which don't correspond
         * to files. skip them */
        if (qemuBlockDriverMatch(drvname, qemuBlockDriversBlockjob)) {
            if (backing) {
                return qemuBlockNodeNameGetBackingChainBacking(backing,
                                                               nodenamestable,
                                                               nodenamedata);
            } else {
                return 0;
            }
        }
    }
139

140 141
    if (parent &&
        (parentnodename = virJSONValueObjectGetString(parent, "node-name"))) {
142
        if ((parentnodedata = virHashLookup(nodenamestable, parentnodename))) {
143
            filename = virJSONValueObjectGetString(parentnodedata, "file");
144 145
            drvparent = virJSONValueObjectGetString(parentnodedata, "drv");
        }
146
    }
147

148 149
    if (VIR_ALLOC(data) < 0)
        goto cleanup;
150

151 152
    if (VIR_STRDUP(data->nodeformat, nodename) < 0 ||
        VIR_STRDUP(data->nodestorage, parentnodename) < 0 ||
153 154 155
        VIR_STRDUP(data->qemufilename, filename) < 0 ||
        VIR_STRDUP(data->drvformat, drvname) < 0 ||
        VIR_STRDUP(data->drvstorage, drvparent) < 0)
156
        goto cleanup;
157

158 159 160 161
    if (backing &&
        qemuBlockNodeNameGetBackingChainBacking(backing, nodenamestable,
                                                &backingdata) < 0)
        goto cleanup;
162

163 164
    VIR_STEAL_PTR(data->backing, backingdata);
    VIR_STEAL_PTR(*nodenamedata, data);
165

166 167 168 169 170
    ret = 0;

 cleanup:
    qemuBlockNodeNameBackingChainDataFree(data);
    return ret;
171 172 173 174
}


static int
175 176 177
qemuBlockNodeNameGetBackingChainDisk(size_t pos ATTRIBUTE_UNUSED,
                                     virJSONValuePtr item,
                                     void *opaque)
178
{
179 180 181 182
    struct qemuBlockNodeNameGetBackingChainData *data = opaque;
    const char *device = virJSONValueObjectGetString(item, "device");
    qemuBlockNodeNameBackingChainDataPtr devicedata = NULL;
    int ret = -1;
183

184 185 186
    if (qemuBlockNodeNameGetBackingChainBacking(item, data->nodenamestable,
                                                &devicedata) < 0)
        goto cleanup;
187

188 189 190
    if (devicedata &&
        virHashAddEntry(data->disks, device, devicedata) < 0)
        goto cleanup;
191

192 193
    devicedata = NULL;
    ret = 1; /* we don't really want to steal @item */
194

195 196
 cleanup:
    qemuBlockNodeNameBackingChainDataFree(devicedata);
197

198
    return ret;
199 200 201 202 203
}


/**
 * qemuBlockNodeNameGetBackingChain:
204 205
 * @namednodes: JSON array of data returned from 'query-named-block-nodes'
 * @blockstats: JSON array of data returned from 'query-blockstats'
206 207 208 209 210 211 212 213 214 215
 *
 * Tries to reconstruct the backing chain from @json to allow detection of
 * node names that were auto-assigned by qemu. This is a best-effort operation
 * and may not be successful. The returned hash table contains the entries as
 * qemuBlockNodeNameBackingChainDataPtr accessible by the node name. The fields
 * then can be used to recover the full backing chain.
 *
 * Returns a hash table on success and NULL on failure.
 */
virHashTablePtr
216 217
qemuBlockNodeNameGetBackingChain(virJSONValuePtr namednodes,
                                 virJSONValuePtr blockstats)
218 219
{
    struct qemuBlockNodeNameGetBackingChainData data;
220 221
    virHashTablePtr namednodestable = NULL;
    virHashTablePtr disks = NULL;
222 223 224 225
    virHashTablePtr ret = NULL;

    memset(&data, 0, sizeof(data));

226
    if (!(namednodestable = virHashCreate(50, virJSONValueHashFree)))
227 228
        goto cleanup;

229 230 231
    if (virJSONValueArrayForeachSteal(namednodes,
                                      qemuBlockNamedNodesArrayToHash,
                                      namednodestable) < 0)
232 233
        goto cleanup;

234
    if (!(disks = virHashCreate(50, qemuBlockNodeNameBackingChainDataHashEntryFree)))
235 236
        goto cleanup;

237 238
    data.nodenamestable = namednodestable;
    data.disks = disks;
239

240 241 242 243
    if (virJSONValueArrayForeachSteal(blockstats,
                                      qemuBlockNodeNameGetBackingChainDisk,
                                      &data) < 0)
        goto cleanup;
244

245
    VIR_STEAL_PTR(ret, disks);
246 247

 cleanup:
248 249
     virHashFree(namednodestable);
     virHashFree(disks);
250 251 252

     return ret;
}
253 254 255 256 257 258 259


static void
qemuBlockDiskClearDetectedNodes(virDomainDiskDefPtr disk)
{
    virStorageSourcePtr next = disk->src;

260
    while (virStorageSourceIsBacking(next)) {
261
        VIR_FREE(next->nodeformat);
262
        VIR_FREE(next->nodestorage);
263 264 265 266 267 268 269 270

        next = next->backingStore;
    }
}


static int
qemuBlockDiskDetectNodes(virDomainDiskDefPtr disk,
271
                         virHashTablePtr disktable)
272 273 274
{
    qemuBlockNodeNameBackingChainDataPtr entry = NULL;
    virStorageSourcePtr src = disk->src;
275 276
    char *alias = NULL;
    int ret = -1;
277

278 279 280
    /* don't attempt the detection if the top level already has node names */
    if (src->nodeformat || src->nodestorage)
        return 0;
281

282 283 284 285 286 287 288
    if (!(alias = qemuAliasFromDisk(disk)))
        goto cleanup;

    if (!(entry = virHashLookup(disktable, alias))) {
        ret = 0;
        goto cleanup;
    }
289

290
    while (virStorageSourceIsBacking(src) && entry) {
291
        if (src->nodeformat || src->nodestorage) {
292
            if (STRNEQ_NULLABLE(src->nodeformat, entry->nodeformat) ||
293
                STRNEQ_NULLABLE(src->nodestorage, entry->nodestorage))
294
                goto cleanup;
295 296 297 298

            break;
        } else {
            if (VIR_STRDUP(src->nodeformat, entry->nodeformat) < 0 ||
299
                VIR_STRDUP(src->nodestorage, entry->nodestorage) < 0)
300
                goto cleanup;
301 302
        }

303
        entry = entry->backing;
304 305 306
        src = src->backingStore;
    }

307
    ret = 0;
308

309 310 311 312 313 314
 cleanup:
    VIR_FREE(alias);
    if (ret < 0)
        qemuBlockDiskClearDetectedNodes(disk);

    return ret;
315 316 317 318 319
}


int
qemuBlockNodeNamesDetect(virQEMUDriverPtr driver,
320 321
                         virDomainObjPtr vm,
                         qemuDomainAsyncJob asyncJob)
322 323 324 325
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virHashTablePtr disktable = NULL;
    virJSONValuePtr data = NULL;
326
    virJSONValuePtr blockstats = NULL;
327 328 329 330 331 332 333
    virDomainDiskDefPtr disk;
    size_t i;
    int ret = -1;

    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_QUERY_NAMED_BLOCK_NODES))
        return 0;

334 335
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;
336 337

    data = qemuMonitorQueryNamedBlockNodes(qemuDomainGetMonitor(vm));
338
    blockstats = qemuMonitorQueryBlockstats(qemuDomainGetMonitor(vm));
339

340
    if (qemuDomainObjExitMonitor(driver, vm) < 0 || !data || !blockstats)
341 342
        goto cleanup;

343
    if (!(disktable = qemuBlockNodeNameGetBackingChain(data, blockstats)))
344 345 346 347 348
        goto cleanup;

    for (i = 0; i < vm->def->ndisks; i++) {
        disk = vm->def->disks[i];

349
        if (qemuBlockDiskDetectNodes(disk, disktable) < 0)
350 351 352 353 354 355 356
            goto cleanup;
    }

    ret = 0;

 cleanup:
    virJSONValueFree(data);
357
    virJSONValueFree(blockstats);
358 359 360 361
    virHashFree(disktable);

    return ret;
}
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380


/**
 * qemuBlockGetNodeData:
 * @data: JSON object returned from query-named-block-nodes
 *
 * Returns a hash table organized by the node name of the JSON value objects of
 * data for given qemu block nodes.
 *
 * Returns a filled virHashTablePtr on success NULL on error.
 */
virHashTablePtr
qemuBlockGetNodeData(virJSONValuePtr data)
{
    virHashTablePtr ret = NULL;

    if (!(ret = virHashCreate(50, virJSONValueHashFree)))
        return NULL;

381 382
    if (virJSONValueArrayForeachSteal(data,
                                      qemuBlockNamedNodesArrayToHash, ret) < 0)
383 384 385 386 387 388 389 390
        goto error;

    return ret;

 error:
    virHashFree(ret);
    return NULL;
}
391 392


393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
/**
 * qemuBlockStorageSourceSupportsConcurrentAccess:
 * @src: disk storage source
 *
 * Returns true if the given storage format supports concurrent access from two
 * separate processes.
 */
bool
qemuBlockStorageSourceSupportsConcurrentAccess(virStorageSourcePtr src)
{
    /* no need to check in backing chain since only RAW storage supports this */
    return src->format == VIR_STORAGE_FILE_RAW;
}


408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
/**
 * qemuBlockStorageSourceGetURI:
 * @src: disk storage source
 *
 * Formats a URI from a virStorageSource.
 */
virURIPtr
qemuBlockStorageSourceGetURI(virStorageSourcePtr src)
{
    virURIPtr uri = NULL;
    virURIPtr ret = NULL;

    if (src->nhosts != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("protocol '%s' accepts only one host"),
                       virStorageNetProtocolTypeToString(src->protocol));
        goto cleanup;
    }

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

    if (src->hosts->transport == VIR_STORAGE_NET_HOST_TRANS_TCP) {
        uri->port = src->hosts->port;

        if (VIR_STRDUP(uri->scheme,
                       virStorageNetProtocolTypeToString(src->protocol)) < 0)
            goto cleanup;
    } else {
        if (virAsprintf(&uri->scheme, "%s+%s",
                        virStorageNetProtocolTypeToString(src->protocol),
                        virStorageNetHostTransportTypeToString(src->hosts->transport)) < 0)
            goto cleanup;
    }

    if (src->path) {
        if (src->volume) {
445
            if (virAsprintf(&uri->path, "/%s/%s",
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
                            src->volume, src->path) < 0)
                goto cleanup;
        } else {
            if (virAsprintf(&uri->path, "%s%s",
                            src->path[0] == '/' ? "" : "/",
                            src->path) < 0)
                goto cleanup;
        }
    }

    if (VIR_STRDUP(uri->server, src->hosts->name) < 0)
        goto cleanup;

    VIR_STEAL_PTR(ret, uri);

 cleanup:
    virURIFree(uri);
    return ret;
}


467 468 469
/**
 * qemuBlockStorageSourceBuildJSONSocketAddress
 * @host: the virStorageNetHostDefPtr definition to build
470
 * @legacy: use old field names/values
471 472 473 474
 *
 * Formats @hosts into a json object conforming to the 'SocketAddress' type
 * in qemu.
 *
475 476 477
 * For compatibility with old approach used in the gluster driver of old qemus
 * use the old spelling for TCP transport and, the path field of the unix socket.
 *
478 479 480 481 482 483 484 485 486
 * Returns a virJSONValuePtr for a single server.
 */
static virJSONValuePtr
qemuBlockStorageSourceBuildJSONSocketAddress(virStorageNetHostDefPtr host,
                                             bool legacy)
{
    virJSONValuePtr server = NULL;
    virJSONValuePtr ret = NULL;
    const char *transport;
487
    const char *field;
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    char *port = NULL;

    switch ((virStorageNetHostTransport) host->transport) {
    case VIR_STORAGE_NET_HOST_TRANS_TCP:
        if (legacy)
            transport = "tcp";
        else
            transport = "inet";

        if (virAsprintf(&port, "%u", host->port) < 0)
            goto cleanup;

        if (virJSONValueObjectCreate(&server,
                                     "s:type", transport,
                                     "s:host", host->name,
                                     "s:port", port,
                                     NULL) < 0)
            goto cleanup;
        break;

    case VIR_STORAGE_NET_HOST_TRANS_UNIX:
509 510 511 512 513
        if (legacy)
            field = "s:socket";
        else
            field = "s:path";

514 515
        if (virJSONValueObjectCreate(&server,
                                     "s:type", "unix",
516
                                     field, host->socket,
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
                                     NULL) < 0)
            goto cleanup;
        break;

    case VIR_STORAGE_NET_HOST_TRANS_RDMA:
    case VIR_STORAGE_NET_HOST_TRANS_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("transport protocol '%s' is not yet supported"),
                       virStorageNetHostTransportTypeToString(host->transport));
        goto cleanup;
    }

    VIR_STEAL_PTR(ret, server);

 cleanup:
    VIR_FREE(port);
    virJSONValueFree(server);

    return ret;
}


539 540 541 542 543 544 545 546
/**
 * qemuBlockStorageSourceBuildHostsJSONSocketAddress:
 * @src: disk storage source
 * @legacy: use 'tcp' instead of 'inet' for compatibility reasons
 *
 * Formats src->hosts into a json object conforming to the 'SocketAddress' type
 * in qemu.
 */
547
static virJSONValuePtr
548 549
qemuBlockStorageSourceBuildHostsJSONSocketAddress(virStorageSourcePtr src,
                                                  bool legacy)
550 551 552 553 554 555 556 557 558 559 560 561 562
{
    virJSONValuePtr servers = NULL;
    virJSONValuePtr server = NULL;
    virJSONValuePtr ret = NULL;
    virStorageNetHostDefPtr host;
    size_t i;

    if (!(servers = virJSONValueNewArray()))
        goto cleanup;

    for (i = 0; i < src->nhosts; i++) {
        host = src->hosts + i;

563 564
        if (!(server = qemuBlockStorageSourceBuildJSONSocketAddress(host, legacy)))
              goto cleanup;
565 566 567 568 569 570 571

        if (virJSONValueArrayAppend(servers, server) < 0)
            goto cleanup;

        server = NULL;
    }

572
    VIR_STEAL_PTR(ret, servers);
573 574 575 576 577 578 579 580 581

 cleanup:
    virJSONValueFree(servers);
    virJSONValueFree(server);

    return ret;
}


582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
/**
 * qemuBlockStorageSourceBuildJSONInetSocketAddress
 * @host: the virStorageNetHostDefPtr definition to build
 *
 * Formats @hosts into a json object conforming to the 'InetSocketAddress' type
 * in qemu.
 *
 * Returns a virJSONValuePtr for a single server.
 */
static virJSONValuePtr
qemuBlockStorageSourceBuildJSONInetSocketAddress(virStorageNetHostDefPtr host)
{
    virJSONValuePtr ret = NULL;
    char *port = NULL;

    if (host->transport != VIR_STORAGE_NET_HOST_TRANS_TCP) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("only TCP protocol can be converted to InetSocketAddress"));
        return NULL;
    }

    if (virAsprintf(&port, "%u", host->port) < 0)
        return NULL;

    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:host", host->name,
                                          "s:port", port,
                                          NULL));

    VIR_FREE(port);
    return ret;
}


616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
/**
 * qemuBlockStorageSourceBuildHostsJSONInetSocketAddress:
 * @src: disk storage source
 *
 * Formats src->hosts into a json object conforming to the 'InetSocketAddress'
 * type in qemu.
 */
static virJSONValuePtr
qemuBlockStorageSourceBuildHostsJSONInetSocketAddress(virStorageSourcePtr src)
{
    virJSONValuePtr servers = NULL;
    virJSONValuePtr server = NULL;
    virJSONValuePtr ret = NULL;
    virStorageNetHostDefPtr host;
    size_t i;

    if (!(servers = virJSONValueNewArray()))
        goto cleanup;

    for (i = 0; i < src->nhosts; i++) {
        host = src->hosts + i;

        if (!(server = qemuBlockStorageSourceBuildJSONInetSocketAddress(host)))
            goto cleanup;

        if (virJSONValueArrayAppend(servers, server) < 0)
            goto cleanup;

        server = NULL;
    }

    VIR_STEAL_PTR(ret, servers);

 cleanup:
    virJSONValueFree(servers);
    virJSONValueFree(server);

    return ret;
}


657
static virJSONValuePtr
658
qemuBlockStorageSourceGetGlusterProps(virStorageSourcePtr src)
659 660
{
    virJSONValuePtr servers = NULL;
661
    virJSONValuePtr props = NULL;
662 663
    virJSONValuePtr ret = NULL;

664
    if (!(servers = qemuBlockStorageSourceBuildHostsJSONSocketAddress(src, true)))
665 666 667 668 669 670 671 672
        return NULL;

     /* { driver:"gluster",
      *   volume:"testvol",
      *   path:"/a.img",
      *   server :[{type:"tcp", host:"1.2.3.4", port:24007},
      *            {type:"unix", socket:"/tmp/glusterd.socket"}, ...]}
      */
673
    if (virJSONValueObjectCreate(&props,
674
                                 "s:driver", "gluster",
675 676
                                 "s:volume", src->volume,
                                 "s:path", src->path,
677
                                 "a:server", &servers, NULL) < 0)
678 679 680 681 682 683 684 685 686 687 688
        goto cleanup;

    if (src->debug &&
        virJSONValueObjectAdd(props, "u:debug", src->debugLevel, NULL) < 0)
        goto cleanup;

    VIR_STEAL_PTR(ret, props);

 cleanup:
    virJSONValueFree(servers);
    virJSONValueFree(props);
689 690 691 692 693

    return ret;
}


694 695 696 697 698 699 700 701 702 703 704 705 706
static virJSONValuePtr
qemuBlockStorageSourceGetVxHSProps(virStorageSourcePtr src)
{
    const char *protocol = virStorageNetProtocolTypeToString(src->protocol);
    virJSONValuePtr server = NULL;
    virJSONValuePtr ret = NULL;

    if (src->nhosts != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("VxHS protocol accepts only one host"));
        return NULL;
    }

707
    if (!(server = qemuBlockStorageSourceBuildJSONInetSocketAddress(&src->hosts[0])))
708 709 710 711
        return NULL;

    /* VxHS disk specification example:
     * { driver:"vxhs",
712
     *   tls-creds:"objvirtio-disk0_tls0",
713 714 715 716 717
     *   vdisk-id:"eb90327c-8302-4725-4e85ed4dc251",
     *   server:{type:"tcp", host:"1.2.3.4", port:9999}}
     */
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", protocol,
718
                                 "S:tls-creds", src->tlsAlias,
719
                                 "s:vdisk-id", src->path,
720
                                 "a:server", &server, NULL) < 0)
721 722 723 724 725 726
        virJSONValueFree(server);

    return ret;
}


727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777
static virJSONValuePtr
qemuBlockStorageSourceGetCURLProps(virStorageSourcePtr src)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *passwordalias = NULL;
    const char *username = NULL;
    virJSONValuePtr ret = NULL;
    virURIPtr uri = NULL;
    char *uristr = NULL;
    const char *driver;

    /**
     * Common options:
     * url, readahead, timeout, username, password-secret, proxy-username,
     * proxy-password-secret
     *
     * Options for http transport:
     * cookie, cookie-secret
     *
     * Options for secure transport (ftps, https):
     * sslverify
     */

    driver = virStorageNetProtocolTypeToString(src->protocol);

    if (!(uri = qemuBlockStorageSourceGetURI(src)))
        goto cleanup;

    if (!(uristr = virURIFormat(uri)))
        goto cleanup;

    if (src->auth) {
        username = src->auth->username;
        passwordalias = srcPriv->secinfo->s.aes.alias;
    }

    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:driver", driver,
                                          "s:url", uristr,
                                          "S:username", username,
                                          "S:password-secret", passwordalias,
                                          NULL));

 cleanup:
    virURIFree(uri);
    VIR_FREE(uristr);

    return ret;
}


778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
static virJSONValuePtr
qemuBlockStorageSourceGetISCSIProps(virStorageSourcePtr src)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *protocol = virStorageNetProtocolTypeToString(src->protocol);
    char *target = NULL;
    char *lunStr = NULL;
    char *username = NULL;
    char *objalias = NULL;
    char *portal = NULL;
    unsigned int lun = 0;
    virJSONValuePtr ret = NULL;

    /* { driver:"iscsi",
     *   transport:"tcp",  ("iser" also possible)
     *   portal:"example.com",
     *   target:"iqn.2017-04.com.example:iscsi-disks",
     *   lun:1,
     *   user:"username",
     *   password-secret:"secret-alias",
     * }
     */

    if (VIR_STRDUP(target, src->path) < 0)
        goto cleanup;

    /* Separate the target and lun */
    if ((lunStr = strchr(target, '/'))) {
        *(lunStr++) = '\0';
        if (virStrToLong_ui(lunStr, NULL, 10, &lun) < 0) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("cannot parse target for lunStr '%s'"),
                           target);
            goto cleanup;
        }
    }

    /* combine host and port into portal */
    if (virSocketAddrNumericFamily(src->hosts[0].name) == AF_INET6) {
        if (virAsprintf(&portal, "[%s]:%u",
                        src->hosts[0].name, src->hosts[0].port) < 0)
            goto cleanup;
    } else {
        if (virAsprintf(&portal, "%s:%u",
                        src->hosts[0].name, src->hosts[0].port) < 0)
            goto cleanup;
    }

    if (src->auth) {
        username = src->auth->username;
        objalias = srcPriv->secinfo->s.aes.alias;
    }

    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:driver", protocol,
                                          "s:portal", portal,
                                          "s:target", target,
                                          "u:lun", lun,
                                          "s:transport", "tcp",
                                          "S:user", username,
                                          "S:password-secret", objalias,
                                          NULL));
        goto cleanup;

 cleanup:
    VIR_FREE(target);
    VIR_FREE(portal);
    return ret;
}


849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
static virJSONValuePtr
qemuBlockStorageSourceGetNBDProps(virStorageSourcePtr src)
{
    virJSONValuePtr serverprops;
    virJSONValuePtr ret = NULL;

    if (src->nhosts != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("nbd protocol accepts only one host"));
        return NULL;
    }

    serverprops = qemuBlockStorageSourceBuildJSONSocketAddress(&src->hosts[0],
                                                               false);
    if (!serverprops)
        return NULL;

866 867
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "nbd",
868
                                 "a:server", &serverprops,
869 870 871 872 873 874 875
                                 "S:export", src->path,
                                 "S:tls-creds", src->tlsAlias,
                                 NULL) < 0)
        goto cleanup;

 cleanup:
    virJSONValueFree(serverprops);
876 877 878 879
    return ret;
}


880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
static virJSONValuePtr
qemuBlockStorageSourceGetRBDProps(virStorageSourcePtr src)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    virJSONValuePtr servers = NULL;
    virJSONValuePtr ret = NULL;
    const char *username = NULL;

    if (src->nhosts > 0 &&
        !(servers = qemuBlockStorageSourceBuildHostsJSONInetSocketAddress(src)))
        return NULL;

    if (src->auth)
        username = srcPriv->secinfo->s.aes.username;

895 896 897 898 899 900
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "rbd",
                                 "s:pool", src->volume,
                                 "s:image", src->path,
                                 "S:snapshot", src->snapshot,
                                 "S:conf", src->configFile,
901
                                 "A:server", &servers,
902 903 904
                                 "S:user", username,
                                 NULL) < 0)
        goto cleanup;
905

906 907
 cleanup:
    virJSONValueFree(servers);
908 909 910 911
    return ret;
}


912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
static virJSONValuePtr
qemuBlockStorageSourceGetSheepdogProps(virStorageSourcePtr src)
{
    virJSONValuePtr serverprops;
    virJSONValuePtr ret = NULL;

    if (src->nhosts != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("sheepdog protocol accepts only one host"));
        return NULL;
    }

    serverprops = qemuBlockStorageSourceBuildJSONSocketAddress(&src->hosts[0],
                                                               false);
    if (!serverprops)
        return NULL;

    /* libvirt does not support the 'snap-id' and 'tag' properties */
930 931
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "sheepdog",
932
                                 "a:server", &serverprops,
933 934 935
                                 "s:vdi", src->path,
                                 NULL) < 0)
        goto cleanup;
936

937 938
 cleanup:
    virJSONValueFree(serverprops);
939 940 941
    return ret;
}

942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962

static virJSONValuePtr
qemuBlockStorageSourceGetSshProps(virStorageSourcePtr src)
{
    virJSONValuePtr serverprops;
    virJSONValuePtr ret = NULL;
    const char *username = NULL;

    if (src->nhosts != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("sheepdog protocol accepts only one host"));
        return NULL;
    }

    serverprops = qemuBlockStorageSourceBuildJSONInetSocketAddress(&src->hosts[0]);
    if (!serverprops)
        return NULL;

    if (src->auth)
        username = src->auth->username;

963 964 965
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "ssh",
                                 "s:path", src->path,
966
                                 "a:server", &serverprops,
967 968 969 970 971 972
                                 "S:user", username,
                                 NULL) < 0)
        goto cleanup;

 cleanup:
    virJSONValueFree(serverprops);
973 974 975 976
    return ret;
}


977 978 979
static virJSONValuePtr
qemuBlockStorageSourceGetFileProps(virStorageSourcePtr src)
{
980
    const char *iomode = NULL;
981 982
    virJSONValuePtr ret = NULL;

983 984 985
    if (src->iomode != VIR_DOMAIN_DISK_IO_DEFAULT)
        iomode = virDomainDiskIoTypeToString(src->iomode);

986 987
    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:driver", "file",
988 989 990
                                          "s:filename", src->path,
                                          "S:aio", iomode,
                                          NULL) < 0);
991 992 993 994
    return ret;
}


995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
static virJSONValuePtr
qemuBlockStorageSourceGetVvfatProps(virStorageSourcePtr src)
{
    virJSONValuePtr ret = NULL;

    /* libvirt currently does not handle the following attributes:
     * '*fat-type': 'int'
     * '*label': 'str'
     */
    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:driver", "vvfat",
                                          "s:dir", src->path,
                                          "b:floppy", src->floppyimg,
                                          "b:rw", !src->readonly, NULL));

    return ret;
}


1014 1015 1016 1017 1018 1019 1020 1021 1022
/**
 * qemuBlockStorageSourceGetBackendProps:
 * @src: disk source
 *
 * Creates a JSON object describing the underlying storage or protocol of a
 * storage source. Returns NULL on error and reports an appropriate error message.
 */
virJSONValuePtr
qemuBlockStorageSourceGetBackendProps(virStorageSourcePtr src)
1023 1024 1025 1026
{
    int actualType = virStorageSourceGetActualType(src);
    virJSONValuePtr fileprops = NULL;

1027
    switch ((virStorageType)actualType) {
1028 1029
    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_FILE:
1030
        if (!(fileprops = qemuBlockStorageSourceGetFileProps(src)))
1031 1032
            return NULL;
        break;
1033 1034 1035 1036 1037 1038 1039

    case VIR_STORAGE_TYPE_DIR:
        /* qemu handles directories by exposing them as a device with emulated
         * FAT filesystem */
        if (!(fileprops = qemuBlockStorageSourceGetVvfatProps(src)))
            return NULL;
        break;
1040

1041 1042 1043
    case VIR_STORAGE_TYPE_VOLUME:
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
1044
        return NULL;
1045 1046

    case VIR_STORAGE_TYPE_NETWORK:
1047 1048
        switch ((virStorageNetProtocol) src->protocol) {
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
1049
            if (!(fileprops = qemuBlockStorageSourceGetGlusterProps(src)))
1050
                return NULL;
1051 1052
            break;

1053 1054
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
            if (!(fileprops = qemuBlockStorageSourceGetVxHSProps(src)))
1055
                return NULL;
1056 1057
            break;

1058 1059 1060 1061 1062
        case VIR_STORAGE_NET_PROTOCOL_HTTP:
        case VIR_STORAGE_NET_PROTOCOL_HTTPS:
        case VIR_STORAGE_NET_PROTOCOL_FTP:
        case VIR_STORAGE_NET_PROTOCOL_FTPS:
        case VIR_STORAGE_NET_PROTOCOL_TFTP:
1063 1064 1065 1066
            if (!(fileprops = qemuBlockStorageSourceGetCURLProps(src)))
                return NULL;
            break;

1067 1068 1069 1070 1071
        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
            if (!(fileprops = qemuBlockStorageSourceGetISCSIProps(src)))
                return NULL;
            break;

1072
        case VIR_STORAGE_NET_PROTOCOL_NBD:
1073 1074 1075 1076
            if (!(fileprops = qemuBlockStorageSourceGetNBDProps(src)))
                return NULL;
            break;

1077
        case VIR_STORAGE_NET_PROTOCOL_RBD:
1078 1079 1080 1081
            if (!(fileprops = qemuBlockStorageSourceGetRBDProps(src)))
                return NULL;
            break;

1082
        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
1083 1084 1085 1086
            if (!(fileprops = qemuBlockStorageSourceGetSheepdogProps(src)))
                return NULL;
            break;

1087
        case VIR_STORAGE_NET_PROTOCOL_SSH:
1088 1089 1090 1091
            if (!(fileprops = qemuBlockStorageSourceGetSshProps(src)))
                return NULL;
            break;

1092 1093
        case VIR_STORAGE_NET_PROTOCOL_NONE:
        case VIR_STORAGE_NET_PROTOCOL_LAST:
1094
            return NULL;
1095 1096 1097 1098
        }
        break;
    }

1099 1100 1101 1102 1103
    if (virJSONValueObjectAdd(fileprops, "S:node-name", src->nodestorage, NULL) < 0) {
        virJSONValueFree(fileprops);
        return NULL;
    }

1104
    return fileprops;
1105
}