qemu_migration.c 238.3 KB
Newer Older
1 2 3
/*
 * qemu_migration.c: QEMU migration handling
 *
4
 * Copyright (C) 2006-2015 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16
 *
 * 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
17
 * License along with this library.  If not, see
O
Osier Yang 已提交
18
 * <http://www.gnu.org/licenses/>.
19 20 21 22 23
 *
 */

#include <config.h>

J
Ján Tomko 已提交
24 25
#include <netdb.h>
#include <sys/socket.h>
26
#include <sys/time.h>
27
#ifdef WITH_GNUTLS
28 29 30
# include <gnutls/gnutls.h>
# include <gnutls/x509.h>
#endif
31
#include <fcntl.h>
32
#include <poll.h>
33 34 35 36 37 38

#include "qemu_migration.h"
#include "qemu_monitor.h"
#include "qemu_domain.h"
#include "qemu_process.h"
#include "qemu_capabilities.h"
39
#include "qemu_alias.h"
40
#include "qemu_cgroup.h"
41
#include "qemu_hotplug.h"
42
#include "qemu_blockjob.h"
43
#include "qemu_security.h"
44

45
#include "domain_audit.h"
46
#include "virlog.h"
47
#include "virerror.h"
48
#include "viralloc.h"
E
Eric Blake 已提交
49
#include "virfile.h"
50
#include "virnetdevopenvswitch.h"
51 52
#include "datatypes.h"
#include "fdstream.h"
53
#include "viruuid.h"
54
#include "virtime.h"
55
#include "locking/domain_lock.h"
56
#include "rpc/virnetsocket.h"
57
#include "virstoragefile.h"
M
Martin Kletzander 已提交
58
#include "viruri.h"
59
#include "virhook.h"
60
#include "virstring.h"
61
#include "virtypedparam.h"
M
Michael R. Hines 已提交
62
#include "virprocess.h"
63
#include "nwfilter_conf.h"
64
#include "storage/storage_driver.h"
65 66 67

#define VIR_FROM_THIS VIR_FROM_QEMU

68 69
VIR_LOG_INIT("qemu.qemu_migration");

70 71 72 73 74 75 76 77 78 79 80 81 82
VIR_ENUM_IMPL(qemuMigrationJobPhase, QEMU_MIGRATION_PHASE_LAST,
              "none",
              "perform2",
              "begin3",
              "perform3",
              "perform3_done",
              "confirm3_cancelled",
              "confirm3",
              "prepare",
              "finish2",
              "finish3",
);

83 84 85 86 87
VIR_ENUM_IMPL(qemuMigrationCompressMethod, QEMU_MIGRATION_COMPRESS_LAST,
              "xbzrle",
              "mt",
);

88 89
#define QEMU_MIGRATION_TLS_ALIAS_BASE "libvirt_migrate"

90
enum qemuMigrationCookieFlags {
91
    QEMU_MIGRATION_COOKIE_FLAG_GRAPHICS,
92
    QEMU_MIGRATION_COOKIE_FLAG_LOCKSTATE,
93
    QEMU_MIGRATION_COOKIE_FLAG_PERSISTENT,
94
    QEMU_MIGRATION_COOKIE_FLAG_NETWORK,
95
    QEMU_MIGRATION_COOKIE_FLAG_NBD,
96
    QEMU_MIGRATION_COOKIE_FLAG_STATS,
97
    QEMU_MIGRATION_COOKIE_FLAG_MEMORY_HOTPLUG,
98
    QEMU_MIGRATION_COOKIE_FLAG_CPU_HOTPLUG,
99 100 101 102 103 104 105

    QEMU_MIGRATION_COOKIE_FLAG_LAST
};

VIR_ENUM_DECL(qemuMigrationCookieFlag);
VIR_ENUM_IMPL(qemuMigrationCookieFlag,
              QEMU_MIGRATION_COOKIE_FLAG_LAST,
106 107 108 109
              "graphics",
              "lockstate",
              "persistent",
              "network",
110
              "nbd",
111
              "statistics",
112 113
              "memory-hotplug",
              "cpu-hotplug");
114 115 116

enum qemuMigrationCookieFeatures {
    QEMU_MIGRATION_COOKIE_GRAPHICS  = (1 << QEMU_MIGRATION_COOKIE_FLAG_GRAPHICS),
117
    QEMU_MIGRATION_COOKIE_LOCKSTATE = (1 << QEMU_MIGRATION_COOKIE_FLAG_LOCKSTATE),
118
    QEMU_MIGRATION_COOKIE_PERSISTENT = (1 << QEMU_MIGRATION_COOKIE_FLAG_PERSISTENT),
119
    QEMU_MIGRATION_COOKIE_NETWORK = (1 << QEMU_MIGRATION_COOKIE_FLAG_NETWORK),
120
    QEMU_MIGRATION_COOKIE_NBD = (1 << QEMU_MIGRATION_COOKIE_FLAG_NBD),
121
    QEMU_MIGRATION_COOKIE_STATS = (1 << QEMU_MIGRATION_COOKIE_FLAG_STATS),
122
    QEMU_MIGRATION_COOKIE_MEMORY_HOTPLUG = (1 << QEMU_MIGRATION_COOKIE_FLAG_MEMORY_HOTPLUG),
123
    QEMU_MIGRATION_COOKIE_CPU_HOTPLUG = (1 << QEMU_MIGRATION_COOKIE_FLAG_CPU_HOTPLUG),
124 125 126 127 128 129 130 131 132 133 134 135
};

typedef struct _qemuMigrationCookieGraphics qemuMigrationCookieGraphics;
typedef qemuMigrationCookieGraphics *qemuMigrationCookieGraphicsPtr;
struct _qemuMigrationCookieGraphics {
    int type;
    int port;
    int tlsPort;
    char *listen;
    char *tlsSubject;
};

136 137 138 139 140 141
typedef struct _qemuMigrationCookieNetData qemuMigrationCookieNetData;
typedef qemuMigrationCookieNetData *qemuMigrationCookieNetDataPtr;
struct _qemuMigrationCookieNetData {
    int vporttype; /* enum virNetDevVPortProfile */

    /*
142
     * Array of pointers to saved data. Each VIF will have its own
143 144 145 146 147 148 149 150 151 152 153 154 155 156
     * data to transfer.
     */
    char *portdata;
};

typedef struct _qemuMigrationCookieNetwork qemuMigrationCookieNetwork;
typedef qemuMigrationCookieNetwork *qemuMigrationCookieNetworkPtr;
struct _qemuMigrationCookieNetwork {
    /* How many virtual NICs are we saving data for? */
    int nnets;

    qemuMigrationCookieNetDataPtr net;
};

157 158 159 160
typedef struct _qemuMigrationCookieNBD qemuMigrationCookieNBD;
typedef qemuMigrationCookieNBD *qemuMigrationCookieNBDPtr;
struct _qemuMigrationCookieNBD {
    int port; /* on which port does NBD server listen for incoming data */
161 162 163 164 165 166

    size_t ndisks;  /* Number of items in @disk array */
    struct {
        char *target;                   /* Disk target */
        unsigned long long capacity;    /* And its capacity */
    } *disks;
167 168
};

169 170 171
typedef struct _qemuMigrationCookie qemuMigrationCookie;
typedef qemuMigrationCookie *qemuMigrationCookiePtr;
struct _qemuMigrationCookie {
E
Eric Blake 已提交
172 173
    unsigned int flags;
    unsigned int flagsMandatory;
174 175

    /* Host properties */
176 177 178 179
    unsigned char localHostuuid[VIR_UUID_BUFLEN];
    unsigned char remoteHostuuid[VIR_UUID_BUFLEN];
    char *localHostname;
    char *remoteHostname;
180 181 182 183

    /* Guest properties */
    unsigned char uuid[VIR_UUID_BUFLEN];
    char *name;
184

185 186 187 188
    /* If (flags & QEMU_MIGRATION_COOKIE_LOCKSTATE) */
    char *lockState;
    char *lockDriver;

189 190
    /* If (flags & QEMU_MIGRATION_COOKIE_GRAPHICS) */
    qemuMigrationCookieGraphicsPtr graphics;
191 192 193

    /* If (flags & QEMU_MIGRATION_COOKIE_PERSISTENT) */
    virDomainDefPtr persistent;
194 195 196

    /* If (flags & QEMU_MIGRATION_COOKIE_NETWORK) */
    qemuMigrationCookieNetworkPtr network;
197 198 199

    /* If (flags & QEMU_MIGRATION_COOKIE_NBD) */
    qemuMigrationCookieNBDPtr nbd;
200 201 202

    /* If (flags & QEMU_MIGRATION_COOKIE_STATS) */
    qemuDomainJobInfoPtr jobInfo;
203 204
};

205 206 207 208 209 210 211 212 213
static void qemuMigrationCookieGraphicsFree(qemuMigrationCookieGraphicsPtr grap)
{
    if (!grap)
        return;
    VIR_FREE(grap->listen);
    VIR_FREE(grap->tlsSubject);
    VIR_FREE(grap);
}

214

215 216 217
static void
qemuMigrationCookieNetworkFree(qemuMigrationCookieNetworkPtr network)
{
218
    size_t i;
219 220 221 222 223 224 225 226 227 228 229 230 231

    if (!network)
        return;

    if (network->net) {
        for (i = 0; i < network->nnets; i++)
            VIR_FREE(network->net[i].portdata);
    }
    VIR_FREE(network->net);
    VIR_FREE(network);
}


232 233 234 235 236 237 238 239 240 241 242 243
static void qemuMigrationCookieNBDFree(qemuMigrationCookieNBDPtr nbd)
{
    if (!nbd)
        return;

    while (nbd->ndisks)
        VIR_FREE(nbd->disks[--nbd->ndisks].target);
    VIR_FREE(nbd->disks);
    VIR_FREE(nbd);
}


244 245 246 247 248
static void qemuMigrationCookieFree(qemuMigrationCookiePtr mig)
{
    if (!mig)
        return;

249 250
    qemuMigrationCookieGraphicsFree(mig->graphics);
    qemuMigrationCookieNetworkFree(mig->network);
251
    qemuMigrationCookieNBDFree(mig->nbd);
252

253 254
    VIR_FREE(mig->localHostname);
    VIR_FREE(mig->remoteHostname);
255
    VIR_FREE(mig->name);
256 257
    VIR_FREE(mig->lockState);
    VIR_FREE(mig->lockDriver);
258
    VIR_FREE(mig->jobInfo);
259 260 261 262
    VIR_FREE(mig);
}


263
#ifdef WITH_GNUTLS
264 265 266 267 268 269 270 271 272 273 274 275
static char *
qemuDomainExtractTLSSubject(const char *certdir)
{
    char *certfile = NULL;
    char *subject = NULL;
    char *pemdata = NULL;
    gnutls_datum_t pemdatum;
    gnutls_x509_crt_t cert;
    int ret;
    size_t subjectlen;

    if (virAsprintf(&certfile, "%s/server-cert.pem", certdir) < 0)
276
        goto error;
277 278

    if (virFileReadAll(certfile, 8192, &pemdata) < 0) {
279 280
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to read server cert %s"), certfile);
281 282 283 284 285
        goto error;
    }

    ret = gnutls_x509_crt_init(&cert);
    if (ret < 0) {
286 287 288
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot initialize cert object: %s"),
                       gnutls_strerror(ret));
289 290 291 292 293 294 295 296
        goto error;
    }

    pemdatum.data = (unsigned char *)pemdata;
    pemdatum.size = strlen(pemdata);

    ret = gnutls_x509_crt_import(cert, &pemdatum, GNUTLS_X509_FMT_PEM);
    if (ret < 0) {
297 298 299
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot load cert data from %s: %s"),
                       certfile, gnutls_strerror(ret));
300 301 302 303 304
        goto error;
    }

    subjectlen = 1024;
    if (VIR_ALLOC_N(subject, subjectlen+1) < 0)
305
        goto error;
306 307 308 309 310 311 312 313 314

    gnutls_x509_crt_get_dn(cert, subject, &subjectlen);
    subject[subjectlen] = '\0';

    VIR_FREE(certfile);
    VIR_FREE(pemdata);

    return subject;

315
 error:
316 317 318 319
    VIR_FREE(certfile);
    VIR_FREE(pemdata);
    return NULL;
}
320
#endif
321 322

static qemuMigrationCookieGraphicsPtr
323
qemuMigrationCookieGraphicsSpiceAlloc(virQEMUDriverPtr driver,
324 325
                                      virDomainGraphicsDefPtr def,
                                      virDomainGraphicsListenDefPtr glisten)
326 327 328
{
    qemuMigrationCookieGraphicsPtr mig = NULL;
    const char *listenAddr;
329
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
330 331

    if (VIR_ALLOC(mig) < 0)
332
        goto error;
333

334
    mig->type = VIR_DOMAIN_GRAPHICS_TYPE_SPICE;
335 336 337 338 339
    mig->port = def->data.spice.port;
    if (cfg->spiceTLS)
        mig->tlsPort = def->data.spice.tlsPort;
    else
        mig->tlsPort = -1;
340

341
    if (!glisten || !(listenAddr = glisten->address))
342
        listenAddr = cfg->spiceListen;
343

344
#ifdef WITH_GNUTLS
345 346 347
    if (cfg->spiceTLS &&
        !(mig->tlsSubject = qemuDomainExtractTLSSubject(cfg->spiceTLSx509certdir)))
        goto error;
348
#endif
349 350
    if (VIR_STRDUP(mig->listen, listenAddr) < 0)
        goto error;
351

352
    virObjectUnref(cfg);
353 354
    return mig;

355
 error:
356
    qemuMigrationCookieGraphicsFree(mig);
357
    virObjectUnref(cfg);
358 359 360 361
    return NULL;
}


362
static qemuMigrationCookieNetworkPtr
363
qemuMigrationCookieNetworkAlloc(virQEMUDriverPtr driver ATTRIBUTE_UNUSED,
364 365 366
                                virDomainDefPtr def)
{
    qemuMigrationCookieNetworkPtr mig;
367
    size_t i;
368 369

    if (VIR_ALLOC(mig) < 0)
370
        goto error;
371 372 373 374

    mig->nnets = def->nnets;

    if (VIR_ALLOC_N(mig->net, def->nnets) <0)
375
        goto error;
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390

    for (i = 0; i < def->nnets; i++) {
        virDomainNetDefPtr netptr;
        virNetDevVPortProfilePtr vport;

        netptr = def->nets[i];
        vport = virDomainNetGetActualVirtPortProfile(netptr);

        if (vport) {
            mig->net[i].vporttype = vport->virtPortType;

            switch (vport->virtPortType) {
            case VIR_NETDEV_VPORT_PROFILE_NONE:
            case VIR_NETDEV_VPORT_PROFILE_8021QBG:
            case VIR_NETDEV_VPORT_PROFILE_8021QBH:
391
               break;
392
            case VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH:
393 394
                if (virNetDevOpenvswitchGetMigrateData(&mig->net[i].portdata,
                                                       netptr->ifname) != 0) {
J
Jiri Denemark 已提交
395 396 397
                        virReportError(VIR_ERR_INTERNAL_ERROR,
                                       _("Unable to run command to get OVS port data for "
                                         "interface %s"), netptr->ifname);
398 399 400
                        goto error;
                }
                break;
401 402 403 404 405 406 407
            default:
                break;
            }
        }
    }
    return mig;

408
 error:
409 410 411 412
    qemuMigrationCookieNetworkFree(mig);
    return NULL;
}

413 414 415
static qemuMigrationCookiePtr
qemuMigrationCookieNew(virDomainObjPtr dom)
{
J
Jiri Denemark 已提交
416
    qemuDomainObjPrivatePtr priv = dom->privateData;
417
    qemuMigrationCookiePtr mig = NULL;
J
Jiri Denemark 已提交
418
    const char *name;
419 420

    if (VIR_ALLOC(mig) < 0)
421
        goto error;
422

J
Jiri Denemark 已提交
423 424 425 426
    if (priv->origname)
        name = priv->origname;
    else
        name = dom->def->name;
427 428
    if (VIR_STRDUP(mig->name, name) < 0)
        goto error;
429 430
    memcpy(mig->uuid, dom->def->uuid, VIR_UUID_BUFLEN);

431
    if (!(mig->localHostname = virGetHostname()))
432
        goto error;
433
    if (virGetHostUUID(mig->localHostuuid) < 0) {
434 435
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Unable to obtain host UUID"));
436 437 438 439 440
        goto error;
    }

    return mig;

441
 error:
442 443 444 445 446
    qemuMigrationCookieFree(mig);
    return NULL;
}


447 448
static int
qemuMigrationCookieAddGraphics(qemuMigrationCookiePtr mig,
449
                               virQEMUDriverPtr driver,
450 451
                               virDomainObjPtr dom)
{
452 453
    size_t i = 0;

454
    if (mig->flags & QEMU_MIGRATION_COOKIE_GRAPHICS) {
455 456
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Migration graphics data already present"));
457 458 459
        return -1;
    }

460
    for (i = 0; i < dom->def->ngraphics; i++) {
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
        if (dom->def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
            virDomainGraphicsListenDefPtr glisten =
                virDomainGraphicsGetListen(dom->def->graphics[i], 0);

            if (!glisten) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("missing listen element"));
                return -1;
            }

            switch (glisten->type) {
            case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_ADDRESS:
            case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NETWORK:
                /* Seamless migration is supported only for listen types
                 * 'address and 'network'. */
                if (!(mig->graphics =
                      qemuMigrationCookieGraphicsSpiceAlloc(driver,
                                                            dom->def->graphics[i],
                                                            glisten)))
                    return -1;
                mig->flags |= QEMU_MIGRATION_COOKIE_GRAPHICS;
                break;

            case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_SOCKET:
            case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_NONE:
            case VIR_DOMAIN_GRAPHICS_LISTEN_TYPE_LAST:
                break;
            }

            /* Seamless migration is supported only for one graphics. */
            if (mig->graphics)
                break;
        }
494
    }
495 496 497 498 499

    return 0;
}


500 501
static int
qemuMigrationCookieAddLockstate(qemuMigrationCookiePtr mig,
502
                                virQEMUDriverPtr driver,
503 504 505 506 507
                                virDomainObjPtr dom)
{
    qemuDomainObjPrivatePtr priv = dom->privateData;

    if (mig->flags & QEMU_MIGRATION_COOKIE_LOCKSTATE) {
508 509
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Migration lockstate data already present"));
510 511 512 513
        return -1;
    }

    if (virDomainObjGetState(dom, NULL) == VIR_DOMAIN_PAUSED) {
514
        if (VIR_STRDUP(mig->lockState, priv->lockState) < 0)
515 516 517 518 519 520
            return -1;
    } else {
        if (virDomainLockProcessInquire(driver->lockManager, dom, &mig->lockState) < 0)
            return -1;
    }

521
    if (VIR_STRDUP(mig->lockDriver, virLockManagerPluginGetName(driver->lockManager)) < 0) {
522 523 524 525 526 527 528 529 530 531 532
        VIR_FREE(mig->lockState);
        return -1;
    }

    mig->flags |= QEMU_MIGRATION_COOKIE_LOCKSTATE;
    mig->flagsMandatory |= QEMU_MIGRATION_COOKIE_LOCKSTATE;

    return 0;
}


533 534
static int
qemuMigrationCookieAddPersistent(qemuMigrationCookiePtr mig,
535
                                 virDomainDefPtr def)
536 537
{
    if (mig->flags & QEMU_MIGRATION_COOKIE_PERSISTENT) {
538 539
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Migration persistent data already present"));
540 541 542
        return -1;
    }

543
    if (!def)
544 545
        return 0;

546
    mig->persistent = def;
547 548 549 550 551 552
    mig->flags |= QEMU_MIGRATION_COOKIE_PERSISTENT;
    mig->flagsMandatory |= QEMU_MIGRATION_COOKIE_PERSISTENT;
    return 0;
}


553 554 555 556 557 558 559 560 561 562 563 564 565
static virDomainDefPtr
qemuMigrationCookieGetPersistent(qemuMigrationCookiePtr mig)
{
    virDomainDefPtr def = mig->persistent;

    mig->persistent = NULL;
    mig->flags &= ~QEMU_MIGRATION_COOKIE_PERSISTENT;
    mig->flagsMandatory &= ~QEMU_MIGRATION_COOKIE_PERSISTENT;

    return def;
}


566 567
static int
qemuMigrationCookieAddNetwork(qemuMigrationCookiePtr mig,
568
                              virQEMUDriverPtr driver,
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
                              virDomainObjPtr dom)
{
    if (mig->flags & QEMU_MIGRATION_COOKIE_NETWORK) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Network migration data already present"));
        return -1;
    }

    if (dom->def->nnets > 0) {
        mig->network = qemuMigrationCookieNetworkAlloc(driver, dom->def);
        if (!mig->network)
            return -1;
        mig->flags |= QEMU_MIGRATION_COOKIE_NETWORK;
    }

    return 0;
}

587

588 589
static int
qemuMigrationCookieAddNBD(qemuMigrationCookiePtr mig,
590
                          virQEMUDriverPtr driver,
591 592 593
                          virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
594 595
    virHashTablePtr stats = NULL;
    size_t i;
596
    int ret = -1, rc;
597 598

    /* It is not a bug if there already is a NBD data */
599 600 601
    qemuMigrationCookieNBDFree(mig->nbd);

    if (VIR_ALLOC(mig->nbd) < 0)
602 603
        return -1;

604 605 606 607 608 609 610 611 612 613 614 615 616
    if (vm->def->ndisks &&
        VIR_ALLOC_N(mig->nbd->disks, vm->def->ndisks) < 0)
        return -1;
    mig->nbd->ndisks = 0;

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

        if (!stats) {
            if (!(stats = virHashCreate(10, virHashValueFree)))
                goto cleanup;

617 618 619
            if (qemuDomainObjEnterMonitorAsync(driver, vm,
                                               priv->job.asyncJob) < 0)
                goto cleanup;
620 621
            rc = qemuMonitorBlockStatsUpdateCapacity(priv->mon, stats, false);
            if (qemuDomainObjExitMonitor(driver, vm) < 0)
622
                goto cleanup;
623
            if (rc < 0)
624 625 626 627 628 629 630 631 632 633 634 635 636 637
                goto cleanup;
        }

        if (!disk->info.alias ||
            !(entry = virHashLookup(stats, disk->info.alias)))
            continue;

        if (VIR_STRDUP(mig->nbd->disks[mig->nbd->ndisks].target,
                       disk->dst) < 0)
            goto cleanup;
        mig->nbd->disks[mig->nbd->ndisks].capacity = entry->capacity;
        mig->nbd->ndisks++;
    }

638 639 640
    mig->nbd->port = priv->nbdPort;
    mig->flags |= QEMU_MIGRATION_COOKIE_NBD;

641 642 643 644
    ret = 0;
 cleanup:
    virHashFree(stats);
    return ret;
645 646 647
}


648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
static int
qemuMigrationCookieAddStatistics(qemuMigrationCookiePtr mig,
                                 virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!priv->job.completed)
        return 0;

    if (!mig->jobInfo && VIR_ALLOC(mig->jobInfo) < 0)
        return -1;

    *mig->jobInfo = *priv->job.completed;
    mig->flags |= QEMU_MIGRATION_COOKIE_STATS;

    return 0;
}


667 668 669
static void qemuMigrationCookieGraphicsXMLFormat(virBufferPtr buf,
                                                 qemuMigrationCookieGraphicsPtr grap)
{
670
    virBufferAsprintf(buf, "<graphics type='%s' port='%d' listen='%s'",
671 672 673 674 675 676
                      virDomainGraphicsTypeToString(grap->type),
                      grap->port, grap->listen);
    if (grap->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE)
        virBufferAsprintf(buf, " tlsPort='%d'", grap->tlsPort);
    if (grap->tlsSubject) {
        virBufferAddLit(buf, ">\n");
677 678 679 680
        virBufferAdjustIndent(buf, 2);
        virBufferEscapeString(buf, "<cert info='subject' value='%s'/>\n", grap->tlsSubject);
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</graphics>\n");
681 682 683 684 685 686
    } else {
        virBufferAddLit(buf, "/>\n");
    }
}


687 688 689 690
static void
qemuMigrationCookieNetworkXMLFormat(virBufferPtr buf,
                                    qemuMigrationCookieNetworkPtr optr)
{
691
    size_t i;
692 693 694 695 696 697
    bool empty = true;

    for (i = 0; i < optr->nnets; i++) {
        /* If optr->net[i].vporttype is not set, there is nothing to transfer */
        if (optr->net[i].vporttype != VIR_NETDEV_VPORT_PROFILE_NONE) {
            if (empty) {
698 699
                virBufferAddLit(buf, "<network>\n");
                virBufferAdjustIndent(buf, 2);
700 701
                empty = false;
            }
702
            virBufferAsprintf(buf, "<interface index='%zu' vporttype='%s'",
703 704 705
                              i, virNetDevVPortTypeToString(optr->net[i].vporttype));
            if (optr->net[i].portdata) {
                virBufferAddLit(buf, ">\n");
706 707
                virBufferAdjustIndent(buf, 2);
                virBufferEscapeString(buf, "<portdata>%s</portdata>\n",
708
                                      optr->net[i].portdata);
709 710
                virBufferAdjustIndent(buf, -2);
                virBufferAddLit(buf, "</interface>\n");
711 712 713 714 715
            } else {
                virBufferAddLit(buf, "/>\n");
            }
        }
    }
716 717 718 719
    if (!empty) {
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</network>\n");
    }
720 721 722
}


723 724 725 726
static void
qemuMigrationCookieStatisticsXMLFormat(virBufferPtr buf,
                                       qemuDomainJobInfoPtr jobInfo)
{
727
    qemuMonitorMigrationStats *stats = &jobInfo->stats;
728 729 730 731

    virBufferAddLit(buf, "<statistics>\n");
    virBufferAdjustIndent(buf, 2);

732 733
    virBufferAsprintf(buf, "<started>%llu</started>\n", jobInfo->started);
    virBufferAsprintf(buf, "<stopped>%llu</stopped>\n", jobInfo->stopped);
734 735 736
    virBufferAsprintf(buf, "<sent>%llu</sent>\n", jobInfo->sent);
    if (jobInfo->timeDeltaSet)
        virBufferAsprintf(buf, "<delta>%lld</delta>\n", jobInfo->timeDelta);
737

738 739 740 741 742 743
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_TIME_ELAPSED,
                      jobInfo->timeElapsed);
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_TIME_REMAINING,
                      jobInfo->timeRemaining);
744
    if (stats->downtime_set)
745 746
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_DOWNTIME,
747 748
                          stats->downtime);
    if (stats->setup_time_set)
749 750
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_SETUP_TIME,
751
                          stats->setup_time);
752 753 754

    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_MEMORY_TOTAL,
755
                      stats->ram_total);
756 757
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_MEMORY_PROCESSED,
758
                      stats->ram_transferred);
759 760
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_MEMORY_REMAINING,
761
                      stats->ram_remaining);
762 763
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_MEMORY_BPS,
764
                      stats->ram_bps);
765

766
    if (stats->ram_duplicate_set) {
767 768
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_MEMORY_CONSTANT,
769
                          stats->ram_duplicate);
770 771
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_MEMORY_NORMAL,
772
                          stats->ram_normal);
773 774
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES,
775
                          stats->ram_normal_bytes);
776 777
    }

778 779 780 781 782 783 784
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_MEMORY_DIRTY_RATE,
                      stats->ram_dirty_rate);
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_MEMORY_ITERATION,
                      stats->ram_iteration);

785 786
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_DISK_TOTAL,
787
                      stats->disk_total);
788 789
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_DISK_PROCESSED,
790
                      stats->disk_transferred);
791 792
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_DISK_REMAINING,
793
                      stats->disk_remaining);
794 795
    virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                      VIR_DOMAIN_JOB_DISK_BPS,
796
                      stats->disk_bps);
797

798
    if (stats->xbzrle_set) {
799 800
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_COMPRESSION_CACHE,
801
                          stats->xbzrle_cache_size);
802 803
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_COMPRESSION_BYTES,
804
                          stats->xbzrle_bytes);
805 806
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_COMPRESSION_PAGES,
807
                          stats->xbzrle_pages);
808 809
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_COMPRESSION_CACHE_MISSES,
810
                          stats->xbzrle_cache_miss);
811 812
        virBufferAsprintf(buf, "<%1$s>%2$llu</%1$s>\n",
                          VIR_DOMAIN_JOB_COMPRESSION_OVERFLOW,
813
                          stats->xbzrle_overflow);
814 815
    }

816 817 818 819
    virBufferAsprintf(buf, "<%1$s>%2$d</%1$s>\n",
                      VIR_DOMAIN_JOB_AUTO_CONVERGE_THROTTLE,
                      stats->cpu_throttle_percentage);

820 821 822 823 824
    virBufferAdjustIndent(buf, -2);
    virBufferAddLit(buf, "</statistics>\n");
}


825
static int
826
qemuMigrationCookieXMLFormat(virQEMUDriverPtr driver,
827
                             virBufferPtr buf,
828
                             qemuMigrationCookiePtr mig)
829 830 831
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
    char hostuuidstr[VIR_UUID_STRING_BUFLEN];
832
    size_t i;
833 834

    virUUIDFormat(mig->uuid, uuidstr);
835
    virUUIDFormat(mig->localHostuuid, hostuuidstr);
836

837
    virBufferAddLit(buf, "<qemu-migration>\n");
838 839 840 841 842
    virBufferAdjustIndent(buf, 2);
    virBufferEscapeString(buf, "<name>%s</name>\n", mig->name);
    virBufferAsprintf(buf, "<uuid>%s</uuid>\n", uuidstr);
    virBufferEscapeString(buf, "<hostname>%s</hostname>\n", mig->localHostname);
    virBufferAsprintf(buf, "<hostuuid>%s</hostuuid>\n", hostuuidstr);
843

844
    for (i = 0; i < QEMU_MIGRATION_COOKIE_FLAG_LAST; i++) {
845
        if (mig->flagsMandatory & (1 << i))
846
            virBufferAsprintf(buf, "<feature name='%s'/>\n",
847 848 849
                              qemuMigrationCookieFlagTypeToString(i));
    }

850 851
    if ((mig->flags & QEMU_MIGRATION_COOKIE_GRAPHICS) &&
        mig->graphics)
852 853
        qemuMigrationCookieGraphicsXMLFormat(buf, mig->graphics);

854 855
    if ((mig->flags & QEMU_MIGRATION_COOKIE_LOCKSTATE) &&
        mig->lockState) {
856
        virBufferAsprintf(buf, "<lockstate driver='%s'>\n",
857
                          mig->lockDriver);
858 859
        virBufferAdjustIndent(buf, 2);
        virBufferAsprintf(buf, "<leases>%s</leases>\n",
860
                          mig->lockState);
861 862
        virBufferAdjustIndent(buf, -2);
        virBufferAddLit(buf, "</lockstate>\n");
863 864
    }

865 866
    if ((mig->flags & QEMU_MIGRATION_COOKIE_PERSISTENT) &&
        mig->persistent) {
867 868 869
        if (qemuDomainDefFormatBuf(driver,
                                   mig->persistent,
                                   VIR_DOMAIN_XML_INACTIVE |
870 871
                                   VIR_DOMAIN_XML_SECURE |
                                   VIR_DOMAIN_XML_MIGRATABLE,
872
                                   buf) < 0)
873
            return -1;
874 875
    }

876 877 878
    if ((mig->flags & QEMU_MIGRATION_COOKIE_NETWORK) && mig->network)
        qemuMigrationCookieNetworkXMLFormat(buf, mig->network);

879
    if ((mig->flags & QEMU_MIGRATION_COOKIE_NBD) && mig->nbd) {
880
        virBufferAddLit(buf, "<nbd");
881 882
        if (mig->nbd->port)
            virBufferAsprintf(buf, " port='%d'", mig->nbd->port);
883 884 885 886 887 888 889 890 891 892 893 894 895 896
        if (mig->nbd->ndisks) {
            virBufferAddLit(buf, ">\n");
            virBufferAdjustIndent(buf, 2);
            for (i = 0; i < mig->nbd->ndisks; i++) {
                virBufferEscapeString(buf, "<disk target='%s'",
                                      mig->nbd->disks[i].target);
                virBufferAsprintf(buf, " capacity='%llu'/>\n",
                                  mig->nbd->disks[i].capacity);
            }
            virBufferAdjustIndent(buf, -2);
            virBufferAddLit(buf, "</nbd>\n");
        } else {
            virBufferAddLit(buf, "/>\n");
        }
897 898
    }

899 900 901
    if (mig->flags & QEMU_MIGRATION_COOKIE_STATS && mig->jobInfo)
        qemuMigrationCookieStatisticsXMLFormat(buf, mig->jobInfo);

902
    virBufferAdjustIndent(buf, -2);
903
    virBufferAddLit(buf, "</qemu-migration>\n");
904
    return 0;
905 906 907
}


908
static char *qemuMigrationCookieXMLFormatStr(virQEMUDriverPtr driver,
909
                                             qemuMigrationCookiePtr mig)
910 911 912
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;

913
    if (qemuMigrationCookieXMLFormat(driver, &buf, mig) < 0) {
914 915 916
        virBufferFreeAndReset(&buf);
        return NULL;
    }
917

918
    if (virBufferCheckError(&buf) < 0)
919 920 921 922 923 924
        return NULL;

    return virBufferContentAndReset(&buf);
}


