libxl_migration.c 41.5 KB
Newer Older
J
Jim Fehlig 已提交
1 2 3
/*
 * libxl_migration.c: methods for handling migration with libxenlight
 *
J
Jim Fehlig 已提交
4
 * Copyright (C) 2014-2015 SUSE LINUX Products GmbH, Nuernberg, Germany.
J
Jim Fehlig 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
 *
 * Authors:
 *     Jim Fehlig <jfehlig@suse.com>
 *     Chunyan Liu <cyliu@suse.com>
 */

#include <config.h>

#include "internal.h"
#include "virlog.h"
#include "virerror.h"
#include "virconf.h"
#include "datatypes.h"
#include "virfile.h"
#include "viralloc.h"
#include "viruuid.h"
#include "vircommand.h"
#include "virstring.h"
#include "virobject.h"
38
#include "virthread.h"
C
Cédric Bosdonnat 已提交
39
#include "virhook.h"
J
Jim Fehlig 已提交
40 41 42 43 44
#include "rpc/virnetsocket.h"
#include "libxl_domain.h"
#include "libxl_driver.h"
#include "libxl_conf.h"
#include "libxl_migration.h"
45
#include "locking/domain_lock.h"
J
Joao Martins 已提交
46
#include "virtypedparam.h"
47
#include "virfdstream.h"
J
Jim Fehlig 已提交
48 49 50 51 52

#define VIR_FROM_THIS VIR_FROM_LIBXL

VIR_LOG_INIT("libxl.libxl_migration");

53 54 55 56 57 58 59 60 61 62 63 64
typedef struct _libxlMigrationCookie libxlMigrationCookie;
typedef libxlMigrationCookie *libxlMigrationCookiePtr;
struct _libxlMigrationCookie {
    /* Host properties */
    char *srcHostname;
    uint32_t xenMigStreamVer;

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

J
Jim Fehlig 已提交
65 66 67
typedef struct _libxlMigrationDstArgs {
    virObject parent;

68
    int recvfd;
J
Jim Fehlig 已提交
69 70 71
    virConnectPtr conn;
    virDomainObjPtr vm;
    unsigned int flags;
72
    libxlMigrationCookiePtr migcookie;
J
Jim Fehlig 已提交
73 74 75 76 77 78 79 80

    /* for freeing listen sockets */
    virNetSocketPtr *socks;
    size_t nsocks;
} libxlMigrationDstArgs;

static virClassPtr libxlMigrationDstArgsClass;

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234

static void
libxlMigrationCookieFree(libxlMigrationCookiePtr mig)
{
    if (!mig)
        return;

    VIR_FREE(mig->srcHostname);
    VIR_FREE(mig->name);
    VIR_FREE(mig);
}

static libxlMigrationCookiePtr
libxlMigrationCookieNew(virDomainObjPtr dom)
{
    libxlMigrationCookiePtr mig = NULL;

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

    if (VIR_STRDUP(mig->name, dom->def->name) < 0)
        goto error;

    memcpy(mig->uuid, dom->def->uuid, VIR_UUID_BUFLEN);

    if (!(mig->srcHostname = virGetHostname()))
        goto error;

    mig->xenMigStreamVer = LIBXL_SAVE_VERSION;

    return mig;

 error:
    libxlMigrationCookieFree(mig);
    return NULL;
}


static int
libxlMigrationBakeCookie(libxlMigrationCookiePtr mig,
                         char **cookieout,
                         int *cookieoutlen)
{
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char uuidstr[VIR_UUID_STRING_BUFLEN];

    if (!cookieout || !cookieoutlen)
        return 0;

    *cookieoutlen = 0;
    virUUIDFormat(mig->uuid, uuidstr);

    virBufferAddLit(&buf, "<libxl-migration>\n");
    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->srcHostname);
    virBufferAsprintf(&buf, "<migration-stream-version>%u</migration-stream-version>\n", mig->xenMigStreamVer);
    virBufferAdjustIndent(&buf, -2);
    virBufferAddLit(&buf, "</libxl-migration>\n");

    if (virBufferCheckError(&buf) < 0)
        return -1;

    *cookieout = virBufferContentAndReset(&buf);
    *cookieoutlen = strlen(*cookieout) + 1;

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

    return 0;
}

static int
libxlMigrationEatCookie(const char *cookiein,
                        int cookieinlen,
                        libxlMigrationCookiePtr *migout)
{
    libxlMigrationCookiePtr mig = NULL;
    xmlDocPtr doc = NULL;
    xmlXPathContextPtr ctxt = NULL;
    char *uuidstr = NULL;
    int ret = -1;

    /*
     * Assume a legacy (V1) migration stream if request came from a
     * source host without cookie support, and hence no way to
     * specify a stream version.
     */
    if (!cookiein || !cookieinlen) {
        if (VIR_ALLOC(mig) < 0)
            return -1;

        mig->xenMigStreamVer = 1;
        *migout = mig;
        return 0;
    }

    if (cookiein[cookieinlen-1] != '\0') {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Migration cookie was not NULL terminated"));
        return -1;
    }

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

    if (VIR_ALLOC(mig) < 0)
        return -1;

    if (!(doc = virXMLParseStringCtxt(cookiein,
                                      _("(libxl_migration_cookie)"),
                                      &ctxt)))
        goto error;

    /* Extract domain name */
    if (!(mig->name = virXPathString("string(./name[1])", ctxt))) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing name element in migration data"));
        goto error;
    }

    /* Extract domain uuid */
    uuidstr = virXPathString("string(./uuid[1])", ctxt);
    if (!uuidstr) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("missing uuid element in migration data"));
        goto error;
    }
    if (virUUIDParse(uuidstr, mig->uuid) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       "%s", _("malformed uuid element"));
        goto error;
    }

    if (virXPathUInt("string(./migration-stream-version[1])",
                     ctxt, &mig->xenMigStreamVer) < 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("missing Xen migration stream version"));
        goto error;
    }

    *migout = mig;
    ret = 0;
    goto cleanup;

 error:
    libxlMigrationCookieFree(mig);

 cleanup:
    VIR_FREE(uuidstr);
    xmlXPathFreeContext(ctxt);
    xmlFreeDoc(doc);
    return ret;
}

