qemu_driver.c 130.3 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 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

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

75 76
static int qemudShutdown(void);

77 78
#define qemudLog(level, msg...) fprintf(stderr, msg)

79 80 81 82 83 84 85 86 87
static void qemuDriverLock(struct qemud_driver *driver)
{
    pthread_mutex_lock(&driver->lock);
}
static void qemuDriverUnlock(struct qemud_driver *driver)
{
    pthread_mutex_unlock(&driver->lock);
}

88 89 90 91 92 93 94 95 96
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 已提交
97
    qemudLog(QEMUD_ERR,
98
             "%s", _("Failed to set close-on-exec file descriptor flag\n"));
99 100 101 102 103 104 105 106 107 108 109 110 111
    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 已提交
112
    qemudLog(QEMUD_ERR,
113
             "%s", _("Failed to set non-blocking file descriptor flag\n"));
114 115 116 117
    return -1;
}


118 119 120 121

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

123 124
static void qemudDispatchVMEvent(int watch,
                                 int fd,
125 126 127
                                 int events,
                                 void *opaque);

128 129
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
130 131
                              virDomainObjPtr vm,
                              const char *migrateFrom);
132

133 134
static void qemudShutdownVMDaemon(virConnectPtr conn,
                                  struct qemud_driver *driver,
135
                                  virDomainObjPtr vm);
136

137
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
138

139
static int qemudMonitorCommand (const virDomainObjPtr vm,
140 141
                                const char *cmd,
                                char **reply);
142

J
Jim Meyering 已提交
143
static struct qemud_driver *qemu_driver = NULL;
144 145


146 147 148
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;
149 150 151 152 153 154 155 156 157
    /* 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 */
158 159

    for (i = 0 ; i < driver->domains.count ; i++) {
160
        virDomainObjPtr vm = driver->domains.objs[i];
161
        virDomainObjLock(vm);
162 163
        if (vm->autostart &&
            !virDomainIsActive(vm)) {
164
            int ret = qemudStartVMDaemon(conn, driver, vm, NULL);
165 166 167 168 169 170
            if (ret < 0) {
                virErrorPtr err = virGetLastError();
                qemudLog(QEMUD_ERR, _("Failed to autostart VM '%s': %s\n"),
                         vm->def->name,
                         err ? err->message : NULL);
            } else {
171 172 173 174 175 176
                virDomainEventPtr event =
                    virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             VIR_DOMAIN_EVENT_STARTED_BOOTED);
                if (event)
                    qemuDomainEventQueue(driver, event);
177
            }
178
        }
179
        virDomainObjUnlock(vm);
180
    }
181 182

    virConnectClose(conn);
183 184
}

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222

/**
 * 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) {
        qemudReportError(conn, vm, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for status file"));
        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;
}


223 224 225 226 227 228 229
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
230 231 232
    uid_t uid = geteuid();
    struct passwd *pw;
    char *base = NULL;
D
Daniel P. Berrange 已提交
233
    char driverConf[PATH_MAX];
234

235
    if (VIR_ALLOC(qemu_driver) < 0)
236 237
        return -1;

238 239 240
    pthread_mutex_init(&qemu_driver->lock, NULL);
    qemuDriverLock(qemu_driver);

241 242 243
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;

244 245
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
246
        goto out_of_memory;
247 248 249 250 251 252
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

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

254
    if (!uid) {
255 256
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
257
            goto out_of_memory;
258

D
Daniel P. Berrange 已提交
259
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
260
            goto out_of_memory;
261 262 263 264

        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu/", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
265 266
    } else {
        if (!(pw = getpwuid(uid))) {
267
            qemudLog(QEMUD_ERR, _("Failed to find user record for uid '%d': %s\n"),
268
                     uid, strerror(errno));
269
            goto error;
270 271
        }

272 273
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/.libvirt/qemu/log", pw->pw_dir) == -1)
274
            goto out_of_memory;
275

276
        if (virAsprintf(&base, "%s/.libvirt", pw->pw_dir) == -1)
277
            goto out_of_memory;
278 279 280 281 282 283 284 285 286

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

    if (virFileMakePath(qemu_driver->stateDir) < 0) {
            qemudLog(QEMUD_ERR, _("Failed to create state dir '%s': %s\n"),
                     qemu_driver->stateDir, strerror(errno));
            goto error;
287 288 289 290 291
    }

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

296
    if (virAsprintf(&qemu_driver->configDir, "%s/qemu", base) == -1)
297 298
        goto out_of_memory;

299
    if (virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
300 301
        goto out_of_memory;

302
    VIR_FREE(base);
303 304 305

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

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
308
        goto error;
D
Daniel P. Berrange 已提交
309 310
    }

311 312 313 314
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
315
                                qemu_driver->autostartDir,
316 317
                                NULL, NULL) < 0)
        goto error;
318 319
    qemudAutostartConfigs(qemu_driver);

320 321
    qemuDriverUnlock(qemu_driver);

322 323
    return 0;

324
out_of_memory:
J
Jim Meyering 已提交
325
    qemudLog (QEMUD_ERR,
326
              "%s", _("qemudStartup: out of memory\n"));
327 328 329
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
330
    VIR_FREE(base);
331
    qemudShutdown();
332 333 334
    return -1;
}

335 336 337 338
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

339 340 341 342 343 344 345 346
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
347 348
}

349 350 351 352 353 354 355 356
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
357 358 359
    if (!qemu_driver)
        return 0;

360
    qemuDriverLock(qemu_driver);
361 362 363 364
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
365 366
                            qemu_driver->autostartDir,
                            qemudNotifyLoadDomain, qemu_driver);
367

368
    qemudAutostartConfigs(qemu_driver);
369
    qemuDriverUnlock(qemu_driver);
370 371

    return 0;
372 373
}

374 375 376 377 378 379 380 381 382 383
/**
 * 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) {
384
    unsigned int i;
385
    int active = 0;
386

387 388 389
    if (!qemu_driver)
        return 0;

390 391 392 393 394 395 396 397
    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);
    }
398

399 400
    qemuDriverUnlock(qemu_driver);
    return active;
401 402
}

403 404 405 406 407 408 409
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
410
    unsigned int i;
411

412
    if (!qemu_driver)
413
        return -1;
414

415
    qemuDriverLock(qemu_driver);
416 417
    virCapabilitiesFree(qemu_driver->caps);

418
    /* shutdown active VMs */
419 420
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr dom = qemu_driver->domains.objs[i];
421
        virDomainObjLock(dom);
422 423
        if (virDomainIsActive(dom))
            qemudShutdownVMDaemon(NULL, qemu_driver, dom);
424
        virDomainObjUnlock(dom);
425
    }
426

427
    virDomainObjListFree(&qemu_driver->domains);
428

429
    VIR_FREE(qemu_driver->logDir);
430 431
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
432
    VIR_FREE(qemu_driver->stateDir);
433
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
434
    VIR_FREE(qemu_driver->vncListen);
D
Daniel P. Berrange 已提交
435

436 437
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
438 439 440 441
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

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

443 444 445
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

446
    qemuDriverUnlock(qemu_driver);
447
    VIR_FREE(qemu_driver);
448 449

    return 0;
450 451 452
}

/* Return -1 for error, 1 to continue reading and 0 for success */
453
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
454
                                      virDomainObjPtr vm,
455 456 457 458
                                      const char *output,
                                      int fd);

static int
459
qemudReadMonitorOutput(virConnectPtr conn,
460
                       virDomainObjPtr vm,
461 462 463 464
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
465 466
                       const char *what,
                       int timeout)
467 468 469 470 471 472 473 474 475 476
{
    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);
        if (ret == 0) {
477
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
478
                             _("QEMU quit during %s startup\n%s"), what, buf);
479 480 481 482 483 484 485 486
            return -1;
        }
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
487
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
488
                                 _("Failure while reading %s startup output: %s"),
489 490 491 492
                                 what, strerror(errno));
                return -1;
            }

493
            ret = poll(&pfd, 1, timeout);
494
            if (ret == 0) {
495
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
496
                                 _("Timed out while reading %s startup output"), what);
497 498 499
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
500
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
501
                                     _("Failure while reading %s startup output: %s"),
502 503 504 505 506 507 508 509 510
                                     what, strerror(errno));
                    return -1;
                }
            } else {
                /* Make sure we continue loop & read any further data
                   available before dealing with EOF */
                if (pfd.revents & (POLLIN | POLLHUP))
                    continue;

511
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
512
                                 _("Failure while reading %s startup output"), what);
513 514 515 516 517
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
518
            if ((ret = func(conn, vm, buf, fd)) != 1)
519 520 521 522
                return ret;
        }
    }

523
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
524
                     _("Out of space while reading %s startup output"), what);
525 526 527 528 529
    return -1;

}

static int
530
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
531
                        virDomainObjPtr vm,
532 533 534 535 536 537 538 539 540 541 542
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

543
static int qemudOpenMonitor(virConnectPtr conn,
544
                            virDomainObjPtr vm,
545
                            const char *monitor) {
546 547 548 549
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
550
    if ((monfd = open(monitor, O_RDWR)) < 0) {
551
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
552
                         _("Unable to open monitor path %s"), monitor);
553 554 555
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
556
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
557
                         "%s", _("Unable to set monitor close-on-exec flag"));
558 559 560
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
561
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
562
                         "%s", _("Unable to put monitor into non-blocking mode"));
563 564 565
        goto error;
    }

566
    ret = qemudReadMonitorOutput(conn,
567
                                 vm, monfd,
568 569
                                 buf, sizeof(buf),
                                 qemudCheckMonitorPrompt,
570
                                 "monitor", 10000);
571

572 573 574 575 576 577
    if (!(vm->monitorpath = strdup(monitor))) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for monitor path"));
        goto error;
    }

578 579 580 581
    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

582 583 584 585 586
 error:
    close(monfd);
    return ret;
}

587 588
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
589
                                   size_t *offset,
590
                                   char **path) {
591
    static const char needle[] = "char device redirected to";
592
    char *tmp, *dev;
593

594
    VIR_FREE(*path);
595
    /* First look for our magic string */
596 597 598 599 600
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
601

602 603 604 605 606
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
607
        if (c_isspace(*tmp)) {
608 609 610 611 612 613 614
            if (VIR_ALLOC_N(*path, (tmp-dev)+1) < 0) {
                qemudReportError(conn, NULL, NULL,
                                 VIR_ERR_NO_MEMORY, NULL);
                return -1;
            }
            strncpy(*path, dev, (tmp-dev));
            (*path)[(tmp-dev)] = '\0';
615
            /* ... now further update offset till we get EOL */
616
            *offset = tmp - haystack;
617 618
            return 0;
        }
619
        tmp++;
620 621 622 623 624
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
625 626
     * least see a \n - indicate that we want to carry
     * on trying again
627
     */
628
    return 1;
629 630 631
}

