qemu_driver.c 134.5 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
4
 * Copyright (C) 2006, 2007, 2008, 2009 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * 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, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

24
#include <config.h>
25

D
Daniel P. Berrange 已提交
26 27 28 29 30 31 32 33 34 35 36
#include <sys/types.h>
#include <sys/poll.h>
#include <dirent.h>
#include <limits.h>
#include <string.h>
#include <stdio.h>
#include <strings.h>
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
37
#include <sys/utsname.h>
38 39 40 41
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <paths.h>
42 43
#include <pwd.h>
#include <stdio.h>
44
#include <sys/wait.h>
45
#include <sys/ioctl.h>
D
Daniel P. Berrange 已提交
46

47
#if HAVE_NUMACTL
48
#define NUMA_VERSION1_COMPATIBILITY 1
49 50 51
#include <numa.h>
#endif

52 53 54 55
#if HAVE_SCHED_H
#include <sched.h>
#endif

56
#include "virterror_internal.h"
57
#include "logging.h"
58
#include "datatypes.h"
59 60
#include "qemu_driver.h"
#include "qemu_conf.h"
J
Jim Meyering 已提交
61
#include "c-ctype.h"
62
#include "event.h"
63
#include "buf.h"
64
#include "util.h"
65
#include "nodeinfo.h"
66
#include "stats_linux.h"
67
#include "capabilities.h"
68
#include "memory.h"
69
#include "uuid.h"
70
#include "domain_conf.h"
71

72 73
#define VIR_FROM_THIS VIR_FROM_QEMU

R
Richard W.M. Jones 已提交
74 75 76
/* For storing short-lived temporary files. */
#define TEMPDIR LOCAL_STATE_DIR "/cache/libvirt"

77 78 79 80
#define QEMU_CMD_PROMPT "\n(qemu) "
#define QEMU_PASSWD_PROMPT "Password: "


81 82
static int qemudShutdown(void);

83 84
#define qemudLog(level, msg...) fprintf(stderr, msg)

85 86
static void qemuDriverLock(struct qemud_driver *driver)
{
87
    virMutexLock(&driver->lock);
88 89 90
}
static void qemuDriverUnlock(struct qemud_driver *driver)
{
91
    virMutexUnlock(&driver->lock);
92 93
}

94 95 96 97 98 99 100 101 102
static int qemudSetCloseExec(int fd) {
    int flags;
    if ((flags = fcntl(fd, F_GETFD)) < 0)
        goto error;
    flags |= FD_CLOEXEC;
    if ((fcntl(fd, F_SETFD, flags)) < 0)
        goto error;
    return 0;
 error:
J
Jim Meyering 已提交
103
    qemudLog(QEMUD_ERR,
104
             "%s", _("Failed to set close-on-exec file descriptor flag\n"));
105 106 107 108 109 110 111 112 113 114 115 116 117
    return -1;
}


static int qemudSetNonBlock(int fd) {
    int flags;
    if ((flags = fcntl(fd, F_GETFL)) < 0)
        goto error;
    flags |= O_NONBLOCK;
    if ((fcntl(fd, F_SETFL, flags)) < 0)
        goto error;
    return 0;
 error:
J
Jim Meyering 已提交
118
    qemudLog(QEMUD_ERR,
119
             "%s", _("Failed to set non-blocking file descriptor flag\n"));
120 121 122 123
    return -1;
}


124 125 126 127

static void qemuDomainEventFlush(int timer, void *opaque);
static void qemuDomainEventQueue(struct qemud_driver *driver,
                                 virDomainEventPtr event);
128

129 130
static void qemudDispatchVMEvent(int watch,
                                 int fd,
131 132 133
                                 int events,
                                 void *opaque);

134 135
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
136
                              virDomainObjPtr vm,
137 138
                              const char *migrateFrom,
                              int stdin_fd);
139

140 141
static void qemudShutdownVMDaemon(virConnectPtr conn,
                                  struct qemud_driver *driver,
142
                                  virDomainObjPtr vm);
143

144
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
145

146 147 148 149 150 151 152 153
static int qemudMonitorCommand(const virDomainObjPtr vm,
                               const char *cmd,
                               char **reply);
static int qemudMonitorCommandExtra(const virDomainObjPtr vm,
                                    const char *cmd,
                                    const char *extra,
                                    const char *extraPrompt,
                                    char **reply);
154

J
Jim Meyering 已提交
155
static struct qemud_driver *qemu_driver = NULL;
156 157


158 159 160 161 162 163
static int
qemudLogFD(virConnectPtr conn, const char* logDir, const char* name)
{
    char logfile[PATH_MAX];
    mode_t logmode;
    uid_t uid = geteuid();
G
Guido Günther 已提交
164
    int ret, fd = -1;
165

G
Guido Günther 已提交
166 167
    if ((ret = snprintf(logfile, sizeof(logfile), "%s/%s.log", logDir, name))
        < 0 || ret >= sizeof(logfile)) {
168
        virReportOOMError(conn);
169 170 171 172 173 174 175 176 177
        return -1;
    }

    logmode = O_CREAT | O_WRONLY;
    if (uid != 0)
        logmode |= O_TRUNC;
    else
        logmode |= O_APPEND;
    if ((fd = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
178 179 180
        virReportSystemError(conn, errno,
                             _("failed to create logfile %s"),
                             logfile);
181 182 183
        return -1;
    }
    if (qemudSetCloseExec(fd) < 0) {
184 185
        virReportSystemError(conn, errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
186 187 188 189 190 191 192
        close(fd);
        return -1;
    }
    return fd;
}


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
static int
qemudLogReadFD(virConnectPtr conn, const char* logDir, const char* name, off_t pos)
{
    char logfile[PATH_MAX];
    mode_t logmode = O_RDONLY;
    int ret, fd = -1;

    if ((ret = snprintf(logfile, sizeof(logfile), "%s/%s.log", logDir, name))
        < 0 || ret >= sizeof(logfile)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("failed to build logfile name %s/%s.log"),
                         logDir, name);
        return -1;
    }


    if ((fd = open(logfile, logmode)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("failed to create logfile %s: %s"),
                         logfile, strerror(errno));
        return -1;
    }
    if (qemudSetCloseExec(fd) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Unable to set VM logfile close-on-exec flag: %s"),
                         strerror(errno));
        close(fd);
        return -1;
    }
    if (lseek(fd, pos, SEEK_SET) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Unable to seek to %lld in %s: %s"),
225
                         (long long) pos, logfile, strerror(errno));
226 227 228 229 230 231
        close(fd);
    }
    return fd;
}


232 233 234
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;
235 236 237 238 239 240 241 242 243
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
    virConnectPtr conn = virConnectOpen(getuid() ?
                                        "qemu:///session" :
                                        "qemu:///system");
    /* Ignoring NULL conn which is mostly harmless here */
244 245

    for (i = 0 ; i < driver->domains.count ; i++) {
246
        virDomainObjPtr vm = driver->domains.objs[i];
247
        virDomainObjLock(vm);
248 249
        if (vm->autostart &&
            !virDomainIsActive(vm)) {
250
            int ret = qemudStartVMDaemon(conn, driver, vm, NULL, -1);
251 252 253 254 255 256
            if (ret < 0) {
                virErrorPtr err = virGetLastError();
                qemudLog(QEMUD_ERR, _("Failed to autostart VM '%s': %s\n"),
                         vm->def->name,
                         err ? err->message : NULL);
            } else {
257 258 259 260 261 262
                virDomainEventPtr event =
                    virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             VIR_DOMAIN_EVENT_STARTED_BOOTED);
                if (event)
                    qemuDomainEventQueue(driver, event);
263
            }
264
        }
265
        virDomainObjUnlock(vm);
266
    }
267 268

    virConnectClose(conn);
269 270
}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

/**
 * qemudRemoveDomainStatus
 *
 * remove all state files of a domain from statedir
 *
 * Returns 0 on success
 */
static int
qemudRemoveDomainStatus(virConnectPtr conn,
                        struct qemud_driver *driver,
                        virDomainObjPtr vm)
{
    int rc = -1;
    char *file = NULL;

    if (virAsprintf(&file, "%s/%s.xml", driver->stateDir, vm->def->name) < 0) {
288
        virReportOOMError(conn);
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        goto cleanup;
    }

    if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR) {
        qemudReportError(conn, vm, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Failed to unlink status file %s"), file);
        goto cleanup;
    }

    if(virFileDeletePid(driver->stateDir, vm->def->name))
        goto cleanup;

    rc = 0;
cleanup:
    VIR_FREE(file);
    return rc;
}


308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
static int qemudOpenMonitor(virConnectPtr conn,
                            struct qemud_driver* driver,
                            virDomainObjPtr vm,
                            const char *monitor,
                            int reconnect);

/**
 * qemudReconnectVMs
 *
 * Reconnect running vms to the daemon process
 */
static int
qemudReconnectVMs(struct qemud_driver *driver)
{
    int i;

    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjPtr vm = driver->domains.objs[i];
        qemudDomainStatusPtr status = NULL;
        char *config = NULL;
        int rc;

        virDomainObjLock(vm);
        if ((rc = virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) == 0)
            DEBUG("Found pid %d for '%s'", vm->pid, vm->def->name);
        else
            goto next;

        if ((config = virDomainConfigFile(NULL,
                                          driver->stateDir,
                                          vm->def->name)) == NULL) {
            qemudLog(QEMUD_ERR, _("Failed to read domain status for %s\n"),
                     vm->def->name);
            goto next_error;
        }

        status = qemudDomainStatusParseFile(NULL, driver->caps, config, 0);
        if (status) {
            vm->newDef = vm->def;
            vm->def = status->def;
        } else {
            qemudLog(QEMUD_ERR, _("Failed to parse domain status for %s\n"),
                     vm->def->name);
            goto next_error;
        }

        if ((rc = qemudOpenMonitor(NULL, driver, vm, status->monitorpath, 1)) != 0) {
            qemudLog(QEMUD_ERR, _("Failed to reconnect monitor for %s: %d\n"),
                     vm->def->name, rc);
            goto next_error;
358
        }
359

360
        if ((vm->logfile = qemudLogFD(NULL, driver->logDir, vm->def->name)) < 0)
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
            return -1;

        if (vm->def->id >= driver->nextvmid)
            driver->nextvmid = vm->def->id + 1;

        vm->state = status->state;
        goto next;

next_error:
        /* we failed to reconnect the vm so remove it's traces */
        vm->def->id = -1;
        qemudRemoveDomainStatus(NULL, driver, vm);
        virDomainDefFree(vm->def);
        vm->def = vm->newDef;
        vm->newDef = NULL;
next:
        virDomainObjUnlock(vm);
378 379
        if (status)
            VIR_FREE(status->monitorpath);
380 381 382 383 384 385 386
        VIR_FREE(status);
        VIR_FREE(config);
    }
    return 0;
}


387 388 389 390 391 392 393
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
394 395
    uid_t uid = geteuid();
    char *base = NULL;
D
Daniel P. Berrange 已提交
396
    char driverConf[PATH_MAX];
397

398
    if (VIR_ALLOC(qemu_driver) < 0)
399 400
        return -1;

401 402 403 404 405
    if (virMutexInit(&qemu_driver->lock) < 0) {
        qemudLog(QEMUD_ERROR, "%s", _("cannot initialize mutex"));
        VIR_FREE(qemu_driver);
        return -1;
    }
406 407
    qemuDriverLock(qemu_driver);

408 409 410
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;

411 412
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
413
        goto out_of_memory;
414 415 416 417 418 419
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

    if ((qemu_driver->domainEventTimer =
         virEventAddTimeout(-1, qemuDomainEventFlush, qemu_driver, NULL)) < 0)
        goto error;
420

421
    if (!uid) {
422 423
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
424
            goto out_of_memory;
425

D
Daniel P. Berrange 已提交
426
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
427
            goto out_of_memory;
428 429 430 431

        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu/", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
432
    } else {
433 434
        char *userdir = virGetUserDirectory(NULL, uid);
        if (!userdir)
435
            goto error;
436

437
        if (virAsprintf(&qemu_driver->logDir,
438 439
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
440
            goto out_of_memory;
441
        }
442

443 444
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
445
            goto out_of_memory;
446 447
        }
        VIR_FREE(userdir);
448 449 450 451 452 453

        if (virAsprintf(&qemu_driver->stateDir, "%s/qemu/run", base) == -1)
            goto out_of_memory;
    }

    if (virFileMakePath(qemu_driver->stateDir) < 0) {
454 455 456
        qemudLog(QEMUD_ERR, _("Failed to create state dir '%s': %s\n"),
                 qemu_driver->stateDir, strerror(errno));
        goto error;
457 458 459 460 461
    }

    /* Configuration paths are either ~/.libvirt/qemu/... (session) or
     * /etc/libvirt/qemu/... (system).
     */
D
Daniel P. Berrange 已提交
462
    if (snprintf (driverConf, sizeof(driverConf), "%s/qemu.conf", base) == -1)
463
        goto out_of_memory;
D
Daniel P. Berrange 已提交
464
    driverConf[sizeof(driverConf)-1] = '\0';
465

466
    if (virAsprintf(&qemu_driver->configDir, "%s/qemu", base) == -1)
467 468
        goto out_of_memory;

469
    if (virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
470 471
        goto out_of_memory;

472
    VIR_FREE(base);
473 474 475

    if ((qemu_driver->caps = qemudCapsInit()) == NULL)
        goto out_of_memory;
D
Daniel P. Berrange 已提交
476 477

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
478
        goto error;
D
Daniel P. Berrange 已提交
479 480
    }

481 482 483 484
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
485
                                qemu_driver->autostartDir,
486 487
                                NULL, NULL) < 0)
        goto error;
488
    qemudReconnectVMs(qemu_driver);
489 490
    qemudAutostartConfigs(qemu_driver);

491 492
    qemuDriverUnlock(qemu_driver);

493 494
    return 0;

495
out_of_memory:
J
Jim Meyering 已提交
496
    qemudLog (QEMUD_ERR,
497
              "%s", _("qemudStartup: out of memory\n"));
498 499 500
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
501
    VIR_FREE(base);
502
    qemudShutdown();
503 504 505
    return -1;
}

506 507 508 509
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

510 511 512 513 514 515 516 517
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
518 519
}

520 521 522 523 524 525 526 527
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
528 529 530
    if (!qemu_driver)
        return 0;

531
    qemuDriverLock(qemu_driver);