J
Jim Fehlig 已提交
235 236 237 238 239
static void
libxlMigrationDstArgsDispose(void *obj)
{
    libxlMigrationDstArgs *args = obj;

240
    libxlMigrationCookieFree(args->migcookie);
J
Jim Fehlig 已提交
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    VIR_FREE(args->socks);
}

static int
libxlMigrationDstArgsOnceInit(void)
{
    if (!(libxlMigrationDstArgsClass = virClassNew(virClassForObject(),
                                                   "libxlMigrationDstArgs",
                                                   sizeof(libxlMigrationDstArgs),
                                                   libxlMigrationDstArgsDispose)))
        return -1;

    return 0;
}

VIR_ONCE_GLOBAL_INIT(libxlMigrationDstArgs)

static void
259
libxlDoMigrateReceive(void *opaque)
J
Jim Fehlig 已提交
260 261 262 263 264
{
    libxlMigrationDstArgs *args = opaque;
    virDomainObjPtr vm = args->vm;
    virNetSocketPtr *socks = args->socks;
    size_t nsocks = args->nsocks;
265 266
    libxlDriverPrivatePtr driver = args->conn->privateData;
    int recvfd = args->recvfd;
J
Jim Fehlig 已提交
267 268
    size_t i;
    int ret;
269 270
    bool remove_dom = 0;

W
Wang Yufei 已提交
271
    virObjectRef(vm);
272 273 274
    virObjectLock(vm);
    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;
J
Jim Fehlig 已提交
275

276 277 278 279
    /*
     * Always start the domain paused.  If needed, unpause in the
     * finish phase, after transfer of the domain is complete.
     */
280 281
    ret = libxlDomainStartRestore(driver, vm, true, recvfd,
                                  args->migcookie->xenMigStreamVer);
J
Jim Fehlig 已提交
282 283

    if (ret < 0 && !vm->persistent)
284
        remove_dom = true;
J
Jim Fehlig 已提交
285

286 287 288 289 290 291 292 293 294
    /* Remove all listen socks from event handler, and close them. */
    for (i = 0; i < nsocks; i++) {
        virNetSocketRemoveIOCallback(socks[i]);
        virNetSocketClose(socks[i]);
        virObjectUnref(socks[i]);
        socks[i] = NULL;
    }
    args->nsocks = 0;
    VIR_FORCE_CLOSE(recvfd);
295
    virObjectUnref(args);
296

W
Wang Yufei 已提交
297
    libxlDomainObjEndJob(driver, vm);
298 299

 cleanup:
300
    if (remove_dom) {
301
        virDomainObjListRemove(driver->domains, vm);
302
        virObjectLock(vm);
303
    }
W
Wang Yufei 已提交
304
    virDomainObjEndAPI(&vm);
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
}


static void
libxlMigrateReceive(virNetSocketPtr sock,
                    int events ATTRIBUTE_UNUSED,
                    void *opaque)
{
    libxlMigrationDstArgs *args = opaque;
    virNetSocketPtr *socks = args->socks;
    size_t nsocks = args->nsocks;
    virNetSocketPtr client_sock;
    int recvfd = -1;
    virThread thread;
    size_t i;

    /* Accept migration connection */
322
    if (virNetSocketAccept(sock, &client_sock) < 0 || !client_sock) {
323 324 325 326 327
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to accept migration connection"));
        goto fail;
    }
    VIR_DEBUG("Accepted migration connection."
328
              "  Spawning thread to process migration data");
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    recvfd = virNetSocketDupFD(client_sock, true);
    virObjectUnref(client_sock);

    /*
     * Avoid blocking the event loop.  Start a thread to receive
     * the migration data
     */
    args->recvfd = recvfd;
    if (virThreadCreate(&thread, false,
                        libxlDoMigrateReceive, args) < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to create thread for receiving migration data"));
        goto fail;
    }

    return;

 fail:
J
Jim Fehlig 已提交
347 348 349 350 351 352 353 354 355
    /* Remove all listen socks from event handler, and close them. */
    for (i = 0; i < nsocks; i++) {
        virNetSocketUpdateIOCallback(socks[i], 0);
        virNetSocketRemoveIOCallback(socks[i]);
        virNetSocketClose(socks[i]);
        socks[i] = NULL;
    }
    args->nsocks = 0;
    VIR_FORCE_CLOSE(recvfd);
356
    virObjectUnref(args);
J
Jim Fehlig 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
}

static int
libxlDoMigrateSend(libxlDriverPrivatePtr driver,
                   virDomainObjPtr vm,
                   unsigned long flags,
                   int sockfd)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    int xl_flags = 0;
    int ret;

    if (flags & VIR_MIGRATE_LIVE)
        xl_flags = LIBXL_SUSPEND_LIVE;

J
Jim Fehlig 已提交
372
    ret = libxl_domain_suspend(cfg->ctx, vm->def->id, sockfd,
J
Jim Fehlig 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
                               xl_flags, NULL);
    if (ret != 0) {
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("Failed to send migration data to destination host"));
        ret = -1;
    }

    virObjectUnref(cfg);
    return ret;
}

static bool
libxlDomainMigrationIsAllowed(virDomainDefPtr def)
{
    /* Migration is not allowed if definition contains any hostdevs */
    if (def->nhostdevs > 0) {
        virReportError(VIR_ERR_OPERATION_INVALID, "%s",
                       _("domain has assigned host devices"));
        return false;
    }

    return true;
}

char *
libxlDomainMigrationBegin(virConnectPtr conn,
                          virDomainObjPtr vm,
400 401 402
                          const char *xmlin,
                          char **cookieout,
                          int *cookieoutlen)
