qemu_block.c 79.8 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 26 27

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

#define VIR_FROM_THIS VIR_FROM_QEMU

32 33
VIR_LOG_INIT("qemu.qemu_block");

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/* 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;
}

52

53
static int
J
Ján Tomko 已提交
54
qemuBlockNamedNodesArrayToHash(size_t pos G_GNUC_UNUSED,
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
                               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;
}


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

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

    VIR_FREE(data->qemufilename);
81

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

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

    VIR_FREE(data);
}

90
G_DEFINE_AUTOPTR_CLEANUP_FUNC(qemuBlockNodeNameBackingChainData,
91 92
                        qemuBlockNodeNameBackingChainDataFree);

93 94 95

static void
qemuBlockNodeNameBackingChainDataHashEntryFree(void *opaque,
J
Ján Tomko 已提交
96
                                               const void *name G_GNUC_UNUSED)
97 98 99 100 101
{
    qemuBlockNodeNameBackingChainDataFree(opaque);
}


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

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

        drivers++;
    }

    return false;
}


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


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

145
    if (!nodename)
146 147
        return 0;

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

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

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

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

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

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

190
    return 0;
191 192 193 194
}


static int
J
Ján Tomko 已提交
195
qemuBlockNodeNameGetBackingChainDisk(size_t pos G_GNUC_UNUSED,
196 197
                                     virJSONValuePtr item,
                                     void *opaque)
198
{
199 200
    struct qemuBlockNodeNameGetBackingChainData *data = opaque;
    const char *device = virJSONValueObjectGetString(item, "device");
J
Ján Tomko 已提交
201
    g_autoptr(qemuBlockNodeNameBackingChainData) devicedata = NULL;
202

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

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

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


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

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

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

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

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

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

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

J
Ján Tomko 已提交
258
    return g_steal_pointer(&disks);
259
}
260 261 262 263 264 265 266


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

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

        next = next->backingStore;
    }
}


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

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

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

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

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

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

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

314
    ret = 0;
315

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

    return ret;
321 322 323 324 325
}


int
qemuBlockNodeNamesDetect(virQEMUDriverPtr driver,
326 327
                         virDomainObjPtr vm,
                         qemuDomainAsyncJob asyncJob)
328 329
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
J
Ján Tomko 已提交
330 331 332
    g_autoptr(virHashTable) disktable = NULL;
    g_autoptr(virJSONValue) data = NULL;
    g_autoptr(virJSONValue) blockstats = NULL;
333 334 335 336 337 338
    virDomainDiskDefPtr disk;
    size_t i;

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

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

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

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

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

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

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

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


/**
 * 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)
{
J
Ján Tomko 已提交
374
    g_autoptr(virHashTable) nodedata = NULL;
375

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

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

J
Ján Tomko 已提交
383
    return g_steal_pointer(&nodedata);
384
}
385 386


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


402 403 404 405 406 407 408 409 410
/**
 * qemuBlockStorageSourceGetURI:
 * @src: disk storage source
 *
 * Formats a URI from a virStorageSource.
 */
virURIPtr
qemuBlockStorageSourceGetURI(virStorageSourcePtr src)
{
J
Ján Tomko 已提交
411
    g_autoptr(virURI) uri = NULL;
412 413 414 415 416

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

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

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

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

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

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

J
Ján Tomko 已提交
452
    return g_steal_pointer(&uri);
453 454 455
}


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

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

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

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

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

J
Ján Tomko 已提交
517
    return g_steal_pointer(&server);
518 519 520
}


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

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

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

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

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

        server = NULL;
    }

J
Ján Tomko 已提交
553
    return g_steal_pointer(&servers);
554 555 556
}


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

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


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

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

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

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

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

        server = NULL;
    }

J
Ján Tomko 已提交
620
    return g_steal_pointer(&servers);
621 622 623
}


624
static virJSONValuePtr
625
qemuBlockStorageSourceGetGlusterProps(virStorageSourcePtr src,
626 627
                                      bool legacy,
                                      bool onlytarget)
628
{
J
Ján Tomko 已提交
629 630
    g_autoptr(virJSONValue) servers = NULL;
    g_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 643
                                 "s:volume", src->volume,
                                 "s:path", src->path,
644
                                 "a:server", &servers, NULL) < 0)
645
        return NULL;
646

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

J
Ján Tomko 已提交
652
    return g_steal_pointer(&props);
653 654 655
}


656
static virJSONValuePtr
657 658
qemuBlockStorageSourceGetVxHSProps(virStorageSourcePtr src,
                                   bool onlytarget)
659
{
J
Ján Tomko 已提交
660
    g_autoptr(virJSONValue) server = NULL;
661
    const char *tlsAlias = src->tlsAlias;
662 663 664 665 666 667 668 669
    virJSONValuePtr ret = NULL;

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

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

673 674 675
    if (onlytarget)
        tlsAlias = NULL;

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

    return ret;
}


691
static virJSONValuePtr
692 693
qemuBlockStorageSourceGetCURLProps(virStorageSourcePtr src,
                                   bool onlytarget)
694 695 696 697 698
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
    const char *passwordalias = NULL;
    const char *username = NULL;
    virJSONValuePtr ret = NULL;
J
Ján Tomko 已提交
699
    g_autoptr(virURI) uri = NULL;
700
    g_autofree char *uristr = NULL;
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715

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


    if (!(uri = qemuBlockStorageSourceGetURI(src)))
716
        return NULL;
717 718

    if (!(uristr = virURIFormat(uri)))
719
        return NULL;
720