532 533 534 535
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
536 537
                            qemu_driver->autostartDir,
                            qemudNotifyLoadDomain, qemu_driver);
538

539
    qemudAutostartConfigs(qemu_driver);
540
    qemuDriverUnlock(qemu_driver);
541 542

    return 0;
543 544
}

545 546 547 548 549 550 551 552 553 554
/**
 * qemudActive:
 *
 * Checks if the QEmu daemon is active, i.e. has an active domain or
 * an active network
 *
 * Returns 1 if active, 0 otherwise
 */
static int
qemudActive(void) {
555
    unsigned int i;
556
    int active = 0;
557

558 559 560
    if (!qemu_driver)
        return 0;

561 562 563 564 565 566 567 568
    qemuDriverLock(qemu_driver);
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr vm = qemu_driver->domains.objs[i];
        virDomainObjLock(vm);
        if (virDomainIsActive(vm))
            active = 1;
        virDomainObjUnlock(vm);
    }
569

570 571
    qemuDriverUnlock(qemu_driver);
    return active;
572 573
}

574 575 576 577 578 579 580
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
581

582
    if (!qemu_driver)
583
        return -1;
584

585
    qemuDriverLock(qemu_driver);
586 587
    virCapabilitiesFree(qemu_driver->caps);

588
    virDomainObjListFree(&qemu_driver->domains);
589

590
    VIR_FREE(qemu_driver->logDir);
591 592
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
593
    VIR_FREE(qemu_driver->stateDir);
594
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
595
    VIR_FREE(qemu_driver->vncListen);
596
    VIR_FREE(qemu_driver->vncPassword);
D
Daniel P. Berrange 已提交
597

598 599
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
600 601 602 603
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

    if (qemu_driver->domainEventTimer != -1)
        virEventRemoveTimeout(qemu_driver->domainEventTimer);
604

605 606 607
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

608
    qemuDriverUnlock(qemu_driver);
609
    virMutexDestroy(&qemu_driver->lock);
610
    VIR_FREE(qemu_driver);
611 612

    return 0;
613 614 615
}

/* Return -1 for error, 1 to continue reading and 0 for success */
616
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
617
                                      virDomainObjPtr vm,
618 619 620
                                      const char *output,
                                      int fd);

621 622 623
/*
 * Returns -1 for error, 0 on end-of-file, 1 for success
 */
624
static int
625
qemudReadMonitorOutput(virConnectPtr conn,
626
                       virDomainObjPtr vm,
627 628 629 630
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
631 632
                       const char *what,
                       int timeout)
633 634 635 636
{
    int got = 0;
    buf[0] = '\0';

637
    /* Consume & discard the initial greeting */
638 639 640 641
    while (got < (buflen-1)) {
        int ret;

        ret = read(fd, buf+got, buflen-got-1);
642

643 644 645 646 647 648
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
649 650 651
                virReportSystemError(conn, errno,
                                     _("Failure while reading %s startup output"),
                                     what);
652 653 654
                return -1;
            }

655
            ret = poll(&pfd, 1, timeout);
656
            if (ret == 0) {
657
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
658
                                 _("Timed out while reading %s startup output"), what);
659 660 661
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
662 663 664
                    virReportSystemError(conn, errno,
                                         _("Failure while reading %s startup output"),
                                         what);
665 666 667 668 669 670 671 672
                    return -1;
                }
            } else {
                /* Make sure we continue loop & read any further data
                   available before dealing with EOF */
                if (pfd.revents & (POLLIN | POLLHUP))
                    continue;

673
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
674
                                 _("Failure while reading %s startup output"), what);
675 676
                return -1;
            }
677 678
        } else if (ret == 0) {
            return 0;
679 680 681
        } else {
            got += ret;
            buf[got] = '\0';
682 683 684 685 686 687
            ret = func(conn, vm, buf, fd);
            if (ret == -1)
                return -1;
            if (ret == 1)
                continue;
            return 1;
688 689 690
        }
    }

691
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
692
                     _("Out of space while reading %s startup output"), what);
693 694 695 696 697
    return -1;

}

static int
698
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
699
                        virDomainObjPtr vm,
700 701 702 703 704 705 706 707 708 709 710
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

711
static int qemudOpenMonitor(virConnectPtr conn,
712
                            struct qemud_driver* driver,
713
                            virDomainObjPtr vm,
714 715
                            const char *monitor,
                            int reconnect) {
716 717 718 719
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
720
    if ((monfd = open(monitor, O_RDWR)) < 0) {
721
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
722
                         _("Unable to open monitor path %s"), monitor);
723 724 725
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
726
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
727
                         "%s", _("Unable to set monitor close-on-exec flag"));
728 729 730
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
731
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
732
                         "%s", _("Unable to put monitor into non-blocking mode"));
733 734 735
        goto error;
    }

736
    if (!reconnect) {
737 738 739 740 741 742 743 744
        if (qemudReadMonitorOutput(conn,
                                   vm, monfd,
                                   buf, sizeof(buf),
                                   qemudCheckMonitorPrompt,
                                   "monitor", 10000) <= 0)
            ret = -1;
        else
            ret = 0;
745 746 747 748 749 750 751
    } else {
        vm->monitor = monfd;
        ret = 0;
    }

    if (ret != 0)
         goto error;
752

753
    if (!(vm->monitorpath = strdup(monitor))) {
754
        virReportOOMError(conn);
755 756 757
        goto error;
    }

758 759 760 761 762 763
    if ((vm->monitor_watch = virEventAddHandle(vm->monitor, 0,
                                               qemudDispatchVMEvent,
                                               driver, NULL)) < 0)
        goto error;


764 765 766 767
    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

768 769 770 771 772
 error:
    close(monfd);
    return ret;
}

773 774
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
775
                                   size_t *offset,
776
                                   char **path) {
777
    static const char needle[] = "char device redirected to";
778
    char *tmp, *dev;
779

780
    VIR_FREE(*path);
781
    /* First look for our magic string */
782 783 784 785 786
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
787

788 789 790 791 792
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
793
        if (c_isspace(*tmp)) {
794
            if (VIR_ALLOC_N(*path, (tmp-dev)+1) < 0) {
795
                virReportOOMError(conn);
796 797 798 799
                return -1;
            }
            strncpy(*path, dev, (tmp-dev));
            (*path)[(tmp-dev)] = '\0';
800
            /* ... now further update offset till we get EOL */
801
            *offset = tmp - haystack;
802 803
            return 0;
        }
804
        tmp++;
805 806 807 808 809
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
810 811
     * least see a \n - indicate that we want to carry
     * on trying again
812
     */
813
    return 1;
814 815 816
}

static int
817
qemudFindCharDevicePTYs(virConnectPtr conn,
818
                        virDomainObjPtr vm,
819 820
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
821
{
822
    struct qemud_driver* driver = conn->privateData;
823
    char *monitor = NULL;
824
    size_t offset = 0;
825
    int ret, i;
826 827 828 829 830

    /* The order in which QEMU prints out the PTY paths is
       the order in which it procsses its monitor, serial
       and parallel device args. This code must match that
       ordering.... */
831

832
    /* So first comes the monitor device */
833 834
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
835

836
    /* then the serial devices */
837 838
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
839 840 841 842
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
843 844 845 846
        }
    }

    /* and finally the parallel devices */
847 848
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
849 850 851 852
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
853 854 855 856
        }
    }

    /* Got them all, so now open the monitor console */
857
    ret = qemudOpenMonitor(conn, driver, vm, monitor, 0);
858 859 860 861

cleanup:
    VIR_FREE(monitor);
    return ret;
862 863
}

864
static int qemudWaitForMonitor(virConnectPtr conn,
865 866 867
                               struct qemud_driver* driver,
                               virDomainObjPtr vm, off_t pos)
{
868
    char buf[1024]; /* Plenty of space to get startup greeting */
869 870 871 872 873
    int logfd;
    int ret;

    if ((logfd = qemudLogReadFD(conn, driver->logDir, vm->def->name, pos))
        < 0)
874
        return -1;
875 876 877 878 879 880

    ret = qemudReadMonitorOutput(conn, vm, logfd, buf, sizeof(buf),
                                 qemudFindCharDevicePTYs,
                                 "console", 3000);
    if (close(logfd) < 0)
        qemudLog(QEMUD_WARN, _("Unable to close logfile: %s\n"),
881
                 strerror(errno));
882 883 884 885 886 887 888 889 890 891 892

    if (ret == 1) /* Success */
        return 0;

    if (ret == -1)
        return -1;

    /* Unexpected end of file - inform user of QEMU log data */
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                     _("unable to start guest: %s"), buf);
    return -1;
893 894
}

895 896
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
897
                    virDomainObjPtr vm) {
898 899 900 901 902 903
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
904
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
905 906 907 908 909
        vm->nvcpupids = 1;
    else
        vm->nvcpupids = vm->def->vcpus;

    if (VIR_ALLOC_N(vm->vcpupids, vm->nvcpupids) < 0) {
910
        virReportOOMError(conn);
911 912 913
        return -1;
    }

914
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
915 916 917 918
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

919
    if (qemudMonitorCommand(vm, "info cpus", &qemucpus) < 0) {
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 967 968 969 970 971 972 973 974 975 976 977
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot run monitor command to fetch CPU thread info"));
        VIR_FREE(vm->vcpupids);
        vm->nvcpupids = 0;
        return -1;
    }

    /*
     * This is the gross format we're about to parse :-{
     *
     * (qemu) info cpus
     * * CPU #0: pc=0x00000000000f0c4a thread_id=30019
     *   CPU #1: pc=0x00000000fffffff0 thread_id=30020
     *   CPU #2: pc=0x00000000fffffff0 thread_id=30021
     *
     */
    line = qemucpus;
    do {
        char *offset = strchr(line, '#');
        char *end = NULL;
        int vcpu = 0, tid = 0;

        /* See if we're all done */
        if (offset == NULL)
            break;

        /* Extract VCPU number */
        if (virStrToLong_i(offset + 1, &end, 10, &vcpu) < 0)
            goto error;
        if (end == NULL || *end != ':')
            goto error;

        /* Extract host Thread ID */
        if ((offset = strstr(line, "thread_id=")) == NULL)
            goto error;
        if (virStrToLong_i(offset + strlen("thread_id="), &end, 10, &tid) < 0)
            goto error;
        if (end == NULL || !c_isspace(*end))
            goto error;

        /* Validate the VCPU is in expected range & order */
        if (vcpu > vm->nvcpupids ||
            vcpu != (lastVcpu + 1))
            goto error;

        lastVcpu = vcpu;
        vm->vcpupids[vcpu] = tid;

        /* Skip to next data line */
        line = strchr(offset, '\r');
        if (line == NULL)
            line = strchr(offset, '\n');
    } while (line != NULL);

    /* Validate we got data for all VCPUs we expected */
    if (lastVcpu != (vm->def->vcpus - 1))
        goto error;

978
    VIR_FREE(qemucpus);
979 980 981 982
    return 0;

error:
    VIR_FREE(vm->vcpupids);
983 984
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
985 986 987 988 989 990 991 992

    /* Explicitly return success, not error. Older KVM does
       not have vCPU -> Thread mapping info and we don't
       want to break its use. This merely disables ability
       to pin vCPUS with libvirt */
    return 0;
}

993 994
static int
qemudInitCpus(virConnectPtr conn,
D
Daniel Veillard 已提交
995 996
              virDomainObjPtr vm,
              const char *migrateFrom) {
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    char *info = NULL;
#if HAVE_SCHED_GETAFFINITY
    cpu_set_t mask;
    int i, maxcpu = QEMUD_CPUMASK_LEN;
    virNodeInfo nodeinfo;

    if (virNodeInfoPopulate(conn, &nodeinfo) < 0)
        return -1;

    /* setaffinity fails if you set bits for CPUs which
     * aren't present, so we have to limit ourselves */
    if (maxcpu > nodeinfo.cpus)
        maxcpu = nodeinfo.cpus;

    CPU_ZERO(&mask);
D
Daniel P. Berrange 已提交
1012 1013 1014 1015 1016 1017
    if (vm->def->cpumask) {
        for (i = 0 ; i < maxcpu ; i++)
            if (vm->def->cpumask[i])
                CPU_SET(i, &mask);
    } else {
        for (i = 0 ; i < maxcpu ; i++)
1018
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
1019
    }
1020 1021 1022 1023

    for (i = 0 ; i < vm->nvcpupids ; i++) {
        if (sched_setaffinity(vm->vcpupids[i],
                              sizeof(mask), &mask) < 0) {
1024 1025
            virReportSystemError(conn, errno, "%s",
                                 _("failed to set CPU affinity"));
1026 1027 1028 1029 1030
            return -1;
        }
    }
#endif /* HAVE_SCHED_GETAFFINITY */

D
Daniel Veillard 已提交
1031 1032
    if (migrateFrom == NULL) {
        /* Allow the CPUS to start executing */
1033
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
D
Daniel Veillard 已提交
1034 1035 1036 1037 1038
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("resume operation failed"));
            return -1;
        }
        VIR_FREE(info);
1039 1040 1041 1042 1043 1044
    }

    return 0;
}


1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
static int
qemudInitPasswords(virConnectPtr conn,
                   struct qemud_driver *driver,
                   virDomainObjPtr vm) {
    char *info = NULL;

    /*
     * NB: Might have more passwords to set in the future. eg a qcow
     * disk decryption password, but there's no monitor command
     * for that yet...
     */

    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
1059
        (vm->def->graphics->data.vnc.passwd || driver->vncPassword)) {
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077

        if (qemudMonitorCommandExtra(vm, "change vnc password",
                                     vm->def->graphics->data.vnc.passwd ?
                                     vm->def->graphics->data.vnc.passwd :
                                     driver->vncPassword,
                                     QEMU_PASSWD_PROMPT,
                                     &info) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("setting VNC password failed"));
            return -1;
        }
        VIR_FREE(info);
    }

    return 0;
}


1078
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    int i;

    for (i = 5900 ; i < 6000 ; i++) {
        int fd;
        int reuse = 1;
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_port = htons(i);
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
        fd = socket(PF_INET, SOCK_STREAM, 0);
        if (fd < 0)
            return -1;

        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&reuse, sizeof(reuse)) < 0) {
            close(fd);
            break;
        }

        if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
            /* Not in use, lets grab it */
            close(fd);
            return i;
        }
        close(fd);

        if (errno == EADDRINUSE) {
            /* In use, try next */
            continue;
        }
        /* Some other bad failure, get out.. */
        break;
    }
    return -1;
}