J
Jim Fehlig 已提交
403 404 405
{
    libxlDriverPrivatePtr driver = conn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
John Ferlan 已提交
406
    libxlMigrationCookiePtr mig = NULL;
J
Jim Fehlig 已提交
407 408 409 410 411 412 413
    virDomainDefPtr tmpdef = NULL;
    virDomainDefPtr def;
    char *xml = NULL;

    if (libxlDomainObjBeginJob(driver, vm, LIBXL_JOB_MODIFY) < 0)
        goto cleanup;

414 415 416 417 418 419
    if (!(mig = libxlMigrationCookieNew(vm)))
        goto endjob;

    if (libxlMigrationBakeCookie(mig, cookieout, cookieoutlen) < 0)
        goto endjob;

J
Jim Fehlig 已提交
420 421 422
    if (xmlin) {
        if (!(tmpdef = virDomainDefParseString(xmlin, cfg->caps,
                                               driver->xmlopt,
423
                                               NULL,
424 425
                                               VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                               VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
J
Jim Fehlig 已提交
426 427 428 429 430 431 432 433 434 435 436 437 438
            goto endjob;

        if (!libxlDomainDefCheckABIStability(driver, vm->def, tmpdef))
            goto endjob;

        def = tmpdef;
    } else {
        def = vm->def;
    }

    if (!libxlDomainMigrationIsAllowed(def))
        goto endjob;

439
    xml = virDomainDefFormat(def, cfg->caps, VIR_DOMAIN_DEF_FORMAT_SECURE);
J
Jim Fehlig 已提交
440

441
 endjob:
W
Wang Yufei 已提交
442
    libxlDomainObjEndJob(driver, vm);
443

J
Jim Fehlig 已提交
444
 cleanup:
J
John Ferlan 已提交
445
    libxlMigrationCookieFree(mig);
J
Jim Fehlig 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
    virDomainDefFree(tmpdef);
    virObjectUnref(cfg);
    return xml;
}

virDomainDefPtr
libxlDomainMigrationPrepareDef(libxlDriverPrivatePtr driver,
                               const char *dom_xml,
                               const char *dname)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    virDomainDefPtr def;
    char *name = NULL;

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

    if (!(def = virDomainDefParseString(dom_xml, cfg->caps, driver->xmlopt,
467
                                        NULL,
468 469
                                        VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                        VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE)))
J
Jim Fehlig 已提交
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
        goto cleanup;

    if (dname) {
        name = def->name;
        if (VIR_STRDUP(def->name, dname) < 0) {
            virDomainDefFree(def);
            def = NULL;
        }
    }

 cleanup:
    virObjectUnref(cfg);
    VIR_FREE(name);
    return def;
}

486 487 488 489 490 491 492 493
static int
libxlDomainMigrationPrepareAny(virConnectPtr dconn,
                               virDomainDefPtr *def,
                               const char *cookiein,
                               int cookieinlen,
                               libxlMigrationCookiePtr *mig,
                               char **xmlout,
                               bool *taint_hook)
J
Jim Fehlig 已提交
494 495
{
    libxlDriverPrivatePtr driver = dconn->privateData;
C
Cédric Bosdonnat 已提交
496
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Jim Fehlig 已提交
497

498 499
    if (libxlMigrationEatCookie(cookiein, cookieinlen, mig) < 0)
        return -1;
500

501
    if ((*mig)->xenMigStreamVer > LIBXL_SAVE_VERSION) {
502 503
        virReportError(VIR_ERR_OPERATION_UNSUPPORTED,
                       _("Xen migration stream version '%d' is not supported on this host"),
504 505
                       (*mig)->xenMigStreamVer);
        return -1;
506 507
    }

C
Cédric Bosdonnat 已提交
508 509 510 511 512 513 514 515
    /* Let migration hook filter domain XML */
    if (virHookPresent(VIR_HOOK_DRIVER_LIBXL)) {
        char *xml;
        int hookret;

        if (!(xml = virDomainDefFormat(*def, cfg->caps,
                                       VIR_DOMAIN_XML_SECURE |
                                       VIR_DOMAIN_XML_MIGRATABLE)))
516
            return -1;
C
Cédric Bosdonnat 已提交
517 518 519

        hookret = virHookCall(VIR_HOOK_DRIVER_LIBXL, (*def)->name,
                              VIR_HOOK_LIBXL_OP_MIGRATE, VIR_HOOK_SUBOP_BEGIN,
520
                              NULL, xml, xmlout);
C
Cédric Bosdonnat 已提交
521 522 523
        VIR_FREE(xml);

        if (hookret < 0) {
524
            return -1;
C
Cédric Bosdonnat 已提交
525
        } else if (hookret == 0) {
526
            if (virStringIsEmpty(*xmlout)) {
C
Cédric Bosdonnat 已提交
527 528 529 530 531
                VIR_DEBUG("Migrate hook filter returned nothing; using the"
                          " original XML");
            } else {
                virDomainDefPtr newdef;

532 533
                VIR_DEBUG("Using hook-filtered domain XML: %s", *xmlout);
                newdef = virDomainDefParseString(*xmlout, cfg->caps, driver->xmlopt,
534
                                                 NULL,
C
Cédric Bosdonnat 已提交
535 536 537
                                                 VIR_DOMAIN_DEF_PARSE_INACTIVE |
                                                 VIR_DOMAIN_DEF_PARSE_SKIP_VALIDATE);
                if (!newdef)
538
                    return -1;
C
Cédric Bosdonnat 已提交
539 540 541 542 543 544 545 546 547

                /* TODO At some stage we will want to have some check of what the user
                 * did in the hook. */

                virDomainDefFree(*def);
                *def = newdef;
                /* We should taint the domain here. However, @vm and therefore
                 * privateData too are still NULL, so just notice the fact and
                 * taint it later. */
548
                *taint_hook = true;
C
Cédric Bosdonnat 已提交
549 550 551 552
            }
        }
    }

553 554 555
    return 0;
}

B
Bob Liu 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
int
libxlDomainMigrationPrepareTunnel3(virConnectPtr dconn,
                                   virStreamPtr st,
                                   virDomainDefPtr *def,
                                   const char *cookiein,
                                   int cookieinlen,
                                   unsigned int flags)
{
    libxlMigrationCookiePtr mig = NULL;
    libxlDriverPrivatePtr driver = dconn->privateData;
    virDomainObjPtr vm = NULL;
    libxlMigrationDstArgs *args = NULL;
    virThread thread;
    bool taint_hook = false;
    libxlDomainObjPrivatePtr priv = NULL;
    char *xmlout = NULL;
    int dataFD[2] = { -1, -1 };
    int ret = -1;

    if (libxlDomainMigrationPrepareAny(dconn, def, cookiein, cookieinlen,
                                       &mig, &xmlout, &taint_hook) < 0)
        goto error;

    if (!(vm = virDomainObjListAdd(driver->domains, *def,
                                   driver->xmlopt,
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
        goto error;

586
    virObjectRef(vm);
B
Bob Liu 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
    *def = NULL;
    priv = vm->privateData;

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

    /*
     * The data flow of tunnel3 migration in the dest side:
     * stream -> pipe -> recvfd of libxlDomainStartRestore
     */
    if (pipe(dataFD) < 0)
        goto error;

    /* Stream data will be written to pipeIn */
    if (virFDStreamOpen(st, dataFD[1]) < 0)
        goto error;
    dataFD[1] = -1; /* 'st' owns the FD now & will close it */

    if (libxlMigrationDstArgsInitialize() < 0)
        goto error;

    if (!(args = virObjectNew(libxlMigrationDstArgsClass)))
        goto error;

    args->conn = dconn;
    args->vm = vm;
    args->flags = flags;
    args->migcookie = mig;
    /* Receive from pipeOut */
    args->recvfd = dataFD[0];
    args->nsocks = 0;
620 621
    mig = NULL;

B
Bob Liu 已提交
622 623 624 625 626 627 628 629 630 631
    if (virThreadCreate(&thread, false, libxlDoMigrateReceive, args) < 0) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Failed to create thread for receiving migration data"));
        goto error;
    }

    ret = 0;
    goto done;

 error:
632
    libxlMigrationCookieFree(mig);
B
Bob Liu 已提交
633 634 635 636 637 638
    VIR_FORCE_CLOSE(dataFD[1]);
    VIR_FORCE_CLOSE(dataFD[0]);
    virObjectUnref(args);
    /* Remove virDomainObj from domain list */
    if (vm) {
        virDomainObjListRemove(driver->domains, vm);
639
        virObjectLock(vm);
B
Bob Liu 已提交
640 641 642
    }

 done:
643
    virDomainObjEndAPI(&vm);
B
Bob Liu 已提交
644 645 646
    return ret;
}

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
int
libxlDomainMigrationPrepare(virConnectPtr dconn,
                            virDomainDefPtr *def,
                            const char *uri_in,
                            char **uri_out,
                            const char *cookiein,
                            int cookieinlen,
                            unsigned int flags)
{
    libxlDriverPrivatePtr driver = dconn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    libxlMigrationCookiePtr mig = NULL;
    virDomainObjPtr vm = NULL;
    char *hostname = NULL;
    char *xmlout = NULL;
    unsigned short port;
    char portstr[100];
    virURIPtr uri = NULL;
    virNetSocketPtr *socks = NULL;
    size_t nsocks = 0;
    int nsocks_listen = 0;
    libxlMigrationDstArgs *args = NULL;
    bool taint_hook = false;
    libxlDomainObjPrivatePtr priv = NULL;
    size_t i;
    int ret = -1;

    if (libxlDomainMigrationPrepareAny(dconn, def, cookiein, cookieinlen,
                                       &mig, &xmlout, &taint_hook) < 0)
        goto error;

678
    if (!(vm = virDomainObjListAdd(driver->domains, *def,
J
Jim Fehlig 已提交
679 680 681 682
                                   driver->xmlopt,
                                   VIR_DOMAIN_OBJ_LIST_ADD_LIVE |
                                   VIR_DOMAIN_OBJ_LIST_ADD_CHECK_LIVE,
                                   NULL)))
J
Jim Fehlig 已提交
683
        goto error;
684

685
    virObjectRef(vm);
686
    *def = NULL;
C
Cédric Bosdonnat 已提交
687 688 689 690 691 692
    priv = vm->privateData;

    if (taint_hook) {
        /* Domain XML has been altered by a hook script. */
        priv->hookRun = true;
    }
J
Jim Fehlig 已提交
693 694 695 696

    /* Create socket connection to receive migration data */
    if (!uri_in) {
        if ((hostname = virGetHostname()) == NULL)
J
Jim Fehlig 已提交
697
            goto error;
J
Jim Fehlig 已提交
698 699 700 701 702

        if (STRPREFIX(hostname, "localhost")) {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("hostname on destination resolved to localhost,"
                             " but migration requires an FQDN"));
J
Jim Fehlig 已提交
703
            goto error;
J
Jim Fehlig 已提交
704 705 706
        }

        if (virPortAllocatorAcquire(driver->migrationPorts, &port) < 0)
J
Jim Fehlig 已提交
707
            goto error;
J
Jim Fehlig 已提交
708

709
        priv->migrationPort = port;
J
Jim Fehlig 已提交
710
        if (virAsprintf(uri_out, "tcp://%s:%d", hostname, port) < 0)
J
Jim Fehlig 已提交
711
            goto error;
J
Jim Fehlig 已提交
712 713 714 715 716
    } else {
        if (!(STRPREFIX(uri_in, "tcp://"))) {
            /* not full URI, add prefix tcp:// */
            char *tmp;
            if (virAsprintf(&tmp, "tcp://%s", uri_in) < 0)
J
Jim Fehlig 已提交
717
                goto error;
J
Jim Fehlig 已提交
718 719 720 721 722 723 724 725 726 727
            uri = virURIParse(tmp);
            VIR_FREE(tmp);
        } else {
            uri = virURIParse(uri_in);
        }

        if (uri == NULL) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("unable to parse URI: %s"),
                           uri_in);
J
Jim Fehlig 已提交
728
            goto error;
J
Jim Fehlig 已提交
729 730 731 732 733 734
        }

        if (uri->server == NULL) {
            virReportError(VIR_ERR_INVALID_ARG,
                           _("missing host in migration URI: %s"),
                           uri_in);
J
Jim Fehlig 已提交
735
            goto error;
J
Jim Fehlig 已提交
736
        }
737
        hostname = uri->server;
J
Jim Fehlig 已提交
738 739 740

        if (uri->port == 0) {
            if (virPortAllocatorAcquire(driver->migrationPorts, &port) < 0)
J
Jim Fehlig 已提交
741
                goto error;
J
Jim Fehlig 已提交
742

743
            priv->migrationPort = port;
J
Jim Fehlig 已提交
744 745 746 747 748
        } else {
            port = uri->port;
        }

        if (virAsprintf(uri_out, "tcp://%s:%d", hostname, port) < 0)
J
Jim Fehlig 已提交
749
            goto error;
J
Jim Fehlig 已提交
750 751 752 753
    }

    snprintf(portstr, sizeof(portstr), "%d", port);

754 755 756
    if (virNetSocketNewListenTCP(hostname, portstr,
                                 AF_UNSPEC,
                                 &socks, &nsocks) < 0) {
J
Jim Fehlig 已提交
757 758
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Fail to create socket for incoming migration"));
J
Jim Fehlig 已提交
759
        goto error;
J
Jim Fehlig 已提交
760 761 762
    }

    if (libxlMigrationDstArgsInitialize() < 0)
J
Jim Fehlig 已提交
763
        goto error;
J
Jim Fehlig 已提交
764 765

    if (!(args = virObjectNew(libxlMigrationDstArgsClass)))
J
Jim Fehlig 已提交
766
        goto error;
J
Jim Fehlig 已提交
767 768 769 770 771 772

    args->conn = dconn;
    args->vm = vm;
    args->flags = flags;
    args->socks = socks;
    args->nsocks = nsocks;
773
    args->migcookie = mig;
J
John Ferlan 已提交
774
    mig = NULL;
J
Jim Fehlig 已提交
775 776 777 778 779 780 781 782 783 784

    for (i = 0; i < nsocks; i++) {
        if (virNetSocketSetBlocking(socks[i], true) < 0)
             continue;

        if (virNetSocketListen(socks[i], 1) < 0)
            continue;

        if (virNetSocketAddIOCallback(socks[i],
                                      VIR_EVENT_HANDLE_READABLE,
785
                                      libxlMigrateReceive,
J
Jim Fehlig 已提交
786
                                      args,
787
                                      NULL) < 0)
J
Jim Fehlig 已提交
788 789 790 791 792 793
            continue;

        nsocks_listen++;
    }

    if (!nsocks_listen)
J
Jim Fehlig 已提交
794
        goto error;
J
Jim Fehlig 已提交
795 796 797 798

    ret = 0;
    goto done;

J
Jim Fehlig 已提交
799
 error:
J
Jim Fehlig 已提交
800 801 802 803
    for (i = 0; i < nsocks; i++) {
        virNetSocketClose(socks[i]);
        virObjectUnref(socks[i]);
    }
804
    VIR_FREE(socks);
805
    virObjectUnref(args);
806 807 808 809
    if (priv) {
        virPortAllocatorRelease(priv->migrationPort);
        priv->migrationPort = 0;
    }
810 811 812
    /* Remove virDomainObj from domain list */
    if (vm) {
        virDomainObjListRemove(driver->domains, vm);
813
        virObjectLock(vm);
814
    }
J
Jim Fehlig 已提交
815 816

 done:
C
Cédric Bosdonnat 已提交
817
    VIR_FREE(xmlout);
J
John Ferlan 已提交
818
    libxlMigrationCookieFree(mig);
819 820 821 822
    if (!uri_in)
        VIR_FREE(hostname);
    else
        virURIFree(uri);
823
    virDomainObjEndAPI(&vm);
C
Cédric Bosdonnat 已提交
824
    virObjectUnref(cfg);
J
Jim Fehlig 已提交
825 826 827
    return ret;
}

B
Bob Liu 已提交
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
typedef struct _libxlTunnelMigrationThread libxlTunnelMigrationThread;
struct _libxlTunnelMigrationThread {
    virStreamPtr st;
    int srcFD;
};
#define TUNNEL_SEND_BUF_SIZE 65536

/*
 * The data flow of tunnel3 migration in the src side:
 * libxlDoMigrateSend() -> pipe
 * libxlTunnel3MigrationFunc() polls pipe out and then write to dest stream.
 */
static void libxlTunnel3MigrationFunc(void *arg)
{
    libxlTunnelMigrationThread *data = (libxlTunnelMigrationThread *)arg;
    char *buffer = NULL;
    struct pollfd fds[1];
    int timeout = -1;

    if (VIR_ALLOC_N(buffer, TUNNEL_SEND_BUF_SIZE) < 0)
        return;

    fds[0].fd = data->srcFD;
    for (;;) {
        int ret;

        fds[0].events = POLLIN;
        fds[0].revents = 0;
        ret = poll(fds, ARRAY_CARDINALITY(fds), timeout);
        if (ret < 0) {
            if (errno == EAGAIN || errno == EINTR)
                continue;
            virReportError(errno, "%s",
                           _("poll failed in libxlTunnel3MigrationFunc"));
            goto cleanup;
        }

        if (ret == 0) {
            VIR_DEBUG("poll returned 0");
            break;
        }

        if (fds[0].revents & (POLLIN | POLLERR | POLLHUP)) {
            int nbytes;

            nbytes = read(data->srcFD, buffer, TUNNEL_SEND_BUF_SIZE);
            if (nbytes > 0) {
                /* Write to dest stream */
                if (virStreamSend(data->st, buffer, nbytes) < 0) {
                    virStreamAbort(data->st);
                    goto cleanup;
                }
            } else if (nbytes < 0) {
                virReportError(errno, "%s",
                               _("tunnelled migration failed to read from xen side"));
                virStreamAbort(data->st);
                goto cleanup;
            } else {
                /* EOF; transferred all data */
                break;
            }
        }
    }

    ignore_value(virStreamFinish(data->st));

 cleanup:
    VIR_FREE(buffer);

    return;
}

struct libxlTunnelControl {
    libxlTunnelMigrationThread tmThread;
    virThread thread;
    int dataFD[2];
};

static int
libxlMigrationStartTunnel(libxlDriverPrivatePtr driver,
                          virDomainObjPtr vm,
                          unsigned long flags,
                          virStreamPtr st,
911
                          struct libxlTunnelControl **tnl)
B
Bob Liu 已提交
912
{
913
    struct libxlTunnelControl *tc = NULL;
B
Bob Liu 已提交
914 915 916 917 918
    libxlTunnelMigrationThread *arg = NULL;
    int ret = -1;

    if (VIR_ALLOC(tc) < 0)
        goto out;
919
    *tnl = tc;
B
Bob Liu 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966

    tc->dataFD[0] = -1;
    tc->dataFD[1] = -1;
    if (pipe(tc->dataFD) < 0) {
        virReportError(errno, "%s", _("Unable to make pipes"));
        goto out;
    }

    arg = &tc->tmThread;
    /* Read from pipe */
    arg->srcFD = tc->dataFD[0];
    /* Write to dest stream */
    arg->st = st;
    if (virThreadCreate(&tc->thread, true,
                        libxlTunnel3MigrationFunc, arg) < 0) {
        virReportError(errno, "%s",
                       _("Unable to create tunnel migration thread"));
        goto out;
    }

    virObjectUnlock(vm);
    /* Send data to pipe */
    ret = libxlDoMigrateSend(driver, vm, flags, tc->dataFD[1]);
    virObjectLock(vm);

 out:
    /* libxlMigrationStopTunnel will be called in libxlDoMigrateP2P to free
     * all resources for us. */
    return ret;
}

static void libxlMigrationStopTunnel(struct libxlTunnelControl *tc)
{
    if (!tc)
        return;

    virThreadCancel(&tc->thread);
    virThreadJoin(&tc->thread);

    VIR_FORCE_CLOSE(tc->dataFD[0]);
    VIR_FORCE_CLOSE(tc->dataFD[1]);
    VIR_FREE(tc);
}

/* This function is a simplification of virDomainMigrateVersion3Full and
 * restricting it to migration v3 with params since it was the first to be
 * introduced in libxl.
J
Joao Martins 已提交
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985
 */
static int
libxlDoMigrateP2P(libxlDriverPrivatePtr driver,
                  virDomainObjPtr vm,
                  virConnectPtr sconn,
                  const char *xmlin,
                  virConnectPtr dconn,
                  const char *dconnuri ATTRIBUTE_UNUSED,
                  const char *dname,
                  const char *uri,
                  unsigned int flags)
{
    virDomainPtr ddomain = NULL;
    virTypedParameterPtr params = NULL;
    int nparams = 0;
    int maxparams = 0;
    char *uri_out = NULL;
    char *dom_xml = NULL;
    unsigned long destflags;
986 987
    char *cookieout = NULL;
    int cookieoutlen;
J
Joao Martins 已提交
988 989 990
    bool cancelled = true;
    virErrorPtr orig_err = NULL;
    int ret = -1;
B
Bob Liu 已提交
991 992 993
    /* For tunnel migration */
    virStreamPtr st = NULL;
    struct libxlTunnelControl *tc = NULL;
J
Joao Martins 已提交
994

995 996
    dom_xml = libxlDomainMigrationBegin(sconn, vm, xmlin,
                                        &cookieout, &cookieoutlen);
J
Joao Martins 已提交
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    if (!dom_xml)
        goto cleanup;

    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;

    /* We don't require the destination to have P2P support
     * as it looks to be normal migration from the receiver perpective.
     */
    destflags = flags & ~(VIR_MIGRATE_PEER2PEER);

    VIR_DEBUG("Prepare3");
    virObjectUnlock(vm);
B
Bob Liu 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029
    if (flags & VIR_MIGRATE_TUNNELLED) {
        if (!(st = virStreamNew(dconn, 0)))
            goto cleanup;
        ret = dconn->driver->domainMigratePrepareTunnel3Params
            (dconn, st, params, nparams, cookieout, cookieoutlen, NULL, NULL, destflags);
    } else {
        ret = dconn->driver->domainMigratePrepare3Params
            (dconn, params, nparams, cookieout, cookieoutlen, NULL, NULL, &uri_out, destflags);
    }
J
Joao Martins 已提交
1030 1031 1032 1033 1034
    virObjectLock(vm);

    if (ret == -1)
        goto cleanup;

B
Bob Liu 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
        if (uri_out) {
            if (virTypedParamsReplaceString(&params, &nparams,
                                            VIR_MIGRATE_PARAM_URI, uri_out) < 0) {
                orig_err = virSaveLastError();
                goto finish;
            }
        } else {
            virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                           _("domainMigratePrepare3 did not set uri"));
J
Joao Martins 已提交
1045 1046 1047 1048 1049
            goto finish;
        }
    }

    VIR_DEBUG("Perform3 uri=%s", NULLSTR(uri_out));