925 926 927 928 929 930 931
static qemuMigrationCookieGraphicsPtr
qemuMigrationCookieGraphicsXMLParse(xmlXPathContextPtr ctxt)
{
    qemuMigrationCookieGraphicsPtr grap;
    char *tmp;

    if (VIR_ALLOC(grap) < 0)
932
        goto error;
933 934

    if (!(tmp = virXPathString("string(./graphics/@type)", ctxt))) {
935 936
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing type attribute in migration data"));
937 938 939
        goto error;
    }
    if ((grap->type = virDomainGraphicsTypeFromString(tmp)) < 0) {
940 941
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unknown graphics type %s"), tmp);
942 943 944
        VIR_FREE(tmp);
        goto error;
    }
E
Eric Blake 已提交
945
    VIR_FREE(tmp);
946
    if (virXPathInt("string(./graphics/@port)", ctxt, &grap->port) < 0) {
947 948
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing port attribute in migration data"));
949 950 951 952
        goto error;
    }
    if (grap->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
        if (virXPathInt("string(./graphics/@tlsPort)", ctxt, &grap->tlsPort) < 0) {
953 954
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("missing tlsPort attribute in migration data"));
955 956 957 958
            goto error;
        }
    }
    if (!(grap->listen = virXPathString("string(./graphics/@listen)", ctxt))) {
959 960
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing listen attribute in migration data"));
961 962 963
        goto error;
    }
    /* Optional */
964
    grap->tlsSubject = virXPathString("string(./graphics/cert[@info='subject']/@value)", ctxt);
965 966 967

    return grap;

968
 error:
969 970 971 972 973
    qemuMigrationCookieGraphicsFree(grap);
    return NULL;
}


974 975 976 977
static qemuMigrationCookieNetworkPtr
qemuMigrationCookieNetworkXMLParse(xmlXPathContextPtr ctxt)
{
    qemuMigrationCookieNetworkPtr optr;
978
    size_t i;
979 980 981 982 983 984
    int n;
    xmlNodePtr *interfaces = NULL;
    char *vporttype;
    xmlNodePtr save_ctxt = ctxt->node;

    if (VIR_ALLOC(optr) < 0)
985
        goto error;
986 987 988 989 990 991 992 993

    if ((n = virXPathNodeSet("./network/interface", ctxt, &interfaces)) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing interface information"));
        goto error;
    }

    optr->nnets = n;
994
    if (VIR_ALLOC_N(optr->net, optr->nnets) < 0)
995
        goto error;
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

    for (i = 0; i < n; i++) {
        /* portdata is optional, and may not exist */
        ctxt->node = interfaces[i];
        optr->net[i].portdata = virXPathString("string(./portdata[1])", ctxt);

        if (!(vporttype = virXMLPropString(interfaces[i], "vporttype"))) {
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("missing vporttype attribute in migration data"));
            goto error;
        }
        optr->net[i].vporttype = virNetDevVPortTypeFromString(vporttype);
    }

    VIR_FREE(interfaces);

1012
 cleanup:
1013 1014 1015
    ctxt->node = save_ctxt;
    return optr;

1016
 error:
1017 1018 1019 1020 1021 1022 1023
    VIR_FREE(interfaces);
    qemuMigrationCookieNetworkFree(optr);
    optr = NULL;
    goto cleanup;
}


1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
static qemuMigrationCookieNBDPtr
qemuMigrationCookieNBDXMLParse(xmlXPathContextPtr ctxt)
{
    qemuMigrationCookieNBDPtr ret = NULL;
    char *port = NULL, *capacity = NULL;
    size_t i;
    int n;
    xmlNodePtr *disks = NULL;
    xmlNodePtr save_ctxt = ctxt->node;

    if (VIR_ALLOC(ret) < 0)
        goto error;

    port = virXPathString("string(./nbd/@port)", ctxt);
    if (port && virStrToLong_i(port, NULL, 10, &ret->port) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Malformed nbd port '%s'"),
                       port);
        goto error;
    }

    /* Now check if source sent a list of disks to prealloc. We might be
     * talking to an older server, so it's not an error if the list is
     * missing. */
    if ((n = virXPathNodeSet("./nbd/disk", ctxt, &disks)) > 0) {
        if (VIR_ALLOC_N(ret->disks, n) < 0)
            goto error;
        ret->ndisks = n;

        for (i = 0; i < n; i++) {
            ctxt->node = disks[i];
            VIR_FREE(capacity);

            if (!(ret->disks[i].target = virXPathString("string(./@target)", ctxt))) {
                virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                               _("Malformed disk target"));
                goto error;
            }

            capacity = virXPathString("string(./@capacity)", ctxt);
            if (!capacity ||
                virStrToLong_ull(capacity, NULL, 10,
                                 &ret->disks[i].capacity) < 0) {
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Malformed disk capacity: '%s'"),
                               NULLSTR(capacity));
                goto error;
            }
        }
    }

 cleanup:
    VIR_FREE(port);
    VIR_FREE(capacity);
    VIR_FREE(disks);
    ctxt->node = save_ctxt;
    return ret;
 error:
    qemuMigrationCookieNBDFree(ret);
    ret = NULL;
    goto cleanup;
}


1088 1089 1090 1091
static qemuDomainJobInfoPtr
qemuMigrationCookieStatisticsXMLParse(xmlXPathContextPtr ctxt)
{
    qemuDomainJobInfoPtr jobInfo = NULL;
1092
    qemuMonitorMigrationStats *stats;
1093 1094 1095 1096 1097 1098 1099 1100
    xmlNodePtr save_ctxt = ctxt->node;

    if (!(ctxt->node = virXPathNode("./statistics", ctxt)))
        goto cleanup;

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

1101
    stats = &jobInfo->stats;
1102 1103
    jobInfo->type = VIR_DOMAIN_JOB_COMPLETED;

1104 1105
    virXPathULongLong("string(./started[1])", ctxt, &jobInfo->started);
    virXPathULongLong("string(./stopped[1])", ctxt, &jobInfo->stopped);
1106 1107 1108
    virXPathULongLong("string(./sent[1])", ctxt, &jobInfo->sent);
    if (virXPathLongLong("string(./delta[1])", ctxt, &jobInfo->timeDelta) == 0)
        jobInfo->timeDeltaSet = true;
1109

1110 1111 1112 1113
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_TIME_ELAPSED "[1])",
                      ctxt, &jobInfo->timeElapsed);
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_TIME_REMAINING "[1])",
                      ctxt, &jobInfo->timeRemaining);
1114

1115
    if (virXPathULongLong("string(./" VIR_DOMAIN_JOB_DOWNTIME "[1])",
1116 1117
                          ctxt, &stats->downtime) == 0)
        stats->downtime_set = true;
1118
    if (virXPathULongLong("string(./" VIR_DOMAIN_JOB_SETUP_TIME "[1])",
1119 1120
                          ctxt, &stats->setup_time) == 0)
        stats->setup_time_set = true;
1121 1122

    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_TOTAL "[1])",
1123
                      ctxt, &stats->ram_total);
1124
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_PROCESSED "[1])",
1125
                      ctxt, &stats->ram_transferred);
1126
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_REMAINING "[1])",
1127
                      ctxt, &stats->ram_remaining);
1128
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_BPS "[1])",
1129
                      ctxt, &stats->ram_bps);
1130 1131

    if (virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_CONSTANT "[1])",
1132 1133
                          ctxt, &stats->ram_duplicate) == 0)
        stats->ram_duplicate_set = true;
1134
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_NORMAL "[1])",
1135
                      ctxt, &stats->ram_normal);
1136
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_NORMAL_BYTES "[1])",
1137
                      ctxt, &stats->ram_normal_bytes);
1138

1139 1140 1141 1142 1143
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_DIRTY_RATE "[1])",
                      ctxt, &stats->ram_dirty_rate);
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_MEMORY_ITERATION "[1])",
                      ctxt, &stats->ram_iteration);

1144
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_DISK_TOTAL "[1])",
1145
                      ctxt, &stats->disk_total);
1146
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_DISK_PROCESSED "[1])",
1147
                      ctxt, &stats->disk_transferred);
1148
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_DISK_REMAINING "[1])",
1149
                      ctxt, &stats->disk_remaining);
1150
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_DISK_BPS "[1])",
1151
                      ctxt, &stats->disk_bps);
1152 1153

    if (virXPathULongLong("string(./" VIR_DOMAIN_JOB_COMPRESSION_CACHE "[1])",
1154 1155
                          ctxt, &stats->xbzrle_cache_size) == 0)
        stats->xbzrle_set = true;
1156
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_COMPRESSION_BYTES "[1])",
1157
                      ctxt, &stats->xbzrle_bytes);
1158
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_COMPRESSION_PAGES "[1])",
1159
                      ctxt, &stats->xbzrle_pages);
1160
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_COMPRESSION_CACHE_MISSES "[1])",
1161
                      ctxt, &stats->xbzrle_cache_miss);
1162
    virXPathULongLong("string(./" VIR_DOMAIN_JOB_COMPRESSION_OVERFLOW "[1])",
1163
                      ctxt, &stats->xbzrle_overflow);
1164

1165 1166
    virXPathInt("string(./" VIR_DOMAIN_JOB_AUTO_CONVERGE_THROTTLE "[1])",
                ctxt, &stats->cpu_throttle_percentage);
1167 1168 1169 1170 1171 1172
 cleanup:
    ctxt->node = save_ctxt;
    return jobInfo;
}


1173 1174
static int
qemuMigrationCookieXMLParse(qemuMigrationCookiePtr mig,
1175
                            virQEMUDriverPtr driver,
1176
                            xmlDocPtr doc,
1177
                            xmlXPathContextPtr ctxt,
E
Eric Blake 已提交
1178
                            unsigned int flags)
1179 1180
{
    char uuidstr[VIR_UUID_STRING_BUFLEN];
1181
    char *tmp = NULL;
1182
    xmlNodePtr *nodes = NULL;
1183 1184
    size_t i;
    int n;
1185 1186 1187 1188
    virCapsPtr caps = NULL;

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto error;
1189 1190 1191 1192 1193 1194 1195 1196

    /* We don't store the uuid, name, hostname, or hostuuid
     * values. We just compare them to local data to do some
     * sanity checking on migration operation
     */

    /* Extract domain name */
    if (!(tmp = virXPathString("string(./name[1])", ctxt))) {
1197 1198
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing name element in migration data"));
1199 1200 1201
        goto error;
    }
    if (STRNEQ(tmp, mig->name)) {
1202 1203 1204
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Incoming cookie data had unexpected name %s vs %s"),
                       tmp, mig->name);
1205 1206 1207 1208 1209 1210 1211
        goto error;
    }
    VIR_FREE(tmp);

    /* Extract domain uuid */
    tmp = virXPathString("string(./uuid[1])", ctxt);
    if (!tmp) {
1212 1213
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing uuid element in migration data"));
1214 1215 1216 1217
        goto error;
    }
    virUUIDFormat(mig->uuid, uuidstr);
    if (STRNEQ(tmp, uuidstr)) {
1218 1219 1220
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Incoming cookie data had unexpected UUID %s vs %s"),
                       tmp, uuidstr);
1221
        goto error;
1222 1223 1224 1225
    }
    VIR_FREE(tmp);

    /* Check & forbid "localhost" migration */
1226
    if (!(mig->remoteHostname = virXPathString("string(./hostname[1])", ctxt))) {
1227 1228
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing hostname element in migration data"));
1229 1230
        goto error;
    }
1231
    if (STREQ(mig->remoteHostname, mig->localHostname)) {
1232 1233 1234
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Attempt to migrate guest to the same host %s"),
                       mig->remoteHostname);
1235 1236 1237 1238
        goto error;
    }

    if (!(tmp = virXPathString("string(./hostuuid[1])", ctxt))) {
1239 1240 1241
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing hostuuid element in migration data"));
        goto error;
1242
    }
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    if (virUUIDParse(tmp, mig->remoteHostuuid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("malformed hostuuid element in migration data"));
        goto error;
    }
    if (memcmp(mig->remoteHostuuid, mig->localHostuuid, VIR_UUID_BUFLEN) == 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Attempt to migrate guest to the same host %s"),
                       tmp);
        goto error;
    }
    VIR_FREE(tmp);
1255

1256 1257
    /* Check to ensure all mandatory features from XML are also
     * present in 'flags' */
1258
    if ((n = virXPathNodeSet("./feature", ctxt, &nodes)) < 0)
1259 1260
        goto error;

1261
    for (i = 0; i < n; i++) {
1262 1263 1264
        int val;
        char *str = virXMLPropString(nodes[i], "name");
        if (!str) {
1265 1266
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("missing feature name"));
1267 1268 1269 1270
            goto error;
        }

        if ((val = qemuMigrationCookieFlagTypeFromString(str)) < 0) {
1271 1272 1273
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unknown migration cookie feature %s"),
                           str);
1274 1275 1276 1277 1278
            VIR_FREE(str);
            goto error;
        }

        if ((flags & (1 << val)) == 0) {
1279 1280 1281
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Unsupported migration cookie feature %s"),
                           str);
1282
            VIR_FREE(str);
1283
            goto error;
1284 1285 1286 1287 1288
        }
        VIR_FREE(str);
    }
    VIR_FREE(nodes);

1289 1290 1291 1292 1293
    if ((flags & QEMU_MIGRATION_COOKIE_GRAPHICS) &&
        virXPathBoolean("count(./graphics) > 0", ctxt) &&
        (!(mig->graphics = qemuMigrationCookieGraphicsXMLParse(ctxt))))
        goto error;

1294 1295 1296 1297
    if ((flags & QEMU_MIGRATION_COOKIE_LOCKSTATE) &&
        virXPathBoolean("count(./lockstate) > 0", ctxt)) {
        mig->lockDriver = virXPathString("string(./lockstate[1]/@driver)", ctxt);
        if (!mig->lockDriver) {
1298 1299
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("Missing lock driver name in migration cookie"));
1300 1301 1302 1303 1304 1305 1306
            goto error;
        }
        mig->lockState = virXPathString("string(./lockstate[1]/leases[1])", ctxt);
        if (mig->lockState && STREQ(mig->lockState, ""))
            VIR_FREE(mig->lockState);
    }

1307 1308 1309
    if ((flags & QEMU_MIGRATION_COOKIE_PERSISTENT) &&
        virXPathBoolean("count(./domain) > 0", ctxt)) {
        if ((n = virXPathNodeSet("./domain", ctxt, &nodes)) > 1) {
1310 1311 1312 1313
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Too many domain elements in "
                             "migration cookie: %d"),
                           n);
1314 1315
            goto error;
        }
1316
        mig->persistent = virDomainDefParseNode(doc, nodes[0],
1317
                                                caps, driver->xmlopt, NULL,
1318
                                                VIR_DOMAIN_DEF_PARSE_INACTIVE |
1319 1320
                                                VIR_DOMAIN_DEF_PARSE_ABI_UPDATE |
                                                VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE);
1321 1322 1323 1324 1325 1326 1327 1328
        if (!mig->persistent) {
            /* virDomainDefParseNode already reported
             * an error for us */
            goto error;
        }
        VIR_FREE(nodes);
    }

1329 1330 1331 1332 1333
    if ((flags & QEMU_MIGRATION_COOKIE_NETWORK) &&
        virXPathBoolean("count(./network) > 0", ctxt) &&
        (!(mig->network = qemuMigrationCookieNetworkXMLParse(ctxt))))
        goto error;

1334
    if (flags & QEMU_MIGRATION_COOKIE_NBD &&
1335 1336 1337
        virXPathBoolean("boolean(./nbd)", ctxt) &&
        (!(mig->nbd = qemuMigrationCookieNBDXMLParse(ctxt))))
        goto error;
1338

1339 1340 1341 1342 1343
    if (flags & QEMU_MIGRATION_COOKIE_STATS &&
        virXPathBoolean("boolean(./statistics)", ctxt) &&
        (!(mig->jobInfo = qemuMigrationCookieStatisticsXMLParse(ctxt))))
        goto error;

1344
    virObjectUnref(caps);
1345 1346
    return 0;

1347
 error:
1348
    VIR_FREE(tmp);
1349
    VIR_FREE(nodes);
1350
    virObjectUnref(caps);
1351 1352 1353 1354 1355 1356
    return -1;
}


static int
qemuMigrationCookieXMLParseStr(qemuMigrationCookiePtr mig,
1357
                               virQEMUDriverPtr driver,
1358
                               const char *xml,
E
Eric Blake 已提交
1359
                               unsigned int flags)
1360 1361 1362
{
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
1363
    int ret = -1;
1364 1365 1366

    VIR_DEBUG("xml=%s", NULLSTR(xml));

1367
    if (!(doc = virXMLParseStringCtxt(xml, _("(qemu_migration_cookie)"), &ctxt)))
1368 1369
        goto cleanup;

1370
    ret = qemuMigrationCookieXMLParse(mig, driver, doc, ctxt, flags);
1371

1372
 cleanup:
1373 1374 1375 1376 1377 1378 1379 1380 1381
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);

    return ret;
}


static int
qemuMigrationBakeCookie(qemuMigrationCookiePtr mig,
1382
                        virQEMUDriverPtr driver,
1383
                        virDomainObjPtr dom,
1384 1385
                        char **cookieout,
                        int *cookieoutlen,
E
Eric Blake 已提交
1386
                        unsigned int flags)
1387
{
1388 1389
    if (!cookieout || !cookieoutlen)
        return 0;
1390 1391 1392

    *cookieoutlen = 0;

1393 1394 1395 1396
    if (flags & QEMU_MIGRATION_COOKIE_GRAPHICS &&
        qemuMigrationCookieAddGraphics(mig, driver, dom) < 0)
        return -1;

1397 1398 1399 1400
    if (flags & QEMU_MIGRATION_COOKIE_LOCKSTATE &&
        qemuMigrationCookieAddLockstate(mig, driver, dom) < 0)
        return -1;

1401 1402 1403 1404 1405
    if (flags & QEMU_MIGRATION_COOKIE_NETWORK &&
        qemuMigrationCookieAddNetwork(mig, driver, dom) < 0) {
        return -1;
    }

1406 1407 1408 1409
    if ((flags & QEMU_MIGRATION_COOKIE_NBD) &&
        qemuMigrationCookieAddNBD(mig, driver, dom) < 0)
        return -1;

1410 1411 1412 1413
    if (flags & QEMU_MIGRATION_COOKIE_STATS &&
        qemuMigrationCookieAddStatistics(mig, dom) < 0)
        return -1;

1414 1415 1416
    if (flags & QEMU_MIGRATION_COOKIE_MEMORY_HOTPLUG)
        mig->flagsMandatory |= QEMU_MIGRATION_COOKIE_MEMORY_HOTPLUG;

1417 1418 1419
    if (flags & QEMU_MIGRATION_COOKIE_CPU_HOTPLUG)
        mig->flagsMandatory |= QEMU_MIGRATION_COOKIE_CPU_HOTPLUG;

1420
    if (!(*cookieout = qemuMigrationCookieXMLFormatStr(driver, mig)))
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        return -1;

    *cookieoutlen = strlen(*cookieout) + 1;

    VIR_DEBUG("cookielen=%d cookie=%s", *cookieoutlen, *cookieout);

    return 0;
}


static qemuMigrationCookiePtr
1432
qemuMigrationEatCookie(virQEMUDriverPtr driver,
1433
                       virDomainObjPtr dom,
1434 1435
                       const char *cookiein,
                       int cookieinlen,
E
Eric Blake 已提交
1436
                       unsigned int flags)
1437 1438 1439 1440 1441 1442
{
    qemuMigrationCookiePtr mig = NULL;

    /* Parse & validate incoming cookie (if any) */
    if (cookiein && cookieinlen &&
        cookiein[cookieinlen-1] != '\0') {
1443 1444
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Migration cookie was not NULL terminated"));
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
        goto error;
    }

    VIR_DEBUG("cookielen=%d cookie='%s'", cookieinlen, NULLSTR(cookiein));

    if (!(mig = qemuMigrationCookieNew(dom)))
        return NULL;

    if (cookiein && cookieinlen &&
        qemuMigrationCookieXMLParseStr(mig,
1455
                                       driver,
1456 1457 1458 1459
                                       cookiein,
                                       flags) < 0)
        goto error;

1460 1461 1462 1463 1464 1465 1466 1467
    if (flags & QEMU_MIGRATION_COOKIE_PERSISTENT &&
        mig->persistent &&
        STRNEQ(dom->def->name, mig->persistent->name)) {
        VIR_FREE(mig->persistent->name);
        if (VIR_STRDUP(mig->persistent->name, dom->def->name) < 0)
            goto error;
    }

1468 1469 1470
    if (mig->flags & QEMU_MIGRATION_COOKIE_LOCKSTATE) {
        if (!mig->lockDriver) {
            if (virLockManagerPluginUsesState(driver->lockManager)) {
1471 1472 1473
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Missing %s lock state for migration cookie"),
                               virLockManagerPluginGetName(driver->lockManager));
1474 1475 1476 1477
                goto error;
            }
        } else if (STRNEQ(mig->lockDriver,
                          virLockManagerPluginGetName(driver->lockManager))) {
1478 1479 1480 1481
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("Source host lock driver %s different from target %s"),
                           mig->lockDriver,
                           virLockManagerPluginGetName(driver->lockManager));
1482 1483 1484 1485
            goto error;
        }
    }

1486 1487
    return mig;

1488
 error:
1489 1490 1491
    qemuMigrationCookieFree(mig);
    return NULL;
}
1492

1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
/* qemuMigrationCheckTLSCreds
 * @driver: pointer to qemu driver
 * @vm: domain object
 * @asyncJob: migration job to join
 *
 * Query the migration parameters looking for the 'tls-creds' parameter.
 * If found, then we can support setting or clearing the parameters and thus
 * can support TLS for migration.
 *
 * Returns 0 if we were able to successfully fetch the params and
 * additionally if the tls-creds parameter exists, saves it in the
 * private domain structure. Returns -1 on failure.
 */
static int
qemuMigrationCheckTLSCreds(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           qemuDomainAsyncJob asyncJob)
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuMonitorMigrationParams migParams = { 0 };

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

    if (qemuMonitorGetMigrationParams(priv->mon, &migParams) < 0)
        goto cleanup;

    /* NB: Could steal NULL pointer too! Let caller decide what to do. */
    VIR_STEAL_PTR(priv->migTLSAlias, migParams.migrateTLSAlias);

    ret = 0;

 cleanup:
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        ret = -1;

    qemuMigrationParamsClear(&migParams);

    return ret;
}


/* qemuMigrationCheckSetupTLS
 * @conn: Connection pointer
 * @driver: pointer to qemu driver
 * @vm: domain object
 * @cfg: configuration pointer
 * @asyncJob: migration job to join
 *
 * Check if TLS is possible and set up the environment. Assumes the caller
 * desires to use TLS (e.g. caller found VIR_MIGRATE_TLS flag).
 *
 * Ensure the qemu.conf has been properly configured to add an entry for
 * "migrate_tls_x509_cert_dir". Also check if the "tls-creds" parameter
 * was present from a query of migration parameters
 *
 * Returns 0 on success, -1 on error/failure
 */
static int
qemuMigrationCheckSetupTLS(virConnectPtr conn,
                           virQEMUDriverPtr driver,
                           virQEMUDriverConfigPtr cfg,
                           virDomainObjPtr vm,
                           qemuDomainAsyncJob asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!cfg->migrateTLSx509certdir) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("host migration TLS directory not configured"));
        return -1;
    }

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

    if (!priv->migTLSAlias) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("TLS migration is not supported with this "
                         "QEMU binary"));
        return -1;
    }

    /* If there's a secret, then grab/store it now using the connection */
    if (cfg->migrateTLSx509secretUUID &&
        !(priv->migSecinfo =
          qemuDomainSecretInfoTLSNew(conn, priv, QEMU_MIGRATION_TLS_ALIAS_BASE,
                                     cfg->migrateTLSx509secretUUID)))
        return -1;

    return 0;
}


/* qemuMigrationAddTLSObjects
 * @driver: pointer to qemu driver
 * @vm: domain object
 * @cfg: configuration pointer
 * @tlsListen: server or client
 * @asyncJob: Migration job to join
 * @tlsAlias: alias to be generated for TLS object
 * @secAlias: alias to be generated for a secinfo object
 * @migParams: migration parameters to set
 *
 * Create the TLS objects for the migration and set the migParams value
 *
 * Returns 0 on success, -1 on failure
 */
static int
qemuMigrationAddTLSObjects(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           virQEMUDriverConfigPtr cfg,
                           bool tlsListen,
                           qemuDomainAsyncJob asyncJob,
                           char **tlsAlias,
                           char **secAlias,
                           qemuMonitorMigrationParamsPtr migParams)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virJSONValuePtr tlsProps = NULL;
    virJSONValuePtr secProps = NULL;

    if (qemuDomainGetTLSObjects(priv->qemuCaps, priv->migSecinfo,
                                cfg->migrateTLSx509certdir, tlsListen,
                                cfg->migrateTLSx509verify,
                                QEMU_MIGRATION_TLS_ALIAS_BASE,
                                &tlsProps, tlsAlias, &secProps, secAlias) < 0)
        return -1;

    /* Ensure the domain doesn't already have the TLS objects defined...
     * This should prevent any issues just in case some cleanup wasn't
     * properly completed (both src and dst use the same alias) or
     * some other error path between now and perform . */
    qemuDomainDelTLSObjects(driver, vm, asyncJob, *secAlias, *tlsAlias);

    if (qemuDomainAddTLSObjects(driver, vm, asyncJob, *secAlias, &secProps,
                                *tlsAlias, &tlsProps) < 0)
        return -1;

    if (VIR_STRDUP(migParams->migrateTLSAlias, *tlsAlias) < 0)
        return -1;

    return 0;
}


1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
static void
qemuMigrationStoreDomainState(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    priv->preMigrationState = virDomainObjGetState(vm, NULL);

    VIR_DEBUG("Storing pre-migration state=%d domain=%p",
              priv->preMigrationState, vm);
}

/* Returns true if the domain was resumed, false otherwise */
static bool
qemuMigrationRestoreDomainState(virConnectPtr conn, virDomainObjPtr vm)
{
    virQEMUDriverPtr driver = conn->privateData;
    qemuDomainObjPrivatePtr priv = vm->privateData;
1656 1657
    int reason;
    virDomainState state = virDomainObjGetState(vm, &reason);
1658 1659
    bool ret = false;

1660 1661 1662 1663 1664
    VIR_DEBUG("driver=%p, vm=%p, pre-mig-state=%s, state=%s, reason=%s",
              driver, vm,
              virDomainStateTypeToString(priv->preMigrationState),
              virDomainStateTypeToString(state),
              virDomainStateReasonToString(state, reason));
1665

1666 1667 1668 1669 1670
    if (state != VIR_DOMAIN_PAUSED ||
        reason == VIR_DOMAIN_PAUSED_POSTCOPY_FAILED)
        goto cleanup;

    if (priv->preMigrationState == VIR_DOMAIN_RUNNING) {
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
        /* This is basically the only restore possibility that's safe
         * and we should attempt to do */

        VIR_DEBUG("Restoring pre-migration state due to migration error");

        /* we got here through some sort of failure; start the domain again */
        if (qemuProcessStartCPUs(driver, vm, conn,
                                 VIR_DOMAIN_RUNNING_MIGRATION_CANCELED,
                                 QEMU_ASYNC_JOB_MIGRATION_OUT) < 0) {
            /* Hm, we already know we are in error here.  We don't want to
             * overwrite the previous error, though, so we just throw something
             * to the logs and hope for the best */
            VIR_ERROR(_("Failed to resume guest %s after failure"), vm->def->name);
            goto cleanup;
        }
        ret = true;
    }

 cleanup:
    priv->preMigrationState = VIR_DOMAIN_NOSTATE;
    return ret;
}

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747

static int
qemuMigrationPrecreateDisk(virConnectPtr conn,
                           virDomainDiskDefPtr disk,
                           unsigned long long capacity)
{
    int ret = -1;
    virStoragePoolPtr pool = NULL;
    virStorageVolPtr vol = NULL;
    char *volName = NULL, *basePath = NULL;
    char *volStr = NULL;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    const char *format = NULL;
    unsigned int flags = 0;

    VIR_DEBUG("Precreate disk type=%s", virStorageTypeToString(disk->src->type));

    switch ((virStorageType) disk->src->type) {
    case VIR_STORAGE_TYPE_FILE:
        if (!virDomainDiskGetSource(disk)) {
            VIR_DEBUG("Dropping sourceless disk '%s'",
                      disk->dst);
            return 0;
        }

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

        if (!(volName = strrchr(basePath, '/'))) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("malformed disk path: %s"),
                           disk->src->path);
            goto cleanup;
        }

        *volName = '\0';
        volName++;

        if (!(pool = storagePoolLookupByTargetPath(conn, basePath)))
            goto cleanup;
        format = virStorageFileFormatTypeToString(disk->src->format);
        if (disk->src->format == VIR_STORAGE_FILE_QCOW2)
            flags |= VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA;
        break;

    case VIR_STORAGE_TYPE_VOLUME:
        if (!(pool = virStoragePoolLookupByName(conn, disk->src->srcpool->pool)))
            goto cleanup;
        format = virStorageFileFormatTypeToString(disk->src->format);
        volName = disk->src->srcpool->volume;
        if (disk->src->format == VIR_STORAGE_FILE_QCOW2)
            flags |= VIR_STORAGE_VOL_CREATE_PREALLOC_METADATA;
        break;

1748 1749 1750 1751 1752
    case VIR_STORAGE_TYPE_NETWORK:
        VIR_DEBUG("Skipping creation of network disk '%s'",
                  disk->dst);
        return 0;

1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
    case VIR_STORAGE_TYPE_BLOCK:
    case VIR_STORAGE_TYPE_DIR:
    case VIR_STORAGE_TYPE_NONE:
    case VIR_STORAGE_TYPE_LAST:
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("cannot precreate storage for disk type '%s'"),
                       virStorageTypeToString(disk->src->type));
        goto cleanup;
    }

    if ((vol = virStorageVolLookupByName(pool, volName))) {
        VIR_DEBUG("Skipping creation of already existing volume of name '%s'",
                  volName);
        ret = 0;
        goto cleanup;
    }

    virBufferAddLit(&buf, "<volume>\n");
    virBufferAdjustIndent(&buf, 2);
    virBufferEscapeString(&buf, "<name>%s</name>\n", volName);
    virBufferAsprintf(&buf, "<capacity>%llu</capacity>\n", capacity);
    virBufferAddLit(&buf, "<target>\n");
    virBufferAdjustIndent(&buf, 2);
    virBufferAsprintf(&buf, "<format type='%s'/>\n", format);
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</target>\n");
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</volume>\n");

    if (!(volStr = virBufferContentAndReset(&buf))) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("unable to create volume XML"));
        goto cleanup;
    }

    if (!(vol = virStorageVolCreateXML(pool, volStr, flags)))
        goto cleanup;

    ret = 0;
 cleanup:
    VIR_FREE(basePath);
    VIR_FREE(volStr);
    virObjectUnref(vol);
    virObjectUnref(pool);
    return ret;
}

1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820
static bool
qemuMigrateDisk(virDomainDiskDef const *disk,
                size_t nmigrate_disks, const char **migrate_disks)
{
    size_t i;

    /* Check if the disk alias is in the list */
    if (nmigrate_disks) {
        for (i = 0; i < nmigrate_disks; i++) {
            if (STREQ(disk->dst, migrate_disks[i]))
                return true;
        }
        return false;
    }

    /* Default is to migrate only non-shared non-readonly disks
     * with source */
    return !disk->src->shared && !disk->src->readonly &&
           virDomainDiskGetSource(disk);
}

1821 1822 1823 1824 1825

static int
qemuMigrationPrecreateStorage(virConnectPtr conn,
                              virQEMUDriverPtr driver ATTRIBUTE_UNUSED,
                              virDomainObjPtr vm,
1826 1827
                              qemuMigrationCookieNBDPtr nbd,
                              size_t nmigrate_disks,
1828 1829
                              const char **migrate_disks,
                              bool incremental)
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
{
    int ret = -1;
    size_t i = 0;

    if (!nbd || !nbd->ndisks)
        return 0;

    for (i = 0; i < nbd->ndisks; i++) {
        virDomainDiskDefPtr disk;
        const char *diskSrcPath;

1841
        VIR_DEBUG("Looking up disk target '%s' (capacity=%llu)",
1842 1843
                  nbd->disks[i].target, nbd->disks[i].capacity);

1844 1845
        if (!(disk = virDomainDiskByName(vm->def, nbd->disks[i].target,
                                         false))) {
1846 1847 1848 1849 1850 1851 1852 1853
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           _("unable to find disk by target: %s"),
                           nbd->disks[i].target);
            goto cleanup;
        }

        diskSrcPath = virDomainDiskGetSource(disk);

1854 1855
        /* Skip disks we don't want to migrate and already existing disks. */
        if (!qemuMigrateDisk(disk, nmigrate_disks, migrate_disks) ||
1856 1857 1858 1859
            (diskSrcPath && virFileExists(diskSrcPath))) {
            continue;
        }

1860 1861 1862 1863 1864 1865 1866
        if (incremental) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("pre-creation of storage targets for incremental "
                             "storage migration is not supported"));
            goto cleanup;
        }

1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
        VIR_DEBUG("Proceeding with disk source %s", NULLSTR(diskSrcPath));

        if (qemuMigrationPrecreateDisk(conn, disk, nbd->disks[i].capacity) < 0)
            goto cleanup;
    }

    ret = 0;
 cleanup:
    return ret;
}


1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
/**
 * qemuMigrationStartNBDServer:
 * @driver: qemu driver
 * @vm: domain
 *
 * Starts NBD server. This is a newer method to copy
 * storage during migration than using 'blk' and 'inc'
 * arguments in 'migrate' monitor command.
 * Error is reported here.
 *
 * Returns 0 on success, -1 otherwise.
 */
static int
qemuMigrationStartNBDServer(virQEMUDriverPtr driver,
J
Ján Tomko 已提交
1893
                            virDomainObjPtr vm,
1894 1895
                            const char *listenAddr,
                            size_t nmigrate_disks,
1896 1897
                            const char **migrate_disks,
                            int nbdPort)