1114 1115 1116
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

1117 1118
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
1119
                              virDomainObjPtr vm,
1120 1121
                              const char *migrateFrom,
                              int stdin_fd) {
1122
    const char **argv = NULL, **tmp;
1123
    const char **progenv = NULL;
1124
    int i, ret;
1125
    struct stat sb;
1126 1127
    int *tapfds = NULL;
    int ntapfds = 0;
1128
    unsigned int qemuCmdFlags;
1129
    fd_set keepfd;
1130
    const char *emulator;
G
Guido Günther 已提交
1131
    pid_t child;
1132
    int pos = -1;
1133 1134

    FD_ZERO(&keepfd);
1135

1136
    if (virDomainIsActive(vm)) {
1137
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1138
                         "%s", _("VM is already active"));
1139 1140 1141
        return -1;
    }

1142 1143 1144
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
1145
        int port = qemudNextFreeVNCPort(driver);
1146
        if (port < 0) {
1147
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1148
                             "%s", _("Unable to find an unused VNC port"));
1149 1150
            return -1;
        }
1151 1152
        vm->def->graphics->data.vnc.port = port;
    }
1153

1154
    if (virFileMakePath(driver->logDir) < 0) {
1155 1156 1157
        virReportSystemError(conn, errno,
                             _("cannot create log directory %s"),
                             driver->logDir);
1158 1159 1160
        return -1;
    }

1161
    if((vm->logfile = qemudLogFD(conn, driver->logDir, vm->def->name)) < 0)
1162 1163
        return -1;

1164 1165 1166 1167 1168 1169
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

1170 1171 1172 1173
    /* Make sure the binary we are about to try exec'ing exists.
     * Technically we could catch the exec() failure, but that's
     * in a sub-process so its hard to feed back a useful error
     */
1174
    if (stat(emulator, &sb) < 0) {
1175 1176 1177
        virReportSystemError(conn, errno,
                             _("Cannot find QEMU binary %s"),
                             emulator);
1178 1179 1180
        return -1;
    }

1181
    if (qemudExtractVersionInfo(emulator,
1182 1183 1184 1185
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
1186
                         emulator);
1187 1188
        return -1;
    }
1189

1190
    vm->def->id = driver->nextvmid++;
1191
    if (qemudBuildCommandLine(conn, driver, vm,
1192
                              qemuCmdFlags, &argv, &progenv,
1193
                              &tapfds, &ntapfds, migrateFrom) < 0) {
1194
        close(vm->logfile);
1195
        vm->def->id = -1;
1196 1197 1198 1199
        vm->logfile = -1;
        return -1;
    }

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
    tmp = progenv;
    while (*tmp) {
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
            qemudLog(QEMUD_WARN, _("Unable to write envv to logfile %d: %s\n"),
                     errno, strerror(errno));
        if (safewrite(vm->logfile, " ", 1) < 0)
            qemudLog(QEMUD_WARN, _("Unable to write envv to logfile %d: %s\n"),
                     errno, strerror(errno));
        tmp++;
    }
1210 1211
    tmp = argv;
    while (*tmp) {
1212
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
1213
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1214
                     errno, strerror(errno));
1215
        if (safewrite(vm->logfile, " ", 1) < 0)
1216
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1217 1218 1219
                     errno, strerror(errno));
        tmp++;
    }
1220
    if (safewrite(vm->logfile, "\n", 1) < 0)
1221
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1222 1223
                 errno, strerror(errno));

1224 1225 1226
    if ((pos = lseek(vm->logfile, 0, SEEK_END)) < 0)
        qemudLog(QEMUD_WARN, _("Unable to seek to end of logfile %d: %s\n"),
                 errno, strerror(errno));
1227

1228 1229 1230
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

G
Guido Günther 已提交
1231
    ret = virExec(conn, argv, progenv, &keepfd, &child,
1232
                  stdin_fd, &vm->logfile, &vm->logfile,
G
Guido Günther 已提交
1233 1234 1235 1236 1237
                  VIR_EXEC_NONBLOCK | VIR_EXEC_DAEMON);

    /* wait for qemu process to to show up */
    if (ret == 0) {
        int retries = 100;
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        int childstat;

        while (waitpid(child, &childstat, 0) == -1 &&
               errno == EINTR);

        if (childstat == 0) {
            while (retries) {
                if ((ret = virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) == 0)
                    break;
                usleep(100*1000);
                retries--;
            }
            if (ret)
                qemudLog(QEMUD_WARN, _("Domain %s didn't show up\n"), vm->def->name);
        } else {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Unable to daemonize QEMU process"));
            ret = -1;
G
Guido Günther 已提交
1256 1257 1258 1259
        }
    }

    if (ret == 0) {
1260
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
G
Guido Günther 已提交
1261
    } else
1262
        vm->def->id = -1;
1263

1264
    for (i = 0 ; argv[i] ; i++)
1265 1266
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
1267

1268 1269 1270 1271
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

1272 1273 1274
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
1275
        }
1276
        VIR_FREE(tapfds);
1277 1278
    }

1279
    if (ret == 0) {
1280
        if ((qemudWaitForMonitor(conn, driver, vm, pos) < 0) ||
1281
            (qemudDetectVcpuPIDs(conn, vm) < 0) ||
1282 1283
            (qemudInitCpus(conn, vm, migrateFrom) < 0) ||
            (qemudInitPasswords(conn, driver, vm) < 0)) {
1284 1285 1286
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
1287
    }
1288
    qemudSaveDomainStatus(conn, qemu_driver, vm);
1289

1290
    return ret;
1291 1292 1293
}


1294
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
1295 1296
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
1297
        return;
1298

1299
    qemudLog(QEMUD_DEBUG, _("Shutting down VM '%s'\n"), vm->def->name);
1300

G
Guido Günther 已提交
1301 1302 1303 1304
    if (virKillProcess(vm->pid, 0) == 0 &&
        virKillProcess(vm->pid, SIGTERM) < 0)
        qemudLog(QEMUD_ERROR, _("Failed to send SIGTERM to %s (%d): %s\n"),
                 vm->def->name, vm->pid, strerror(errno));
1305

1306 1307 1308 1309
    if (vm->monitor_watch != -1) {
        virEventRemoveHandle(vm->monitor_watch);
        vm->monitor_watch = -1;
    }
1310 1311

    if (close(vm->logfile) < 0)
1312
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
1313
                 errno, strerror(errno));
1314 1315 1316 1317 1318
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
    vm->monitor = -1;

G
Guido Günther 已提交
1319 1320
    /* shut it off for sure */
    virKillProcess(vm->pid, SIGKILL);
1321

G
Guido Günther 已提交
1322
    qemudRemoveDomainStatus(conn, driver, vm);
1323
    vm->pid = -1;
1324
    vm->def->id = -1;
1325
    vm->state = VIR_DOMAIN_SHUTOFF;
1326
    VIR_FREE(vm->vcpupids);
1327
    vm->nvcpupids = 0;
1328 1329

    if (vm->newDef) {
1330
        virDomainDefFree(vm->def);
1331
        vm->def = vm->newDef;
1332
        vm->def->id = -1;
1333 1334 1335 1336 1337
        vm->newDef = NULL;
    }
}


1338
static void
1339
qemudDispatchVMEvent(int watch, int fd, int events, void *opaque) {
1340
    struct qemud_driver *driver = opaque;
1341
    virDomainObjPtr vm = NULL;
1342
    virDomainEventPtr event = NULL;
1343
    unsigned int i;
1344
    int quit = 0, failed = 0;
1345

1346
    qemuDriverLock(driver);
1347
    for (i = 0 ; i < driver->domains.count ; i++) {
1348 1349 1350
        virDomainObjPtr tmpvm = driver->domains.objs[i];
        virDomainObjLock(tmpvm);
        if (virDomainIsActive(tmpvm) &&
1351
            tmpvm->monitor_watch == watch) {
1352
            vm = tmpvm;
1353
            break;
1354
        }
1355
        virDomainObjUnlock(tmpvm);
1356 1357 1358
    }

    if (!vm)
1359
        goto cleanup;
1360

1361
    if (vm->monitor != fd) {
1362 1363
        failed = 1;
    } else {
1364
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
1365
            quit = 1;
1366 1367 1368 1369
        else {
            qemudLog(QEMUD_ERROR, _("unhandled fd event %d for %s"),
                                    events, vm->def->name);
            failed = 1;
1370
        }
1371 1372
    }

1373
    if (failed || quit) {
1374 1375 1376 1377 1378
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         quit ?
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN :
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
        qemudShutdownVMDaemon(NULL, driver, vm);
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains,
                                    vm);
            vm = NULL;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1390 1391
    if (event)
        qemuDomainEventQueue(driver, event);
1392
    qemuDriverUnlock(driver);
1393 1394
}

1395
static int
1396 1397 1398 1399 1400
qemudMonitorCommandExtra(const virDomainObjPtr vm,
                         const char *cmd,
                         const char *extra,
                         const char *extraPrompt,
                         char **reply) {
D
Daniel P. Berrange 已提交
1401 1402
    int size = 0;
    char *buf = NULL;
1403
    size_t cmdlen = strlen(cmd);
1404
    size_t extralen = extra ? strlen(extra) : 0;
D
Daniel P. Berrange 已提交
1405

1406 1407 1408
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420
        return -1;

    *reply = NULL;

    for (;;) {
        struct pollfd fd = { vm->monitor, POLLIN | POLLERR | POLLHUP, 0 };
        char *tmp;

        /* Read all the data QEMU has sent thus far */
        for (;;) {
            char data[1024];
            int got = read(vm->monitor, data, sizeof(data));
D
Daniel P. Berrange 已提交
1421

1422 1423
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1424 1425 1426 1427 1428
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1429
                goto error;
1430
            }
1431
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1432 1433
                goto error;

D
Daniel P. Berrange 已提交
1434 1435 1436 1437
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1438

D
Daniel P. Berrange 已提交
1439
        /* Look for QEMU prompt to indicate completion */
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464
        if (buf) {
            if (extra) {
                if (strstr(buf, extraPrompt) != NULL) {
                    if (safewrite(vm->monitor, extra, extralen) != extralen)
                        return -1;
                    if (safewrite(vm->monitor, "\r", 1) != 1)
                        return -1;
                    extra = NULL;
                }
            } else if ((tmp = strstr(buf, QEMU_CMD_PROMPT)) != NULL) {
                char *commptr = NULL, *nlptr = NULL;
                /* Preserve the newline */
                tmp[1] = '\0';

                /* The monitor doesn't dump clean output after we have written to
                 * it. Every character we write dumps a bunch of useless stuff,
                 * so the result looks like "cXcoXcomXcommXcommaXcommanXcommand"
                 * Try to throw away everything before the first full command
                 * occurence, and inbetween the command and the newline starting
                 * the response
                 */
                if ((commptr = strstr(buf, cmd)))
                    memmove(buf, commptr, strlen(commptr)+1);
                if ((nlptr = strchr(buf, '\n')))
                    memmove(buf+strlen(cmd), nlptr, strlen(nlptr)+1);
C
Cole Robinson 已提交
1465

1466 1467
                break;
            }
D
Daniel P. Berrange 已提交
1468 1469 1470 1471 1472 1473
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1474
            goto error;
D
Daniel P. Berrange 已提交
1475 1476 1477
        }
    }

1478 1479
    /* Log, but ignore failures to write logfile for VM */
    if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1480
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1481 1482
                 strerror(errno));

D
Daniel P. Berrange 已提交
1483 1484
    *reply = buf;
    return 0;
1485 1486 1487 1488 1489

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1490
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1491
                     strerror(errno));
1492
        VIR_FREE(buf);
1493 1494
    }
    return -1;
D
Daniel P. Berrange 已提交
1495 1496
}

1497 1498 1499 1500 1501 1502 1503 1504
static int
qemudMonitorCommand(const virDomainObjPtr vm,
                    const char *cmd,
                    char **reply) {
    return qemudMonitorCommandExtra(vm, cmd, NULL, NULL, reply);
}


1505 1506 1507 1508 1509 1510
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
1511
static int qemudProbe(void)
1512 1513 1514
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
G
Guido Günther 已提交
1515
        (virFileExists("/usr/bin/kvm")) ||
1516 1517 1518 1519
        (virFileExists("/usr/bin/xenner")))
        return 1;

    return 0;
1520
}
1521

1522
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1523
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1524
                                  int flags ATTRIBUTE_UNUSED) {
1525 1526 1527
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1528
        goto decline;
1529

1530 1531 1532 1533 1534 1535
    if (!qemudProbe())
        goto decline;

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "qemu:///session" : "qemu:///system");
        if (!conn->uri) {
1536
            virReportOOMError(conn);
1537 1538 1539 1540
            return VIR_DRV_OPEN_ERROR;
        }
    } else if (conn->uri->scheme == NULL ||
               conn->uri->path == NULL)
1541 1542
        goto decline;

1543
    if (STRNEQ (conn->uri->scheme, "qemu"))
1544 1545
        goto decline;

1546
    if (uid != 0) {
1547
        if (STRNEQ (conn->uri->path, "/session"))
1548
            goto decline;
1549
    } else { /* root */
1550 1551
        if (STRNEQ (conn->uri->path, "/system") &&
            STRNEQ (conn->uri->path, "/session"))
1552
            goto decline;
1553 1554 1555 1556 1557
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1558 1559

 decline:
1560
    return VIR_DRV_OPEN_DECLINED;
1561 1562 1563
}

static int qemudClose(virConnectPtr conn) {
1564
    struct qemud_driver *driver = conn->privateData;
1565 1566 1567

    /* Get rid of callbacks registered for this conn */
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
1568 1569 1570 1571 1572 1573

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
    case VIR_DRV_FEATURE_MIGRATION_V2: return 1;
    default: return 0;
    }
}

1584
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1585
    return "QEMU";
1586 1587
}

1588 1589 1590 1591 1592

static int kvmGetMaxVCPUs(void) {
    int maxvcpus = 1;

    int r, fd;
1593

1594 1595
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1596
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608
        return maxvcpus;
    }

    r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS);
    if (r > 0)
        maxvcpus = r;

    close(fd);
    return maxvcpus;
}


1609
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1610 1611 1612
    if (!type)
        return 16;

1613
    if (STRCASEEQ(type, "qemu"))
1614 1615
        return 16;

1616
    if (STRCASEEQ(type, "kvm"))
1617
        return kvmGetMaxVCPUs();
1618

1619
    if (STRCASEEQ(type, "kqemu"))