static int
632
qemudFindCharDevicePTYs(virConnectPtr conn,
633
                        virDomainObjPtr vm,
634 635
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
636
{
637
    char *monitor = NULL;
638
    size_t offset = 0;
639
    int ret, i;
640 641 642 643 644

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

646
    /* So first comes the monitor device */
647 648
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
649

650
    /* then the serial devices */
651 652
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
653 654 655 656
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
657 658 659 660
        }
    }

    /* and finally the parallel devices */
661 662
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
663 664 665 666
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
667 668 669 670
        }
    }

    /* Got them all, so now open the monitor console */
671
    ret = qemudOpenMonitor(conn, vm, monitor);
672 673 674 675

cleanup:
    VIR_FREE(monitor);
    return ret;
676 677
}

678
static int qemudWaitForMonitor(virConnectPtr conn,
679
                               virDomainObjPtr vm) {
680
    char buf[1024]; /* Plenty of space to get startup greeting */
681
    int ret = qemudReadMonitorOutput(conn,
682
                                     vm, vm->stderr_fd,
683
                                     buf, sizeof(buf),
684
                                     qemudFindCharDevicePTYs,
685
                                     "console", 3000);
686 687

    buf[sizeof(buf)-1] = '\0';
688 689

    if (safewrite(vm->logfile, buf, strlen(buf)) < 0) {
690
        /* Log, but ignore failures to write logfile for VM */
691
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
692 693 694 695 696
                 strerror(errno));
    }
    return ret;
}

697 698
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
699
                    virDomainObjPtr vm) {
700 701 702 703 704 705
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
706
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
707 708 709 710 711 712 713 714 715 716
        vm->nvcpupids = 1;
    else
        vm->nvcpupids = vm->def->vcpus;

    if (VIR_ALLOC_N(vm->vcpupids, vm->nvcpupids) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("allocate cpumap"));
        return -1;
    }

717
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
718 719 720 721
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

722
    if (qemudMonitorCommand(vm, "info cpus", &qemucpus) < 0) {
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780
        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;

781
    VIR_FREE(qemucpus);
782 783 784 785
    return 0;

error:
    VIR_FREE(vm->vcpupids);
786 787
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
788 789 790 791 792 793 794 795

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

796 797
static int
qemudInitCpus(virConnectPtr conn,
D
Daniel Veillard 已提交
798 799
              virDomainObjPtr vm,
              const char *migrateFrom) {
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
    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 已提交
815 816 817 818 819 820
    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++)
821
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
822
    }
823 824 825 826 827 828 829 830 831 832 833 834

    for (i = 0 ; i < vm->nvcpupids ; i++) {
        if (sched_setaffinity(vm->vcpupids[i],
                              sizeof(mask), &mask) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("failed to set CPU affinity %s"),
                             strerror(errno));
            return -1;
        }
    }
#endif /* HAVE_SCHED_GETAFFINITY */

D
Daniel Veillard 已提交
835 836
    if (migrateFrom == NULL) {
        /* Allow the CPUS to start executing */
837
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
D
Daniel Veillard 已提交
838 839 840 841 842
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("resume operation failed"));
            return -1;
        }
        VIR_FREE(info);
843 844 845 846 847 848
    }

    return 0;
}


849
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    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;
}

885 886 887
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

888 889
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
890 891
                              virDomainObjPtr vm,
                              const char *migrateFrom) {
892
    const char **argv = NULL, **tmp;
893
    const char **progenv = NULL;
894
    int i, ret;
895
    char logfile[PATH_MAX];
896
    struct stat sb;
897 898
    int *tapfds = NULL;
    int ntapfds = 0;
899
    unsigned int qemuCmdFlags;
900
    fd_set keepfd;
901
    const char *emulator;
G
Guido Günther 已提交
902 903
    uid_t uid = geteuid();
    mode_t logmode;
904 905

    FD_ZERO(&keepfd);
906

907
    if (virDomainIsActive(vm)) {
908
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
909
                         "%s", _("VM is already active"));
910 911 912
        return -1;
    }

913 914 915
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
916
        int port = qemudNextFreeVNCPort(driver);
917
        if (port < 0) {
918
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
919
                             "%s", _("Unable to find an unused VNC port"));
920 921
            return -1;
        }
922 923
        vm->def->graphics->data.vnc.port = port;
    }
924

925
    if ((strlen(driver->logDir) + /* path */
926 927 928 929
         1 + /* Separator */
         strlen(vm->def->name) + /* basename */
         4 + /* suffix .log */
         1 /* NULL */) > PATH_MAX) {
930
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
931
                         _("config file path too long: %s/%s.log"),
932
                         driver->logDir, vm->def->name);
933 934
        return -1;
    }
935
    strcpy(logfile, driver->logDir);
936 937 938 939
    strcat(logfile, "/");
    strcat(logfile, vm->def->name);
    strcat(logfile, ".log");

940
    if (virFileMakePath(driver->logDir) < 0) {
941
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
942
                         _("cannot create log directory %s: %s"),
943
                         driver->logDir, strerror(errno));
944 945 946
        return -1;
    }

G
Guido Günther 已提交
947 948 949 950 951 952
    logmode = O_CREAT | O_WRONLY;
    if (uid != 0)
        logmode |= O_TRUNC;
    else
        logmode |= O_APPEND;
    if ((vm->logfile = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
953
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
954
                         _("failed to create logfile %s: %s"),
955 956 957
                         logfile, strerror(errno));
        return -1;
    }
958 959
    if (qemudSetCloseExec(vm->logfile) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
960
                         _("Unable to set VM logfile close-on-exec flag %s"),
961 962 963 964 965
                         strerror(errno));
        close(vm->logfile);
        vm->logfile = -1;
        return -1;
    }
966

967 968 969 970 971 972
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

973 974 975 976
    /* 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
     */
977
    if (stat(emulator, &sb) < 0) {
978 979
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot find QEMU binary %s: %s"),
980
                         emulator,
981 982 983 984
                         strerror(errno));
        return -1;
    }

985
    if (qemudExtractVersionInfo(emulator,
986 987 988 989
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
990
                         emulator);
991 992
        return -1;
    }
993

994
    vm->def->id = driver->nextvmid++;
995
    if (qemudBuildCommandLine(conn, driver, vm,
996
                              qemuCmdFlags, &argv, &progenv,
997
                              &tapfds, &ntapfds, migrateFrom) < 0) {
998
        close(vm->logfile);
999
        vm->def->id = -1;
1000 1001 1002 1003
        vm->logfile = -1;
        return -1;
    }

1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
    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++;
    }
1014 1015
    tmp = argv;
    while (*tmp) {
1016
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
1017
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1018
                     errno, strerror(errno));
1019
        if (safewrite(vm->logfile, " ", 1) < 0)
1020
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1021 1022 1023
                     errno, strerror(errno));
        tmp++;
    }
1024
    if (safewrite(vm->logfile, "\n", 1) < 0)
1025
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1026 1027
                 errno, strerror(errno));

1028 1029 1030
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;

1031 1032 1033
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

1034
    ret = virExec(conn, argv, progenv, &keepfd, &vm->pid,
1035 1036
                  vm->stdin_fd, &vm->stdout_fd, &vm->stderr_fd,
                  VIR_EXEC_NONBLOCK);
1037
    if (ret == 0)
1038
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
1039 1040
    else
        vm->def->id = -1;
1041

1042
    for (i = 0 ; argv[i] ; i++)
1043 1044
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
1045

1046 1047 1048 1049
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

1050 1051 1052
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
1053
        }
1054
        VIR_FREE(tapfds);
1055 1056
    }

1057
    if (ret == 0) {
1058
        if (((vm->stdout_watch = virEventAddHandle(vm->stdout_fd,
1059 1060 1061 1062 1063
                                                   VIR_EVENT_HANDLE_READABLE |
                                                   VIR_EVENT_HANDLE_ERROR |
                                                   VIR_EVENT_HANDLE_HANGUP,
                                                   qemudDispatchVMEvent,
                                                   driver, NULL)) < 0) ||
1064 1065 1066 1067 1068
            ((vm->stderr_watch = virEventAddHandle(vm->stderr_fd,
                                                   VIR_EVENT_HANDLE_READABLE |
                                                   VIR_EVENT_HANDLE_ERROR |
                                                   VIR_EVENT_HANDLE_HANGUP,
                                                   qemudDispatchVMEvent,
1069
                                                   driver, NULL)) < 0) ||
1070 1071 1072
            (qemudWaitForMonitor(conn, vm) < 0) ||
            (qemudDetectVcpuPIDs(conn, vm) < 0) ||
            (qemudInitCpus(conn, vm, migrateFrom) < 0)) {
1073 1074 1075
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
1076
    }
1077
    qemudSaveDomainStatus(conn, qemu_driver, vm);
1078

1079
    return ret;
1080 1081
}

1082
static int qemudVMData(struct qemud_driver *driver ATTRIBUTE_UNUSED,
1083
                       virDomainObjPtr vm, int fd) {
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    char buf[4096];
    if (vm->pid < 0)
        return 0;

    for (;;) {
        int ret = read(fd, buf, sizeof(buf)-1);
        if (ret < 0) {
            if (errno == EAGAIN)
                return 0;
            return -1;
        }
        if (ret == 0) {
            return 0;
        }
        buf[ret] = '\0';

1100
        if (safewrite(vm->logfile, buf, ret) < 0) {
1101
            /* Log, but ignore failures to write logfile for VM */
1102
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1103 1104 1105 1106 1107 1108
                     strerror(errno));
        }
    }
}


1109
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
1110 1111
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
1112
        return;
1113

1114
    qemudLog(QEMUD_INFO, _("Shutting down VM '%s'\n"), vm->def->name);
1115 1116 1117

    kill(vm->pid, SIGTERM);

1118 1119
    qemudVMData(driver, vm, vm->stdout_fd);
    qemudVMData(driver, vm, vm->stderr_fd);
1120

1121 1122
    virEventRemoveHandle(vm->stdout_watch);
    virEventRemoveHandle(vm->stderr_watch);
1123 1124

    if (close(vm->logfile) < 0)
1125
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
1126
                 errno, strerror(errno));
1127 1128
    close(vm->stdout_fd);
    close(vm->stderr_fd);