1898 1899 1900 1901 1902 1903 1904
{
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;
    unsigned short port = 0;
    char *diskAlias = NULL;
    size_t i;

1905 1906 1907 1908 1909 1910
    if (nbdPort < 0 || nbdPort > USHRT_MAX) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("nbd port must be in range 0-65535"));
        return -1;
    }

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

1914 1915
        /* check whether disk should be migrated */
        if (!qemuMigrateDisk(disk, nmigrate_disks, migrate_disks))
1916 1917
            continue;

1918 1919 1920 1921 1922 1923
        if (disk->src->readonly) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                           _("Cannot migrate read-only disk %s"), disk->dst);
            goto cleanup;
        }

1924
        VIR_FREE(diskAlias);
1925
        if (!(diskAlias = qemuAliasFromDisk(disk)))
1926 1927 1928 1929 1930 1931
            goto cleanup;

        if (qemuDomainObjEnterMonitorAsync(driver, vm,
                                           QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
            goto cleanup;

1932 1933 1934 1935 1936 1937 1938 1939
        if (port == 0) {
            if (nbdPort)
                port = nbdPort;
            else if (virPortAllocatorAcquire(driver->migrationPorts, &port) < 0)
                goto exit_monitor;

            if (qemuMonitorNBDServerStart(priv->mon, listenAddr, port) < 0)
                goto exit_monitor;
1940 1941
        }

1942 1943 1944
        if (qemuMonitorNBDServerAdd(priv->mon, diskAlias, true) < 0)
            goto exit_monitor;
        if (qemuDomainObjExitMonitor(driver, vm) < 0)
1945 1946 1947 1948 1949 1950
            goto cleanup;
    }

    priv->nbdPort = port;
    ret = 0;

1951
 cleanup:
1952
    VIR_FREE(diskAlias);
1953
    if (ret < 0 && nbdPort == 0)
1954
        virPortAllocatorRelease(driver->migrationPorts, port);
1955
    return ret;
1956 1957 1958 1959

 exit_monitor:
    ignore_value(qemuDomainObjExitMonitor(driver, vm));
    goto cleanup;
1960 1961
}

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988

static int
qemuMigrationStopNBDServer(virQEMUDriverPtr driver,
                           virDomainObjPtr vm,
                           qemuMigrationCookiePtr mig)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (!mig->nbd)
        return 0;

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

    if (qemuMonitorNBDServerStop(priv->mon) < 0)
        VIR_WARN("Unable to stop NBD server");
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        return -1;

    virPortAllocatorRelease(driver->migrationPorts, priv->nbdPort);
    priv->nbdPort = 0;
    return 0;
}


/**
1989
 * qemuMigrationDriveMirrorReady:
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
 * @driver: qemu driver
 * @vm: domain
 *
 * Check the status of all drive-mirrors started by
 * qemuMigrationDriveMirror. Any pending block job events
 * for the mirrored disks will be processed.
 *
 * Returns 1 if all mirrors are "ready",
 *         0 if some mirrors are still performing initial sync,
 *        -1 on error.
 */
static int
2002
qemuMigrationDriveMirrorReady(virQEMUDriverPtr driver,
2003 2004 2005
                              virDomainObjPtr vm)
{
    size_t i;
2006 2007
    size_t notReady = 0;
    int status;
2008 2009 2010

    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
2011
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2012

2013
        if (!diskPriv->migrating)
2014 2015
            continue;

2016 2017
        status = qemuBlockJobUpdate(driver, vm, disk);
        if (status == VIR_DOMAIN_BLOCK_JOB_FAILED) {
2018 2019 2020 2021 2022
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("migration of disk %s failed"),
                           disk->dst);
            return -1;
        }
2023 2024 2025

        if (disk->mirrorState != VIR_DOMAIN_DISK_MIRROR_STATE_READY)
            notReady++;
2026 2027
    }

2028 2029 2030 2031 2032 2033 2034
    if (notReady) {
        VIR_DEBUG("Waiting for %zu disk mirrors to get ready", notReady);
        return 0;
    } else {
        VIR_DEBUG("All disk mirrors are ready");
        return 1;
    }
2035 2036 2037
}


2038 2039 2040 2041
/*
 * If @check is true, the function will report an error and return a different
 * code in case a block job fails. This way we can properly abort migration in
 * case some block jobs failed once all memory has already been transferred.
2042
 *
2043 2044 2045 2046
 * Returns 1 if all mirrors are gone,
 *         0 if some mirrors are still active,
 *         -1 some mirrors failed but some are still active,
 *         -2 all mirrors are gone but some of them failed.
2047 2048
 */
static int
2049
qemuMigrationDriveMirrorCancelled(virQEMUDriverPtr driver,
2050
                                  virDomainObjPtr vm,
2051
                                  bool check)
2052
{
2053 2054 2055 2056
    size_t i;
    size_t active = 0;
    int status;
    bool failed = false;
2057

2058 2059 2060
    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2061

2062 2063
        if (!diskPriv->migrating)
            continue;
2064

2065 2066 2067 2068
        status = qemuBlockJobUpdate(driver, vm, disk);
        switch (status) {
        case VIR_DOMAIN_BLOCK_JOB_FAILED:
            if (check) {
2069
                virReportError(VIR_ERR_OPERATION_FAILED,
2070
                               _("migration of disk %s failed"),
2071
                               disk->dst);
2072
                failed = true;
2073
            }
2074 2075 2076 2077 2078 2079
            /* fallthrough */
        case VIR_DOMAIN_BLOCK_JOB_CANCELED:
        case VIR_DOMAIN_BLOCK_JOB_COMPLETED:
            qemuBlockJobSyncEnd(driver, vm, disk);
            diskPriv->migrating = false;
            break;
2080

2081 2082
        default:
            active++;
2083
        }
2084
    }
2085

2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
    if (failed) {
        if (active) {
            VIR_DEBUG("Some disk mirrors failed; still waiting for %zu "
                      "disk mirrors to finish", active);
            return -1;
        } else {
            VIR_DEBUG("All disk mirrors are gone; some of them failed");
            return -2;
        }
    } else {
        if (active) {
            VIR_DEBUG("Waiting for %zu disk mirrors to finish", active);
            return 0;
        } else {
            VIR_DEBUG("All disk mirrors are gone");
            return 1;
2102
        }
2103
    }
2104
}
2105 2106


2107 2108 2109 2110 2111 2112 2113 2114 2115
/*
 * Returns 0 on success,
 *         1 when job is already completed or it failed and failNoJob is false,
 *         -1 on error or when job failed and failNoJob is true.
 */
static int
qemuMigrationCancelOneDriveMirror(virQEMUDriverPtr driver,
                                  virDomainObjPtr vm,
                                  virDomainDiskDefPtr disk,
2116 2117
                                  bool failNoJob,
                                  qemuDomainAsyncJob asyncJob)
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *diskAlias = NULL;
    int ret = -1;
    int status;
    int rv;

    status = qemuBlockJobUpdate(driver, vm, disk);
    switch (status) {
    case VIR_DOMAIN_BLOCK_JOB_FAILED:
    case VIR_DOMAIN_BLOCK_JOB_CANCELED:
        if (failNoJob) {
            virReportError(VIR_ERR_OPERATION_FAILED,
                           _("migration of disk %s failed"),
                           disk->dst);
            return -1;
        }
        return 1;

    case VIR_DOMAIN_BLOCK_JOB_COMPLETED:
        return 1;
    }

2141
    if (!(diskAlias = qemuAliasFromDisk(disk)))
2142 2143
        return -1;

2144
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
2145 2146 2147 2148 2149 2150 2151 2152
        goto cleanup;

    rv = qemuMonitorBlockJobCancel(priv->mon, diskAlias, true);

    if (qemuDomainObjExitMonitor(driver, vm) < 0 || rv < 0)
        goto cleanup;

    ret = 0;
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163

 cleanup:
    VIR_FREE(diskAlias);
    return ret;
}


/**
 * qemuMigrationCancelDriveMirror:
 * @driver: qemu driver
 * @vm: domain
2164
 * @check: if true report an error when some of the mirrors fails
2165 2166 2167 2168 2169 2170 2171 2172 2173
 *
 * Cancel all drive-mirrors started by qemuMigrationDriveMirror.
 * Any pending block job events for the affected disks will be
 * processed.
 *
 * Returns 0 on success, -1 otherwise.
 */
static int
qemuMigrationCancelDriveMirror(virQEMUDriverPtr driver,
2174
                               virDomainObjPtr vm,
2175
                               bool check,
2176 2177
                               qemuDomainAsyncJob asyncJob,
                               virConnectPtr dconn)
2178
{
2179
    virErrorPtr err = NULL;
2180
    int ret = -1;
2181
    size_t i;
2182 2183 2184 2185
    int rv;
    bool failed = false;

    VIR_DEBUG("Cancelling drive mirrors for domain %s", vm->def->name);
2186 2187 2188

    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
2189
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2190

2191
        if (!diskPriv->migrating)
2192 2193
            continue;

2194 2195
        rv = qemuMigrationCancelOneDriveMirror(driver, vm, disk,
                                               check, asyncJob);
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
        if (rv != 0) {
            if (rv < 0) {
                if (!err)
                    err = virSaveLastError();
                failed = true;
            }
            qemuBlockJobSyncEnd(driver, vm, disk);
            diskPriv->migrating = false;
        }
    }

    while ((rv = qemuMigrationDriveMirrorCancelled(driver, vm, check)) != 1) {
2208 2209 2210 2211 2212 2213 2214
        if (check && !failed &&
            dconn && virConnectIsAlive(dconn) <= 0) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("Lost connection to destination host"));
            failed = true;
        }

2215 2216 2217 2218
        if (rv < 0) {
            failed = true;
            if (rv == -2)
                break;
2219
        }
2220

2221 2222 2223 2224 2225
        if (failed && !err)
            err = virSaveLastError();

        if (virDomainObjWait(vm) < 0)
            goto cleanup;
2226 2227
    }

2228 2229 2230
    ret = failed ? -1 : 0;

 cleanup:
2231 2232 2233 2234 2235
    if (err) {
        virSetError(err);
        virFreeError(err);
    }
    return ret;
2236 2237 2238
}


2239 2240 2241 2242 2243 2244
/**
 * qemuMigrationDriveMirror:
 * @driver: qemu driver
 * @vm: domain
 * @mig: migration cookie
 * @host: where are we migrating to
2245
 * @speed: bandwidth limit in MiB/s
2246 2247 2248 2249
 * @migrate_flags: migrate monitor command flags
 *
 * Run drive-mirror to feed NBD server running on dst and wait
 * till the process switches into another phase where writes go
2250 2251 2252 2253 2254
 * simultaneously to both source and destination. On success,
 * update @migrate_flags so we don't tell 'migrate' command
 * to do the very same operation. On failure, the caller is
 * expected to call qemuMigrationCancelDriveMirror to stop all
 * running mirrors.
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
 *
 * Returns 0 on success (@migrate_flags updated),
 *        -1 otherwise.
 */
static int
qemuMigrationDriveMirror(virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         qemuMigrationCookiePtr mig,
                         const char *host,
                         unsigned long speed,
2265 2266
                         unsigned int *migrate_flags,
                         size_t nmigrate_disks,
2267 2268
                         const char **migrate_disks,
                         virConnectPtr dconn)
2269 2270 2271 2272
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;
    int port;
2273
    size_t i;
2274 2275
    char *diskAlias = NULL;
    char *nbd_dest = NULL;
2276
    char *hoststr = NULL;
2277
    unsigned long long mirror_speed = speed;
2278
    unsigned int mirror_flags = VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT;
2279
    int rv;
2280
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
2281 2282

    VIR_DEBUG("Starting drive mirrors for domain %s", vm->def->name);
2283

2284 2285 2286 2287 2288 2289 2290 2291
    if (mirror_speed > LLONG_MAX >> 20) {
        virReportError(VIR_ERR_OVERFLOW,
                       _("bandwidth must be less than %llu"),
                       LLONG_MAX >> 20);
        goto cleanup;
    }
    mirror_speed <<= 20;

2292 2293 2294 2295
    /* steal NBD port and thus prevent its propagation back to destination */
    port = mig->nbd->port;
    mig->nbd->port = 0;

2296 2297
    /* escape literal IPv6 address */
    if (strchr(host, ':')) {
2298
        if (virAsprintf(&hoststr, "[%s]", host) < 0)
2299
            goto cleanup;
2300
    } else if (VIR_STRDUP(hoststr, host) < 0) {
2301
        goto cleanup;
2302 2303
    }

2304 2305 2306 2307 2308
    if (*migrate_flags & QEMU_MONITOR_MIGRATE_NON_SHARED_INC)
        mirror_flags |= VIR_DOMAIN_BLOCK_REBASE_SHALLOW;

    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
2309
        qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);
2310
        int mon_ret;
2311

2312 2313
        /* check whether disk should be migrated */
        if (!qemuMigrateDisk(disk, nmigrate_disks, migrate_disks))
2314 2315
            continue;

2316
        if (!(diskAlias = qemuAliasFromDisk(disk)) ||
2317
            (virAsprintf(&nbd_dest, "nbd:%s:%d:exportname=%s",
2318
                         hoststr, port, diskAlias) < 0))
2319 2320
            goto cleanup;

2321
        if (qemuDomainObjEnterMonitorAsync(driver, vm,
2322
                                           QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
2323 2324
            goto cleanup;

2325
        qemuBlockJobSyncBegin(disk);
2326
        /* Force "raw" format for NBD export */
2327
        mon_ret = qemuMonitorDriveMirror(priv->mon, diskAlias, nbd_dest,
2328
                                         "raw", mirror_speed, 0, 0, mirror_flags);
2329 2330
        VIR_FREE(diskAlias);
        VIR_FREE(nbd_dest);
2331

2332
        if (qemuDomainObjExitMonitor(driver, vm) < 0 || mon_ret < 0) {
2333
            qemuBlockJobSyncEnd(driver, vm, disk);
2334 2335
            goto cleanup;
        }
2336
        diskPriv->migrating = true;
2337

2338
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0) {
2339 2340 2341
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
            goto cleanup;
        }
2342
    }
2343

2344 2345 2346
    while ((rv = qemuMigrationDriveMirrorReady(driver, vm)) != 1) {
        if (rv < 0)
            goto cleanup;
2347

2348
        if (priv->job.abortJob) {
2349 2350 2351 2352 2353
            priv->job.current->type = VIR_DOMAIN_JOB_CANCELLED;
            virReportError(VIR_ERR_OPERATION_ABORTED, _("%s: %s"),
                           qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                           _("canceled by client"));
            goto cleanup;
2354
        }
2355

2356 2357 2358 2359 2360 2361
        if (dconn && virConnectIsAlive(dconn) <= 0) {
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("Lost connection to destination host"));
            goto cleanup;
        }

2362
        if (virDomainObjWait(vm) < 0)
2363
            goto cleanup;
2364 2365
    }

2366
    /* Okay, all disks are ready. Modify migrate_flags */
2367 2368 2369 2370
    *migrate_flags &= ~(QEMU_MONITOR_MIGRATE_NON_SHARED_DISK |
                        QEMU_MONITOR_MIGRATE_NON_SHARED_INC);
    ret = 0;

2371
 cleanup:
2372
    virObjectUnref(cfg);
2373 2374
    VIR_FREE(diskAlias);
    VIR_FREE(nbd_dest);
2375
    VIR_FREE(hoststr);
2376 2377
    return ret;
}
2378

2379

2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
/**
 * qemuMigrationIsAllowedHostdev:
 * @def: domain definition
 *
 * Checks that @def does not contain any host devices unsupported accross
 * migrations. Returns true if the vm is allowed to migrate.
 */
static bool
qemuMigrationIsAllowedHostdev(const virDomainDef *def)
{
    size_t i;

    /* Migration with USB host devices is allowed, all other devices are
     * forbidden. */
    for (i = 0; i < def->nhostdevs; i++) {
        virDomainHostdevDefPtr hostdev = def->hostdevs[i];
        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS ||
            hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("domain has assigned non-USB host devices"));
            return false;
        }
    }

    return true;
}


2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
/**
 * qemuMigrationIsAllowed:
 * @driver: qemu driver struct
 * @vm: domain object
 * @remote: migration is remote
 * @flags: migration flags (see struct virDomainMigrateFlags)
 *
 * Validates that the configuration of @vm can be migrated in various
 * situations. If @remote is true, the migration happens to remote host. @flags
 * is used to check various special migration types according to the request.
 *
 * Returns true if migration is supported. Reports libvirt error and returns
 * false otherwise.
 */
2422
bool
2423 2424 2425
qemuMigrationIsAllowed(virQEMUDriverPtr driver,
                       virDomainObjPtr vm,
                       bool remote,
2426
                       unsigned int flags)
2427
{
2428
    int nsnapshots;
2429
    int pauseReason;
2430
    size_t i;
2431

2432 2433 2434 2435 2436
    /* perform these checks only when migrating to remote hosts */
    if (remote) {
        nsnapshots = virDomainSnapshotObjListNum(vm->snapshots, NULL, 0);
        if (nsnapshots < 0)
            return false;
2437

2438 2439 2440 2441 2442
        if (nsnapshots > 0) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           _("cannot migrate domain with %d snapshots"),
                           nsnapshots);
            return false;
2443
        }
2444

2445
        /* cancel migration if disk I/O error is emitted while migrating */
2446
        if (flags & VIR_MIGRATE_ABORT_ON_ERROR &&
2447
            !(flags & VIR_MIGRATE_OFFLINE) &&
2448 2449
            virDomainObjGetState(vm, &pauseReason) == VIR_DOMAIN_PAUSED &&
            pauseReason == VIR_DOMAIN_PAUSED_IOERROR) {
E
Eric Blake 已提交
2450
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2451
                           _("cannot migrate domain with I/O error"));
E
Eric Blake 已提交
2452 2453
            return false;
        }
2454 2455

    }
2456

2457 2458 2459 2460 2461 2462 2463
    /* following checks don't make sense for offline migration */
    if (!(flags & VIR_MIGRATE_OFFLINE)) {
        if (qemuProcessAutoDestroyActive(driver, vm)) {
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("domain is marked for auto destroy"));
            return false;
        }
2464

2465

2466 2467
        if (qemuDomainHasBlockjob(vm, false)) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
2468
                           _("domain has active block job"));
2469 2470 2471 2472 2473 2474
            return false;
        }

        if (!qemuMigrationIsAllowedHostdev(vm->def))
            return false;

2475
        if (vm->def->cpu) {
2476 2477
            for (i = 0; i < vm->def->cpu->nfeatures; i++) {
                virCPUFeatureDefPtr feature = &vm->def->cpu->features[i];
J
Ján Tomko 已提交
2478

2479 2480
                if (feature->policy != VIR_CPU_FEATURE_REQUIRE)
                    continue;
J
Ján Tomko 已提交
2481

2482 2483 2484 2485 2486 2487 2488
                /* QEMU blocks migration and save with invariant TSC enabled */
                if (STREQ(feature->name, "invtsc")) {
                    virReportError(VIR_ERR_OPERATION_INVALID,
                                   _("domain has CPU feature: %s"),
                                   feature->name);
                    return false;
                }
2489
            }
J
Ján Tomko 已提交
2490 2491
        }

2492 2493 2494
        /* Verify that memory device config can be transferred reliably */
        for (i = 0; i < vm->def->nmems; i++) {
            virDomainMemoryDefPtr mem = vm->def->mems[i];
2495

2496 2497 2498 2499 2500
            if (mem->model == VIR_DOMAIN_MEMORY_MODEL_DIMM &&
                mem->info.type != VIR_DOMAIN_DEVICE_ADDRESS_TYPE_DIMM) {
                virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                               _("domain's dimm info lacks slot ID "
                                 "or base address"));
2501

2502 2503
                return false;
            }
2504
        }
2505 2506 2507 2508 2509 2510

        if (vm->def->nshmems) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("migration with shmem device is not supported"));
            return false;
        }
2511 2512
    }

2513 2514 2515
    return true;
}

2516
static bool
2517 2518 2519
qemuMigrationIsSafe(virDomainDefPtr def,
                    size_t nmigrate_disks,
                    const char **migrate_disks)
2520
{
2521
    size_t i;
2522

2523
    for (i = 0; i < def->ndisks; i++) {
2524
        virDomainDiskDefPtr disk = def->disks[i];
2525
        const char *src = virDomainDiskGetSource(disk);
2526

2527 2528
        /* Our code elsewhere guarantees shared disks are either readonly (in
         * which case cache mode doesn't matter) or used with cache=none */
2529
        if (qemuMigrateDisk(disk, nmigrate_disks, migrate_disks) &&
2530
            disk->cachemode != VIR_DOMAIN_DISK_CACHE_DISABLE) {
2531
            int rc;
2532

E
Eric Blake 已提交
2533
            if (virDomainDiskGetType(disk) == VIR_STORAGE_TYPE_FILE) {
2534
                if ((rc = virFileIsSharedFS(src)) < 0)
2535 2536
                    return false;
                else if (rc == 0)
2537
                    continue;
2538
                if ((rc = virStorageFileIsClusterFS(src)) < 0)
2539
                    return false;
2540 2541
                else if (rc == 1)
                    continue;
2542 2543
            } else if (disk->src->type == VIR_STORAGE_TYPE_NETWORK &&
                       disk->src->protocol == VIR_STORAGE_NET_PROTOCOL_RBD) {
2544
                continue;
2545
            }
2546

2547 2548 2549
            virReportError(VIR_ERR_MIGRATE_UNSAFE, "%s",
                           _("Migration may lead to data corruption if disks"
                             " use cache != none"));
2550 2551 2552 2553 2554 2555 2556
            return false;
        }
    }

    return true;
}

2557 2558 2559 2560
/** qemuMigrationSetOffline
 * Pause domain for non-live migration.
 */
int
2561
qemuMigrationSetOffline(virQEMUDriverPtr driver,
2562 2563 2564
                        virDomainObjPtr vm)
{
    int ret;
2565
    VIR_DEBUG("driver=%p vm=%p", driver, vm);
2566 2567
    ret = qemuProcessStopCPUs(driver, vm, VIR_DOMAIN_PAUSED_MIGRATION,
                              QEMU_ASYNC_JOB_MIGRATION_OUT);
2568
    if (ret == 0) {
2569
        virObjectEventPtr event;
2570

2571
        event = virDomainEventLifecycleNewFromObj(vm,
2572 2573
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
2574
        qemuDomainEventQueue(driver, event);
2575 2576 2577 2578 2579
    }

    return ret;
}

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621

void
qemuMigrationPostcopyFailed(virQEMUDriverPtr driver,
                            virDomainObjPtr vm)
{
    virDomainState state;
    int reason;

    state = virDomainObjGetState(vm, &reason);

    if (state != VIR_DOMAIN_PAUSED &&
        state != VIR_DOMAIN_RUNNING)
        return;

    if (state == VIR_DOMAIN_PAUSED &&
        reason == VIR_DOMAIN_PAUSED_POSTCOPY_FAILED)
        return;

    VIR_WARN("Migration of domain %s failed during post-copy; "
             "leaving the domain paused", vm->def->name);

    if (state == VIR_DOMAIN_RUNNING) {
        virObjectEventPtr event;

        if (qemuProcessStopCPUs(driver, vm,
                                VIR_DOMAIN_PAUSED_POSTCOPY_FAILED,
                                QEMU_ASYNC_JOB_MIGRATION_IN) < 0) {
            VIR_WARN("Unable to pause guest CPUs for %s", vm->def->name);
            return;
        }

        event = virDomainEventLifecycleNewFromObj(vm,
                                VIR_DOMAIN_EVENT_SUSPENDED,
                                VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED);
        qemuDomainEventQueue(driver, event);
    } else {
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED,
                             VIR_DOMAIN_PAUSED_POSTCOPY_FAILED);
    }
}


2622
static int
2623
qemuMigrationSetOption(virQEMUDriverPtr driver,
2624
                       virDomainObjPtr vm,
2625
                       qemuMonitorMigrationCaps capability,
2626
                       bool state,
2627 2628 2629 2630 2631 2632 2633 2634
                       qemuDomainAsyncJob job)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret;

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

2635
    ret = qemuMonitorGetMigrationCapability(priv->mon, capability);
2636 2637 2638

    if (ret < 0) {
        goto cleanup;
2639 2640 2641
    } else if (ret == 0 && !state) {
        /* Unsupported but we want it off anyway */
        goto cleanup;
2642 2643
    } else if (ret == 0) {
        if (job == QEMU_ASYNC_JOB_MIGRATION_IN) {
2644 2645 2646 2647
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
                           _("Migration option '%s' is not supported by "
                             "target QEMU binary"),
                           qemuMonitorMigrationCapsTypeToString(capability));
2648
        } else {
2649 2650 2651 2652
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
                           _("Migration option '%s' is not supported by "
                             "source QEMU binary"),
                           qemuMonitorMigrationCapsTypeToString(capability));
2653 2654 2655 2656 2657
        }
        ret = -1;
        goto cleanup;
    }

2658
    ret = qemuMonitorSetMigrationCapability(priv->mon, capability, state);
2659 2660

 cleanup:
2661 2662
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        ret = -1;
2663 2664 2665
    return ret;
}

2666 2667 2668 2669 2670 2671 2672

static int
qemuMigrationSetPostCopy(virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         bool state,
                         qemuDomainAsyncJob job)
{
2673 2674
    qemuDomainObjPrivatePtr priv = vm->privateData;

2675 2676 2677 2678 2679
    if (qemuMigrationSetOption(driver, vm,
                               QEMU_MONITOR_MIGRATION_CAPS_POSTCOPY,
                               state, job) < 0)
        return -1;

2680
    priv->job.postcopyEnabled = state;
2681 2682 2683 2684
    return 0;
}


2685
static int
2686
qemuMigrationWaitForSpice(virDomainObjPtr vm)
2687 2688 2689
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

2690 2691
    if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_SEAMLESS_MIGRATION) ||
        !priv->job.spiceMigration)
2692 2693
        return 0;

2694
    VIR_DEBUG("Waiting for SPICE to finish migration");
2695 2696
    while (!priv->job.spiceMigrated && !priv->job.abortJob) {
        if (virDomainObjWait(vm) < 0)
2697 2698 2699 2700
            return -1;
    }
    return 0;
}
2701

2702 2703 2704 2705

static void
qemuMigrationUpdateJobType(qemuDomainJobInfoPtr jobInfo)
{
2706
    switch ((qemuMonitorMigrationStatus) jobInfo->stats.status) {
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724
    case QEMU_MONITOR_MIGRATION_STATUS_COMPLETED:
        jobInfo->type = VIR_DOMAIN_JOB_COMPLETED;
        break;

    case QEMU_MONITOR_MIGRATION_STATUS_INACTIVE:
        jobInfo->type = VIR_DOMAIN_JOB_NONE;
        break;

    case QEMU_MONITOR_MIGRATION_STATUS_ERROR:
        jobInfo->type = VIR_DOMAIN_JOB_FAILED;
        break;

    case QEMU_MONITOR_MIGRATION_STATUS_CANCELLED:
        jobInfo->type = VIR_DOMAIN_JOB_CANCELLED;
        break;

    case QEMU_MONITOR_MIGRATION_STATUS_SETUP:
    case QEMU_MONITOR_MIGRATION_STATUS_ACTIVE:
2725
    case QEMU_MONITOR_MIGRATION_STATUS_POSTCOPY:
2726
    case QEMU_MONITOR_MIGRATION_STATUS_CANCELLING:
2727
    case QEMU_MONITOR_MIGRATION_STATUS_LAST:
2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
        break;
    }
}


int
qemuMigrationFetchJobStatus(virQEMUDriverPtr driver,
                            virDomainObjPtr vm,
                            qemuDomainAsyncJob asyncJob,
                            qemuDomainJobInfoPtr jobInfo)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rv;

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

2745 2746
    memset(&jobInfo->stats, 0, sizeof(jobInfo->stats));
    rv = qemuMonitorGetMigrationStats(priv->mon, &jobInfo->stats);
2747 2748 2749 2750 2751 2752 2753 2754 2755

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

    qemuMigrationUpdateJobType(jobInfo);
    return qemuDomainJobInfoUpdateTime(jobInfo);
}


2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773
static const char *
qemuMigrationJobName(virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    switch (priv->job.asyncJob) {
    case QEMU_ASYNC_JOB_MIGRATION_OUT:
        return _("migration job");
    case QEMU_ASYNC_JOB_SAVE:
        return _("domain save job");
    case QEMU_ASYNC_JOB_DUMP:
        return _("domain core dump job");
    default:
        return _("job");
    }
}


2774
static int
2775
qemuMigrationUpdateJobStatus(virQEMUDriverPtr driver,
2776
                             virDomainObjPtr vm,
2777
                             qemuDomainAsyncJob asyncJob)
2778
{
2779
    qemuDomainObjPrivatePtr priv = vm->privateData;
2780 2781
    qemuDomainJobInfoPtr jobInfo = priv->job.current;
    qemuDomainJobInfo newInfo = *jobInfo;
2782

2783 2784
    if (qemuMigrationFetchJobStatus(driver, vm, asyncJob, &newInfo) < 0)
        return -1;
2785

2786 2787 2788
    *jobInfo = newInfo;
    return 0;
}
2789

2790

2791 2792 2793
static int
qemuMigrationCheckJobStatus(virQEMUDriverPtr driver,
                            virDomainObjPtr vm,
2794 2795
                            qemuDomainAsyncJob asyncJob,
                            bool updateJobStats)
2796 2797 2798
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuDomainJobInfoPtr jobInfo = priv->job.current;
2799

2800 2801 2802 2803 2804
    bool events = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_MIGRATION_EVENT);

    if (events)
        qemuMigrationUpdateJobType(jobInfo);
    else if (qemuMigrationUpdateJobStatus(driver, vm, asyncJob) < 0)
2805
        return -1;
2806

2807 2808
    switch (jobInfo->type) {
    case VIR_DOMAIN_JOB_NONE:
2809 2810
        virReportError(VIR_ERR_OPERATION_FAILED, _("%s: %s"),
                       qemuMigrationJobName(vm), _("is not active"));
2811
        return -1;
2812

2813
    case VIR_DOMAIN_JOB_FAILED:
2814 2815
        virReportError(VIR_ERR_OPERATION_FAILED, _("%s: %s"),
                       qemuMigrationJobName(vm), _("unexpectedly failed"));
2816
        return -1;
2817

2818
    case VIR_DOMAIN_JOB_CANCELLED:
2819 2820
        virReportError(VIR_ERR_OPERATION_ABORTED, _("%s: %s"),
                       qemuMigrationJobName(vm), _("canceled by client"));
2821 2822
        return -1;

2823 2824
    case VIR_DOMAIN_JOB_COMPLETED:
        /* Fetch statistics of a completed migration */
2825
        if (events && updateJobStats &&
2826 2827 2828 2829
            qemuMigrationUpdateJobStatus(driver, vm, asyncJob) < 0)
            return -1;
        break;

2830 2831 2832
    case VIR_DOMAIN_JOB_BOUNDED:
    case VIR_DOMAIN_JOB_UNBOUNDED:
    case VIR_DOMAIN_JOB_LAST:
2833 2834
        break;
    }
2835
    return 0;
2836 2837 2838
}


2839 2840 2841
enum qemuMigrationCompletedFlags {
    QEMU_MIGRATION_COMPLETED_ABORT_ON_ERROR = (1 << 0),
    QEMU_MIGRATION_COMPLETED_CHECK_STORAGE  = (1 << 1),
2842
    QEMU_MIGRATION_COMPLETED_UPDATE_STATS   = (1 << 2),
2843
    QEMU_MIGRATION_COMPLETED_POSTCOPY       = (1 << 3),
2844 2845
};

2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856
/**
 * Returns 1 if migration completed successfully,
 *         0 if the domain is still being migrated,
 *         -1 migration failed,
 *         -2 something else failed, we need to cancel migration.
 */
static int
qemuMigrationCompleted(virQEMUDriverPtr driver,
                       virDomainObjPtr vm,
                       qemuDomainAsyncJob asyncJob,
                       virConnectPtr dconn,
2857
                       unsigned int flags)
2858 2859 2860 2861
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuDomainJobInfoPtr jobInfo = priv->job.current;
    int pauseReason;
2862
    bool updateStats = !!(flags & QEMU_MIGRATION_COMPLETED_UPDATE_STATS);
2863

2864
    if (qemuMigrationCheckJobStatus(driver, vm, asyncJob, updateStats) < 0)
2865 2866
        goto error;

2867 2868
    if (flags & QEMU_MIGRATION_COMPLETED_CHECK_STORAGE &&
        qemuMigrationDriveMirrorReady(driver, vm) < 0)
2869 2870
        goto error;

2871
    if (flags & QEMU_MIGRATION_COMPLETED_ABORT_ON_ERROR &&
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884
        virDomainObjGetState(vm, &pauseReason) == VIR_DOMAIN_PAUSED &&
        pauseReason == VIR_DOMAIN_PAUSED_IOERROR) {
        virReportError(VIR_ERR_OPERATION_FAILED, _("%s: %s"),
                       qemuMigrationJobName(vm), _("failed due to I/O error"));
        goto error;
    }

    if (dconn && virConnectIsAlive(dconn) <= 0) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Lost connection to destination host"));
        goto error;
    }

2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
    /* In case of postcopy the source considers migration completed at the
     * moment it switched from active to postcopy-active state. The destination
     * will continue waiting until the migrate state changes to completed.
     */
    if (flags & QEMU_MIGRATION_COMPLETED_POSTCOPY &&
        jobInfo->type == VIR_DOMAIN_JOB_UNBOUNDED &&
        jobInfo->stats.status == QEMU_MONITOR_MIGRATION_STATUS_POSTCOPY) {
        VIR_DEBUG("Migration switched to post-copy");
        if (updateStats &&
            qemuMigrationUpdateJobStatus(driver, vm, asyncJob) < 0)
            goto error;
        return 1;
    }

