qemu_driver.c 133.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 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
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;
        } else
            vm->monitorpath = status->monitorpath;

        if((vm->logfile = qemudLogFD(NULL, driver->logDir, vm->def->name)) < 0)
            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);
        VIR_FREE(status);
        VIR_FREE(config);
    }
    return 0;
}


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

471
    VIR_FREE(base);
472 473 474

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

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

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

490 491
    qemuDriverUnlock(qemu_driver);

492 493
    return 0;

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

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

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

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

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

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

    return 0;
542 543
}

544 545 546 547 548 549 550 551 552 553
/**
 * 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) {
554
    unsigned int i;
555
    int active = 0;
556

557 558 559
    if (!qemu_driver)
        return 0;

560 561 562 563 564 565 566 567
    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);
    }
568

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

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

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

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

587
    virDomainObjListFree(&qemu_driver->domains);
588

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

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

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

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

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

    return 0;
612 613 614
}

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

static int
621
qemudReadMonitorOutput(virConnectPtr conn,
622
                       virDomainObjPtr vm,
623 624 625 626
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
627 628
                       const char *what,
                       int timeout)
629 630 631 632 633 634 635 636 637
{
    int got = 0;
    buf[0] = '\0';

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

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

639 640 641 642 643 644
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
645 646 647
                virReportSystemError(conn, errno,
                                     _("Failure while reading %s startup output"),
                                     what);
648 649 650
                return -1;
            }

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

669
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
670
                                 _("Failure while reading %s startup output"), what);
671 672 673 674 675
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
676
            if ((ret = func(conn, vm, buf, fd)) != 1)
677 678 679 680
                return ret;
        }
    }

681
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
682
                     _("Out of space while reading %s startup output"), what);
683 684 685 686 687
    return -1;

}

static int
688
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
689
                        virDomainObjPtr vm,
690 691 692 693 694 695 696 697 698 699 700
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

701
static int qemudOpenMonitor(virConnectPtr conn,
702
                            struct qemud_driver* driver,
703
                            virDomainObjPtr vm,
704 705
                            const char *monitor,
                            int reconnect) {
706 707 708 709
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
710
    if ((monfd = open(monitor, O_RDWR)) < 0) {
711
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
712
                         _("Unable to open monitor path %s"), monitor);
713 714 715
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
716
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
717
                         "%s", _("Unable to set monitor close-on-exec flag"));
718 719 720
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
721
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
722
                         "%s", _("Unable to put monitor into non-blocking mode"));
723 724 725
        goto error;
    }

726 727 728 729 730 731 732 733 734 735 736 737 738
    if (!reconnect) {
        ret = qemudReadMonitorOutput(conn,
                                     vm, monfd,
                                     buf, sizeof(buf),
                                     qemudCheckMonitorPrompt,
                                     "monitor", 10000);
    } else {
        vm->monitor = monfd;
        ret = 0;
    }

    if (ret != 0)
         goto error;
739

740
    if (!(vm->monitorpath = strdup(monitor))) {
741
        virReportOOMError(conn);
742 743 744
        goto error;
    }

745 746 747 748 749 750
    if ((vm->monitor_watch = virEventAddHandle(vm->monitor, 0,
                                               qemudDispatchVMEvent,
                                               driver, NULL)) < 0)
        goto error;


751 752 753 754
    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

755 756 757 758 759
 error:
    close(monfd);
    return ret;
}

760 761
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
762
                                   size_t *offset,
763
                                   char **path) {
764
    static const char needle[] = "char device redirected to";
765
    char *tmp, *dev;
766

767
    VIR_FREE(*path);
768
    /* First look for our magic string */
769 770 771 772 773
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
774

775 776 777 778 779
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
780
        if (c_isspace(*tmp)) {
781
            if (VIR_ALLOC_N(*path, (tmp-dev)+1) < 0) {
782
                virReportOOMError(conn);
783 784 785 786
                return -1;
            }
            strncpy(*path, dev, (tmp-dev));
            (*path)[(tmp-dev)] = '\0';
787
            /* ... now further update offset till we get EOL */
788
            *offset = tmp - haystack;
789 790
            return 0;
        }
791
        tmp++;
792 793 794 795 796
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
797 798
     * least see a \n - indicate that we want to carry
     * on trying again
799
     */
800
    return 1;
801 802 803
}

static int
804
qemudFindCharDevicePTYs(virConnectPtr conn,
805
                        virDomainObjPtr vm,
806 807
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
808
{
809
    struct qemud_driver* driver = conn->privateData;
810
    char *monitor = NULL;
811
    size_t offset = 0;
812
    int ret, i;
813 814 815 816 817

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

819
    /* So first comes the monitor device */
820 821
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
822

823
    /* then the serial devices */
824 825
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
826 827 828 829
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
830 831 832 833
        }
    }

    /* and finally the parallel devices */
834 835
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
836 837 838 839
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
840 841 842 843
        }
    }

    /* Got them all, so now open the monitor console */
844
    ret = qemudOpenMonitor(conn, driver, vm, monitor, 0);
845 846 847 848

cleanup:
    VIR_FREE(monitor);
    return ret;
849 850
}

851
static int qemudWaitForMonitor(virConnectPtr conn,
852 853 854
                               struct qemud_driver* driver,
                               virDomainObjPtr vm, off_t pos)
{
855
    char buf[1024]; /* Plenty of space to get startup greeting */
856 857 858 859 860 861 862 863 864 865 866 867
    int logfd;
    int ret;

    if ((logfd = qemudLogReadFD(conn, driver->logDir, vm->def->name, pos))
        < 0)
        return logfd;

    ret = qemudReadMonitorOutput(conn, vm, logfd, buf, sizeof(buf),
                                 qemudFindCharDevicePTYs,
                                 "console", 3000);
    if (close(logfd) < 0)
        qemudLog(QEMUD_WARN, _("Unable to close logfile: %s\n"),
868 869 870 871
                 strerror(errno));
    return ret;
}

872 873
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
874
                    virDomainObjPtr vm) {
875 876 877 878 879 880
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
881
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
882 883 884 885 886
        vm->nvcpupids = 1;
    else
        vm->nvcpupids = vm->def->vcpus;

    if (VIR_ALLOC_N(vm->vcpupids, vm->nvcpupids) < 0) {
887
        virReportOOMError(conn);
888 889 890
        return -1;
    }

891
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
892 893 894 895
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

896
    if (qemudMonitorCommand(vm, "info cpus", &qemucpus) < 0) {
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 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
        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;

955
    VIR_FREE(qemucpus);
956 957 958 959
    return 0;

error:
    VIR_FREE(vm->vcpupids);
960 961
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
962 963 964 965 966 967 968 969

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

970 971
static int
qemudInitCpus(virConnectPtr conn,
D
Daniel Veillard 已提交
972 973
              virDomainObjPtr vm,
              const char *migrateFrom) {
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    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 已提交
989 990 991 992 993 994
    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++)
995
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
996
    }
997 998 999 1000

    for (i = 0 ; i < vm->nvcpupids ; i++) {
        if (sched_setaffinity(vm->vcpupids[i],
                              sizeof(mask), &mask) < 0) {
1001 1002
            virReportSystemError(conn, errno, "%s",
                                 _("failed to set CPU affinity"));
1003 1004 1005 1006 1007
            return -1;
        }
    }
#endif /* HAVE_SCHED_GETAFFINITY */

D
Daniel Veillard 已提交
1008 1009
    if (migrateFrom == NULL) {
        /* Allow the CPUS to start executing */
1010
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
D
Daniel Veillard 已提交
1011 1012 1013 1014 1015
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("resume operation failed"));
            return -1;
        }
        VIR_FREE(info);
1016 1017 1018 1019 1020 1021
    }

    return 0;
}


1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
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 &&
        vm->def->graphics->data.vnc.passwd) {

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


1055
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    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;
}

1091 1092 1093
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

1094 1095
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
1096
                              virDomainObjPtr vm,
1097 1098
                              const char *migrateFrom,
                              int stdin_fd) {
1099
    const char **argv = NULL, **tmp;
1100
    const char **progenv = NULL;
1101
    int i, ret;
1102
    struct stat sb;
1103 1104
    int *tapfds = NULL;
    int ntapfds = 0;
1105
    unsigned int qemuCmdFlags;
1106
    fd_set keepfd;
1107
    const char *emulator;
G
Guido Günther 已提交
1108
    pid_t child;
1109
    int pos = -1;
1110 1111

    FD_ZERO(&keepfd);
1112

1113
    if (virDomainIsActive(vm)) {
1114
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1115
                         "%s", _("VM is already active"));
1116 1117 1118
        return -1;
    }

1119 1120 1121
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
1122
        int port = qemudNextFreeVNCPort(driver);
1123
        if (port < 0) {
1124
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1125
                             "%s", _("Unable to find an unused VNC port"));
1126 1127
            return -1;
        }
1128 1129
        vm->def->graphics->data.vnc.port = port;
    }
1130

1131
    if (virFileMakePath(driver->logDir) < 0) {
1132 1133 1134
        virReportSystemError(conn, errno,
                             _("cannot create log directory %s"),
                             driver->logDir);
1135 1136 1137
        return -1;
    }

1138
    if((vm->logfile = qemudLogFD(conn, driver->logDir, vm->def->name)) < 0)
1139 1140
        return -1;

1141 1142 1143 1144 1145 1146
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

1147 1148 1149 1150
    /* 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
     */
1151
    if (stat(emulator, &sb) < 0) {
1152 1153 1154
        virReportSystemError(conn, errno,
                             _("Cannot find QEMU binary %s"),
                             emulator);
1155 1156 1157
        return -1;
    }