1129 1130 1131
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
1132 1133
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;
1134 1135 1136 1137 1138
    vm->monitor = -1;

    if (waitpid(vm->pid, NULL, WNOHANG) != vm->pid) {
        kill(vm->pid, SIGKILL);
        if (waitpid(vm->pid, NULL, 0) != vm->pid) {
J
Jim Meyering 已提交
1139
            qemudLog(QEMUD_WARN,
1140
                     "%s", _("Got unexpected pid, damn\n"));
1141 1142
        }
    }
1143
    qemudRemoveDomainStatus(conn, driver, vm);
1144 1145

    vm->pid = -1;
1146
    vm->def->id = -1;
1147
    vm->state = VIR_DOMAIN_SHUTOFF;
1148
    VIR_FREE(vm->vcpupids);
1149
    vm->nvcpupids = 0;
1150 1151

    if (vm->newDef) {
1152
        virDomainDefFree(vm->def);
1153
        vm->def = vm->newDef;
1154
        vm->def->id = -1;
1155 1156 1157 1158 1159
        vm->newDef = NULL;
    }
}


1160
static void
1161
qemudDispatchVMEvent(int watch, int fd, int events, void *opaque) {
1162
    struct qemud_driver *driver = opaque;
1163
    virDomainObjPtr vm = NULL;
1164
    virDomainEventPtr event = NULL;
1165
    unsigned int i;
1166
    int quit = 0, failed = 0;
1167

1168
    qemuDriverLock(driver);
1169
    for (i = 0 ; i < driver->domains.count ; i++) {
1170 1171 1172 1173 1174 1175
        virDomainObjPtr tmpvm = driver->domains.objs[i];
        virDomainObjLock(tmpvm);
        if (virDomainIsActive(tmpvm) &&
            (tmpvm->stdout_watch == watch ||
             tmpvm->stderr_watch == watch)) {
            vm = tmpvm;
1176
            break;
1177
        }
1178
        virDomainObjUnlock(tmpvm);
1179 1180 1181
    }

    if (!vm)
1182
        goto cleanup;
1183

1184 1185
    if (vm->stdout_fd != fd &&
        vm->stderr_fd != fd) {
1186 1187 1188 1189 1190 1191 1192 1193
        failed = 1;
    } else {
        if (events & VIR_EVENT_HANDLE_READABLE) {
            if (qemudVMData(driver, vm, fd) < 0)
                failed = 1;
        } else {
            quit = 1;
        }
1194 1195
    }

1196
    if (failed || quit) {
1197 1198 1199 1200 1201
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         quit ?
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN :
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
        qemudShutdownVMDaemon(NULL, driver, vm);
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains,
                                    vm);
            vm = NULL;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1213 1214
    if (event)
        qemuDomainEventQueue(driver, event);
1215
    qemuDriverUnlock(driver);
1216 1217
}

1218
static int
1219
qemudMonitorCommand (const virDomainObjPtr vm,
1220 1221
                     const char *cmd,
                     char **reply) {
D
Daniel P. Berrange 已提交
1222 1223
    int size = 0;
    char *buf = NULL;
1224
    size_t cmdlen = strlen(cmd);
D
Daniel P. Berrange 已提交
1225

1226 1227 1228
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        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 已提交
1241

1242 1243
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1244 1245 1246 1247 1248
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1249
                goto error;
1250
            }
1251
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1252 1253
                goto error;

D
Daniel P. Berrange 已提交
1254 1255 1256 1257
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1258

D
Daniel P. Berrange 已提交
1259
        /* Look for QEMU prompt to indicate completion */
D
Daniel P. Berrange 已提交
1260
        if (buf && ((tmp = strstr(buf, "\n(qemu) ")) != NULL)) {
C
Cole Robinson 已提交
1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
            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);

D
Daniel P. Berrange 已提交
1278 1279 1280 1281 1282 1283 1284
            break;
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1285
            goto error;
D
Daniel P. Berrange 已提交
1286 1287 1288
        }
    }

1289 1290
    /* Log, but ignore failures to write logfile for VM */
    if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1291
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1292 1293
                 strerror(errno));

D
Daniel P. Berrange 已提交
1294 1295
    *reply = buf;
    return 0;
1296 1297 1298 1299 1300

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1301
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1302
                     strerror(errno));
1303
        VIR_FREE(buf);
1304 1305
    }
    return -1;
D
Daniel P. Berrange 已提交
1306 1307
}

1308 1309 1310 1311 1312 1313
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
1314
static int qemudProbe(void)
1315 1316 1317
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
G
Guido Günther 已提交
1318
        (virFileExists("/usr/bin/kvm")) ||
1319 1320 1321 1322
        (virFileExists("/usr/bin/xenner")))
        return 1;

    return 0;
1323
}
1324

1325
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1326
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1327
                                  int flags ATTRIBUTE_UNUSED) {
1328 1329 1330
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1331
        goto decline;
1332

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    if (!qemudProbe())
        goto decline;

    if (conn->uri == NULL) {
        conn->uri = xmlParseURI(uid ? "qemu:///session" : "qemu:///system");
        if (!conn->uri) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,NULL);
            return VIR_DRV_OPEN_ERROR;
        }
    } else if (conn->uri->scheme == NULL ||
               conn->uri->path == NULL)
1344 1345
        goto decline;

1346
    if (STRNEQ (conn->uri->scheme, "qemu"))
1347 1348
        goto decline;

1349
    if (uid != 0) {
1350
        if (STRNEQ (conn->uri->path, "/session"))
1351
            goto decline;
1352
    } else { /* root */
1353 1354
        if (STRNEQ (conn->uri->path, "/system") &&
            STRNEQ (conn->uri->path, "/session"))
1355
            goto decline;
1356 1357 1358 1359 1360
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1361 1362

 decline:
1363
    return VIR_DRV_OPEN_DECLINED;
1364 1365 1366
}

static int qemudClose(virConnectPtr conn) {
1367
    struct qemud_driver *driver = conn->privateData;
1368 1369 1370

    /* Get rid of callbacks registered for this conn */
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
1371 1372 1373 1374 1375 1376

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
/* 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;
    }
}

1387
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1388
    return "QEMU";
1389 1390
}

1391 1392 1393 1394 1395

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

    int r, fd;
1396

1397 1398
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1399
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
        return maxvcpus;
    }

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

    close(fd);
    return maxvcpus;
}


1412
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1413 1414 1415
    if (!type)
        return 16;

1416
    if (STRCASEEQ(type, "qemu"))
1417 1418
        return 16;

1419
    if (STRCASEEQ(type, "kvm"))
1420
        return kvmGetMaxVCPUs();
1421

1422
    if (STRCASEEQ(type, "kqemu"))
1423
        return 1;
1424 1425 1426

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1427 1428 1429
    return -1;
}

1430 1431 1432
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1433 1434 1435
}


1436
static char *qemudGetCapabilities(virConnectPtr conn) {
1437
    struct qemud_driver *driver = conn->privateData;
1438
    char *xml;
1439

1440
    qemuDriverLock(driver);
1441
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1442 1443
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                 "%s", _("failed to allocate space for capabilities support"));
1444
    qemuDriverUnlock(driver);
1445

1446
    return xml;
1447 1448 1449
}


1450 1451 1452 1453 1454 1455 1456 1457
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
1458
    int ret = -1;
1459 1460 1461 1462

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1463
        goto cleanup;
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    }
    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"));
1474
            goto cleanup;
1475 1476 1477
        }
        freeMems[numCells++] = mem;
    }
1478 1479 1480 1481
    ret = numCells;

cleanup:
    return ret;
1482 1483 1484 1485 1486
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
1487
    unsigned long long freeMem = -1;
1488
    int n;
1489

1490 1491 1492
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1493
        goto cleanup;
1494 1495 1496 1497 1498 1499 1500
    }

    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"));
1501
            goto cleanup;
1502 1503 1504 1505
        }
        freeMem += mem;
    }

1506
cleanup:
1507 1508 1509 1510
    return freeMem;
}

#endif
1511

D
Daniel P. Berrange 已提交
1512 1513 1514
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1515
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1516 1517 1518 1519 1520 1521

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

    if (!(pidinfo = fopen(proc, "r"))) {
1522
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1523 1524 1525 1526 1527
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1528
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1529
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1530 1531 1532 1533 1534 1535 1536 1537
        return -1;
    }

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

1540
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1541 1542 1543 1544 1545 1546 1547

    fclose(pidinfo);

    return 0;
}


1548
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1549
                                          int id) {
1550 1551 1552 1553
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1554
    qemuDriverLock(driver);
1555
    vm  = virDomainFindByID(&driver->domains, id);
1556
    qemuDriverUnlock(driver);
1557 1558

    if (!vm) {
1559
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1560
        goto cleanup;
1561 1562
    }

1563
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1564
    if (dom) dom->id = vm->def->id;
1565 1566

cleanup:
1567 1568
    if (vm)
        virDomainObjUnlock(vm);
1569 1570
    return dom;
}
1571

1572
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1573
                                            const unsigned char *uuid) {
1574 1575 1576
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1577

1578
    qemuDriverLock(driver);
1579
    vm = virDomainFindByUUID(&driver->domains, uuid);
1580 1581
    qemuDriverUnlock(driver);

1582
    if (!vm) {
1583
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1584
        goto cleanup;
1585 1586
    }

1587
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1588
    if (dom) dom->id = vm->def->id;
1589 1590

cleanup:
1591 1592
    if (vm)
        virDomainObjUnlock(vm);
1593 1594
    return dom;
}
1595

1596
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1597
                                            const char *name) {
1598 1599 1600
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1601

1602
    qemuDriverLock(driver);
1603
    vm = virDomainFindByName(&driver->domains, name);
1604 1605
    qemuDriverUnlock(driver);

1606
    if (!vm) {
1607
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1608
        goto cleanup;
1609 1610
    }

1611
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1612
    if (dom) dom->id = vm->def->id;
1613 1614

cleanup:
1615 1616
    if (vm)
        virDomainObjUnlock(vm);
1617 1618 1619
    return dom;
}

1620
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1621 1622 1623
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1624
    qemuDriverLock(driver);
1625
    if (qemudExtractVersion(conn, driver) < 0)
1626
        goto cleanup;
1627

1628
    *version = qemu_driver->qemuVersion;
1629 1630 1631
    ret = 0;

cleanup:
1632
    qemuDriverUnlock(driver);
1633
    return ret;
D
Daniel P. Berrange 已提交
1634 1635
}

1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
static char *
qemudGetHostname (virConnectPtr conn)
{
    int r;
    char hostname[HOST_NAME_MAX+1], *str;

    r = gethostname (hostname, HOST_NAME_MAX+1);
    if (r == -1) {
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return NULL;
    }
    /* Caller frees this string. */
    str = strdup (hostname);
    if (str == NULL) {
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                         "%s", strerror (errno));
        return NULL;
    }
    return str;
}

