qemu_block.c 53.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * 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"
22
#include "qemu_command.h"
23
#include "qemu_domain.h"
24
#include "qemu_alias.h"
25
#include "qemu_monitor_json.h"
26 27 28

#include "viralloc.h"
#include "virstring.h"
29
#include "virlog.h"
30 31 32

#define VIR_FROM_THIS VIR_FROM_QEMU

33 34
VIR_LOG_INIT("qemu.qemu_block");

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/* qemu declares the buffer for node names as a 32 byte array */
static const size_t qemuBlockNodeNameBufSize = 32;

static int
qemuBlockNodeNameValidate(const char *nn)
{
    if (!nn)
        return 0;

    if (strlen(nn) >= qemuBlockNodeNameBufSize) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("node-name '%s' too long for qemu"), nn);
        return -1;
    }

    return 0;
}

53

54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
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;
}


72 73 74 75 76 77 78 79 80 81
static void
qemuBlockNodeNameBackingChainDataFree(qemuBlockNodeNameBackingChainDataPtr data)
{
    if (!data)
        return;

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

    VIR_FREE(data->qemufilename);
82

83 84 85
    VIR_FREE(data->drvformat);
    VIR_FREE(data->drvstorage);

86
    qemuBlockNodeNameBackingChainDataFree(data->backing);
87 88 89 90

    VIR_FREE(data);
}

91 92 93
VIR_DEFINE_AUTOPTR_FUNC(qemuBlockNodeNameBackingChainData,
                        qemuBlockNodeNameBackingChainDataFree);

94 95 96 97 98 99 100 101 102

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


103 104 105 106
/* list of driver names of layers that qemu automatically adds into the
 * backing chain */
static const char *qemuBlockDriversBlockjob[] = {
    "mirror_top", "commit_top", NULL };
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122

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

        drivers++;
    }

    return false;
}


123 124 125 126 127 128
struct qemuBlockNodeNameGetBackingChainData {
    virHashTablePtr nodenamestable;
    virHashTablePtr disks;
};


129
static int
130 131 132
qemuBlockNodeNameGetBackingChainBacking(virJSONValuePtr next,
                                        virHashTablePtr nodenamestable,
                                        qemuBlockNodeNameBackingChainDataPtr *nodenamedata)
133
{
134
    VIR_AUTOPTR(qemuBlockNodeNameBackingChainData) data = NULL;
135 136 137 138 139 140
    qemuBlockNodeNameBackingChainDataPtr backingdata = NULL;
    virJSONValuePtr backing = virJSONValueObjectGetObject(next, "backing");
    virJSONValuePtr parent = virJSONValueObjectGetObject(next, "parent");
    virJSONValuePtr parentnodedata;
    virJSONValuePtr nodedata;
    const char *nodename = virJSONValueObjectGetString(next, "node-name");
141 142
    const char *drvname = NULL;
    const char *drvparent = NULL;
143 144
    const char *parentnodename = NULL;
    const char *filename = NULL;
145

146
    if (!nodename)
147 148
        return 0;

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
    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;
            }
        }
    }
164

165 166
    if (parent &&
        (parentnodename = virJSONValueObjectGetString(parent, "node-name"))) {
167
        if ((parentnodedata = virHashLookup(nodenamestable, parentnodename))) {
168
            filename = virJSONValueObjectGetString(parentnodedata, "file");
169 170
            drvparent = virJSONValueObjectGetString(parentnodedata, "drv");
        }
171
    }
172

173
    if (VIR_ALLOC(data) < 0)
174
        return -1;
175

176 177
    if (VIR_STRDUP(data->nodeformat, nodename) < 0 ||
        VIR_STRDUP(data->nodestorage, parentnodename) < 0 ||
178 179 180
        VIR_STRDUP(data->qemufilename, filename) < 0 ||
        VIR_STRDUP(data->drvformat, drvname) < 0 ||
        VIR_STRDUP(data->drvstorage, drvparent) < 0)
181
        return -1;
182

183 184 185
    if (backing &&
        qemuBlockNodeNameGetBackingChainBacking(backing, nodenamestable,
                                                &backingdata) < 0)
186
        return -1;
187

188 189
    VIR_STEAL_PTR(data->backing, backingdata);
    VIR_STEAL_PTR(*nodenamedata, data);
190

191
    return 0;
192 193 194 195
}


static int
196 197 198
qemuBlockNodeNameGetBackingChainDisk(size_t pos ATTRIBUTE_UNUSED,
                                     virJSONValuePtr item,
                                     void *opaque)
199
{
200 201
    struct qemuBlockNodeNameGetBackingChainData *data = opaque;
    const char *device = virJSONValueObjectGetString(item, "device");
202
    VIR_AUTOPTR(qemuBlockNodeNameBackingChainData) devicedata = NULL;
203

204 205
    if (qemuBlockNodeNameGetBackingChainBacking(item, data->nodenamestable,
                                                &devicedata) < 0)
206
        return -1;
207

208 209
    if (devicedata &&
        virHashAddEntry(data->disks, device, devicedata) < 0)
210
        return -1;
211

212
    devicedata = NULL;
213
    return 1; /* we don't really want to steal @item */
214 215 216 217 218
}


/**
 * qemuBlockNodeNameGetBackingChain:
219 220
 * @namednodes: JSON array of data returned from 'query-named-block-nodes'
 * @blockstats: JSON array of data returned from 'query-blockstats'
221 222 223 224 225 226 227 228 229 230
 *
 * 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
231 232
qemuBlockNodeNameGetBackingChain(virJSONValuePtr namednodes,
                                 virJSONValuePtr blockstats)
233 234
{
    struct qemuBlockNodeNameGetBackingChainData data;
235 236
    VIR_AUTOPTR(virHashTable) namednodestable = NULL;
    VIR_AUTOPTR(virHashTable) disks = NULL;
237 238 239

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

240
    if (!(namednodestable = virHashCreate(50, virJSONValueHashFree)))
241
        return NULL;
242

243 244 245
    if (virJSONValueArrayForeachSteal(namednodes,
                                      qemuBlockNamedNodesArrayToHash,
                                      namednodestable) < 0)
246
        return NULL;
247

248
    if (!(disks = virHashCreate(50, qemuBlockNodeNameBackingChainDataHashEntryFree)))
249
        return NULL;
250

251 252
    data.nodenamestable = namednodestable;
    data.disks = disks;
253

254 255 256
    if (virJSONValueArrayForeachSteal(blockstats,
                                      qemuBlockNodeNameGetBackingChainDisk,
                                      &data) < 0)
257
        return NULL;
258

P
Peter Krempa 已提交
259
    VIR_RETURN_PTR(disks);
260
}
261 262 263 264 265 266 267


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

268
    while (virStorageSourceIsBacking(next)) {
269
        VIR_FREE(next->nodeformat);
270
        VIR_FREE(next->nodestorage);
271 272 273 274 275 276 277 278

        next = next->backingStore;
    }
}


static int
qemuBlockDiskDetectNodes(virDomainDiskDefPtr disk,
279
                         virHashTablePtr disktable)
280 281 282
{
    qemuBlockNodeNameBackingChainDataPtr entry = NULL;
    virStorageSourcePtr src = disk->src;
283
    VIR_AUTOFREE(char *) alias = NULL;
284
    int ret = -1;
285

286 287 288
    /* don't attempt the detection if the top level already has node names */
    if (src->nodeformat || src->nodestorage)
        return 0;