2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
    if (jobInfo->type == VIR_DOMAIN_JOB_COMPLETED)
        return 1;
    else
        return 0;

 error:
    if (jobInfo->type == VIR_DOMAIN_JOB_UNBOUNDED) {
        /* The migration was aborted by us rather than QEMU itself. */
        jobInfo->type = VIR_DOMAIN_JOB_FAILED;
        return -2;
    } else if (jobInfo->type == VIR_DOMAIN_JOB_COMPLETED) {
        jobInfo->type = VIR_DOMAIN_JOB_FAILED;
        return -1;
    } else {
        return -1;
    }
}


2918 2919 2920
/* Returns 0 on success, -2 when migration needs to be cancelled, or -1 when
 * QEMU reports failed migration.
 */
2921
static int
J
Jiri Denemark 已提交
2922 2923
qemuMigrationWaitForCompletion(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
2924
                               qemuDomainAsyncJob asyncJob,
J
Jiri Denemark 已提交
2925
                               virConnectPtr dconn,
2926
                               unsigned int flags)
2927
{
2928
    qemuDomainObjPrivatePtr priv = vm->privateData;
J
Jiri Denemark 已提交
2929
    qemuDomainJobInfoPtr jobInfo = priv->job.current;
2930
    bool events = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_MIGRATION_EVENT);
2931
    int rv;
2932

2933
    flags |= QEMU_MIGRATION_COMPLETED_UPDATE_STATS;
2934

J
Jiri Denemark 已提交
2935
    jobInfo->type = VIR_DOMAIN_JOB_UNBOUNDED;
2936 2937
    while ((rv = qemuMigrationCompleted(driver, vm, asyncJob,
                                        dconn, flags)) != 1) {
2938 2939
        if (rv < 0)
            return rv;
2940

2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953
        if (events) {
            if (virDomainObjWait(vm) < 0) {
                jobInfo->type = VIR_DOMAIN_JOB_FAILED;
                return -2;
            }
        } else {
            /* Poll every 50ms for progress & to allow cancellation */
            struct timespec ts = { .tv_sec = 0, .tv_nsec = 50 * 1000 * 1000ull };

            virObjectUnlock(vm);
            nanosleep(&ts, NULL);
            virObjectLock(vm);
        }
2954 2955
    }

2956 2957 2958 2959 2960
    qemuDomainJobInfoUpdateDowntime(jobInfo);
    VIR_FREE(priv->job.completed);
    if (VIR_ALLOC(priv->job.completed) == 0)
        *priv->job.completed = *jobInfo;

2961
    return 0;
2962 2963 2964
}


2965 2966 2967
static int
qemuMigrationWaitForDestCompletion(virQEMUDriverPtr driver,
                                   virDomainObjPtr vm,
2968 2969
                                   qemuDomainAsyncJob asyncJob,
                                   bool postcopy)
2970 2971
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
2972
    unsigned int flags = 0;
2973 2974 2975 2976 2977 2978 2979
    int rv;

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

    VIR_DEBUG("Waiting for incoming migration to complete");

2980 2981 2982 2983 2984
    if (postcopy)
        flags = QEMU_MIGRATION_COMPLETED_POSTCOPY;

    while ((rv = qemuMigrationCompleted(driver, vm, asyncJob,
                                        NULL, flags)) != 1) {
2985 2986 2987 2988 2989 2990 2991 2992
        if (rv < 0 || virDomainObjWait(vm) < 0)
            return -1;
    }

    return 0;
}


2993
static int
2994
qemuDomainMigrateGraphicsRelocate(virQEMUDriverPtr driver,
2995
                                  virDomainObjPtr vm,
2996 2997
                                  qemuMigrationCookiePtr cookie,
                                  const char *graphicsuri)
2998 2999
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3000 3001
    int ret = -1;
    const char *listenAddress = NULL;
3002
    virSocketAddr addr;
3003 3004 3005 3006 3007
    virURIPtr uri = NULL;
    int type = -1;
    int port = -1;
    int tlsPort = -1;
    const char *tlsSubject = NULL;
3008

3009
    if (!cookie || (!cookie->graphics && !graphicsuri))
3010 3011
        return 0;

3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030
    if (graphicsuri && !(uri = virURIParse(graphicsuri)))
        goto cleanup;

    if (cookie->graphics) {
        type = cookie->graphics->type;

        listenAddress = cookie->graphics->listen;

        if (!listenAddress ||
            (virSocketAddrParse(&addr, listenAddress, AF_UNSPEC) > 0 &&
             virSocketAddrIsWildcard(&addr)))
            listenAddress = cookie->remoteHostname;

        port = cookie->graphics->port;
        tlsPort = cookie->graphics->tlsPort;
        tlsSubject = cookie->graphics->tlsSubject;
    }

    if (uri) {
3031
        size_t i;
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058

        if ((type = virDomainGraphicsTypeFromString(uri->scheme)) < 0) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("unknown graphics type %s"), uri->scheme);
            goto cleanup;
        }

        if (uri->server)
            listenAddress = uri->server;
        if (uri->port > 0)
            port = uri->port;

        for (i = 0; i < uri->paramsCount; i++) {
            virURIParamPtr param = uri->params + i;

            if (STRCASEEQ(param->name, "tlsPort")) {
                if (virStrToLong_i(param->value, NULL, 10, &tlsPort) < 0) {
                    virReportError(VIR_ERR_INVALID_ARG,
                                   _("invalid tlsPort number: %s"),
                                   param->value);
                    goto cleanup;
                }
            } else if (STRCASEEQ(param->name, "tlsSubject")) {
                tlsSubject = param->value;
            }
        }
    }
3059 3060 3061 3062

    /* QEMU doesn't support VNC relocation yet, so
     * skip it to avoid generating an error
     */
3063 3064 3065 3066
    if (type != VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
        ret = 0;
        goto cleanup;
    }
3067

3068 3069 3070 3071 3072 3073 3074 3075 3076
    /* Older libvirt sends port == 0 for listen type='none' graphics. It's
     * safe to ignore such requests since relocation to unknown port does
     * not make sense in general.
     */
    if (port <= 0 && tlsPort <= 0) {
        ret = 0;
        goto cleanup;
    }

3077 3078 3079 3080
    if (qemuDomainObjEnterMonitorAsync(driver, vm,
                                       QEMU_ASYNC_JOB_MIGRATION_OUT) == 0) {
        ret = qemuMonitorGraphicsRelocate(priv->mon, type, listenAddress,
                                          port, tlsPort, tlsSubject);
3081
        priv->job.spiceMigration = !ret;
3082 3083
        if (qemuDomainObjExitMonitor(driver, vm) < 0)
            ret = -1;
3084
    }
3085

3086
 cleanup:
3087
    virURIFree(uri);
3088 3089 3090 3091
    return ret;
}


3092
static int
3093
qemuDomainMigrateOPDRelocate(virQEMUDriverPtr driver ATTRIBUTE_UNUSED,
3094 3095 3096
                             virDomainObjPtr vm,
                             qemuMigrationCookiePtr cookie)
{
3097 3098
    virDomainNetDefPtr netptr;
    int ret = -1;
3099
    size_t i;
3100 3101 3102 3103 3104 3105 3106 3107

    for (i = 0; i < cookie->network->nnets; i++) {
        netptr = vm->def->nets[i];

        switch (cookie->network->net[i].vporttype) {
        case VIR_NETDEV_VPORT_PROFILE_NONE:
        case VIR_NETDEV_VPORT_PROFILE_8021QBG:
        case VIR_NETDEV_VPORT_PROFILE_8021QBH:
3108
           break;
3109
        case VIR_NETDEV_VPORT_PROFILE_OPENVSWITCH:
3110 3111
            if (virNetDevOpenvswitchSetMigrateData(cookie->network->net[i].portdata,
                                                   netptr->ifname) != 0) {
J
Jiri Denemark 已提交
3112 3113 3114
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               _("Unable to run command to set OVS port data for "
                                 "interface %s"), netptr->ifname);
3115 3116 3117
                goto cleanup;
            }
            break;
3118 3119 3120 3121 3122
        default:
            break;
        }
    }

3123
    ret = 0;
3124
 cleanup:
3125 3126 3127 3128
    return ret;
}


3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168
int
qemuMigrationCheckIncoming(virQEMUCapsPtr qemuCaps,
                           const char *migrateFrom)
{
    if (STRPREFIX(migrateFrom, "rdma")) {
        if (!virQEMUCapsGet(qemuCaps, QEMU_CAPS_MIGRATE_RDMA)) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("incoming RDMA migration is not supported "
                             "with this QEMU binary"));
            return -1;
        }
    } else if (!STRPREFIX(migrateFrom, "tcp") &&
               !STRPREFIX(migrateFrom, "exec") &&
               !STRPREFIX(migrateFrom, "fd") &&
               !STRPREFIX(migrateFrom, "unix") &&
               STRNEQ(migrateFrom, "stdio")) {
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                       _("unknown migration protocol"));
        return -1;
    }

    return 0;
}


char *
qemuMigrationIncomingURI(const char *migrateFrom,
                         int migrateFd)
{
    char *uri = NULL;

    if (STREQ(migrateFrom, "stdio"))
        ignore_value(virAsprintf(&uri, "fd:%d", migrateFd));
    else
        ignore_value(VIR_STRDUP(uri, migrateFrom));

    return uri;
}


3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
int
qemuMigrationRunIncoming(virQEMUDriverPtr driver,
                         virDomainObjPtr vm,
                         const char *uri,
                         qemuDomainAsyncJob asyncJob)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;
    int rv;

    VIR_DEBUG("Setting up incoming migration with URI %s", uri);

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

    rv = qemuMonitorMigrateIncoming(priv->mon, uri);

    if (qemuDomainObjExitMonitor(driver, vm) < 0 || rv < 0)
        goto cleanup;

    if (asyncJob == QEMU_ASYNC_JOB_MIGRATION_IN) {
        /* qemuMigrationWaitForDestCompletion is called from the Finish phase */
        ret = 0;
        goto cleanup;
    }

3195
    if (qemuMigrationWaitForDestCompletion(driver, vm, asyncJob, false) < 0)
3196 3197 3198 3199 3200 3201 3202 3203 3204
        goto cleanup;

    ret = 0;

 cleanup:
    return ret;
}


3205 3206 3207 3208 3209 3210
/* This is called for outgoing non-p2p migrations when a connection to the
 * client which initiated the migration was closed but we were waiting for it
 * to follow up with the next phase, that is, in between
 * qemuDomainMigrateBegin3 and qemuDomainMigratePerform3 or
 * qemuDomainMigratePerform3 and qemuDomainMigrateConfirm3.
 */
3211 3212 3213 3214
static virDomainObjPtr
qemuMigrationCleanup(virDomainObjPtr vm,
                     virConnectPtr conn,
                     void *opaque)
3215
{
3216
    virQEMUDriverPtr driver = opaque;
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
    qemuDomainObjPrivatePtr priv = vm->privateData;

    VIR_DEBUG("vm=%s, conn=%p, asyncJob=%s, phase=%s",
              vm->def->name, conn,
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
              qemuDomainAsyncJobPhaseToString(priv->job.asyncJob,
                                              priv->job.phase));

    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
        goto cleanup;

    VIR_DEBUG("The connection which started outgoing migration of domain %s"
              " was closed; canceling the migration",
              vm->def->name);

3232
    switch ((qemuMigrationJobPhase) priv->job.phase) {
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262
    case QEMU_MIGRATION_PHASE_BEGIN3:
        /* just forget we were about to migrate */
        qemuDomainObjDiscardAsyncJob(driver, vm);
        break;

    case QEMU_MIGRATION_PHASE_PERFORM3_DONE:
        VIR_WARN("Migration of domain %s finished but we don't know if the"
                 " domain was successfully started on destination or not",
                 vm->def->name);
        /* clear the job and let higher levels decide what to do */
        qemuDomainObjDiscardAsyncJob(driver, vm);
        break;

    case QEMU_MIGRATION_PHASE_PERFORM3:
        /* cannot be seen without an active migration API; unreachable */
    case QEMU_MIGRATION_PHASE_CONFIRM3:
    case QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED:
        /* all done; unreachable */
    case QEMU_MIGRATION_PHASE_PREPARE:
    case QEMU_MIGRATION_PHASE_FINISH2:
    case QEMU_MIGRATION_PHASE_FINISH3:
        /* incoming migration; unreachable */
    case QEMU_MIGRATION_PHASE_PERFORM2:
        /* single phase outgoing migration; unreachable */
    case QEMU_MIGRATION_PHASE_NONE:
    case QEMU_MIGRATION_PHASE_LAST:
        /* unreachable */
        ;
    }

3263
 cleanup:
3264 3265 3266
    return vm;
}

3267

3268
/* The caller is supposed to lock the vm and start a migration job. */
3269 3270 3271 3272 3273 3274 3275
static char *
qemuMigrationBeginPhase(virQEMUDriverPtr driver,
                        virDomainObjPtr vm,
                        const char *xmlin,
                        const char *dname,
                        char **cookieout,
                        int *cookieoutlen,
3276 3277
                        size_t nmigrate_disks,
                        const char **migrate_disks,
3278
                        unsigned long flags)
3279 3280 3281
{
    char *rv = NULL;
    qemuMigrationCookiePtr mig = NULL;
3282
    virDomainDefPtr def = NULL;
3283
    qemuDomainObjPrivatePtr priv = vm->privateData;
3284
    virCapsPtr caps = NULL;
3285
    unsigned int cookieFlags = QEMU_MIGRATION_COOKIE_LOCKSTATE;
3286

3287
    VIR_DEBUG("driver=%p, vm=%p, xmlin=%s, dname=%s,"
3288 3289
              " cookieout=%p, cookieoutlen=%p,"
              " nmigrate_disks=%zu, migrate_disks=%p, flags=%lx",
3290
              driver, vm, NULLSTR(xmlin), NULLSTR(dname),
3291 3292
              cookieout, cookieoutlen, nmigrate_disks,
              migrate_disks, flags);
3293

3294 3295 3296
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

3297 3298 3299 3300 3301 3302
    /* Only set the phase if we are inside QEMU_ASYNC_JOB_MIGRATION_OUT.
     * Otherwise we will start the async job later in the perform phase losing
     * change protection.
     */
    if (priv->job.asyncJob == QEMU_ASYNC_JOB_MIGRATION_OUT)
        qemuMigrationJobSetPhase(driver, vm, QEMU_MIGRATION_PHASE_BEGIN3);
3303

3304
    if (!qemuMigrationIsAllowed(driver, vm, true, flags))
3305 3306
        goto cleanup;

3307 3308
    if (!(flags & VIR_MIGRATE_UNSAFE) &&
        !qemuMigrationIsSafe(vm->def, nmigrate_disks, migrate_disks))
3309 3310
        goto cleanup;

3311 3312 3313 3314 3315 3316 3317 3318 3319
    if (flags & VIR_MIGRATE_POSTCOPY &&
        (!(flags & VIR_MIGRATE_LIVE) ||
         flags & VIR_MIGRATE_PAUSED)) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("post-copy migration is not supported with non-live "
                         "or paused migration"));
        goto cleanup;
    }

3320 3321 3322 3323 3324 3325
    if (flags & VIR_MIGRATE_POSTCOPY && flags & VIR_MIGRATE_TUNNELLED) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("post-copy is not supported with tunnelled migration"));
        goto cleanup;
    }

3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368
    if (flags & (VIR_MIGRATE_NON_SHARED_DISK | VIR_MIGRATE_NON_SHARED_INC)) {
        bool has_drive_mirror =  virQEMUCapsGet(priv->qemuCaps,
                                                QEMU_CAPS_DRIVE_MIRROR);

        if (nmigrate_disks) {
            if (has_drive_mirror) {
                size_t i, j;
                /* Check user requested only known disk targets. */
                for (i = 0; i < nmigrate_disks; i++) {
                    for (j = 0; j < vm->def->ndisks; j++) {
                        if (STREQ(vm->def->disks[j]->dst, migrate_disks[i]))
                            break;
                    }

                    if (j == vm->def->ndisks) {
                        virReportError(VIR_ERR_INVALID_ARG,
                                       _("disk target %s not found"),
                                       migrate_disks[i]);
                        goto cleanup;
                    }
                }

                if (flags & VIR_MIGRATE_TUNNELLED) {
                    virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                                   _("Selecting disks to migrate is not "
                                     "implemented for tunnelled migration"));
                    goto cleanup;
                }
            } else {
                virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                               _("qemu does not support drive-mirror command"));
                goto cleanup;
            }
        }

        if (has_drive_mirror) {
            /* TODO support NBD for TUNNELLED migration */
            if (flags & VIR_MIGRATE_TUNNELLED) {
                VIR_WARN("NBD in tunnelled migration is currently not supported");
            } else {
                cookieFlags |= QEMU_MIGRATION_COOKIE_NBD;
                priv->nbdPort = 0;
            }
3369 3370 3371
        }
    }

3372
    if (virDomainDefHasMemoryHotplug(vm->def) ||
3373
        ((flags & VIR_MIGRATE_PERSIST_DEST) &&
3374
         vm->newDef && virDomainDefHasMemoryHotplug(vm->newDef)))
3375 3376
        cookieFlags |= QEMU_MIGRATION_COOKIE_MEMORY_HOTPLUG;

3377 3378 3379 3380 3381
    if (!qemuDomainVcpuHotplugIsInOrder(vm->def) ||
        ((flags & VIR_MIGRATE_PERSIST_DEST) &&
         vm->newDef && !qemuDomainVcpuHotplugIsInOrder(vm->newDef)))
        cookieFlags |= QEMU_MIGRATION_COOKIE_CPU_HOTPLUG;

3382
    if (!(mig = qemuMigrationEatCookie(driver, vm, NULL, 0, 0)))
3383 3384 3385 3386
        goto cleanup;

    if (qemuMigrationBakeCookie(mig, driver, vm,
                                cookieout, cookieoutlen,
3387
                                cookieFlags) < 0)
3388 3389
        goto cleanup;

L
liguang 已提交
3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411
    if (flags & VIR_MIGRATE_OFFLINE) {
        if (flags & (VIR_MIGRATE_NON_SHARED_DISK |
                     VIR_MIGRATE_NON_SHARED_INC)) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("offline migration cannot handle "
                             "non-shared storage"));
            goto cleanup;
        }
        if (!(flags & VIR_MIGRATE_PERSIST_DEST)) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("offline migration must be specified with "
                             "the persistent flag set"));
            goto cleanup;
        }
        if (flags & VIR_MIGRATE_TUNNELLED) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("tunnelled offline migration does not "
                             "make sense"));
            goto cleanup;
        }
    }

3412
    if (xmlin) {
3413
        if (!(def = virDomainDefParseString(xmlin, caps, driver->xmlopt, priv->qemuCaps,
3414 3415
                                            VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                            VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
3416 3417
            goto cleanup;

3418
        if (!qemuDomainDefCheckABIStability(driver, vm->def, def))
3419 3420
            goto cleanup;

3421
        rv = qemuDomainDefFormatLive(driver, def, false, true);
3422
    } else {
3423
        rv = qemuDomainDefFormatLive(driver, vm->def, false, true);
3424
    }
3425

3426
 cleanup:
3427
    qemuMigrationCookieFree(mig);
3428
    virObjectUnref(caps);
3429
    virDomainDefFree(def);
3430 3431 3432
    return rv;
}

3433 3434 3435 3436 3437 3438 3439
char *
qemuMigrationBegin(virConnectPtr conn,
                   virDomainObjPtr vm,
                   const char *xmlin,
                   const char *dname,
                   char **cookieout,
                   int *cookieoutlen,
3440 3441
                   size_t nmigrate_disks,
                   const char **migrate_disks,
3442 3443 3444
                   unsigned long flags)
{
    virQEMUDriverPtr driver = conn->privateData;
3445
    virQEMUDriverConfigPtr cfg = NULL;
3446
    char *xml = NULL;
3447
    qemuDomainAsyncJob asyncJob;
3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458

    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
            goto cleanup;
        asyncJob = QEMU_ASYNC_JOB_MIGRATION_OUT;
    } else {
        if (qemuDomainObjBeginJob(driver, vm, QEMU_JOB_MODIFY) < 0)
            goto cleanup;
        asyncJob = QEMU_ASYNC_JOB_NONE;
    }

3459 3460
    qemuMigrationStoreDomainState(vm);

3461 3462 3463 3464 3465 3466 3467 3468 3469 3470
    if (!virDomainObjIsActive(vm) && !(flags & VIR_MIGRATE_OFFLINE)) {
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
        goto endjob;
    }

    /* Check if there is any ejected media.
     * We don't want to require them on the destination.
     */
    if (!(flags & VIR_MIGRATE_OFFLINE) &&
3471
        qemuProcessRefreshDisks(driver, vm, asyncJob) < 0)
3472 3473 3474 3475
        goto endjob;

    if (!(xml = qemuMigrationBeginPhase(driver, vm, xmlin, dname,
                                        cookieout, cookieoutlen,
3476
                                        nmigrate_disks, migrate_disks, flags)))
3477 3478
        goto endjob;

3479 3480 3481 3482 3483 3484
    if (flags & VIR_MIGRATE_TLS) {
        cfg = virQEMUDriverGetConfig(driver);
        if (qemuMigrationCheckSetupTLS(conn, driver, cfg, vm, asyncJob) < 0)
            goto endjob;
    }

3485 3486 3487 3488 3489
    if ((flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        /* We keep the job active across API calls until the confirm() call.
         * This prevents any other APIs being invoked while migration is taking
         * place.
         */
3490
        if (virCloseCallbacksSet(driver->closeCallbacks, vm, conn,
3491 3492
                                 qemuMigrationCleanup) < 0) {
            VIR_FREE(xml);
3493
            goto endjob;
3494
        }
3495
        qemuMigrationJobContinue(vm);
3496 3497 3498 3499
    } else {
        goto endjob;
    }

3500
 cleanup:
3501
    virObjectUnref(cfg);
M
Michal Privoznik 已提交
3502
    virDomainObjEndAPI(&vm);
3503 3504
    return xml;

3505
 endjob:
3506 3507 3508 3509
    if (flags & VIR_MIGRATE_CHANGE_PROTECTION)
        qemuMigrationJobFinish(driver, vm);
    else
        qemuDomainObjEndJob(driver, vm);
3510 3511 3512
    goto cleanup;
}

3513

3514 3515
/* Prepare is the first step, and it runs on the destination host.
 */
3516

3517
static void
3518
qemuMigrationPrepareCleanup(virQEMUDriverPtr driver,
3519 3520 3521 3522 3523 3524 3525 3526 3527 3528
                            virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    VIR_DEBUG("driver=%p, vm=%s, job=%s, asyncJob=%s",
              driver,
              vm->def->name,
              qemuDomainJobTypeToString(priv->job.active),
              qemuDomainAsyncJobTypeToString(priv->job.asyncJob));

3529 3530 3531
    virPortAllocatorRelease(driver->migrationPorts, priv->migrationPort);
    priv->migrationPort = 0;

3532 3533 3534 3535 3536
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_IN))
        return;
    qemuDomainObjDiscardAsyncJob(driver, vm);
}

3537
static qemuProcessIncomingDefPtr
3538 3539 3540 3541
qemuMigrationPrepareIncoming(virDomainObjPtr vm,
                             bool tunnel,
                             const char *protocol,
                             const char *listenAddress,
3542 3543
                             unsigned short port,
                             int fd)
3544 3545
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
3546
    qemuProcessIncomingDefPtr inc = NULL;
3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
    char *migrateFrom = NULL;

    if (tunnel) {
        if (VIR_STRDUP(migrateFrom, "stdio") < 0)
            goto cleanup;
    } else {
        bool encloseAddress = false;
        bool hostIPv6Capable = false;
        bool qemuIPv6Capable = false;
        struct addrinfo *info = NULL;
        struct addrinfo hints = { .ai_flags = AI_ADDRCONFIG,
                                  .ai_socktype = SOCK_STREAM };
        const char *incFormat;

        if (getaddrinfo("::", NULL, &hints, &info) == 0) {
            freeaddrinfo(info);
            hostIPv6Capable = true;
        }
        qemuIPv6Capable = virQEMUCapsGet(priv->qemuCaps,
                                         QEMU_CAPS_IPV6_MIGRATION);

        if (listenAddress) {
            if (virSocketAddrNumericFamily(listenAddress) == AF_INET6) {
                if (!qemuIPv6Capable) {
                    virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                                   _("qemu isn't capable of IPv6"));
                    goto cleanup;
                }
                if (!hostIPv6Capable) {
                    virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                                   _("host isn't capable of IPv6"));
                    goto cleanup;
                }
                /* IPv6 address must be escaped in brackets on the cmd line */
                encloseAddress = true;
            } else {
                /* listenAddress is a hostname or IPv4 */
            }
        } else if (qemuIPv6Capable && hostIPv6Capable) {
            /* Listen on :: instead of 0.0.0.0 if QEMU understands it
             * and there is at least one IPv6 address configured
             */
            listenAddress = "::";
            encloseAddress = true;
        } else {
            listenAddress = "0.0.0.0";
        }

        /* QEMU will be started with
         *   -incoming protocol:[<IPv6 addr>]:port,
         *   -incoming protocol:<IPv4 addr>:port, or
         *   -incoming protocol:<hostname>:port
         */
        if (encloseAddress)
            incFormat = "%s:[%s]:%d";
        else
            incFormat = "%s:%s:%d";
        if (virAsprintf(&migrateFrom, incFormat,
                        protocol, listenAddress, port) < 0)
            goto cleanup;
    }

3609 3610
    inc = qemuProcessIncomingDefNew(priv->qemuCaps, listenAddress,
                                    migrateFrom, fd, NULL);
3611

3612
 cleanup:
3613 3614
    VIR_FREE(migrateFrom);
    return inc;
3615 3616
}

3617 3618 3619 3620
static int
qemuMigrationSetCompression(virQEMUDriverPtr driver,
                            virDomainObjPtr vm,
                            qemuDomainAsyncJob job,
3621 3622
                            qemuMigrationCompressionPtr compression,
                            qemuMonitorMigrationParamsPtr migParams)
3623
{
3624 3625 3626
    int ret = -1;
    qemuDomainObjPrivatePtr priv = vm->privateData;

3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
    if (qemuMigrationSetOption(driver, vm,
                               QEMU_MONITOR_MIGRATION_CAPS_XBZRLE,
                               compression->methods &
                                   (1ULL << QEMU_MIGRATION_COMPRESS_XBZRLE),
                               job) < 0)
        return -1;

    if (qemuMigrationSetOption(driver, vm,
                               QEMU_MONITOR_MIGRATION_CAPS_COMPRESS,
                               compression->methods &
                                   (1ULL << QEMU_MIGRATION_COMPRESS_MT),
                               job) < 0)
        return -1;

3641 3642 3643
    if (qemuDomainObjEnterMonitorAsync(driver, vm, job) < 0)
        return -1;

3644 3645
    migParams->compressLevel_set = compression->level_set;
    migParams->compressLevel = compression->level;
3646

3647 3648
    migParams->compressThreads_set = compression->threads_set;
    migParams->compressThreads = compression->threads;
3649

3650 3651
    migParams->decompressThreads_set = compression->dthreads_set;
    migParams->decompressThreads = compression->dthreads;
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664

    if (compression->xbzrle_cache_set &&
        qemuMonitorSetMigrationCacheSize(priv->mon,
                                         compression->xbzrle_cache) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        ret = -1;

    return ret;
3665 3666
}

3667

3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
void
qemuMigrationParamsClear(qemuMonitorMigrationParamsPtr migParams)
{
    if (!migParams)
        return;

    VIR_FREE(migParams->migrateTLSAlias);
    VIR_FREE(migParams->migrateTLSHostname);
}


void
qemuMigrationParamsFree(qemuMonitorMigrationParamsPtr *migParams)
{
    if (!*migParams)
        return;

    qemuMigrationParamsClear(*migParams);
    VIR_FREE(*migParams);
}


3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
/* qemuMigrationSetEmptyTLSParams
 * @driver: pointer to qemu driver
 * @vm: domain object
 * @asyncJob: migration job to join
 * @migParams: Pointer to a migration parameters block
 *
 * If we support setting the tls-creds, then set both tls-creds and
 * tls-hostname to the empty string ("") which indicates to not use
 * TLS on this migration.
 *
 * Returns 0 on success, -1 on failure
 */
static int
qemuMigrationSetEmptyTLSParams(virQEMUDriverPtr driver,
                               virDomainObjPtr vm,
                               qemuDomainAsyncJob asyncJob,
                               qemuMonitorMigrationParamsPtr migParams)
{
   qemuDomainObjPrivatePtr priv = vm->privateData;

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

   if (!priv->migTLSAlias)
       return 0;

   if (VIR_STRDUP(migParams->migrateTLSAlias, "") < 0 ||
       VIR_STRDUP(migParams->migrateTLSHostname, "") < 0)
       return -1;

    return 0;
}


3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764
qemuMonitorMigrationParamsPtr
qemuMigrationParams(virTypedParameterPtr params,
                    int nparams,
                    unsigned long flags)
{
    qemuMonitorMigrationParamsPtr migParams;

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

    if (!params)
        return migParams;

#define GET(PARAM, VAR)                                                     \
    do {                                                                    \
        int rc;                                                             \
        if ((rc = virTypedParamsGetInt(params, nparams,                     \
                                       VIR_MIGRATE_PARAM_ ## PARAM,         \
                                       &migParams->VAR)) < 0)               \
            goto error;                                                     \
                                                                            \
        if (rc == 1)                                                        \
            migParams->VAR ## _set = true;                                  \
    } while (0)

    GET(AUTO_CONVERGE_INITIAL, cpuThrottleInitial);
    GET(AUTO_CONVERGE_INCREMENT, cpuThrottleIncrement);

#undef GET

    if ((migParams->cpuThrottleInitial_set ||
         migParams->cpuThrottleIncrement_set) &&
        !(flags & VIR_MIGRATE_AUTO_CONVERGE)) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Turn auto convergence on to tune it"));
        goto error;
    }

    return migParams;

 error:
3765
    qemuMigrationParamsFree(&migParams);
3766 3767 3768 3769
    return NULL;
}


3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794
static int
qemuMigrationSetParams(virQEMUDriverPtr driver,
                       virDomainObjPtr vm,
                       qemuDomainAsyncJob job,
                       qemuMonitorMigrationParamsPtr migParams)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int ret = -1;

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

    if (qemuMonitorSetMigrationParams(priv->mon, migParams) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        ret = -1;

    return ret;
}


3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859
/* qemuMigrationResetTLS
 * @driver: pointer to qemu driver
 * @vm: domain object
 * @asyncJob: migration job to join
 * @tlsAlias: alias generated for TLS object (may be NULL)
 * @secAlias: alias generated for a secinfo object (may be NULL)
 *
 * Deconstruct all the setup possibly done for TLS - delete the TLS and
 * security objects, fre the secinfo, and reset the migration params to "".
 *
 * Returns 0 on success, -1 on failure
 */
int
qemuMigrationResetTLS(virQEMUDriverPtr driver,
                      virDomainObjPtr vm,
                      qemuDomainAsyncJob asyncJob,
                      char *in_tlsAlias,
                      char *in_secAlias)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    char *tlsAlias = in_tlsAlias;
    char *secAlias = in_secAlias;
    qemuMonitorMigrationParams migParams = { 0 };
    int ret;

    /* If coming from a path that doesn't know whether it's been used or not,
     * let's first check we need to do this. If the tls-creds doesn't exist
     * or if they're set to "" then there's nothing to do since we never set
     * anything up */
    if (!in_tlsAlias && qemuMigrationCheckTLSCreds(driver, vm, asyncJob) < 0)
        return -1;

    if (!priv->migTLSAlias || !*priv->migTLSAlias)
        return 0;

    /* NB: If either or both fail to allocate memory we can still proceed
     *     since the next time we migrate another deletion attempt will be
     *     made after successfully generating the aliases. */
    if (!tlsAlias)
        tlsAlias = qemuAliasTLSObjFromSrcAlias(QEMU_MIGRATION_TLS_ALIAS_BASE);
    if (!secAlias)
        secAlias = qemuDomainGetSecretAESAlias(QEMU_MIGRATION_TLS_ALIAS_BASE,
                                               false);

    qemuDomainDelTLSObjects(driver, vm, asyncJob, secAlias, tlsAlias);
    qemuDomainSecretInfoFree(&priv->migSecinfo);

    if (VIR_STRDUP(migParams.migrateTLSAlias, "") < 0 ||
        VIR_STRDUP(migParams.migrateTLSHostname, "") < 0 ||
        qemuMigrationSetParams(driver, vm, asyncJob, &migParams) < 0)
        goto cleanup;

    ret = 0;

 cleanup:
    if (!in_tlsAlias)
        VIR_FREE(tlsAlias);
    if (!in_secAlias)
        VIR_FREE(secAlias);
    qemuMigrationParamsClear(&migParams);

    return ret;
}


3860
static int
3861
qemuMigrationPrepareAny(virQEMUDriverPtr driver,
3862 3863 3864 3865 3866
                        virConnectPtr dconn,
                        const char *cookiein,
                        int cookieinlen,
                        char **cookieout,
                        int *cookieoutlen,
3867
                        virDomainDefPtr *def,
3868
                        const char *origname,
L
liguang 已提交
3869
                        virStreamPtr st,
3870
                        const char *protocol,
3871 3872
                        unsigned short port,
                        bool autoPort,
3873
                        const char *listenAddress,
3874 3875
                        size_t nmigrate_disks,
                        const char **migrate_disks,
3876
                        int nbdPort,
3877
                        qemuMigrationCompressionPtr compression,
L
liguang 已提交
3878
                        unsigned long flags)