721
    if (!onlytarget && src->auth) {
722 723 724 725 726 727 728 729 730 731 732 733 734 735
        username = src->auth->username;
        passwordalias = srcPriv->secinfo->s.aes.alias;
    }

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

    return ret;
}


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

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

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

    /* 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)
778
            return NULL;
779 780 781
    } else {
        if (virAsprintf(&portal, "%s:%u",
                        src->hosts[0].name, src->hosts[0].port) < 0)
782
            return NULL;
783 784
    }

785
    if (!onlytarget && src->auth) {
786 787 788 789 790 791 792 793 794 795 796
        username = src->auth->username;
        objalias = srcPriv->secinfo->s.aes.alias;
    }

    ignore_value(virJSONValueObjectCreate(&ret,
                                          "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
static virJSONValuePtr
804 805
qemuBlockStorageSourceGetNBDProps(virStorageSourcePtr src,
                                  bool onlytarget)
806
{
J
Ján Tomko 已提交
807
    g_autoptr(virJSONValue) serverprops = NULL;
808
    const char *tlsAlias = src->tlsAlias;
809 810 811 812 813 814 815 816 817 818 819 820 821
    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;

822 823 824
    if (onlytarget)
        tlsAlias = NULL;

825
    if (virJSONValueObjectCreate(&ret,
826
                                 "a:server", &serverprops,
827
                                 "S:export", src->path,
828
                                 "S:tls-creds", tlsAlias,
829
                                 NULL) < 0)
830
        return NULL;
831

832 833 834 835
    return ret;
}


836
static virJSONValuePtr
837 838
qemuBlockStorageSourceGetRBDProps(virStorageSourcePtr src,
                                  bool onlytarget)
839 840
{
    qemuDomainStorageSourcePrivatePtr srcPriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
J
Ján Tomko 已提交
841
    g_autoptr(virJSONValue) servers = NULL;
842 843
    virJSONValuePtr ret = NULL;
    const char *username = NULL;
J
Ján Tomko 已提交
844 845
    g_autoptr(virJSONValue) authmodes = NULL;
    g_autoptr(virJSONValue) mode = NULL;
846
    const char *keysecret = NULL;
847 848 849 850 851

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

852
    if (!onlytarget && src->auth) {
853
        username = srcPriv->secinfo->s.aes.username;
854 855 856
        keysecret = srcPriv->secinfo->s.aes.alias;
        /* the auth modes are modelled after our old command line generator */
        if (!(authmodes = virJSONValueNewArray()))
857
            return NULL;
858 859 860

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

        mode = NULL;

        if (!(mode = virJSONValueNewString("none")) ||
            virJSONValueArrayAppend(authmodes, mode) < 0)
867
            return NULL;
868 869 870

        mode = NULL;
    }
871

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

    return ret;
}


888 889 890
static virJSONValuePtr
qemuBlockStorageSourceGetSheepdogProps(virStorageSourcePtr src)
{
J
Ján Tomko 已提交
891
    g_autoptr(virJSONValue) serverprops = NULL;
892 893 894 895 896 897 898 899 900 901 902 903 904 905
    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 */
906
    if (virJSONValueObjectCreate(&ret,
907
                                 "a:server", &serverprops,
908 909
                                 "s:vdi", src->path,
                                 NULL) < 0)
910
        return NULL;
911 912 913 914

    return ret;
}

915 916 917 918

static virJSONValuePtr
qemuBlockStorageSourceGetSshProps(virStorageSourcePtr src)
{
J
Ján Tomko 已提交
919
    g_autoptr(virJSONValue) serverprops = NULL;
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
    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;

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

943 944 945 946
    return ret;
}


947
static virJSONValuePtr
948 949
qemuBlockStorageSourceGetFileProps(virStorageSourcePtr src,
                                   bool onlytarget)