1658
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1659
    struct qemud_driver *driver = conn->privateData;
1660 1661
    int got = 0, i;

1662 1663 1664
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1665 1666
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
1667 1668 1669
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1670

D
Daniel P. Berrange 已提交
1671 1672
    return got;
}
1673

1674
static int qemudNumDomains(virConnectPtr conn) {
1675
    struct qemud_driver *driver = conn->privateData;
1676 1677
    int n = 0, i;

1678 1679 1680
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1681
        if (virDomainIsActive(driver->domains.objs[i]))
1682
            n++;
1683 1684 1685
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1686

1687
    return n;
D
Daniel P. Berrange 已提交
1688
}
1689

1690
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1691
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1692
    struct qemud_driver *driver = conn->privateData;
1693
    virDomainDefPtr def;
1694
    virDomainObjPtr vm = NULL;
1695
    virDomainPtr dom = NULL;
1696
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1697

1698
    qemuDriverLock(driver);
1699
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
1700
        goto cleanup;
1701

1702
    vm = virDomainFindByName(&driver->domains, def->name);
1703
    if (vm) {
1704
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1705
                         _("domain '%s' is already defined"),
1706
                         def->name);
1707
        goto cleanup;
1708
    }
1709
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1710 1711 1712 1713 1714
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1715
                         _("domain with uuid '%s' is already defined"),
1716
                         uuidstr);
1717
        goto cleanup;
1718
    }
1719

1720 1721
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1722 1723 1724 1725
                                  def)))
        goto cleanup;

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

1727 1728 1729
    if (qemudStartVMDaemon(conn, driver, vm, NULL) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1730
        vm = NULL;
1731
        goto cleanup;
D
Daniel P. Berrange 已提交
1732
    }
1733 1734 1735 1736

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

1738
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1739
    if (dom) dom->id = vm->def->id;
1740 1741 1742

cleanup:
    virDomainDefFree(def);
1743 1744
    if (vm)
        virDomainObjUnlock(vm);
1745 1746
    if (event)
        qemuDomainEventQueue(driver, event);
1747
    qemuDriverUnlock(driver);
1748
    return dom;
D
Daniel P. Berrange 已提交
1749 1750 1751
}


1752
static int qemudDomainSuspend(virDomainPtr dom) {
1753
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1754
    char *info;
1755 1756
    virDomainObjPtr vm;
    int ret = -1;
1757
    virDomainEventPtr event = NULL;
1758

1759
    qemuDriverLock(driver);
1760
    vm = virDomainFindByID(&driver->domains, dom->id);
1761 1762
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1763
    if (!vm) {
1764
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
1765
        goto cleanup;
D
Daniel P. Berrange 已提交
1766
    }
1767
    if (!virDomainIsActive(vm)) {
1768 1769
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1770
        goto cleanup;
D
Daniel P. Berrange 已提交
1771
    }
1772
    if (vm->state != VIR_DOMAIN_PAUSED) {
1773
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
1774 1775 1776 1777 1778 1779
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("suspend operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
1780 1781 1782
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
1783
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1784
    }
1785
    qemudSaveDomainStatus(dom->conn, driver, vm);
1786 1787 1788
    ret = 0;

cleanup:
1789 1790
    if (vm)
        virDomainObjUnlock(vm);
1791 1792 1793 1794 1795 1796

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1797
    return ret;
D
Daniel P. Berrange 已提交
1798 1799 1800
}


1801
static int qemudDomainResume(virDomainPtr dom) {
1802
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1803
    char *info;
1804 1805
    virDomainObjPtr vm;
    int ret = -1;
1806
    virDomainEventPtr event = NULL;
1807

1808
    qemuDriverLock(driver);
1809
    vm = virDomainFindByID(&driver->domains, dom->id);
1810 1811
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1812
    if (!vm) {
1813 1814
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1815
        goto cleanup;
D
Daniel P. Berrange 已提交
1816
    }
1817
    if (!virDomainIsActive(vm)) {
1818 1819
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1820
        goto cleanup;
D
Daniel P. Berrange 已提交
1821
    }
1822
    if (vm->state == VIR_DOMAIN_PAUSED) {
1823
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
1824 1825 1826 1827 1828 1829
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("resume operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;
        qemudDebug("Reply %s", info);
1830 1831 1832
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
1833
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1834
    }
1835
    qemudSaveDomainStatus(dom->conn, driver, vm);
1836 1837 1838
    ret = 0;

cleanup:
1839 1840
    if (vm)
        virDomainObjUnlock(vm);
1841 1842 1843 1844 1845
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1846
    return ret;
D
Daniel P. Berrange 已提交
1847 1848 1849
}


1850
static int qemudDomainShutdown(virDomainPtr dom) {
1851 1852
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1853
    char* info;
1854
    int ret = -1;
1855

1856
    qemuDriverLock(driver);
1857
    vm = virDomainFindByID(&driver->domains, dom->id);
1858 1859
    qemuDriverUnlock(driver);

1860 1861
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1862
                         _("no domain with matching id %d"), dom->id);
1863
        goto cleanup;
1864 1865
    }

1866
    if (qemudMonitorCommand(vm, "system_powerdown", &info) < 0) {
1867
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1868
                         "%s", _("shutdown operation failed"));
1869
        goto cleanup;
1870
    }
D
Daniel Veillard 已提交
1871
    VIR_FREE(info);
1872 1873 1874
    ret = 0;

cleanup:
1875 1876
    if (vm)
        virDomainObjUnlock(vm);
1877
    return ret;
1878 1879 1880
}


1881
static int qemudDomainDestroy(virDomainPtr dom) {
1882 1883 1884
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1885
    virDomainEventPtr event = NULL;
1886

1887
    qemuDriverLock(driver);
1888
    vm  = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1889
    if (!vm) {
1890
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1891
                         _("no domain with matching id %d"), dom->id);
1892
        goto cleanup;
D
Daniel P. Berrange 已提交
1893
    }
1894

1895
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1896 1897 1898
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1899
    if (!vm->persistent) {
1900 1901
        virDomainRemoveInactive(&driver->domains,
                                vm);
1902 1903
        vm = NULL;
    }
1904 1905 1906
    ret = 0;

cleanup:
1907 1908
    if (vm)
        virDomainObjUnlock(vm);
1909 1910
    if (event)
        qemuDomainEventQueue(driver, event);
1911
    qemuDriverUnlock(driver);
1912
    return ret;
D
Daniel P. Berrange 已提交
1913 1914 1915
}


1916
static char *qemudDomainGetOSType(virDomainPtr dom) {
1917 1918 1919
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1920

1921
    qemuDriverLock(driver);
1922
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1923
    qemuDriverUnlock(driver);
1924 1925
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1926
                         "%s", _("no domain with matching uuid"));
1927
        goto cleanup;
1928 1929
    }

1930
    if (!(type = strdup(vm->def->os.type)))
1931 1932
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for ostype"));
1933 1934

cleanup:
1935 1936
    if (vm)
        virDomainObjUnlock(vm);
1937 1938 1939
    return type;
}

1940 1941
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1942 1943 1944
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1945

1946
    qemuDriverLock(driver);
1947
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1948 1949
    qemuDriverUnlock(driver);

1950
    if (!vm) {
1951 1952 1953
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1954
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1955
                         _("no domain with matching uuid '%s'"), uuidstr);
1956
        goto cleanup;
1957 1958
    }

1959 1960 1961
    ret = vm->def->maxmem;

cleanup:
1962 1963
    if (vm)
        virDomainObjUnlock(vm);
1964
    return ret;
1965 1966 1967
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1968 1969 1970
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1971

1972
    qemuDriverLock(driver);
1973
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1974 1975
    qemuDriverUnlock(driver);

1976
    if (!vm) {
1977 1978 1979
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1980
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1981
                         _("no domain with matching uuid '%s'"), uuidstr);
1982
        goto cleanup;
1983 1984 1985 1986
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1987
                         "%s", _("cannot set max memory lower than current memory"));
1988
        goto cleanup;;
1989 1990 1991
    }

    vm->def->maxmem = newmax;
1992 1993 1994
    ret = 0;

cleanup:
1995 1996
    if (vm)
        virDomainObjUnlock(vm);
1997
    return ret;
1998 1999 2000
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
2001 2002 2003
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2004

2005
    qemuDriverLock(driver);
2006
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2007
    qemuDriverUnlock(driver);
2008
    if (!vm) {
2009 2010 2011
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2012
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2013
                         _("no domain with matching uuid '%s'"), uuidstr);
2014
        goto cleanup;
2015 2016
    }

2017
    if (virDomainIsActive(vm)) {
2018
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
2019
                         "%s", _("cannot set memory of an active domain"));
2020
        goto cleanup;
2021 2022 2023 2024
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2025
                         "%s", _("cannot set memory higher than max memory"));
2026
        goto cleanup;
2027 2028 2029
    }

    vm->def->memory = newmem;
2030 2031 2032
    ret = 0;

cleanup:
2033 2034
    if (vm)
        virDomainObjUnlock(vm);
2035
    return ret;
2036 2037
}

2038
static int qemudDomainGetInfo(virDomainPtr dom,
2039
                              virDomainInfoPtr info) {
2040 2041 2042 2043
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

2044
    qemuDriverLock(driver);
2045
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2046
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2047
    if (!vm) {
2048 2049
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2050
        goto cleanup;
D
Daniel P. Berrange 已提交
2051 2052
    }

2053
    info->state = vm->state;
D
Daniel P. Berrange 已提交
2054

2055
    if (!virDomainIsActive(vm)) {
2056
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2057
    } else {
2058
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
2059
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
2060
            goto cleanup;
D
Daniel P. Berrange 已提交
2061 2062 2063
        }
    }

2064 2065 2066
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
2067 2068 2069
    ret = 0;

cleanup:
2070 2071
    if (vm)
        virDomainObjUnlock(vm);
2072
    return ret;
D
Daniel P. Berrange 已提交
2073 2074 2075
}


D
Daniel P. Berrange 已提交
2076
static char *qemudEscape(const char *in, int shell)
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
{
    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 已提交
2098 2099 2100 2101
            if (shell)
                len += 5;
            else
                len += 1;
2102 2103 2104 2105 2106 2107 2108
            break;
        default:
            len += 1;
            break;
        }
    }

2109
    if (VIR_ALLOC_N(out, len + 1) < 0)
2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127
        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 已提交
2128 2129 2130 2131 2132 2133 2134 2135 2136
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

2148 2149 2150 2151 2152
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
2153 2154 2155 2156
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
2157

2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
#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];
};