1158
    if (qemudExtractVersionInfo(emulator,
1159 1160 1161 1162
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
1163
                         emulator);
1164 1165
        return -1;
    }
1166

1167
    vm->def->id = driver->nextvmid++;
1168
    if (qemudBuildCommandLine(conn, driver, vm,
1169
                              qemuCmdFlags, &argv, &progenv,
1170
                              &tapfds, &ntapfds, migrateFrom) < 0) {
1171
        close(vm->logfile);
1172
        vm->def->id = -1;
1173 1174 1175 1176
        vm->logfile = -1;
        return -1;
    }

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
    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++;
    }
1187 1188
    tmp = argv;
    while (*tmp) {
1189
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
1190
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1191
                     errno, strerror(errno));
1192
        if (safewrite(vm->logfile, " ", 1) < 0)
1193
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1194 1195 1196
                     errno, strerror(errno));
        tmp++;
    }
1197
    if (safewrite(vm->logfile, "\n", 1) < 0)
1198
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1199 1200
                 errno, strerror(errno));

1201 1202 1203
    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));
1204

1205 1206 1207
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

G
Guido Günther 已提交
1208
    ret = virExec(conn, argv, progenv, &keepfd, &child,
1209
                  stdin_fd, &vm->logfile, &vm->logfile,
G
Guido Günther 已提交
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
                  VIR_EXEC_NONBLOCK | VIR_EXEC_DAEMON);

    /* wait for qemu process to to show up */
    if (ret == 0) {
        int retries = 100;
        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);
    }

    if (ret == 0) {
1226
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
G
Guido Günther 已提交
1227
    } else
1228
        vm->def->id = -1;
1229

1230
    for (i = 0 ; argv[i] ; i++)
1231 1232
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
1233

1234 1235 1236 1237
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

1238 1239 1240
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
1241
        }
1242
        VIR_FREE(tapfds);
1243 1244
    }

1245
    if (ret == 0) {
1246
        if ((qemudWaitForMonitor(conn, driver, vm, pos) < 0) ||
1247
            (qemudDetectVcpuPIDs(conn, vm) < 0) ||
1248 1249
            (qemudInitCpus(conn, vm, migrateFrom) < 0) ||
            (qemudInitPasswords(conn, driver, vm) < 0)) {
1250 1251 1252
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
1253
    }
1254
    qemudSaveDomainStatus(conn, qemu_driver, vm);
1255

1256
    return ret;
1257 1258 1259
}


1260
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
1261 1262
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
1263
        return;
1264

1265
    qemudLog(QEMUD_INFO, _("Shutting down VM '%s'\n"), vm->def->name);
1266

G
Guido Günther 已提交
1267 1268 1269 1270
    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));
1271

1272
    virEventRemoveHandle(vm->monitor_watch);
1273 1274

    if (close(vm->logfile) < 0)
1275
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
1276
                 errno, strerror(errno));
1277 1278 1279 1280 1281
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
    vm->monitor = -1;

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

G
Guido Günther 已提交
1285
    qemudRemoveDomainStatus(conn, driver, vm);
1286
    vm->pid = -1;
1287
    vm->def->id = -1;
1288
    vm->state = VIR_DOMAIN_SHUTOFF;
1289
    VIR_FREE(vm->vcpupids);
1290
    vm->nvcpupids = 0;
1291 1292

    if (vm->newDef) {
1293
        virDomainDefFree(vm->def);
1294
        vm->def = vm->newDef;
1295
        vm->def->id = -1;
1296 1297 1298 1299 1300
        vm->newDef = NULL;
    }
}


1301
static void
1302
qemudDispatchVMEvent(int watch, int fd, int events, void *opaque) {
1303
    struct qemud_driver *driver = opaque;
1304
    virDomainObjPtr vm = NULL;
1305
    virDomainEventPtr event = NULL;
1306
    unsigned int i;
1307
    int quit = 0, failed = 0;
1308

1309
    qemuDriverLock(driver);
1310
    for (i = 0 ; i < driver->domains.count ; i++) {
1311 1312 1313
        virDomainObjPtr tmpvm = driver->domains.objs[i];
        virDomainObjLock(tmpvm);
        if (virDomainIsActive(tmpvm) &&
1314
            tmpvm->monitor_watch == watch) {
1315
            vm = tmpvm;
1316
            break;
1317
        }
1318
        virDomainObjUnlock(tmpvm);
1319 1320 1321
    }

    if (!vm)
1322
        goto cleanup;
1323

1324
    if (vm->monitor != fd) {
1325 1326
        failed = 1;
    } else {
1327
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
1328
            quit = 1;
1329 1330 1331 1332
        else {
            qemudLog(QEMUD_ERROR, _("unhandled fd event %d for %s"),
                                    events, vm->def->name);
            failed = 1;
1333
        }
1334 1335
    }

1336
    if (failed || quit) {
1337 1338 1339 1340 1341
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         quit ?
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN :
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
        qemudShutdownVMDaemon(NULL, driver, vm);
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains,
                                    vm);
            vm = NULL;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1353 1354
    if (event)
        qemuDomainEventQueue(driver, event);
1355
    qemuDriverUnlock(driver);
1356 1357
}

1358
static int
1359 1360 1361 1362 1363
qemudMonitorCommandExtra(const virDomainObjPtr vm,
                         const char *cmd,
                         const char *extra,
                         const char *extraPrompt,
                         char **reply) {
D
Daniel P. Berrange 已提交
1364 1365
    int size = 0;
    char *buf = NULL;
1366
    size_t cmdlen = strlen(cmd);
1367
    size_t extralen = extra ? strlen(extra) : 0;
D
Daniel P. Berrange 已提交
1368

1369 1370 1371
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
        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 已提交
1384

1385 1386
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1387 1388 1389 1390 1391
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1392
                goto error;
1393
            }
1394
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1395 1396
                goto error;

D
Daniel P. Berrange 已提交
1397 1398 1399 1400
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1401

D
Daniel P. Berrange 已提交
1402
        /* Look for QEMU prompt to indicate completion */
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
        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 已提交
1428

1429 1430
                break;
            }
D
Daniel P. Berrange 已提交
1431 1432 1433 1434 1435 1436
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1437
            goto error;
D
Daniel P. Berrange 已提交
1438 1439 1440
        }
    }

1441 1442
    /* Log, but ignore failures to write logfile for VM */
    if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1443
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1444 1445
                 strerror(errno));

D
Daniel P. Berrange 已提交
1446 1447
    *reply = buf;
    return 0;
1448 1449 1450 1451 1452

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1453
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1454
                     strerror(errno));
1455
        VIR_FREE(buf);
1456 1457
    }
    return -1;
D
Daniel P. Berrange 已提交
1458 1459
}

1460 1461 1462 1463 1464 1465 1466 1467
static int
qemudMonitorCommand(const virDomainObjPtr vm,
                    const char *cmd,
                    char **reply) {
    return qemudMonitorCommandExtra(vm, cmd, NULL, NULL, reply);
}


1468 1469 1470 1471 1472 1473
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
1474
static int qemudProbe(void)
1475 1476 1477
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
G
Guido Günther 已提交
1478
        (virFileExists("/usr/bin/kvm")) ||
1479 1480 1481 1482
        (virFileExists("/usr/bin/xenner")))
        return 1;

    return 0;
1483
}
1484

1485
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1486
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1487
                                  int flags ATTRIBUTE_UNUSED) {
1488 1489 1490
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1491
        goto decline;
1492

1493 1494 1495 1496 1497 1498
    if (!qemudProbe())
        goto decline;

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "qemu:///session" : "qemu:///system");
        if (!conn->uri) {
1499
            virReportOOMError(conn);
1500 1501 1502 1503
            return VIR_DRV_OPEN_ERROR;
        }
    } else if (conn->uri->scheme == NULL ||
               conn->uri->path == NULL)
1504 1505
        goto decline;

1506
    if (STRNEQ (conn->uri->scheme, "qemu"))
1507 1508
        goto decline;

1509
    if (uid != 0) {
1510
        if (STRNEQ (conn->uri->path, "/session"))
1511
            goto decline;
1512
    } else { /* root */
1513 1514
        if (STRNEQ (conn->uri->path, "/system") &&
            STRNEQ (conn->uri->path, "/session"))
1515
            goto decline;
1516 1517 1518 1519 1520
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1521 1522

 decline:
1523
    return VIR_DRV_OPEN_DECLINED;
1524 1525 1526
}