950
{
951
    const char *iomode = NULL;
952
    const char *prManagerAlias = NULL;
953 954
    virJSONValuePtr ret = NULL;

955 956 957 958 959 960 961
    if (!onlytarget) {
        if (src->pr)
            prManagerAlias = src->pr->mgralias;

        if (src->iomode != VIR_DOMAIN_DISK_IO_DEFAULT)
            iomode = virDomainDiskIoTypeToString(src->iomode);
    }
962

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


972
static virJSONValuePtr
973 974
qemuBlockStorageSourceGetVvfatProps(virStorageSourcePtr src,
                                    bool onlytarget)
975
{
J
Ján Tomko 已提交
976
    g_autoptr(virJSONValue) ret = NULL;
977 978 979 980 981

    /* libvirt currently does not handle the following attributes:
     * '*fat-type': 'int'
     * '*label': 'str'
     */
982 983 984 985 986
    if (virJSONValueObjectCreate(&ret,
                                 "s:driver", "vvfat",
                                 "s:dir", src->path,
                                 "b:floppy", src->floppyimg, NULL) < 0)
        return NULL;
987

988 989 990 991
    if (!onlytarget &&
        virJSONValueObjectAdd(ret, "b:rw", !src->readonly, NULL) < 0)
        return NULL;

J
Ján Tomko 已提交
992
    return g_steal_pointer(&ret);
993 994 995
}


996 997 998 999
static int
qemuBlockStorageSourceGetBlockdevGetCacheProps(virStorageSourcePtr src,
                                               virJSONValuePtr props)
{
J
Ján Tomko 已提交
1000
    g_autoptr(virJSONValue) cacheobj = NULL;
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
    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;

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

    return 0;
}


1024 1025 1026
/**
 * qemuBlockStorageSourceGetBackendProps:
 * @src: disk source
1027
 * @legacy: use legacy formatting of attributes (for -drive / old qemus)
1028
 * @onlytarget: omit any data which does not identify the image itself
1029
 * @autoreadonly: use the auto-read-only feature of qemu
1030 1031 1032 1033 1034
 *
 * 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
1035
qemuBlockStorageSourceGetBackendProps(virStorageSourcePtr src,
1036
                                      bool legacy,
1037 1038
                                      bool onlytarget,
                                      bool autoreadonly)
1039 1040
{
    int actualType = virStorageSourceGetActualType(src);
J
Ján Tomko 已提交
1041
    g_autoptr(virJSONValue) fileprops = NULL;
1042
    const char *driver = NULL;
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
    virTristateBool aro = VIR_TRISTATE_BOOL_ABSENT;
    virTristateBool ro = VIR_TRISTATE_BOOL_ABSENT;

    if (autoreadonly) {
        aro = VIR_TRISTATE_BOOL_YES;
    } else {
        if (src->readonly)
            ro = VIR_TRISTATE_BOOL_YES;
        else
            ro = VIR_TRISTATE_BOOL_NO;
    }
1054

1055
    switch ((virStorageType)actualType) {
1056 1057
    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_FILE:
1058 1059 1060 1061 1062 1063 1064 1065 1066
        if (virStorageSourceIsBlockLocal(src)) {
            if (src->hostcdrom)
                driver = "host_cdrom";
            else
                driver = "host_device";
        } else {
            driver = "file";
        }

1067
        if (!(fileprops = qemuBlockStorageSourceGetFileProps(src, onlytarget)))
1068 1069
            return NULL;
        break;
1070 1071 1072 1073

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

1078 1079 1080
    case VIR_STORAGE_TYPE_VOLUME:
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
1081
        return NULL;
1082 1083

    case VIR_STORAGE_TYPE_NETWORK:
1084 1085
        switch ((virStorageNetProtocol) src->protocol) {
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
1086
            driver = "gluster";
1087
            if (!(fileprops = qemuBlockStorageSourceGetGlusterProps(src, legacy, onlytarget)))
1088
                return NULL;
1089 1090
            break;

1091
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
1092
            driver = "vxhs";
1093
            if (!(fileprops = qemuBlockStorageSourceGetVxHSProps(src, onlytarget)))
1094
                return NULL;
1095 1096
            break;

1097 1098 1099 1100 1101
        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:
1102
            driver = virStorageNetProtocolTypeToString(src->protocol);
1103
            if (!(fileprops = qemuBlockStorageSourceGetCURLProps(src, onlytarget)))
1104 1105 1106
                return NULL;
            break;

1107
        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
1108
            driver = "iscsi";
1109
            if (!(fileprops = qemuBlockStorageSourceGetISCSIProps(src, onlytarget)))
1110 1111 1112
                return NULL;
            break;

1113
        case VIR_STORAGE_NET_PROTOCOL_NBD:
1114
            driver = "nbd";
1115
            if (!(fileprops = qemuBlockStorageSourceGetNBDProps(src, onlytarget)))
1116 1117 1118
                return NULL;
            break;

1119
        case VIR_STORAGE_NET_PROTOCOL_RBD:
1120
            driver = "rbd";
1121
            if (!(fileprops = qemuBlockStorageSourceGetRBDProps(src, onlytarget)))
1122 1123 1124
                return NULL;
            break;

1125
        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
1126
            driver = "sheepdog";
1127 1128 1129 1130
            if (!(fileprops = qemuBlockStorageSourceGetSheepdogProps(src)))
                return NULL;
            break;

1131
        case VIR_STORAGE_NET_PROTOCOL_SSH:
1132
            driver = "ssh";
1133 1134 1135 1136
            if (!(fileprops = qemuBlockStorageSourceGetSshProps(src)))
                return NULL;
            break;

1137 1138
        case VIR_STORAGE_NET_PROTOCOL_NONE:
        case VIR_STORAGE_NET_PROTOCOL_LAST:
1139
            return NULL;
1140 1141 1142 1143
        }
        break;
    }

1144 1145 1146
    if (driver && virJSONValueObjectPrependString(fileprops, "driver", driver) < 0)
        return NULL;

1147 1148 1149
    if (!onlytarget) {
        if (qemuBlockNodeNameValidate(src->nodestorage) < 0 ||
            virJSONValueObjectAdd(fileprops, "S:node-name", src->nodestorage, NULL) < 0)
1150
            return NULL;
1151

1152 1153 1154 1155 1156
        if (!legacy) {
            if (qemuBlockStorageSourceGetBlockdevGetCacheProps(src, fileprops) < 0)
                return NULL;

            if (virJSONValueObjectAdd(fileprops,
1157 1158
                                      "T:read-only", ro,
                                      "T:auto-read-only", aro,
1159 1160 1161 1162
                                      "s:discard", "unmap",
                                      NULL) < 0)
                return NULL;
        }
1163 1164
    }

J
Ján Tomko 已提交
1165
    return g_steal_pointer(&fileprops);
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 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246


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)
{
J
Ján Tomko 已提交
1247
    g_autoptr(virJSONValue) encprops = NULL;
1248 1249 1250 1251 1252 1253 1254

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

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

1257
    return 0;
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
}


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);
J
Ján Tomko 已提交
1292
    g_autoptr(virJSONValue) props = NULL;
1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315

    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)
1316
        return NULL;
1317

J
Ján Tomko 已提交
1318
    return g_steal_pointer(&props);
1319 1320 1321 1322 1323 1324 1325
}


static virJSONValuePtr
qemuBlockStorageSourceGetBlockdevFormatProps(virStorageSourcePtr src)
{
    const char *driver = NULL;
J
Ján Tomko 已提交
1326
    g_autoptr(virJSONValue) props = NULL;
1327 1328

    if (!(props = qemuBlockStorageSourceGetBlockdevFormatCommonProps(src)))
1329
        return NULL;
1330 1331 1332 1333 1334 1335 1336

    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)
1337
            return NULL;
1338 1339 1340 1341
        break;

    case VIR_STORAGE_FILE_QCOW2:
        if (qemuBlockStorageSourceGetFormatQcow2Props(src, props) < 0)
1342
            return NULL;
1343 1344 1345 1346
        break;

    case VIR_STORAGE_FILE_QCOW:
        if (qemuBlockStorageSourceGetFormatQcowGenericProps(src, "qcow", props) < 0)
1347
            return NULL;
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
        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));
1378
        return NULL;
1379 1380 1381 1382

    case VIR_STORAGE_FILE_LAST:
    default:
        virReportEnumRangeError(virStorageFileFormat, src->format);
1383
        return NULL;
1384 1385 1386 1387
    }

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

J
Ján Tomko 已提交
1390
    return g_steal_pointer(&props);
1391 1392 1393 1394 1395 1396 1397
}


/**
 * qemuBlockStorageSourceGetBlockdevProps:
 *
 * @src: storage source to format
1398
 * @backingStore: a storage source to use as backing of @src
1399 1400 1401 1402 1403 1404
 *
 * 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
1405 1406
qemuBlockStorageSourceGetBlockdevProps(virStorageSourcePtr src,
                                       virStorageSourcePtr backingStore)
1407
{
J
Ján Tomko 已提交
1408
    g_autoptr(virJSONValue) props = NULL;
1409 1410

    if (!(props = qemuBlockStorageSourceGetBlockdevFormatProps(src)))
1411
        return NULL;
1412

1413
    if (virJSONValueObjectAppendString(props, "file", src->nodestorage) < 0)
1414
        return NULL;
1415

1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
    if (backingStore) {
        if (src->format >= VIR_STORAGE_FILE_BACKING) {
            if (virStorageSourceIsBacking(backingStore)) {
                if (virJSONValueObjectAppendString(props, "backing",
                                                   backingStore->nodeformat) < 0)
                    return NULL;
            } else {
                /* chain is terminated, indicate that no detection should happen
                 * in qemu */
                if (virJSONValueObjectAppendNull(props, "backing") < 0)
                    return NULL;
            }
1428
        } else {
1429 1430 1431 1432
            if (virStorageSourceIsBacking(backingStore)) {
                virReportError(VIR_ERR_CONFIG_UNSUPPORTED,
                               _("storage format '%s' does not support backing store"),
                               virStorageFileFormatTypeToString(src->format));
1433
                return NULL;
1434
            }
1435 1436 1437
        }
    }