289

290
    if (!(alias = qemuAliasDiskDriveFromDisk(disk)))
291 292 293 294 295 296
        goto cleanup;

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

298
    while (virStorageSourceIsBacking(src) && entry) {
299
        if (src->nodeformat || src->nodestorage) {
300
            if (STRNEQ_NULLABLE(src->nodeformat, entry->nodeformat) ||
301
                STRNEQ_NULLABLE(src->nodestorage, entry->nodestorage))
302
                goto cleanup;
303 304 305 306

            break;
        } else {
            if (VIR_STRDUP(src->nodeformat, entry->nodeformat) < 0 ||
307
                VIR_STRDUP(src->nodestorage, entry->nodestorage) < 0)
308
                goto cleanup;
309 310
        }

311
        entry = entry->backing;
312 313 314
        src = src->backingStore;
    }

315
    ret = 0;
316

317 318 319 320 321
 cleanup:
    if (ret < 0)
        qemuBlockDiskClearDetectedNodes(disk);

    return ret;
322 323 324 325 326
}


int
qemuBlockNodeNamesDetect(virQEMUDriverPtr driver,
327 328
                         virDomainObjPtr vm,
                         qemuDomainAsyncJob asyncJob)
329 330
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
331
    VIR_AUTOPTR(virHashTable) disktable = NULL;
332 333
    VIR_AUTOPTR(virJSONValue) data = NULL;
    VIR_AUTOPTR(virJSONValue) blockstats = NULL;
334 335 336 337 338 339
    virDomainDiskDefPtr disk;
    size_t i;

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

340 341
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;
342 343

    data = qemuMonitorQueryNamedBlockNodes(qemuDomainGetMonitor(vm));
344
    blockstats = qemuMonitorQueryBlockstats(qemuDomainGetMonitor(vm));
345

346
    if (qemuDomainObjExitMonitor(driver, vm) < 0 || !data || !blockstats)
347
        return -1;
348

349
    if (!(disktable = qemuBlockNodeNameGetBackingChain(data, blockstats)))
350
        return -1;
351 352 353 354

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

355
        if (qemuBlockDiskDetectNodes(disk, disktable) < 0)
356
            return -1;
357 358
    }

359
    return 0;
360
}
361 362 363 364 365 366 367 368 369 370 371 372 373 374


/**
 * 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)
{
375
    VIR_AUTOPTR(virHashTable) nodedata = NULL;
376

377
    if (!(nodedata = virHashCreate(50, virJSONValueHashFree)))
378 379
        return NULL;

380
    if (virJSONValueArrayForeachSteal(data,
381
                                      qemuBlockNamedNodesArrayToHash, nodedata) < 0)
382
        return NULL;
383

P
Peter Krempa 已提交
384
    VIR_RETURN_PTR(nodedata);
385
}
386 387


388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
/**
 * 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;
}


403 404 405 406 407 408 409 410 411
/**
 * qemuBlockStorageSourceGetURI:
 * @src: disk storage source
 *
 * Formats a URI from a virStorageSource.
 */
virURIPtr
qemuBlockStorageSourceGetURI(virStorageSourcePtr src)
{
412
    VIR_AUTOPTR(virURI) uri = NULL;
413 414 415 416 417

    if (src->nhosts != 1) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("protocol '%s' accepts only one host"),
                       virStorageNetProtocolTypeToString(src->protocol));
418
        return NULL;
419 420 421
    }

    if (VIR_ALLOC(uri) < 0)
422
        return NULL;
423 424 425 426 427 428

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

        if (VIR_STRDUP(uri->scheme,
                       virStorageNetProtocolTypeToString(src->protocol)) < 0)
429
            return NULL;
430 431 432 433
    } else {
        if (virAsprintf(&uri->scheme, "%s+%s",
                        virStorageNetProtocolTypeToString(src->protocol),
                        virStorageNetHostTransportTypeToString(src->hosts->transport)) < 0)
434
            return NULL;
435 436 437 438
    }

    if (src->path) {
        if (src->volume) {
439
            if (virAsprintf(&uri->path, "/%s/%s",
440
                            src->volume, src->path) < 0)
441
                return NULL;
442 443 444 445
        } else {
            if (virAsprintf(&uri->path, "%s%s",
                            src->path[0] == '/' ? "" : "/",
                            src->path) < 0)
446
                return NULL;
447 448 449 450
        }
    }

    if (VIR_STRDUP(uri->server, src->hosts->name) < 0)
451
        return NULL;
452

P
Peter Krempa 已提交
453
    VIR_RETURN_PTR(uri);
454 455 456
}


457 458 459
/**
 * qemuBlockStorageSourceBuildJSONSocketAddress
 * @host: the virStorageNetHostDefPtr definition to build
460
 * @legacy: use old field names/values
461 462 463 464
 *
 * Formats @hosts into a json object conforming to the 'SocketAddress' type
 * in qemu.
 *
465 466 467
 * 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.
 *
468 469 470 471 472 473
 * Returns a virJSONValuePtr for a single server.
 */
static virJSONValuePtr
qemuBlockStorageSourceBuildJSONSocketAddress(virStorageNetHostDefPtr host,
                                             bool legacy)
{
474
    VIR_AUTOPTR(virJSONValue) server = NULL;
475
    const char *transport;
476
    const char *field;
477
    VIR_AUTOFREE(char *) port = NULL;
478 479 480 481 482 483 484 485 486

    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)
487
            return NULL;
488 489 490 491 492 493

        if (virJSONValueObjectCreate(&server,
                                     "s:type", transport,
                                     "s:host", host->name,
                                     "s:port", port,
                                     NULL) < 0)
494
            return NULL;