static int qemudClose(virConnectPtr conn) {
1527
    struct qemud_driver *driver = conn->privateData;
1528 1529 1530

    /* Get rid of callbacks registered for this conn */
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
1531 1532 1533 1534 1535 1536

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
/* 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;
    }
}

1547
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1548
    return "QEMU";
1549 1550
}

1551 1552 1553 1554 1555

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

    int r, fd;
1556

1557 1558
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1559
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
        return maxvcpus;
    }

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

    close(fd);
    return maxvcpus;
}


1572
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1573 1574 1575
    if (!type)
        return 16;

1576
    if (STRCASEEQ(type, "qemu"))
1577 1578
        return 16;

1579
    if (STRCASEEQ(type, "kvm"))
1580
        return kvmGetMaxVCPUs();
1581

1582
    if (STRCASEEQ(type, "kqemu"))
1583
        return 1;
1584 1585 1586

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1587 1588 1589
    return -1;
}

1590 1591 1592
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1593 1594 1595
}


1596
static char *qemudGetCapabilities(virConnectPtr conn) {
1597
    struct qemud_driver *driver = conn->privateData;
1598
    char *xml;
1599

1600
    qemuDriverLock(driver);
1601
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1602
        virReportOOMError(conn);
1603
    qemuDriverUnlock(driver);
1604

1605
    return xml;
1606 1607 1608
}


1609 1610 1611 1612 1613 1614 1615 1616
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
1617
    int ret = -1;
1618 1619 1620 1621

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1622
        goto cleanup;
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
    }
    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"));
1633
            goto cleanup;
1634 1635 1636
        }
        freeMems[numCells++] = mem;
    }
1637 1638 1639 1640
    ret = numCells;

cleanup:
    return ret;
1641 1642 1643 1644 1645
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
1646
    unsigned long long freeMem = -1;
1647
    int n;
1648

1649 1650 1651
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1652
        goto cleanup;
1653 1654 1655 1656 1657 1658 1659
    }

    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"));
1660
            goto cleanup;
1661 1662 1663 1664
        }
        freeMem += mem;
    }

1665
cleanup:
1666 1667 1668 1669
    return freeMem;
}

#endif
1670

D
Daniel P. Berrange 已提交
1671 1672 1673
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1674
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1675 1676 1677 1678 1679 1680

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

    if (!(pidinfo = fopen(proc, "r"))) {
1681
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1682 1683 1684 1685 1686
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1687
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1688
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1689 1690 1691 1692 1693 1694 1695 1696
        return -1;
    }

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

1699
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1700 1701 1702 1703 1704 1705 1706

    fclose(pidinfo);

    return 0;
}


1707
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1708
                                          int id) {
1709 1710 1711 1712
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1713
    qemuDriverLock(driver);
1714
    vm  = virDomainFindByID(&driver->domains, id);
1715
    qemuDriverUnlock(driver);
1716 1717

    if (!vm) {
1718
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1719
        goto cleanup;
1720 1721
    }

1722
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1723
    if (dom) dom->id = vm->def->id;
1724 1725

cleanup:
1726 1727
    if (vm)
        virDomainObjUnlock(vm);
1728 1729
    return dom;
}
1730

1731
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1732
                                            const unsigned char *uuid) {
1733 1734 1735
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1736

1737
    qemuDriverLock(driver);
1738
    vm = virDomainFindByUUID(&driver->domains, uuid);
1739 1740
    qemuDriverUnlock(driver);

1741
    if (!vm) {
1742
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1743
        goto cleanup;
1744 1745
    }

1746
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1747
    if (dom) dom->id = vm->def->id;
1748 1749

cleanup:
1750 1751
    if (vm)
        virDomainObjUnlock(vm);
1752 1753
    return dom;
}
1754

1755
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1756
                                            const char *name) {
1757 1758 1759
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1760

1761
    qemuDriverLock(driver);
1762
    vm = virDomainFindByName(&driver->domains, name);
1763 1764
    qemuDriverUnlock(driver);

1765
    if (!vm) {
1766
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1767
        goto cleanup;
1768 1769
    }

1770
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1771
    if (dom) dom->id = vm->def->id;
1772 1773

cleanup:
1774 1775
    if (vm)
        virDomainObjUnlock(vm);
1776 1777 1778
    return dom;
}

1779
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1780 1781 1782
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1783
    qemuDriverLock(driver);
1784
    if (qemudExtractVersion(conn, driver) < 0)
1785
        goto cleanup;
1786

1787
    *version = qemu_driver->qemuVersion;
1788 1789 1790
    ret = 0;

cleanup:
1791
    qemuDriverUnlock(driver);
1792
    return ret;
D
Daniel P. Berrange 已提交
1793 1794
}

1795 1796 1797
static char *
qemudGetHostname (virConnectPtr conn)
{
1798
    char *result;
1799

1800 1801
    result = virGetHostname();
    if (result == NULL) {
1802 1803 1804 1805 1806
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return NULL;
    }
    /* Caller frees this string. */
1807
    return result;
1808 1809
}

1810
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1811
    struct qemud_driver *driver = conn->privateData;
1812 1813
    int got = 0, i;

1814 1815 1816
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1817 1818
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
1819 1820 1821
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1822

D
Daniel P. Berrange 已提交
1823 1824
    return got;
}
1825

1826
static int qemudNumDomains(virConnectPtr conn) {
1827
    struct qemud_driver *driver = conn->privateData;
1828 1829
    int n = 0, i;

1830 1831 1832
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1833
        if (virDomainIsActive(driver->domains.objs[i]))
1834
            n++;
1835 1836 1837
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1838

1839
    return n;
D
Daniel P. Berrange 已提交
1840
}
1841

1842
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1843
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1844
    struct qemud_driver *driver = conn->privateData;
1845
    virDomainDefPtr def;
1846
    virDomainObjPtr vm = NULL;
1847
    virDomainPtr dom = NULL;
1848
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1849

1850
    qemuDriverLock(driver);
1851 1852
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1853
        goto cleanup;
1854

1855
    vm = virDomainFindByName(&driver->domains, def->name);
1856
    if (vm) {
1857
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1858
                         _("domain '%s' is already defined"),
1859
                         def->name);
1860
        goto cleanup;
1861
    }
1862
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1863 1864 1865 1866 1867
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1868
                         _("domain with uuid '%s' is already defined"),
1869
                         uuidstr);
1870
        goto cleanup;
1871
    }
1872

1873 1874
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1875 1876 1877 1878
                                  def)))
        goto cleanup;

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

1880
    if (qemudStartVMDaemon(conn, driver, vm, NULL, -1) < 0) {
1881 1882
        virDomainRemoveInactive(&driver->domains,
                                vm);
1883
        vm = NULL;
1884
        goto cleanup;
D
Daniel P. Berrange 已提交
1885
    }
1886 1887 1888 1889

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

1891
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1892
    if (dom) dom->id = vm->def->id;
1893 1894 1895

cleanup:
    virDomainDefFree(def);
1896 1897
    if (vm)
        virDomainObjUnlock(vm);
1898 1899
    if (event)
        qemuDomainEventQueue(driver, event);
1900
    qemuDriverUnlock(driver);
1901
    return dom;
D
Daniel P. Berrange 已提交
1902 1903 1904
}


1905
static int qemudDomainSuspend(virDomainPtr dom) {
1906
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1907
    char *info;
1908 1909
    virDomainObjPtr vm;
    int ret = -1;
1910
    virDomainEventPtr event = NULL;
1911

1912
    qemuDriverLock(driver);
1913
    vm = virDomainFindByID(&driver->domains, dom->id);
1914 1915
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1916
    if (!vm) {
1917
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
1918
        goto cleanup;
D
Daniel P. Berrange 已提交
1919
    }
1920
    if (!virDomainIsActive(vm)) {
1921 1922
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1923
        goto cleanup;
D
Daniel P. Berrange 已提交
1924
    }
1925
    if (vm->state != VIR_DOMAIN_PAUSED) {
1926
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
1927 1928 1929 1930 1931 1932
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("suspend operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
1933 1934 1935
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
1936
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1937
    }
1938
    qemudSaveDomainStatus(dom->conn, driver, vm);
1939 1940 1941
    ret = 0;

cleanup:
1942 1943
    if (vm)
        virDomainObjUnlock(vm);
1944 1945 1946 1947 1948 1949

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1950
    return ret;
D
Daniel P. Berrange 已提交
1951 1952 1953
}


1954
static int qemudDomainResume(virDomainPtr dom) {
1955
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1956
    char *info;
1957 1958
    virDomainObjPtr vm;
    int ret = -1;
1959
    virDomainEventPtr event = NULL;
1960

1961
    qemuDriverLock(driver);
1962
    vm = virDomainFindByID(&driver->domains, dom->id);
1963 1964
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1965
    if (!vm) {
1966 1967
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1968
        goto cleanup;
D
Daniel P. Berrange 已提交
1969
    }
1970
    if (!virDomainIsActive(vm)) {
1971 1972
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1973
        goto cleanup;
D
Daniel P. Berrange 已提交
1974
    }
1975
    if (vm->state == VIR_DOMAIN_PAUSED) {
1976
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
1977 1978 1979 1980 1981 1982
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("resume operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;
        qemudDebug("Reply %s", info);
1983 1984 1985
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
1986
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1987
    }
1988
    qemudSaveDomainStatus(dom->conn, driver, vm);
1989 1990 1991
    ret = 0;

cleanup:
1992 1993
    if (vm)
        virDomainObjUnlock(vm);
1994 1995 1996 1997 1998
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1999
    return ret;
D
Daniel P. Berrange 已提交
2000 2001 2002
}


2003
static int qemudDomainShutdown(virDomainPtr dom) {
2004 2005
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2006
    char* info;
2007
    int ret = -1;
2008

2009
    qemuDriverLock(driver);
2010
    vm = virDomainFindByID(&driver->domains, dom->id);
2011 2012
    qemuDriverUnlock(driver);

2013 2014
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2015
                         _("no domain with matching id %d"), dom->id);
2016
        goto cleanup;
2017 2018
    }

2019
    if (qemudMonitorCommand(vm, "system_powerdown", &info) < 0) {
2020
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2021
                         "%s", _("shutdown operation failed"));
2022
        goto cleanup;
2023
    }
D
Daniel Veillard 已提交
2024
    VIR_FREE(info);
2025 2026 2027
    ret = 0;

cleanup:
2028 2029
    if (vm)
        virDomainObjUnlock(vm);
2030
    return ret;
2031 2032 2033
}