3879 3880
{
    virDomainObjPtr vm = NULL;
3881
    virObjectEventPtr event = NULL;
3882
    virQEMUDriverConfigPtr cfg = NULL;
3883
    int ret = -1;
3884
    int dataFD[2] = { -1, -1 };
3885
    qemuDomainObjPrivatePtr priv = NULL;
3886
    qemuMigrationCookiePtr mig = NULL;
3887
    bool tunnel = !!st;
J
Jiri Denemark 已提交
3888
    char *xmlout = NULL;
L
liguang 已提交
3889
    unsigned int cookieFlags;
3890
    virCapsPtr caps = NULL;
3891
    qemuProcessIncomingDefPtr incoming = NULL;
3892
    bool taint_hook = false;
3893 3894 3895
    bool stopProcess = false;
    bool relabel = false;
    int rv;
3896 3897
    char *tlsAlias = NULL;
    char *secAlias = NULL;
3898
    qemuMonitorMigrationParams migParams = { 0 };
3899

3900 3901
    virNWFilterReadLockFilterUpdates();

L
liguang 已提交
3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921
    if (flags & VIR_MIGRATE_OFFLINE) {
        if (flags & (VIR_MIGRATE_NON_SHARED_DISK |
                     VIR_MIGRATE_NON_SHARED_INC)) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("offline migration cannot handle "
                             "non-shared storage"));
            goto cleanup;
        }
        if (!(flags & VIR_MIGRATE_PERSIST_DEST)) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("offline migration must be specified with "
                             "the persistent flag set"));
            goto cleanup;
        }
        if (tunnel) {
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("tunnelled offline migration does not "
                             "make sense"));
            goto cleanup;
        }
3922 3923 3924
        cookieFlags = 0;
    } else {
        cookieFlags = QEMU_MIGRATION_COOKIE_GRAPHICS;
L
liguang 已提交
3925 3926
    }

3927 3928 3929 3930 3931 3932 3933 3934 3935
    if (flags & VIR_MIGRATE_POSTCOPY &&
        (!(flags & VIR_MIGRATE_LIVE) ||
         flags & VIR_MIGRATE_PAUSED)) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("post-copy migration is not supported with non-live "
                         "or paused migration"));
        goto cleanup;
    }

3936 3937 3938 3939 3940 3941
    if (flags & VIR_MIGRATE_POSTCOPY && flags & VIR_MIGRATE_TUNNELLED) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("post-copy is not supported with tunnelled migration"));
        goto cleanup;
    }

3942 3943 3944
    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

3945
    if (!qemuMigrationIsAllowedHostdev(*def))
3946 3947
        goto cleanup;

J
Jiri Denemark 已提交
3948 3949 3950 3951 3952
    /* Let migration hook filter domain XML */
    if (virHookPresent(VIR_HOOK_DRIVER_QEMU)) {
        char *xml;
        int hookret;

3953
        if (!(xml = qemuDomainDefFormatXML(driver, *def,
3954 3955
                                           VIR_DOMAIN_XML_SECURE |
                                           VIR_DOMAIN_XML_MIGRATABLE)))
J
Jiri Denemark 已提交
3956 3957
            goto cleanup;

3958
        hookret = virHookCall(VIR_HOOK_DRIVER_QEMU, (*def)->name,
J
Jiri Denemark 已提交
3959 3960 3961 3962 3963 3964 3965
                              VIR_HOOK_QEMU_OP_MIGRATE, VIR_HOOK_SUBOP_BEGIN,
                              NULL, xml, &xmlout);
        VIR_FREE(xml);

        if (hookret < 0) {
            goto cleanup;
        } else if (hookret == 0) {
3966
            if (virStringIsEmpty(xmlout)) {
J
Jiri Denemark 已提交
3967 3968 3969 3970 3971 3972
                VIR_DEBUG("Migrate hook filter returned nothing; using the"
                          " original XML");
            } else {
                virDomainDefPtr newdef;

                VIR_DEBUG("Using hook-filtered domain XML: %s", xmlout);
3973
                newdef = virDomainDefParseString(xmlout, caps, driver->xmlopt, NULL,
3974 3975
                                                 VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                                 VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE);
J
Jiri Denemark 已提交
3976 3977 3978
                if (!newdef)
                    goto cleanup;

3979
                if (!qemuDomainDefCheckABIStability(driver, *def, newdef)) {
J
Jiri Denemark 已提交
3980 3981 3982 3983
                    virDomainDefFree(newdef);
                    goto cleanup;
                }

3984 3985
                virDomainDefFree(*def);
                *def = newdef;
3986 3987 3988 3989
                /* We should taint the domain here. However, @vm and therefore
                 * privateData too are still NULL, so just notice the fact and
                 * taint it later. */
                taint_hook = true;
J
Jiri Denemark 已提交
3990 3991 3992 3993
            }
        }
    }

3994
    if (!(vm = virDomainObjListAdd(driver->domains, *def,
3995
                                   driver->xmlopt,
3996 3997 3998
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
3999
        goto cleanup;
4000

4001
    virObjectRef(vm);
4002
    *def = NULL;
4003
    priv = vm->privateData;
4004 4005
    if (VIR_STRDUP(priv->origname, origname) < 0)
        goto cleanup;
4006

4007 4008 4009 4010 4011
    if (taint_hook) {
        /* Domain XML has been altered by a hook script. */
        priv->hookRun = true;
    }

4012
    if (!(mig = qemuMigrationEatCookie(driver, vm, cookiein, cookieinlen,
4013
                                       QEMU_MIGRATION_COOKIE_LOCKSTATE |
4014
                                       QEMU_MIGRATION_COOKIE_NBD |
4015 4016
                                       QEMU_MIGRATION_COOKIE_MEMORY_HOTPLUG |
                                       QEMU_MIGRATION_COOKIE_CPU_HOTPLUG)))
4017 4018
        goto cleanup;

4019 4020
    if (STREQ_NULLABLE(protocol, "rdma") &&
        !virMemoryLimitIsSet(vm->def->mem.hard_limit)) {
M
Michael R. Hines 已提交
4021 4022 4023 4024 4025 4026
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("cannot start RDMA migration with no memory hard "
                         "limit set"));
        goto cleanup;
    }

4027
    if (qemuMigrationPrecreateStorage(dconn, driver, vm, mig->nbd,
4028 4029
                                      nmigrate_disks, migrate_disks,
                                      !!(flags & VIR_MIGRATE_NON_SHARED_INC)) < 0)
4030 4031
        goto cleanup;

4032
    if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
4033
        goto cleanup;
4034
    qemuMigrationJobSetPhase(driver, vm, QEMU_MIGRATION_PHASE_PREPARE);
4035 4036 4037 4038

    /* Domain starts inactive, even if the domain XML had an id field. */
    vm->def->id = -1;

L
liguang 已提交
4039 4040 4041
    if (flags & VIR_MIGRATE_OFFLINE)
        goto done;

4042 4043
    if (tunnel &&
        (pipe(dataFD) < 0 || virSetCloseExec(dataFD[1]) < 0)) {
4044 4045
        virReportSystemError(errno, "%s",
                             _("cannot create pipe for tunnelled migration"));
4046
        goto stopjob;
4047 4048
    }

4049
    if (qemuProcessInit(driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN,
4050
                        true, VIR_QEMU_PROCESS_START_AUTODESTROY) < 0)
4051
        goto stopjob;
4052
    stopProcess = true;
4053

4054 4055 4056
    if (!(incoming = qemuMigrationPrepareIncoming(vm, tunnel, protocol,
                                                  listenAddress, port,
                                                  dataFD[0])))
4057
        goto stopjob;
4058 4059
    dataFD[0] = -1; /* the FD is now owned by incoming */

4060 4061 4062 4063
    if (qemuProcessPrepareDomain(dconn, driver, vm,
                                 VIR_QEMU_PROCESS_START_AUTODESTROY) < 0)
        goto stopjob;

4064 4065 4066
    if (qemuProcessPrepareHost(driver, vm, !!incoming) < 0)
        goto stopjob;

4067 4068 4069 4070 4071 4072 4073
    rv = qemuProcessLaunch(dconn, driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN,
                           incoming, NULL,
                           VIR_NETDEV_VPORT_PROFILE_OP_MIGRATE_IN_START,
                           VIR_QEMU_PROCESS_START_AUTODESTROY);
    if (rv < 0) {
        if (rv == -2)
            relabel = true;
4074
        goto stopjob;
4075
    }
4076
    relabel = true;
4077

4078 4079 4080 4081
    if (tunnel) {
        if (virFDStreamOpen(st, dataFD[1]) < 0) {
            virReportSystemError(errno, "%s",
                                 _("cannot pass pipe for tunnelled migration"));
4082
            goto stopjob;
4083
        }
4084
        dataFD[1] = -1; /* 'st' owns the FD now & will close it */
4085 4086
    }

4087
    if (qemuMigrationSetCompression(driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN,
4088
                                    compression, &migParams) < 0)
4089
        goto stopjob;
4090

4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114
    /* Migrations using TLS need to add the "tls-creds-x509" object and
     * set the migration TLS parameters */
    if (flags & VIR_MIGRATE_TLS) {
        cfg = virQEMUDriverGetConfig(driver);
        if (qemuMigrationCheckSetupTLS(dconn, driver, cfg, vm,
                                       QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
            goto stopjob;

        if (qemuMigrationAddTLSObjects(driver, vm, cfg, true,
                                       QEMU_ASYNC_JOB_MIGRATION_IN,
                                       &tlsAlias, &secAlias, &migParams) < 0)
            goto stopjob;

        /* Force reset of 'tls-hostname', it's a source only parameter */
        if (VIR_STRDUP(migParams.migrateTLSHostname, "") < 0)
            goto stopjob;

    } else {
        if (qemuMigrationSetEmptyTLSParams(driver, vm,
                                           QEMU_ASYNC_JOB_MIGRATION_IN,
                                           &migParams) < 0)
            goto stopjob;
    }

4115
    if (STREQ_NULLABLE(protocol, "rdma") &&
M
Michael R. Hines 已提交
4116
        virProcessSetMaxMemLock(vm->pid, vm->def->mem.hard_limit << 10) < 0) {
4117
        goto stopjob;
M
Michael R. Hines 已提交
4118 4119
    }

4120 4121
    if (qemuMigrationSetOption(driver, vm,
                               QEMU_MONITOR_MIGRATION_CAPS_RDMA_PIN_ALL,
4122 4123
                               flags & VIR_MIGRATE_RDMA_PIN_ALL,
                               QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
4124
        goto stopjob;
4125

4126 4127 4128 4129 4130
    if (qemuMigrationSetPostCopy(driver, vm,
                                 flags & VIR_MIGRATE_POSTCOPY,
                                 QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
        goto stopjob;

4131 4132 4133 4134
    if (qemuMigrationSetParams(driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN,
                               &migParams) < 0)
        goto stopjob;

4135 4136 4137
    if (mig->nbd &&
        flags & (VIR_MIGRATE_NON_SHARED_DISK | VIR_MIGRATE_NON_SHARED_INC) &&
        virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_NBD_SERVER)) {
4138
        if (qemuMigrationStartNBDServer(driver, vm, incoming->address,
4139 4140
                                        nmigrate_disks, migrate_disks,
                                        nbdPort) < 0) {
4141
            goto stopjob;
4142
        }
4143
        cookieFlags |= QEMU_MIGRATION_COOKIE_NBD;
4144 4145
    }

4146 4147 4148 4149 4150 4151 4152 4153 4154
    if (mig->lockState) {
        VIR_DEBUG("Received lockstate %s", mig->lockState);
        VIR_FREE(priv->lockState);
        priv->lockState = mig->lockState;
        mig->lockState = NULL;
    } else {
        VIR_DEBUG("Received no lockstate");
    }

4155 4156 4157 4158 4159 4160 4161 4162 4163
    if (incoming->deferredURI &&
        qemuMigrationRunIncoming(driver, vm, incoming->deferredURI,
                                 QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
        goto stopjob;

    if (qemuProcessFinishStartup(dconn, driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN,
                                 false, VIR_DOMAIN_PAUSED_MIGRATION) < 0)
        goto stopjob;

4164
 done:
4165 4166
    if (qemuMigrationBakeCookie(mig, driver, vm, cookieout,
                                cookieoutlen, cookieFlags) < 0) {
4167 4168 4169 4170 4171 4172 4173
        /* We could tear down the whole guest here, but
         * cookie data is (so far) non-critical, so that
         * seems a little harsh. We'll just warn for now.
         */
        VIR_WARN("Unable to encode migration cookie");
    }

4174
    if (qemuDomainCleanupAdd(vm, qemuMigrationPrepareCleanup) < 0)
4175
        goto stopjob;
4176

L
liguang 已提交
4177 4178
    if (!(flags & VIR_MIGRATE_OFFLINE)) {
        virDomainAuditStart(vm, "migrated", true);
4179
        event = virDomainEventLifecycleNewFromObj(vm,
L
liguang 已提交
4180 4181 4182
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_MIGRATED);
    }
4183

4184 4185 4186 4187
    /* We keep the job active across API calls until the finish() call.
     * This prevents any other APIs being invoked while incoming
     * migration is taking place.
     */
4188
    qemuMigrationJobContinue(vm);
4189

4190 4191
    if (autoPort)
        priv->migrationPort = port;
4192 4193 4194 4195 4196
    /* in this case port is not auto selected and we don't need to manage it
     * anymore after cookie is baked
     */
    if (nbdPort != 0)
        priv->nbdPort = 0;
4197
    ret = 0;
4198

4199
 cleanup:
4200 4201 4202
    VIR_FREE(tlsAlias);
    VIR_FREE(secAlias);
    virObjectUnref(cfg);
4203
    qemuProcessIncomingDefFree(incoming);
J
Jiri Denemark 已提交
4204
    VIR_FREE(xmlout);
4205 4206
    VIR_FORCE_CLOSE(dataFD[0]);
    VIR_FORCE_CLOSE(dataFD[1]);
4207 4208 4209
    if (ret < 0 && priv) {
        /* priv is set right after vm is added to the list of domains
         * and there is no 'goto cleanup;' in the middle of those */
4210
        VIR_FREE(priv->origname);
4211 4212 4213 4214 4215
        /* release if port is auto selected which is not the case if
         * it is given in parameters
         */
        if (nbdPort == 0)
            virPortAllocatorRelease(driver->migrationPorts, priv->nbdPort);
4216
        priv->nbdPort = 0;
4217
        virDomainObjRemoveTransientDef(vm);
4218
        qemuDomainRemoveInactive(driver, vm);
4219
    }
4220
    qemuMigrationParamsClear(&migParams);
M
Michal Privoznik 已提交
4221
    virDomainObjEndAPI(&vm);
4222
    qemuDomainEventQueue(driver, event);
4223
    qemuMigrationCookieFree(mig);
4224
    virObjectUnref(caps);
4225
    virNWFilterUnlockFilterUpdates();
4226
    return ret;
4227

4228
 stopjob:
4229 4230 4231 4232
    ignore_value(qemuMigrationResetTLS(driver, vm,
                                       QEMU_ASYNC_JOB_MIGRATION_IN,
                                       tlsAlias, secAlias));

4233 4234 4235 4236
    if (stopProcess) {
        unsigned int stopFlags = VIR_QEMU_PROCESS_STOP_MIGRATED;
        if (!relabel)
            stopFlags |= VIR_QEMU_PROCESS_STOP_NO_RELABEL;
4237
        virDomainAuditStart(vm, "migrated", false);
4238 4239
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED,
                        QEMU_ASYNC_JOB_MIGRATION_IN, stopFlags);
4240
    }
4241

4242
    qemuMigrationJobFinish(driver, vm);
4243
    goto cleanup;
4244 4245 4246
}


4247 4248 4249 4250 4251
/*
 * This version starts an empty VM listening on a localhost TCP port, and
 * sets up the corresponding virStream to handle the incoming data.
 */
int
4252
qemuMigrationPrepareTunnel(virQEMUDriverPtr driver,
4253 4254 4255 4256 4257 4258
                           virConnectPtr dconn,
                           const char *cookiein,
                           int cookieinlen,
                           char **cookieout,
                           int *cookieoutlen,
                           virStreamPtr st,
4259
                           virDomainDefPtr *def,
4260
                           const char *origname,
L
liguang 已提交
4261
                           unsigned long flags)
4262
{
4263
    qemuMigrationCompressionPtr compression = NULL;
4264 4265 4266
    int ret;

    VIR_DEBUG("driver=%p, dconn=%p, cookiein=%s, cookieinlen=%d, "
4267
              "cookieout=%p, cookieoutlen=%p, st=%p, def=%p, "
4268
              "origname=%s, flags=%lx",
4269
              driver, dconn, NULLSTR(cookiein), cookieinlen,
4270
              cookieout, cookieoutlen, st, *def, origname, flags);
4271

4272 4273 4274 4275 4276 4277
    if (st == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("tunnelled migration requested but NULL stream passed"));
        return -1;
    }

4278 4279 4280
    if (!(compression = qemuMigrationCompressionParse(NULL, 0, flags)))
        return -1;

4281
    ret = qemuMigrationPrepareAny(driver, dconn, cookiein, cookieinlen,
4282
                                  cookieout, cookieoutlen, def, origname,
4283 4284 4285
                                  st, NULL, 0, false, NULL, 0, NULL, 0,
                                  compression, flags);
    VIR_FREE(compression);
4286 4287 4288 4289
    return ret;
}


4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312
static virURIPtr
qemuMigrationParseURI(const char *uri, bool *wellFormed)
{
    char *tmp = NULL;
    virURIPtr parsed;

    /* For compatibility reasons tcp://... URIs are sent as tcp:...
     * We need to transform them to a well-formed URI before parsing. */
    if (STRPREFIX(uri, "tcp:") && !STRPREFIX(uri + 4, "//")) {
        if (virAsprintf(&tmp, "tcp://%s", uri + 4) < 0)
            return NULL;
        uri = tmp;
    }

    parsed = virURIParse(uri);
    if (parsed && wellFormed)
        *wellFormed = !tmp;
    VIR_FREE(tmp);

    return parsed;
}


4313
int
4314
qemuMigrationPrepareDirect(virQEMUDriverPtr driver,
4315
                           virConnectPtr dconn,
4316 4317 4318 4319
                           const char *cookiein,
                           int cookieinlen,
                           char **cookieout,
                           int *cookieoutlen,
4320 4321
                           const char *uri_in,
                           char **uri_out,
4322
                           virDomainDefPtr *def,
4323
                           const char *origname,
4324
                           const char *listenAddress,
4325 4326
                           size_t nmigrate_disks,
                           const char **migrate_disks,
4327
                           int nbdPort,
4328
                           qemuMigrationCompressionPtr compression,
L
liguang 已提交
4329
                           unsigned long flags)
4330
{
4331 4332
    unsigned short port = 0;
    bool autoPort = true;
4333 4334
    char *hostname = NULL;
    int ret = -1;
4335
    virURIPtr uri = NULL;
4336 4337
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    const char *migrateHost = cfg->migrateHost;
J
Jiri Denemark 已提交
4338

4339 4340
    VIR_DEBUG("driver=%p, dconn=%p, cookiein=%s, cookieinlen=%d, "
              "cookieout=%p, cookieoutlen=%p, uri_in=%s, uri_out=%p, "
4341
              "def=%p, origname=%s, listenAddress=%s, "
4342
              "nmigrate_disks=%zu, migrate_disks=%p, nbdPort=%d, flags=%lx",
4343 4344
              driver, dconn, NULLSTR(cookiein), cookieinlen,
              cookieout, cookieoutlen, NULLSTR(uri_in), uri_out,
4345
              *def, origname, NULLSTR(listenAddress),
4346
              nmigrate_disks, migrate_disks, nbdPort, flags);
4347

4348 4349
    *uri_out = NULL;

4350 4351 4352
    /* The URI passed in may be NULL or a string "tcp://somehostname:port".
     *
     * If the URI passed in is NULL then we allocate a port number
4353 4354 4355
     * from our pool of port numbers, and if the migrateHost is configured,
     * we return a URI of "tcp://migrateHost:port", otherwise return a URI
     * of "tcp://ourhostname:port".
4356 4357 4358 4359 4360 4361
     *
     * If the URI passed in is not NULL then we try to parse out the
     * port number and use that (note that the hostname is assumed
     * to be a correct hostname which refers to the target machine).
     */
    if (uri_in == NULL) {
4362 4363 4364
        bool encloseAddress = false;
        const char *incFormat;

4365
        if (virPortAllocatorAcquire(driver->migrationPorts, &port) < 0)
4366
            goto cleanup;
4367

4368
        if (migrateHost != NULL) {
4369 4370
            if (virSocketAddrNumericFamily(migrateHost) == AF_INET6)
                encloseAddress = true;
4371

4372
            if (VIR_STRDUP(hostname, migrateHost) < 0)
4373 4374 4375 4376 4377
                goto cleanup;
        } else {
            if ((hostname = virGetHostname()) == NULL)
                goto cleanup;
        }
4378 4379

        if (STRPREFIX(hostname, "localhost")) {
4380 4381 4382
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("hostname on destination resolved to localhost,"
                             " but migration requires an FQDN"));
4383 4384 4385 4386 4387
            goto cleanup;
        }

        /* XXX this really should have been a properly well-formed
         * URI, but we can't add in tcp:// now without breaking
4388
         * compatibility with old targets. We at least make the
4389 4390
         * new targets accept both syntaxes though.
         */
4391 4392 4393 4394 4395 4396
        if (encloseAddress)
            incFormat = "%s:[%s]:%d";
        else
            incFormat = "%s:%s:%d";

        if (virAsprintf(uri_out, incFormat, "tcp", hostname, port) < 0)
4397 4398
            goto cleanup;
    } else {
4399
        bool well_formed_uri;
J
Ján Tomko 已提交
4400

4401 4402
        if (!(uri = qemuMigrationParseURI(uri_in, &well_formed_uri)))
            goto cleanup;
J
Ján Tomko 已提交
4403

4404 4405 4406 4407 4408 4409 4410
        if (uri->scheme == NULL) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("missing scheme in migration URI: %s"),
                           uri_in);
            goto cleanup;
        }

M
Michael R. Hines 已提交
4411 4412
        if (STRNEQ(uri->scheme, "tcp") &&
            STRNEQ(uri->scheme, "rdma")) {
4413 4414 4415
            virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED,
                           _("unsupported scheme %s in migration URI %s"),
                           uri->scheme, uri_in);
J
Ján Tomko 已提交
4416 4417 4418 4419 4420 4421 4422 4423 4424 4425
            goto cleanup;
        }

        if (uri->server == NULL) {
            virReportError(VIR_ERR_INVALID_ARG, _("missing host in migration"
                                                  " URI: %s"), uri_in);
            goto cleanup;
        }

        if (uri->port == 0) {
4426
            if (virPortAllocatorAcquire(driver->migrationPorts, &port) < 0)
4427
                goto cleanup;
4428

4429
            /* Send well-formed URI only if uri_in was well-formed */
4430 4431 4432 4433 4434 4435 4436 4437
            if (well_formed_uri) {
                uri->port = port;
                if (!(*uri_out = virURIFormat(uri)))
                    goto cleanup;
            } else {
                if (virAsprintf(uri_out, "%s:%d", uri_in, port) < 0)
                    goto cleanup;
            }
4438
        } else {
4439 4440
            port = uri->port;
            autoPort = false;
4441 4442 4443 4444 4445 4446
        }
    }

    if (*uri_out)
        VIR_DEBUG("Generated uri_out=%s", *uri_out);

4447
    ret = qemuMigrationPrepareAny(driver, dconn, cookiein, cookieinlen,
4448
                                  cookieout, cookieoutlen, def, origname,
4449
                                  NULL, uri ? uri->scheme : "tcp",
4450
                                  port, autoPort, listenAddress,
4451 4452
                                  nmigrate_disks, migrate_disks, nbdPort,
                                  compression, flags);
4453
 cleanup:
4454
    virURIFree(uri);
4455
    VIR_FREE(hostname);
4456
    virObjectUnref(cfg);
4457
    if (ret != 0) {
4458
        VIR_FREE(*uri_out);
4459 4460 4461
        if (autoPort)
            virPortAllocatorRelease(driver->migrationPorts, port);
    }
4462 4463 4464 4465
    return ret;
}


4466 4467 4468
virDomainDefPtr
qemuMigrationPrepareDef(virQEMUDriverPtr driver,
                        const char *dom_xml,
4469 4470
                        const char *dname,
                        char **origname)
4471 4472 4473
{
    virCapsPtr caps = NULL;
    virDomainDefPtr def;
4474
    char *name = NULL;
4475 4476 4477 4478 4479 4480 4481 4482 4483 4484

    if (!dom_xml) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("no domain XML passed"));
        return NULL;
    }

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        return NULL;

4485
    if (!(def = virDomainDefParseString(dom_xml, caps, driver->xmlopt, NULL,
4486 4487
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                        VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
4488 4489 4490
        goto cleanup;

    if (dname) {
4491
        name = def->name;
4492 4493 4494 4495 4496 4497
        if (VIR_STRDUP(def->name, dname) < 0) {
            virDomainDefFree(def);
            def = NULL;
        }
    }

4498
 cleanup:
4499
    virObjectUnref(caps);
4500 4501 4502 4503
    if (def && origname)
        *origname = name;
    else
        VIR_FREE(name);
4504 4505 4506 4507
    return def;
}


4508 4509 4510 4511 4512 4513 4514 4515 4516 4517
static int
qemuMigrationConfirmPhase(virQEMUDriverPtr driver,
                          virConnectPtr conn,
                          virDomainObjPtr vm,
                          const char *cookiein,
                          int cookieinlen,
                          unsigned int flags,
                          int retcode)
{
    qemuMigrationCookiePtr mig;
4518
    virObjectEventPtr event;
4519 4520
    int rv = -1;
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
4521 4522
    qemuDomainObjPrivatePtr priv = vm->privateData;
    qemuDomainJobInfoPtr jobInfo = NULL;
4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535

    VIR_DEBUG("driver=%p, conn=%p, vm=%p, cookiein=%s, cookieinlen=%d, "
              "flags=%x, retcode=%d",
              driver, conn, vm, NULLSTR(cookiein), cookieinlen,
              flags, retcode);

    virCheckFlags(QEMU_MIGRATION_FLAGS, -1);

    qemuMigrationJobSetPhase(driver, vm,
                             retcode == 0
                             ? QEMU_MIGRATION_PHASE_CONFIRM3
                             : QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED);

4536 4537
    if (!(mig = qemuMigrationEatCookie(driver, vm, cookiein, cookieinlen,
                                       QEMU_MIGRATION_COOKIE_STATS)))
4538 4539
        goto cleanup;

4540 4541 4542
    if (retcode == 0)
        jobInfo = priv->job.completed;
    else
4543
        VIR_FREE(priv->job.completed);
4544 4545 4546

    /* Update times with the values sent by the destination daemon */
    if (mig->jobInfo && jobInfo) {
4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559
        int reason;

        /* We need to refresh migration statistics after a completed post-copy
         * migration since priv->job.completed contains obsolete data from the
         * time we switched to post-copy mode.
         */
        if (virDomainObjGetState(vm, &reason) == VIR_DOMAIN_PAUSED &&
            reason == VIR_DOMAIN_PAUSED_POSTCOPY &&
            qemuMigrationFetchJobStatus(driver, vm,
                                        QEMU_ASYNC_JOB_MIGRATION_OUT,
                                        jobInfo) < 0)
            VIR_WARN("Could not refresh migration statistics");

4560 4561 4562 4563 4564
        qemuDomainJobInfoUpdateTime(jobInfo);
        jobInfo->timeDeltaSet = mig->jobInfo->timeDeltaSet;
        jobInfo->timeDelta = mig->jobInfo->timeDelta;
        jobInfo->stats.downtime_set = mig->jobInfo->stats.downtime_set;
        jobInfo->stats.downtime = mig->jobInfo->stats.downtime;
4565 4566
    }

4567 4568 4569
    if (flags & VIR_MIGRATE_OFFLINE)
        goto done;

4570 4571
    /* Did the migration go as planned?  If yes, kill off the domain object.
     * If something failed, resume CPUs, but only if we didn't use post-copy.
4572 4573 4574 4575
     */
    if (retcode == 0) {
        /* If guest uses SPICE and supports seamless migration we have to hold
         * up domain shutdown until SPICE server transfers its data */
4576
        qemuMigrationWaitForSpice(vm);
4577 4578

        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_MIGRATED,
4579
                        QEMU_ASYNC_JOB_MIGRATION_OUT,
4580 4581 4582
                        VIR_QEMU_PROCESS_STOP_MIGRATED);
        virDomainAuditStop(vm, "migrated");

4583
        event = virDomainEventLifecycleNewFromObj(vm,
4584 4585
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
4586 4587
        qemuDomainEventQueue(driver, event);
        qemuDomainEventEmitJobCompleted(driver, vm);
4588
    } else {
4589
        virErrorPtr orig_err = virSaveLastError();
4590
        int reason;
4591 4592

        /* cancel any outstanding NBD jobs */
4593
        qemuMigrationCancelDriveMirror(driver, vm, false,
4594
                                       QEMU_ASYNC_JOB_MIGRATION_OUT, NULL);
4595 4596 4597

        virSetError(orig_err);
        virFreeError(orig_err);
4598

4599 4600 4601 4602
        if (virDomainObjGetState(vm, &reason) == VIR_DOMAIN_PAUSED &&
            reason == VIR_DOMAIN_PAUSED_POSTCOPY) {
            qemuMigrationPostcopyFailed(driver, vm);
        } else if (qemuMigrationRestoreDomainState(conn, vm)) {
4603 4604 4605
            event = virDomainEventLifecycleNewFromObj(vm,
                                                      VIR_DOMAIN_EVENT_RESUMED,
                                                      VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
4606
            qemuDomainEventQueue(driver, event);
4607 4608
        }

4609
        if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0)
4610 4611 4612
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
    }

4613
 done:
4614 4615 4616
    qemuMigrationCookieFree(mig);
    rv = 0;

4617
 cleanup:
4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630
    virObjectUnref(cfg);
    return rv;
}

int
qemuMigrationConfirm(virConnectPtr conn,
                     virDomainObjPtr vm,
                     const char *cookiein,
                     int cookieinlen,
                     unsigned int flags,
                     int cancelled)
{
    virQEMUDriverPtr driver = conn->privateData;
4631
    qemuMigrationJobPhase phase;
4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645
    virQEMUDriverConfigPtr cfg = NULL;
    int ret = -1;

    cfg = virQEMUDriverGetConfig(driver);

    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT))
        goto cleanup;

    if (cancelled)
        phase = QEMU_MIGRATION_PHASE_CONFIRM3_CANCELLED;
    else
        phase = QEMU_MIGRATION_PHASE_CONFIRM3;

    qemuMigrationJobStartPhase(driver, vm, phase);
4646 4647
    virCloseCallbacksUnset(driver->closeCallbacks, vm,
                           qemuMigrationCleanup);
4648 4649 4650 4651 4652

    ret = qemuMigrationConfirmPhase(driver, conn, vm,
                                    cookiein, cookieinlen,
                                    flags, cancelled);

4653
    qemuMigrationJobFinish(driver, vm);
4654
    if (!virDomainObjIsActive(vm)) {
4655
        if (flags & VIR_MIGRATE_UNDEFINE_SOURCE) {
4656
            virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm);
4657 4658
            vm->persistent = 0;
        }
4659 4660 4661
        qemuDomainRemoveInactive(driver, vm);
    }

4662
 cleanup:
M
Michal Privoznik 已提交
4663
    virDomainObjEndAPI(&vm);
4664 4665 4666 4667 4668
    virObjectUnref(cfg);
    return ret;
}


4669 4670
enum qemuMigrationDestinationType {
    MIGRATION_DEST_HOST,
4671
    MIGRATION_DEST_CONNECT_HOST,
4672
    MIGRATION_DEST_FD,
4673
};
4674

4675 4676 4677 4678
enum qemuMigrationForwardType {
    MIGRATION_FWD_DIRECT,
    MIGRATION_FWD_STREAM,
};
4679

4680 4681 4682 4683 4684 4685
typedef struct _qemuMigrationSpec qemuMigrationSpec;
typedef qemuMigrationSpec *qemuMigrationSpecPtr;
struct _qemuMigrationSpec {
    enum qemuMigrationDestinationType destType;
    union {
        struct {
4686
            const char *protocol;
4687 4688 4689 4690
            const char *name;
            int port;
        } host;

4691 4692 4693 4694
        struct {
            int qemu;
            int local;
        } fd;
4695 4696 4697 4698 4699 4700 4701
    } dest;

    enum qemuMigrationForwardType fwdType;
    union {
        virStreamPtr stream;
    } fwd;
};
4702 4703 4704

#define TUNNEL_SEND_BUF_SIZE 65536

4705 4706 4707 4708 4709 4710 4711
typedef struct _qemuMigrationIOThread qemuMigrationIOThread;
typedef qemuMigrationIOThread *qemuMigrationIOThreadPtr;
struct _qemuMigrationIOThread {
    virThread thread;
    virStreamPtr st;
    int sock;
    virError err;
4712 4713
    int wakeupRecvFD;
    int wakeupSendFD;
4714 4715 4716
};