495 496 497
        break;

    case VIR_STORAGE_NET_HOST_TRANS_UNIX:
498 499 500 501 502
        if (legacy)
            field = "s:socket";
        else
            field = "s:path";

503 504
        if (virJSONValueObjectCreate(&server,
                                     "s:type", "unix",
505
                                     field, host->socket,
506
                                     NULL) < 0)
507
            return NULL;
508 509 510 511 512 513 514
        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));
515
        return NULL;
516 517
    }

P
Peter Krempa 已提交
518
    VIR_RETURN_PTR(server);
519 520 521
}


522 523 524 525 526 527 528 529
/**
 * 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.
 */
530
static virJSONValuePtr
531 532
qemuBlockStorageSourceBuildHostsJSONSocketAddress(virStorageSourcePtr src,
                                                  bool legacy)
533
{
534 535
    VIR_AUTOPTR(virJSONValue) servers = NULL;
    VIR_AUTOPTR(virJSONValue) server = NULL;
536 537 538 539
    virStorageNetHostDefPtr host;
    size_t i;

    if (!(servers = virJSONValueNewArray()))
540
        return NULL;
541 542 543 544

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

545
        if (!(server = qemuBlockStorageSourceBuildJSONSocketAddress(host, legacy)))
546
              return NULL;
547 548

        if (virJSONValueArrayAppend(servers, server) < 0)
549
            return NULL;
550 551 552 553

        server = NULL;
    }

P
Peter Krempa 已提交
554
    VIR_RETURN_PTR(servers);
555 556 557
}


558 559 560 561 562 563 564 565 566 567 568 569 570
/**
 * 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;
571
    VIR_AUTOFREE(char *) port = NULL;
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

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

    return ret;
}


591 592 593 594 595 596 597 598 599 600
/**
 * qemuBlockStorageSourceBuildHostsJSONInetSocketAddress:
 * @src: disk storage source
 *
 * Formats src->hosts into a json object conforming to the 'InetSocketAddress'
 * type in qemu.
 */
static virJSONValuePtr
qemuBlockStorageSourceBuildHostsJSONInetSocketAddress(virStorageSourcePtr src)
{
601 602
    VIR_AUTOPTR(virJSONValue) servers = NULL;
    VIR_AUTOPTR(virJSONValue) server = NULL;
603 604 605 606
    virStorageNetHostDefPtr host;
    size_t i;

    if (!(servers = virJSONValueNewArray()))
607
        return NULL;
608 609 610 611 612

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

        if (!(server = qemuBlockStorageSourceBuildJSONInetSocketAddress(host)))
613
            return NULL;
614 615

        if (virJSONValueArrayAppend(servers, server) < 0)
616
            return NULL;
617 618 619 620

        server = NULL;
    }

P
Peter Krempa 已提交
621
    VIR_RETURN_PTR(servers);
622 623 624
}


625
static virJSONValuePtr
626 627
qemuBlockStorageSourceGetGlusterProps(virStorageSourcePtr src,
                                      bool legacy)
628
{
629 630
    VIR_AUTOPTR(virJSONValue) servers = NULL;
    VIR_AUTOPTR(virJSONValue) props = NULL;
631

632
    if (!(servers = qemuBlockStorageSourceBuildHostsJSONSocketAddress(src, legacy)))
633 634 635 636 637 638 639 640
        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"}, ...]}
      */
641
    if (virJSONValueObjectCreate(&props,
642
                                 "s:driver", "gluster",
643 644
                                 "s:volume", src->volume,
                                 "s:path", src->path,
645
                                 "a:server", &servers, NULL) < 0)
646
        return NULL;
647 648 649

    if (src->debug &&
        virJSONValueObjectAdd(props, "u:debug", src->debugLevel, NULL) < 0)
650
        return NULL;
651

P
Peter Krempa 已提交
652
    VIR_RETURN_PTR(props);
653 654 655
}


656 657 658 659
static virJSONValuePtr
qemuBlockStorageSourceGetVxHSProps(virStorageSourcePtr src)
{
    const char *protocol = virStorageNetProtocolTypeToString(src->protocol);
660
    VIR_AUTOPTR(virJSONValue) server = NULL;
661 662 663 664 665 666 667 668
    virJSONValuePtr ret = NULL;

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

669
    if (!(server = qemuBlockStorageSourceBuildJSONInetSocketAddress(&src->hosts[0])))
670 671 672 673
        return NULL;

    /* VxHS disk specification example:
     * { driver:"vxhs",
674
     *   tls-creds:"objvirtio-disk0_tls0",
675 676 677
     *   vdisk-id:"eb90327c-8302-4725-4e85ed4dc251",
     *   server:{type:"tcp", host:"1.2.3.4", port:9999}}
     */
678 679 680 681 682
    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:driver", protocol,
                                          "S:tls-creds", src->tlsAlias,
                                          "s:vdisk-id", src->path,
                                          "a:server", &server, NULL));
683 684 685 686 687

    return ret;
}


688 689 690 691 692 693 694
static virJSONValuePtr
qemuBlockStorageSourceGetCURLProps(virStorageSourcePtr src)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *passwordalias = NULL;
    const char *username = NULL;
    virJSONValuePtr ret = NULL;
695
    VIR_AUTOPTR(virURI) uri = NULL;
696
    VIR_AUTOFREE(char *) uristr = NULL;
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
    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)))
714
        return NULL;
715 716

    if (!(uristr = virURIFormat(uri)))
717
        return NULL;
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734

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

    return ret;
}


735 736 737 738 739
static virJSONValuePtr
qemuBlockStorageSourceGetISCSIProps(virStorageSourcePtr src)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *protocol = virStorageNetProtocolTypeToString(src->protocol);
740
    VIR_AUTOFREE(char *) target = NULL;
741 742 743
    char *lunStr = NULL;
    char *username = NULL;
    char *objalias = NULL;
744
    VIR_AUTOFREE(char *) portal = NULL;
745 746 747 748 749 750 751 752 753 754
    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",
755
     *   initiator-name:"iqn.2017-04.com.example:client"
756 757 758 759
     * }
     */

    if (VIR_STRDUP(target, src->path) < 0)
760
        return NULL;