1620
        return 1;
1621 1622 1623

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1624 1625 1626
    return -1;
}

1627 1628 1629
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1630 1631 1632
}


1633
static char *qemudGetCapabilities(virConnectPtr conn) {
1634
    struct qemud_driver *driver = conn->privateData;
1635
    char *xml;
1636

1637
    qemuDriverLock(driver);
1638
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1639
        virReportOOMError(conn);
1640
    qemuDriverUnlock(driver);
1641

1642
    return xml;
1643 1644 1645
}


1646 1647 1648 1649 1650 1651 1652 1653
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
1654
    int ret = -1;
1655 1656 1657 1658

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1659
        goto cleanup;
1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    }
    lastCell = startCell + maxCells - 1;
    if (lastCell > numa_max_node())
        lastCell = numa_max_node();

    for (numCells = 0, n = startCell ; n <= lastCell ; n++) {
        long long mem;
        if (numa_node_size64(n, &mem) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Failed to query NUMA free memory"));
1670
            goto cleanup;
1671 1672 1673
        }
        freeMems[numCells++] = mem;
    }
1674 1675 1676 1677
    ret = numCells;

cleanup:
    return ret;
1678 1679 1680 1681 1682
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
1683
    unsigned long long freeMem = -1;
1684
    int n;
1685

1686 1687 1688
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1689
        goto cleanup;
1690 1691 1692 1693 1694 1695 1696
    }

    for (n = 0 ; n <= numa_max_node() ; n++) {
        long long mem;
        if (numa_node_size64(n, &mem) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("Failed to query NUMA free memory"));
1697
            goto cleanup;
1698 1699 1700 1701
        }
        freeMem += mem;
    }

1702
cleanup:
1703 1704 1705 1706
    return freeMem;
}

#endif
1707

D
Daniel P. Berrange 已提交
1708 1709 1710
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1711
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1712 1713 1714 1715 1716 1717

    if (snprintf(proc, sizeof(proc), "/proc/%d/stat", pid) >= (int)sizeof(proc)) {
        return -1;
    }

    if (!(pidinfo = fopen(proc, "r"))) {
1718
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1719 1720 1721 1722 1723
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1724
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1725
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1726 1727 1728 1729 1730 1731 1732 1733
        return -1;
    }

    /* We got jiffies
     * We want nanoseconds
     * _SC_CLK_TCK is jiffies per second
     * So calulate thus....
     */
1734
    *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
D
Daniel P. Berrange 已提交
1735

1736
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1737 1738 1739 1740 1741 1742 1743

    fclose(pidinfo);

    return 0;
}


1744
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1745
                                          int id) {
1746 1747 1748 1749
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1750
    qemuDriverLock(driver);
1751
    vm  = virDomainFindByID(&driver->domains, id);
1752
    qemuDriverUnlock(driver);
1753 1754

    if (!vm) {
1755
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1756
        goto cleanup;
1757 1758
    }

1759
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1760
    if (dom) dom->id = vm->def->id;
1761 1762

cleanup:
1763 1764
    if (vm)
        virDomainObjUnlock(vm);
1765 1766
    return dom;
}
1767

1768
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1769
                                            const unsigned char *uuid) {
1770 1771 1772
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1773

1774
    qemuDriverLock(driver);
1775
    vm = virDomainFindByUUID(&driver->domains, uuid);
1776 1777
    qemuDriverUnlock(driver);

1778
    if (!vm) {
1779
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1780
        goto cleanup;
1781 1782
    }

1783
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1784
    if (dom) dom->id = vm->def->id;
1785 1786

cleanup:
1787 1788
    if (vm)
        virDomainObjUnlock(vm);
1789 1790
    return dom;
}
1791

1792
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1793
                                            const char *name) {
1794 1795 1796
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1797

1798
    qemuDriverLock(driver);
1799
    vm = virDomainFindByName(&driver->domains, name);
1800 1801
    qemuDriverUnlock(driver);

1802
    if (!vm) {
1803
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1804
        goto cleanup;
1805 1806
    }

1807
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1808
    if (dom) dom->id = vm->def->id;
1809 1810

cleanup:
1811 1812
    if (vm)
        virDomainObjUnlock(vm);
1813 1814 1815
    return dom;
}

1816
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1817 1818 1819
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1820
    qemuDriverLock(driver);
1821
    if (qemudExtractVersion(conn, driver) < 0)
1822
        goto cleanup;
1823

1824
    *version = qemu_driver->qemuVersion;
1825 1826 1827
    ret = 0;

cleanup:
1828
    qemuDriverUnlock(driver);
1829
    return ret;
D
Daniel P. Berrange 已提交
1830 1831
}

1832 1833 1834
static char *
qemudGetHostname (virConnectPtr conn)
{
1835
    char *result;
1836

1837 1838
    result = virGetHostname();
    if (result == NULL) {
1839 1840 1841 1842 1843
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return NULL;
    }
    /* Caller frees this string. */
1844
    return result;
1845 1846
}

1847
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1848
    struct qemud_driver *driver = conn->privateData;
1849 1850
    int got = 0, i;

1851 1852 1853
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1854 1855
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
1856 1857 1858
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1859

D
Daniel P. Berrange 已提交
1860 1861
    return got;
}
1862

1863
static int qemudNumDomains(virConnectPtr conn) {
1864
    struct qemud_driver *driver = conn->privateData;
1865 1866
    int n = 0, i;

1867 1868 1869
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1870
        if (virDomainIsActive(driver->domains.objs[i]))
1871
            n++;
1872 1873 1874
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1875

1876
    return n;
D
Daniel P. Berrange 已提交
1877
}
1878

1879
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1880
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1881
    struct qemud_driver *driver = conn->privateData;
1882
    virDomainDefPtr def;
1883
    virDomainObjPtr vm = NULL;
1884
    virDomainPtr dom = NULL;
1885
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1886

1887
    qemuDriverLock(driver);
1888 1889
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1890
        goto cleanup;
1891

1892
    vm = virDomainFindByName(&driver->domains, def->name);
1893
    if (vm) {
1894
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1895
                         _("domain '%s' is already defined"),
1896
                         def->name);
1897
        goto cleanup;
1898
    }
1899
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1900 1901 1902 1903 1904
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1905
                         _("domain with uuid '%s' is already defined"),
1906
                         uuidstr);
1907
        goto cleanup;
1908
    }
1909

1910 1911
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1912 1913 1914 1915
                                  def)))
        goto cleanup;

    def = NULL;
D
Daniel P. Berrange 已提交
1916

1917
    if (qemudStartVMDaemon(conn, driver, vm, NULL, -1) < 0) {
1918 1919
        virDomainRemoveInactive(&driver->domains,
                                vm);
1920
        vm = NULL;
1921
        goto cleanup;
D
Daniel P. Berrange 已提交
1922
    }
1923 1924 1925 1926

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
D
Daniel P. Berrange 已提交
1927

1928
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1929
    if (dom) dom->id = vm->def->id;
1930 1931 1932

cleanup:
    virDomainDefFree(def);
1933 1934
    if (vm)
        virDomainObjUnlock(vm);
1935 1936
    if (event)
        qemuDomainEventQueue(driver, event);
1937
    qemuDriverUnlock(driver);
1938
    return dom;
D
Daniel P. Berrange 已提交
1939 1940 1941
}


1942
static int qemudDomainSuspend(virDomainPtr dom) {
1943
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1944
    char *info;
1945 1946
    virDomainObjPtr vm;
    int ret = -1;
1947
    virDomainEventPtr event = NULL;
1948

1949
    qemuDriverLock(driver);
1950
    vm = virDomainFindByID(&driver->domains, dom->id);
1951 1952
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1953
    if (!vm) {
1954
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
1955
        goto cleanup;
D
Daniel P. Berrange 已提交
1956
    }
1957
    if (!virDomainIsActive(vm)) {
1958 1959
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1960
        goto cleanup;
D
Daniel P. Berrange 已提交
1961
    }
1962
    if (vm->state != VIR_DOMAIN_PAUSED) {
1963
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
1964 1965 1966 1967 1968 1969
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("suspend operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
1970 1971 1972
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
1973
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1974
    }
1975
    qemudSaveDomainStatus(dom->conn, driver, vm);
1976 1977 1978
    ret = 0;

cleanup:
1979 1980
    if (vm)
        virDomainObjUnlock(vm);
1981 1982 1983 1984 1985 1986

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1987
    return ret;
D
Daniel P. Berrange 已提交
1988 1989 1990
}


1991
static int qemudDomainResume(virDomainPtr dom) {
1992
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1993
    char *info;
1994 1995
    virDomainObjPtr vm;
    int ret = -1;
1996
    virDomainEventPtr event = NULL;
1997

1998
    qemuDriverLock(driver);
1999
    vm = virDomainFindByID(&driver->domains, dom->id);
2000 2001
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
2002
    if (!vm) {
2003 2004
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
2005
        goto cleanup;
D
Daniel P. Berrange 已提交
2006
    }
2007
    if (!virDomainIsActive(vm)) {
2008 2009
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
2010
        goto cleanup;
D
Daniel P. Berrange 已提交
2011
    }
2012
    if (vm->state == VIR_DOMAIN_PAUSED) {
2013
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
2014 2015 2016 2017 2018 2019
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("resume operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;
        qemudDebug("Reply %s", info);
2020 2021 2022
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
2023
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
2024
    }
2025
    qemudSaveDomainStatus(dom->conn, driver, vm);
2026 2027 2028
    ret = 0;

cleanup:
2029 2030
    if (vm)
        virDomainObjUnlock(vm);
2031 2032 2033 2034 2035
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
2036
    return ret;
D
Daniel P. Berrange 已提交
2037 2038 2039
}


2040
static int qemudDomainShutdown(virDomainPtr dom) {
2041 2042
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2043
    char* info;
2044
    int ret = -1;
2045

2046
    qemuDriverLock(driver);
2047
    vm = virDomainFindByID(&driver->domains, dom->id);
2048 2049
    qemuDriverUnlock(driver);

2050 2051
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2052
                         _("no domain with matching id %d"), dom->id);
2053
        goto cleanup;
2054 2055
    }

2056
    if (qemudMonitorCommand(vm, "system_powerdown", &info) < 0) {
2057
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2058
                         "%s", _("shutdown operation failed"));
2059
        goto cleanup;
2060
    }
D
Daniel Veillard 已提交
2061
    VIR_FREE(info);
2062 2063 2064
    ret = 0;

cleanup:
2065 2066
    if (vm)
        virDomainObjUnlock(vm);
2067
    return ret;
2068 2069 2070
}


2071
static int qemudDomainDestroy(virDomainPtr dom) {
2072 2073 2074
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2075
    virDomainEventPtr event = NULL;
2076

2077
    qemuDriverLock(driver);
2078
    vm  = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
2079
    if (!vm) {
2080
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2081
                         _("no domain with matching id %d"), dom->id);
2082
        goto cleanup;
D
Daniel P. Berrange 已提交
2083
    }
2084

2085
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2086 2087 2088
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
2089
    if (!vm->persistent) {
2090 2091
        virDomainRemoveInactive(&driver->domains,
                                vm);
2092 2093
        vm = NULL;
    }
2094 2095 2096
    ret = 0;

cleanup:
2097 2098
    if (vm)
        virDomainObjUnlock(vm);
2099 2100
    if (event)
        qemuDomainEventQueue(driver, event);
2101
    qemuDriverUnlock(driver);
2102
    return ret;
D
Daniel P. Berrange 已提交
2103 2104 2105
}


2106
static char *qemudDomainGetOSType(virDomainPtr dom) {
2107 2108 2109
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
2110

2111
    qemuDriverLock(driver);
2112
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2113
    qemuDriverUnlock(driver);
2114 2115
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2116
                         "%s", _("no domain with matching uuid"));
2117
        goto cleanup;
2118 2119
    }

2120
    if (!(type = strdup(vm->def->os.type)))
2121
        virReportOOMError(dom->conn);
2122 2123

cleanup:
2124 2125
    if (vm)
        virDomainObjUnlock(vm);
2126 2127 2128
    return type;
}

2129 2130
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
2131 2132 2133
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
2134

2135
    qemuDriverLock(driver);
2136
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2137 2138
    qemuDriverUnlock(driver);

2139
    if (!vm) {
2140 2141 2142
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2143
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2144
                         _("no domain with matching uuid '%s'"), uuidstr);
2145
        goto cleanup;
2146 2147
    }

2148 2149 2150
    ret = vm->def->maxmem;

cleanup:
2151 2152
    if (vm)
        virDomainObjUnlock(vm);
2153
    return ret;
2154 2155 2156
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
2157 2158 2159
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2160

2161
    qemuDriverLock(driver);
2162
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2163 2164
    qemuDriverUnlock(driver);

2165
    if (!vm) {
2166 2167 2168
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2169
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2170
                         _("no domain with matching uuid '%s'"), uuidstr);
2171
        goto cleanup;
2172 2173 2174 2175
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2176
                         "%s", _("cannot set max memory lower than current memory"));
2177
        goto cleanup;;
2178 2179 2180
    }

    vm->def->maxmem = newmax;
2181 2182 2183
    ret = 0;

cleanup:
2184 2185
    if (vm)
        virDomainObjUnlock(vm);
2186
    return ret;
2187 2188 2189
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
2190 2191 2192
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2193

2194
    qemuDriverLock(driver);
2195
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2196
    qemuDriverUnlock(driver);
2197
    if (!vm) {
2198 2199 2200
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2201
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2202
                         _("no domain with matching uuid '%s'"), uuidstr);
2203
        goto cleanup;
2204 2205
    }

2206
    if (virDomainIsActive(vm)) {
2207
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
2208
                         "%s", _("cannot set memory of an active domain"));
2209
        goto cleanup;
2210 2211 2212 2213
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2214
                         "%s", _("cannot set memory higher than max memory"));
2215
        goto cleanup;
2216 2217 2218
    }

    vm->def->memory = newmem;
2219 2220 2221
    ret = 0;

cleanup:
2222 2223
    if (vm)
        virDomainObjUnlock(vm);
2224
    return ret;
2225 2226
}

2227
static int qemudDomainGetInfo(virDomainPtr dom,
2228
                              virDomainInfoPtr info) {
2229 2230 2231 2232
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

2233
    qemuDriverLock(driver);
2234
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2235
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2236
    if (!vm) {
2237 2238
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2239
        goto cleanup;
D
Daniel P. Berrange 已提交
2240 2241
    }

2242
    info->state = vm->state;
D
Daniel P. Berrange 已提交
2243

2244
    if (!virDomainIsActive(vm)) {
2245
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2246
    } else {
2247
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
2248
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
2249
            goto cleanup;
D
Daniel P. Berrange 已提交
2250 2251 2252
        }
    }