static void qemuMigrationIOFunc(void *arg)
4717
{
4718
    qemuMigrationIOThreadPtr data = arg;
4719 4720 4721 4722 4723 4724 4725
    char *buffer = NULL;
    struct pollfd fds[2];
    int timeout = -1;
    virErrorPtr err = NULL;

    VIR_DEBUG("Running migration tunnel; stream=%p, sock=%d",
              data->st, data->sock);
4726

4727
    if (VIR_ALLOC_N(buffer, TUNNEL_SEND_BUF_SIZE) < 0)
4728
        goto abrt;
4729

4730 4731 4732
    fds[0].fd = data->sock;
    fds[1].fd = data->wakeupRecvFD;

4733
    for (;;) {
4734 4735 4736 4737 4738 4739 4740 4741 4742 4743
        int ret;

        fds[0].events = fds[1].events = POLLIN;
        fds[0].revents = fds[1].revents = 0;

        ret = poll(fds, ARRAY_CARDINALITY(fds), timeout);

        if (ret < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
4744
            virReportSystemError(errno, "%s",
4745 4746
                                 _("poll failed in migration tunnel"));
            goto abrt;
4747
        }
4748 4749 4750 4751 4752 4753 4754

        if (ret == 0) {
            /* We were asked to gracefully stop but reading would block. This
             * can only happen if qemu told us migration finished but didn't
             * close the migration fd. We handle this in the same way as EOF.
             */
            VIR_DEBUG("QEMU forgot to close migration fd");
4755
            break;
4756
        }
4757

4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773
        if (fds[1].revents & (POLLIN | POLLERR | POLLHUP)) {
            char stop = 0;

            if (saferead(data->wakeupRecvFD, &stop, 1) != 1) {
                virReportSystemError(errno, "%s",
                                     _("failed to read from wakeup fd"));
                goto abrt;
            }

            VIR_DEBUG("Migration tunnel was asked to %s",
                      stop ? "abort" : "finish");
            if (stop) {
                goto abrt;
            } else {
                timeout = 0;
            }
4774 4775
        }

4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792
        if (fds[0].revents & (POLLIN | POLLERR | POLLHUP)) {
            int nbytes;

            nbytes = saferead(data->sock, buffer, TUNNEL_SEND_BUF_SIZE);
            if (nbytes > 0) {
                if (virStreamSend(data->st, buffer, nbytes) < 0)
                    goto error;
            } else if (nbytes < 0) {
                virReportSystemError(errno, "%s",
                        _("tunnelled migration failed to read from qemu"));
                goto abrt;
            } else {
                /* EOF; get out of here */
                break;
            }
        }
    }
4793

4794 4795
    if (virStreamFinish(data->st) < 0)
        goto error;
4796

4797
    VIR_FORCE_CLOSE(data->sock);
4798 4799
    VIR_FREE(buffer);

4800 4801
    return;

4802
 abrt:
4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813
    err = virSaveLastError();
    if (err && err->code == VIR_ERR_OK) {
        virFreeError(err);
        err = NULL;
    }
    virStreamAbort(data->st);
    if (err) {
        virSetError(err);
        virFreeError(err);
    }

4814
 error:
4815 4816 4817 4818 4819
    /* Let the source qemu know that the transfer cant continue anymore.
     * Don't copy the error for EPIPE as destination has the actual error. */
    VIR_FORCE_CLOSE(data->sock);
    if (!virLastErrorIsSystemErrno(EPIPE))
        virCopyLastError(&data->err);
4820
    virResetLastError();
4821
    VIR_FREE(buffer);
4822 4823 4824 4825 4826 4827 4828
}


static qemuMigrationIOThreadPtr
qemuMigrationStartTunnel(virStreamPtr st,
                         int sock)
{
4829 4830
    qemuMigrationIOThreadPtr io = NULL;
    int wakeupFD[2] = { -1, -1 };
4831

4832 4833 4834 4835
    if (pipe2(wakeupFD, O_CLOEXEC) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to make pipe"));
        goto error;
4836 4837
    }

4838
    if (VIR_ALLOC(io) < 0)
4839
        goto error;
4840

4841 4842
    io->st = st;
    io->sock = sock;
4843 4844
    io->wakeupRecvFD = wakeupFD[0];
    io->wakeupSendFD = wakeupFD[1];
4845 4846 4847 4848 4849 4850

    if (virThreadCreate(&io->thread, true,
                        qemuMigrationIOFunc,
                        io) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to create migration thread"));
4851
        goto error;
4852 4853 4854
    }

    return io;
4855

4856
 error:
4857 4858 4859 4860
    VIR_FORCE_CLOSE(wakeupFD[0]);
    VIR_FORCE_CLOSE(wakeupFD[1]);
    VIR_FREE(io);
    return NULL;
4861 4862 4863
}

static int
4864
qemuMigrationStopTunnel(qemuMigrationIOThreadPtr io, bool error)
4865 4866
{
    int rv = -1;
4867 4868 4869 4870 4871 4872 4873 4874 4875
    char stop = error ? 1 : 0;

    /* make sure the thread finishes its job and is joinable */
    if (safewrite(io->wakeupSendFD, &stop, 1) != 1) {
        virReportSystemError(errno, "%s",
                             _("failed to wakeup migration tunnel"));
        goto cleanup;
    }

4876 4877 4878 4879
    virThreadJoin(&io->thread);

    /* Forward error from the IO thread, to this thread */
    if (io->err.code != VIR_ERR_OK) {
4880 4881 4882 4883
        if (error)
            rv = 0;
        else
            virSetError(&io->err);
4884 4885 4886 4887 4888 4889
        virResetError(&io->err);
        goto cleanup;
    }

    rv = 0;

4890
 cleanup:
4891 4892
    VIR_FORCE_CLOSE(io->wakeupSendFD);
    VIR_FORCE_CLOSE(io->wakeupRecvFD);
4893 4894
    VIR_FREE(io);
    return rv;
4895 4896
}

4897
static int
4898
qemuMigrationConnect(virQEMUDriverPtr driver,
4899 4900 4901 4902 4903 4904 4905 4906 4907
                     virDomainObjPtr vm,
                     qemuMigrationSpecPtr spec)
{
    virNetSocketPtr sock;
    const char *host;
    char *port = NULL;
    int ret = -1;

    host = spec->dest.host.name;
4908
    if (virAsprintf(&port, "%d", spec->dest.host.port) < 0)
4909 4910 4911 4912 4913
        return -1;

    spec->destType = MIGRATION_DEST_FD;
    spec->dest.fd.qemu = -1;

4914
    if (qemuSecuritySetSocketLabel(driver->securityManager, vm->def) < 0)
4915
        goto cleanup;
4916 4917 4918
    if (virNetSocketNewConnectTCP(host, port,
                                  AF_UNSPEC,
                                  &sock) == 0) {
4919
        spec->dest.fd.qemu = virNetSocketDupFD(sock, true);
4920
        virObjectUnref(sock);
4921
    }
4922
    if (qemuSecurityClearSocketLabel(driver->securityManager, vm->def) < 0 ||
4923 4924 4925
        spec->dest.fd.qemu == -1)
        goto cleanup;

4926 4927 4928 4929 4930 4931 4932
    /* Migration expects a blocking FD */
    if (virSetBlocking(spec->dest.fd.qemu, true) < 0) {
        virReportSystemError(errno, _("Unable to set FD %d blocking"),
                             spec->dest.fd.qemu);
        goto cleanup;
    }

4933 4934
    ret = 0;

4935
 cleanup:
4936 4937 4938 4939 4940 4941
    VIR_FREE(port);
    if (ret < 0)
        VIR_FORCE_CLOSE(spec->dest.fd.qemu);
    return ret;
}

4942
static int
4943
qemuMigrationRun(virQEMUDriverPtr driver,
4944
                 virDomainObjPtr vm,
4945
                 const char *persist_xml,
4946 4947 4948 4949 4950 4951
                 const char *cookiein,
                 int cookieinlen,
                 char **cookieout,
                 int *cookieoutlen,
                 unsigned long flags,
                 unsigned long resource,
4952
                 qemuMigrationSpecPtr spec,
4953
                 virConnectPtr dconn,
4954 4955
                 const char *graphicsuri,
                 size_t nmigrate_disks,
4956
                 const char **migrate_disks,
4957 4958
                 qemuMigrationCompressionPtr compression,
                 qemuMonitorMigrationParamsPtr migParams)
4959
{
4960
    int ret = -1;
4961
    unsigned int migrate_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
4962
    virQEMUDriverConfigPtr cfg = NULL;
4963
    qemuDomainObjPrivatePtr priv = vm->privateData;
4964
    qemuMigrationCookiePtr mig = NULL;
4965 4966
    char *tlsAlias = NULL;
    char *secAlias = NULL;
4967
    qemuMigrationIOThreadPtr iothread = NULL;
4968
    int fd = -1;
4969
    unsigned long migrate_speed = resource ? resource : priv->migMaxBandwidth;
4970
    virErrorPtr orig_err = NULL;
4971
    unsigned int cookieFlags = 0;
4972
    bool abort_on_error = !!(flags & VIR_MIGRATE_ABORT_ON_ERROR);
4973
    bool events = virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_MIGRATION_EVENT);
4974
    bool inPostCopy = false;
4975
    unsigned int waitFlags;
4976
    virDomainDefPtr persistDef = NULL;
4977
    char *timestamp;
4978
    int rc;
4979 4980 4981

    VIR_DEBUG("driver=%p, vm=%p, cookiein=%s, cookieinlen=%d, "
              "cookieout=%p, cookieoutlen=%p, flags=%lx, resource=%lu, "
4982 4983
              "spec=%p (dest=%d, fwd=%d), dconn=%p, graphicsuri=%s, "
              "nmigrate_disks=%zu, migrate_disks=%p",
4984 4985
              driver, vm, NULLSTR(cookiein), cookieinlen,
              cookieout, cookieoutlen, flags, resource,
4986
              spec, spec->destType, spec->fwdType, dconn,
4987
              NULLSTR(graphicsuri), nmigrate_disks, migrate_disks);
4988

4989 4990 4991 4992 4993 4994 4995 4996 4997 4998
    if (flags & VIR_MIGRATE_NON_SHARED_DISK) {
        migrate_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_DISK;
        cookieFlags |= QEMU_MIGRATION_COOKIE_NBD;
    }

    if (flags & VIR_MIGRATE_NON_SHARED_INC) {
        migrate_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_INC;
        cookieFlags |= QEMU_MIGRATION_COOKIE_NBD;
    }

4999 5000
    if (virLockManagerPluginUsesState(driver->lockManager) &&
        !cookieout) {
5001 5002 5003 5004
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("Migration with lock driver %s requires"
                         " cookie support"),
                       virLockManagerPluginGetName(driver->lockManager));
5005 5006 5007
        return -1;
    }

5008 5009 5010
    if (events)
        priv->signalIOError = abort_on_error;

5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021
    if (flags & VIR_MIGRATE_PERSIST_DEST) {
        if (persist_xml) {
            persistDef = qemuMigrationPrepareDef(driver, persist_xml,
                                                 NULL, NULL);
            if (!persistDef)
                goto cleanup;
        } else {
            persistDef = vm->newDef;
        }
    }

5022 5023 5024
    mig = qemuMigrationEatCookie(driver, vm, cookiein, cookieinlen,
                                 cookieFlags | QEMU_MIGRATION_COOKIE_GRAPHICS);
    if (!mig)
5025 5026
        goto cleanup;

5027
    if (qemuDomainMigrateGraphicsRelocate(driver, vm, mig, graphicsuri) < 0)
5028 5029
        VIR_WARN("unable to provide data for graphics client relocation");

5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058
    if (flags & VIR_MIGRATE_TLS) {
        cfg = virQEMUDriverGetConfig(driver);

        /* Begin/CheckSetupTLS already set up migTLSAlias, the following
         * assumes that and adds the TLS objects to the domain. */
        if (qemuMigrationAddTLSObjects(driver, vm, cfg, false,
                                       QEMU_ASYNC_JOB_MIGRATION_OUT,
                                       &tlsAlias, &secAlias, migParams) < 0)
            goto cleanup;

        /* We need to add tls-hostname whenever QEMU itself does not
         * connect directly to the destination. */
        if (spec->destType == MIGRATION_DEST_CONNECT_HOST ||
            spec->destType == MIGRATION_DEST_FD) {
            if (VIR_STRDUP(migParams->migrateTLSHostname,
                           spec->dest.host.name) < 0)
                goto cleanup;
        } else {
            /* Be sure there's nothing from a previous migration */
            if (VIR_STRDUP(migParams->migrateTLSHostname, "") < 0)
                goto cleanup;
        }
    } else {
        if (qemuMigrationSetEmptyTLSParams(driver, vm,
                                           QEMU_ASYNC_JOB_MIGRATION_OUT,
                                           migParams) < 0)
            goto cleanup;
    }

5059 5060 5061 5062 5063 5064 5065
    if (migrate_flags & (QEMU_MONITOR_MIGRATE_NON_SHARED_DISK |
                         QEMU_MONITOR_MIGRATE_NON_SHARED_INC)) {
        if (mig->nbd) {
            /* This will update migrate_flags on success */
            if (qemuMigrationDriveMirror(driver, vm, mig,
                                         spec->dest.host.name,
                                         migrate_speed,
5066 5067
                                         &migrate_flags,
                                         nmigrate_disks,
5068 5069
                                         migrate_disks,
                                         dconn) < 0) {
5070 5071 5072 5073 5074 5075 5076 5077
                goto cleanup;
            }
        } else {
            /* Destination doesn't support NBD server.
             * Fall back to previous implementation. */
            VIR_DEBUG("Destination doesn't support NBD server "
                      "Falling back to previous implementation.");
        }
5078 5079
    }

5080
    /* Before EnterMonitor, since qemuMigrationSetOffline already does that */
5081 5082 5083 5084 5085 5086
    if (!(flags & VIR_MIGRATE_LIVE) &&
        virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
        if (qemuMigrationSetOffline(driver, vm) < 0)
            goto cleanup;
    }

5087
    if (qemuMigrationSetCompression(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT,
5088
                                    compression, migParams) < 0)
5089 5090
        goto cleanup;

5091 5092 5093 5094
    if (qemuMigrationSetOption(driver, vm,
                               QEMU_MONITOR_MIGRATION_CAPS_AUTO_CONVERGE,
                               flags & VIR_MIGRATE_AUTO_CONVERGE,
                               QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
5095 5096
        goto cleanup;

5097 5098
    if (qemuMigrationSetOption(driver, vm,
                               QEMU_MONITOR_MIGRATION_CAPS_RDMA_PIN_ALL,
5099
                               flags & VIR_MIGRATE_RDMA_PIN_ALL,
5100 5101 5102
                               QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
        goto cleanup;

5103 5104 5105 5106 5107
    if (qemuMigrationSetPostCopy(driver, vm,
                                 flags & VIR_MIGRATE_POSTCOPY,
                                 QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
        goto cleanup;

5108
    if (qemuMigrationSetParams(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT,
5109
                               migParams) < 0)
5110 5111
        goto cleanup;

5112 5113
    if (qemuDomainObjEnterMonitorAsync(driver, vm,
                                       QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
5114 5115
        goto cleanup;

5116
    if (priv->job.abortJob) {
5117 5118
        /* explicitly do this *after* we entered the monitor,
         * as this is a critical section so we are guaranteed
5119
         * priv->job.abortJob will not change */
5120
        ignore_value(qemuDomainObjExitMonitor(driver, vm));
5121
        priv->job.current->type = VIR_DOMAIN_JOB_CANCELLED;
5122 5123 5124 5125 5126 5127
        virReportError(VIR_ERR_OPERATION_ABORTED, _("%s: %s"),
                       qemuDomainAsyncJobTypeToString(priv->job.asyncJob),
                       _("canceled by client"));
        goto cleanup;
    }

5128 5129
    if (qemuMonitorSetMigrationSpeed(priv->mon, migrate_speed) < 0)
        goto exit_monitor;
5130

5131 5132
    /* connect to the destination qemu if needed */
    if (spec->destType == MIGRATION_DEST_CONNECT_HOST &&
5133
        qemuMigrationConnect(driver, vm, spec) < 0) {
5134
        goto exit_monitor;
5135
    }
5136

5137 5138 5139 5140 5141 5142
    /* log start of migration */
    if ((timestamp = virTimeStringNow()) != NULL) {
        qemuDomainLogAppendMessage(driver, vm, "%s: initiating migration\n", timestamp);
        VIR_FREE(timestamp);
    }

5143 5144
    switch (spec->destType) {
    case MIGRATION_DEST_HOST:
M
Michael R. Hines 已提交
5145 5146
        if (STREQ(spec->dest.host.protocol, "rdma") &&
            virProcessSetMaxMemLock(vm->pid, vm->def->mem.hard_limit << 10) < 0) {
5147
            goto exit_monitor;
M
Michael R. Hines 已提交
5148
        }
5149
        ret = qemuMonitorMigrateToHost(priv->mon, migrate_flags,
5150
                                       spec->dest.host.protocol,
5151 5152 5153 5154
                                       spec->dest.host.name,
                                       spec->dest.host.port);
        break;

5155 5156 5157 5158
    case MIGRATION_DEST_CONNECT_HOST:
        /* handled above and transformed into MIGRATION_DEST_FD */
        break;

5159
    case MIGRATION_DEST_FD:
5160
        if (spec->fwdType != MIGRATION_FWD_DIRECT) {
5161
            fd = spec->dest.fd.local;
5162 5163
            spec->dest.fd.local = -1;
        }
5164 5165 5166 5167
        ret = qemuMonitorMigrateToFd(priv->mon, migrate_flags,
                                     spec->dest.fd.qemu);
        VIR_FORCE_CLOSE(spec->dest.fd.qemu);
        break;
5168
    }
5169 5170
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
        ret = -1;
5171
    if (ret < 0)
5172 5173
        goto cleanup;
    ret = -1;
5174 5175 5176 5177

    /* From this point onwards we *must* call cancel to abort the
     * migration on source if anything goes wrong */

5178 5179 5180 5181 5182 5183 5184 5185
    if (spec->fwdType != MIGRATION_FWD_DIRECT) {
        if (!(iothread = qemuMigrationStartTunnel(spec->fwd.stream, fd)))
            goto cancel;
        /* If we've created a tunnel, then the 'fd' will be closed in the
         * qemuMigrationIOFunc as data->sock.
         */
        fd = -1;
    }
5186

5187 5188 5189 5190 5191 5192 5193 5194
    waitFlags = 0;
    if (abort_on_error)
        waitFlags |= QEMU_MIGRATION_COMPLETED_ABORT_ON_ERROR;
    if (mig->nbd)
        waitFlags |= QEMU_MIGRATION_COMPLETED_CHECK_STORAGE;
    if (flags & VIR_MIGRATE_POSTCOPY)
        waitFlags |= QEMU_MIGRATION_COMPLETED_POSTCOPY;

5195 5196
    rc = qemuMigrationWaitForCompletion(driver, vm,
                                        QEMU_ASYNC_JOB_MIGRATION_OUT,
5197
                                        dconn, waitFlags);
5198 5199 5200
    if (rc == -2)
        goto cancel;
    else if (rc == -1)
5201
        goto cleanup;
5202

5203 5204 5205
    if (priv->job.current->stats.status == QEMU_MONITOR_MIGRATION_STATUS_POSTCOPY)
        inPostCopy = true;

5206 5207 5208
    /* When migration completed, QEMU will have paused the CPUs for us.
     * Wait for the STOP event to be processed or explicitly stop CPUs
     * (for old QEMU which does not send events) to release the lock state.
5209
     */
5210 5211 5212 5213 5214
    if (priv->monJSON) {
        while (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
            priv->signalStop = true;
            rc = virDomainObjWait(vm);
            priv->signalStop = false;
5215 5216
            if (rc < 0)
                goto cancelPostCopy;
5217
        }
5218 5219
    } else if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING &&
               qemuMigrationSetOffline(driver, vm) < 0) {
5220
        goto cancelPostCopy;
5221
    }
5222 5223
    if (priv->job.completed)
        priv->job.completed->stopped = priv->job.current->stopped;
5224

5225
    ret = 0;
5226

5227
 cleanup:
5228 5229 5230
    if (ret < 0 && !orig_err)
        orig_err = virSaveLastError();

5231
    /* cancel any outstanding NBD jobs */
5232
    if (mig && mig->nbd) {
5233
        if (qemuMigrationCancelDriveMirror(driver, vm, ret == 0,
5234 5235
                                           QEMU_ASYNC_JOB_MIGRATION_OUT,
                                           dconn) < 0)
5236 5237
            ret = -1;
    }
5238

5239 5240 5241 5242 5243 5244 5245 5246
    if (qemuMigrationResetTLS(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT,
                              tlsAlias, secAlias) < 0)
        ret = -1;

    VIR_FREE(tlsAlias);
    VIR_FREE(secAlias);
    virObjectUnref(cfg);

5247
    if (spec->fwdType != MIGRATION_FWD_DIRECT) {
5248
        if (iothread && qemuMigrationStopTunnel(iothread, ret < 0) < 0)
5249 5250
            ret = -1;
    }
5251
    VIR_FORCE_CLOSE(fd);
5252

5253
    if (priv->job.completed) {
5254
        qemuDomainJobInfoUpdateTime(priv->job.completed);
5255
        qemuDomainJobInfoUpdateDowntime(priv->job.completed);
5256
        ignore_value(virTimeMillisNow(&priv->job.completed->sent));
5257
    }
5258

5259
    if (priv->job.current->type == VIR_DOMAIN_JOB_UNBOUNDED && !inPostCopy)
5260 5261
        priv->job.current->type = VIR_DOMAIN_JOB_FAILED;

5262 5263
    cookieFlags |= QEMU_MIGRATION_COOKIE_NETWORK |
                   QEMU_MIGRATION_COOKIE_STATS;
5264

5265
    if (ret == 0 &&
5266 5267 5268
        (qemuMigrationCookieAddPersistent(mig, persistDef) < 0 ||
         qemuMigrationBakeCookie(mig, driver, vm, cookieout,
                                 cookieoutlen, cookieFlags) < 0)) {
5269
        VIR_WARN("Unable to encode migration cookie");
5270
    }
5271

5272 5273
    if (persistDef != vm->newDef)
        virDomainDefFree(persistDef);
5274 5275
    qemuMigrationCookieFree(mig);

5276 5277 5278
    if (events)
        priv->signalIOError = false;

5279 5280 5281 5282 5283
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }

5284 5285
    return ret;

5286 5287 5288 5289
 exit_monitor:
    ignore_value(qemuDomainObjExitMonitor(driver, vm));
    goto cleanup;

5290
 cancel:
5291 5292
    orig_err = virSaveLastError();

5293
    if (virDomainObjIsActive(vm)) {
5294 5295
        if (qemuDomainObjEnterMonitorAsync(driver, vm,
                                           QEMU_ASYNC_JOB_MIGRATION_OUT) == 0) {
5296
            qemuMonitorMigrateCancel(priv->mon);
5297
            ignore_value(qemuDomainObjExitMonitor(driver, vm));
5298
        }
5299
    }
5300
    goto cleanup;
5301 5302 5303 5304 5305 5306 5307

 cancelPostCopy:
    priv->job.current->type = VIR_DOMAIN_JOB_FAILED;
    if (inPostCopy)
        goto cancel;
    else
        goto cleanup;
5308 5309
}

5310
/* Perform migration using QEMU's native migrate support,
5311 5312
 * not encrypted obviously
 */
5313
static int doNativeMigrate(virQEMUDriverPtr driver,
5314
                           virDomainObjPtr vm,
5315
                           const char *persist_xml,
5316 5317 5318 5319 5320 5321
                           const char *uri,
                           const char *cookiein,
                           int cookieinlen,
                           char **cookieout,
                           int *cookieoutlen,
                           unsigned long flags,
5322
                           unsigned long resource,
5323
                           virConnectPtr dconn,
5324 5325
                           const char *graphicsuri,
                           size_t nmigrate_disks,
5326
                           const char **migrate_disks,
5327 5328
                           qemuMigrationCompressionPtr compression,
                           qemuMonitorMigrationParamsPtr migParams)
5329
{
5330
    qemuDomainObjPrivatePtr priv = vm->privateData;
M
Martin Kletzander 已提交
5331
    virURIPtr uribits = NULL;
5332
    int ret = -1;
5333 5334 5335
    qemuMigrationSpec spec;

    VIR_DEBUG("driver=%p, vm=%p, uri=%s, cookiein=%s, cookieinlen=%d, "
5336
              "cookieout=%p, cookieoutlen=%p, flags=%lx, resource=%lu, "
5337
              "graphicsuri=%s, nmigrate_disks=%zu migrate_disks=%p",
5338
              driver, vm, uri, NULLSTR(cookiein), cookieinlen,
5339
              cookieout, cookieoutlen, flags, resource,
5340
              NULLSTR(graphicsuri), nmigrate_disks, migrate_disks);
5341

5342
    if (!(uribits = qemuMigrationParseURI(uri, NULL)))
5343 5344
        return -1;

5345 5346 5347 5348 5349 5350 5351
    if (uribits->scheme == NULL) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("missing scheme in migration URI: %s"),
                       uri);
        goto cleanup;
    }

M
Michael R. Hines 已提交
5352 5353 5354 5355 5356
    if (STREQ(uribits->scheme, "rdma")) {
        if (!virQEMUCapsGet(priv->qemuCaps, QEMU_CAPS_MIGRATE_RDMA)) {
            virReportError(VIR_ERR_OPERATION_UNSUPPORTED, "%s",
                           _("outgoing RDMA migration is not supported "
                             "with this QEMU binary"));
5357
            goto cleanup;
M
Michael R. Hines 已提交
5358
        }
5359
        if (!virMemoryLimitIsSet(vm->def->mem.hard_limit)) {
M
Michael R. Hines 已提交
5360 5361 5362
            virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                           _("cannot start RDMA migration with no memory hard "
                             "limit set"));
5363
            goto cleanup;
M
Michael R. Hines 已提交
5364 5365 5366
        }
    }

5367
    if (STRNEQ(uribits->scheme, "rdma"))
5368 5369
        spec.destType = MIGRATION_DEST_CONNECT_HOST;
    else
5370
        spec.destType = MIGRATION_DEST_HOST;
5371
    spec.dest.host.protocol = uribits->scheme;
5372 5373 5374
    spec.dest.host.name = uribits->server;
    spec.dest.host.port = uribits->port;
    spec.fwdType = MIGRATION_FWD_DIRECT;
5375

5376
    ret = qemuMigrationRun(driver, vm, persist_xml, cookiein, cookieinlen, cookieout,
5377
                           cookieoutlen, flags, resource, &spec, dconn,
5378
                           graphicsuri, nmigrate_disks, migrate_disks,
5379
                           compression, migParams);
5380 5381 5382 5383

    if (spec.destType == MIGRATION_DEST_FD)
        VIR_FORCE_CLOSE(spec.dest.fd.qemu);

5384
 cleanup:
5385
    virURIFree(uribits);
5386 5387 5388 5389 5390

    return ret;
}


5391
static int doTunnelMigrate(virQEMUDriverPtr driver,
5392 5393
                           virDomainObjPtr vm,
                           virStreamPtr st,
5394
                           const char *persist_xml,
5395 5396 5397 5398 5399
                           const char *cookiein,
                           int cookieinlen,
                           char **cookieout,
                           int *cookieoutlen,
                           unsigned long flags,
5400
                           unsigned long resource,
5401
                           virConnectPtr dconn,
5402 5403
                           const char *graphicsuri,
                           size_t nmigrate_disks,
5404
                           const char **migrate_disks,
5405 5406
                           qemuMigrationCompressionPtr compression,
                           qemuMonitorMigrationParamsPtr migParams)
5407 5408 5409
{
    int ret = -1;
    qemuMigrationSpec spec;
5410
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
5411
    int fds[2] = { -1, -1 };
5412 5413

    VIR_DEBUG("driver=%p, vm=%p, st=%p, cookiein=%s, cookieinlen=%d, "
5414
              "cookieout=%p, cookieoutlen=%p, flags=%lx, resource=%lu, "
5415
              "graphicsuri=%s, nmigrate_disks=%zu, migrate_disks=%p",
5416
              driver, vm, st, NULLSTR(cookiein), cookieinlen,
5417
              cookieout, cookieoutlen, flags, resource,
5418
              NULLSTR(graphicsuri), nmigrate_disks, migrate_disks);
5419 5420 5421 5422

    spec.fwdType = MIGRATION_FWD_STREAM;
    spec.fwd.stream = st;

5423

5424 5425 5426
    spec.destType = MIGRATION_DEST_FD;
    spec.dest.fd.qemu = -1;
    spec.dest.fd.local = -1;
5427

5428 5429 5430 5431 5432
    if (pipe2(fds, O_CLOEXEC) == 0) {
        spec.dest.fd.qemu = fds[1];
        spec.dest.fd.local = fds[0];
    }
    if (spec.dest.fd.qemu == -1 ||
5433 5434
        qemuSecuritySetImageFDLabel(driver->securityManager, vm->def,
                                    spec.dest.fd.qemu) < 0) {
5435 5436 5437
        virReportSystemError(errno, "%s",
                             _("cannot create pipe for tunnelled migration"));
        goto cleanup;
5438 5439
    }

5440 5441 5442
    ret = qemuMigrationRun(driver, vm, persist_xml, cookiein, cookieinlen,
                           cookieout, cookieoutlen, flags, resource, &spec,
                           dconn, graphicsuri, nmigrate_disks, migrate_disks,
5443
                           compression, migParams);
5444

5445
 cleanup:
5446 5447
    VIR_FORCE_CLOSE(spec.dest.fd.qemu);
    VIR_FORCE_CLOSE(spec.dest.fd.local);
5448

5449
    virObjectUnref(cfg);
5450 5451 5452 5453
    return ret;
}


5454 5455 5456 5457
/* This is essentially a re-impl of virDomainMigrateVersion2
 * from libvirt.c, but running in source libvirtd context,
 * instead of client app context & also adding in tunnel
 * handling */
5458
static int doPeer2PeerMigrate2(virQEMUDriverPtr driver,
5459
                               virConnectPtr sconn ATTRIBUTE_UNUSED,
5460 5461
                               virConnectPtr dconn,
                               virDomainObjPtr vm,
5462
                               const char *dconnuri,
5463 5464 5465
                               unsigned long flags,
                               const char *dname,
                               unsigned long resource)
5466 5467 5468
{
    virDomainPtr ddomain = NULL;
    char *uri_out = NULL;
5469
    char *cookie = NULL;
5470 5471 5472
    char *dom_xml = NULL;
    int cookielen = 0, ret;
    virErrorPtr orig_err = NULL;
5473
    bool cancelled;
5474
    virStreamPtr st = NULL;
5475
    unsigned long destflags;
5476
    qemuMigrationCompressionPtr compression = NULL;
5477
    qemuMonitorMigrationParams migParams = { 0 };
5478

5479
    VIR_DEBUG("driver=%p, sconn=%p, dconn=%p, vm=%p, dconnuri=%s, "
5480
              "flags=%lx, dname=%s, resource=%lu",
5481 5482
              driver, sconn, dconn, vm, NULLSTR(dconnuri),
              flags, NULLSTR(dname), resource);
5483

5484 5485 5486 5487 5488
    /* In version 2 of the protocol, the prepare step is slightly
     * different.  We fetch the domain XML of the source domain
     * and pass it to Prepare2.
     */
    if (!(dom_xml = qemuDomainFormatXML(driver, vm,
5489 5490
                                        QEMU_DOMAIN_FORMAT_LIVE_FLAGS |
                                        VIR_DOMAIN_XML_MIGRATABLE)))
5491 5492 5493 5494 5495
        return -1;

    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED)
        flags |= VIR_MIGRATE_PAUSED;

5496 5497
    destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR |
                          VIR_MIGRATE_AUTO_CONVERGE);
5498

5499 5500 5501
    if (!(compression = qemuMigrationCompressionParse(NULL, 0, flags)))
        goto cleanup;

5502 5503 5504 5505 5506 5507 5508 5509 5510 5511
    VIR_DEBUG("Prepare2 %p", dconn);
    if (flags & VIR_MIGRATE_TUNNELLED) {
        /*
         * Tunnelled Migrate Version 2 does not support cookies
         * due to missing parameters in the prepareTunnel() API.
         */

        if (!(st = virStreamNew(dconn, 0)))
            goto cleanup;

5512
        qemuDomainObjEnterRemote(vm);
5513
        ret = dconn->driver->domainMigratePrepareTunnel
5514
            (dconn, st, destflags, dname, resource, dom_xml);
5515
        qemuDomainObjExitRemote(vm);
5516
    } else {
5517
        qemuDomainObjEnterRemote(vm);
5518 5519
        ret = dconn->driver->domainMigratePrepare2
            (dconn, &cookie, &cookielen, NULL, &uri_out,
5520
             destflags, dname, resource, dom_xml);
5521
        qemuDomainObjExitRemote(vm);
5522 5523 5524
    }
    VIR_FREE(dom_xml);
    if (ret == -1)
5525 5526 5527
        goto cleanup;

    /* the domain may have shutdown or crashed while we had the locks dropped
5528
     * in qemuDomainObjEnterRemote, so check again
5529 5530
     */
    if (!virDomainObjIsActive(vm)) {
5531 5532
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
5533 5534 5535
        goto cleanup;
    }

5536 5537
    if (!(flags & VIR_MIGRATE_TUNNELLED) &&
        (uri_out == NULL)) {
5538 5539
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("domainMigratePrepare2 did not set uri"));
5540
        cancelled = true;
5541
        orig_err = virSaveLastError();
5542
        goto finish;
5543 5544
    }

5545 5546 5547 5548
    /* Perform the migration.  The driver isn't supposed to return
     * until the migration is complete.
     */
    VIR_DEBUG("Perform %p", sconn);
5549
    qemuMigrationJobSetPhase(driver, vm, QEMU_MIGRATION_PHASE_PERFORM2);
5550
    if (flags & VIR_MIGRATE_TUNNELLED)
5551
        ret = doTunnelMigrate(driver, vm, st, NULL,
5552
                              NULL, 0, NULL, NULL,
5553
                              flags, resource, dconn,
5554
                              NULL, 0, NULL, compression, &migParams);
5555
    else