2034
static int qemudDomainDestroy(virDomainPtr dom) {
2035 2036 2037
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2038
    virDomainEventPtr event = NULL;
2039

2040
    qemuDriverLock(driver);
2041
    vm  = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
2042
    if (!vm) {
2043
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2044
                         _("no domain with matching id %d"), dom->id);
2045
        goto cleanup;
D
Daniel P. Berrange 已提交
2046
    }
2047

2048
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2049 2050 2051
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
2052
    if (!vm->persistent) {
2053 2054
        virDomainRemoveInactive(&driver->domains,
                                vm);
2055 2056
        vm = NULL;
    }
2057 2058 2059
    ret = 0;

cleanup:
2060 2061
    if (vm)
        virDomainObjUnlock(vm);
2062 2063
    if (event)
        qemuDomainEventQueue(driver, event);
2064
    qemuDriverUnlock(driver);
2065
    return ret;
D
Daniel P. Berrange 已提交
2066 2067 2068
}


2069
static char *qemudDomainGetOSType(virDomainPtr dom) {
2070 2071 2072
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
2073

2074
    qemuDriverLock(driver);
2075
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2076
    qemuDriverUnlock(driver);
2077 2078
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2079
                         "%s", _("no domain with matching uuid"));
2080
        goto cleanup;
2081 2082
    }

2083
    if (!(type = strdup(vm->def->os.type)))
2084
        virReportOOMError(dom->conn);
2085 2086

cleanup:
2087 2088
    if (vm)
        virDomainObjUnlock(vm);
2089 2090 2091
    return type;
}

2092 2093
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
2094 2095 2096
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
2097

2098
    qemuDriverLock(driver);
2099
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2100 2101
    qemuDriverUnlock(driver);

2102
    if (!vm) {
2103 2104 2105
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2106
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2107
                         _("no domain with matching uuid '%s'"), uuidstr);
2108
        goto cleanup;
2109 2110
    }

2111 2112 2113
    ret = vm->def->maxmem;

cleanup:
2114 2115
    if (vm)
        virDomainObjUnlock(vm);
2116
    return ret;
2117 2118 2119
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
2120 2121 2122
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2123

2124
    qemuDriverLock(driver);
2125
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2126 2127
    qemuDriverUnlock(driver);

2128
    if (!vm) {
2129 2130 2131
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2132
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2133
                         _("no domain with matching uuid '%s'"), uuidstr);
2134
        goto cleanup;
2135 2136 2137 2138
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2139
                         "%s", _("cannot set max memory lower than current memory"));
2140
        goto cleanup;;
2141 2142 2143
    }

    vm->def->maxmem = newmax;
2144 2145 2146
    ret = 0;

cleanup:
2147 2148
    if (vm)
        virDomainObjUnlock(vm);
2149
    return ret;
2150 2151 2152
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
2153 2154 2155
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2156

2157
    qemuDriverLock(driver);
2158
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2159
    qemuDriverUnlock(driver);
2160
    if (!vm) {
2161 2162 2163
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2164
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2165
                         _("no domain with matching uuid '%s'"), uuidstr);
2166
        goto cleanup;
2167 2168
    }

2169
    if (virDomainIsActive(vm)) {
2170
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
2171
                         "%s", _("cannot set memory of an active domain"));
2172
        goto cleanup;
2173 2174 2175 2176
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2177
                         "%s", _("cannot set memory higher than max memory"));
2178
        goto cleanup;
2179 2180 2181
    }

    vm->def->memory = newmem;
2182 2183 2184
    ret = 0;

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

2190
static int qemudDomainGetInfo(virDomainPtr dom,
2191
                              virDomainInfoPtr info) {
2192 2193 2194 2195
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

2196
    qemuDriverLock(driver);
2197
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2198
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2199
    if (!vm) {
2200 2201
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2202
        goto cleanup;
D
Daniel P. Berrange 已提交
2203 2204
    }

2205
    info->state = vm->state;
D
Daniel P. Berrange 已提交
2206

2207
    if (!virDomainIsActive(vm)) {
2208
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2209
    } else {
2210
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
2211
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
2212
            goto cleanup;
D
Daniel P. Berrange 已提交
2213 2214 2215
        }
    }

2216 2217 2218
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
2219 2220 2221
    ret = 0;

cleanup:
2222 2223
    if (vm)
        virDomainObjUnlock(vm);
2224
    return ret;
D
Daniel P. Berrange 已提交
2225 2226 2227
}


D
Daniel P. Berrange 已提交
2228
static char *qemudEscape(const char *in, int shell)
2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
{
    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 已提交
2250 2251 2252 2253
            if (shell)
                len += 5;
            else
                len += 1;
2254 2255 2256 2257 2258 2259 2260
            break;
        default:
            len += 1;
            break;
        }
    }

2261
    if (VIR_ALLOC_N(out, len + 1) < 0)
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
        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 已提交
2280 2281 2282 2283 2284 2285 2286 2287 2288
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

2300 2301 2302 2303 2304
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
2305 2306 2307 2308
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
2309

2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
#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];
};

2321
static int qemudDomainSave(virDomainPtr dom,
2322
                           const char *path) {
2323 2324 2325 2326 2327 2328 2329
    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;
2330
    struct qemud_save_header header;
2331
    int ret = -1;
2332
    virDomainEventPtr event = NULL;
2333 2334 2335 2336 2337

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

2338
    qemuDriverLock(driver);
2339 2340
    vm = virDomainFindByID(&driver->domains, dom->id);

D
Daniel P. Berrange 已提交
2341
    if (!vm) {
2342
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2343
                         _("no domain with matching id %d"), dom->id);
2344
        goto cleanup;
D
Daniel P. Berrange 已提交
2345
    }
2346

2347
    if (!virDomainIsActive(vm)) {
2348
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2349
                         "%s", _("domain is not running"));
2350
        goto cleanup;
D
Daniel P. Berrange 已提交
2351
    }
2352 2353 2354 2355

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
2356
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
2357
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2358
                             "%s", _("suspend operation failed"));
2359
            goto cleanup;
2360
        }
2361 2362 2363
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
        VIR_FREE(info);
2364 2365 2366
    }

    /* Get XML for the domain */
2367
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2368 2369
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2370
                         "%s", _("failed to get domain xml"));
2371
        goto cleanup;
2372 2373 2374 2375 2376 2377
    }
    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,
2378
                         _("failed to create '%s'"), path);
2379
        goto cleanup;
2380 2381 2382 2383
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2384
                         "%s", _("failed to write save header"));
2385
        goto cleanup;
2386 2387 2388 2389
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2390
                         "%s", _("failed to write xml"));
2391
        goto cleanup;
2392 2393
    }

2394
    if (close(fd) < 0) {
2395 2396 2397
        virReportSystemError(dom->conn, errno,
                             _("unable to save file %s"),
                             path);
2398 2399 2400
        goto cleanup;
    }
    fd = -1;
2401 2402 2403 2404 2405

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2406
                         "%s", _("out of memory"));
2407
        goto cleanup;
2408
    }
2409
    if (virAsprintf(&command, "migrate \"exec:"
2410
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
2411
                  "\"", safe_path) == -1) {
2412
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2413
                         "%s", _("out of memory"));
2414 2415
        command = NULL;
        goto cleanup;
2416 2417
    }

2418
    if (qemudMonitorCommand(vm, command, &info) < 0) {
2419
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2420
                         "%s", _("migrate operation failed"));
2421
        goto cleanup;
2422 2423
    }

2424 2425 2426 2427 2428 2429 2430 2431
    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"));
2432
        goto cleanup;
2433 2434
    }

2435 2436
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2437 2438 2439
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2440
    if (!vm->persistent) {
2441 2442
        virDomainRemoveInactive(&driver->domains,
                                vm);
2443 2444
        vm = NULL;
    }
2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
    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);
2456 2457
    if (vm)
        virDomainObjUnlock(vm);
2458 2459
    if (event)
        qemuDomainEventQueue(driver, event);
2460
    qemuDriverUnlock(driver);
2461
    return ret;
D
Daniel P. Berrange 已提交
2462 2463 2464
}


2465
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
2466 2467
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2468
    int max;
2469
    int ret = -1;
2470

2471
    qemuDriverLock(driver);
2472
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2473 2474
    qemuDriverUnlock(driver);

2475
    if (!vm) {
2476 2477 2478
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2479
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2480
                         _("no domain with matching uuid '%s'"), uuidstr);
2481
        goto cleanup;
2482 2483
    }

2484
    if (virDomainIsActive(vm)) {
2485
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
2486
                         _("cannot change vcpu count of an active domain"));
2487
        goto cleanup;
2488 2489 2490 2491 2492
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
2493
        goto cleanup;
2494 2495 2496 2497 2498 2499
    }

    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);
2500
        goto cleanup;
2501 2502 2503
    }

    vm->def->vcpus = nvcpus;
2504 2505 2506
    ret = 0;

cleanup:
2507 2508
    if (vm)
        virDomainObjUnlock(vm);
2509
    return ret;
2510 2511
}

2512 2513 2514 2515 2516 2517 2518

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2519 2520
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2521 2522 2523
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;
2524
    int ret = -1;
2525

2526
    qemuDriverLock(driver);
2527
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2528 2529
    qemuDriverUnlock(driver);

2530
    if (!virDomainIsActive(vm)) {
2531 2532
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2533
        goto cleanup;
2534 2535 2536 2537 2538 2539
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
2540
        goto cleanup;
2541 2542 2543
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2544
        goto cleanup;
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557

    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) {
2558 2559
            virReportSystemError(dom->conn, errno, "%s",
                                 _("cannot set affinity"));
2560
            goto cleanup;
2561 2562 2563 2564
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2565
        goto cleanup;
2566
    }
2567
    ret = 0;
2568