2253 2254 2255
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
2256 2257 2258
    ret = 0;

cleanup:
2259 2260
    if (vm)
        virDomainObjUnlock(vm);
2261
    return ret;
D
Daniel P. Berrange 已提交
2262 2263 2264
}


D
Daniel P. Berrange 已提交
2265
static char *qemudEscape(const char *in, int shell)
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286
{
    int len = 0;
    int i, j;
    char *out;

    /* To pass through the QEMU monitor, we need to use escape
       sequences: \r, \n, \", \\

       To pass through both QEMU + the shell, we need to escape
       the single character ' as the five characters '\\''
    */

    for (i = 0; in[i] != '\0'; i++) {
        switch(in[i]) {
        case '\r':
        case '\n':
        case '"':
        case '\\':
            len += 2;
            break;
        case '\'':
D
Daniel P. Berrange 已提交
2287 2288 2289 2290
            if (shell)
                len += 5;
            else
                len += 1;
2291 2292 2293 2294 2295 2296 2297
            break;
        default:
            len += 1;
            break;
        }
    }

2298
    if (VIR_ALLOC_N(out, len + 1) < 0)
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
        return NULL;

    for (i = j = 0; in[i] != '\0'; i++) {
        switch(in[i]) {
        case '\r':
            out[j++] = '\\';
            out[j++] = 'r';
            break;
        case '\n':
            out[j++] = '\\';
            out[j++] = 'n';
            break;
        case '"':
        case '\\':
            out[j++] = '\\';
            out[j++] = in[i];
            break;
        case '\'':
D
Daniel P. Berrange 已提交
2317 2318 2319 2320 2321 2322 2323 2324 2325
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

2337 2338 2339 2340 2341
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
2342 2343 2344 2345
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
2346

2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
#define QEMUD_SAVE_VERSION 1

struct qemud_save_header {
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
    int version;
    int xml_len;
    int was_running;
    int unused[16];
};

2358
static int qemudDomainSave(virDomainPtr dom,
2359
                           const char *path) {
2360 2361 2362 2363 2364 2365 2366
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *command = NULL;
    char *info = NULL;
    int fd = -1;
    char *safe_path = NULL;
    char *xml = NULL;
2367
    struct qemud_save_header header;
2368
    int ret = -1;
2369
    virDomainEventPtr event = NULL;
2370 2371 2372 2373 2374

    memset(&header, 0, sizeof(header));
    memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
    header.version = QEMUD_SAVE_VERSION;

2375
    qemuDriverLock(driver);
2376 2377
    vm = virDomainFindByID(&driver->domains, dom->id);

D
Daniel P. Berrange 已提交
2378
    if (!vm) {
2379
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2380
                         _("no domain with matching id %d"), dom->id);
2381
        goto cleanup;
D
Daniel P. Berrange 已提交
2382
    }
2383

2384
    if (!virDomainIsActive(vm)) {
2385
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2386
                         "%s", _("domain is not running"));
2387
        goto cleanup;
D
Daniel P. Berrange 已提交
2388
    }
2389 2390 2391 2392

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
2393
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
2394
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2395
                             "%s", _("suspend operation failed"));
2396
            goto cleanup;
2397
        }
2398 2399 2400
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
        VIR_FREE(info);
2401 2402 2403
    }

    /* Get XML for the domain */
2404
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2405 2406
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2407
                         "%s", _("failed to get domain xml"));
2408
        goto cleanup;
2409 2410 2411 2412 2413 2414
    }
    header.xml_len = strlen(xml) + 1;

    /* Write header to file, followed by XML */
    if ((fd = open(path, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2415
                         _("failed to create '%s'"), path);
2416
        goto cleanup;
2417 2418 2419 2420
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2421
                         "%s", _("failed to write save header"));
2422
        goto cleanup;
2423 2424 2425 2426
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2427
                         "%s", _("failed to write xml"));
2428
        goto cleanup;
2429 2430
    }

2431
    if (close(fd) < 0) {
2432 2433 2434
        virReportSystemError(dom->conn, errno,
                             _("unable to save file %s"),
                             path);
2435 2436 2437
        goto cleanup;
    }
    fd = -1;
2438 2439 2440 2441 2442

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2443
                         "%s", _("out of memory"));
2444
        goto cleanup;
2445
    }
2446
    if (virAsprintf(&command, "migrate \"exec:"
2447
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
2448
                  "\"", safe_path) == -1) {
2449
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2450
                         "%s", _("out of memory"));
2451 2452
        command = NULL;
        goto cleanup;
2453 2454
    }

2455
    if (qemudMonitorCommand(vm, command, &info) < 0) {
2456
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2457
                         "%s", _("migrate operation failed"));
2458
        goto cleanup;
2459 2460
    }

2461 2462 2463 2464 2465 2466 2467 2468
    DEBUG ("migrate reply: %s", info);

    /* If the command isn't supported then qemu prints:
     * unknown command: migrate" */
    if (strstr(info, "unknown command:")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'migrate' not supported by this qemu"));
2469
        goto cleanup;
2470 2471
    }

2472 2473
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2474 2475 2476
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2477
    if (!vm->persistent) {
2478 2479
        virDomainRemoveInactive(&driver->domains,
                                vm);
2480 2481
        vm = NULL;
    }
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492
    ret = 0;

cleanup:
    if (fd != -1)
        close(fd);
    VIR_FREE(xml);
    VIR_FREE(safe_path);
    VIR_FREE(command);
    VIR_FREE(info);
    if (ret != 0)
        unlink(path);
2493 2494
    if (vm)
        virDomainObjUnlock(vm);
2495 2496
    if (event)
        qemuDomainEventQueue(driver, event);
2497
    qemuDriverUnlock(driver);
2498
    return ret;
D
Daniel P. Berrange 已提交
2499 2500 2501
}


2502
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
2503 2504
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2505
    int max;
2506
    int ret = -1;
2507

2508
    qemuDriverLock(driver);
2509
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2510 2511
    qemuDriverUnlock(driver);

2512
    if (!vm) {
2513 2514 2515
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2516
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2517
                         _("no domain with matching uuid '%s'"), uuidstr);
2518
        goto cleanup;
2519 2520
    }

2521
    if (virDomainIsActive(vm)) {
2522
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
2523
                         _("cannot change vcpu count of an active domain"));
2524
        goto cleanup;
2525 2526 2527 2528 2529
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
2530
        goto cleanup;
2531 2532 2533 2534 2535 2536
    }

    if (nvcpus > max) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("requested vcpus is greater than max allowable"
                           " vcpus for the domain: %d > %d"), nvcpus, max);
2537
        goto cleanup;
2538 2539 2540
    }

    vm->def->vcpus = nvcpus;
2541 2542 2543
    ret = 0;

cleanup:
2544 2545
    if (vm)
        virDomainObjUnlock(vm);
2546
    return ret;
2547 2548
}

2549 2550 2551 2552 2553 2554 2555

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2556 2557
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2558 2559 2560
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;
2561
    int ret = -1;
2562

2563
    qemuDriverLock(driver);
2564
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2565 2566
    qemuDriverUnlock(driver);

2567
    if (!virDomainIsActive(vm)) {
2568 2569
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2570
        goto cleanup;
2571 2572 2573 2574 2575 2576
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
2577
        goto cleanup;
2578 2579 2580
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2581
        goto cleanup;
2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594

    maxcpu = maplen * 8;
    if (maxcpu > nodeinfo.cpus)
        maxcpu = nodeinfo.cpus;

    CPU_ZERO(&mask);
    for (i = 0 ; i < maxcpu ; i++) {
        if ((cpumap[i/8] >> (i % 8)) & 1)
            CPU_SET(i, &mask);
    }

    if (vm->vcpupids != NULL) {
        if (sched_setaffinity(vm->vcpupids[vcpu], sizeof(mask), &mask) < 0) {
2595 2596
            virReportSystemError(dom->conn, errno, "%s",
                                 _("cannot set affinity"));
2597
            goto cleanup;
2598 2599 2600 2601
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2602
        goto cleanup;
2603
    }
2604
    ret = 0;
2605

2606
cleanup:
2607 2608
    if (vm)
        virDomainObjUnlock(vm);
2609
    return ret;
2610 2611 2612 2613 2614 2615 2616 2617
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2618 2619
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2620 2621
    virNodeInfo nodeinfo;
    int i, v, maxcpu;
2622
    int ret = -1;
2623

2624
    qemuDriverLock(driver);
2625
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2626 2627
    qemuDriverUnlock(driver);

2628
    if (!virDomainIsActive(vm)) {
2629 2630
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2631
        goto cleanup;
2632 2633 2634
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2635
        goto cleanup;
2636 2637 2638 2639 2640 2641 2642 2643 2644

    maxcpu = maplen * 8;
    if (maxcpu > nodeinfo.cpus)
        maxcpu = nodeinfo.cpus;

    /* Clamp to actual number of vcpus */
    if (maxinfo > vm->nvcpupids)
        maxinfo = vm->nvcpupids;

2645 2646 2647 2648 2649 2650 2651 2652
    if (maxinfo >= 1) {
        if (info != NULL) {
            memset(info, 0, sizeof(*info) * maxinfo);
            for (i = 0 ; i < maxinfo ; i++) {
                info[i].number = i;
                info[i].state = VIR_VCPU_RUNNING;
                /* XXX cpu time, current pCPU mapping */
            }
2653 2654
        }

2655 2656 2657 2658 2659 2660 2661 2662 2663
        if (cpumaps != NULL) {
            memset(cpumaps, 0, maplen * maxinfo);
            if (vm->vcpupids != NULL) {
                for (v = 0 ; v < maxinfo ; v++) {
                    cpu_set_t mask;
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);
                    CPU_ZERO(&mask);

                    if (sched_getaffinity(vm->vcpupids[v], sizeof(mask), &mask) < 0) {
2664 2665
                        virReportSystemError(dom->conn, errno, "%s",
                                             _("cannot get affinity"));
2666 2667 2668 2669 2670 2671
                        goto cleanup;
                    }

                    for (i = 0 ; i < maxcpu ; i++)
                        if (CPU_ISSET(i, &mask))
                            VIR_USE_CPU(cpumap, i);
2672
                }
2673 2674 2675 2676
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
2677 2678 2679
            }
        }
    }
2680
    ret = maxinfo;
2681

2682
cleanup:
2683 2684
    if (vm)
        virDomainObjUnlock(vm);
2685
    return ret;
2686 2687 2688 2689
}
#endif /* HAVE_SCHED_GETAFFINITY */


2690
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
2691 2692
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2693
    const char *type;
2694
    int ret = -1;
2695

2696
    qemuDriverLock(driver);
2697
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2698 2699
    qemuDriverUnlock(driver);

2700
    if (!vm) {
2701 2702 2703
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2704
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2705
                         _("no domain with matching uuid '%s'"), uuidstr);
2706
        goto cleanup;
2707 2708
    }

2709
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2710 2711 2712
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
2713
        goto cleanup;
2714 2715
    }

2716
    ret = qemudGetMaxVCPUs(dom->conn, type);
2717

2718
cleanup:
2719 2720
    if (vm)
        virDomainObjUnlock(vm);
2721 2722 2723 2724
    return ret;
}


2725
static int qemudDomainRestore(virConnectPtr conn,
2726 2727 2728
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
2729
    virDomainObjPtr vm = NULL;
2730 2731 2732
    int fd = -1;
    int ret = -1;
    char *xml = NULL;
2733
    struct qemud_save_header header;
2734
    virDomainEventPtr event = NULL;
2735

2736
    qemuDriverLock(driver);
2737 2738 2739
    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2740
                         "%s", _("cannot read domain image"));
2741
        goto cleanup;
2742 2743 2744 2745
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2746
                         "%s", _("failed to read qemu header"));
2747
        goto cleanup;
2748 2749 2750 2751
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2752
                         "%s", _("image magic is incorrect"));
2753
        goto cleanup;
2754 2755 2756 2757
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2758
                         _("image version is not supported (%d > %d)"),
2759
                         header.version, QEMUD_SAVE_VERSION);
2760
        goto cleanup;
2761 2762
    }

2763
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2764
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2765
                         "%s", _("out of memory"));
2766
        goto cleanup;
2767 2768 2769 2770
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2771
                         "%s", _("failed to read XML"));
2772
        goto cleanup;
2773 2774 2775
    }

    /* Create a domain from this XML */
2776 2777
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
2778
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2779
                         "%s", _("failed to parse XML"));
2780
        goto cleanup;
2781 2782 2783
    }

    /* Ensure the name and UUID don't already exist in an active VM */
2784
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2785
    if (!vm)
2786
        vm = virDomainFindByName(&driver->domains, def->name);
2787 2788 2789 2790 2791 2792 2793 2794
    if (vm) {
        if (virDomainIsActive(vm)) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain is already active as '%s'"), vm->def->name);
            goto cleanup;
        } else {
            virDomainObjUnlock(vm);
        }
2795 2796
    }

2797 2798 2799
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2800
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2801
                         "%s", _("failed to assign new VM"));
2802
        goto cleanup;
2803
    }
2804
    def = NULL;
2805 2806

    /* Set the migration source and start it up. */
2807
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio", fd);
2808
    close(fd);
2809
    fd = -1;
2810
    if (ret < 0) {
2811
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2812
                         "%s", _("failed to start VM"));
2813
        if (!vm->persistent) {
2814 2815
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2816 2817
            vm = NULL;
        }
2818
        goto cleanup;
2819 2820
    }

2821 2822 2823
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
2824

2825 2826 2827
    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2828
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
2829
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2830
                             "%s", _("failed to resume domain"));
2831
            goto cleanup;
2832
        }
2833
        VIR_FREE(info);
2834 2835
        vm->state = VIR_DOMAIN_RUNNING;
    }
2836
    ret = 0;
2837

2838 2839 2840 2841 2842
cleanup:
    virDomainDefFree(def);
    VIR_FREE(xml);
    if (fd != -1)
        close(fd);
2843 2844
    if (vm)
        virDomainObjUnlock(vm);
2845 2846
    if (event)
        qemuDomainEventQueue(driver, event);
2847
    qemuDriverUnlock(driver);
2848
    return ret;
D
Daniel P. Berrange 已提交
2849 2850 2851
}