B
Bob Liu 已提交
1050
    if (flags & VIR_MIGRATE_TUNNELLED)
1051
        ret = libxlMigrationStartTunnel(driver, vm, flags, st, &tc);
B
Bob Liu 已提交
1052 1053 1054
    else
        ret = libxlDomainMigrationPerform(driver, vm, NULL, NULL,
                                          uri_out, NULL, flags);
J
Joao Martins 已提交
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 1088 1089 1090 1091
    if (ret < 0)
        orig_err = virSaveLastError();

    cancelled = (ret < 0);

 finish:
    VIR_DEBUG("Finish3 ret=%d", ret);
    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 {
        virObjectUnlock(vm);
        ddomain = dconn->driver->domainMigrateFinish3Params
            (dconn, params, nparams, NULL, 0, NULL, NULL,
             destflags, cancelled);
        virObjectLock(vm);
    }

    cancelled = (ddomain == NULL);

    /* If Finish3Params 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();

    VIR_DEBUG("Confirm3 cancelled=%d vm=%p", cancelled, vm);
    ret = libxlDomainMigrationConfirm(driver, vm, flags, cancelled);

    if (ret < 0)
        VIR_WARN("Guest %s probably left in 'paused' state on source",
                 vm->def->name);

 cleanup:
B
Bob Liu 已提交
1092 1093 1094 1095 1096
    if (flags & VIR_MIGRATE_TUNNELLED) {
        libxlMigrationStopTunnel(tc);
        virObjectUnref(st);
    }

J
Joao Martins 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    if (ddomain) {
        virObjectUnref(ddomain);
        ret = 0;
    } else {
        ret = -1;
    }

    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }

1109
    VIR_FREE(cookieout);
J
Joao Martins 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    VIR_FREE(dom_xml);
    VIR_FREE(uri_out);
    virTypedParamsFree(params, nparams);
    return ret;
}

static int virConnectCredType[] = {
    VIR_CRED_AUTHNAME,
    VIR_CRED_PASSPHRASE,
};

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

/* On P2P mode there is only the Perform3 phase and we need to handle
 * the connection with the destination libvirtd and perform the migration.
 * Here we first tackle the first part of it, and libxlDoMigrationP2P handles
 * the migration process with an established virConnectPtr to the destination.
 */