2569
cleanup:
2570 2571
    if (vm)
        virDomainObjUnlock(vm);
2572
    return ret;
2573 2574 2575 2576 2577 2578 2579 2580
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2581 2582
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2583 2584
    virNodeInfo nodeinfo;
    int i, v, maxcpu;
2585
    int ret = -1;
2586

2587
    qemuDriverLock(driver);
2588
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2589 2590
    qemuDriverUnlock(driver);

2591
    if (!virDomainIsActive(vm)) {
2592 2593
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2594
        goto cleanup;
2595 2596 2597
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2598
        goto cleanup;
2599 2600 2601 2602 2603 2604 2605 2606 2607

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

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

2608 2609 2610 2611 2612 2613 2614 2615
    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 */
            }
2616 2617
        }

2618 2619 2620 2621 2622 2623 2624 2625 2626
        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) {
2627 2628
                        virReportSystemError(dom->conn, errno, "%s",
                                             _("cannot get affinity"));
2629 2630 2631 2632 2633 2634
                        goto cleanup;
                    }

                    for (i = 0 ; i < maxcpu ; i++)
                        if (CPU_ISSET(i, &mask))
                            VIR_USE_CPU(cpumap, i);
2635
                }
2636 2637 2638 2639
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
2640 2641 2642
            }
        }
    }
2643
    ret = maxinfo;
2644

2645
cleanup:
2646 2647
    if (vm)
        virDomainObjUnlock(vm);
2648
    return ret;
2649 2650 2651 2652
}
#endif /* HAVE_SCHED_GETAFFINITY */


2653
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
2654 2655
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2656
    const char *type;
2657
    int ret = -1;
2658

2659
    qemuDriverLock(driver);
2660
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2661 2662
    qemuDriverUnlock(driver);

2663
    if (!vm) {
2664 2665 2666
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2667
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2668
                         _("no domain with matching uuid '%s'"), uuidstr);
2669
        goto cleanup;
2670 2671
    }

2672
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2673 2674 2675
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
2676
        goto cleanup;
2677 2678
    }

2679
    ret = qemudGetMaxVCPUs(dom->conn, type);
2680

2681
cleanup:
2682 2683
    if (vm)
        virDomainObjUnlock(vm);
2684 2685 2686 2687
    return ret;
}


2688
static int qemudDomainRestore(virConnectPtr conn,
2689 2690 2691
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
2692
    virDomainObjPtr vm = NULL;
2693 2694 2695
    int fd = -1;
    int ret = -1;
    char *xml = NULL;
2696
    struct qemud_save_header header;
2697
    virDomainEventPtr event = NULL;
2698

2699
    qemuDriverLock(driver);
2700 2701 2702
    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2703
                         "%s", _("cannot read domain image"));
2704
        goto cleanup;
2705 2706 2707 2708
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2709
                         "%s", _("failed to read qemu header"));
2710
        goto cleanup;
2711 2712 2713 2714
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2715
                         "%s", _("image magic is incorrect"));
2716
        goto cleanup;
2717 2718 2719 2720
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2721
                         _("image version is not supported (%d > %d)"),
2722
                         header.version, QEMUD_SAVE_VERSION);
2723
        goto cleanup;
2724 2725
    }

2726
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2727
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2728
                         "%s", _("out of memory"));
2729
        goto cleanup;
2730 2731 2732 2733
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2734
                         "%s", _("failed to read XML"));
2735
        goto cleanup;
2736 2737 2738
    }

    /* Create a domain from this XML */
2739 2740
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
2741
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2742
                         "%s", _("failed to parse XML"));
2743
        goto cleanup;
2744 2745 2746
    }

    /* Ensure the name and UUID don't already exist in an active VM */
2747
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2748
    if (!vm)
2749
        vm = virDomainFindByName(&driver->domains, def->name);
2750 2751 2752 2753 2754 2755 2756 2757
    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);
        }
2758 2759
    }

2760 2761 2762
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2763
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2764
                         "%s", _("failed to assign new VM"));
2765
        goto cleanup;
2766
    }
2767
    def = NULL;
2768 2769

    /* Set the migration source and start it up. */
2770
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio", fd);
2771
    close(fd);
2772
    fd = -1;
2773
    if (ret < 0) {
2774
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2775
                         "%s", _("failed to start VM"));
2776
        if (!vm->persistent) {
2777 2778
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2779 2780
            vm = NULL;
        }
2781
        goto cleanup;
2782 2783
    }

2784 2785 2786
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
2787

2788 2789 2790
    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2791
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
2792
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2793
                             "%s", _("failed to resume domain"));
2794
            goto cleanup;
2795
        }
2796
        VIR_FREE(info);
2797 2798
        vm->state = VIR_DOMAIN_RUNNING;
    }
2799
    ret = 0;
2800

2801 2802 2803 2804 2805
cleanup:
    virDomainDefFree(def);
    VIR_FREE(xml);
    if (fd != -1)
        close(fd);
2806 2807
    if (vm)
        virDomainObjUnlock(vm);
2808 2809
    if (event)
        qemuDomainEventQueue(driver, event);
2810
    qemuDriverUnlock(driver);
2811
    return ret;
D
Daniel P. Berrange 已提交
2812 2813 2814
}


2815
static char *qemudDomainDumpXML(virDomainPtr dom,
2816
                                int flags ATTRIBUTE_UNUSED) {
2817 2818 2819 2820
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2821
    qemuDriverLock(driver);
2822
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2823 2824
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
2825
    if (!vm) {
2826 2827
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2828
        goto cleanup;
D
Daniel P. Berrange 已提交
2829 2830
    }

2831 2832 2833 2834 2835 2836
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
2837 2838
    if (vm)
        virDomainObjUnlock(vm);
2839
    return ret;
D
Daniel P. Berrange 已提交
2840 2841 2842
}


2843
static int qemudListDefinedDomains(virConnectPtr conn,
2844
                            char **const names, int nnames) {
2845
    struct qemud_driver *driver = conn->privateData;
2846
    int got = 0, i;
2847

2848
    qemuDriverLock(driver);
2849
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
2850
        virDomainObjLock(driver->domains.objs[i]);
2851 2852
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2853
                virReportOOMError(conn);
2854
                virDomainObjUnlock(driver->domains.objs[i]);
2855 2856
                goto cleanup;
            }
2857
        }
2858
        virDomainObjUnlock(driver->domains.objs[i]);
D
Daniel P. Berrange 已提交
2859
    }
2860

2861
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2862
    return got;
2863 2864 2865

 cleanup:
    for (i = 0 ; i < got ; i++)
2866
        VIR_FREE(names[i]);
2867
    qemuDriverUnlock(driver);
2868
    return -1;
D
Daniel P. Berrange 已提交
2869 2870
}

2871
static int qemudNumDefinedDomains(virConnectPtr conn) {
2872
    struct qemud_driver *driver = conn->privateData;
2873 2874
    int n = 0, i;

2875
    qemuDriverLock(driver);
2876 2877
    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2878
            n++;
2879
    qemuDriverUnlock(driver);
2880

2881
    return n;
D
Daniel P. Berrange 已提交
2882 2883 2884
}


2885
static int qemudDomainStart(virDomainPtr dom) {
2886 2887 2888
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2889
    virDomainEventPtr event = NULL;
2890

2891
    qemuDriverLock(driver);
2892
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2893 2894
    qemuDriverUnlock(driver);

2895
    if (!vm) {
2896
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2897
                         "%s", _("no domain with matching uuid"));
2898
        goto cleanup;
2899 2900
    }

2901
    ret = qemudStartVMDaemon(dom->conn, driver, vm, NULL, -1);
2902
    if (ret != -1)
2903 2904 2905
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
2906 2907

cleanup:
2908 2909
    if (vm)
        virDomainObjUnlock(vm);
2910 2911 2912 2913 2914
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
2915
    return ret;
D
Daniel P. Berrange 已提交
2916 2917 2918
}


2919
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2920
    struct qemud_driver *driver = conn->privateData;
2921
    virDomainDefPtr def;
2922
    virDomainObjPtr vm = NULL;
2923
    virDomainPtr dom = NULL;
2924
    virDomainEventPtr event = NULL;
2925
    int newVM = 1;
2926

2927
    qemuDriverLock(driver);
2928 2929
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
2930
        goto cleanup;
2931

2932
    vm = virDomainFindByName(&driver->domains, def->name);
2933 2934
    if (vm) {
        virDomainObjUnlock(vm);
2935
        newVM = 0;
2936
    }
2937

2938 2939 2940 2941
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2942
        goto cleanup;
2943
    }
2944
    vm->persistent = 1;
2945

2946 2947
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2948
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2949 2950
        virDomainRemoveInactive(&driver->domains,
                                vm);
2951
        vm = NULL;
2952
        goto cleanup;
2953 2954
    }

2955 2956 2957 2958 2959
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
2960

2961
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2962
    if (dom) dom->id = vm->def->id;
2963 2964

cleanup:
2965 2966
    if (vm)
        virDomainObjUnlock(vm);
2967 2968
    if (event)
        qemuDomainEventQueue(driver, event);
2969
    qemuDriverUnlock(driver);
2970
    return dom;
D
Daniel P. Berrange 已提交
2971 2972
}

2973
static int qemudDomainUndefine(virDomainPtr dom) {
2974 2975
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2976
    virDomainEventPtr event = NULL;
2977
    int ret = -1;
D
Daniel P. Berrange 已提交
2978

2979
    qemuDriverLock(driver);
2980
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2981

D
Daniel P. Berrange 已提交
2982
    if (!vm) {
2983 2984
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2985
        goto cleanup;
D
Daniel P. Berrange 已提交
2986 2987
    }

2988
    if (virDomainIsActive(vm)) {
2989 2990
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
2991
        goto cleanup;
D
Daniel P. Berrange 已提交
2992 2993
    }

2994 2995 2996
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
2997
        goto cleanup;
2998 2999 3000
    }

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