761 762 763 764 765 766 767 768

    /* 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);
769
            return NULL;
770 771 772 773 774 775 776
        }
    }

    /* 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)
777
            return NULL;
778 779 780
    } else {
        if (virAsprintf(&portal, "%s:%u",
                        src->hosts[0].name, src->hosts[0].port) < 0)
781
            return NULL;
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796
    }

    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,
797
                                          "S:initiator-name", src->initiator.iqn,
798 799 800 801 802
                                          NULL));
    return ret;
}


803 804 805
static virJSONValuePtr
qemuBlockStorageSourceGetNBDProps(virStorageSourcePtr src)
{
806
    VIR_AUTOPTR(virJSONValue) serverprops = NULL;
807 808 809 810 811 812 813 814 815 816 817 818 819
    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;

820 821
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "nbd",
822
                                 "a:server", &serverprops,
823 824 825
                                 "S:export", src->path,
                                 "S:tls-creds", src->tlsAlias,
                                 NULL) < 0)
826
        return NULL;
827

828 829 830 831
    return ret;
}


832 833 834 835
static virJSONValuePtr
qemuBlockStorageSourceGetRBDProps(virStorageSourcePtr src)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
836
    VIR_AUTOPTR(virJSONValue) servers = NULL;
837 838
    virJSONValuePtr ret = NULL;
    const char *username = NULL;
839 840
    VIR_AUTOPTR(virJSONValue) authmodes = NULL;
    VIR_AUTOPTR(virJSONValue) mode = NULL;
841
    const char *keysecret = NULL;
842 843 844 845 846

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

847
    if (src->auth) {
848
        username = srcPriv->secinfo->s.aes.username;
849 850 851
        keysecret = srcPriv->secinfo->s.aes.alias;
        /* the auth modes are modelled after our old command line generator */
        if (!(authmodes = virJSONValueNewArray()))
852
            return NULL;
853 854 855

        if (!(mode = virJSONValueNewString("cephx")) ||
            virJSONValueArrayAppend(authmodes, mode) < 0)
856
            return NULL;
857 858 859 860 861

        mode = NULL;

        if (!(mode = virJSONValueNewString("none")) ||
            virJSONValueArrayAppend(authmodes, mode) < 0)
862
            return NULL;
863 864 865

        mode = NULL;
    }
866

867 868 869 870 871 872
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "rbd",
                                 "s:pool", src->volume,
                                 "s:image", src->path,
                                 "S:snapshot", src->snapshot,
                                 "S:conf", src->configFile,
873
                                 "A:server", &servers,
874
                                 "S:user", username,
875 876
                                 "A:auth-client-required", &authmodes,
                                 "S:key-secret", keysecret,
877
                                 NULL) < 0)
878
        return NULL;
879 880 881 882 883

    return ret;
}


884 885 886
static virJSONValuePtr
qemuBlockStorageSourceGetSheepdogProps(virStorageSourcePtr src)
{
887
    VIR_AUTOPTR(virJSONValue) serverprops = NULL;
888 889 890 891 892 893 894 895 896 897 898 899 900 901
    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 */
902 903
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "sheepdog",
904
                                 "a:server", &serverprops,
905 906
                                 "s:vdi", src->path,
                                 NULL) < 0)
907
        return NULL;
908 909 910 911

    return ret;
}

912 913 914 915

static virJSONValuePtr
qemuBlockStorageSourceGetSshProps(virStorageSourcePtr src)
{
916
    VIR_AUTOPTR(virJSONValue) serverprops = NULL;
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
    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;

933 934 935
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "ssh",
                                 "s:path", src->path,
936
                                 "a:server", &serverprops,
937 938
                                 "S:user", username,
                                 NULL) < 0)
939
        return NULL;
940

941 942 943 944
    return ret;
}


945 946 947
static virJSONValuePtr
qemuBlockStorageSourceGetFileProps(virStorageSourcePtr src)
{
948
    const char *driver = "file";
949
    const char *iomode = NULL;
950
    const char *prManagerAlias = NULL;
951 952
    virJSONValuePtr ret = NULL;

953 954 955
    if (src->iomode != VIR_DOMAIN_DISK_IO_DEFAULT)
        iomode = virDomainDiskIoTypeToString(src->iomode);

956 957 958 959 960 961 962
    if (virStorageSourceIsBlockLocal(src)) {
        if (src->hostcdrom)
            driver = "host_cdrom";
        else
            driver = "host_device";
    }

963 964 965
    if (src->pr)
        prManagerAlias = src->pr->mgralias;

966
    ignore_value(virJSONValueObjectCreate(&ret,
967
                                          "s:driver", driver,
968 969
                                          "s:filename", src->path,
                                          "S:aio", iomode,
970
                                          "S:pr-manager", prManagerAlias,
971
                                          NULL) < 0);
972 973 974 975
    return ret;
}


976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
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;
}


995 996 997 998
static int
qemuBlockStorageSourceGetBlockdevGetCacheProps(virStorageSourcePtr src,
                                               virJSONValuePtr props)
{
999
    VIR_AUTOPTR(virJSONValue) cacheobj = NULL;
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
    bool direct = false;
    bool noflush = false;

    if (src->cachemode == VIR_DOMAIN_DISK_CACHE_DEFAULT)
        return 0;

    if (qemuDomainDiskCachemodeFlags(src->cachemode, NULL, &direct, &noflush) < 0)
        return -1;

    if (virJSONValueObjectCreate(&cacheobj,
                                 "b:direct", direct,
                                 "b:no-flush", noflush,
                                 NULL) < 0)
        return -1;

1015
    if (virJSONValueObjectAppend(props, "cache", cacheobj) < 0)
1016
        return -1;
1017
    cacheobj = NULL;
1018 1019 1020 1021 1022

    return 0;
}