int
libxlDomainMigrationPerformP2P(libxlDriverPrivatePtr driver,
                               virDomainObjPtr vm,
                               virConnectPtr sconn,
                               const char *xmlin,
                               const char *dconnuri,
                               const char *uri_str ATTRIBUTE_UNUSED,
                               const char *dname,
                               unsigned int flags)
{
    int ret = -1;
    bool useParams;
    virConnectPtr dconn = NULL;
    virErrorPtr orig_err = NULL;
J
Joao Martins 已提交
1145
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
J
Joao Martins 已提交
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157

    virObjectUnlock(vm);
    dconn = virConnectOpenAuth(dconnuri, &virConnectAuthConfig, 0);
    virObjectLock(vm);

    if (dconn == NULL) {
        virReportError(VIR_ERR_OPERATION_FAILED,
                       _("Failed to connect to remote libvirt URI %s: %s"),
                       dconnuri, virGetLastErrorMessage());
        return ret;
    }

J
Joao Martins 已提交
1158 1159 1160 1161
    if (virConnectSetKeepAlive(dconn, cfg->keepAliveInterval,
                               cfg->keepAliveCount) < 0)
        goto cleanup;

J
Joao Martins 已提交
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    virObjectUnlock(vm);
    useParams = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
                                         VIR_DRV_FEATURE_MIGRATION_PARAMS);
    virObjectLock(vm);

    if (!useParams) {
        virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                       _("Destination libvirt does not support migration with extensible parameters"));
        goto cleanup;
    }

    ret = libxlDoMigrateP2P(driver, vm, sconn, xmlin, dconn, dconnuri,
                            dname, uri_str, flags);

 cleanup:
    orig_err = virSaveLastError();
    virObjectUnlock(vm);
    virObjectUnref(dconn);