3003 3004 3005
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
3006

3007 3008
    virDomainRemoveInactive(&driver->domains,
                            vm);
3009
    vm = NULL;
3010
    ret = 0;
D
Daniel P. Berrange 已提交
3011

3012
cleanup:
3013 3014
    if (vm)
        virDomainObjUnlock(vm);
3015 3016
    if (event)
        qemuDomainEventQueue(driver, event);
3017
    qemuDriverUnlock(driver);
3018
    return ret;
D
Daniel P. Berrange 已提交
3019 3020
}

3021
/* Return the disks name for use in monitor commands */
3022
static char *qemudDiskDeviceName(const virConnectPtr conn,
3023
                                 const virDomainDiskDefPtr disk) {
3024 3025 3026 3027 3028 3029

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

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
3030
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3031 3032 3033 3034 3035 3036 3037
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
3038
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
3039
                ret = virAsprintf(&devname, "ide%d-hd%d", busid, devid);
3040
            else
3041
                ret = virAsprintf(&devname, "ide%d-cd%d", busid, devid);
3042 3043
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
3044
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
3045
                ret = virAsprintf(&devname, "scsi%d-hd%d", busid, devid);
3046
            else
3047
                ret = virAsprintf(&devname, "scsi%d-cd%d", busid, devid);
3048 3049
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
3050
            ret = virAsprintf(&devname, "floppy%d", devid);
3051 3052
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
3053
            ret = virAsprintf(&devname, "virtio%d", devid);
3054 3055
            break;
        default:
3056
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
3057 3058 3059 3060 3061 3062
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
3063
        virReportOOMError(conn);
3064 3065 3066 3067 3068 3069
        return NULL;
    }

    return devname;
}

3070 3071
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           virDomainObjPtr vm,
3072 3073
                                           virDomainDeviceDefPtr dev)
{
3074
    virDomainDiskDefPtr origdisk = NULL, newdisk;
3075
    char *cmd, *reply, *safe_path;
3076
    char *devname = NULL;
3077
    unsigned int qemuCmdFlags;
3078
    int i;
3079

3080
    origdisk = NULL;
3081
    newdisk = dev->data.disk;
3082 3083 3084 3085
    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];
3086
            break;
3087
        }
3088 3089 3090
    }

    if (!origdisk) {
3091
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3092 3093 3094 3095 3096 3097 3098 3099 3100
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
3101
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3102 3103 3104 3105 3106 3107
                         _("Cannot determine QEMU argv syntax %s"),
                         vm->def->emulator);
        return -1;
    }

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
3108
        if (!(devname = qemudDiskDeviceName(conn, newdisk)))
3109 3110 3111 3112 3113 3114 3115 3116 3117
            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 {
3118
            qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3119 3120 3121 3122 3123 3124 3125 3126
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
3127
            virReportOOMError(conn);
3128 3129 3130
            return -1;
        }
    }
3131

3132
    if (newdisk->src) {
3133 3134
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
3135
            virReportOOMError(conn);
3136
            VIR_FREE(devname);
3137 3138
            return -1;
        }
3139
        if (virAsprintf(&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
3140
            virReportOOMError(conn);
3141
            VIR_FREE(safe_path);
3142
            VIR_FREE(devname);
3143 3144
            return -1;
        }
3145
        VIR_FREE(safe_path);
3146

3147
    } else if (virAsprintf(&cmd, "eject %s", devname) == -1) {
3148
        virReportOOMError(conn);
3149
        VIR_FREE(devname);
3150 3151
        return -1;
    }
3152
    VIR_FREE(devname);
3153

3154
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3155
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3156
                         "%s", _("could not change cdrom media"));
3157
        VIR_FREE(cmd);
3158 3159
        return -1;
    }
3160 3161 3162 3163

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
3164
    DEBUG ("ejectable media change reply: %s", reply);
3165
    if (strstr(reply, "\ndevice ")) {
3166
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3167
                          _("changing cdrom media failed: %s"), reply);
3168 3169 3170 3171
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3172 3173
    VIR_FREE(reply);
    VIR_FREE(cmd);
3174

3175 3176
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
3177
    newdisk->src = NULL;
3178
    origdisk->type = newdisk->type;
3179 3180 3181
    return 0;
}

3182 3183 3184
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
3185 3186
{
    int ret, i;
3187
    char *cmd, *reply, *s;
3188 3189 3190 3191 3192
    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)) {
3193
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3194 3195 3196 3197 3198 3199
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3200
        virReportOOMError(conn);
3201 3202 3203 3204 3205
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3206
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3207 3208 3209 3210
                         "%s", _("out of memory"));
        return -1;
    }

3211 3212
    ret = virAsprintf(&cmd, "pci_add 0 storage file=%s,if=%s",
                      safe_path, type);
3213 3214
    VIR_FREE(safe_path);
    if (ret == -1) {
3215
        virReportOOMError(conn);
3216 3217 3218
        return ret;
    }

3219
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3220
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3221 3222 3223 3224 3225 3226 3227 3228
                         _("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... */
3229 3230 3231 3232 3233 3234
#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 已提交
3235
            qemudLog(QEMUD_WARN, "%s", _("Unable to parse slot number\n"));
3236
    } else {
3237
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251
                          _("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;
}
3252

3253 3254 3255
static int qemudDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                                 virDomainObjPtr vm,
                                                 virDomainDeviceDefPtr dev)
3256
{
3257 3258
    int ret, i;
    char *safe_path;
3259 3260
    char *cmd, *reply;

3261 3262
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3263
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3264 3265 3266 3267 3268
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

3269
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3270
        virReportOOMError(conn);
3271
        return -1;
3272 3273
    }

3274 3275
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3276
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3277 3278 3279 3280
                         "%s", _("out of memory"));
        return -1;
    }

3281
    ret = virAsprintf(&cmd, "usb_add disk:%s", safe_path);
3282
    VIR_FREE(safe_path);
3283
    if (ret == -1) {
3284
        virReportOOMError(conn);
3285 3286 3287
        return ret;
    }

3288
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3289
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3290
                         "%s", _("cannot attach usb disk"));
3291 3292 3293 3294 3295 3296 3297 3298
        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 ")) {
3299
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3300
                          "%s",
3301
                          _("adding usb disk failed"));
3302 3303 3304 3305
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3306

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

3311 3312 3313 3314 3315
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3316 3317 3318
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3319 3320 3321 3322
{
    int ret;
    char *cmd, *reply;

3323
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
3324
        virReportOOMError(conn);
3325 3326
        return -1;
    }
3327

3328
    if (dev->data.hostdev->source.subsys.u.usb.vendor) {
3329 3330 3331
        ret = virAsprintf(&cmd, "usb_add host:%.4x:%.4x",
                          dev->data.hostdev->source.subsys.u.usb.vendor,
                          dev->data.hostdev->source.subsys.u.usb.product);
3332
    } else {
3333 3334 3335
        ret = virAsprintf(&cmd, "usb_add host:%.3d.%.3d",
                          dev->data.hostdev->source.subsys.u.usb.bus,
                          dev->data.hostdev->source.subsys.u.usb.device);
3336 3337
    }
    if (ret == -1) {
3338
        virReportOOMError(conn);
3339 3340 3341
        return -1;
    }

3342
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3343
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3344 3345 3346 3347 3348 3349 3350 3351 3352
                         "%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 ")) {
3353
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3354 3355 3356 3357 3358 3359
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3360

3361
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
3362

3363 3364
    VIR_FREE(reply);
    VIR_FREE(cmd);
3365 3366 3367
    return 0;
}

3368 3369
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
3370 3371 3372 3373
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3374

3375
    qemuDriverLock(driver);
3376
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3377
    if (!vm) {
3378
        qemuDriverUnlock(driver);
3379 3380
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3381
        goto cleanup;
3382 3383 3384
    }

    if (!virDomainIsActive(vm)) {
3385
        qemuDriverUnlock(driver);
3386 3387
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
3388
        goto cleanup;
3389 3390
    }

3391 3392
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
3393
    qemuDriverUnlock(driver);
3394 3395 3396
    if (dev == NULL)
        goto cleanup;

3397

3398 3399
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
3400 3401
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
3402
            ret = qemudDomainChangeEjectableMedia(dom->conn, vm, dev);
3403 3404 3405
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
3406
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, vm, dev);
3407 3408
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
3409
                ret = qemudDomainAttachPciDiskDevice(dom->conn, vm, dev);
3410 3411 3412 3413 3414 3415
            }
            break;
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("this disk device type cannot be attached"));
            goto cleanup;
3416
        }
3417
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
3418 3419
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
3420
        ret = qemudDomainAttachHostDevice(dom->conn, vm, dev);
3421
    } else {
3422
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
3423
                         "%s", _("this device type cannot be attached"));
3424
        goto cleanup;
3425 3426
    }

3427
    qemudSaveDomainStatus(dom->conn, driver, vm);
3428
cleanup:
G
Guido Günther 已提交
3429 3430
    if (ret < 0)
        virDomainDeviceDefFree(dev);
3431 3432
    if (vm)
        virDomainObjUnlock(vm);
3433 3434 3435
    return ret;
}

3436 3437
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3438 3439
{
    int i, ret = -1;
3440 3441
    char *cmd = NULL;
    char *reply = NULL;
3442 3443 3444 3445 3446 3447 3448 3449 3450 3451
    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) {
3452
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3453
                         _("disk %s not found"), dev->data.disk->dst);