1023 1024 1025
/**
 * qemuBlockStorageSourceGetBackendProps:
 * @src: disk source
1026
 * @legacy: use legacy formatting of attributes (for -drive / old qemus)
1027 1028 1029 1030 1031
 *
 * 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
1032 1033
qemuBlockStorageSourceGetBackendProps(virStorageSourcePtr src,
                                      bool legacy)
1034 1035
{
    int actualType = virStorageSourceGetActualType(src);
1036
    VIR_AUTOPTR(virJSONValue) fileprops = NULL;
1037

1038
    switch ((virStorageType)actualType) {
1039 1040
    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_FILE:
1041
        if (!(fileprops = qemuBlockStorageSourceGetFileProps(src)))
1042 1043
            return NULL;
        break;
1044 1045 1046 1047 1048 1049 1050

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

1052 1053 1054
    case VIR_STORAGE_TYPE_VOLUME:
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
1055
        return NULL;
1056 1057

    case VIR_STORAGE_TYPE_NETWORK:
1058 1059
        switch ((virStorageNetProtocol) src->protocol) {
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
1060
            if (!(fileprops = qemuBlockStorageSourceGetGlusterProps(src, legacy)))
1061
                return NULL;
1062 1063
            break;

1064 1065
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
            if (!(fileprops = qemuBlockStorageSourceGetVxHSProps(src)))
1066
                return NULL;
1067 1068
            break;

1069 1070 1071 1072 1073
        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:
1074 1075 1076 1077
            if (!(fileprops = qemuBlockStorageSourceGetCURLProps(src)))
                return NULL;
            break;

1078 1079 1080 1081 1082
        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
            if (!(fileprops = qemuBlockStorageSourceGetISCSIProps(src)))
                return NULL;
            break;

1083
        case VIR_STORAGE_NET_PROTOCOL_NBD:
1084 1085 1086 1087
            if (!(fileprops = qemuBlockStorageSourceGetNBDProps(src)))
                return NULL;
            break;

1088
        case VIR_STORAGE_NET_PROTOCOL_RBD:
1089 1090 1091 1092
            if (!(fileprops = qemuBlockStorageSourceGetRBDProps(src)))
                return NULL;
            break;

1093
        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
1094 1095 1096 1097
            if (!(fileprops = qemuBlockStorageSourceGetSheepdogProps(src)))
                return NULL;
            break;

1098
        case VIR_STORAGE_NET_PROTOCOL_SSH:
1099 1100 1101 1102
            if (!(fileprops = qemuBlockStorageSourceGetSshProps(src)))
                return NULL;
            break;

1103 1104
        case VIR_STORAGE_NET_PROTOCOL_NONE:
        case VIR_STORAGE_NET_PROTOCOL_LAST:
1105
            return NULL;
1106 1107 1108 1109
        }
        break;
    }

1110
    if (qemuBlockNodeNameValidate(src->nodestorage) < 0 ||
1111
        virJSONValueObjectAdd(fileprops, "S:node-name", src->nodestorage, NULL) < 0)
1112
        return NULL;
1113 1114 1115

    if (!legacy) {
        if (qemuBlockStorageSourceGetBlockdevGetCacheProps(src, fileprops) < 0)
1116
            return NULL;
1117

1118 1119 1120 1121
        if (virJSONValueObjectAdd(fileprops,
                                  "b:read-only", src->readonly,
                                  "s:discard", "unmap",
                                  NULL) < 0)
1122
            return NULL;
1123 1124
    }

P
Peter Krempa 已提交
1125
    VIR_RETURN_PTR(fileprops);
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 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 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 1203 1204 1205 1206


static int
qemuBlockStorageSourceGetFormatRawProps(virStorageSourcePtr src,
                                        virJSONValuePtr props)
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *driver = "raw";
    const char *secretalias = NULL;

    if (src->encryption &&
        src->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_LUKS &&
        srcPriv &&
        srcPriv->encinfo) {
        driver = "luks";
        secretalias = srcPriv->encinfo->s.aes.alias;
    }

    /* currently unhandled properties for the 'raw' driver:
     * 'offset'
     * 'size'
     */

    if (virJSONValueObjectAdd(props,
                              "s:driver", driver,
                              "S:key-secret", secretalias, NULL) < 0)
        return -1;

    return 0;
}


static int
qemuBlockStorageSourceGetCryptoProps(virStorageSourcePtr src,
                                     virJSONValuePtr *encprops)
{
    qemuDomainStorageSourcePrivatePtr srcpriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *encformat = NULL;

    *encprops = NULL;

    /* qemu requires encrypted secrets regardless of encryption method used when
     * passed using the blockdev infrastructure, thus only
     * VIR_DOMAIN_SECRET_INFO_TYPE_AES works here. The correct type needs to be
     * instantiated elsewhere. */
    if (!src->encryption ||
        !srcpriv ||
        !srcpriv->encinfo ||
        srcpriv->encinfo->type != VIR_DOMAIN_SECRET_INFO_TYPE_AES)
        return 0;

    switch ((virStorageEncryptionFormatType) src->encryption->format) {
    case VIR_STORAGE_ENCRYPTION_FORMAT_QCOW:
        encformat = "aes";
        break;

    case VIR_STORAGE_ENCRYPTION_FORMAT_LUKS:
        encformat = "luks";
        break;

    case VIR_STORAGE_ENCRYPTION_FORMAT_DEFAULT:
    case VIR_STORAGE_ENCRYPTION_FORMAT_LAST:
    default:
        virReportEnumRangeError(virStorageEncryptionFormatType,
                                src->encryption->format);
        return -1;
    }

    return virJSONValueObjectCreate(encprops,
                                    "s:format", encformat,
                                    "s:key-secret", srcpriv->encinfo->s.aes.alias,
                                    NULL);
}


static int
qemuBlockStorageSourceGetFormatQcowGenericProps(virStorageSourcePtr src,
                                                const char *format,
                                                virJSONValuePtr props)
{
1207
    VIR_AUTOPTR(virJSONValue) encprops = NULL;
1208 1209 1210 1211 1212 1213 1214

    if (qemuBlockStorageSourceGetCryptoProps(src, &encprops) < 0)
        return -1;

    if (virJSONValueObjectAdd(props,
                              "s:driver", format,
                              "A:encrypt", &encprops, NULL) < 0)
1215
        return -1;
1216

1217
    return 0;
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
}


static int
qemuBlockStorageSourceGetFormatQcow2Props(virStorageSourcePtr src,
                                          virJSONValuePtr props)
{
    /* currently unhandled qcow2 props:
     *
     * 'lazy-refcounts'
     * 'pass-discard-request'
     * 'pass-discard-snapshot'
     * 'pass-discard-other'
     * 'overlap-check'
     * 'l2-cache-size'
     * 'l2-cache-entry-size'
     * 'refcount-cache-size'
     * 'cache-clean-interval'
     */

    if (qemuBlockStorageSourceGetFormatQcowGenericProps(src, "qcow2", props) < 0)
        return -1;

    return 0;
}


static virJSONValuePtr
qemuBlockStorageSourceGetBlockdevFormatCommonProps(virStorageSourcePtr src)
{
    const char *detectZeroes = NULL;
    const char *discard = NULL;
    int detectZeroesMode = virDomainDiskGetDetectZeroesMode(src->discard,
                                                            src->detect_zeroes);
1252
    VIR_AUTOPTR(virJSONValue) props = NULL;
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275

    if (qemuBlockNodeNameValidate(src->nodeformat) < 0)
        return NULL;

    if (src->discard)
        discard = virDomainDiskDiscardTypeToString(src->discard);

    if (detectZeroesMode)
        detectZeroes = virDomainDiskDetectZeroesTypeToString(detectZeroesMode);

    /* currently unhandled global properties:
     * '*force-share': 'bool'
     */

    if (virJSONValueObjectCreate(&props,
                                 "s:node-name", src->nodeformat,
                                 "b:read-only", src->readonly,
                                 "S:discard", discard,
                                 "S:detect-zeroes", detectZeroes,
                                 NULL) < 0)
        return NULL;

    if (qemuBlockStorageSourceGetBlockdevGetCacheProps(src, props) < 0)
1276
        return NULL;
1277

P
Peter Krempa 已提交
1278
    VIR_RETURN_PTR(props);
1279 1280 1281 1282 1283 1284 1285
}