J
Ján Tomko 已提交
1438
    return g_steal_pointer(&props);
1439
}
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449


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

    virJSONValueFree(data->storageProps);
    virJSONValueFree(data->formatProps);
1450
    virJSONValueFree(data->prmgrProps);
1451 1452
    virJSONValueFree(data->authsecretProps);
    virJSONValueFree(data->encryptsecretProps);
1453 1454
    virJSONValueFree(data->tlsProps);
    VIR_FREE(data->tlsAlias);
1455 1456
    VIR_FREE(data->authsecretAlias);
    VIR_FREE(data->encryptsecretAlias);
1457 1458
    VIR_FREE(data->driveCmd);
    VIR_FREE(data->driveAlias);
1459 1460 1461 1462 1463 1464 1465
    VIR_FREE(data);
}


/**
 * qemuBlockStorageSourceAttachPrepareBlockdev:
 * @src: storage source to prepare data from
1466
 * @backingStore: storage source to use as backing of @src
1467
 * @autoreadonly: use 'auto-read-only' feature of qemu
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
 *
 * 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
1480
qemuBlockStorageSourceAttachPrepareBlockdev(virStorageSourcePtr src,
1481
                                            virStorageSourcePtr backingStore,
1482
                                            bool autoreadonly)
1483
{
J
Ján Tomko 已提交
1484
    g_autoptr(qemuBlockStorageSourceAttachData) data = NULL;
1485 1486 1487 1488

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

1489
    if (!(data->formatProps = qemuBlockStorageSourceGetBlockdevProps(src,
1490
                                                                     backingStore)) ||
1491 1492 1493
        !(data->storageProps = qemuBlockStorageSourceGetBackendProps(src, false,
                                                                     false,
                                                                     autoreadonly)))
1494
        return NULL;
1495 1496 1497 1498

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

J
Ján Tomko 已提交
1499
    return g_steal_pointer(&data);
1500 1501 1502
}


1503 1504 1505
static int
qemuBlockStorageSourceAttachApplyStorageDeps(qemuMonitorPtr mon,
                                             qemuBlockStorageSourceAttachDataPtr data)
1506
{
1507 1508 1509 1510
    if (data->prmgrProps &&
        qemuMonitorAddObject(mon, &data->prmgrProps, &data->prmgrAlias) < 0)
        return -1;

1511 1512 1513 1514 1515
    if (data->authsecretProps &&
        qemuMonitorAddObject(mon, &data->authsecretProps,
                             &data->authsecretAlias) < 0)
        return -1;

1516 1517 1518 1519
    if (data->tlsProps &&
        qemuMonitorAddObject(mon, &data->tlsProps, &data->tlsAlias) < 0)
        return -1;

1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    return 0;
}


static int
qemuBlockStorageSourceAttachApplyStorage(qemuMonitorPtr mon,
                                         qemuBlockStorageSourceAttachDataPtr data)
{
    int rv;

1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    if (data->storageProps) {
        rv = qemuMonitorBlockdevAdd(mon, data->storageProps);
        data->storageProps = NULL;

        if (rv < 0)
            return -1;

        data->storageAttached = true;
    }

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
    return 0;
}


static int
qemuBlockStorageSourceAttachApplyFormatDeps(qemuMonitorPtr mon,
                                            qemuBlockStorageSourceAttachDataPtr data)
{
    if (data->encryptsecretProps &&
        qemuMonitorAddObject(mon, &data->encryptsecretProps,
                             &data->encryptsecretAlias) < 0)
        return -1;

    return 0;
}


static int
qemuBlockStorageSourceAttachApplyFormat(qemuMonitorPtr mon,
                                        qemuBlockStorageSourceAttachDataPtr data)
{
    int rv;

1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
    if (data->formatProps) {
        rv = qemuMonitorBlockdevAdd(mon, data->formatProps);
        data->formatProps = NULL;

        if (rv < 0)
            return -1;

        data->formatAttached = true;
    }

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


/**
 * 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
 * error occurred, changes which were already applied need to be rolled back by
 * calling qemuBlockStorageSourceAttachRollback.
 */
int
qemuBlockStorageSourceAttachApply(qemuMonitorPtr mon,
                                  qemuBlockStorageSourceAttachDataPtr data)
{
    if (qemuBlockStorageSourceAttachApplyStorageDeps(mon, data) < 0 ||
        qemuBlockStorageSourceAttachApplyStorage(mon, data) < 0 ||
        qemuBlockStorageSourceAttachApplyFormatDeps(mon, data) < 0 ||
        qemuBlockStorageSourceAttachApplyFormat(mon, data) < 0)
        return -1;

1600 1601 1602 1603 1604 1605 1606
    if (data->driveCmd) {
        if (qemuMonitorAddDrive(mon, data->driveCmd) < 0)
            return -1;

        data->driveAdded = true;
    }

1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
    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);

1629 1630 1631 1632 1633 1634
    if (data->driveAdded) {
        if (qemuMonitorDriveDel(mon, data->driveAlias) < 0)
            VIR_WARN("Unable to remove drive %s (%s) after failed "
                     "qemuMonitorAddDevice", data->driveAlias, data->driveCmd);
    }

1635 1636 1637 1638 1639 1640
    if (data->formatAttached)
        ignore_value(qemuMonitorBlockdevDel(mon, data->formatNodeName));

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

1641 1642 1643
    if (data->prmgrAlias)
        ignore_value(qemuMonitorDelObject(mon, data->prmgrAlias));

1644 1645 1646 1647 1648 1649
    if (data->authsecretAlias)
        ignore_value(qemuMonitorDelObject(mon, data->authsecretAlias));

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

1650 1651 1652
    if (data->tlsAlias)
        ignore_value(qemuMonitorDelObject(mon, data->tlsAlias));

1653

1654 1655 1656 1657
    virErrorRestore(&orig_err);
}