J
Joao Martins 已提交
1180
    virObjectUnref(cfg);
J
Joao Martins 已提交
1181 1182 1183 1184 1185 1186 1187 1188
    virObjectLock(vm);
    if (orig_err) {
        virSetError(orig_err);
        virFreeError(orig_err);
    }
    return ret;
}

J
Jim Fehlig 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197
int
libxlDomainMigrationPerform(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            const char *dom_xml ATTRIBUTE_UNUSED,
                            const char *dconnuri ATTRIBUTE_UNUSED,
                            const char *uri_str,
                            const char *dname ATTRIBUTE_UNUSED,
                            unsigned int flags)
{
1198
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
    char *hostname = NULL;
    unsigned short port = 0;
    char portstr[100];
    virURIPtr uri = NULL;
    virNetSocketPtr sock;
    int sockfd = -1;
    int ret = -1;

    /* parse dst host:port from uri */
    uri = virURIParse(uri_str);
    if (uri == NULL || uri->server == NULL || uri->port == 0)
        goto cleanup;

    hostname = uri->server;
    port = uri->port;
    snprintf(portstr, sizeof(portstr), "%d", port);

    /* socket connect to dst host:port */
1217 1218
    if (virNetSocketNewConnectTCP(hostname, portstr,
                                  AF_UNSPEC,
1219
                                  &sock) < 0)
J
Jim Fehlig 已提交
1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
        goto cleanup;

    if (virNetSocketSetBlocking(sock, true) < 0) {
        virObjectUnref(sock);
        goto cleanup;
    }

    sockfd = virNetSocketDupFD(sock, true);
    virObjectUnref(sock);

1230 1231 1232 1233
    if (virDomainLockProcessPause(driver->lockManager, vm, &priv->lockState) < 0)
        VIR_WARN("Unable to release lease on %s", vm->def->name);
    VIR_DEBUG("Preserving lock state '%s'", NULLSTR(priv->lockState));

J
Jim Fehlig 已提交
1234 1235 1236 1237 1238
    /* suspend vm and send saved data to dst through socket fd */
    virObjectUnlock(vm);
    ret = libxlDoMigrateSend(driver, vm, flags, sockfd);
    virObjectLock(vm);

1239 1240 1241 1242 1243 1244
    if (ret < 0)
        virDomainLockProcessResume(driver->lockManager,
                                   "xen:///system",
                                   vm,
                                   priv->lockState);

J
Jim Fehlig 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
 cleanup:
    VIR_FORCE_CLOSE(sockfd);
    virURIFree(uri);
    return ret;
}