static virJSONValuePtr
qemuBlockStorageSourceGetBlockdevFormatProps(virStorageSourcePtr src)
{
    const char *driver = NULL;
1286
    VIR_AUTOPTR(virJSONValue) props = NULL;
1287 1288

    if (!(props = qemuBlockStorageSourceGetBlockdevFormatCommonProps(src)))
1289
        return NULL;
1290 1291 1292 1293 1294 1295 1296

    switch ((virStorageFileFormat) src->format) {
    case VIR_STORAGE_FILE_FAT:
        /* The fat layer is emulated by the storage access layer, so we need to
         * put a raw layer on top */
    case VIR_STORAGE_FILE_RAW:
        if (qemuBlockStorageSourceGetFormatRawProps(src, props) < 0)
1297
            return NULL;
1298 1299 1300 1301
        break;

    case VIR_STORAGE_FILE_QCOW2:
        if (qemuBlockStorageSourceGetFormatQcow2Props(src, props) < 0)
1302
            return NULL;
1303 1304 1305 1306
        break;

    case VIR_STORAGE_FILE_QCOW:
        if (qemuBlockStorageSourceGetFormatQcowGenericProps(src, "qcow", props) < 0)
1307
            return NULL;
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
        break;

    /* formats without any special parameters */
    case VIR_STORAGE_FILE_PLOOP:
        driver = "parallels";
        break;

    case VIR_STORAGE_FILE_VHD:
        driver = "vhdx";
        break;

    case VIR_STORAGE_FILE_BOCHS:
    case VIR_STORAGE_FILE_CLOOP:
    case VIR_STORAGE_FILE_DMG:
    case VIR_STORAGE_FILE_VDI:
    case VIR_STORAGE_FILE_VPC:
    case VIR_STORAGE_FILE_QED:
    case VIR_STORAGE_FILE_VMDK:
        driver = virStorageFileFormatTypeToString(src->format);
        break;

    case VIR_STORAGE_FILE_AUTO_SAFE:
    case VIR_STORAGE_FILE_AUTO:
    case VIR_STORAGE_FILE_NONE:
    case VIR_STORAGE_FILE_COW:
    case VIR_STORAGE_FILE_ISO:
    case VIR_STORAGE_FILE_DIR:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("mishandled storage format '%s'"),
                       virStorageFileFormatTypeToString(src->format));
1338
        return NULL;
1339 1340 1341 1342

    case VIR_STORAGE_FILE_LAST:
    default:
        virReportEnumRangeError(virStorageFileFormat, src->format);
1343
        return NULL;
1344 1345 1346 1347
    }

    if (driver &&
        virJSONValueObjectAdd(props, "s:driver", driver, NULL) < 0)
1348
        return NULL;
1349

P
Peter Krempa 已提交
1350
    VIR_RETURN_PTR(props);
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366
}


/**
 * qemuBlockStorageSourceGetBlockdevProps:
 *
 * @src: storage source to format
 *
 * Formats @src into a JSON object which can be used with blockdev-add or
 * -blockdev. The formatted object contains both the storage and format layer
 * in nested form including link to the backing chain layer if necessary.
 */
virJSONValuePtr
qemuBlockStorageSourceGetBlockdevProps(virStorageSourcePtr src)
{
    bool backingSupported = src->format >= VIR_STORAGE_FILE_BACKING;
1367
    VIR_AUTOPTR(virJSONValue) props = NULL;
1368 1369 1370 1371 1372

    if (virStorageSourceHasBacking(src) && !backingSupported) {
        virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                       _("storage format '%s' does not support backing store"),
                       virStorageFileFormatTypeToString(src->format));
1373
        return NULL;
1374 1375 1376
    }

    if (!(props = qemuBlockStorageSourceGetBlockdevFormatProps(src)))
1377
        return NULL;
1378

1379
    if (virJSONValueObjectAppendString(props, "file", src->nodestorage) < 0)
1380
        return NULL;
1381 1382 1383 1384 1385

    if (src->backingStore && backingSupported) {
        if (virStorageSourceHasBacking(src)) {
            if (virJSONValueObjectAppendString(props, "backing",
                                               src->backingStore->nodeformat) < 0)
1386
                return NULL;
1387 1388 1389 1390
        } else {
            /* chain is terminated, indicate that no detection should happen
             * in qemu */
            if (virJSONValueObjectAppendNull(props, "backing") < 0)
1391
                return NULL;
1392 1393 1394
        }
    }

P
Peter Krempa 已提交
1395
    VIR_RETURN_PTR(props);
1396
}
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406


void
qemuBlockStorageSourceAttachDataFree(qemuBlockStorageSourceAttachDataPtr data)
{
    if (!data)
        return;

    virJSONValueFree(data->storageProps);
    virJSONValueFree(data->formatProps);
1407
    virJSONValueFree(data->prmgrProps);
1408 1409
    virJSONValueFree(data->authsecretProps);
    virJSONValueFree(data->encryptsecretProps);
1410 1411
    virJSONValueFree(data->tlsProps);
    VIR_FREE(data->tlsAlias);
1412 1413
    VIR_FREE(data->authsecretAlias);
    VIR_FREE(data->encryptsecretAlias);
1414 1415
    VIR_FREE(data->driveCmd);
    VIR_FREE(data->driveAlias);
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
    VIR_FREE(data);
}


/**
 * qemuBlockStorageSourceAttachPrepareBlockdev:
 * @src: storage source to prepare data from
 *
 * Creates a qemuBlockStorageSourceAttachData structure containing data to attach
 * @src to a VM using the blockdev-add approach. Note that this function only
 * creates the data for the storage source itself, any other related
 * authentication/encryption/... objects need to be prepared separately.
 *
 * The changes are then applied using qemuBlockStorageSourceAttachApply.
 *
 * Returns the filled data structure on success or NULL on error and a libvirt
 * error is reported
 */