1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
/**
 * 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);
J
Ján Tomko 已提交
1671
    g_autoptr(qemuBlockStorageSourceAttachData) data = NULL;
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
    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;
}


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
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)
{
J
Ján Tomko 已提交
1741 1742
    g_autoptr(qemuBlockStorageSourceAttachData) backend = NULL;
    g_autoptr(qemuBlockStorageSourceChainData) data = NULL;
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
    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;
    }

J
Ján Tomko 已提交
1756
    return g_steal_pointer(&data);
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
}


/**
 * 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)
{
J
Ján Tomko 已提交
1772 1773
    g_autoptr(qemuBlockStorageSourceAttachData) backend = NULL;
    g_autoptr(qemuBlockStorageSourceChainData) data = NULL;
1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

    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;

J
Ján Tomko 已提交
1784
    return g_steal_pointer(&data);
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
}


/**
 * 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]);
}


1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
/**
 * 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;
}
1864 1865 1866 1867 1868 1869 1870 1871 1872


int
qemuBlockSnapshotAddLegacy(virJSONValuePtr actions,
                           virDomainDiskDefPtr disk,
                           virStorageSourcePtr newsrc,
                           bool reuse)
{
    const char *format = virStorageFileFormatTypeToString(newsrc->format);
1873 1874
    g_autofree char *device = NULL;
    g_autofree char *source = NULL;
1875 1876

    if (!(device = qemuAliasDiskDriveFromDisk(disk)))
1877
        return -1;
1878 1879

    if (qemuGetDriveSourceString(newsrc, NULL, &source) < 0)
1880
        return -1;
1881

1882
    return qemuMonitorTransactionSnapshotLegacy(actions, device, source, format, reuse);
1883
}
1884 1885


1886 1887 1888 1889 1890
int
qemuBlockSnapshotAddBlockdev(virJSONValuePtr actions,
                             virDomainDiskDefPtr disk,
                             virStorageSourcePtr newsrc)
{
1891 1892 1893
    return qemuMonitorTransactionSnapshotBlockdev(actions,
                                                  disk->src->nodeformat,
                                                  newsrc->nodeformat);
1894 1895 1896
}


1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916
/**
 * 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;
}
1917 1918


1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
/**
 * qemuBlockGetBackingStoreString:
 * @src: storage source to get the string for
 *
 * Formats a string used in the backing store field of a disk image which
 * supports backing store. Non-local storage may result in use of the json:
 * pseudo protocol for any complex configuration.
 */
char *
qemuBlockGetBackingStoreString(virStorageSourcePtr src)
{
    int actualType = virStorageSourceGetActualType(src);
J
Ján Tomko 已提交
1931 1932
    g_autoptr(virJSONValue) backingProps = NULL;
    g_autoptr(virURI) uri = NULL;
1933
    g_autofree char *backingJSON = NULL;
1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986
    char *ret = NULL;

    if (virStorageSourceIsLocalStorage(src)) {
        ignore_value(VIR_STRDUP(ret, src->path));
        return ret;
    }

    /* generate simplified URIs for the easy cases */
    if (actualType == VIR_STORAGE_TYPE_NETWORK &&
        src->nhosts == 1 &&
        src->hosts->transport == VIR_STORAGE_NET_HOST_TRANS_TCP) {

        switch ((virStorageNetProtocol) src->protocol) {
        case VIR_STORAGE_NET_PROTOCOL_NBD:
        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:
        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
            if (!(uri = qemuBlockStorageSourceGetURI(src)))
                return NULL;

            if (!(ret = virURIFormat(uri)))
                return NULL;

            return ret;

        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
        case VIR_STORAGE_NET_PROTOCOL_RBD:
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
        case VIR_STORAGE_NET_PROTOCOL_SSH:
        case VIR_STORAGE_NET_PROTOCOL_LAST:
        case VIR_STORAGE_NET_PROTOCOL_NONE:
            break;
        }
    }

    /* use json: pseudo protocol otherwise */
    if (!(backingProps = qemuBlockStorageSourceGetBackendProps(src, false, true, false)))
        return NULL;

    if (!(backingJSON = virJSONValueToString(backingProps, false)))
        return NULL;

    if (virAsprintf(&ret, "json:%s", backingJSON) < 0)
        return NULL;

    return ret;
}


1987 1988 1989 1990 1991
static int
qemuBlockStorageSourceCreateAddBacking(virStorageSourcePtr backing,
                                       virJSONValuePtr props,
                                       bool format)
{
1992
    g_autofree char *backingFileStr = NULL;
1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005
    const char *backingFormatStr = NULL;

    if (!virStorageSourceIsBacking(backing))
        return 0;

    if (format) {
        if (backing->encryption &&
            backing->encryption->format == VIR_STORAGE_ENCRYPTION_FORMAT_LUKS)
            backingFormatStr = "luks";
        else
            backingFormatStr = virStorageFileFormatTypeToString(backing->format);
    }

2006 2007
    if (!(backingFileStr = qemuBlockGetBackingStoreString(backing)))
        return -1;
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024

    if (virJSONValueObjectAdd(props,
                              "S:backing-file", backingFileStr,
                              "S:backing-fmt", backingFormatStr,
                              NULL) < 0)
        return -1;

    return 0;
}


static int
qemuBlockStorageSourceCreateGetFormatPropsGeneric(virStorageSourcePtr src,
                                                  const char *driver,
                                                  virJSONValuePtr *retprops,
                                                  virStorageSourcePtr backing)
{
J
Ján Tomko 已提交
2025
    g_autoptr(virJSONValue) props = NULL;
2026 2027 2028 2029

    if (virJSONValueObjectCreate(&props,
                                 "s:driver", driver,
                                 "s:file", src->nodestorage,
2030
                                 "U:size", src->capacity,
2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
                                 NULL) < 0)
        return -1;

    if (backing &&
        qemuBlockStorageSourceCreateAddBacking(backing, props, false) < 0)
        return -1;

    VIR_STEAL_PTR(*retprops, props);
    return 0;
}


static int
qemuBlockStorageSourceCreateGetEncryptionLUKS(virStorageSourcePtr src,
                                              virJSONValuePtr *luksProps)
{
    qemuDomainStorageSourcePrivatePtr srcpriv = QEMU_DOMAIN_STORAGE_SOURCE_PRIVATE(src);
J
Ján Tomko 已提交
2048
    g_autoptr(virJSONValue) props = NULL;
2049
    g_autofree char *cipheralg = NULL;
2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
    const char *keysecret = NULL;

    if (srcpriv &&
        srcpriv->encinfo &&
        srcpriv->encinfo->type == VIR_DOMAIN_SECRET_INFO_TYPE_AES)
        keysecret = srcpriv->encinfo->s.aes.alias;

    if (virJSONValueObjectCreate(&props,
                                 "s:key-secret", keysecret,
                                 NULL) < 0)
        return -1;

    if (src->encryption) {
        if (src->encryption->encinfo.cipher_name &&
            virAsprintf(&cipheralg, "%s-%u",
                        src->encryption->encinfo.cipher_name,
                        src->encryption->encinfo.cipher_size) < 0)
            return -1;

        if (virJSONValueObjectAdd(props,
                                  "S:cipher-alg", cipheralg,
                                  "S:cipher-mode", src->encryption->encinfo.cipher_mode,
                                  "S:hash-alg", src->encryption->encinfo.cipher_hash,
                                  "S:ivgen-alg", src->encryption->encinfo.ivgen_name,
                                  "S:ivgen-hash-alg", src->encryption->encinfo.ivgen_hash,
                                  NULL) < 0)
            return -1;
    }

    VIR_STEAL_PTR(*luksProps, props);
    return 0;
}