virDomainPtr
libxlDomainMigrationFinish(virConnectPtr dconn,
                           virDomainObjPtr vm,
                           unsigned int flags,
                           int cancelled)
{
    libxlDriverPrivatePtr driver = dconn->privateData;
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
    libxlDomainObjPrivatePtr priv = vm->privateData;
    virObjectEventPtr event = NULL;
    virDomainPtr dom = NULL;

1263
    virPortAllocatorRelease(priv->migrationPort);
J
Jim Fehlig 已提交
1264 1265 1266 1267 1268
    priv->migrationPort = 0;

    if (cancelled)
        goto cleanup;

1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
    /* Check if domain is alive */
    if (!virDomainObjIsActive(vm)) {
        /* Migration failed if domain is inactive */
        virReportError(VIR_ERR_OPERATION_FAILED,
                       "%s", _("Migration failed. Domain is not running "
                               "on destination host"));
        goto cleanup;
    }

    /* Unpause if requested */
J
Jim Fehlig 已提交
1279
    if (!(flags & VIR_MIGRATE_PAUSED)) {
J
Jim Fehlig 已提交
1280
        if (libxl_domain_unpause(cfg->ctx, vm->def->id) != 0) {
J
Jim Fehlig 已提交
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297
            virReportError(VIR_ERR_OPERATION_FAILED, "%s",
                           _("Failed to unpause domain"));
            goto cleanup;
        }

        virDomainObjSetState(vm, VIR_DOMAIN_RUNNING,
                             VIR_DOMAIN_RUNNING_MIGRATED);
        event = virDomainEventLifecycleNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
    } else {
        virDomainObjSetState(vm, VIR_DOMAIN_PAUSED, VIR_DOMAIN_PAUSED_USER);
        event = virDomainEventLifecycleNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
    }

1298 1299 1300 1301 1302
    if (event) {
        libxlDomainEventQueue(driver, event);
        event = NULL;
    }

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
    if (flags & VIR_MIGRATE_PERSIST_DEST) {
        unsigned int oldPersist = vm->persistent;
        virDomainDefPtr vmdef;

        vm->persistent = 1;
        if (!(vmdef = virDomainObjGetPersistentDef(cfg->caps,
                                                   driver->xmlopt, vm)))
            goto cleanup;

        if (virDomainSaveConfig(cfg->configDir, cfg->caps, vmdef) < 0)
            goto cleanup;

        event = virDomainEventLifecycleNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_DEFINED,
                                         oldPersist ?
                                         VIR_DOMAIN_EVENT_DEFINED_UPDATED :
                                         VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event) {
            libxlDomainEventQueue(driver, event);
            event = NULL;
        }
    }