qemuBlockStorageSourceAttachDataPtr
qemuBlockStorageSourceAttachPrepareBlockdev(virStorageSourcePtr src)
{
1437
    VIR_AUTOPTR(qemuBlockStorageSourceAttachData) data = NULL;
1438 1439 1440 1441 1442 1443

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

    if (!(data->formatProps = qemuBlockStorageSourceGetBlockdevProps(src)) ||
        !(data->storageProps = qemuBlockStorageSourceGetBackendProps(src, false)))
1444
        return NULL;
1445 1446 1447 1448

    data->storageNodeName = src->nodestorage;
    data->formatNodeName = src->nodeformat;

P
Peter Krempa 已提交
1449
    VIR_RETURN_PTR(data);
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
}


/**
 * qemuBlockStorageSourceAttachApply:
 * @mon: monitor object
 * @data: structure holding data of block device to apply
 *
 * Attaches a virStorageSource definition converted to
 * qemuBlockStorageSourceAttachData to a running VM. This function expects being
 * called after the monitor was entered.
 *
 * Returns 0 on success and -1 on error with a libvirt error reported. If an
1463
 * error occurred, changes which were already applied need to be rolled back by
1464 1465 1466 1467 1468 1469 1470 1471
 * calling qemuBlockStorageSourceAttachRollback.
 */
int
qemuBlockStorageSourceAttachApply(qemuMonitorPtr mon,
                                  qemuBlockStorageSourceAttachDataPtr data)
{
    int rv;

1472 1473 1474 1475
    if (data->prmgrProps &&
        qemuMonitorAddObject(mon, &data->prmgrProps, &data->prmgrAlias) < 0)
        return -1;

1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
    if (data->authsecretProps &&
        qemuMonitorAddObject(mon, &data->authsecretProps,
                             &data->authsecretAlias) < 0)
        return -1;

    if (data->encryptsecretProps &&
        qemuMonitorAddObject(mon, &data->encryptsecretProps,
                             &data->encryptsecretAlias) < 0)
        return -1;

1486 1487 1488 1489
    if (data->tlsProps &&
        qemuMonitorAddObject(mon, &data->tlsProps, &data->tlsAlias) < 0)
        return -1;

1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509
    if (data->storageProps) {
        rv = qemuMonitorBlockdevAdd(mon, data->storageProps);
        data->storageProps = NULL;

        if (rv < 0)
            return -1;

        data->storageAttached = true;
    }

    if (data->formatProps) {
        rv = qemuMonitorBlockdevAdd(mon, data->formatProps);
        data->formatProps = NULL;

        if (rv < 0)
            return -1;

        data->formatAttached = true;
    }

1510 1511 1512 1513 1514 1515 1516
    if (data->driveCmd) {
        if (qemuMonitorAddDrive(mon, data->driveCmd) < 0)
            return -1;

        data->driveAdded = true;
    }

1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538
    return 0;
}


/**
 * qemuBlockStorageSourceAttachRollback:
 * @mon: monitor object
 * @data: structure holding data of block device to roll back
 *
 * Attempts a best effort rollback of changes which were made to a running VM by
 * qemuBlockStorageSourceAttachApply. Preserves any existing errors.
 *
 * This function expects being called after the monitor was entered.
 */
void
qemuBlockStorageSourceAttachRollback(qemuMonitorPtr mon,
                                     qemuBlockStorageSourceAttachDataPtr data)
{
    virErrorPtr orig_err;

    virErrorPreserveLast(&orig_err);

1539 1540 1541 1542 1543 1544
    if (data->driveAdded) {
        if (qemuMonitorDriveDel(mon, data->driveAlias) < 0)
            VIR_WARN("Unable to remove drive %s (%s) after failed "
                     "qemuMonitorAddDevice", data->driveAlias, data->driveCmd);
    }

1545 1546 1547 1548 1549 1550
    if (data->formatAttached)
        ignore_value(qemuMonitorBlockdevDel(mon, data->formatNodeName));

    if (data->storageAttached)
        ignore_value(qemuMonitorBlockdevDel(mon, data->storageNodeName));

1551 1552 1553
    if (data->prmgrAlias)
        ignore_value(qemuMonitorDelObject(mon, data->prmgrAlias));

1554 1555 1556 1557 1558 1559
    if (data->authsecretAlias)
        ignore_value(qemuMonitorDelObject(mon, data->authsecretAlias));

    if (data->encryptsecretAlias)
        ignore_value(qemuMonitorDelObject(mon, data->encryptsecretAlias));

1560 1561 1562
    if (data->tlsAlias)
        ignore_value(qemuMonitorDelObject(mon, data->tlsAlias));

1563

1564 1565 1566 1567
    virErrorRestore(&orig_err);
}


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
/**
 * qemuBlockStorageSourceDetachPrepare:
 * @src: disk source structure
 * @driveAlias: Alias of the -drive backend, the pointer is always consumed
 *
 * Prepare qemuBlockStorageSourceAttachDataPtr for detaching a single source
 * from a VM. If @driveAlias is NULL -blockdev is assumed.
 */
qemuBlockStorageSourceAttachDataPtr
qemuBlockStorageSourceDetachPrepare(virStorageSourcePtr src,
                                    char *driveAlias)
{
    qemuDomainStorageSourcePrivatePtr srcpriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    VIR_AUTOPTR(qemuBlockStorageSourceAttachData) data = NULL;
    qemuBlockStorageSourceAttachDataPtr ret = NULL;

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

    if (driveAlias) {
        VIR_STEAL_PTR(data->driveAlias, driveAlias);
        data->driveAdded = true;
    } else {
        data->formatNodeName = src->nodeformat;
        data->formatAttached = true;
        data->storageNodeName = src->nodestorage;
        data->storageAttached = true;
    }

    if (src->pr &&
        !virStoragePRDefIsManaged(src->pr) &&
        VIR_STRDUP(data->prmgrAlias, src->pr->mgralias) < 0)
        goto cleanup;

    if (VIR_STRDUP(data->tlsAlias, src->tlsAlias) < 0)
        goto cleanup;

    if (srcpriv) {
        if (srcpriv->secinfo &&
            srcpriv->secinfo->type == VIR_DOMAIN_SECRET_INFO_TYPE_AES &&
            VIR_STRDUP(data->authsecretAlias, srcpriv->secinfo->s.aes.alias) < 0)
            goto cleanup;

        if (srcpriv->encinfo &&
            srcpriv->encinfo->type == VIR_DOMAIN_SECRET_INFO_TYPE_AES &&
            VIR_STRDUP(data->encryptsecretAlias, srcpriv->encinfo->s.aes.alias) < 0)
            goto cleanup;
    }

    VIR_STEAL_PTR(ret, data);

 cleanup:
    VIR_FREE(driveAlias);
    return ret;
}