static int
qemuBlockStorageSourceCreateGetFormatPropsLUKS(virStorageSourcePtr src,
                                               virJSONValuePtr *props)
{
J
Ján Tomko 已提交
2088
    g_autoptr(virJSONValue) luksprops = NULL;
2089 2090 2091 2092 2093 2094 2095

    if (qemuBlockStorageSourceCreateGetEncryptionLUKS(src, &luksprops) < 0)
        return -1;

    if (virJSONValueObjectAdd(luksprops,
                              "s:driver", "luks",
                              "s:file", src->nodestorage,
2096
                              "U:size", src->capacity,
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
                              NULL) < 0)
        return -1;

    VIR_STEAL_PTR(*props, luksprops);
    return 0;
}


static int
qemuBlockStorageSourceCreateAddEncryptionQcow(virStorageSourcePtr src,
                                              virJSONValuePtr props)
{
J
Ján Tomko 已提交
2109
    g_autoptr(virJSONValue) encryptProps = NULL;
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137

    if (!src->encryption)
        return 0;

    if (src->encryption->format != VIR_STORAGE_ENCRYPTION_FORMAT_LUKS) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("creation of qcow/qcow2 files supports only 'luks' encryption"));
        return -1;
    }

    if (qemuBlockStorageSourceCreateGetEncryptionLUKS(src, &encryptProps) < 0)
        return -1;

    if (virJSONValueObjectAdd(encryptProps, "s:format", "luks", NULL) < 0)
        return -1;

    if (virJSONValueObjectAdd(props, "a:encrypt", &encryptProps, NULL) < 0)
        return -1;

    return 0;
}


static int
qemuBlockStorageSourceCreateGetFormatPropsQcow2(virStorageSourcePtr src,
                                                virStorageSourcePtr backing,
                                                virJSONValuePtr *props)
{
J
Ján Tomko 已提交
2138
    g_autoptr(virJSONValue) qcow2props = NULL;
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148
    const char *qcow2version = NULL;

    if (STREQ_NULLABLE(src->compat, "0.10"))
        qcow2version = "v2";
    else if (STREQ_NULLABLE(src->compat, "1.1"))
        qcow2version = "v3";

    if (virJSONValueObjectCreate(&qcow2props,
                                 "s:driver", "qcow2",
                                 "s:file", src->nodestorage,
2149
                                 "U:size", src->capacity,
2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
                                 "S:version", qcow2version,
                                 NULL) < 0)
        return -1;

    if (qemuBlockStorageSourceCreateAddBacking(backing, qcow2props, true) < 0 ||
        qemuBlockStorageSourceCreateAddEncryptionQcow(src, qcow2props) < 0)
        return -1;

    VIR_STEAL_PTR(*props, qcow2props);
    return 0;
}


static int
qemuBlockStorageSourceCreateGetFormatPropsQcow(virStorageSourcePtr src,
                                               virStorageSourcePtr backing,
                                               virJSONValuePtr *props)
{
J
Ján Tomko 已提交
2168
    g_autoptr(virJSONValue) qcowprops = NULL;
2169 2170 2171 2172

    if (virJSONValueObjectCreate(&qcowprops,
                                 "s:driver", "qcow",
                                 "s:file", src->nodestorage,
2173
                                 "U:size", src->capacity,
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190
                                 NULL) < 0)
        return -1;

    if (qemuBlockStorageSourceCreateAddBacking(backing, qcowprops, false) < 0 ||
        qemuBlockStorageSourceCreateAddEncryptionQcow(src, qcowprops) < 0)
        return -1;

    VIR_STEAL_PTR(*props, qcowprops);
    return 0;
}


static int
qemuBlockStorageSourceCreateGetFormatPropsQed(virStorageSourcePtr src,
                                              virStorageSourcePtr backing,
                                              virJSONValuePtr *props)
{
J
Ján Tomko 已提交
2191
    g_autoptr(virJSONValue) qedprops = NULL;
2192 2193 2194 2195

    if (virJSONValueObjectCreate(&qedprops,
                                 "s:driver", "qed",
                                 "s:file", src->nodestorage,
2196
                                 "U:size", src->capacity,
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
                                 NULL) < 0)
        return -1;

    if (qemuBlockStorageSourceCreateAddBacking(backing, qedprops, true) < 0)
        return -1;

    VIR_STEAL_PTR(*props, qedprops);
    return 0;
}


/**
 * qemuBlockStorageSourceCreateGetFormatProps:
 * @src: storage source to format
 * @backing: storage source describing backing image of @src (if necessary)
 * @props: filled with props to be used with 'blockdev-create' to format @src
 *
 * @src must be properly initialized to contain node-names of the protocol layer
 * which should be formatted. @props may be NULL with success returned in which
 * case creation of given storage format is not supported. Note that creation
 * of 'raw' storage is also returns NULL as there is nothing to do.
 */