2169
static int qemudDomainSave(virDomainPtr dom,
2170
                           const char *path) {
2171 2172 2173 2174 2175 2176 2177
    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;
2178
    struct qemud_save_header header;
2179
    int ret = -1;
2180
    virDomainEventPtr event = NULL;
2181 2182 2183 2184 2185

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

2186
    qemuDriverLock(driver);
2187 2188
    vm = virDomainFindByID(&driver->domains, dom->id);

D
Daniel P. Berrange 已提交
2189
    if (!vm) {
2190
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2191
                         _("no domain with matching id %d"), dom->id);
2192
        goto cleanup;
D
Daniel P. Berrange 已提交
2193
    }
2194

2195
    if (!virDomainIsActive(vm)) {
2196
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2197
                         "%s", _("domain is not running"));
2198
        goto cleanup;
D
Daniel P. Berrange 已提交
2199
    }
2200 2201 2202 2203 2204 2205

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
        if (qemudDomainSuspend(dom) != 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2206
                             "%s", _("failed to pause domain"));
2207
            goto cleanup;
2208 2209 2210 2211
        }
    }

    /* Get XML for the domain */
2212
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2213 2214
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2215
                         "%s", _("failed to get domain xml"));
2216
        goto cleanup;
2217 2218 2219 2220 2221 2222
    }
    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,
2223
                         _("failed to create '%s'"), path);
2224
        goto cleanup;
2225 2226 2227 2228
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2229
                         "%s", _("failed to write save header"));
2230
        goto cleanup;
2231 2232 2233 2234
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2235
                         "%s", _("failed to write xml"));
2236
        goto cleanup;
2237 2238
    }

2239 2240 2241 2242 2243 2244 2245
    if (close(fd) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         _("unable to save file %s %s"),
                         path, strerror(errno));
        goto cleanup;
    }
    fd = -1;
2246 2247 2248 2249 2250

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2251
                         "%s", _("out of memory"));
2252
        goto cleanup;
2253
    }
2254
    if (virAsprintf(&command, "migrate \"exec:"
2255
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
2256
                  "\"", safe_path) == -1) {
2257
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2258
                         "%s", _("out of memory"));
2259 2260
        command = NULL;
        goto cleanup;
2261 2262
    }

2263
    if (qemudMonitorCommand(vm, command, &info) < 0) {
2264
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2265
                         "%s", _("migrate operation failed"));
2266
        goto cleanup;
2267 2268
    }

2269 2270 2271 2272 2273 2274 2275 2276
    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"));
2277
        goto cleanup;
2278 2279
    }

2280 2281
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2282 2283 2284
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2285
    if (!vm->persistent) {
2286 2287
        virDomainRemoveInactive(&driver->domains,
                                vm);
2288 2289
        vm = NULL;
    }
2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
    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);
2301 2302
    if (vm)
        virDomainObjUnlock(vm);
2303 2304
    if (event)
        qemuDomainEventQueue(driver, event);
2305
    qemuDriverUnlock(driver);
2306
    return ret;
D
Daniel P. Berrange 已提交
2307 2308 2309
}


2310
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
2311 2312
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2313
    int max;
2314
    int ret = -1;
2315

2316
    qemuDriverLock(driver);
2317
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2318 2319
    qemuDriverUnlock(driver);

2320
    if (!vm) {
2321 2322 2323
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2324
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2325
                         _("no domain with matching uuid '%s'"), uuidstr);
2326
        goto cleanup;
2327 2328
    }

2329
    if (virDomainIsActive(vm)) {
2330
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
2331
                         _("cannot change vcpu count of an active domain"));
2332
        goto cleanup;
2333 2334 2335 2336 2337
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
2338
        goto cleanup;
2339 2340 2341 2342 2343 2344
    }

    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);
2345
        goto cleanup;
2346 2347 2348
    }

    vm->def->vcpus = nvcpus;
2349 2350 2351
    ret = 0;

cleanup:
2352 2353
    if (vm)
        virDomainObjUnlock(vm);
2354
    return ret;
2355 2356
}

2357 2358 2359 2360 2361 2362 2363

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2364 2365
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2366 2367 2368
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;
2369
    int ret = -1;
2370

2371
    qemuDriverLock(driver);
2372
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2373 2374
    qemuDriverUnlock(driver);

2375
    if (!virDomainIsActive(vm)) {
2376 2377
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2378
        goto cleanup;
2379 2380 2381 2382 2383 2384
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
2385
        goto cleanup;
2386 2387 2388
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2389
        goto cleanup;
2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404

    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) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                             _("cannot set affinity: %s"), strerror(errno));
2405
            goto cleanup;
2406 2407 2408 2409
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2410
        goto cleanup;
2411
    }
2412
    ret = 0;
2413

2414
cleanup:
2415 2416
    if (vm)
        virDomainObjUnlock(vm);
2417
    return ret;
2418 2419 2420 2421 2422 2423 2424 2425
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2426 2427
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2428 2429
    virNodeInfo nodeinfo;
    int i, v, maxcpu;
2430
    int ret = -1;
2431

2432
    qemuDriverLock(driver);
2433
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2434 2435
    qemuDriverUnlock(driver);

2436
    if (!virDomainIsActive(vm)) {
2437 2438
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2439
        goto cleanup;
2440 2441 2442
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2443
        goto cleanup;
2444 2445 2446 2447 2448 2449 2450 2451 2452

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

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

2453 2454 2455 2456 2457 2458 2459 2460
    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 */
            }
2461 2462
        }

2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
        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) {
                        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                                         _("cannot get affinity: %s"), strerror(errno));
                        goto cleanup;
                    }

                    for (i = 0 ; i < maxcpu ; i++)
                        if (CPU_ISSET(i, &mask))
                            VIR_USE_CPU(cpumap, i);
2480
                }
2481 2482 2483 2484
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
2485 2486 2487
            }
        }
    }
2488
    ret = maxinfo;
2489

2490
cleanup:
2491 2492
    if (vm)
        virDomainObjUnlock(vm);
2493
    return ret;
2494 2495 2496 2497
}
#endif /* HAVE_SCHED_GETAFFINITY */


2498
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
2499 2500
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2501
    const char *type;
2502
    int ret = -1;
2503

2504
    qemuDriverLock(driver);
2505
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2506 2507
    qemuDriverUnlock(driver);

2508
    if (!vm) {
2509 2510 2511
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2512
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2513
                         _("no domain with matching uuid '%s'"), uuidstr);
2514
        goto cleanup;
2515 2516
    }

2517
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2518 2519 2520
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
2521
        goto cleanup;
2522 2523
    }

2524
    ret = qemudGetMaxVCPUs(dom->conn, type);
2525

2526
cleanup:
2527 2528
    if (vm)
        virDomainObjUnlock(vm);
2529 2530 2531 2532
    return ret;
}


2533
static int qemudDomainRestore(virConnectPtr conn,
2534 2535 2536
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
2537
    virDomainObjPtr vm = NULL;
2538 2539 2540
    int fd = -1;
    int ret = -1;
    char *xml = NULL;
2541
    struct qemud_save_header header;
2542
    virDomainEventPtr event = NULL;
2543

2544
    qemuDriverLock(driver);
2545 2546 2547
    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2548
                         "%s", _("cannot read domain image"));
2549
        goto cleanup;
2550 2551 2552 2553
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2554
                         "%s", _("failed to read qemu header"));
2555
        goto cleanup;
2556 2557 2558 2559
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2560
                         "%s", _("image magic is incorrect"));
2561
        goto cleanup;
2562 2563 2564 2565
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2566
                         _("image version is not supported (%d > %d)"),
2567
                         header.version, QEMUD_SAVE_VERSION);
2568
        goto cleanup;
2569 2570
    }

2571
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2572
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2573
                         "%s", _("out of memory"));
2574
        goto cleanup;
2575 2576 2577 2578
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2579
                         "%s", _("failed to read XML"));
2580
        goto cleanup;
2581 2582 2583
    }

    /* Create a domain from this XML */
2584
    if (!(def = virDomainDefParseString(conn, driver->caps, xml))) {
2585
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2586
                         "%s", _("failed to parse XML"));
2587
        goto cleanup;
2588 2589 2590
    }

    /* Ensure the name and UUID don't already exist in an active VM */
2591
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2592
    if (!vm)
2593
        vm = virDomainFindByName(&driver->domains, def->name);
2594
    if (vm && virDomainIsActive(vm)) {
2595
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2596
                         _("domain is already active as '%s'"), vm->def->name);
2597
        goto cleanup;
2598 2599
    }

2600 2601 2602
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2603
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2604
                         "%s", _("failed to assign new VM"));
2605
        goto cleanup;
2606
    }
2607
    def = NULL;
2608 2609

    /* Set the migration source and start it up. */
2610
    vm->stdin_fd = fd;
2611
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio");
2612
    close(fd);
2613
    fd = -1;
2614
    vm->stdin_fd = -1;
2615
    if (ret < 0) {
2616
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2617
                         "%s", _("failed to start VM"));
2618
        if (!vm->persistent) {
2619 2620
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2621 2622
            vm = NULL;
        }
2623
        goto cleanup;
2624 2625
    }

2626 2627 2628
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
2629

2630 2631 2632
    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2633
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
2634
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2635
                             "%s", _("failed to resume domain"));
2636
            goto cleanup;
2637
        }
2638
        VIR_FREE(info);
2639 2640
        vm->state = VIR_DOMAIN_RUNNING;
    }
2641
    ret = 0;
2642

2643 2644 2645 2646 2647
cleanup:
    virDomainDefFree(def);
    VIR_FREE(xml);
    if (fd != -1)
        close(fd);
2648 2649
    if (vm)
        virDomainObjUnlock(vm);
2650 2651
    if (event)
        qemuDomainEventQueue(driver, event);
2652
    qemuDriverUnlock(driver);
2653
    return ret;
D
Daniel P. Berrange 已提交
2654 2655 2656
}


2657
static char *qemudDomainDumpXML(virDomainPtr dom,
2658
                                int flags ATTRIBUTE_UNUSED) {
2659 2660 2661 2662
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2663
    qemuDriverLock(driver);
2664
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2665 2666
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
2667
    if (!vm) {
2668 2669
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2670
        goto cleanup;
D
Daniel P. Berrange 已提交
2671 2672
    }

2673 2674 2675 2676 2677 2678
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
2679 2680
    if (vm)
        virDomainObjUnlock(vm);
2681
    return ret;
D
Daniel P. Berrange 已提交
2682 2683 2684
}


2685
static int qemudListDefinedDomains(virConnectPtr conn,
2686
                            char **const names, int nnames) {
2687
    struct qemud_driver *driver = conn->privateData;
2688
    int got = 0, i;
2689

2690
    qemuDriverLock(driver);
2691
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
2692
        virDomainObjLock(driver->domains.objs[i]);
2693 2694
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2695
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
2696
                                 "%s", _("failed to allocate space for VM name string"));