2852
static char *qemudDomainDumpXML(virDomainPtr dom,
2853
                                int flags ATTRIBUTE_UNUSED) {
2854 2855 2856 2857
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2858
    qemuDriverLock(driver);
2859
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2860 2861
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
2862
    if (!vm) {
2863 2864
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2865
        goto cleanup;
D
Daniel P. Berrange 已提交
2866 2867
    }

2868 2869 2870 2871 2872 2873
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
2874 2875
    if (vm)
        virDomainObjUnlock(vm);
2876
    return ret;
D
Daniel P. Berrange 已提交
2877 2878 2879
}


2880
static int qemudListDefinedDomains(virConnectPtr conn,
2881
                            char **const names, int nnames) {
2882
    struct qemud_driver *driver = conn->privateData;
2883
    int got = 0, i;
2884

2885
    qemuDriverLock(driver);
2886
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
2887
        virDomainObjLock(driver->domains.objs[i]);
2888 2889
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2890
                virReportOOMError(conn);
2891
                virDomainObjUnlock(driver->domains.objs[i]);
2892 2893
                goto cleanup;
            }
2894
        }
2895
        virDomainObjUnlock(driver->domains.objs[i]);
D
Daniel P. Berrange 已提交
2896
    }
2897

2898
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2899
    return got;
2900 2901 2902

 cleanup:
    for (i = 0 ; i < got ; i++)
2903
        VIR_FREE(names[i]);
2904
    qemuDriverUnlock(driver);
2905
    return -1;
D
Daniel P. Berrange 已提交
2906 2907
}

2908
static int qemudNumDefinedDomains(virConnectPtr conn) {
2909
    struct qemud_driver *driver = conn->privateData;
2910 2911
    int n = 0, i;

2912
    qemuDriverLock(driver);
2913 2914
    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2915
            n++;
2916
    qemuDriverUnlock(driver);
2917

2918
    return n;
D
Daniel P. Berrange 已提交
2919 2920 2921
}


2922
static int qemudDomainStart(virDomainPtr dom) {
2923 2924 2925
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2926
    virDomainEventPtr event = NULL;
2927

2928
    qemuDriverLock(driver);
2929
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2930 2931
    qemuDriverUnlock(driver);

2932
    if (!vm) {
2933
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2934
                         "%s", _("no domain with matching uuid"));
2935
        goto cleanup;
2936 2937
    }

2938
    ret = qemudStartVMDaemon(dom->conn, driver, vm, NULL, -1);
2939
    if (ret != -1)
2940 2941 2942
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
2943 2944

cleanup:
2945 2946
    if (vm)
        virDomainObjUnlock(vm);
2947 2948 2949 2950 2951
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
2952
    return ret;
D
Daniel P. Berrange 已提交
2953 2954 2955
}


2956
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2957
    struct qemud_driver *driver = conn->privateData;
2958
    virDomainDefPtr def;
2959
    virDomainObjPtr vm = NULL;
2960
    virDomainPtr dom = NULL;
2961
    virDomainEventPtr event = NULL;
2962
    int newVM = 1;
2963

2964
    qemuDriverLock(driver);
2965 2966
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
2967
        goto cleanup;
2968

2969
    vm = virDomainFindByName(&driver->domains, def->name);
2970 2971
    if (vm) {
        virDomainObjUnlock(vm);
2972
        newVM = 0;
2973
    }
2974

2975 2976 2977 2978
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2979
        goto cleanup;
2980
    }
2981
    vm->persistent = 1;
2982

2983 2984
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2985
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2986 2987
        virDomainRemoveInactive(&driver->domains,
                                vm);
2988
        vm = NULL;
2989
        goto cleanup;
2990 2991
    }

2992 2993 2994 2995 2996
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
2997

2998
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2999
    if (dom) dom->id = vm->def->id;
3000 3001

cleanup:
3002 3003
    if (vm)
        virDomainObjUnlock(vm);
3004 3005
    if (event)
        qemuDomainEventQueue(driver, event);
3006
    qemuDriverUnlock(driver);
3007
    return dom;
D
Daniel P. Berrange 已提交
3008 3009
}

3010
static int qemudDomainUndefine(virDomainPtr dom) {
3011 3012
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3013
    virDomainEventPtr event = NULL;
3014
    int ret = -1;
D
Daniel P. Berrange 已提交
3015

3016
    qemuDriverLock(driver);
3017
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3018

D
Daniel P. Berrange 已提交
3019
    if (!vm) {
3020 3021
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3022
        goto cleanup;
D
Daniel P. Berrange 已提交
3023 3024
    }

3025
    if (virDomainIsActive(vm)) {
3026 3027
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
3028
        goto cleanup;
D
Daniel P. Berrange 已提交
3029 3030
    }

3031 3032 3033
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
3034
        goto cleanup;
3035 3036 3037
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
3038
        goto cleanup;
D
Daniel P. Berrange 已提交
3039

3040 3041 3042
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
3043

3044 3045
    virDomainRemoveInactive(&driver->domains,
                            vm);
3046
    vm = NULL;
3047
    ret = 0;
D
Daniel P. Berrange 已提交
3048

3049
cleanup:
3050 3051
    if (vm)
        virDomainObjUnlock(vm);
3052 3053
    if (event)
        qemuDomainEventQueue(driver, event);
3054
    qemuDriverUnlock(driver);
3055
    return ret;
D
Daniel P. Berrange 已提交
3056 3057
}

3058
/* Return the disks name for use in monitor commands */
3059
static char *qemudDiskDeviceName(const virConnectPtr conn,
3060
                                 const virDomainDiskDefPtr disk) {
3061 3062 3063 3064 3065 3066

    int busid, devid;
    int ret;
    char *devname;

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
3067
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3068 3069 3070 3071 3072 3073 3074
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
3075
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
3076
                ret = virAsprintf(&devname, "ide%d-hd%d", busid, devid);
3077
            else
3078
                ret = virAsprintf(&devname, "ide%d-cd%d", busid, devid);
3079 3080
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
3081
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
3082
                ret = virAsprintf(&devname, "scsi%d-hd%d", busid, devid);
3083
            else
3084
                ret = virAsprintf(&devname, "scsi%d-cd%d", busid, devid);
3085 3086
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
3087
            ret = virAsprintf(&devname, "floppy%d", devid);
3088 3089
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
3090
            ret = virAsprintf(&devname, "virtio%d", devid);
3091 3092
            break;
        default:
3093
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
3094 3095 3096 3097 3098 3099
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
3100
        virReportOOMError(conn);
3101 3102 3103 3104 3105 3106
        return NULL;
    }

    return devname;
}

3107 3108
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           virDomainObjPtr vm,
3109 3110
                                           virDomainDeviceDefPtr dev)
{
3111
    virDomainDiskDefPtr origdisk = NULL, newdisk;
3112
    char *cmd, *reply, *safe_path;
3113
    char *devname = NULL;
3114
    unsigned int qemuCmdFlags;
3115
    int i;
3116

3117
    origdisk = NULL;
3118
    newdisk = dev->data.disk;
3119 3120 3121 3122
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->bus == newdisk->bus &&
            STREQ(vm->def->disks[i]->dst, newdisk->dst)) {
            origdisk = vm->def->disks[i];
3123
            break;
3124
        }
3125 3126 3127
    }

    if (!origdisk) {
3128
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3129 3130 3131 3132 3133 3134 3135 3136 3137
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
3138
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3139 3140 3141 3142 3143 3144
                         _("Cannot determine QEMU argv syntax %s"),
                         vm->def->emulator);
        return -1;
    }

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
3145
        if (!(devname = qemudDiskDeviceName(conn, newdisk)))
3146 3147 3148 3149 3150 3151 3152 3153 3154
            return -1;
    } else {
        /* Back compat for no -drive option */
        if (newdisk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)
            devname = strdup(newdisk->dst);
        else if (newdisk->device == VIR_DOMAIN_DISK_DEVICE_CDROM &&
                 STREQ(newdisk->dst, "hdc"))
            devname = strdup("cdrom");
        else {
3155
            qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3156 3157 3158 3159 3160 3161 3162 3163
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
3164
            virReportOOMError(conn);
3165 3166 3167
            return -1;
        }
    }
3168

3169
    if (newdisk->src) {
3170 3171
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
3172
            virReportOOMError(conn);
3173
            VIR_FREE(devname);
3174 3175
            return -1;
        }
3176
        if (virAsprintf(&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
3177
            virReportOOMError(conn);
3178
            VIR_FREE(safe_path);
3179
            VIR_FREE(devname);
3180 3181
            return -1;
        }
3182
        VIR_FREE(safe_path);
3183

3184
    } else if (virAsprintf(&cmd, "eject %s", devname) == -1) {
3185
        virReportOOMError(conn);
3186
        VIR_FREE(devname);
3187 3188
        return -1;
    }
3189
    VIR_FREE(devname);
3190

3191
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3192
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3193
                         "%s", _("could not change cdrom media"));
3194
        VIR_FREE(cmd);
3195 3196
        return -1;
    }
3197 3198 3199 3200

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
3201
    DEBUG ("ejectable media change reply: %s", reply);
3202
    if (strstr(reply, "\ndevice ")) {
3203
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3204
                          _("changing cdrom media failed: %s"), reply);
3205 3206 3207 3208
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3209 3210
    VIR_FREE(reply);
    VIR_FREE(cmd);
3211

3212 3213
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
3214
    newdisk->src = NULL;
3215
    origdisk->type = newdisk->type;
3216 3217 3218
    return 0;
}

3219 3220 3221
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
3222 3223
{
    int ret, i;
3224
    char *cmd, *reply, *s;
3225 3226 3227 3228 3229
    char *safe_path;
    const char* type = virDomainDiskBusTypeToString(dev->data.disk->bus);

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3230
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3231 3232 3233 3234 3235 3236
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3237
        virReportOOMError(conn);
3238 3239 3240 3241 3242
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3243
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3244 3245 3246 3247
                         "%s", _("out of memory"));
        return -1;
    }

3248 3249
    ret = virAsprintf(&cmd, "pci_add 0 storage file=%s,if=%s",
                      safe_path, type);
3250 3251
    VIR_FREE(safe_path);
    if (ret == -1) {
3252
        virReportOOMError(conn);
3253 3254 3255
        return ret;
    }

3256
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3257
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3258 3259 3260 3261 3262 3263 3264 3265
                         _("cannot attach %s disk"), type);
        VIR_FREE(cmd);
        return -1;
    }

    DEBUG ("pci_add reply: %s", reply);
    /* If the command succeeds qemu prints:
     * OK bus 0... */
3266 3267 3268 3269 3270 3271
#define PCI_ATTACH_OK_MSG "OK bus 0, slot "
    if ((s=strstr(reply, PCI_ATTACH_OK_MSG))) {
        char* dummy = s;
        s += strlen(PCI_ATTACH_OK_MSG);

        if (virStrToLong_i ((const char*)s, &dummy, 10, &dev->data.disk->slotnum) == -1)
J
Jim Meyering 已提交
3272
            qemudLog(QEMUD_WARN, "%s", _("Unable to parse slot number\n"));
3273
    } else {
3274
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
                          _("adding %s disk failed"), type);
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }

    vm->def->disks[vm->def->ndisks++] = dev->data.disk;
    qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
          virDomainDiskQSort);

    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}
3289

3290 3291 3292
static int qemudDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                                 virDomainObjPtr vm,
                                                 virDomainDeviceDefPtr dev)
3293
{
3294 3295
    int ret, i;
    char *safe_path;
3296 3297
    char *cmd, *reply;

3298 3299
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3300
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3301 3302 3303 3304 3305
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

3306
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3307
        virReportOOMError(conn);
3308
        return -1;
3309 3310
    }

3311 3312
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3313
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3314 3315 3316 3317
                         "%s", _("out of memory"));
        return -1;
    }

3318
    ret = virAsprintf(&cmd, "usb_add disk:%s", safe_path);
3319
    VIR_FREE(safe_path);
3320
    if (ret == -1) {
3321
        virReportOOMError(conn);
3322 3323 3324
        return ret;
    }

3325
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3326
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3327
                         "%s", _("cannot attach usb disk"));
3328 3329 3330 3331 3332 3333 3334 3335
        VIR_FREE(cmd);
        return -1;
    }

    DEBUG ("attach_usb reply: %s", reply);
    /* If the command failed qemu prints:
     * Could not add ... */
    if (strstr(reply, "Could not add ")) {
3336
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3337
                          "%s",
3338
                          _("adding usb disk failed"));
3339 3340 3341 3342
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3343

3344 3345 3346
    vm->def->disks[vm->def->ndisks++] = dev->data.disk;
    qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
          virDomainDiskQSort);
3347

3348 3349 3350 3351 3352
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3353 3354 3355
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3356 3357 3358 3359
{
    int ret;
    char *cmd, *reply;

3360
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
3361
        virReportOOMError(conn);
3362 3363
        return -1;
    }
3364

3365
    if (dev->data.hostdev->source.subsys.u.usb.vendor) {
3366 3367 3368
        ret = virAsprintf(&cmd, "usb_add host:%.4x:%.4x",
                          dev->data.hostdev->source.subsys.u.usb.vendor,
                          dev->data.hostdev->source.subsys.u.usb.product);
3369
    } else {
3370 3371 3372
        ret = virAsprintf(&cmd, "usb_add host:%.3d.%.3d",
                          dev->data.hostdev->source.subsys.u.usb.bus,
                          dev->data.hostdev->source.subsys.u.usb.device);
3373 3374
    }
    if (ret == -1) {
3375
        virReportOOMError(conn);
3376 3377 3378
        return -1;
    }

3379
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3380
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3381 3382 3383 3384 3385 3386 3387 3388 3389
                         "%s", _("cannot attach usb device"));
        VIR_FREE(cmd);
        return -1;
    }

    DEBUG ("attach_usb reply: %s", reply);
    /* If the command failed qemu prints:
     * Could not add ... */
    if (strstr(reply, "Could not add ")) {
3390
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3391 3392 3393 3394 3395 3396
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3397

3398
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
3399

3400 3401
    VIR_FREE(reply);
    VIR_FREE(cmd);
3402 3403 3404
    return 0;
}

3405 3406
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
3407 3408 3409 3410
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3411

3412
    qemuDriverLock(driver);
3413
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3414
    if (!vm) {
3415
        qemuDriverUnlock(driver);
3416 3417
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3418
        goto cleanup;
3419 3420 3421
    }

    if (!virDomainIsActive(vm)) {
3422
        qemuDriverUnlock(driver);
3423 3424
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
3425
        goto cleanup;
3426 3427
    }