int
qemuBlockStorageSourceCreateGetFormatProps(virStorageSourcePtr src,
                                           virStorageSourcePtr backing,
                                           virJSONValuePtr *props)
{
    switch ((virStorageFileFormat) src->format) {
    case VIR_STORAGE_FILE_RAW:
        if (!src->encryption ||
            src->encryption->format != VIR_STORAGE_ENCRYPTION_FORMAT_LUKS)
            return 0;

        return qemuBlockStorageSourceCreateGetFormatPropsLUKS(src, props);

    case VIR_STORAGE_FILE_QCOW2:
        return qemuBlockStorageSourceCreateGetFormatPropsQcow2(src, backing, props);

    case VIR_STORAGE_FILE_QCOW:
        return qemuBlockStorageSourceCreateGetFormatPropsQcow(src, backing, props);

    case VIR_STORAGE_FILE_QED:
        return qemuBlockStorageSourceCreateGetFormatPropsQed(src, backing, props);

    case VIR_STORAGE_FILE_VPC:
        return qemuBlockStorageSourceCreateGetFormatPropsGeneric(src, "vpc",
                                                                 props, NULL);

    case VIR_STORAGE_FILE_PLOOP:
        return qemuBlockStorageSourceCreateGetFormatPropsGeneric(src, "parallels",
                                                                 props, NULL);

    case VIR_STORAGE_FILE_VDI:
        return qemuBlockStorageSourceCreateGetFormatPropsGeneric(src, "vdi",
                                                                 props, NULL);

    case VIR_STORAGE_FILE_VHD:
        return qemuBlockStorageSourceCreateGetFormatPropsGeneric(src, "vhdx",
                                                                 props, NULL);

    case VIR_STORAGE_FILE_VMDK:
        return qemuBlockStorageSourceCreateGetFormatPropsGeneric(src, "vmdk",
                                                                 props, backing);

    /* unsupported by qemu / impossible */
    case VIR_STORAGE_FILE_FAT:
    case VIR_STORAGE_FILE_BOCHS:
    case VIR_STORAGE_FILE_CLOOP:
    case VIR_STORAGE_FILE_DMG:
    case VIR_STORAGE_FILE_COW:
    case VIR_STORAGE_FILE_ISO:
    case VIR_STORAGE_FILE_DIR:
        return 0;

    case VIR_STORAGE_FILE_AUTO_SAFE:
    case VIR_STORAGE_FILE_AUTO:
    case VIR_STORAGE_FILE_NONE:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("mishandled storage format '%s'"),
                       virStorageFileFormatTypeToString(src->format));
        return -1;

    case VIR_STORAGE_FILE_LAST:
    default:
        break;
    }

    virReportEnumRangeError(virStorageFileFormat, src->format);
    return -1;
}
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302


/**
 * qemuBlockStorageSourceCreateGetStorageProps:
 * @src: storage source to create
 * @props: filled with props to be used with 'blockdev-create' to create @src
 *
 * This function should be used only if @src->type is VIR_STORAGE_TYPE_NETWORK.
 * Note that @props may be NULL if qemu does not support creation storage
 * on given protocol. @src->physical is used as size for the storage.
 */
int
qemuBlockStorageSourceCreateGetStorageProps(virStorageSourcePtr src,
                                            virJSONValuePtr *props)
{
    int actualType = virStorageSourceGetActualType(src);
J
Ján Tomko 已提交
2303
    g_autoptr(virJSONValue) location = NULL;
2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368
    const char *driver = NULL;
    const char *filename = NULL;

    switch ((virStorageType) actualType) {
    case VIR_STORAGE_TYPE_FILE:
        driver = "file";
        filename = src->path;
        break;

    case VIR_STORAGE_TYPE_NETWORK:
        switch ((virStorageNetProtocol) src->protocol) {
        case VIR_STORAGE_NET_PROTOCOL_GLUSTER:
            driver = "gluster";
            if (!(location = qemuBlockStorageSourceGetGlusterProps(src, false, false)))
                return -1;
            break;

        case VIR_STORAGE_NET_PROTOCOL_RBD:
            driver = "rbd";
            if (!(location = qemuBlockStorageSourceGetRBDProps(src, false)))
                return -1;
            break;

        case VIR_STORAGE_NET_PROTOCOL_SHEEPDOG:
            driver = "sheepdog";
            if (!(location = qemuBlockStorageSourceGetSheepdogProps(src)))
                return -1;
            break;

        case VIR_STORAGE_NET_PROTOCOL_SSH:
            driver = "ssh";
            if (!(location = qemuBlockStorageSourceGetSshProps(src)))
                return -1;
            break;

            /* unsupported/impossible */
        case VIR_STORAGE_NET_PROTOCOL_NBD:
        case VIR_STORAGE_NET_PROTOCOL_ISCSI:
        case VIR_STORAGE_NET_PROTOCOL_VXHS:
        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:
        case VIR_STORAGE_NET_PROTOCOL_NONE:
        case VIR_STORAGE_NET_PROTOCOL_LAST:
            return 0;
        }
        break;

    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_DIR:
    case VIR_STORAGE_TYPE_VOLUME:
        return 0;

    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
         virReportEnumRangeError(virStorageType, actualType);
         return -1;
    }

    if (virJSONValueObjectCreate(props,
                                 "s:driver", driver,
                                 "S:filename", filename,
                                 "A:location", &location,
2369
                                 "U:size", src->physical,
2370 2371 2372 2373 2374
                                 NULL) < 0)
        return -1;

    return 0;
}
2375 2376 2377 2378 2379 2380 2381 2382 2383 2384


static int
qemuBlockStorageSourceCreateGeneric(virDomainObjPtr vm,
                                    virJSONValuePtr createProps,
                                    virStorageSourcePtr src,
                                    virStorageSourcePtr chain,
                                    bool storageCreate,
                                    qemuDomainAsyncJob asyncJob)
{
J
Ján Tomko 已提交
2385
    g_autoptr(virJSONValue) props = createProps;
2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuBlockJobDataPtr job = NULL;
    int ret = -1;
    int rc;

    if (!(job = qemuBlockJobNewCreate(vm, src, chain, storageCreate)))
        return -1;

    qemuBlockJobSyncBegin(job);

    if (qemuDomainObjEnterMonitorAsync(priv->driver, vm, asyncJob) < 0)
        goto cleanup;

    rc = qemuMonitorBlockdevCreate(priv->mon, job->name, props);
    props = NULL;

    if (qemuDomainObjExitMonitor(priv->driver, vm) < 0 || rc < 0)
        goto cleanup;

    qemuBlockJobStarted(job, vm);

    qemuBlockJobUpdate(vm, job, QEMU_ASYNC_JOB_NONE);
    while (qemuBlockJobIsRunning(job))  {
        if (virDomainObjWait(vm) < 0)
            goto cleanup;
        qemuBlockJobUpdate(vm, job, QEMU_ASYNC_JOB_NONE);
    }

    if (job->state == QEMU_BLOCKJOB_STATE_FAILED ||
        job->state == QEMU_BLOCKJOB_STATE_CANCELLED) {
        if (job->state == QEMU_BLOCKJOB_STATE_CANCELLED && !job->errmsg) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("blockdev-create job was cancelled"));
        } else {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("failed to format image: '%s'"), NULLSTR(job->errmsg));
        }
        goto cleanup;
    }

    ret = 0;

 cleanup:
    qemuBlockJobStartupFinalize(vm, job);
    return ret;
}