2697
                virDomainObjUnlock(driver->domains.objs[i]);
2698 2699
                goto cleanup;
            }
2700
        }
2701
        virDomainObjUnlock(driver->domains.objs[i]);
D
Daniel P. Berrange 已提交
2702
    }
2703

2704
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2705
    return got;
2706 2707 2708

 cleanup:
    for (i = 0 ; i < got ; i++)
2709
        VIR_FREE(names[i]);
2710
    qemuDriverUnlock(driver);
2711
    return -1;
D
Daniel P. Berrange 已提交
2712 2713
}

2714
static int qemudNumDefinedDomains(virConnectPtr conn) {
2715
    struct qemud_driver *driver = conn->privateData;
2716 2717
    int n = 0, i;

2718
    qemuDriverLock(driver);
2719 2720
    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2721
            n++;
2722
    qemuDriverUnlock(driver);
2723

2724
    return n;
D
Daniel P. Berrange 已提交
2725 2726 2727
}


2728
static int qemudDomainStart(virDomainPtr dom) {
2729 2730 2731
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2732
    virDomainEventPtr event = NULL;
2733

2734
    qemuDriverLock(driver);
2735
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2736 2737
    qemuDriverUnlock(driver);

2738
    if (!vm) {
2739
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2740
                         "%s", _("no domain with matching uuid"));
2741
        goto cleanup;
2742 2743
    }

2744
    ret = qemudStartVMDaemon(dom->conn, driver, vm, NULL);
2745
    if (ret != -1)
2746 2747 2748
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
2749 2750

cleanup:
2751 2752
    if (vm)
        virDomainObjUnlock(vm);
2753 2754 2755 2756 2757
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
2758
    return ret;
D
Daniel P. Berrange 已提交
2759 2760 2761
}


2762
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2763
    struct qemud_driver *driver = conn->privateData;
2764
    virDomainDefPtr def;
2765
    virDomainObjPtr vm = NULL;
2766
    virDomainPtr dom = NULL;
2767
    virDomainEventPtr event = NULL;
2768
    int newVM = 1;
2769

2770
    qemuDriverLock(driver);
2771
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
2772
        goto cleanup;
2773

2774
    vm = virDomainFindByName(&driver->domains, def->name);
2775 2776
    if (vm) {
        virDomainObjUnlock(vm);
2777
        newVM = 0;
2778
    }
2779

2780 2781 2782 2783
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2784
        goto cleanup;
2785
    }
2786
    vm->persistent = 1;
2787

2788 2789
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2790
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2791 2792
        virDomainRemoveInactive(&driver->domains,
                                vm);
2793
        vm = NULL;
2794
        goto cleanup;
2795 2796
    }

2797 2798 2799 2800 2801
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
2802

2803
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2804
    if (dom) dom->id = vm->def->id;
2805 2806

cleanup:
2807 2808
    if (vm)
        virDomainObjUnlock(vm);
2809 2810
    if (event)
        qemuDomainEventQueue(driver, event);
2811
    qemuDriverUnlock(driver);
2812
    return dom;
D
Daniel P. Berrange 已提交
2813 2814
}

2815
static int qemudDomainUndefine(virDomainPtr dom) {
2816 2817
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2818
    virDomainEventPtr event = NULL;
2819
    int ret = -1;
D
Daniel P. Berrange 已提交
2820

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

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

2830
    if (virDomainIsActive(vm)) {
2831 2832
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
2833
        goto cleanup;
D
Daniel P. Berrange 已提交
2834 2835
    }

2836 2837 2838
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
2839
        goto cleanup;
2840 2841 2842
    }

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

2845 2846 2847
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
2848

2849 2850
    virDomainRemoveInactive(&driver->domains,
                            vm);
2851
    vm = NULL;
2852
    ret = 0;
D
Daniel P. Berrange 已提交
2853

2854
cleanup:
2855 2856
    if (vm)
        virDomainObjUnlock(vm);
2857 2858
    if (event)
        qemuDomainEventQueue(driver, event);
2859
    qemuDriverUnlock(driver);
2860
    return ret;
D
Daniel P. Berrange 已提交
2861 2862
}

2863
/* Return the disks name for use in monitor commands */
2864
static char *qemudDiskDeviceName(const virConnectPtr conn,
2865
                                 const virDomainDiskDefPtr disk) {
2866 2867 2868 2869 2870 2871

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

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
2872
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2873 2874 2875 2876 2877 2878 2879
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
2880
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
2881
                ret = virAsprintf(&devname, "ide%d-hd%d", busid, devid);
2882
            else
2883
                ret = virAsprintf(&devname, "ide%d-cd%d", busid, devid);
2884 2885
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
2886
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
2887
                ret = virAsprintf(&devname, "scsi%d-hd%d", busid, devid);
2888
            else
2889
                ret = virAsprintf(&devname, "scsi%d-cd%d", busid, devid);
2890 2891
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
2892
            ret = virAsprintf(&devname, "floppy%d", devid);
2893 2894
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
2895
            ret = virAsprintf(&devname, "virtio%d", devid);
2896 2897
            break;
        default:
2898
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
2899 2900 2901 2902 2903 2904
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
2905
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2906 2907 2908 2909 2910 2911
        return NULL;
    }

    return devname;
}

2912 2913
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           virDomainObjPtr vm,
2914 2915
                                           virDomainDeviceDefPtr dev)
{
2916
    virDomainDiskDefPtr origdisk = NULL, newdisk;
2917
    char *cmd, *reply, *safe_path;
2918
    char *devname = NULL;
2919
    unsigned int qemuCmdFlags;
2920
    int i;
2921

2922
    origdisk = NULL;
2923
    newdisk = dev->data.disk;
2924 2925 2926 2927
    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];
2928
            break;
2929
        }
2930 2931 2932
    }

    if (!origdisk) {
2933
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2934 2935 2936 2937 2938 2939 2940 2941 2942
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
2943
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2944 2945 2946 2947 2948 2949
                         _("Cannot determine QEMU argv syntax %s"),
                         vm->def->emulator);
        return -1;
    }

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
2950
        if (!(devname = qemudDiskDeviceName(conn, newdisk)))
2951 2952 2953 2954 2955 2956 2957 2958 2959
            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 {
2960
            qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2961 2962 2963 2964 2965 2966 2967 2968
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
2969
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2970 2971 2972
            return -1;
        }
    }
2973

2974
    if (newdisk->src) {
2975 2976
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
2977
            qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2978
            VIR_FREE(devname);
2979 2980
            return -1;
        }
2981
        if (virAsprintf(&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
2982
            qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2983
            VIR_FREE(safe_path);
2984
            VIR_FREE(devname);
2985 2986
            return -1;
        }
2987
        VIR_FREE(safe_path);
2988

2989
    } else if (virAsprintf(&cmd, "eject %s", devname) == -1) {
2990
        qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2991
        VIR_FREE(devname);
2992 2993
        return -1;
    }
2994
    VIR_FREE(devname);
2995

2996
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
2997
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
2998
                         "%s", _("could not change cdrom media"));
2999
        VIR_FREE(cmd);
3000 3001
        return -1;
    }
3002 3003 3004 3005

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
3006
    DEBUG ("ejectable media change reply: %s", reply);
3007
    if (strstr(reply, "\ndevice ")) {
3008
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3009
                          _("changing cdrom media failed: %s"), reply);
3010 3011 3012 3013
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3014 3015
    VIR_FREE(reply);
    VIR_FREE(cmd);
3016

3017 3018
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
3019
    newdisk->src = NULL;
3020
    origdisk->type = newdisk->type;
3021 3022 3023
    return 0;
}

3024 3025 3026
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
3027 3028
{
    int ret, i;
3029
    char *cmd, *reply, *s;
3030 3031 3032 3033 3034
    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)) {
3035
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3036 3037 3038 3039 3040 3041
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3042
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3043 3044 3045 3046 3047
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3048
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3049 3050 3051 3052
                         "%s", _("out of memory"));
        return -1;
    }

3053 3054
    ret = virAsprintf(&cmd, "pci_add 0 storage file=%s,if=%s",
                      safe_path, type);
3055 3056
    VIR_FREE(safe_path);
    if (ret == -1) {
3057
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3058 3059 3060
        return ret;
    }

3061
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3062
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3063 3064 3065 3066 3067 3068 3069 3070
                         _("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... */
3071 3072 3073 3074 3075 3076
#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 已提交
3077
            qemudLog(QEMUD_WARN, "%s", _("Unable to parse slot number\n"));
3078
    } else {
3079
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
                          _("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;
}
3094

3095 3096 3097
static int qemudDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                                 virDomainObjPtr vm,
                                                 virDomainDeviceDefPtr dev)
3098
{
3099 3100
    int ret, i;
    char *safe_path;
3101 3102
    char *cmd, *reply;

3103 3104
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3105
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3106 3107 3108 3109 3110
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

3111
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3112
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3113
        return -1;
3114 3115
    }

3116 3117
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3118
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3119 3120 3121 3122
                         "%s", _("out of memory"));
        return -1;
    }

3123
    ret = virAsprintf(&cmd, "usb_add disk:%s", safe_path);
3124
    VIR_FREE(safe_path);
3125
    if (ret == -1) {
3126
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3127 3128 3129
        return ret;
    }

3130
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3131
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3132
                         "%s", _("cannot attach usb disk"));
3133 3134 3135 3136 3137 3138 3139 3140
        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 ")) {
3141
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3142
                          "%s",
3143
                          _("adding usb disk failed"));
3144 3145 3146 3147
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3148

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

3153 3154 3155 3156 3157
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3158 3159 3160
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3161 3162 3163 3164
{
    int ret;
    char *cmd, *reply;

3165
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
3166
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3167 3168
        return -1;
    }
3169

3170
    if (dev->data.hostdev->source.subsys.u.usb.vendor) {
3171 3172 3173
        ret = virAsprintf(&cmd, "usb_add host:%.4x:%.4x",
                          dev->data.hostdev->source.subsys.u.usb.vendor,
                          dev->data.hostdev->source.subsys.u.usb.product);
3174
    } else {
3175 3176 3177
        ret = virAsprintf(&cmd, "usb_add host:%.3d.%.3d",
                          dev->data.hostdev->source.subsys.u.usb.bus,
                          dev->data.hostdev->source.subsys.u.usb.device);
3178 3179
    }
    if (ret == -1) {
3180
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3181 3182 3183
        return -1;
    }