1326
    if (virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps) < 0)
1327 1328
        goto cleanup;

1329
    dom = virGetDomain(dconn, vm->def->name, vm->def->uuid, vm->def->id);
J
Jim Fehlig 已提交
1330

1331
 cleanup:
J
Jim Fehlig 已提交
1332
    if (dom == NULL) {
1333
        libxlDomainDestroyInternal(driver, vm);
1334 1335 1336
        libxlDomainCleanup(driver, vm);
        virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                             VIR_DOMAIN_SHUTOFF_FAILED);
J
Jim Fehlig 已提交
1337 1338
        event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1339
        if (!vm->persistent) {
1340
            virDomainObjListRemove(driver->domains, vm);
1341 1342 1343
            /* Caller passed a locked vm and expects the same on return */
            virObjectLock(vm);
        }
J
Jim Fehlig 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    }

    if (event)
        libxlDomainEventQueue(driver, event);
    virObjectUnref(cfg);
    return dom;
}

int
libxlDomainMigrationConfirm(libxlDriverPrivatePtr driver,
                            virDomainObjPtr vm,
                            unsigned int flags,
                            int cancelled)
{
    libxlDriverConfigPtr cfg = libxlDriverConfigGet(driver);
1359
    libxlDomainObjPrivatePtr priv = vm->privateData;
J
Jim Fehlig 已提交
1360 1361 1362 1363
    virObjectEventPtr event = NULL;
    int ret = -1;

    if (cancelled) {
1364 1365 1366 1367 1368
        /* Resume lock process that was paused in MigrationPerform */
        virDomainLockProcessResume(driver->lockManager,
                                   "xen:///system",
                                   vm,
                                   priv->lockState);
J
Jim Fehlig 已提交
1369
        if (libxl_domain_resume(cfg->ctx, vm->def->id, 1, 0) == 0) {
J
Jim Fehlig 已提交
1370 1371 1372 1373 1374 1375 1376 1377
            ret = 0;
        } else {
            VIR_DEBUG("Unable to resume domain '%s' after failed migration",
                      vm->def->name);
            virDomainObjSetState(vm, VIR_DOMAIN_PAUSED,
                                 VIR_DOMAIN_PAUSED_MIGRATION);
            event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_SUSPENDED,
                                     VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
1378
            ignore_value(virDomainSaveStatus(driver->xmlopt, cfg->stateDir, vm, cfg->caps));
J
Jim Fehlig 已提交
1379 1380 1381 1382
        }
        goto cleanup;
    }

1383
    libxlDomainDestroyInternal(driver, vm);
1384 1385 1386
    libxlDomainCleanup(driver, vm);
    virDomainObjSetState(vm, VIR_DOMAIN_SHUTOFF,
                         VIR_DOMAIN_SHUTOFF_MIGRATED);
J
Jim Fehlig 已提交
1387 1388 1389 1390 1391 1392 1393 1394
    event = virDomainEventLifecycleNewFromObj(vm, VIR_DOMAIN_EVENT_STOPPED,
                                              VIR_DOMAIN_EVENT_STOPPED_MIGRATED);

    VIR_DEBUG("Domain '%s' successfully migrated", vm->def->name);

    if (flags & VIR_MIGRATE_UNDEFINE_SOURCE)
        virDomainDeleteConfig(cfg->configDir, cfg->autostartDir, vm);

1395
    if (!vm->persistent || (flags & VIR_MIGRATE_UNDEFINE_SOURCE)) {
J
Jim Fehlig 已提交
1396
        virDomainObjListRemove(driver->domains, vm);
1397 1398
        /* Caller passed a locked vm and expects the same on return */
        virObjectLock(vm);
1399
    }
J
Jim Fehlig 已提交
1400 1401 1402 1403 1404 1405 1406 1407 1408

    ret = 0;

 cleanup:
    if (event)
        libxlDomainEventQueue(driver, event);
    virObjectUnref(cfg);
    return ret;
}