1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741
void
qemuBlockStorageSourceChainDataFree(qemuBlockStorageSourceChainDataPtr data)
{
    size_t i;

    if (!data)
        return;

    for (i = 0; i < data->nsrcdata; i++)
        qemuBlockStorageSourceAttachDataFree(data->srcdata[i]);

    VIR_FREE(data->srcdata);
    VIR_FREE(data);
}


/**
 * qemuBlockStorageSourceChainDetachPrepareBlockdev
 * @src: storage source chain to remove
 *
 * Prepares qemuBlockStorageSourceChainDataPtr for detaching @src and its
 * backingStore if -blockdev was used.
 */
qemuBlockStorageSourceChainDataPtr
qemuBlockStorageSourceChainDetachPrepareBlockdev(virStorageSourcePtr src)
{
    VIR_AUTOPTR(qemuBlockStorageSourceAttachData) backend = NULL;
    VIR_AUTOPTR(qemuBlockStorageSourceChainData) data = NULL;
    virStorageSourcePtr n;

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

    for (n = src; virStorageSourceIsBacking(n); n = n->backingStore) {
        if (!(backend = qemuBlockStorageSourceDetachPrepare(n, NULL)))
            return NULL;

        if (VIR_APPEND_ELEMENT(data->srcdata, data->nsrcdata, backend) < 0)
            return NULL;
    }

    VIR_RETURN_PTR(data);
}


/**
 * qemuBlockStorageSourceChainDetachPrepareLegacy
 * @src: storage source chain to remove
 * @driveAlias: Alias of the 'drive' backend (always consumed)
 *
 * Prepares qemuBlockStorageSourceChainDataPtr for detaching @src and its
 * backingStore if -drive was used.
 */
qemuBlockStorageSourceChainDataPtr
qemuBlockStorageSourceChainDetachPrepareDrive(virStorageSourcePtr src,
                                              char *driveAlias)
{
    VIR_AUTOPTR(qemuBlockStorageSourceAttachData) backend = NULL;
    VIR_AUTOPTR(qemuBlockStorageSourceChainData) data = NULL;

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

    if (!(backend = qemuBlockStorageSourceDetachPrepare(src, driveAlias)))
        return NULL;

    if (VIR_APPEND_ELEMENT(data->srcdata, data->nsrcdata, backend) < 0)
        return NULL;

    VIR_RETURN_PTR(data);
}


/**
 * qemuBlockStorageSourceChainAttach:
 * @mon: monitor object
 * @data: storage source chain data
 *
 * Attach a storage source including its backing chain and supporting objects.
 * Caller must enter @mon prior calling this function. In case of error this
 * function returns -1. @data is updated so that qemuBlockStorageSourceChainDetach
 * can be used to roll-back the changes.
 */
int
qemuBlockStorageSourceChainAttach(qemuMonitorPtr mon,
                                  qemuBlockStorageSourceChainDataPtr data)
{
    size_t i;

    for (i = data->nsrcdata; i > 0; i--) {
        if (qemuBlockStorageSourceAttachApply(mon, data->srcdata[i - 1]) < 0)
            return -1;
    }

    return 0;
}


/**
 * qemuBlockStorageSourceChainDetach:
 * @mon: monitor object
 * @data: storage source chain data
 *
 * Detach a unused storage source including all its backing chain and related
 * objects described by @data.
 */
void
qemuBlockStorageSourceChainDetach(qemuMonitorPtr mon,
                                  qemuBlockStorageSourceChainDataPtr data)
{
    size_t i;

    for (i = 0; i < data->nsrcdata; i++)
        qemuBlockStorageSourceAttachRollback(mon, data->srcdata[i]);
}


1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
/**
 * qemuBlockStorageSourceDetachOneBlockdev:
 * @driver: qemu driver object
 * @vm: domain object
 * @asyncJob: currently running async job
 * @src: storage source to detach
 *
 * Detaches one virStorageSource using blockdev-del. Note that this does not
 * detach any authentication/encryption objects. This function enters the
 * monitor internally.
 */
int
qemuBlockStorageSourceDetachOneBlockdev(virQEMUDriverPtr driver,
                                        virDomainObjPtr vm,
                                        qemuDomainAsyncJob asyncJob,
                                        virStorageSourcePtr src)
{
    int ret;

    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
        return -1;

    ret = qemuMonitorBlockdevDel(qemuDomainGetMonitor(vm), src->nodeformat);

    if (ret == 0)
        ret = qemuMonitorBlockdevDel(qemuDomainGetMonitor(vm), src->nodestorage);

    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return -1;

    return ret;
}
1774 1775 1776 1777 1778 1779 1780 1781 1782


int
qemuBlockSnapshotAddLegacy(virJSONValuePtr actions,
                           virDomainDiskDefPtr disk,
                           virStorageSourcePtr newsrc,
                           bool reuse)
{
    const char *format = virStorageFileFormatTypeToString(newsrc->format);
1783 1784
    VIR_AUTOFREE(char *) device = NULL;
    VIR_AUTOFREE(char *) source = NULL;
1785 1786

    if (!(device = qemuAliasDiskDriveFromDisk(disk)))
1787
        return -1;
1788 1789

    if (qemuGetDriveSourceString(newsrc, NULL, &source) < 0)
1790
        return -1;
1791 1792 1793 1794 1795 1796 1797

    if (qemuMonitorJSONTransactionAdd(actions, "blockdev-snapshot-sync",
                                      "s:device", device,
                                      "s:snapshot-file", source,
                                      "s:format", format,
                                      "S:mode", reuse ? "existing" : NULL,
                                      NULL) < 0)
1798
        return -1;
1799

1800
    return 0;
1801
}
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823


/**
 * qemuBlockStorageGetCopyOnReadProps:
 * @disk: disk with copy-on-read enabled
 *
 * Creates blockdev properties for a disk copy-on-read layer.
 */
virJSONValuePtr
qemuBlockStorageGetCopyOnReadProps(virDomainDiskDefPtr disk)
{
    qemuDomainDiskPrivatePtr priv = QEMU_DOMAIN_DISK_PRIVATE(disk);
    virJSONValuePtr ret = NULL;

    ignore_value(virJSONValueObjectCreate(&ret,
                                          "s:driver", "copy-on-read",
                                          "s:node-name", priv->nodeCopyOnRead,
                                          "s:file", disk->src->nodeformat,
                                          NULL));

    return ret;
}