3184
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3185
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3186 3187 3188 3189 3190 3191 3192 3193 3194
                         "%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 ")) {
3195
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3196 3197 3198 3199 3200 3201
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3202

3203
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
3204

3205 3206
    VIR_FREE(reply);
    VIR_FREE(cmd);
3207 3208 3209
    return 0;
}

3210 3211
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
3212 3213 3214 3215
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3216

3217
    qemuDriverLock(driver);
3218
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3219
    if (!vm) {
3220
        qemuDriverUnlock(driver);
3221 3222
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3223
        goto cleanup;
3224 3225 3226
    }

    if (!virDomainIsActive(vm)) {
3227
        qemuDriverUnlock(driver);
3228 3229
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
3230
        goto cleanup;
3231 3232
    }

3233 3234 3235
    dev = virDomainDeviceDefParse(dom->conn,
                                  driver->caps,
                                  vm->def, xml);
3236
    qemuDriverUnlock(driver);
3237 3238 3239
    if (dev == NULL)
        goto cleanup;

3240

3241 3242
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
3243 3244
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
3245
            ret = qemudDomainChangeEjectableMedia(dom->conn, vm, dev);
3246 3247 3248
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
3249
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, vm, dev);
3250 3251
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
3252
                ret = qemudDomainAttachPciDiskDevice(dom->conn, vm, dev);
3253 3254 3255 3256 3257 3258
            }
            break;
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("this disk device type cannot be attached"));
            goto cleanup;
3259
        }
3260
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
3261 3262
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
3263
        ret = qemudDomainAttachHostDevice(dom->conn, vm, dev);
3264
    } else {
3265
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
3266
                         "%s", _("this device type cannot be attached"));
3267
        goto cleanup;
3268 3269
    }

3270
    qemudSaveDomainStatus(dom->conn, driver, vm);
3271
cleanup:
G
Guido Günther 已提交
3272 3273
    if (ret < 0)
        virDomainDeviceDefFree(dev);
3274 3275
    if (vm)
        virDomainObjUnlock(vm);
3276 3277 3278
    return ret;
}

3279 3280
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3281 3282
{
    int i, ret = -1;
3283 3284
    char *cmd = NULL;
    char *reply = NULL;
3285 3286 3287 3288 3289 3290 3291 3292 3293 3294
    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) {
3295
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3296
                         _("disk %s not found"), dev->data.disk->dst);
3297
        goto cleanup;
3298 3299 3300
    }

    if (detach->slotnum < 1) {
3301
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3302
                         _("disk %s cannot be detached - invalid slot number %d"),
3303
                           detach->dst, detach->slotnum);
3304
        goto cleanup;
3305 3306
    }

3307
    if (virAsprintf(&cmd, "pci_del 0 %d", detach->slotnum) < 0) {
3308 3309
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        goto cleanup;
3310 3311
    }

3312
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3313
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3314
                          _("failed to execute detach disk %s command"), detach->dst);
3315
        goto cleanup;
3316 3317 3318 3319 3320 3321
    }

    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")) {
3322
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3323
                          _("failed to detach disk %s: invalid slot %d"),
3324 3325
                          detach->dst, detach->slotnum);
        goto cleanup;
3326 3327 3328 3329 3330
    }

    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) {
3331 3332
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            goto cleanup;
3333 3334 3335 3336 3337 3338 3339 3340
        }
        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;
3341 3342

cleanup:
3343 3344 3345 3346 3347 3348 3349
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
3350 3351 3352 3353
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3354

3355
    qemuDriverLock(driver);
3356
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3357
    if (!vm) {
3358
        qemuDriverUnlock(driver);
3359 3360
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3361
        goto cleanup;
3362 3363 3364
    }

    if (!virDomainIsActive(vm)) {
3365
        qemuDriverUnlock(driver);
3366
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
G
Guido Günther 已提交
3367
                         "%s", _("cannot detach device on inactive domain"));
3368
        goto cleanup;
3369 3370 3371
    }

    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml);
3372
    qemuDriverUnlock(driver);
3373 3374 3375
    if (dev == NULL)
        goto cleanup;

3376 3377 3378 3379 3380

    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))
3381
        ret = qemudDomainDetachPciDiskDevice(dom->conn, vm, dev);
3382
    else
3383 3384 3385
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

3386
    qemudSaveDomainStatus(dom->conn, driver, vm);
3387 3388
cleanup:
    virDomainDeviceDefFree(dev);
3389 3390
    if (vm)
        virDomainObjUnlock(vm);
3391 3392 3393
    return ret;
}

3394
static int qemudDomainGetAutostart(virDomainPtr dom,
3395
                                   int *autostart) {
3396 3397 3398
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3399

3400
    qemuDriverLock(driver);
3401
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3402 3403
    qemuDriverUnlock(driver);

3404
    if (!vm) {
3405 3406
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3407
        goto cleanup;
3408 3409 3410
    }

    *autostart = vm->autostart;
3411
    ret = 0;
3412

3413
cleanup:
3414 3415
    if (vm)
        virDomainObjUnlock(vm);
3416
    return ret;
3417 3418
}

3419
static int qemudDomainSetAutostart(virDomainPtr dom,
3420
                                   int autostart) {
3421 3422
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3423 3424
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
3425

3426
    qemuDriverLock(driver);
3427
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3428 3429
    qemuDriverUnlock(driver);

3430
    if (!vm) {
3431 3432
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3433
        goto cleanup;
3434 3435
    }

3436 3437 3438
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
3439
        goto cleanup;
3440 3441
    }

3442 3443
    autostart = (autostart != 0);

3444 3445 3446 3447 3448
    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;
3449

3450 3451
        if (autostart) {
            int err;
3452

3453 3454 3455 3456 3457 3458
            if ((err = virFileMakePath(driver->autostartDir))) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("cannot create autostart directory %s: %s"),
                                 driver->autostartDir, strerror(err));
                goto cleanup;
            }
3459

3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
            if (symlink(configFile, autostartLink) < 0) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("Failed to create symlink '%s to '%s': %s"),
                                 autostartLink, configFile, strerror(errno));
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("Failed to delete symlink '%s': %s"),
                                 autostartLink, strerror(errno));
                goto cleanup;
            }
3473 3474
        }

3475
        vm->autostart = autostart;
3476
    }
3477
    ret = 0;
3478

3479 3480 3481
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
3482 3483
    if (vm)
        virDomainObjUnlock(vm);
3484
    return ret;
3485 3486
}

3487 3488 3489 3490 3491 3492 3493 3494 3495
/* 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)
{
3496
    struct qemud_driver *driver = dom->conn->privateData;
3497
    char *dummy, *info = NULL;
3498
    const char *p, *eol;
3499
    const char *qemu_dev_name = NULL;
3500
    size_t len;
3501
    int i, ret = -1;
3502
    virDomainObjPtr vm;
3503
    virDomainDiskDefPtr disk = NULL;
3504

3505
    qemuDriverLock(driver);
3506
    vm = virDomainFindByID(&driver->domains, dom->id);
3507
    qemuDriverUnlock(driver);
3508 3509 3510
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3511
        goto cleanup;
3512
    }
3513
    if (!virDomainIsActive (vm)) {
3514 3515
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
3516
        goto cleanup;
3517 3518
    }

3519 3520 3521 3522 3523 3524 3525 3526
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
3527 3528
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
3529
        goto cleanup;
3530 3531
    }

3532
    qemu_dev_name = qemudDiskDeviceName(dom->conn, disk);
3533
    if (!qemu_dev_name)
3534
        goto cleanup;
3535 3536
    len = strlen (qemu_dev_name);

3537
    if (qemudMonitorCommand (vm, "info blockstats", &info) < 0) {
3538 3539
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
3540
        goto cleanup;
3541 3542 3543 3544 3545 3546 3547 3548
    }
    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 已提交
3549
    if (strstr(info, "\ninfo ")) {
3550 3551 3552
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
3553
        goto cleanup;
3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579
    }

    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) {
3580
                if (STRPREFIX (p, "rd_bytes=")) {
3581 3582 3583
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
3584
                } else if (STRPREFIX (p, "wr_bytes=")) {
3585 3586 3587
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
3588
                } else if (STRPREFIX (p, "rd_operations=")) {
3589 3590 3591
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
3592
                } else if (STRPREFIX (p, "wr_operations=")) {
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603
                    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++;
            }
3604
            ret = 0;
3605
            goto cleanup;
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616
        }

        /* 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);
3617
 cleanup:
3618 3619
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
3620 3621
    if (vm)
        virDomainObjUnlock(vm);
3622
    return ret;
3623 3624
}

3625
#ifdef __linux__
3626 3627 3628 3629 3630
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
3631 3632
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3633
    int i;
3634
    int ret = -1;
3635

3636
    qemuDriverLock(driver);
3637
    vm = virDomainFindByID(&driver->domains, dom->id);
3638 3639
    qemuDriverUnlock(driver);

3640 3641
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
3642
                          _("no domain with matching id %d"), dom->id);
3643
        goto cleanup;
3644 3645
    }

3646
    if (!virDomainIsActive(vm)) {
3647
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3648
                         "%s", _("domain is not running"));
3649
        goto cleanup;
3650 3651 3652 3653
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3654
                         "%s", _("NULL or empty path"));
3655
        goto cleanup;
3656 3657 3658
    }

    /* Check the path is one of the domain's network interfaces. */
3659 3660
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
3661 3662 3663 3664
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
3665 3666
    }

3667 3668 3669 3670 3671
    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);
3672

3673
cleanup:
3674 3675
    if (vm)
        virDomainObjUnlock(vm);
3676 3677
    return ret;
}
3678
#else
3679 3680 3681 3682
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
3683 3684 3685 3686
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
}
3687
#endif
3688

3689 3690 3691 3692 3693 3694 3695
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
3696 3697 3698
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
3699

3700
    qemuDriverLock(driver);
3701
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3702 3703
    qemuDriverUnlock(driver);

3704 3705
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
3706
                          "%s", _("no domain with matching uuid"));
3707
        goto cleanup;
3708 3709 3710 3711
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3712
                         "%s", _("NULL or empty path"));
3713
        goto cleanup;
3714 3715 3716
    }

    /* Check the path belongs to this domain. */
3717 3718
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
3719 3720 3721 3722
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
3723 3724
    }

3725 3726 3727 3728 3729 3730 3731 3732 3733
    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;
        }
3734