5556
        ret = doNativeMigrate(driver, vm, NULL, uri_out,
5557 5558
                              cookie, cookielen,
                              NULL, NULL, /* No out cookie with v2 migration */
5559 5560
                              flags, resource, dconn, NULL, 0, NULL,
                              compression, &migParams);
5561 5562 5563 5564

    /* Perform failed. Make sure Finish doesn't overwrite the error */
    if (ret < 0)
        orig_err = virSaveLastError();
5565

5566 5567 5568
    /* If Perform returns < 0, then we need to cancel the VM
     * startup on the destination
     */
5569
    cancelled = ret < 0;
5570

5571
 finish:
5572 5573 5574 5575
    /* In version 2 of the migration protocol, we pass the
     * status code from the sender to the destination host,
     * so it can do any cleanup if the migration failed.
     */
5576
    dname = dname ? dname : vm->def->name;
5577
    VIR_DEBUG("Finish2 %p ret=%d", dconn, ret);
5578
    qemuDomainObjEnterRemote(vm);
5579
    ddomain = dconn->driver->domainMigrateFinish2
5580
        (dconn, dname, cookie, cookielen,
5581
         uri_out ? uri_out : dconnuri, destflags, cancelled);
5582
    qemuDomainObjExitRemote(vm);
5583 5584
    if (cancelled && ddomain)
        VIR_ERROR(_("finish step ignored that migration was cancelled"));
5585

5586
 cleanup:
5587
    if (ddomain) {
5588
        virObjectUnref(ddomain);
5589 5590 5591 5592
        ret = 0;
    } else {
        ret = -1;
    }
5593

5594
    virObjectUnref(st);
5595 5596 5597 5598 5599

    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
5600
    qemuMigrationParamsClear(&migParams);
5601
    VIR_FREE(uri_out);
5602
    VIR_FREE(cookie);
5603
    VIR_FREE(compression);
5604 5605

    return ret;
5606 5607 5608
}


5609 5610 5611 5612
/* This is essentially a re-impl of virDomainMigrateVersion3
 * from libvirt.c, but running in source libvirtd context,
 * instead of client app context & also adding in tunnel
 * handling */
5613 5614 5615 5616 5617 5618 5619
static int
doPeer2PeerMigrate3(virQEMUDriverPtr driver,
                    virConnectPtr sconn,
                    virConnectPtr dconn,
                    const char *dconnuri,
                    virDomainObjPtr vm,
                    const char *xmlin,
5620
                    const char *persist_xml,
5621 5622
                    const char *dname,
                    const char *uri,
5623
                    const char *graphicsuri,
5624
                    const char *listenAddress,
5625 5626
                    size_t nmigrate_disks,
                    const char **migrate_disks,
5627
                    int nbdPort,
5628
                    qemuMigrationCompressionPtr compression,
5629
                    qemuMonitorMigrationParamsPtr migParams,
5630 5631 5632
                    unsigned long long bandwidth,
                    bool useParams,
                    unsigned long flags)
5633 5634 5635 5636 5637 5638 5639 5640 5641 5642
{
    virDomainPtr ddomain = NULL;
    char *uri_out = NULL;
    char *cookiein = NULL;
    char *cookieout = NULL;
    char *dom_xml = NULL;
    int cookieinlen = 0;
    int cookieoutlen = 0;
    int ret = -1;
    virErrorPtr orig_err = NULL;
5643
    bool cancelled = true;
5644
    virStreamPtr st = NULL;
5645
    unsigned long destflags;
5646 5647 5648
    virTypedParameterPtr params = NULL;
    int nparams = 0;
    int maxparams = 0;
5649
    size_t i;
5650 5651

    VIR_DEBUG("driver=%p, sconn=%p, dconn=%p, dconnuri=%s, vm=%p, xmlin=%s, "
5652
              "dname=%s, uri=%s, graphicsuri=%s, listenAddress=%s, "
5653 5654
              "nmigrate_disks=%zu, migrate_disks=%p, nbdPort=%d, "
              "bandwidth=%llu, useParams=%d, flags=%lx",
5655
              driver, sconn, dconn, NULLSTR(dconnuri), vm, NULLSTR(xmlin),
5656
              NULLSTR(dname), NULLSTR(uri), NULLSTR(graphicsuri),
5657
              NULLSTR(listenAddress), nmigrate_disks, migrate_disks, nbdPort,
5658
              bandwidth, useParams, flags);
5659

5660 5661 5662 5663 5664
    /* Unlike the virDomainMigrateVersion3 counterpart, we don't need
     * to worry about auto-setting the VIR_MIGRATE_CHANGE_PROTECTION
     * bit here, because we are already running inside the context of
     * a single job.  */

5665
    dom_xml = qemuMigrationBeginPhase(driver, vm, xmlin, dname,
5666 5667
                                      &cookieout, &cookieoutlen,
                                      nmigrate_disks, migrate_disks, flags);
5668 5669 5670
    if (!dom_xml)
        goto cleanup;

5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690
    if (useParams) {
        if (virTypedParamsAddString(&params, &nparams, &maxparams,
                                    VIR_MIGRATE_PARAM_DEST_XML, dom_xml) < 0)
            goto cleanup;

        if (dname &&
            virTypedParamsAddString(&params, &nparams, &maxparams,
                                    VIR_MIGRATE_PARAM_DEST_NAME, dname) < 0)
            goto cleanup;

        if (uri &&
            virTypedParamsAddString(&params, &nparams, &maxparams,
                                    VIR_MIGRATE_PARAM_URI, uri) < 0)
            goto cleanup;

        if (bandwidth &&
            virTypedParamsAddULLong(&params, &nparams, &maxparams,
                                    VIR_MIGRATE_PARAM_BANDWIDTH,
                                    bandwidth) < 0)
            goto cleanup;
5691 5692 5693 5694 5695 5696

        if (graphicsuri &&
            virTypedParamsAddString(&params, &nparams, &maxparams,
                                    VIR_MIGRATE_PARAM_GRAPHICS_URI,
                                    graphicsuri) < 0)
            goto cleanup;
5697 5698 5699 5700 5701
        if (listenAddress &&
            virTypedParamsAddString(&params, &nparams, &maxparams,
                                    VIR_MIGRATE_PARAM_LISTEN_ADDRESS,
                                    listenAddress) < 0)
            goto cleanup;
5702 5703 5704 5705 5706
        for (i = 0; i < nmigrate_disks; i++)
            if (virTypedParamsAddString(&params, &nparams, &maxparams,
                                        VIR_MIGRATE_PARAM_MIGRATE_DISKS,
                                        migrate_disks[i]) < 0)
                goto cleanup;
5707 5708 5709 5710 5711
        if (nbdPort &&
            virTypedParamsAddInt(&params, &nparams, &maxparams,
                                 VIR_MIGRATE_PARAM_DISKS_PORT,
                                 nbdPort) < 0)
            goto cleanup;
5712 5713 5714 5715

        if (qemuMigrationCompressionDump(compression, &params, &nparams,
                                         &maxparams, &flags) < 0)
            goto cleanup;
5716 5717
    }

5718 5719 5720
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED)
        flags |= VIR_MIGRATE_PAUSED;

5721 5722
    destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR |
                          VIR_MIGRATE_AUTO_CONVERGE);
5723

5724 5725 5726 5727 5728 5729 5730 5731 5732
    VIR_DEBUG("Prepare3 %p", dconn);
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
    if (flags & VIR_MIGRATE_TUNNELLED) {
        if (!(st = virStreamNew(dconn, 0)))
            goto cleanup;

5733
        qemuDomainObjEnterRemote(vm);
5734 5735 5736 5737 5738 5739 5740 5741 5742
        if (useParams) {
            ret = dconn->driver->domainMigratePrepareTunnel3Params
                (dconn, st, params, nparams, cookiein, cookieinlen,
                 &cookieout, &cookieoutlen, destflags);
        } else {
            ret = dconn->driver->domainMigratePrepareTunnel3
                (dconn, st, cookiein, cookieinlen, &cookieout, &cookieoutlen,
                 destflags, dname, bandwidth, dom_xml);
        }
5743
        qemuDomainObjExitRemote(vm);
5744
    } else {
5745
        qemuDomainObjEnterRemote(vm);
5746 5747 5748 5749 5750 5751 5752 5753 5754
        if (useParams) {
            ret = dconn->driver->domainMigratePrepare3Params
                (dconn, params, nparams, cookiein, cookieinlen,
                 &cookieout, &cookieoutlen, &uri_out, destflags);
        } else {
            ret = dconn->driver->domainMigratePrepare3
                (dconn, cookiein, cookieinlen, &cookieout, &cookieoutlen,
                 uri, &uri_out, destflags, dname, bandwidth, dom_xml);
        }
5755
        qemuDomainObjExitRemote(vm);
5756 5757 5758 5759 5760
    }
    VIR_FREE(dom_xml);
    if (ret == -1)
        goto cleanup;

L
liguang 已提交
5761 5762 5763 5764
    if (flags & VIR_MIGRATE_OFFLINE) {
        VIR_DEBUG("Offline migration, skipping Perform phase");
        VIR_FREE(cookieout);
        cookieoutlen = 0;
5765
        cancelled = false;
L
liguang 已提交
5766 5767 5768
        goto finish;
    }

5769 5770 5771 5772
    if (uri_out) {
        uri = uri_out;
        if (useParams &&
            virTypedParamsReplaceString(&params, &nparams,
5773 5774
                                        VIR_MIGRATE_PARAM_URI, uri_out) < 0) {
            orig_err = virSaveLastError();
5775
            goto finish;
5776
        }
5777
    } else if (!uri && !(flags & VIR_MIGRATE_TUNNELLED)) {
5778 5779
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("domainMigratePrepare3 did not set uri"));
5780
        orig_err = virSaveLastError();
5781 5782 5783 5784 5785 5786 5787 5788
        goto finish;
    }

    /* Perform the migration.  The driver isn't supposed to return
     * until the migration is complete. The src VM should remain
     * running, but in paused state until the destination can
     * confirm migration completion.
     */
5789
    VIR_DEBUG("Perform3 %p uri=%s", sconn, NULLSTR(uri));
5790
    qemuMigrationJobSetPhase(driver, vm, QEMU_MIGRATION_PHASE_PERFORM3);
5791 5792 5793 5794 5795
    VIR_FREE(cookiein);
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
5796
    if (flags & VIR_MIGRATE_TUNNELLED) {
5797
        ret = doTunnelMigrate(driver, vm, st, persist_xml,
5798 5799
                              cookiein, cookieinlen,
                              &cookieout, &cookieoutlen,
5800
                              flags, bandwidth, dconn, graphicsuri,
5801 5802
                              nmigrate_disks, migrate_disks, compression,
                              migParams);
5803
    } else {
5804
        ret = doNativeMigrate(driver, vm, persist_xml, uri,
5805 5806
                              cookiein, cookieinlen,
                              &cookieout, &cookieoutlen,
5807
                              flags, bandwidth, dconn, graphicsuri,
5808 5809
                              nmigrate_disks, migrate_disks, compression,
                              migParams);
5810
    }
5811 5812

    /* Perform failed. Make sure Finish doesn't overwrite the error */
5813
    if (ret < 0) {
5814
        orig_err = virSaveLastError();
5815 5816 5817 5818
    } else {
        qemuMigrationJobSetPhase(driver, vm,
                                 QEMU_MIGRATION_PHASE_PERFORM3_DONE);
    }
5819 5820 5821 5822

    /* If Perform returns < 0, then we need to cancel the VM
     * startup on the destination
     */
5823
    cancelled = ret < 0;
5824

5825
 finish:
5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837
    /*
     * The status code from the source is passed to the destination.
     * The dest can cleanup in the source indicated it failed to
     * send all migration data. Returns NULL for ddomain if
     * the dest was unable to complete migration.
     */
    VIR_DEBUG("Finish3 %p ret=%d", dconn, ret);
    VIR_FREE(cookiein);
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860

    if (useParams) {
        if (virTypedParamsGetString(params, nparams,
                                    VIR_MIGRATE_PARAM_DEST_NAME, NULL) <= 0 &&
            virTypedParamsReplaceString(&params, &nparams,
                                        VIR_MIGRATE_PARAM_DEST_NAME,
                                        vm->def->name) < 0) {
            ddomain = NULL;
        } else {
            qemuDomainObjEnterRemote(vm);
            ddomain = dconn->driver->domainMigrateFinish3Params
                (dconn, params, nparams, cookiein, cookieinlen,
                 &cookieout, &cookieoutlen, destflags, cancelled);
            qemuDomainObjExitRemote(vm);
        }
    } else {
        dname = dname ? dname : vm->def->name;
        qemuDomainObjEnterRemote(vm);
        ddomain = dconn->driver->domainMigrateFinish3
            (dconn, dname, cookiein, cookieinlen, &cookieout, &cookieoutlen,
             dconnuri, uri, destflags, cancelled);
        qemuDomainObjExitRemote(vm);
    }
5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880

    if (cancelled) {
        if (ddomain) {
            VIR_ERROR(_("finish step ignored that migration was cancelled"));
        } else {
            /* If Finish reported a useful error, use it instead of the
             * original "migration unexpectedly failed" error.
             *
             * This is ugly but we can't do better with the APIs we have. We
             * only replace the error if Finish was called with cancelled == 1
             * and reported a real error (old libvirt would report an error
             * from RPC instead of MIGRATE_FINISH_OK), which only happens when
             * the domain died on destination. To further reduce a possibility
             * of false positives we also check that Perform returned
             * VIR_ERR_OPERATION_FAILED.
             */
            if (orig_err &&
                orig_err->domain == VIR_FROM_QEMU &&
                orig_err->code == VIR_ERR_OPERATION_FAILED) {
                virErrorPtr err = virGetLastError();
5881 5882
                if (err &&
                    err->domain == VIR_FROM_QEMU &&
5883 5884 5885 5886 5887 5888 5889
                    err->code != VIR_ERR_MIGRATE_FINISH_OK) {
                    virFreeError(orig_err);
                    orig_err = NULL;
                }
            }
        }
    }
5890

5891 5892 5893 5894 5895 5896 5897
    /* If ddomain is NULL, then we were unable to start
     * the guest on the target, and must restart on the
     * source. There is a small chance that the ddomain
     * is NULL due to an RPC failure, in which case
     * ddomain could in fact be running on the dest.
     * The lock manager plugins should take care of
     * safety in this scenario.
5898
     */
5899
    cancelled = ddomain == NULL;
5900

5901 5902 5903 5904 5905 5906
    /* If finish3 set an error, and we don't have an earlier
     * one we need to preserve it in case confirm3 overwrites
     */
    if (!orig_err)
        orig_err = virSaveLastError();

5907 5908 5909 5910
    /*
     * If cancelled, then src VM will be restarted, else
     * it will be killed
     */
5911
    VIR_DEBUG("Confirm3 %p cancelled=%d vm=%p", sconn, cancelled, vm);
5912 5913 5914 5915 5916
    VIR_FREE(cookiein);
    cookiein = cookieout;
    cookieinlen = cookieoutlen;
    cookieout = NULL;
    cookieoutlen = 0;
5917 5918 5919
    ret = qemuMigrationConfirmPhase(driver, sconn, vm,
                                    cookiein, cookieinlen,
                                    flags, cancelled);
5920 5921 5922 5923
    /* If Confirm3 returns -1, there's nothing more we can
     * do, but fortunately worst case is that there is a
     * domain left in 'paused' state on source.
     */
5924 5925 5926
    if (ret < 0)
        VIR_WARN("Guest %s probably left in 'paused' state on source",
                 vm->def->name);
5927 5928 5929

 cleanup:
    if (ddomain) {
5930
        virObjectUnref(ddomain);
5931 5932 5933 5934 5935
        ret = 0;
    } else {
        ret = -1;
    }

5936
    virObjectUnref(st);
5937 5938 5939 5940 5941 5942 5943 5944

    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
    VIR_FREE(uri_out);
    VIR_FREE(cookiein);
    VIR_FREE(cookieout);
5945
    virTypedParamsFree(params, nparams);
5946 5947 5948 5949
    return ret;
}


5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961
static void
qemuMigrationConnectionClosed(virConnectPtr conn,
                              int reason,
                              void *opaque)
{
    virDomainObjPtr vm = opaque;

    VIR_DEBUG("conn=%p, reason=%d, vm=%s", conn, reason, vm->def->name);
    virDomainObjBroadcast(vm);
}


5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973
static int virConnectCredType[] = {
    VIR_CRED_AUTHNAME,
    VIR_CRED_PASSPHRASE,
};


static virConnectAuth virConnectAuthConfig = {
    .credtype = virConnectCredType,
    .ncredtype = ARRAY_CARDINALITY(virConnectCredType),
};


5974
static int doPeer2PeerMigrate(virQEMUDriverPtr driver,
5975
                              virConnectPtr sconn,
5976
                              virDomainObjPtr vm,
5977
                              const char *xmlin,
5978
                              const char *persist_xml,
5979
                              const char *dconnuri,
5980
                              const char *uri,
5981
                              const char *graphicsuri,
5982
                              const char *listenAddress,
5983 5984
                              size_t nmigrate_disks,
                              const char **migrate_disks,
5985
                              int nbdPort,
5986
                              qemuMigrationCompressionPtr compression,
5987
                              qemuMonitorMigrationParamsPtr migParams,
5988 5989
                              unsigned long flags,
                              const char *dname,
5990 5991
                              unsigned long resource,
                              bool *v3proto)
5992 5993 5994 5995
{
    int ret = -1;
    virConnectPtr dconn = NULL;
    bool p2p;
5996
    virErrorPtr orig_err = NULL;
5997
    bool offline = false;
5998
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
5999
    bool useParams;
6000

6001 6002
    VIR_DEBUG("driver=%p, sconn=%p, vm=%p, xmlin=%s, dconnuri=%s, uri=%s, "
              "graphicsuri=%s, listenAddress=%s, nmigrate_disks=%zu, "
6003 6004
              "migrate_disks=%p, nbdPort=%d, flags=%lx, dname=%s, "
              "resource=%lu",
6005
              driver, sconn, vm, NULLSTR(xmlin), NULLSTR(dconnuri),
6006
              NULLSTR(uri), NULLSTR(graphicsuri), NULLSTR(listenAddress),
6007 6008
              nmigrate_disks, migrate_disks, nbdPort, flags, NULLSTR(dname),
              resource);
6009

6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023
    if (flags & VIR_MIGRATE_TUNNELLED && uri) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("migration URI is not supported by tunnelled "
                         "migration"));
        goto cleanup;
    }

    if (flags & VIR_MIGRATE_TUNNELLED && listenAddress) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("listen address is not supported by tunnelled "
                         "migration"));
        goto cleanup;
    }

6024 6025 6026 6027 6028 6029 6030
    if (flags & VIR_MIGRATE_TUNNELLED && nbdPort) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("disk port address is not supported by tunnelled "
                         "migration"));
        goto cleanup;
    }

6031 6032 6033 6034
    /* the order of operations is important here; we make sure the
     * destination side is completely setup before we touch the source
     */

6035
    qemuDomainObjEnterRemote(vm);
6036
    dconn = virConnectOpenAuth(dconnuri, &virConnectAuthConfig, 0);
6037
    qemuDomainObjExitRemote(vm);
6038
    if (dconn == NULL) {
6039
        virReportError(VIR_ERR_OPERATION_FAILED,
6040 6041
                       _("Failed to connect to remote libvirt URI %s: %s"),
                       dconnuri, virGetLastErrorMessage());
6042
        virObjectUnref(cfg);
6043 6044 6045
        return -1;
    }

6046 6047
    if (virConnectSetKeepAlive(dconn, cfg->keepAliveInterval,
                               cfg->keepAliveCount) < 0)
6048 6049
        goto cleanup;

6050 6051 6052 6053 6054
    if (virConnectRegisterCloseCallback(dconn, qemuMigrationConnectionClosed,
                                        vm, NULL) < 0) {
        goto cleanup;
    }

6055
    qemuDomainObjEnterRemote(vm);
6056 6057
    p2p = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                   VIR_DRV_FEATURE_MIGRATION_P2P);
6058
        /* v3proto reflects whether the caller used Perform3, but with
6059
         * p2p migrate, regardless of whether Perform2 or Perform3
6060 6061 6062 6063
         * were used, we decide protocol based on what target supports
         */
    *v3proto = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                        VIR_DRV_FEATURE_MIGRATION_V3);
6064 6065
    useParams = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                         VIR_DRV_FEATURE_MIGRATION_PARAMS);
L
liguang 已提交
6066 6067 6068
    if (flags & VIR_MIGRATE_OFFLINE)
        offline = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                           VIR_DRV_FEATURE_MIGRATION_OFFLINE);
6069
    qemuDomainObjExitRemote(vm);
6070

6071
    if (!p2p) {
6072 6073
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Destination libvirt does not support peer-to-peer migration protocol"));
6074 6075 6076
        goto cleanup;
    }

6077 6078
    /* Only xmlin, dname, uri, and bandwidth parameters can be used with
     * old-style APIs. */
6079
    if (!useParams && (graphicsuri || listenAddress || nmigrate_disks)) {
6080 6081 6082 6083 6084 6085
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("Migration APIs with extensible parameters are not "
                         "supported but extended parameters were passed"));
        goto cleanup;
    }

L
liguang 已提交
6086 6087 6088 6089 6090 6091 6092
    if (flags & VIR_MIGRATE_OFFLINE && !offline) {
        virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
                       _("offline migration is not supported by "
                         "the destination host"));
        goto cleanup;
    }

6093
    /* domain may have been stopped while we were talking to remote daemon */
L
liguang 已提交
6094
    if (!virDomainObjIsActive(vm) && !(flags & VIR_MIGRATE_OFFLINE)) {
6095 6096
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
6097 6098 6099
        goto cleanup;
    }

6100 6101 6102 6103 6104 6105 6106
    /* Change protection is only required on the source side (us), and
     * only for v3 migration when begin and perform are separate jobs.
     * But peer-2-peer is already a single job, and we still want to
     * talk to older destinations that would reject the flag.
     * Therefore it is safe to clear the bit here.  */
    flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;

6107 6108
    if (*v3proto) {
        ret = doPeer2PeerMigrate3(driver, sconn, dconn, dconnuri, vm, xmlin,
6109 6110
                                  persist_xml, dname, uri, graphicsuri,
                                  listenAddress, nmigrate_disks, migrate_disks,
6111 6112
                                  nbdPort, compression, migParams, resource,
                                  useParams, flags);
6113
    } else {
6114
        ret = doPeer2PeerMigrate2(driver, sconn, dconn, vm,
6115
                                  dconnuri, flags, dname, resource);
6116
    }
6117

6118
 cleanup:
6119
    orig_err = virSaveLastError();
6120
    qemuDomainObjEnterRemote(vm);
6121
    virConnectUnregisterCloseCallback(dconn, qemuMigrationConnectionClosed);
6122
    virObjectUnref(dconn);
6123
    qemuDomainObjExitRemote(vm);
6124 6125 6126 6127
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
6128
    virObjectUnref(cfg);
6129 6130 6131 6132
    return ret;
}


6133 6134 6135 6136 6137 6138
/*
 * This implements perform part of the migration protocol when migration job
 * does not need to be active across several APIs, i.e., peer2peer migration or
 * perform phase of v2 non-peer2peer migration.
 */
static int
6139
qemuMigrationPerformJob(virQEMUDriverPtr driver,
6140 6141 6142
                        virConnectPtr conn,
                        virDomainObjPtr vm,
                        const char *xmlin,
6143
                        const char *persist_xml,
6144 6145
                        const char *dconnuri,
                        const char *uri,
6146
                        const char *graphicsuri,
6147
                        const char *listenAddress,
6148 6149
                        size_t nmigrate_disks,
                        const char **migrate_disks,
6150
                        int nbdPort,
6151
                        qemuMigrationCompressionPtr compression,
6152
                        qemuMonitorMigrationParamsPtr migParams,
6153
                        const char *cookiein,
6154 6155 6156 6157 6158 6159 6160
                        int cookieinlen,
                        char **cookieout,
                        int *cookieoutlen,
                        unsigned long flags,
                        const char *dname,
                        unsigned long resource,
                        bool v3proto)
6161
{
6162
    virObjectEventPtr event = NULL;
6163
    int ret = -1;
6164
    virErrorPtr orig_err = NULL;
6165
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
6166

6167
    if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
6168 6169
        goto cleanup;

L
liguang 已提交
6170
    if (!virDomainObjIsActive(vm) && !(flags & VIR_MIGRATE_OFFLINE)) {
6171 6172
        virReportError(VIR_ERR_OPERATION_INVALID,
                       "%s", _("domain is not running"));
6173 6174 6175
        goto endjob;
    }

6176
    if (!qemuMigrationIsAllowed(driver, vm, true, flags))
6177
        goto endjob;
6178

6179 6180
    if (!(flags & VIR_MIGRATE_UNSAFE) &&
        !qemuMigrationIsSafe(vm->def, nmigrate_disks, migrate_disks))
6181
        goto endjob;
6182

6183
    qemuMigrationStoreDomainState(vm);
6184 6185

    if ((flags & (VIR_MIGRATE_TUNNELLED | VIR_MIGRATE_PEER2PEER))) {
6186
        ret = doPeer2PeerMigrate(driver, conn, vm, xmlin, persist_xml,
6187
                                 dconnuri, uri, graphicsuri, listenAddress,
6188
                                 nmigrate_disks, migrate_disks, nbdPort,
6189 6190
                                 compression, migParams, flags, dname, resource,
                                 &v3proto);
6191
    } else {
6192
        qemuMigrationJobSetPhase(driver, vm, QEMU_MIGRATION_PHASE_PERFORM2);
6193
        ret = doNativeMigrate(driver, vm, persist_xml, uri, cookiein, cookieinlen,
6194
                              cookieout, cookieoutlen,
6195
                              flags, resource, NULL, NULL, 0, NULL,
6196
                              compression, migParams);
6197
    }
6198 6199
    if (ret < 0)
        goto endjob;
6200

6201 6202 6203 6204
    /*
     * In v3 protocol, the source VM is not killed off until the
     * confirm step.
     */
6205
    if (!v3proto) {
6206
        qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_MIGRATED,
6207
                        QEMU_ASYNC_JOB_MIGRATION_OUT,
6208
                        VIR_QEMU_PROCESS_STOP_MIGRATED);
6209
        virDomainAuditStop(vm, "migrated");
6210
        event = virDomainEventLifecycleNewFromObj(vm,
6211 6212
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
6213 6214
    }

6215
 endjob:
6216 6217 6218
    if (ret < 0)
        orig_err = virSaveLastError();

6219
    if (qemuMigrationRestoreDomainState(conn, vm)) {
6220
        event = virDomainEventLifecycleNewFromObj(vm,
6221 6222 6223
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
    }
6224

6225
    qemuMigrationJobFinish(driver, vm);
6226
    if (!virDomainObjIsActive(vm) && ret == 0) {
6227
        if (flags & VIR_MIGRATE_UNDEFINE_SOURCE) {
6228
            virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm);
6229 6230
            vm->persistent = 0;
        }
6231
        qemuDomainRemoveInactive(driver, vm);
6232 6233
    }

6234 6235 6236 6237 6238
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }

6239
 cleanup:
M
Michal Privoznik 已提交
6240
    virDomainObjEndAPI(&vm);
6241
    qemuDomainEventQueue(driver, event);
6242
    virObjectUnref(cfg);
6243 6244 6245 6246 6247 6248 6249
    return ret;
}

/*
 * This implements perform phase of v3 migration protocol.
 */
static int
6250
qemuMigrationPerformPhase(virQEMUDriverPtr driver,
6251 6252
                          virConnectPtr conn,
                          virDomainObjPtr vm,
6253
                          const char *persist_xml,
6254
                          const char *uri,
6255
                          const char *graphicsuri,
6256 6257
                          size_t nmigrate_disks,
                          const char **migrate_disks,
6258
                          qemuMigrationCompressionPtr compression,
6259
                          qemuMonitorMigrationParamsPtr migParams,
6260 6261 6262 6263 6264 6265 6266
                          const char *cookiein,
                          int cookieinlen,
                          char **cookieout,
                          int *cookieoutlen,
                          unsigned long flags,
                          unsigned long resource)
{
6267
    virObjectEventPtr event = NULL;
6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278
    int ret = -1;

    /* If we didn't start the job in the begin phase, start it now. */
    if (!(flags & VIR_MIGRATE_CHANGE_PROTECTION)) {
        if (qemuMigrationJobStart(driver, vm, QEMU_ASYNC_JOB_MIGRATION_OUT) < 0)
            goto cleanup;
    } else if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_OUT)) {
        goto cleanup;
    }

    qemuMigrationJobStartPhase(driver, vm, QEMU_MIGRATION_PHASE_PERFORM3);
6279 6280
    virCloseCallbacksUnset(driver->closeCallbacks, vm,
                           qemuMigrationCleanup);
6281

6282
    ret = doNativeMigrate(driver, vm, persist_xml, uri, cookiein, cookieinlen,
6283
                          cookieout, cookieoutlen,
6284
                          flags, resource, NULL, graphicsuri,
6285
                          nmigrate_disks, migrate_disks, compression, migParams);
6286

6287 6288 6289 6290 6291
    if (ret < 0) {
        if (qemuMigrationRestoreDomainState(conn, vm)) {
            event = virDomainEventLifecycleNewFromObj(vm,
                                                      VIR_DOMAIN_EVENT_RESUMED,
                                                      VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
6292
        }
6293
        goto endjob;
6294
    }
6295 6296 6297

    qemuMigrationJobSetPhase(driver, vm, QEMU_MIGRATION_PHASE_PERFORM3_DONE);

6298 6299
    if (virCloseCallbacksSet(driver->closeCallbacks, vm, conn,
                             qemuMigrationCleanup) < 0)
6300 6301
        goto endjob;

6302
 endjob:
6303
    if (ret < 0)
6304
        qemuMigrationJobFinish(driver, vm);
6305
    else
6306
        qemuMigrationJobContinue(vm);
6307
    if (!virDomainObjIsActive(vm))
6308
        qemuDomainRemoveInactive(driver, vm);
6309

6310
 cleanup:
M
Michal Privoznik 已提交
6311
    virDomainObjEndAPI(&vm);
6312
    qemuDomainEventQueue(driver, event);
6313 6314 6315
    return ret;
}

6316
int
6317
qemuMigrationPerform(virQEMUDriverPtr driver,
6318 6319 6320
                     virConnectPtr conn,
                     virDomainObjPtr vm,
                     const char *xmlin,
6321
                     const char *persist_xml,
6322 6323
                     const char *dconnuri,
                     const char *uri,
6324
                     const char *graphicsuri,
6325
                     const char *listenAddress,
6326 6327
                     size_t nmigrate_disks,
                     const char **migrate_disks,
6328
                     int nbdPort,
6329
                     qemuMigrationCompressionPtr compression,
6330
                     qemuMonitorMigrationParamsPtr migParams,
6331 6332 6333 6334 6335 6336 6337 6338 6339 6340
                     const char *cookiein,
                     int cookieinlen,
                     char **cookieout,
                     int *cookieoutlen,
                     unsigned long flags,
                     const char *dname,
                     unsigned long resource,
                     bool v3proto)
{
    VIR_DEBUG("driver=%p, conn=%p, vm=%p, xmlin=%s, dconnuri=%s, "
6341
              "uri=%s, graphicsuri=%s, listenAddress=%s, "
6342
              "nmigrate_disks=%zu, migrate_disks=%p, nbdPort=%d, "
6343 6344
              "cookiein=%s, cookieinlen=%d, cookieout=%p, cookieoutlen=%p, "
              "flags=%lx, dname=%s, resource=%lu, v3proto=%d",
6345
              driver, conn, vm, NULLSTR(xmlin), NULLSTR(dconnuri),
6346
              NULLSTR(uri), NULLSTR(graphicsuri), NULLSTR(listenAddress),
6347 6348 6349
              nmigrate_disks, migrate_disks, nbdPort,
              NULLSTR(cookiein), cookieinlen, cookieout, cookieoutlen,
              flags, NULLSTR(dname), resource, v3proto);
6350 6351 6352

    if ((flags & (VIR_MIGRATE_TUNNELLED | VIR_MIGRATE_PEER2PEER))) {
        if (cookieinlen) {
6353 6354
            virReportError(VIR_ERR_OPERATION_INVALID,
                           "%s", _("received unexpected cookie with P2P migration"));
6355 6356 6357
            return -1;
        }

6358
        return qemuMigrationPerformJob(driver, conn, vm, xmlin, persist_xml, dconnuri, uri,
6359
                                       graphicsuri, listenAddress,
6360
                                       nmigrate_disks, migrate_disks, nbdPort,
6361 6362
                                       compression, migParams,
                                       cookiein, cookieinlen,
6363 6364
                                       cookieout, cookieoutlen,
                                       flags, dname, resource, v3proto);
6365 6366
    } else {
        if (dconnuri) {
6367 6368
            virReportError(VIR_ERR_INTERNAL_ERROR,
                           "%s", _("Unexpected dconnuri parameter with non-peer2peer migration"));
6369 6370 6371 6372
            return -1;
        }

        if (v3proto) {
6373
            return qemuMigrationPerformPhase(driver, conn, vm, persist_xml, uri,
6374
                                             graphicsuri,
6375
                                             nmigrate_disks, migrate_disks,
6376 6377
                                             compression, migParams,
                                             cookiein, cookieinlen,
6378
                                             cookieout, cookieoutlen,
6379
                                             flags, resource);
6380
        } else {
6381
            return qemuMigrationPerformJob(driver, conn, vm, xmlin, persist_xml, NULL,
6382
                                           uri, graphicsuri, listenAddress,
6383
                                           nmigrate_disks, migrate_disks, nbdPort,
6384 6385
                                           compression, migParams,
                                           cookiein, cookieinlen,
6386 6387 6388 6389 6390
                                           cookieout, cookieoutlen, flags,
                                           dname, resource, v3proto);
        }
    }
}
6391