3428 3429
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
3430
    qemuDriverUnlock(driver);
3431 3432 3433
    if (dev == NULL)
        goto cleanup;

3434

3435 3436
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
3437 3438
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
3439
            ret = qemudDomainChangeEjectableMedia(dom->conn, vm, dev);
3440 3441 3442
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
3443
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, vm, dev);
3444 3445
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
3446
                ret = qemudDomainAttachPciDiskDevice(dom->conn, vm, dev);
3447 3448 3449 3450 3451 3452
            }
            break;
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("this disk device type cannot be attached"));
            goto cleanup;
3453
        }
3454
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
3455 3456
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
3457
        ret = qemudDomainAttachHostDevice(dom->conn, vm, dev);
3458
    } else {
3459
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
3460
                         "%s", _("this device type cannot be attached"));
3461
        goto cleanup;
3462 3463
    }

3464
    qemudSaveDomainStatus(dom->conn, driver, vm);
3465
cleanup:
G
Guido Günther 已提交
3466 3467
    if (ret < 0)
        virDomainDeviceDefFree(dev);
3468 3469
    if (vm)
        virDomainObjUnlock(vm);
3470 3471 3472
    return ret;
}

3473 3474
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3475 3476
{
    int i, ret = -1;
3477 3478
    char *cmd = NULL;
    char *reply = NULL;
3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
    virDomainDiskDefPtr detach = NULL;

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
            detach = vm->def->disks[i];
            break;
        }
    }

    if (!detach) {
3489
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3490
                         _("disk %s not found"), dev->data.disk->dst);
3491
        goto cleanup;
3492 3493 3494
    }

    if (detach->slotnum < 1) {
3495
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3496
                         _("disk %s cannot be detached - invalid slot number %d"),
3497
                           detach->dst, detach->slotnum);
3498
        goto cleanup;
3499 3500
    }

3501
    if (virAsprintf(&cmd, "pci_del 0 %d", detach->slotnum) < 0) {
3502
        virReportOOMError(conn);
3503
        goto cleanup;
3504 3505
    }

3506
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3507
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3508
                          _("failed to execute detach disk %s command"), detach->dst);
3509
        goto cleanup;
3510 3511 3512 3513 3514 3515
    }

    DEBUG ("pci_del reply: %s", reply);
    /* If the command fails due to a wrong slot qemu prints: invalid slot,
     * nothing is printed on success */
    if (strstr(reply, "invalid slot")) {
3516
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3517
                          _("failed to detach disk %s: invalid slot %d"),
3518 3519
                          detach->dst, detach->slotnum);
        goto cleanup;
3520 3521 3522 3523 3524
    }

    if (vm->def->ndisks > 1) {
        vm->def->disks[i] = vm->def->disks[--vm->def->ndisks];
        if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks) < 0) {
3525
            virReportOOMError(conn);
3526
            goto cleanup;
3527 3528 3529 3530 3531 3532 3533 3534
        }
        qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
              virDomainDiskQSort);
    } else {
        VIR_FREE(vm->def->disks[0]);
        vm->def->ndisks = 0;
    }
    ret = 0;
3535 3536

cleanup:
3537 3538 3539 3540 3541 3542 3543
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
3544 3545 3546 3547
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3548

3549
    qemuDriverLock(driver);
3550
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3551
    if (!vm) {
3552
        qemuDriverUnlock(driver);
3553 3554
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3555
        goto cleanup;
3556 3557 3558
    }

    if (!virDomainIsActive(vm)) {
3559
        qemuDriverUnlock(driver);
3560
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
G
Guido Günther 已提交
3561
                         "%s", _("cannot detach device on inactive domain"));
3562
        goto cleanup;
3563 3564
    }

3565 3566
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
3567
    qemuDriverUnlock(driver);
3568 3569 3570
    if (dev == NULL)
        goto cleanup;

3571 3572 3573 3574 3575

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
        (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
         dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO))
3576
        ret = qemudDomainDetachPciDiskDevice(dom->conn, vm, dev);
3577
    else
3578 3579 3580
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

3581
    qemudSaveDomainStatus(dom->conn, driver, vm);
3582 3583
cleanup:
    virDomainDeviceDefFree(dev);
3584 3585
    if (vm)
        virDomainObjUnlock(vm);
3586 3587 3588
    return ret;
}

3589
static int qemudDomainGetAutostart(virDomainPtr dom,
3590
                                   int *autostart) {
3591 3592 3593
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3594

3595
    qemuDriverLock(driver);
3596
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3597 3598
    qemuDriverUnlock(driver);

3599
    if (!vm) {
3600 3601
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3602
        goto cleanup;
3603 3604 3605
    }

    *autostart = vm->autostart;
3606
    ret = 0;
3607

3608
cleanup:
3609 3610
    if (vm)
        virDomainObjUnlock(vm);
3611
    return ret;
3612 3613
}

3614
static int qemudDomainSetAutostart(virDomainPtr dom,
3615
                                   int autostart) {
3616 3617
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3618 3619
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
3620

3621
    qemuDriverLock(driver);
3622
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3623 3624
    qemuDriverUnlock(driver);

3625
    if (!vm) {
3626 3627
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3628
        goto cleanup;
3629 3630
    }

3631 3632 3633
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
3634
        goto cleanup;
3635 3636
    }

3637 3638
    autostart = (autostart != 0);

3639 3640 3641 3642 3643
    if (vm->autostart != autostart) {
        if ((configFile = virDomainConfigFile(dom->conn, driver->configDir, vm->def->name)) == NULL)
            goto cleanup;
        if ((autostartLink = virDomainConfigFile(dom->conn, driver->autostartDir, vm->def->name)) == NULL)
            goto cleanup;
3644

3645 3646
        if (autostart) {
            int err;
3647

3648
            if ((err = virFileMakePath(driver->autostartDir))) {
3649 3650 3651
                virReportSystemError(dom->conn, err,
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
3652 3653
                goto cleanup;
            }
3654

3655
            if (symlink(configFile, autostartLink) < 0) {
3656 3657 3658
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
3659 3660 3661 3662
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
3663 3664 3665
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
3666 3667
                goto cleanup;
            }
3668 3669
        }

3670
        vm->autostart = autostart;
3671
    }
3672
    ret = 0;
3673

3674 3675 3676
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
3677 3678
    if (vm)
        virDomainObjUnlock(vm);
3679
    return ret;
3680 3681
}

3682 3683 3684 3685 3686 3687 3688 3689 3690
/* This uses the 'info blockstats' monitor command which was
 * integrated into both qemu & kvm in late 2007.  If the command is
 * not supported we detect this and return the appropriate error.
 */
static int
qemudDomainBlockStats (virDomainPtr dom,
                       const char *path,
                       struct _virDomainBlockStats *stats)
{
3691
    struct qemud_driver *driver = dom->conn->privateData;
3692
    char *dummy, *info = NULL;
3693
    const char *p, *eol;
3694
    const char *qemu_dev_name = NULL;
3695
    size_t len;
3696
    int i, ret = -1;
3697
    virDomainObjPtr vm;
3698
    virDomainDiskDefPtr disk = NULL;
3699

3700
    qemuDriverLock(driver);
3701
    vm = virDomainFindByID(&driver->domains, dom->id);
3702
    qemuDriverUnlock(driver);
3703 3704 3705
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3706
        goto cleanup;
3707
    }
3708
    if (!virDomainIsActive (vm)) {
3709 3710
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
3711
        goto cleanup;
3712 3713
    }

3714 3715 3716 3717 3718 3719 3720 3721
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
3722 3723
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
3724
        goto cleanup;
3725 3726
    }

3727
    qemu_dev_name = qemudDiskDeviceName(dom->conn, disk);
3728
    if (!qemu_dev_name)
3729
        goto cleanup;
3730 3731
    len = strlen (qemu_dev_name);

3732
    if (qemudMonitorCommand (vm, "info blockstats", &info) < 0) {
3733 3734
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
3735
        goto cleanup;
3736 3737 3738 3739 3740 3741 3742 3743
    }
    DEBUG ("info blockstats reply: %s", info);

    /* If the command isn't supported then qemu prints the supported
     * info commands, so the output starts "info ".  Since this is
     * unlikely to be the name of a block device, we can use this
     * to detect if qemu supports the command.
     */
C
Cole Robinson 已提交
3744
    if (strstr(info, "\ninfo ")) {
3745 3746 3747
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
3748
        goto cleanup;
3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
    }

    stats->rd_req = -1;
    stats->rd_bytes = -1;
    stats->wr_req = -1;
    stats->wr_bytes = -1;
    stats->errs = -1;

    /* The output format for both qemu & KVM is:
     *   blockdevice: rd_bytes=% wr_bytes=% rd_operations=% wr_operations=%
     *   (repeated for each block device)
     * where '%' is a 64 bit number.
     */
    p = info;

    while (*p) {
        if (STREQLEN (p, qemu_dev_name, len)
            && p[len] == ':' && p[len+1] == ' ') {

            eol = strchr (p, '\n');
            if (!eol)
                eol = p + strlen (p);

            p += len+2;         /* Skip to first label. */

            while (*p) {
3775
                if (STRPREFIX (p, "rd_bytes=")) {
3776 3777 3778
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
3779
                } else if (STRPREFIX (p, "wr_bytes=")) {
3780 3781 3782
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
3783
                } else if (STRPREFIX (p, "rd_operations=")) {
3784 3785 3786
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
3787
                } else if (STRPREFIX (p, "wr_operations=")) {
3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_req) == -1)
                        DEBUG ("error reading wr_req: %s", p);
                } else
                    DEBUG ("unknown block stat near %s", p);

                /* Skip to next label. */
                p = strchr (p, ' ');
                if (!p || p >= eol) break;
                p++;
            }
3799
            ret = 0;
3800
            goto cleanup;
3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
        }

        /* Skip to next line. */
        p = strchr (p, '\n');
        if (!p) break;
        p++;
    }

    /* If we reach here then the device was not found. */
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                      _("device not found: %s (%s)"), path, qemu_dev_name);
3812
 cleanup:
3813 3814
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
3815 3816
    if (vm)
        virDomainObjUnlock(vm);
3817
    return ret;
3818 3819
}

3820
#ifdef __linux__
3821 3822 3823 3824 3825
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
3826 3827
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3828
    int i;
3829
    int ret = -1;
3830

3831
    qemuDriverLock(driver);
3832
    vm = virDomainFindByID(&driver->domains, dom->id);
3833 3834
    qemuDriverUnlock(driver);

3835 3836
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
3837
                          _("no domain with matching id %d"), dom->id);
3838
        goto cleanup;
3839 3840
    }

3841
    if (!virDomainIsActive(vm)) {
3842
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3843
                         "%s", _("domain is not running"));
3844
        goto cleanup;
3845 3846 3847 3848
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3849
                         "%s", _("NULL or empty path"));
3850
        goto cleanup;
3851 3852 3853
    }

    /* Check the path is one of the domain's network interfaces. */
3854 3855
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
3856 3857 3858 3859
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
3860 3861
    }

3862 3863 3864 3865 3866
    if (ret == 0)
        ret = linuxDomainInterfaceStats (dom->conn, path, stats);
    else
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path, '%s' is not a known interface"), path);
3867

3868
cleanup:
3869 3870
    if (vm)
        virDomainObjUnlock(vm);
3871 3872
    return ret;
}
3873
#else
3874 3875 3876 3877
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
3878 3879 3880 3881
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
}
3882
#endif
3883

3884 3885 3886 3887 3888 3889 3890
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
3891 3892 3893
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
3894

3895
    qemuDriverLock(driver);
3896
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3897 3898
    qemuDriverUnlock(driver);

3899 3900
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
3901
                          "%s", _("no domain with matching uuid"));
3902
        goto cleanup;
3903 3904 3905 3906
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3907
                         "%s", _("NULL or empty path"));
3908
        goto cleanup;
3909 3910 3911
    }

    /* Check the path belongs to this domain. */
3912 3913
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
3914 3915 3916 3917
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
3918 3919
    }

3920 3921 3922 3923 3924 3925 3926 3927 3928
    if (ret == 0) {
        ret = -1;
        /* The path is correct, now try to open it and get its size. */
        fd = open (path, O_RDONLY);
        if (fd == -1) {
            qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                              "%s", strerror (errno));
            goto cleanup;
        }
3929

3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944
        /* Seek and read. */
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
         * be 64 bits on all platforms.
         */
        if (lseek (fd, offset, SEEK_SET) == (off_t) -1 ||
            saferead (fd, buffer, size) == (ssize_t) -1) {
            qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                              "%s", strerror (errno));
            goto cleanup;
        }

        ret = 0;
    } else {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          "%s", _("invalid path"));
3945 3946
    }

3947 3948 3949
cleanup:
    if (fd >= 0)
        close (fd);
3950 3951
    if (vm)
        virDomainObjUnlock(vm);
3952 3953 3954
    return ret;
}

R
Richard W.M. Jones 已提交
3955 3956 3957 3958 3959 3960
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
3961 3962 3963
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char cmd[256], *info = NULL;
R
Richard W.M. Jones 已提交
3964 3965 3966
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

3967
    qemuDriverLock(driver);
3968
    vm = virDomainFindByID(&driver->domains, dom->id);
3969
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
3970 3971 3972 3973

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3974 3975 3976 3977 3978 3979 3980
        goto cleanup;
    }

    if (flags != VIR_MEMORY_VIRTUAL) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          "%s", _("QEMU driver only supports virtual memory addrs"));
        goto cleanup;
R
Richard W.M. Jones 已提交
3981 3982
    }

3983
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3984 3985
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
3986
        goto cleanup;
R
Richard W.M. Jones 已提交
3987 3988 3989 3990 3991 3992
    }

    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
3993
        goto cleanup;
R
Richard W.M. Jones 已提交
3994 3995 3996 3997
    }

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
3998
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
R
Richard W.M. Jones 已提交
3999
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
4000
                          "%s", _("'memsave' command failed"));
4001
        goto cleanup;
R
Richard W.M. Jones 已提交
4002 4003 4004 4005 4006 4007 4008 4009
    }

    DEBUG ("memsave reply: %s", info);

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
4010
        goto cleanup;
R
Richard W.M. Jones 已提交
4011 4012 4013
    }

    ret = 0;
4014 4015 4016

cleanup:
    VIR_FREE(info);