3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749
        /* 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"));
3750 3751
    }

3752 3753 3754
cleanup:
    if (fd >= 0)
        close (fd);
3755 3756
    if (vm)
        virDomainObjUnlock(vm);
3757 3758 3759
    return ret;
}

R
Richard W.M. Jones 已提交
3760 3761 3762 3763 3764 3765
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
3766 3767 3768
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char cmd[256], *info = NULL;
R
Richard W.M. Jones 已提交
3769 3770 3771
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

3772
    qemuDriverLock(driver);
3773
    vm = virDomainFindByID(&driver->domains, dom->id);
3774
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
3775 3776 3777 3778

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3779 3780 3781 3782 3783 3784 3785
        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 已提交
3786 3787
    }

3788
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3789 3790
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
3791
        goto cleanup;
R
Richard W.M. Jones 已提交
3792 3793 3794 3795 3796 3797
    }

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

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
3803
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
R
Richard W.M. Jones 已提交
3804
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3805
                          "%s", _("'memsave' command failed"));
3806
        goto cleanup;
R
Richard W.M. Jones 已提交
3807 3808 3809 3810 3811 3812 3813 3814
    }

    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));
3815
        goto cleanup;
R
Richard W.M. Jones 已提交
3816 3817 3818
    }

    ret = 0;
3819 3820 3821

cleanup:
    VIR_FREE(info);
R
Richard W.M. Jones 已提交
3822 3823
    if (fd >= 0) close (fd);
    unlink (tmp);
3824 3825
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
3826 3827 3828
    return ret;
}

3829

3830 3831
static int
qemudDomainEventRegister (virConnectPtr conn,
3832
                          virConnectDomainEventCallback callback,
3833 3834
                          void *opaque,
                          virFreeCallback freecb)
3835
{
3836 3837 3838
    struct qemud_driver *driver = conn->privateData;
    int ret;

3839
    qemuDriverLock(driver);
3840 3841
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
3842
    qemuDriverUnlock(driver);
3843

3844
    return ret;
3845 3846 3847 3848
}

static int
qemudDomainEventDeregister (virConnectPtr conn,
3849
                            virConnectDomainEventCallback callback)
3850
{
3851 3852 3853
    struct qemud_driver *driver = conn->privateData;
    int ret;

3854
    qemuDriverLock(driver);
3855 3856 3857 3858 3859 3860
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
3861
    qemuDriverUnlock(driver);
3862

3863
    return ret;
3864 3865
}

3866 3867 3868 3869 3870
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
                                        virConnectDomainEventCallback cb,
                                        void *cbopaque,
                                        void *opaque)
3871
{
3872
    struct qemud_driver *driver = opaque;
3873

3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
    /* 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);
3918 3919
}

D
Daniel Veillard 已提交
3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937
/* 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;
3938 3939
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
3940 3941 3942 3943 3944
    virDomainObjPtr vm = NULL;
    int this_port;
    char hostname [HOST_NAME_MAX+1];
    char migrateFrom [64];
    const char *p;
3945
    virDomainEventPtr event = NULL;
3946 3947 3948
    int ret = -1;;

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

3950
    qemuDriverLock(driver);
D
Daniel Veillard 已提交
3951 3952 3953
    if (!dom_xml) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                          "%s", _("no domain XML passed"));
3954
        goto cleanup;
D
Daniel Veillard 已提交
3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974
    }

    /* 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));
3975
            goto cleanup;
D
Daniel Veillard 已提交
3976 3977 3978
        }

        /* Caller frees */
3979
        if (virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port) < 0) {
D
Daniel Veillard 已提交
3980 3981
            qemudReportError (dconn, NULL, NULL, VIR_ERR_NO_MEMORY,
                              "%s", strerror (errno));
3982
            goto cleanup;
D
Daniel Veillard 已提交
3983 3984 3985 3986 3987 3988 3989 3990 3991
        }
    } 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"));
3992
            goto cleanup;
D
Daniel Veillard 已提交
3993 3994 3995 3996 3997 3998 3999 4000 4001
        }

        /* 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"));
4002
            goto cleanup;
D
Daniel Veillard 已提交
4003 4004 4005 4006 4007 4008 4009
        }
    }

    /* Parse the domain XML. */
    if (!(def = virDomainDefParseString(dconn, driver->caps, dom_xml))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to parse XML"));
4010
        goto cleanup;
D
Daniel Veillard 已提交
4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026
    }

    /* 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"));
4027
        goto cleanup;
D
Daniel Veillard 已提交
4028 4029 4030 4031 4032 4033 4034 4035 4036
    }
#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);
4037
            goto cleanup;
D
Daniel Veillard 已提交
4038 4039 4040 4041 4042 4043 4044 4045
        }
    }

    if (!(vm = virDomainAssignDef(dconn,
                                  &driver->domains,
                                  def))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to assign new VM"));
4046
        goto cleanup;
D
Daniel Veillard 已提交
4047
    }
4048
    def = NULL;
D
Daniel Veillard 已提交
4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059

    /* 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);
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom) < 0) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to start listening VM"));
4060
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4061
            virDomainRemoveInactive(&driver->domains, vm);
4062 4063
            vm = NULL;
        }
4064
        goto cleanup;
D
Daniel Veillard 已提交
4065
    }
4066 4067 4068 4069

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

4072 4073 4074 4075 4076
cleanup:
    virDomainDefFree(def);
    if (ret != 0) {
        VIR_FREE(*uri_out);
    }
4077 4078
    if (vm)
        virDomainObjUnlock(vm);
4079 4080
    if (event)
        qemuDomainEventQueue(driver, event);
4081
    qemuDriverUnlock(driver);
4082
    return ret;
D
Daniel Veillard 已提交
4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094
}

/* 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)
{
4095 4096
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4097
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4098 4099
    char *safe_uri;
    char cmd[HOST_NAME_MAX+50];
4100 4101
    char *info = NULL;
    int ret = -1;
D
Daniel Veillard 已提交
4102

4103
    qemuDriverLock(driver);
4104
    vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel Veillard 已提交
4105 4106 4107
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
4108
        goto cleanup;
D
Daniel Veillard 已提交
4109 4110 4111 4112 4113
    }

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

4117 4118 4119
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
        snprintf(cmd, sizeof cmd, "%s", "stop");
4120
        qemudMonitorCommand (vm, cmd, &info);
4121 4122 4123
        DEBUG ("stop reply: %s", info);
        VIR_FREE(info);

4124 4125 4126 4127 4128 4129
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
        event = NULL;
4130 4131
    }

D
Daniel Veillard 已提交
4132 4133 4134
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
4135
        qemudMonitorCommand (vm, cmd, &info);
D
Daniel Veillard 已提交
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145

        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));
4146
        goto cleanup;
D
Daniel Veillard 已提交
4147 4148 4149 4150
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

4151
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
D
Daniel Veillard 已提交
4152 4153
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("migrate operation failed"));
4154
        goto cleanup;
D
Daniel Veillard 已提交
4155 4156 4157 4158 4159 4160 4161 4162
    }

    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);
4163
        goto cleanup;
D
Daniel Veillard 已提交
4164 4165 4166 4167
    }

    /* Clean up the source domain. */
    qemudShutdownVMDaemon (dom->conn, driver, vm);
4168 4169 4170 4171

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
4172
    if (!vm->persistent) {
D
Daniel Veillard 已提交
4173
        virDomainRemoveInactive(&driver->domains, vm);
4174 4175
        vm = NULL;
    }
4176
    ret = 0;
D
Daniel Veillard 已提交
4177

4178 4179
cleanup:
    VIR_FREE(info);
4180 4181
    if (vm)
        virDomainObjUnlock(vm);
4182 4183
    if (event)
        qemuDomainEventQueue(driver, event);
4184
    qemuDriverUnlock(driver);
4185
    return ret;
D
Daniel Veillard 已提交
4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197
}

/* 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)
{
4198 4199 4200
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4201
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4202 4203
    char *info = NULL;

4204
    qemuDriverLock(driver);
4205
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
4206 4207 4208
    if (!vm) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching name %s"), dname);
4209
        goto cleanup;
D
Daniel Veillard 已提交
4210 4211 4212 4213 4214 4215 4216 4217 4218
    }

    /* 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;
4219 4220 4221
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
D
Daniel Veillard 已提交
4222 4223
    } else {
        qemudShutdownVMDaemon (dconn, driver, vm);
4224 4225 4226
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
4227
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4228
            virDomainRemoveInactive(&driver->domains, vm);
4229 4230
            vm = NULL;
        }
D
Daniel Veillard 已提交
4231
    }
4232 4233

cleanup:
4234 4235
    if (vm)
        virDomainObjUnlock(vm);
4236 4237
    if (event)
        qemuDomainEventQueue(driver, event);
4238
    qemuDriverUnlock(driver);
4239
    return dom;
D
Daniel Veillard 已提交
4240 4241
}

4242 4243 4244 4245 4246
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
4247
    qemudSupportsFeature, /* supports_feature */
4248 4249
    qemudGetType, /* type */
    qemudGetVersion, /* version */
4250
    qemudGetHostname, /* hostname */
4251
    NULL, /* URI  */
4252 4253 4254 4255 4256
    qemudGetMaxVCPUs, /* getMaxVcpus */
    qemudGetNodeInfo, /* nodeGetInfo */
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
4257
    qemudDomainCreate, /* domainCreateXML */
4258 4259 4260 4261 4262
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
4263
    qemudDomainShutdown, /* domainShutdown */
4264 4265 4266
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
4267 4268 4269
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
4270 4271 4272 4273
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
4274
    qemudDomainSetVcpus, /* domainSetVcpus */
4275 4276 4277 4278
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
4279 4280
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
4281
#endif
4282
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
4283 4284 4285 4286 4287 4288
    qemudDomainDumpXML, /* domainDumpXML */
    qemudListDefinedDomains, /* listDomains */
    qemudNumDefinedDomains, /* numOfDomains */
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
4289
    qemudDomainAttachDevice, /* domainAttachDevice */
4290
    qemudDomainDetachDevice, /* domainDetachDevice */
4291 4292 4293 4294 4295
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
4296 4297
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
4298
    NULL, /* domainMigrateFinish */
4299
    qemudDomainBlockStats, /* domainBlockStats */
4300
    qemudDomainInterfaceStats, /* domainInterfaceStats */
4301
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
4302
    qemudDomainMemoryPeek, /* domainMemoryPeek */
4303 4304 4305 4306
#if HAVE_NUMACTL
    qemudNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    qemudNodeGetFreeMemory,  /* getFreeMemory */
#else
4307
    NULL, /* nodeGetCellsFreeMemory */
4308
    NULL, /* getFreeMemory */
4309
#endif
4310 4311
    qemudDomainEventRegister, /* domainEventRegister */
    qemudDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
4312 4313
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
4314 4315 4316
};


4317
static virStateDriver qemuStateDriver = {
4318 4319 4320 4321
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
4322
};
4323

4324
int qemuRegister(void) {
4325 4326 4327 4328 4329
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}