6392
static int
6393 6394
qemuMigrationVPAssociatePortProfiles(virDomainDefPtr def)
{
6395
    size_t i;
6396 6397 6398 6399 6400
    int last_good_net = -1;
    virDomainNetDefPtr net;

    for (i = 0; i < def->nnets; i++) {
        net = def->nets[i];
6401
        if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT) {
6402
            if (virNetDevVPortProfileAssociate(net->ifname,
6403
                                               virDomainNetGetActualVirtPortProfile(net),
6404
                                               &net->mac,
6405
                                               virDomainNetGetActualDirectDev(net),
6406
                                               -1,
6407
                                               def->uuid,
6408 6409
                                               VIR_NETDEV_VPORT_PROFILE_OP_MIGRATE_IN_FINISH,
                                               false) < 0) {
6410 6411 6412
                virReportError(VIR_ERR_OPERATION_FAILED,
                               _("Port profile Associate failed for %s"),
                               net->ifname);
6413
                goto err_exit;
6414
            }
6415
            last_good_net = i;
6416
            VIR_DEBUG("Port profile Associate succeeded for %s", net->ifname);
6417

6418
            if (virNetDevMacVLanVPortProfileRegisterCallback(net->ifname, &net->mac,
6419 6420 6421 6422
                                                             virDomainNetGetActualDirectDev(net), def->uuid,
                                                             virDomainNetGetActualVirtPortProfile(net),
                                                             VIR_NETDEV_VPORT_PROFILE_OP_CREATE))
                goto err_exit;
6423 6424 6425
        }
    }

6426
    return 0;
6427

6428
 err_exit:
6429
    for (i = 0; last_good_net != -1 && i <= last_good_net; i++) {
6430
        net = def->nets[i];
6431
        if (virDomainNetGetActualType(net) == VIR_DOMAIN_NET_TYPE_DIRECT) {
6432
            ignore_value(virNetDevVPortProfileDisassociate(net->ifname,
6433
                                                           virDomainNetGetActualVirtPortProfile(net),
6434
                                                           &net->mac,
6435
                                                           virDomainNetGetActualDirectDev(net),
6436
                                                           -1,
6437
                                                           VIR_NETDEV_VPORT_PROFILE_OP_MIGRATE_IN_FINISH));
6438 6439
        }
    }
6440
    return -1;
6441 6442 6443
}


J
Jiri Denemark 已提交
6444 6445 6446
static int
qemuMigrationPersist(virQEMUDriverPtr driver,
                     virDomainObjPtr vm,
6447 6448
                     qemuMigrationCookiePtr mig,
                     bool ignoreSaveError)
J
Jiri Denemark 已提交
6449 6450 6451 6452
{
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
    virCapsPtr caps = NULL;
    virDomainDefPtr vmdef;
6453 6454
    virDomainDefPtr oldDef = NULL;
    unsigned int oldPersist = vm->persistent;
J
Jiri Denemark 已提交
6455 6456 6457 6458 6459 6460 6461
    virObjectEventPtr event;
    int ret = -1;

    if (!(caps = virQEMUDriverGetCapabilities(driver, false)))
        goto cleanup;

    vm->persistent = 1;
6462 6463
    oldDef = vm->newDef;
    vm->newDef = qemuMigrationCookieGetPersistent(mig);
J
Jiri Denemark 已提交
6464

6465 6466
    if (!(vmdef = virDomainObjGetPersistentDef(caps, driver->xmlopt, vm)))
        goto error;
J
Jiri Denemark 已提交
6467

6468 6469
    if (virDomainSaveConfig(cfg->configDir, driver->caps, vmdef) < 0 &&
        !ignoreSaveError)
6470
        goto error;
J
Jiri Denemark 已提交
6471 6472 6473

    event = virDomainEventLifecycleNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_DEFINED,
6474 6475 6476
                                              oldPersist ?
                                              VIR_DOMAIN_EVENT_DEFINED_UPDATED :
                                              VIR_DOMAIN_EVENT_DEFINED_ADDED);
6477
    qemuDomainEventQueue(driver, event);
J
Jiri Denemark 已提交
6478 6479 6480 6481

    ret = 0;

 cleanup:
6482
    virDomainDefFree(oldDef);
J
Jiri Denemark 已提交
6483 6484 6485
    virObjectUnref(caps);
    virObjectUnref(cfg);
    return ret;
6486 6487 6488 6489 6490 6491 6492

 error:
    virDomainDefFree(vm->newDef);
    vm->persistent = oldPersist;
    vm->newDef = oldDef;
    oldDef = NULL;
    goto cleanup;
J
Jiri Denemark 已提交
6493 6494 6495
}


6496
virDomainPtr
6497
qemuMigrationFinish(virQEMUDriverPtr driver,
6498 6499
                    virConnectPtr dconn,
                    virDomainObjPtr vm,
6500 6501 6502 6503
                    const char *cookiein,
                    int cookieinlen,
                    char **cookieout,
                    int *cookieoutlen,
6504
                    unsigned long flags,
6505 6506
                    int retcode,
                    bool v3proto)
6507 6508
{
    virDomainPtr dom = NULL;
6509
    qemuMigrationCookiePtr mig = NULL;
6510
    virErrorPtr orig_err = NULL;
6511
    int cookie_flags = 0;
J
Jiri Denemark 已提交
6512
    qemuDomainObjPrivatePtr priv = vm->privateData;
6513
    virQEMUDriverConfigPtr cfg = virQEMUDriverGetConfig(driver);
6514
    unsigned short port;
6515 6516
    unsigned long long timeReceived = 0;
    virObjectEventPtr event;
6517
    qemuDomainJobInfoPtr jobInfo = NULL;
6518
    bool inPostCopy = false;
6519
    bool doKill = true;
6520

6521
    VIR_DEBUG("driver=%p, dconn=%p, vm=%p, cookiein=%s, cookieinlen=%d, "
6522
              "cookieout=%p, cookieoutlen=%p, flags=%lx, retcode=%d",
6523 6524
              driver, dconn, vm, NULLSTR(cookiein), cookieinlen,
              cookieout, cookieoutlen, flags, retcode);
6525

6526 6527 6528
    port = priv->migrationPort;
    priv->migrationPort = 0;

6529 6530
    if (!qemuMigrationJobIsActive(vm, QEMU_ASYNC_JOB_MIGRATION_IN)) {
        qemuMigrationErrorReport(driver, vm->def->name);
6531
        goto cleanup;
6532
    }
6533

6534 6535
    ignore_value(virTimeMillisNow(&timeReceived));

6536 6537 6538
    qemuMigrationJobStartPhase(driver, vm,
                               v3proto ? QEMU_MIGRATION_PHASE_FINISH3
                                       : QEMU_MIGRATION_PHASE_FINISH2);
6539

6540
    qemuDomainCleanupRemove(vm, qemuMigrationPrepareCleanup);
6541
    VIR_FREE(priv->job.completed);
6542

6543
    cookie_flags = QEMU_MIGRATION_COOKIE_NETWORK |
6544 6545
                   QEMU_MIGRATION_COOKIE_STATS |
                   QEMU_MIGRATION_COOKIE_NBD;
6546 6547 6548
    /* Some older versions of libvirt always send persistent XML in the cookie
     * even though VIR_MIGRATE_PERSIST_DEST was not used. */
    cookie_flags |= QEMU_MIGRATION_COOKIE_PERSISTENT;
6549 6550 6551

    if (!(mig = qemuMigrationEatCookie(driver, vm, cookiein,
                                       cookieinlen, cookie_flags)))
6552
        goto endjob;
6553

6554
    if (flags & VIR_MIGRATE_OFFLINE) {
6555 6556 6557 6558 6559
        if (retcode == 0 &&
            qemuMigrationPersist(driver, vm, mig, false) == 0)
            dom = virGetDomain(dconn, vm->def->name, vm->def->uuid);
        goto endjob;
    }
6560

6561 6562 6563 6564
    if (retcode != 0) {
        /* Check for a possible error on the monitor in case Finish was called
         * earlier than monitor EOF handler got a chance to process the error
         */
6565
        qemuDomainCheckMonitor(driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN);
6566 6567
        goto endjob;
    }
6568

6569 6570 6571 6572 6573 6574
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
        qemuMigrationErrorReport(driver, vm->def->name);
        goto endjob;
    }
6575

6576 6577
    if (qemuMigrationVPAssociatePortProfiles(vm->def) < 0)
        goto endjob;
6578

6579 6580
    if (mig->network && qemuDomainMigrateOPDRelocate(driver, vm, mig) < 0)
        VIR_WARN("unable to provide network data for relocation");
6581

6582 6583
    if (qemuMigrationStopNBDServer(driver, vm, mig) < 0)
        goto endjob;
6584

6585 6586
    if (qemuRefreshVirtioChannelState(driver, vm,
                                      QEMU_ASYNC_JOB_MIGRATION_IN) < 0)
6587 6588
        goto endjob;

6589 6590
    if (qemuConnectAgent(driver, vm) < 0)
        goto endjob;
6591

6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604
    if (flags & VIR_MIGRATE_PERSIST_DEST) {
        if (qemuMigrationPersist(driver, vm, mig, !v3proto) < 0) {
            /* Hmpf.  Migration was successful, but making it persistent
             * was not.  If we report successful, then when this domain
             * shuts down, management tools are in for a surprise.  On the
             * other hand, if we report failure, then the management tools
             * might try to restart the domain on the source side, even
             * though the domain is actually running on the destination.
             * Pretend success and hope that this is a rare situation and
             * management tools are smart.
             *
             * However, in v3 protocol, the source VM is still available
             * to restart during confirm() step, so we kill it off now.
6605 6606 6607
             */
            if (v3proto)
                goto endjob;
6608
        }
6609
    }
6610

6611 6612 6613 6614
    /* We need to wait for QEMU to process all data sent by the source
     * before starting guest CPUs.
     */
    if (qemuMigrationWaitForDestCompletion(driver, vm,
6615 6616
                                           QEMU_ASYNC_JOB_MIGRATION_IN,
                                           !!(flags & VIR_MIGRATE_POSTCOPY)) < 0) {
6617 6618 6619 6620 6621 6622
        /* There's not much we can do for v2 protocol since the
         * original domain on the source host is already gone.
         */
        if (v3proto)
            goto endjob;
    }
6623

6624 6625 6626
    if (priv->job.current->stats.status == QEMU_MONITOR_MIGRATION_STATUS_POSTCOPY)
        inPostCopy = true;

6627 6628 6629 6630 6631 6632
    if (!(flags & VIR_MIGRATE_PAUSED)) {
        /* run 'cont' on the destination, which allows migration on qemu
         * >= 0.10.6 to work properly.  This isn't strictly necessary on
         * older qemu's, but it also doesn't hurt anything there
         */
        if (qemuProcessStartCPUs(driver, vm, dconn,
6633 6634
                                 inPostCopy ? VIR_DOMAIN_RUNNING_POSTCOPY
                                            : VIR_DOMAIN_RUNNING_MIGRATED,
6635 6636 6637 6638 6639 6640 6641 6642
                                 QEMU_ASYNC_JOB_MIGRATION_IN) < 0) {
            if (virGetLastError() == NULL)
                virReportError(VIR_ERR_INTERNAL_ERROR,
                               "%s", _("resume operation failed"));
            /* Need to save the current error, in case shutting
             * down the process overwrites it
             */
            orig_err = virSaveLastError();
6643

6644 6645 6646 6647 6648 6649 6650 6651 6652 6653
            /*
             * In v3 protocol, the source VM is still available to
             * restart during confirm() step, so we kill it off
             * now.
             * In v2 protocol, the source is dead, so we leave
             * target in paused state, in case admin can fix
             * things up.
             */
            if (v3proto)
                goto endjob;
6654
        }
6655 6656

        if (inPostCopy) {
6657
            doKill = false;
6658 6659 6660 6661 6662
            event = virDomainEventLifecycleNewFromObj(vm,
                                        VIR_DOMAIN_EVENT_RESUMED,
                                        VIR_DOMAIN_EVENT_RESUMED_POSTCOPY);
            qemuDomainEventQueue(driver, event);
        }
6663
    }
6664

6665
    if (mig->jobInfo) {
6666
        jobInfo = mig->jobInfo;
6667 6668 6669 6670 6671 6672
        mig->jobInfo = NULL;

        if (jobInfo->sent && timeReceived) {
            jobInfo->timeDelta = timeReceived - jobInfo->sent;
            jobInfo->received = timeReceived;
            jobInfo->timeDeltaSet = true;
6673
        }
6674 6675
        qemuDomainJobInfoUpdateTime(jobInfo);
        qemuDomainJobInfoUpdateDowntime(jobInfo);
6676
    }
L
liguang 已提交
6677

6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690
    if (inPostCopy) {
        if (qemuMigrationWaitForDestCompletion(driver, vm,
                                               QEMU_ASYNC_JOB_MIGRATION_IN,
                                               false) < 0) {
            goto endjob;
        }
        if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_RUNNING) {
            virDomainObjSetState(vm,
                                 VIR_DOMAIN_RUNNING,
                                 VIR_DOMAIN_RUNNING_MIGRATED);
        }
    }

6691
    dom = virGetDomain(dconn, vm->def->name, vm->def->uuid);
6692

6693 6694 6695 6696
    event = virDomainEventLifecycleNewFromObj(vm,
                                              VIR_DOMAIN_EVENT_RESUMED,
                                              VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
    qemuDomainEventQueue(driver, event);
6697

6698 6699 6700 6701 6702 6703
    if (virDomainObjGetState(vm, NULL) == VIR_DOMAIN_PAUSED) {
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
        event = virDomainEventLifecycleNewFromObj(vm,
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
                                                  VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
        qemuDomainEventQueue(driver, event);
6704
    }
6705

6706
    if (virDomainObjIsActive(vm) &&
6707
        virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, driver->caps) < 0)
6708 6709 6710 6711 6712
        VIR_WARN("Failed to save status on vm %s", vm->def->name);

    /* Guest is successfully running, so cancel previous auto destroy */
    qemuProcessAutoDestroyRemove(driver, vm);

6713
 endjob:
6714
    if (!dom &&
6715 6716
        !(flags & VIR_MIGRATE_OFFLINE) &&
        virDomainObjIsActive(vm)) {
6717
        if (doKill) {
6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728
            qemuProcessStop(driver, vm, VIR_DOMAIN_SHUTOFF_FAILED,
                            QEMU_ASYNC_JOB_MIGRATION_IN,
                            VIR_QEMU_PROCESS_STOP_MIGRATED);
            virDomainAuditStop(vm, "failed");
            event = virDomainEventLifecycleNewFromObj(vm,
                                VIR_DOMAIN_EVENT_STOPPED,
                                VIR_DOMAIN_EVENT_STOPPED_FAILED);
            qemuDomainEventQueue(driver, event);
        } else {
            qemuMigrationPostcopyFailed(driver, vm);
        }
6729 6730
    }

6731 6732 6733 6734 6735 6736
    if (dom) {
        priv->job.completed = jobInfo;
        jobInfo = NULL;
        if (qemuMigrationBakeCookie(mig, driver, vm, cookieout, cookieoutlen,
                                    QEMU_MIGRATION_COOKIE_STATS) < 0)
            VIR_WARN("Unable to encode migration cookie");
6737 6738 6739 6740 6741 6742

        /* Remove completed stats for post-copy, everything but timing fields
         * is obsolete anyway.
         */
        if (inPostCopy)
            VIR_FREE(priv->job.completed);
6743 6744 6745

        qemuMigrationSetPostCopy(driver, vm, false,
                                 QEMU_ASYNC_JOB_MIGRATION_IN);
6746
    }
6747

6748 6749 6750 6751
    if (qemuMigrationResetTLS(driver, vm, QEMU_ASYNC_JOB_MIGRATION_IN,
                              NULL, NULL) < 0)
        goto endjob;

6752
    qemuMigrationJobFinish(driver, vm);
6753
    if (!virDomainObjIsActive(vm))
6754
        qemuDomainRemoveInactive(driver, vm);
6755

6756
 cleanup:
6757
    VIR_FREE(jobInfo);
6758
    virPortAllocatorRelease(driver->migrationPorts, port);
6759
    if (priv->mon)
6760
        qemuMonitorSetDomainLog(priv->mon, NULL, NULL, NULL);
6761
    VIR_FREE(priv->origname);
M
Michal Privoznik 已提交
6762
    virDomainObjEndAPI(&vm);
6763 6764 6765 6766
    if (mig) {
        virDomainDefFree(qemuMigrationCookieGetPersistent(mig));
        qemuMigrationCookieFree(mig);
    }
6767 6768 6769 6770
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
6771
    virObjectUnref(cfg);
6772 6773 6774 6775 6776 6777

    /* Set a special error if Finish is expected to return NULL as a result of
     * successful call with retcode != 0
     */
    if (retcode != 0 && !dom && !virGetLastError())
        virReportError(VIR_ERR_MIGRATE_FINISH_OK, NULL);
6778 6779
    return dom;
}
6780

6781

6782
/* Helper function called while vm is active.  */
6783
int
6784
qemuMigrationToFile(virQEMUDriverPtr driver, virDomainObjPtr vm,
6785
                    int fd,
6786
                    const char *compressor,
6787
                    qemuDomainAsyncJob asyncJob)
6788 6789 6790
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    int rc;
6791
    int ret = -1;
6792 6793
    virCommandPtr cmd = NULL;
    int pipeFD[2] = { -1, -1 };
6794
    unsigned long saveMigBandwidth = priv->migMaxBandwidth;
6795
    char *errbuf = NULL;
6796
    virErrorPtr orig_err = NULL;
6797 6798 6799 6800 6801

    /* Increase migration bandwidth to unlimited since target is a file.
     * Failure to change migration speed is not fatal. */
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) == 0) {
        qemuMonitorSetMigrationSpeed(priv->mon,
6802 6803
                                     QEMU_DOMAIN_MIG_BANDWIDTH_MAX);
        priv->migMaxBandwidth = QEMU_DOMAIN_MIG_BANDWIDTH_MAX;
6804 6805
        if (qemuDomainObjExitMonitor(driver, vm) < 0)
            return -1;
6806
    }
6807

6808 6809 6810 6811 6812 6813 6814
    if (!virDomainObjIsActive(vm)) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("guest unexpectedly quit"));
        /* nothing to tear down */
        return -1;
    }

6815 6816 6817 6818
    if (compressor && pipe(pipeFD) < 0) {
        virReportSystemError(errno, "%s",
                             _("Failed to create pipe for migration"));
        return -1;
6819 6820
    }

6821 6822 6823 6824
    /* All right! We can use fd migration, which means that qemu
     * doesn't have to open() the file, so while we still have to
     * grant SELinux access, we can do it on fd and avoid cleanup
     * later, as well as skip futzing with cgroup.  */
6825 6826
    if (qemuSecuritySetImageFDLabel(driver->securityManager, vm->def,
                                    compressor ? pipeFD[1] : fd) < 0)
6827 6828
        goto cleanup;

6829
    if (qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) < 0)
6830 6831
        goto cleanup;

6832
    if (!compressor) {
6833 6834 6835
        rc = qemuMonitorMigrateToFd(priv->mon,
                                    QEMU_MONITOR_MIGRATE_BACKGROUND,
                                    fd);
6836 6837 6838 6839 6840 6841 6842
    } else {
        const char *prog = compressor;
        const char *args[] = {
            prog,
            "-c",
            NULL
        };
6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853

        cmd = virCommandNewArgs(args);
        virCommandSetInputFD(cmd, pipeFD[0]);
        virCommandSetOutputFD(cmd, &fd);
        virCommandSetErrorBuffer(cmd, &errbuf);
        virCommandDoAsyncIO(cmd);
        if (virSetCloseExec(pipeFD[1]) < 0) {
            virReportSystemError(errno, "%s",
                                 _("Unable to set cloexec flag"));
            ignore_value(qemuDomainObjExitMonitor(driver, vm));
            goto cleanup;
6854
        }
6855 6856 6857 6858 6859 6860 6861 6862 6863 6864
        if (virCommandRunAsync(cmd, NULL) < 0) {
            ignore_value(qemuDomainObjExitMonitor(driver, vm));
            goto cleanup;
        }
        rc = qemuMonitorMigrateToFd(priv->mon,
                                    QEMU_MONITOR_MIGRATE_BACKGROUND,
                                    pipeFD[1]);
        if (VIR_CLOSE(pipeFD[0]) < 0 ||
            VIR_CLOSE(pipeFD[1]) < 0)
            VIR_WARN("failed to close intermediate pipe");
6865
    }
6866
    if (qemuDomainObjExitMonitor(driver, vm) < 0)
6867
        goto cleanup;
6868 6869 6870
    if (rc < 0)
        goto cleanup;

6871
    rc = qemuMigrationWaitForCompletion(driver, vm, asyncJob, NULL, 0);
6872

6873 6874 6875 6876
    if (rc < 0) {
        if (rc == -2) {
            orig_err = virSaveLastError();
            virCommandAbort(cmd);
6877 6878
            if (virDomainObjIsActive(vm) &&
                qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) == 0) {
6879
                qemuMonitorMigrateCancel(priv->mon);
6880
                ignore_value(qemuDomainObjExitMonitor(driver, vm));
6881 6882
            }
        }
6883
        goto cleanup;
6884
    }
6885

6886 6887 6888
    if (cmd && virCommandWait(cmd, NULL) < 0)
        goto cleanup;

6889
    qemuDomainEventEmitJobCompleted(driver, vm);
6890 6891
    ret = 0;

6892
 cleanup:
6893 6894 6895
    if (ret < 0 && !orig_err)
        orig_err = virSaveLastError();

6896
    /* Restore max migration bandwidth */
6897 6898
    if (virDomainObjIsActive(vm) &&
        qemuDomainObjEnterMonitorAsync(driver, vm, asyncJob) == 0) {
6899 6900
        qemuMonitorSetMigrationSpeed(priv->mon, saveMigBandwidth);
        priv->migMaxBandwidth = saveMigBandwidth;
6901
        ignore_value(qemuDomainObjExitMonitor(driver, vm));
6902 6903
    }

6904 6905
    VIR_FORCE_CLOSE(pipeFD[0]);
    VIR_FORCE_CLOSE(pipeFD[1]);
6906 6907 6908 6909 6910
    if (cmd) {
        VIR_DEBUG("Compression binary stderr: %s", NULLSTR(errbuf));
        VIR_FREE(errbuf);
        virCommandFree(cmd);
    }
6911 6912 6913 6914 6915 6916

    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }

6917 6918
    return ret;
}
6919

6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950

int
qemuMigrationCancel(virQEMUDriverPtr driver,
                    virDomainObjPtr vm)
{
    qemuDomainObjPrivatePtr priv = vm->privateData;
    virHashTablePtr blockJobs = NULL;
    bool storage = false;
    size_t i;
    int ret = -1;

    VIR_DEBUG("Canceling unfinished outgoing migration of domain %s",
              vm->def->name);

    for (i = 0; i < vm->def->ndisks; i++) {
        virDomainDiskDefPtr disk = vm->def->disks[i];
        if (QEMU_DOMAIN_DISK_PRIVATE(disk)->migrating) {
            qemuBlockJobSyncBegin(disk);
            storage = true;
        }
    }

    qemuDomainObjEnterMonitor(driver, vm);

    ignore_value(qemuMonitorMigrateCancel(priv->mon));
    if (storage)
        blockJobs = qemuMonitorGetAllBlockJobInfo(priv->mon);

    if (qemuDomainObjExitMonitor(driver, vm) < 0 || (storage && !blockJobs))
        goto endsyncjob;

6951 6952 6953
    ignore_value(qemuMigrationResetTLS(driver, vm, QEMU_ASYNC_JOB_NONE,
                                       NULL, NULL));

6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975
    if (!storage) {
        ret = 0;
        goto cleanup;
    }

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

        if (!diskPriv->migrating)
            continue;

        if (virHashLookup(blockJobs, disk->info.alias)) {
            VIR_DEBUG("Drive mirror on disk %s is still running", disk->dst);
        } else {
            VIR_DEBUG("Drive mirror on disk %s is gone", disk->dst);
            qemuBlockJobSyncEnd(driver, vm, disk);
            diskPriv->migrating = false;
        }
    }

    if (qemuMigrationCancelDriveMirror(driver, vm, false,
6976
                                       QEMU_ASYNC_JOB_NONE, NULL) < 0)
6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000
        goto endsyncjob;

    ret = 0;

 cleanup:
    virHashFree(blockJobs);
    return ret;

 endsyncjob:
    if (storage) {
        for (i = 0; i < vm->def->ndisks; i++) {
            virDomainDiskDefPtr disk = vm->def->disks[i];
            qemuDomainDiskPrivatePtr diskPriv = QEMU_DOMAIN_DISK_PRIVATE(disk);

            if (diskPriv->migrating) {
                qemuBlockJobSyncEnd(driver, vm, disk);
                diskPriv->migrating = false;
            }
        }
    }
    goto cleanup;
}


7001
int
7002
qemuMigrationJobStart(virQEMUDriverPtr driver,
7003
                      virDomainObjPtr vm,
7004
                      qemuDomainAsyncJob job)
7005 7006 7007
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

7008
    if (qemuDomainObjBeginAsyncJob(driver, vm, job) < 0)
7009 7010
        return -1;

7011
    if (job == QEMU_ASYNC_JOB_MIGRATION_IN) {
7012
        qemuDomainObjSetAsyncJobMask(vm, QEMU_JOB_NONE);
7013
    } else {
7014 7015 7016
        qemuDomainObjSetAsyncJobMask(vm, (QEMU_JOB_DEFAULT_MASK |
                                          JOB_MASK(QEMU_JOB_SUSPEND) |
                                          JOB_MASK(QEMU_JOB_MIGRATION_OP)));
7017
    }
7018

J
Jiri Denemark 已提交
7019
    priv->job.current->type = VIR_DOMAIN_JOB_UNBOUNDED;
7020 7021 7022 7023 7024

    return 0;
}

void
7025
qemuMigrationJobSetPhase(virQEMUDriverPtr driver,
7026
                         virDomainObjPtr vm,
7027
                         qemuMigrationJobPhase phase)
7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (phase < priv->job.phase) {
        VIR_ERROR(_("migration protocol going backwards %s => %s"),
                  qemuMigrationJobPhaseTypeToString(priv->job.phase),
                  qemuMigrationJobPhaseTypeToString(phase));
        return;
    }

    qemuDomainObjSetJobPhase(driver, vm, phase);
}

void
7042
qemuMigrationJobStartPhase(virQEMUDriverPtr driver,
7043
                           virDomainObjPtr vm,
7044
                           qemuMigrationJobPhase phase)
7045 7046 7047 7048
{
    qemuMigrationJobSetPhase(driver, vm, phase);
}

7049
void
7050 7051
qemuMigrationJobContinue(virDomainObjPtr vm)
{
7052
    qemuDomainObjReleaseAsyncJob(vm);
7053 7054 7055 7056
}

bool
qemuMigrationJobIsActive(virDomainObjPtr vm,
7057
                         qemuDomainAsyncJob job)
7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068
{
    qemuDomainObjPrivatePtr priv = vm->privateData;

    if (priv->job.asyncJob != job) {
        const char *msg;

        if (job == QEMU_ASYNC_JOB_MIGRATION_IN)
            msg = _("domain '%s' is not processing incoming migration");
        else
            msg = _("domain '%s' is not being migrated");

7069
        virReportError(VIR_ERR_OPERATION_INVALID, msg, vm->def->name);
7070 7071 7072 7073 7074
        return false;
    }
    return true;
}

7075
void
7076
qemuMigrationJobFinish(virQEMUDriverPtr driver, virDomainObjPtr vm)
7077
{
7078
    qemuDomainObjEndAsyncJob(driver, vm);
7079
}
7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133


static void
qemuMigrationErrorFree(void *data,
                       const void *name ATTRIBUTE_UNUSED)
{
    virErrorPtr err = data;
    virFreeError(err);
}

int
qemuMigrationErrorInit(virQEMUDriverPtr driver)
{
    driver->migrationErrors = virHashAtomicNew(64, qemuMigrationErrorFree);
    if (driver->migrationErrors)
        return 0;
    else
        return -1;
}

/**
 * This function consumes @err; the caller should consider the @err pointer
 * invalid after calling this function.
 */
void
qemuMigrationErrorSave(virQEMUDriverPtr driver,
                       const char *name,
                       virErrorPtr err)
{
    if (!err)
        return;

    VIR_DEBUG("Saving incoming migration error for domain %s: %s",
              name, err->message);
    if (virHashAtomicUpdate(driver->migrationErrors, name, err) < 0) {
        VIR_WARN("Failed to save migration error for domain '%s'", name);
        virFreeError(err);
    }
}

void
qemuMigrationErrorReport(virQEMUDriverPtr driver,
                         const char *name)
{
    virErrorPtr err;

    if (!(err = virHashAtomicSteal(driver->migrationErrors, name)))
        return;

    VIR_DEBUG("Restoring saved incoming migration error for domain %s: %s",
              name, err->message);
    virSetError(err);
    virFreeError(err);
}
7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171


/* don't ever pass NULL params with non zero nparams */
qemuMigrationCompressionPtr
qemuMigrationCompressionParse(virTypedParameterPtr params,
                              int nparams,
                              unsigned long flags)
{
    size_t i;
    qemuMigrationCompressionPtr compression = NULL;

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

    for (i = 0; i < nparams; i++) {
        int method;

        if (STRNEQ(params[i].field, VIR_MIGRATE_PARAM_COMPRESSION))
            continue;

        method = qemuMigrationCompressMethodTypeFromString(params[i].value.s);
        if (method < 0) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Unsupported compression method '%s'"),
                           params[i].value.s);
            goto error;
        }

        if (compression->methods & (1ULL << method)) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("Compression method '%s' is specified twice"),
                           params[i].value.s);
            goto error;
        }

        compression->methods |= 1ULL << method;
    }

7172
#define GET_PARAM(PARAM, TYPE, VALUE)                                       \
7173 7174
    do {                                                                    \
        int rc;                                                             \
7175
        const char *par = VIR_MIGRATE_PARAM_COMPRESSION_ ## PARAM;          \
7176 7177
                                                                            \
        if ((rc = virTypedParamsGet ## TYPE(params, nparams,                \
7178
                                            par, &compression->VALUE)) < 0) \
7179 7180 7181
            goto error;                                                     \
                                                                            \
        if (rc == 1)                                                        \
7182
            compression->VALUE ## _set = true;                              \
7183 7184 7185
    } while (0)

    if (params) {
7186 7187 7188 7189
        GET_PARAM(MT_LEVEL, Int, level);
        GET_PARAM(MT_THREADS, Int, threads);
        GET_PARAM(MT_DTHREADS, Int, dthreads);
        GET_PARAM(XBZRLE_CACHE, ULLong, xbzrle_cache);
7190 7191 7192 7193
    }

#undef GET_PARAM

7194 7195 7196
    if ((compression->level_set ||
         compression->threads_set ||
         compression->dthreads_set) &&
7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
        !(compression->methods & (1ULL << QEMU_MIGRATION_COMPRESS_MT))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Turn multithread compression on to tune it"));
        goto error;
    }

    if (compression->xbzrle_cache_set &&
        !(compression->methods & (1ULL << QEMU_MIGRATION_COMPRESS_XBZRLE))) {
        virReportError(VIR_ERR_INVALID_ARG, "%s",
                       _("Turn xbzrle compression on to tune it"));
        goto error;
    }

7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228
    if (!compression->methods && (flags & VIR_MIGRATE_COMPRESSED))
        compression->methods = 1ULL << QEMU_MIGRATION_COMPRESS_XBZRLE;

    return compression;

 error:
    VIR_FREE(compression);
    return NULL;
}

int
qemuMigrationCompressionDump(qemuMigrationCompressionPtr compression,
                             virTypedParameterPtr *params,
                             int *nparams,
                             int *maxparams,
                             unsigned long *flags)
{
    size_t i;

7229 7230
    if (compression->methods == 1ULL << QEMU_MIGRATION_COMPRESS_XBZRLE &&
        !compression->xbzrle_cache_set) {
7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242
        *flags |= VIR_MIGRATE_COMPRESSED;
        return 0;
    }

    for (i = 0; i < QEMU_MIGRATION_COMPRESS_LAST; ++i) {
        if ((compression->methods & (1ULL << i)) &&
            virTypedParamsAddString(params, nparams, maxparams,
                                    VIR_MIGRATE_PARAM_COMPRESSION,
                                    qemuMigrationCompressMethodTypeToString(i)) < 0)
            return -1;
    }

7243
    if (compression->level_set &&
7244 7245
        virTypedParamsAddInt(params, nparams, maxparams,
                             VIR_MIGRATE_PARAM_COMPRESSION_MT_LEVEL,
7246
                             compression->level) < 0)
7247 7248
        return -1;

7249
    if (compression->threads_set &&
7250 7251
        virTypedParamsAddInt(params, nparams, maxparams,
                             VIR_MIGRATE_PARAM_COMPRESSION_MT_THREADS,
7252
                             compression->threads) < 0)
7253 7254
        return -1;

7255
    if (compression->dthreads_set &&
7256 7257
        virTypedParamsAddInt(params, nparams, maxparams,
                             VIR_MIGRATE_PARAM_COMPRESSION_MT_DTHREADS,
7258
                             compression->dthreads) < 0)
7259 7260 7261 7262 7263 7264 7265 7266
        return -1;

    if (compression->xbzrle_cache_set &&
        virTypedParamsAddULLong(params, nparams, maxparams,
                                VIR_MIGRATE_PARAM_COMPRESSION_XBZRLE_CACHE,
                                compression->xbzrle_cache) < 0)
        return -1;

7267 7268
    return 0;
}