static int
qemuBlockStorageSourceCreateStorage(virDomainObjPtr vm,
                                    virStorageSourcePtr src,
                                    virStorageSourcePtr chain,
                                    qemuDomainAsyncJob asyncJob)
{
    int actualType = virStorageSourceGetActualType(src);
J
Ján Tomko 已提交
2441
    g_autoptr(virJSONValue) createstorageprops = NULL;
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
    int ret;

    /* We create local files directly to be able to apply security labels
     * properly. This is enough for formats which store the capacity of the image
     * in the metadata as they will grow. We must create a correctly sized
     * image for 'raw' and 'luks' though as the image size influences the
     * capacity.
     */
    if (actualType != VIR_STORAGE_TYPE_NETWORK &&
        !(actualType == VIR_STORAGE_TYPE_FILE && src->format == VIR_STORAGE_FILE_RAW))
        return 0;

    if (qemuBlockStorageSourceCreateGetStorageProps(src, &createstorageprops) < 0)
        return -1;

    if (!createstorageprops) {
        /* we can always try opening it to see whether it was existing */
        return 0;
    }

    ret = qemuBlockStorageSourceCreateGeneric(vm, createstorageprops, src, chain,
                                              true, asyncJob);
    createstorageprops = NULL;

    return ret;
}


static int
qemuBlockStorageSourceCreateFormat(virDomainObjPtr vm,
                                   virStorageSourcePtr src,
                                   virStorageSourcePtr backingStore,
                                   virStorageSourcePtr chain,
                                   qemuDomainAsyncJob asyncJob)
{
J
Ján Tomko 已提交
2477
    g_autoptr(virJSONValue) createformatprops = NULL;
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
    int ret;

    if (src->format == VIR_STORAGE_FILE_RAW)
        return 0;

    if (qemuBlockStorageSourceCreateGetFormatProps(src, backingStore,
                                                   &createformatprops) < 0)
        return -1;

    if (!createformatprops) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("can't create storage format '%s'"),
                       virStorageFileFormatTypeToString(src->format));
        return -1;
    }

    ret = qemuBlockStorageSourceCreateGeneric(vm, createformatprops, src, chain,
                                              false, asyncJob);
    createformatprops = NULL;

    return ret;
}


/**
 * qemuBlockStorageSourceCreate:
 * @vm: domain object
 * @src: storage source definition to create
 * @backingStore: backingStore of the new image (used only in image metadata)
 * @chain: backing chain to unplug in case of a long-running job failure
 * @data: qemuBlockStorageSourceAttachData for @src so that it can be attached
 * @asyncJob: qemu asynchronous job type
 *
 * Creates and formats a storage volume according to @src and attaches it to @vm.
 * @data must provide attachment data as if @src was existing. @src is attached
 * after successful return of this function. If libvirtd is restarted during
 * the create job @chain is unplugged, otherwise it's left for the caller.
 * If @backingStore is provided, the new image will refer to it as its backing
 * store.
 */
int
qemuBlockStorageSourceCreate(virDomainObjPtr vm,
                             virStorageSourcePtr src,
                             virStorageSourcePtr backingStore,
                             virStorageSourcePtr chain,
                             qemuBlockStorageSourceAttachDataPtr data,
                             qemuDomainAsyncJob asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;
    int rc;

    if (qemuDomainObjEnterMonitorAsync(priv->driver, vm, asyncJob) < 0)
        goto cleanup;

    rc = qemuBlockStorageSourceAttachApplyStorageDeps(priv->mon, data);

    if (qemuDomainObjExitMonitor(priv->driver, vm) < 0 || rc < 0)
        goto cleanup;

    if (qemuBlockStorageSourceCreateStorage(vm, src, chain, asyncJob) < 0)
        goto cleanup;

    if (qemuDomainObjEnterMonitorAsync(priv->driver, vm, asyncJob) < 0)
        goto cleanup;

    rc = qemuBlockStorageSourceAttachApplyStorage(priv->mon, data);

    if (rc == 0)
        rc = qemuBlockStorageSourceAttachApplyFormatDeps(priv->mon, data);

    if (qemuDomainObjExitMonitor(priv->driver, vm) < 0 || rc < 0)
        goto cleanup;

    if (qemuBlockStorageSourceCreateFormat(vm, src, backingStore, chain,
                                           asyncJob) < 0)
        goto cleanup;

    if (qemuDomainObjEnterMonitorAsync(priv->driver, vm, asyncJob) < 0)
        goto cleanup;

    rc = qemuBlockStorageSourceAttachApplyFormat(priv->mon, data);

    if (qemuDomainObjExitMonitor(priv->driver, vm) < 0 || rc < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    if (ret < 0 &&
        virDomainObjIsActive(vm) &&
        qemuDomainObjEnterMonitorAsync(priv->driver, vm, asyncJob) == 0) {

        qemuBlockStorageSourceAttachRollback(priv->mon, data);
        ignore_value(qemuDomainObjExitMonitor(priv->driver, vm));
    }

    return ret;
}


/**
 * qemuBlockStorageSourceCreateDetectSize:
 * @vm: domain object
 * @src: storage source to update size/capacity on
 * @templ: storage source template
 * @asyncJob: qemu asynchronous job type
 *
 * When creating a storage source via blockdev-create we need to know the size
 * and capacity of the original volume (e.g. when creating a snapshot or copy).
 * This function updates @src's 'capacity' and 'physical' attributes according
 * to the detected sizes from @templ.
 */
int
qemuBlockStorageSourceCreateDetectSize(virDomainObjPtr vm,
                                       virStorageSourcePtr src,
                                       virStorageSourcePtr templ,
                                       qemuDomainAsyncJob asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
J
Ján Tomko 已提交
2598
    g_autoptr(virHashTable) stats = NULL;
2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
    qemuBlockStatsPtr entry;
    int rc;

    if (!(stats = virHashCreate(10, virHashValueFree)))
        return -1;

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

    rc = qemuMonitorBlockStatsUpdateCapacityBlockdev(priv->mon, stats);

    if (qemuDomainObjExitMonitor(priv->driver, vm) < 0 || rc < 0)
        return -1;

    if (!(entry = virHashLookup(stats, templ->nodeformat))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("failed to update capacity data for block node '%s'"),
                       templ->nodeformat);
        return -1;
    }

    if (src->format == VIR_STORAGE_FILE_RAW) {
        src->physical = entry->capacity;
    } else {
        src->physical = entry->physical;
    }

    src->capacity = entry->capacity;

    return 0;
}