3454
        goto cleanup;
3455 3456 3457
    }

    if (detach->slotnum < 1) {
3458
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3459
                         _("disk %s cannot be detached - invalid slot number %d"),
3460
                           detach->dst, detach->slotnum);
3461
        goto cleanup;
3462 3463
    }

3464
    if (virAsprintf(&cmd, "pci_del 0 %d", detach->slotnum) < 0) {
3465
        virReportOOMError(conn);
3466
        goto cleanup;
3467 3468
    }

3469
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3470
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3471
                          _("failed to execute detach disk %s command"), detach->dst);
3472
        goto cleanup;
3473 3474 3475 3476 3477 3478
    }

    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")) {
3479
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3480
                          _("failed to detach disk %s: invalid slot %d"),
3481 3482
                          detach->dst, detach->slotnum);
        goto cleanup;
3483 3484 3485 3486 3487
    }

    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) {
3488
            virReportOOMError(conn);
3489
            goto cleanup;
3490 3491 3492 3493 3494 3495 3496 3497
        }
        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;
3498 3499

cleanup:
3500 3501 3502 3503 3504 3505 3506
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
3507 3508 3509 3510
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3511

3512
    qemuDriverLock(driver);
3513
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3514
    if (!vm) {
3515
        qemuDriverUnlock(driver);
3516 3517
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3518
        goto cleanup;
3519 3520 3521
    }

    if (!virDomainIsActive(vm)) {
3522
        qemuDriverUnlock(driver);
3523
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
G
Guido Günther 已提交
3524
                         "%s", _("cannot detach device on inactive domain"));
3525
        goto cleanup;
3526 3527
    }

3528 3529
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
3530
    qemuDriverUnlock(driver);
3531 3532 3533
    if (dev == NULL)
        goto cleanup;

3534 3535 3536 3537 3538

    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))
3539
        ret = qemudDomainDetachPciDiskDevice(dom->conn, vm, dev);
3540
    else
3541 3542 3543
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

3544
    qemudSaveDomainStatus(dom->conn, driver, vm);
3545 3546
cleanup:
    virDomainDeviceDefFree(dev);
3547 3548
    if (vm)
        virDomainObjUnlock(vm);
3549 3550 3551
    return ret;
}

3552
static int qemudDomainGetAutostart(virDomainPtr dom,
3553
                                   int *autostart) {
3554 3555 3556
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3557

3558
    qemuDriverLock(driver);
3559
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3560 3561
    qemuDriverUnlock(driver);

3562
    if (!vm) {
3563 3564
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3565
        goto cleanup;
3566 3567 3568
    }

    *autostart = vm->autostart;
3569
    ret = 0;
3570

3571
cleanup:
3572 3573
    if (vm)
        virDomainObjUnlock(vm);
3574
    return ret;
3575 3576
}

3577
static int qemudDomainSetAutostart(virDomainPtr dom,
3578
                                   int autostart) {
3579 3580
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3581 3582
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
3583

3584
    qemuDriverLock(driver);
3585
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3586 3587
    qemuDriverUnlock(driver);

3588
    if (!vm) {
3589 3590
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3591
        goto cleanup;
3592 3593
    }

3594 3595 3596
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
3597
        goto cleanup;
3598 3599
    }

3600 3601
    autostart = (autostart != 0);

3602 3603 3604 3605 3606
    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;
3607

3608 3609
        if (autostart) {
            int err;
3610

3611
            if ((err = virFileMakePath(driver->autostartDir))) {
3612 3613 3614
                virReportSystemError(dom->conn, err,
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
3615 3616
                goto cleanup;
            }
3617

3618
            if (symlink(configFile, autostartLink) < 0) {
3619 3620 3621
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
3622 3623 3624 3625
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
3626 3627 3628
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
3629 3630
                goto cleanup;
            }
3631 3632
        }

3633
        vm->autostart = autostart;
3634
    }
3635
    ret = 0;
3636

3637 3638 3639
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
3640 3641
    if (vm)
        virDomainObjUnlock(vm);
3642
    return ret;
3643 3644
}

3645 3646 3647 3648 3649 3650 3651 3652 3653
/* 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)
{
3654
    struct qemud_driver *driver = dom->conn->privateData;
3655
    char *dummy, *info = NULL;
3656
    const char *p, *eol;
3657
    const char *qemu_dev_name = NULL;
3658
    size_t len;
3659
    int i, ret = -1;
3660
    virDomainObjPtr vm;
3661
    virDomainDiskDefPtr disk = NULL;
3662

3663
    qemuDriverLock(driver);
3664
    vm = virDomainFindByID(&driver->domains, dom->id);
3665
    qemuDriverUnlock(driver);
3666 3667 3668
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3669
        goto cleanup;
3670
    }
3671
    if (!virDomainIsActive (vm)) {
3672 3673
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
3674
        goto cleanup;
3675 3676
    }

3677 3678 3679 3680 3681 3682 3683 3684
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
3685 3686
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
3687
        goto cleanup;
3688 3689
    }

3690
    qemu_dev_name = qemudDiskDeviceName(dom->conn, disk);
3691
    if (!qemu_dev_name)
3692
        goto cleanup;
3693 3694
    len = strlen (qemu_dev_name);

3695
    if (qemudMonitorCommand (vm, "info blockstats", &info) < 0) {
3696 3697
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
3698
        goto cleanup;
3699 3700 3701 3702 3703 3704 3705 3706
    }
    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 已提交
3707
    if (strstr(info, "\ninfo ")) {
3708 3709 3710
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
3711
        goto cleanup;
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737
    }

    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) {
3738
                if (STRPREFIX (p, "rd_bytes=")) {
3739 3740 3741
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
3742
                } else if (STRPREFIX (p, "wr_bytes=")) {
3743 3744 3745
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
3746
                } else if (STRPREFIX (p, "rd_operations=")) {
3747 3748 3749
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
3750
                } else if (STRPREFIX (p, "wr_operations=")) {
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761
                    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++;
            }
3762
            ret = 0;
3763
            goto cleanup;
3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
        }

        /* 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);
3775
 cleanup:
3776 3777
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
3778 3779
    if (vm)
        virDomainObjUnlock(vm);
3780
    return ret;
3781 3782
}

3783
#ifdef __linux__
3784 3785 3786 3787 3788
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
3789 3790
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3791
    int i;
3792
    int ret = -1;
3793

3794
    qemuDriverLock(driver);
3795
    vm = virDomainFindByID(&driver->domains, dom->id);
3796 3797
    qemuDriverUnlock(driver);

3798 3799
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
3800
                          _("no domain with matching id %d"), dom->id);
3801
        goto cleanup;
3802 3803
    }

3804
    if (!virDomainIsActive(vm)) {
3805
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3806
                         "%s", _("domain is not running"));
3807
        goto cleanup;
3808 3809 3810 3811
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3812
                         "%s", _("NULL or empty path"));
3813
        goto cleanup;
3814 3815 3816
    }

    /* Check the path is one of the domain's network interfaces. */
3817 3818
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
3819 3820 3821 3822
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
3823 3824
    }

3825 3826 3827 3828 3829
    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);
3830

3831
cleanup:
3832 3833
    if (vm)
        virDomainObjUnlock(vm);
3834 3835
    return ret;
}
3836
#else
3837 3838 3839 3840
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
3841 3842 3843 3844
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
}
3845
#endif
3846

3847 3848 3849 3850 3851 3852 3853
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
3854 3855 3856
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
3857

3858
    qemuDriverLock(driver);
3859
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3860 3861
    qemuDriverUnlock(driver);

3862 3863
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
3864
                          "%s", _("no domain with matching uuid"));
3865
        goto cleanup;
3866 3867 3868 3869
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3870
                         "%s", _("NULL or empty path"));
3871
        goto cleanup;
3872 3873 3874
    }

    /* Check the path belongs to this domain. */
3875 3876
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
3877 3878 3879 3880
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
3881 3882
    }

3883 3884 3885 3886 3887 3888 3889 3890 3891
    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;
        }
3892