R
Richard W.M. Jones 已提交
4017 4018
    if (fd >= 0) close (fd);
    unlink (tmp);
4019 4020
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
4021 4022 4023
    return ret;
}

4024

4025 4026
static int
qemudDomainEventRegister (virConnectPtr conn,
4027
                          virConnectDomainEventCallback callback,
4028 4029
                          void *opaque,
                          virFreeCallback freecb)
4030
{
4031 4032 4033
    struct qemud_driver *driver = conn->privateData;
    int ret;

4034
    qemuDriverLock(driver);
4035 4036
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
4037
    qemuDriverUnlock(driver);
4038

4039
    return ret;
4040 4041 4042 4043
}

static int
qemudDomainEventDeregister (virConnectPtr conn,
4044
                            virConnectDomainEventCallback callback)
4045
{
4046 4047 4048
    struct qemud_driver *driver = conn->privateData;
    int ret;

4049
    qemuDriverLock(driver);
4050 4051 4052 4053 4054 4055
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
4056
    qemuDriverUnlock(driver);
4057

4058
    return ret;
4059 4060
}

4061 4062 4063 4064 4065
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
                                        virConnectDomainEventCallback cb,
                                        void *cbopaque,
                                        void *opaque)
4066
{
4067
    struct qemud_driver *driver = opaque;
4068

4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
    /* Drop the lock whle dispatching, for sake of re-entrancy */
    qemuDriverUnlock(driver);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    qemuDriverLock(driver);
}

static void qemuDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
{
    struct qemud_driver *driver = opaque;
    virDomainEventQueue tempQueue;

    qemuDriverLock(driver);

    driver->domainEventDispatching = 1;

    /* Copy the queue, so we're reentrant safe */
    tempQueue.count = driver->domainEventQueue->count;
    tempQueue.events = driver->domainEventQueue->events;
    driver->domainEventQueue->count = 0;
    driver->domainEventQueue->events = NULL;

    virEventUpdateTimeout(driver->domainEventTimer, -1);
    virDomainEventQueueDispatch(&tempQueue,
                                driver->domainEventCallbacks,
                                qemuDomainEventDispatchFunc,
                                driver);

    /* Purge any deleted callbacks */
    virDomainEventCallbackListPurgeMarked(driver->domainEventCallbacks);

    driver->domainEventDispatching = 0;
    qemuDriverUnlock(driver);
}


/* driver must be locked before calling */
static void qemuDomainEventQueue(struct qemud_driver *driver,
                                 virDomainEventPtr event)
{
    if (virDomainEventQueuePush(driver->domainEventQueue,
                                event) < 0)
        virDomainEventFree(event);
    if (qemu_driver->domainEventQueue->count == 1)
        virEventUpdateTimeout(driver->domainEventTimer, 0);
4113 4114
}

D
Daniel Veillard 已提交
4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
/* Migration support. */

/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
static int
qemudDomainMigratePrepare2 (virConnectPtr dconn,
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
                            const char *uri_in,
                            char **uri_out,
                            unsigned long flags ATTRIBUTE_UNUSED,
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
    static int port = 0;
4133 4134
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
4135 4136 4137 4138 4139
    virDomainObjPtr vm = NULL;
    int this_port;
    char hostname [HOST_NAME_MAX+1];
    char migrateFrom [64];
    const char *p;
4140
    virDomainEventPtr event = NULL;
4141 4142 4143
    int ret = -1;;

    *uri_out = NULL;
D
Daniel Veillard 已提交
4144

4145
    qemuDriverLock(driver);
D
Daniel Veillard 已提交
4146 4147 4148
    if (!dom_xml) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                          "%s", _("no domain XML passed"));
4149
        goto cleanup;
D
Daniel Veillard 已提交
4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169
    }

    /* 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
     * from our pool of port numbers and return a URI of
     * "tcp://ourhostname:port".
     *
     * 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) {
        this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
        if (port == QEMUD_MIGRATION_NUM_PORTS) port = 0;

        /* Get hostname */
        if (gethostname (hostname, HOST_NAME_MAX+1) == -1) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                              "%s", strerror (errno));
4170
            goto cleanup;
D
Daniel Veillard 已提交
4171 4172 4173
        }

        /* Caller frees */
4174
        if (virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port) < 0) {
4175
            virReportOOMError (dconn);
4176
            goto cleanup;
D
Daniel Veillard 已提交
4177 4178 4179 4180 4181 4182 4183 4184 4185
        }
    } else {
        /* Check the URI starts with "tcp:".  We will escape the
         * URI when passing it to the qemu monitor, so bad
         * characters in hostname part don't matter.
         */
        if (!STREQLEN (uri_in, "tcp:", 6)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_ARG,
                  "%s", _("only tcp URIs are supported for KVM migrations"));
4186
            goto cleanup;
D
Daniel Veillard 已提交
4187 4188 4189 4190 4191 4192 4193 4194 4195
        }

        /* Get the port number. */
        p = strrchr (uri_in, ':');
        p++; /* definitely has a ':' in it, see above */
        this_port = virParseNumber (&p);
        if (this_port == -1 || p-uri_in != strlen (uri_in)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_ARG,
                              "%s", _("URI did not have ':port' at the end"));
4196
            goto cleanup;
D
Daniel Veillard 已提交
4197 4198 4199 4200
        }
    }

    /* Parse the domain XML. */
4201 4202
    if (!(def = virDomainDefParseString(dconn, driver->caps, dom_xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
D
Daniel Veillard 已提交
4203 4204
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to parse XML"));
4205
        goto cleanup;
D
Daniel Veillard 已提交
4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221
    }

    /* Target domain name, maybe renamed. */
    dname = dname ? dname : def->name;

#if 1
    /* Ensure the name and UUID don't already exist in an active VM */
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
#else
    /* For TESTING ONLY you can change #if 1 -> #if 0 above and use
     * this code which lets you do localhost migrations.  You must still
     * supply a fresh 'dname' but this code assigns a random UUID.
     */
    if (virUUIDGenerate (def->uuid) == -1) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
            _("could not generate random UUID"));
4222
        goto cleanup;
D
Daniel Veillard 已提交
4223 4224 4225 4226 4227 4228 4229 4230 4231
    }
#endif

    if (!vm) vm = virDomainFindByName(&driver->domains, dname);
    if (vm) {
        if (virDomainIsActive(vm)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                              _("domain with the same name or UUID already exists as '%s'"),
                              vm->def->name);
4232
            goto cleanup;
D
Daniel Veillard 已提交
4233 4234 4235 4236 4237 4238 4239 4240
        }
    }

    if (!(vm = virDomainAssignDef(dconn,
                                  &driver->domains,
                                  def))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to assign new VM"));
4241
        goto cleanup;
D
Daniel Veillard 已提交
4242
    }
4243
    def = NULL;
D
Daniel Veillard 已提交
4244 4245 4246 4247 4248 4249 4250 4251

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

    /* Start the QEMU daemon, with the same command-line arguments plus
     * -incoming tcp:0.0.0.0:port
     */
    snprintf (migrateFrom, sizeof (migrateFrom), "tcp:0.0.0.0:%d", this_port);
4252
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom, -1) < 0) {
D
Daniel Veillard 已提交
4253 4254
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to start listening VM"));
4255
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4256
            virDomainRemoveInactive(&driver->domains, vm);
4257 4258
            vm = NULL;
        }
4259
        goto cleanup;
D
Daniel Veillard 已提交
4260
    }
4261 4262 4263 4264

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_MIGRATED);
4265
    ret = 0;
D
Daniel Veillard 已提交
4266

4267 4268 4269 4270 4271
cleanup:
    virDomainDefFree(def);
    if (ret != 0) {
        VIR_FREE(*uri_out);
    }
4272 4273
    if (vm)
        virDomainObjUnlock(vm);
4274 4275
    if (event)
        qemuDomainEventQueue(driver, event);
4276
    qemuDriverUnlock(driver);
4277
    return ret;
D
Daniel Veillard 已提交
4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289
}

/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri,
                           unsigned long flags ATTRIBUTE_UNUSED,
                           const char *dname ATTRIBUTE_UNUSED,
                           unsigned long resource)
{
4290 4291
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4292
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4293 4294
    char *safe_uri;
    char cmd[HOST_NAME_MAX+50];
4295 4296
    char *info = NULL;
    int ret = -1;
D
Daniel Veillard 已提交
4297

4298
    qemuDriverLock(driver);
4299
    vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel Veillard 已提交
4300 4301 4302
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
4303
        goto cleanup;
D
Daniel Veillard 已提交
4304 4305 4306 4307 4308
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
4309
        goto cleanup;
D
Daniel Veillard 已提交
4310 4311
    }

4312 4313 4314
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
        snprintf(cmd, sizeof cmd, "%s", "stop");
4315
        qemudMonitorCommand (vm, cmd, &info);
4316 4317 4318
        DEBUG ("stop reply: %s", info);
        VIR_FREE(info);

4319 4320 4321 4322 4323 4324
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
        event = NULL;
4325 4326
    }

D
Daniel Veillard 已提交
4327 4328 4329
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
4330
        qemudMonitorCommand (vm, cmd, &info);
D
Daniel Veillard 已提交
4331 4332 4333 4334 4335 4336 4337 4338 4339 4340

        DEBUG ("migrate_set_speed reply: %s", info);
        VIR_FREE (info);
    }

    /* Issue the migrate command. */
    safe_uri = qemudEscapeMonitorArg (uri);
    if (!safe_uri) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
4341
        goto cleanup;
D
Daniel Veillard 已提交
4342 4343 4344 4345
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

4346
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
D
Daniel Veillard 已提交
4347 4348
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("migrate operation failed"));
4349
        goto cleanup;
D
Daniel Veillard 已提交
4350 4351 4352 4353 4354 4355 4356 4357
    }

    DEBUG ("migrate reply: %s", info);

    /* Now check for "fail" in the output string */
    if (strstr(info, "fail") != NULL) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          _("migrate failed: %s"), info);
4358
        goto cleanup;
D
Daniel Veillard 已提交
4359 4360 4361 4362
    }

    /* Clean up the source domain. */
    qemudShutdownVMDaemon (dom->conn, driver, vm);
4363 4364 4365 4366

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
4367
    if (!vm->persistent) {
D
Daniel Veillard 已提交
4368
        virDomainRemoveInactive(&driver->domains, vm);
4369 4370
        vm = NULL;
    }
4371
    ret = 0;
D
Daniel Veillard 已提交
4372

4373 4374
cleanup:
    VIR_FREE(info);
4375 4376
    if (vm)
        virDomainObjUnlock(vm);
4377 4378
    if (event)
        qemuDomainEventQueue(driver, event);
4379
    qemuDriverUnlock(driver);
4380
    return ret;
D
Daniel Veillard 已提交
4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
}

/* Finish is the third and final step, and it runs on the destination host. */
static virDomainPtr
qemudDomainMigrateFinish2 (virConnectPtr dconn,
                           const char *dname,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri ATTRIBUTE_UNUSED,
                           unsigned long flags ATTRIBUTE_UNUSED,
                           int retcode)
{
4393 4394 4395
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4396
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4397 4398
    char *info = NULL;

4399
    qemuDriverLock(driver);
4400
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
4401 4402 4403
    if (!vm) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching name %s"), dname);
4404
        goto cleanup;
D
Daniel Veillard 已提交
4405 4406 4407 4408 4409 4410 4411 4412 4413
    }

    /* Did the migration go as planned?  If yes, return the domain
     * object, but if no, clean up the empty qemu process.
     */
    if (retcode == 0) {
        dom = virGetDomain (dconn, vm->def->name, vm->def->uuid);
        VIR_FREE(info);
        vm->state = VIR_DOMAIN_RUNNING;
4414 4415 4416
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
D
Daniel Veillard 已提交
4417 4418
    } else {
        qemudShutdownVMDaemon (dconn, driver, vm);
4419 4420 4421
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
4422
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4423
            virDomainRemoveInactive(&driver->domains, vm);
4424 4425
            vm = NULL;
        }
D
Daniel Veillard 已提交
4426
    }
4427 4428

cleanup:
4429 4430
    if (vm)
        virDomainObjUnlock(vm);
4431 4432
    if (event)
        qemuDomainEventQueue(driver, event);
4433
    qemuDriverUnlock(driver);
4434
    return dom;
D
Daniel Veillard 已提交
4435 4436
}

4437 4438 4439 4440 4441
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
4442
    qemudSupportsFeature, /* supports_feature */
4443 4444
    qemudGetType, /* type */
    qemudGetVersion, /* version */
4445
    qemudGetHostname, /* hostname */
4446
    NULL, /* URI  */
4447 4448 4449 4450 4451
    qemudGetMaxVCPUs, /* getMaxVcpus */
    qemudGetNodeInfo, /* nodeGetInfo */
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
4452
    qemudDomainCreate, /* domainCreateXML */
4453 4454 4455 4456 4457
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
4458
    qemudDomainShutdown, /* domainShutdown */
4459 4460 4461
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
4462 4463 4464
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
4465 4466 4467 4468
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
4469
    qemudDomainSetVcpus, /* domainSetVcpus */
4470 4471 4472 4473
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
4474 4475
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
4476
#endif
4477
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
4478 4479 4480 4481 4482 4483
    qemudDomainDumpXML, /* domainDumpXML */
    qemudListDefinedDomains, /* listDomains */
    qemudNumDefinedDomains, /* numOfDomains */
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
4484
    qemudDomainAttachDevice, /* domainAttachDevice */
4485
    qemudDomainDetachDevice, /* domainDetachDevice */
4486 4487 4488 4489 4490
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
4491 4492
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
4493
    NULL, /* domainMigrateFinish */
4494
    qemudDomainBlockStats, /* domainBlockStats */
4495
    qemudDomainInterfaceStats, /* domainInterfaceStats */
4496
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
4497
    qemudDomainMemoryPeek, /* domainMemoryPeek */
4498 4499 4500 4501
#if HAVE_NUMACTL
    qemudNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    qemudNodeGetFreeMemory,  /* getFreeMemory */
#else
4502
    NULL, /* nodeGetCellsFreeMemory */
4503
    NULL, /* getFreeMemory */
4504
#endif
4505 4506
    qemudDomainEventRegister, /* domainEventRegister */
    qemudDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
4507 4508
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
4509 4510 4511
};


4512
static virStateDriver qemuStateDriver = {
4513 4514 4515 4516
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
4517
};
4518

4519
int qemuRegister(void) {
4520 4521 4522 4523
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}