3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907
        /* 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"));
3908 3909
    }

3910 3911 3912
cleanup:
    if (fd >= 0)
        close (fd);
3913 3914
    if (vm)
        virDomainObjUnlock(vm);
3915 3916 3917
    return ret;
}

R
Richard W.M. Jones 已提交
3918 3919 3920 3921 3922 3923
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
3924 3925 3926
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char cmd[256], *info = NULL;
R
Richard W.M. Jones 已提交
3927 3928 3929
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

3930
    qemuDriverLock(driver);
3931
    vm = virDomainFindByID(&driver->domains, dom->id);
3932
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
3933 3934 3935 3936

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3937 3938 3939 3940 3941 3942 3943
        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 已提交
3944 3945
    }

3946
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3947 3948
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
3949
        goto cleanup;
R
Richard W.M. Jones 已提交
3950 3951 3952 3953 3954 3955
    }

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

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
3961
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
R
Richard W.M. Jones 已提交
3962
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3963
                          "%s", _("'memsave' command failed"));
3964
        goto cleanup;
R
Richard W.M. Jones 已提交
3965 3966 3967 3968 3969 3970 3971 3972
    }

    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));
3973
        goto cleanup;
R
Richard W.M. Jones 已提交
3974 3975 3976
    }

    ret = 0;
3977 3978 3979

cleanup:
    VIR_FREE(info);
R
Richard W.M. Jones 已提交
3980 3981
    if (fd >= 0) close (fd);
    unlink (tmp);
3982 3983
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
3984 3985 3986
    return ret;
}

3987

3988 3989
static int
qemudDomainEventRegister (virConnectPtr conn,
3990
                          virConnectDomainEventCallback callback,
3991 3992
                          void *opaque,
                          virFreeCallback freecb)
3993
{
3994 3995 3996
    struct qemud_driver *driver = conn->privateData;
    int ret;

3997
    qemuDriverLock(driver);
3998 3999
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
4000
    qemuDriverUnlock(driver);
4001

4002
    return ret;
4003 4004 4005 4006
}

static int
qemudDomainEventDeregister (virConnectPtr conn,
4007
                            virConnectDomainEventCallback callback)
4008
{
4009 4010 4011
    struct qemud_driver *driver = conn->privateData;
    int ret;

4012
    qemuDriverLock(driver);
4013 4014 4015 4016 4017 4018
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
4019
    qemuDriverUnlock(driver);
4020

4021
    return ret;
4022 4023
}

4024 4025 4026 4027 4028
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
                                        virConnectDomainEventCallback cb,
                                        void *cbopaque,
                                        void *opaque)
4029
{
4030
    struct qemud_driver *driver = opaque;
4031

4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075
    /* 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);
4076 4077
}

D
Daniel Veillard 已提交
4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
/* 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;
4096 4097
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
4098 4099 4100 4101 4102
    virDomainObjPtr vm = NULL;
    int this_port;
    char hostname [HOST_NAME_MAX+1];
    char migrateFrom [64];
    const char *p;
4103
    virDomainEventPtr event = NULL;
4104 4105 4106
    int ret = -1;;

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

4108
    qemuDriverLock(driver);
D
Daniel Veillard 已提交
4109 4110 4111
    if (!dom_xml) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                          "%s", _("no domain XML passed"));
4112
        goto cleanup;
D
Daniel Veillard 已提交
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132
    }

    /* 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));
4133
            goto cleanup;
D
Daniel Veillard 已提交
4134 4135 4136
        }

        /* Caller frees */
4137
        if (virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port) < 0) {
4138
            virReportOOMError (dconn);
4139
            goto cleanup;
D
Daniel Veillard 已提交
4140 4141 4142 4143 4144 4145 4146 4147 4148
        }
    } 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"));
4149
            goto cleanup;
D
Daniel Veillard 已提交
4150 4151 4152 4153 4154 4155 4156 4157 4158
        }

        /* 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"));
4159
            goto cleanup;
D
Daniel Veillard 已提交
4160 4161 4162 4163
        }
    }

    /* Parse the domain XML. */
4164 4165
    if (!(def = virDomainDefParseString(dconn, driver->caps, dom_xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
D
Daniel Veillard 已提交
4166 4167
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to parse XML"));
4168
        goto cleanup;
D
Daniel Veillard 已提交
4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184
    }

    /* 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"));
4185
        goto cleanup;
D
Daniel Veillard 已提交
4186 4187 4188 4189 4190 4191 4192 4193 4194
    }
#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);
4195
            goto cleanup;
D
Daniel Veillard 已提交
4196 4197 4198 4199 4200 4201 4202 4203
        }
    }

    if (!(vm = virDomainAssignDef(dconn,
                                  &driver->domains,
                                  def))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to assign new VM"));
4204
        goto cleanup;
D
Daniel Veillard 已提交
4205
    }
4206
    def = NULL;
D
Daniel Veillard 已提交
4207 4208 4209 4210 4211 4212 4213 4214

    /* 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);
4215
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom, -1) < 0) {
D
Daniel Veillard 已提交
4216 4217
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to start listening VM"));
4218
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4219
            virDomainRemoveInactive(&driver->domains, vm);
4220 4221
            vm = NULL;
        }
4222
        goto cleanup;
D
Daniel Veillard 已提交
4223
    }
4224 4225 4226 4227

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

4230 4231 4232 4233 4234
cleanup:
    virDomainDefFree(def);
    if (ret != 0) {
        VIR_FREE(*uri_out);
    }
4235 4236
    if (vm)
        virDomainObjUnlock(vm);
4237 4238
    if (event)
        qemuDomainEventQueue(driver, event);
4239
    qemuDriverUnlock(driver);
4240
    return ret;
D
Daniel Veillard 已提交
4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252
}

/* 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)
{
4253 4254
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4255
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4256 4257
    char *safe_uri;
    char cmd[HOST_NAME_MAX+50];
4258 4259
    char *info = NULL;
    int ret = -1;
D
Daniel Veillard 已提交
4260

4261
    qemuDriverLock(driver);
4262
    vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel Veillard 已提交
4263 4264 4265
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
4266
        goto cleanup;
D
Daniel Veillard 已提交
4267 4268 4269 4270 4271
    }

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

4275 4276 4277
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
        snprintf(cmd, sizeof cmd, "%s", "stop");
4278
        qemudMonitorCommand (vm, cmd, &info);
4279 4280 4281
        DEBUG ("stop reply: %s", info);
        VIR_FREE(info);

4282 4283 4284 4285 4286 4287
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
        event = NULL;
4288 4289
    }

D
Daniel Veillard 已提交
4290 4291 4292
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
4293
        qemudMonitorCommand (vm, cmd, &info);
D
Daniel Veillard 已提交
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303

        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));
4304
        goto cleanup;
D
Daniel Veillard 已提交
4305 4306 4307 4308
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

4309
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
D
Daniel Veillard 已提交
4310 4311
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("migrate operation failed"));
4312
        goto cleanup;
D
Daniel Veillard 已提交
4313 4314 4315 4316 4317 4318 4319 4320
    }

    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);
4321
        goto cleanup;
D
Daniel Veillard 已提交
4322 4323 4324 4325
    }

    /* Clean up the source domain. */
    qemudShutdownVMDaemon (dom->conn, driver, vm);
4326 4327 4328 4329

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
4330
    if (!vm->persistent) {
D
Daniel Veillard 已提交
4331
        virDomainRemoveInactive(&driver->domains, vm);
4332 4333
        vm = NULL;
    }
4334
    ret = 0;
D
Daniel Veillard 已提交
4335

4336 4337
cleanup:
    VIR_FREE(info);
4338 4339
    if (vm)
        virDomainObjUnlock(vm);
4340 4341
    if (event)
        qemuDomainEventQueue(driver, event);
4342
    qemuDriverUnlock(driver);
4343
    return ret;
D
Daniel Veillard 已提交
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
}

/* 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)
{
4356 4357 4358
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4359
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4360 4361
    char *info = NULL;

4362
    qemuDriverLock(driver);
4363
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
4364 4365 4366
    if (!vm) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching name %s"), dname);
4367
        goto cleanup;
D
Daniel Veillard 已提交
4368 4369 4370 4371 4372 4373 4374 4375 4376
    }

    /* 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;
4377 4378 4379
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
D
Daniel Veillard 已提交
4380 4381
    } else {
        qemudShutdownVMDaemon (dconn, driver, vm);
4382 4383 4384
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
4385
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4386
            virDomainRemoveInactive(&driver->domains, vm);
4387 4388
            vm = NULL;
        }
D
Daniel Veillard 已提交
4389
    }
4390 4391

cleanup:
4392 4393
    if (vm)
        virDomainObjUnlock(vm);
4394 4395
    if (event)
        qemuDomainEventQueue(driver, event);
4396
    qemuDriverUnlock(driver);
4397
    return dom;
D
Daniel Veillard 已提交
4398 4399
}

4400 4401 4402 4403 4404
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
4405
    qemudSupportsFeature, /* supports_feature */
4406 4407
    qemudGetType, /* type */
    qemudGetVersion, /* version */
4408
    qemudGetHostname, /* hostname */
4409
    NULL, /* URI  */
4410 4411 4412 4413 4414
    qemudGetMaxVCPUs, /* getMaxVcpus */
    qemudGetNodeInfo, /* nodeGetInfo */
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
4415
    qemudDomainCreate, /* domainCreateXML */
4416 4417 4418 4419 4420
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
4421
    qemudDomainShutdown, /* domainShutdown */
4422 4423 4424
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
4425 4426 4427
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
4428 4429 4430 4431
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
4432
    qemudDomainSetVcpus, /* domainSetVcpus */
4433 4434 4435 4436
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
4437 4438
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
4439
#endif
4440
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
4441 4442 4443 4444 4445 4446
    qemudDomainDumpXML, /* domainDumpXML */
    qemudListDefinedDomains, /* listDomains */
    qemudNumDefinedDomains, /* numOfDomains */
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
4447
    qemudDomainAttachDevice, /* domainAttachDevice */
4448
    qemudDomainDetachDevice, /* domainDetachDevice */
4449 4450 4451 4452 4453
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
4454 4455
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
4456
    NULL, /* domainMigrateFinish */
4457
    qemudDomainBlockStats, /* domainBlockStats */
4458
    qemudDomainInterfaceStats, /* domainInterfaceStats */
4459
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
4460
    qemudDomainMemoryPeek, /* domainMemoryPeek */
4461 4462 4463 4464
#if HAVE_NUMACTL
    qemudNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    qemudNodeGetFreeMemory,  /* getFreeMemory */
#else
4465
    NULL, /* nodeGetCellsFreeMemory */
4466
    NULL, /* getFreeMemory */
4467
#endif
4468 4469
    qemudDomainEventRegister, /* domainEventRegister */
    qemudDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
4470 4471
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
4472 4473 4474
};


4475
static virStateDriver qemuStateDriver = {
4476 4477 4478 4479
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
4480
};
4481

4482
int qemuRegister(void) {
4483 4484 4485 4486
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}