qemu_driver.c 130.9 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
static void qemuDriverLock(struct qemud_driver *driver)
{
81
    virMutexLock(&driver->lock);
82 83 84
}
static void qemuDriverUnlock(struct qemud_driver *driver)
{
85
    virMutexUnlock(&driver->lock);
86 87
}

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 149 150 151
static int
qemudLogFD(virConnectPtr conn, const char* logDir, const char* name)
{
    char logfile[PATH_MAX];
    mode_t logmode;
    uid_t uid = geteuid();
G
Guido Günther 已提交
152
    int ret, fd = -1;
153

G
Guido Günther 已提交
154 155
    if ((ret = snprintf(logfile, sizeof(logfile), "%s/%s.log", logDir, name))
        < 0 || ret >= sizeof(logfile)) {
156
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
G
Guido Günther 已提交
157
                         _("failed to build logfile name %s/%s.log"),
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
                         logDir, name);
        return -1;
    }

    logmode = O_CREAT | O_WRONLY;
    if (uid != 0)
        logmode |= O_TRUNC;
    else
        logmode |= O_APPEND;
    if ((fd = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("failed to create logfile %s: %s"),
                         logfile, strerror(errno));
        return -1;
    }
    if (qemudSetCloseExec(fd) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Unable to set VM logfile close-on-exec flag %s"),
                         strerror(errno));
        close(fd);
        return -1;
    }
    return fd;
}


184 185 186
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;
187 188 189 190 191 192 193 194 195
    /* 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 */
196 197

    for (i = 0 ; i < driver->domains.count ; i++) {
198
        virDomainObjPtr vm = driver->domains.objs[i];
199
        virDomainObjLock(vm);
200 201
        if (vm->autostart &&
            !virDomainIsActive(vm)) {
202
            int ret = qemudStartVMDaemon(conn, driver, vm, NULL);
203 204 205 206 207 208
            if (ret < 0) {
                virErrorPtr err = virGetLastError();
                qemudLog(QEMUD_ERR, _("Failed to autostart VM '%s': %s\n"),
                         vm->def->name,
                         err ? err->message : NULL);
            } else {
209 210 211 212 213 214
                virDomainEventPtr event =
                    virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             VIR_DOMAIN_EVENT_STARTED_BOOTED);
                if (event)
                    qemuDomainEventQueue(driver, event);
215
            }
216
        }
217
        virDomainObjUnlock(vm);
218
    }
219 220

    virConnectClose(conn);
221 222
}

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

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


261 262 263 264 265 266 267
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
268 269 270
    uid_t uid = geteuid();
    struct passwd *pw;
    char *base = NULL;
D
Daniel P. Berrange 已提交
271
    char driverConf[PATH_MAX];
272

273
    if (VIR_ALLOC(qemu_driver) < 0)
274 275
        return -1;

276 277 278 279 280
    if (virMutexInit(&qemu_driver->lock) < 0) {
        qemudLog(QEMUD_ERROR, "%s", _("cannot initialize mutex"));
        VIR_FREE(qemu_driver);
        return -1;
    }
281 282
    qemuDriverLock(qemu_driver);

283 284 285
    /* Don't have a dom0 so start from 1 */
    qemu_driver->nextvmid = 1;

286 287
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
288
        goto out_of_memory;
289 290 291 292 293 294
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

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

296
    if (!uid) {
297 298
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
299
            goto out_of_memory;
300

D
Daniel P. Berrange 已提交
301
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
302
            goto out_of_memory;
303 304 305 306

        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu/", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
307 308
    } else {
        if (!(pw = getpwuid(uid))) {
309
            qemudLog(QEMUD_ERR, _("Failed to find user record for uid '%d': %s\n"),
310
                     uid, strerror(errno));
311
            goto error;
312 313
        }

314 315
        if (virAsprintf(&qemu_driver->logDir,
                        "%s/.libvirt/qemu/log", pw->pw_dir) == -1)
316
            goto out_of_memory;
317

318
        if (virAsprintf(&base, "%s/.libvirt", pw->pw_dir) == -1)
319
            goto out_of_memory;
320 321 322 323 324 325 326 327 328

        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;
329 330 331 332 333
    }

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

338
    if (virAsprintf(&qemu_driver->configDir, "%s/qemu", base) == -1)
339 340
        goto out_of_memory;

341
    if (virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
342 343
        goto out_of_memory;

344
    VIR_FREE(base);
345 346 347

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

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
350
        goto error;
D
Daniel P. Berrange 已提交
351 352
    }

353 354 355 356
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
357
                                qemu_driver->autostartDir,
358 359
                                NULL, NULL) < 0)
        goto error;
360 361
    qemudAutostartConfigs(qemu_driver);

362 363
    qemuDriverUnlock(qemu_driver);

364 365
    return 0;

366
out_of_memory:
J
Jim Meyering 已提交
367
    qemudLog (QEMUD_ERR,
368
              "%s", _("qemudStartup: out of memory\n"));
369 370 371
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
372
    VIR_FREE(base);
373
    qemudShutdown();
374 375 376
    return -1;
}

377 378 379 380
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

381 382 383 384 385 386 387 388
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
389 390
}

391 392 393 394 395 396 397 398
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
399 400 401
    if (!qemu_driver)
        return 0;

402
    qemuDriverLock(qemu_driver);
403 404 405 406
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
407 408
                            qemu_driver->autostartDir,
                            qemudNotifyLoadDomain, qemu_driver);
409

410
    qemudAutostartConfigs(qemu_driver);
411
    qemuDriverUnlock(qemu_driver);
412 413

    return 0;
414 415
}

416 417 418 419 420 421 422 423 424 425
/**
 * 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) {
426
    unsigned int i;
427
    int active = 0;
428

429 430 431
    if (!qemu_driver)
        return 0;

432 433 434 435 436 437 438 439
    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);
    }
440

441 442
    qemuDriverUnlock(qemu_driver);
    return active;
443 444
}

445 446 447 448 449 450 451
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
452
    unsigned int i;
453

454
    if (!qemu_driver)
455
        return -1;
456

457
    qemuDriverLock(qemu_driver);
458 459
    virCapabilitiesFree(qemu_driver->caps);

460
    /* shutdown active VMs */
461 462
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr dom = qemu_driver->domains.objs[i];
463
        virDomainObjLock(dom);
464 465
        if (virDomainIsActive(dom))
            qemudShutdownVMDaemon(NULL, qemu_driver, dom);
466
        virDomainObjUnlock(dom);
467
    }
468

469
    virDomainObjListFree(&qemu_driver->domains);
470

471
    VIR_FREE(qemu_driver->logDir);
472 473
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
474
    VIR_FREE(qemu_driver->stateDir);
475
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
476
    VIR_FREE(qemu_driver->vncListen);
D
Daniel P. Berrange 已提交
477

478 479
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
480 481 482 483
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

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

485 486 487
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

488
    qemuDriverUnlock(qemu_driver);
489
    virMutexDestroy(&qemu_driver->lock);
490
    VIR_FREE(qemu_driver);
491 492

    return 0;
493 494 495
}

/* Return -1 for error, 1 to continue reading and 0 for success */
496
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
497
                                      virDomainObjPtr vm,
498 499 500 501
                                      const char *output,
                                      int fd);

static int
502
qemudReadMonitorOutput(virConnectPtr conn,
503
                       virDomainObjPtr vm,
504 505 506 507
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
508 509
                       const char *what,
                       int timeout)
510 511 512 513 514 515 516 517 518 519
{
    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) {
520
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
521
                             _("QEMU quit during %s startup\n%s"), what, buf);
522 523 524 525 526 527 528 529
            return -1;
        }
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
530
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
531
                                 _("Failure while reading %s startup output: %s"),
532 533 534 535
                                 what, strerror(errno));
                return -1;
            }

536
            ret = poll(&pfd, 1, timeout);
537
            if (ret == 0) {
538
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
539
                                 _("Timed out while reading %s startup output"), what);
540 541 542
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
543
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
544
                                     _("Failure while reading %s startup output: %s"),
545 546 547 548 549 550 551 552 553
                                     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;

554
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
555
                                 _("Failure while reading %s startup output"), what);
556 557 558 559 560
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
561
            if ((ret = func(conn, vm, buf, fd)) != 1)
562 563 564 565
                return ret;
        }
    }

566
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
567
                     _("Out of space while reading %s startup output"), what);
568 569 570 571 572
    return -1;

}

static int
573
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
574
                        virDomainObjPtr vm,
575 576 577 578 579 580 581 582 583 584 585
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

586
static int qemudOpenMonitor(virConnectPtr conn,
587
                            virDomainObjPtr vm,
588
                            const char *monitor) {
589 590 591 592
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
593
    if ((monfd = open(monitor, O_RDWR)) < 0) {
594
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
595
                         _("Unable to open monitor path %s"), monitor);
596 597 598
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
599
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
600
                         "%s", _("Unable to set monitor close-on-exec flag"));
601 602 603
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
604
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
605
                         "%s", _("Unable to put monitor into non-blocking mode"));
606 607 608
        goto error;
    }

609
    ret = qemudReadMonitorOutput(conn,
610
                                 vm, monfd,
611 612
                                 buf, sizeof(buf),
                                 qemudCheckMonitorPrompt,
613
                                 "monitor", 10000);
614

615 616 617 618 619 620
    if (!(vm->monitorpath = strdup(monitor))) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for monitor path"));
        goto error;
    }

621 622 623 624
    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

625 626 627 628 629
 error:
    close(monfd);
    return ret;
}

630 631
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
632
                                   size_t *offset,
633
                                   char **path) {
634
    static const char needle[] = "char device redirected to";
635
    char *tmp, *dev;
636

637
    VIR_FREE(*path);
638
    /* First look for our magic string */
639 640 641 642 643
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
644

645 646 647 648 649
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
650
        if (c_isspace(*tmp)) {
651 652 653 654 655 656 657
            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';
658
            /* ... now further update offset till we get EOL */
659
            *offset = tmp - haystack;
660 661
            return 0;
        }
662
        tmp++;
663 664 665 666 667
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
668 669
     * least see a \n - indicate that we want to carry
     * on trying again
670
     */
671
    return 1;
672 673 674
}

static int
675
qemudFindCharDevicePTYs(virConnectPtr conn,
676
                        virDomainObjPtr vm,
677 678
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
679
{
680
    char *monitor = NULL;
681
    size_t offset = 0;
682
    int ret, i;
683 684 685 686 687

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

689
    /* So first comes the monitor device */
690 691
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
692

693
    /* then the serial devices */
694 695
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
696 697 698 699
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
700 701 702 703
        }
    }

    /* and finally the parallel devices */
704 705
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
706 707 708 709
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
710 711 712 713
        }
    }

    /* Got them all, so now open the monitor console */
714
    ret = qemudOpenMonitor(conn, vm, monitor);
715 716 717 718

cleanup:
    VIR_FREE(monitor);
    return ret;
719 720
}

721
static int qemudWaitForMonitor(virConnectPtr conn,
722
                               virDomainObjPtr vm) {
723
    char buf[1024]; /* Plenty of space to get startup greeting */
724
    int ret = qemudReadMonitorOutput(conn,
725
                                     vm, vm->stderr_fd,
726
                                     buf, sizeof(buf),
727
                                     qemudFindCharDevicePTYs,
728
                                     "console", 3000);
729 730

    buf[sizeof(buf)-1] = '\0';
731 732

    if (safewrite(vm->logfile, buf, strlen(buf)) < 0) {
733
        /* Log, but ignore failures to write logfile for VM */
734
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
735 736 737 738 739
                 strerror(errno));
    }
    return ret;
}

740 741
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
742
                    virDomainObjPtr vm) {
743 744 745 746 747 748
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
749
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
750 751 752 753 754 755 756 757 758 759
        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;
    }

760
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
761 762 763 764
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

765
    if (qemudMonitorCommand(vm, "info cpus", &qemucpus) < 0) {
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
        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;

824
    VIR_FREE(qemucpus);
825 826 827 828
    return 0;

error:
    VIR_FREE(vm->vcpupids);
829 830
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
831 832 833 834 835 836 837 838

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

839 840
static int
qemudInitCpus(virConnectPtr conn,
D
Daniel Veillard 已提交
841 842
              virDomainObjPtr vm,
              const char *migrateFrom) {
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
    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 已提交
858 859 860 861 862 863
    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++)
864
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
865
    }
866 867 868 869 870 871 872 873 874 875 876 877

    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 已提交
878 879
    if (migrateFrom == NULL) {
        /* Allow the CPUS to start executing */
880
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
D
Daniel Veillard 已提交
881 882 883 884 885
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("resume operation failed"));
            return -1;
        }
        VIR_FREE(info);
886 887 888 889 890 891
    }

    return 0;
}


892
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
    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;
}

928 929 930
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

931 932
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
933 934
                              virDomainObjPtr vm,
                              const char *migrateFrom) {
935
    const char **argv = NULL, **tmp;
936
    const char **progenv = NULL;
937
    int i, ret;
938
    struct stat sb;
939 940
    int *tapfds = NULL;
    int ntapfds = 0;
941
    unsigned int qemuCmdFlags;
942
    fd_set keepfd;
943
    const char *emulator;
G
Guido Günther 已提交
944
    pid_t child;
945 946

    FD_ZERO(&keepfd);
947

948
    if (virDomainIsActive(vm)) {
949
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
950
                         "%s", _("VM is already active"));
951 952 953
        return -1;
    }

954 955 956
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
957
        int port = qemudNextFreeVNCPort(driver);
958
        if (port < 0) {
959
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
960
                             "%s", _("Unable to find an unused VNC port"));
961 962
            return -1;
        }
963 964
        vm->def->graphics->data.vnc.port = port;
    }
965

966
    if (virFileMakePath(driver->logDir) < 0) {
967
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
968
                         _("cannot create log directory %s: %s"),
969
                         driver->logDir, strerror(errno));
970 971 972
        return -1;
    }

973
    if((vm->logfile = qemudLogFD(conn, driver->logDir, vm->def->name)) < 0)
974 975
        return -1;

976 977 978 979 980 981
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

982 983 984 985
    /* 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
     */
986
    if (stat(emulator, &sb) < 0) {
987 988
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot find QEMU binary %s: %s"),
989
                         emulator,
990 991 992 993
                         strerror(errno));
        return -1;
    }

994
    if (qemudExtractVersionInfo(emulator,
995 996 997 998
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
999
                         emulator);
1000 1001
        return -1;
    }
1002

1003
    vm->def->id = driver->nextvmid++;
1004
    if (qemudBuildCommandLine(conn, driver, vm,
1005
                              qemuCmdFlags, &argv, &progenv,
1006
                              &tapfds, &ntapfds, migrateFrom) < 0) {
1007
        close(vm->logfile);
1008
        vm->def->id = -1;
1009 1010 1011 1012
        vm->logfile = -1;
        return -1;
    }

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    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++;
    }
1023 1024
    tmp = argv;
    while (*tmp) {
1025
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
1026
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1027
                     errno, strerror(errno));
1028
        if (safewrite(vm->logfile, " ", 1) < 0)
1029
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1030 1031 1032
                     errno, strerror(errno));
        tmp++;
    }
1033
    if (safewrite(vm->logfile, "\n", 1) < 0)
1034
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
1035 1036
                 errno, strerror(errno));

1037 1038 1039
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;

1040 1041 1042
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

G
Guido Günther 已提交
1043
    ret = virExec(conn, argv, progenv, &keepfd, &child,
1044
                  vm->stdin_fd, &vm->stdout_fd, &vm->stderr_fd,
G
Guido Günther 已提交
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
                  VIR_EXEC_NONBLOCK | VIR_EXEC_DAEMON);

    /* wait for qemu process to to show up */
    if (ret == 0) {
        int retries = 100;
        while (retries) {
            if ((ret = virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) == 0)
                break;
            usleep(100*1000);
            retries--;
        }
        if (ret)
            qemudLog(QEMUD_WARN, _("Domain %s didn't show up\n"), vm->def->name);
    }

    if (ret == 0) {
1061
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
G
Guido Günther 已提交
1062
    } else
1063
        vm->def->id = -1;
1064

1065
    for (i = 0 ; argv[i] ; i++)
1066 1067
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
1068

1069 1070 1071 1072
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

1073 1074 1075
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
1076
        }
1077
        VIR_FREE(tapfds);
1078 1079
    }

1080
    if (ret == 0) {
1081
        if (((vm->stdout_watch = virEventAddHandle(vm->stdout_fd,
1082 1083 1084 1085 1086
                                                   VIR_EVENT_HANDLE_READABLE |
                                                   VIR_EVENT_HANDLE_ERROR |
                                                   VIR_EVENT_HANDLE_HANGUP,
                                                   qemudDispatchVMEvent,
                                                   driver, NULL)) < 0) ||
1087 1088 1089 1090 1091
            ((vm->stderr_watch = virEventAddHandle(vm->stderr_fd,
                                                   VIR_EVENT_HANDLE_READABLE |
                                                   VIR_EVENT_HANDLE_ERROR |
                                                   VIR_EVENT_HANDLE_HANGUP,
                                                   qemudDispatchVMEvent,
1092
                                                   driver, NULL)) < 0) ||
1093 1094 1095
            (qemudWaitForMonitor(conn, vm) < 0) ||
            (qemudDetectVcpuPIDs(conn, vm) < 0) ||
            (qemudInitCpus(conn, vm, migrateFrom) < 0)) {
1096 1097 1098
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
1099
    }
1100
    qemudSaveDomainStatus(conn, qemu_driver, vm);
1101

1102
    return ret;
1103 1104
}

1105
static int qemudVMData(struct qemud_driver *driver ATTRIBUTE_UNUSED,
1106
                       virDomainObjPtr vm, int fd) {
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    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';

1123
        if (safewrite(vm->logfile, buf, ret) < 0) {
1124
            /* Log, but ignore failures to write logfile for VM */
1125
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1126 1127 1128 1129 1130 1131
                     strerror(errno));
        }
    }
}


1132
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
1133 1134
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
1135
        return;
1136

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

G
Guido Günther 已提交
1139 1140 1141 1142
    if (virKillProcess(vm->pid, 0) == 0 &&
        virKillProcess(vm->pid, SIGTERM) < 0)
        qemudLog(QEMUD_ERROR, _("Failed to send SIGTERM to %s (%d): %s\n"),
                 vm->def->name, vm->pid, strerror(errno));
1143

1144 1145
    qemudVMData(driver, vm, vm->stdout_fd);
    qemudVMData(driver, vm, vm->stderr_fd);
1146

1147 1148
    virEventRemoveHandle(vm->stdout_watch);
    virEventRemoveHandle(vm->stderr_watch);
1149 1150

    if (close(vm->logfile) < 0)
1151
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
1152
                 errno, strerror(errno));
1153 1154
    close(vm->stdout_fd);
    close(vm->stderr_fd);
1155 1156 1157
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
1158 1159
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;
1160 1161
    vm->monitor = -1;

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

G
Guido Günther 已提交
1165
    qemudRemoveDomainStatus(conn, driver, vm);
1166
    vm->pid = -1;
1167
    vm->def->id = -1;
1168
    vm->state = VIR_DOMAIN_SHUTOFF;
1169
    VIR_FREE(vm->vcpupids);
1170
    vm->nvcpupids = 0;
1171 1172

    if (vm->newDef) {
1173
        virDomainDefFree(vm->def);
1174
        vm->def = vm->newDef;
1175
        vm->def->id = -1;
1176 1177 1178 1179 1180
        vm->newDef = NULL;
    }
}


1181
static void
1182
qemudDispatchVMEvent(int watch, int fd, int events, void *opaque) {
1183
    struct qemud_driver *driver = opaque;
1184
    virDomainObjPtr vm = NULL;
1185
    virDomainEventPtr event = NULL;
1186
    unsigned int i;
1187
    int quit = 0, failed = 0;
1188

1189
    qemuDriverLock(driver);
1190
    for (i = 0 ; i < driver->domains.count ; i++) {
1191 1192 1193 1194 1195 1196
        virDomainObjPtr tmpvm = driver->domains.objs[i];
        virDomainObjLock(tmpvm);
        if (virDomainIsActive(tmpvm) &&
            (tmpvm->stdout_watch == watch ||
             tmpvm->stderr_watch == watch)) {
            vm = tmpvm;
1197
            break;
1198
        }
1199
        virDomainObjUnlock(tmpvm);
1200 1201 1202
    }

    if (!vm)
1203
        goto cleanup;
1204

1205 1206
    if (vm->stdout_fd != fd &&
        vm->stderr_fd != fd) {
1207 1208 1209 1210 1211 1212 1213 1214
        failed = 1;
    } else {
        if (events & VIR_EVENT_HANDLE_READABLE) {
            if (qemudVMData(driver, vm, fd) < 0)
                failed = 1;
        } else {
            quit = 1;
        }
1215 1216
    }

1217
    if (failed || quit) {
1218 1219 1220 1221 1222
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         quit ?
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN :
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
        qemudShutdownVMDaemon(NULL, driver, vm);
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains,
                                    vm);
            vm = NULL;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1234 1235
    if (event)
        qemuDomainEventQueue(driver, event);
1236
    qemuDriverUnlock(driver);
1237 1238
}

1239
static int
1240
qemudMonitorCommand (const virDomainObjPtr vm,
1241 1242
                     const char *cmd,
                     char **reply) {
D
Daniel P. Berrange 已提交
1243 1244
    int size = 0;
    char *buf = NULL;
1245
    size_t cmdlen = strlen(cmd);
D
Daniel P. Berrange 已提交
1246

1247 1248 1249
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        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 已提交
1262

1263 1264
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1265 1266 1267 1268 1269
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1270
                goto error;
1271
            }
1272
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1273 1274
                goto error;

D
Daniel P. Berrange 已提交
1275 1276 1277 1278
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1279

D
Daniel P. Berrange 已提交
1280
        /* Look for QEMU prompt to indicate completion */
D
Daniel P. Berrange 已提交
1281
        if (buf && ((tmp = strstr(buf, "\n(qemu) ")) != NULL)) {
C
Cole Robinson 已提交
1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
            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 已提交
1299 1300 1301 1302 1303 1304 1305
            break;
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1306
            goto error;
D
Daniel P. Berrange 已提交
1307 1308 1309
        }
    }

1310 1311
    /* Log, but ignore failures to write logfile for VM */
    if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1312
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1313 1314
                 strerror(errno));

D
Daniel P. Berrange 已提交
1315 1316
    *reply = buf;
    return 0;
1317 1318 1319 1320 1321

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1322
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1323
                     strerror(errno));
1324
        VIR_FREE(buf);
1325 1326
    }
    return -1;
D
Daniel P. Berrange 已提交
1327 1328
}

1329 1330 1331 1332 1333 1334
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
1335
static int qemudProbe(void)
1336 1337 1338
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
G
Guido Günther 已提交
1339
        (virFileExists("/usr/bin/kvm")) ||
1340 1341 1342 1343
        (virFileExists("/usr/bin/xenner")))
        return 1;

    return 0;
1344
}
1345

1346
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1347
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1348
                                  int flags ATTRIBUTE_UNUSED) {
1349 1350 1351
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1352
        goto decline;
1353

1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    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)
1365 1366
        goto decline;

1367
    if (STRNEQ (conn->uri->scheme, "qemu"))
1368 1369
        goto decline;

1370
    if (uid != 0) {
1371
        if (STRNEQ (conn->uri->path, "/session"))
1372
            goto decline;
1373
    } else { /* root */
1374 1375
        if (STRNEQ (conn->uri->path, "/system") &&
            STRNEQ (conn->uri->path, "/session"))
1376
            goto decline;
1377 1378 1379 1380 1381
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1382 1383

 decline:
1384
    return VIR_DRV_OPEN_DECLINED;
1385 1386 1387
}

static int qemudClose(virConnectPtr conn) {
1388
    struct qemud_driver *driver = conn->privateData;
1389 1390 1391

    /* Get rid of callbacks registered for this conn */
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
1392 1393 1394 1395 1396 1397

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
/* 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;
    }
}

1408
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1409
    return "QEMU";
1410 1411
}

1412 1413 1414 1415 1416

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

    int r, fd;
1417

1418 1419
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1420
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        return maxvcpus;
    }

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

    close(fd);
    return maxvcpus;
}


1433
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1434 1435 1436
    if (!type)
        return 16;

1437
    if (STRCASEEQ(type, "qemu"))
1438 1439
        return 16;

1440
    if (STRCASEEQ(type, "kvm"))
1441
        return kvmGetMaxVCPUs();
1442

1443
    if (STRCASEEQ(type, "kqemu"))
1444
        return 1;
1445 1446 1447

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1448 1449 1450
    return -1;
}

1451 1452 1453
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1454 1455 1456
}


1457
static char *qemudGetCapabilities(virConnectPtr conn) {
1458
    struct qemud_driver *driver = conn->privateData;
1459
    char *xml;
1460

1461
    qemuDriverLock(driver);
1462
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1463 1464
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                 "%s", _("failed to allocate space for capabilities support"));
1465
    qemuDriverUnlock(driver);
1466

1467
    return xml;
1468 1469 1470
}


1471 1472 1473 1474 1475 1476 1477 1478
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;
1479
    int ret = -1;
1480 1481 1482 1483

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1484
        goto cleanup;
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
    }
    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"));
1495
            goto cleanup;
1496 1497 1498
        }
        freeMems[numCells++] = mem;
    }
1499 1500 1501 1502
    ret = numCells;

cleanup:
    return ret;
1503 1504 1505 1506 1507
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
1508
    unsigned long long freeMem = -1;
1509
    int n;
1510

1511 1512 1513
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
1514
        goto cleanup;
1515 1516 1517 1518 1519 1520 1521
    }

    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"));
1522
            goto cleanup;
1523 1524 1525 1526
        }
        freeMem += mem;
    }

1527
cleanup:
1528 1529 1530 1531
    return freeMem;
}

#endif
1532

D
Daniel P. Berrange 已提交
1533 1534 1535
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1536
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1537 1538 1539 1540 1541 1542

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

    if (!(pidinfo = fopen(proc, "r"))) {
1543
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1544 1545 1546 1547 1548
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1549
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1550
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1551 1552 1553 1554 1555 1556 1557 1558
        return -1;
    }

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

1561
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1562 1563 1564 1565 1566 1567 1568

    fclose(pidinfo);

    return 0;
}


1569
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1570
                                          int id) {
1571 1572 1573 1574
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1575
    qemuDriverLock(driver);
1576
    vm  = virDomainFindByID(&driver->domains, id);
1577
    qemuDriverUnlock(driver);
1578 1579

    if (!vm) {
1580
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1581
        goto cleanup;
1582 1583
    }

1584
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1585
    if (dom) dom->id = vm->def->id;
1586 1587

cleanup:
1588 1589
    if (vm)
        virDomainObjUnlock(vm);
1590 1591
    return dom;
}
1592

1593
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1594
                                            const unsigned char *uuid) {
1595 1596 1597
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1598

1599
    qemuDriverLock(driver);
1600
    vm = virDomainFindByUUID(&driver->domains, uuid);
1601 1602
    qemuDriverUnlock(driver);

1603
    if (!vm) {
1604
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1605
        goto cleanup;
1606 1607
    }

1608
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1609
    if (dom) dom->id = vm->def->id;
1610 1611

cleanup:
1612 1613
    if (vm)
        virDomainObjUnlock(vm);
1614 1615
    return dom;
}
1616

1617
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1618
                                            const char *name) {
1619 1620 1621
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1622

1623
    qemuDriverLock(driver);
1624
    vm = virDomainFindByName(&driver->domains, name);
1625 1626
    qemuDriverUnlock(driver);

1627
    if (!vm) {
1628
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1629
        goto cleanup;
1630 1631
    }

1632
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1633
    if (dom) dom->id = vm->def->id;
1634 1635

cleanup:
1636 1637
    if (vm)
        virDomainObjUnlock(vm);
1638 1639 1640
    return dom;
}

1641
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1642 1643 1644
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1645
    qemuDriverLock(driver);
1646
    if (qemudExtractVersion(conn, driver) < 0)
1647
        goto cleanup;
1648

1649
    *version = qemu_driver->qemuVersion;
1650 1651 1652
    ret = 0;

cleanup:
1653
    qemuDriverUnlock(driver);
1654
    return ret;
D
Daniel P. Berrange 已提交
1655 1656
}

1657 1658 1659
static char *
qemudGetHostname (virConnectPtr conn)
{
1660
    char *result;
1661

1662 1663
    result = virGetHostname();
    if (result == NULL) {
1664 1665 1666 1667 1668
        qemudReportError (conn, NULL, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return NULL;
    }
    /* Caller frees this string. */
1669
    return result;
1670 1671
}

1672
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1673
    struct qemud_driver *driver = conn->privateData;
1674 1675
    int got = 0, i;

1676 1677 1678
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1679 1680
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
1681 1682 1683
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1684

D
Daniel P. Berrange 已提交
1685 1686
    return got;
}
1687

1688
static int qemudNumDomains(virConnectPtr conn) {
1689
    struct qemud_driver *driver = conn->privateData;
1690 1691
    int n = 0, i;

1692 1693 1694
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
1695
        if (virDomainIsActive(driver->domains.objs[i]))
1696
            n++;
1697 1698 1699
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
1700

1701
    return n;
D
Daniel P. Berrange 已提交
1702
}
1703

1704
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1705
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1706
    struct qemud_driver *driver = conn->privateData;
1707
    virDomainDefPtr def;
1708
    virDomainObjPtr vm = NULL;
1709
    virDomainPtr dom = NULL;
1710
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
1711

1712
    qemuDriverLock(driver);
1713 1714
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
1715
        goto cleanup;
1716

1717
    vm = virDomainFindByName(&driver->domains, def->name);
1718
    if (vm) {
1719
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1720
                         _("domain '%s' is already defined"),
1721
                         def->name);
1722
        goto cleanup;
1723
    }
1724
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1725 1726 1727 1728 1729
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1730
                         _("domain with uuid '%s' is already defined"),
1731
                         uuidstr);
1732
        goto cleanup;
1733
    }
1734

1735 1736
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
1737 1738 1739 1740
                                  def)))
        goto cleanup;

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

1742 1743 1744
    if (qemudStartVMDaemon(conn, driver, vm, NULL) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
1745
        vm = NULL;
1746
        goto cleanup;
D
Daniel P. Berrange 已提交
1747
    }
1748 1749 1750 1751

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

1753
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1754
    if (dom) dom->id = vm->def->id;
1755 1756 1757

cleanup:
    virDomainDefFree(def);
1758 1759
    if (vm)
        virDomainObjUnlock(vm);
1760 1761
    if (event)
        qemuDomainEventQueue(driver, event);
1762
    qemuDriverUnlock(driver);
1763
    return dom;
D
Daniel P. Berrange 已提交
1764 1765 1766
}


1767
static int qemudDomainSuspend(virDomainPtr dom) {
1768
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1769
    char *info;
1770 1771
    virDomainObjPtr vm;
    int ret = -1;
1772
    virDomainEventPtr event = NULL;
1773

1774
    qemuDriverLock(driver);
1775
    vm = virDomainFindByID(&driver->domains, dom->id);
1776 1777
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1778
    if (!vm) {
1779
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
1780
        goto cleanup;
D
Daniel P. Berrange 已提交
1781
    }
1782
    if (!virDomainIsActive(vm)) {
1783 1784
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1785
        goto cleanup;
D
Daniel P. Berrange 已提交
1786
    }
1787
    if (vm->state != VIR_DOMAIN_PAUSED) {
1788
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
1789 1790 1791 1792 1793 1794
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("suspend operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
1795 1796 1797
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
1798
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1799
    }
1800
    qemudSaveDomainStatus(dom->conn, driver, vm);
1801 1802 1803
    ret = 0;

cleanup:
1804 1805
    if (vm)
        virDomainObjUnlock(vm);
1806 1807 1808 1809 1810 1811

    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1812
    return ret;
D
Daniel P. Berrange 已提交
1813 1814 1815
}


1816
static int qemudDomainResume(virDomainPtr dom) {
1817
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
1818
    char *info;
1819 1820
    virDomainObjPtr vm;
    int ret = -1;
1821
    virDomainEventPtr event = NULL;
1822

1823
    qemuDriverLock(driver);
1824
    vm = virDomainFindByID(&driver->domains, dom->id);
1825 1826
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
1827
    if (!vm) {
1828 1829
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
1830
        goto cleanup;
D
Daniel P. Berrange 已提交
1831
    }
1832
    if (!virDomainIsActive(vm)) {
1833 1834
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
1835
        goto cleanup;
D
Daniel P. Berrange 已提交
1836
    }
1837
    if (vm->state == VIR_DOMAIN_PAUSED) {
1838
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
1839 1840 1841 1842 1843 1844
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("resume operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;
        qemudDebug("Reply %s", info);
1845 1846 1847
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
1848
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
1849
    }
1850
    qemudSaveDomainStatus(dom->conn, driver, vm);
1851 1852 1853
    ret = 0;

cleanup:
1854 1855
    if (vm)
        virDomainObjUnlock(vm);
1856 1857 1858 1859 1860
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
1861
    return ret;
D
Daniel P. Berrange 已提交
1862 1863 1864
}


1865
static int qemudDomainShutdown(virDomainPtr dom) {
1866 1867
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
1868
    char* info;
1869
    int ret = -1;
1870

1871
    qemuDriverLock(driver);
1872
    vm = virDomainFindByID(&driver->domains, dom->id);
1873 1874
    qemuDriverUnlock(driver);

1875 1876
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1877
                         _("no domain with matching id %d"), dom->id);
1878
        goto cleanup;
1879 1880
    }

1881
    if (qemudMonitorCommand(vm, "system_powerdown", &info) < 0) {
1882
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1883
                         "%s", _("shutdown operation failed"));
1884
        goto cleanup;
1885
    }
D
Daniel Veillard 已提交
1886
    VIR_FREE(info);
1887 1888 1889
    ret = 0;

cleanup:
1890 1891
    if (vm)
        virDomainObjUnlock(vm);
1892
    return ret;
1893 1894 1895
}


1896
static int qemudDomainDestroy(virDomainPtr dom) {
1897 1898 1899
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1900
    virDomainEventPtr event = NULL;
1901

1902
    qemuDriverLock(driver);
1903
    vm  = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1904
    if (!vm) {
1905
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1906
                         _("no domain with matching id %d"), dom->id);
1907
        goto cleanup;
D
Daniel P. Berrange 已提交
1908
    }
1909

1910
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1911 1912 1913
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
1914
    if (!vm->persistent) {
1915 1916
        virDomainRemoveInactive(&driver->domains,
                                vm);
1917 1918
        vm = NULL;
    }
1919 1920 1921
    ret = 0;

cleanup:
1922 1923
    if (vm)
        virDomainObjUnlock(vm);
1924 1925
    if (event)
        qemuDomainEventQueue(driver, event);
1926
    qemuDriverUnlock(driver);
1927
    return ret;
D
Daniel P. Berrange 已提交
1928 1929 1930
}


1931
static char *qemudDomainGetOSType(virDomainPtr dom) {
1932 1933 1934
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
1935

1936
    qemuDriverLock(driver);
1937
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1938
    qemuDriverUnlock(driver);
1939 1940
    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1941
                         "%s", _("no domain with matching uuid"));
1942
        goto cleanup;
1943 1944
    }

1945
    if (!(type = strdup(vm->def->os.type)))
1946 1947
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for ostype"));
1948 1949

cleanup:
1950 1951
    if (vm)
        virDomainObjUnlock(vm);
1952 1953 1954
    return type;
}

1955 1956
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
1957 1958 1959
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
1960

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

1965
    if (!vm) {
1966 1967 1968
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1969
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1970
                         _("no domain with matching uuid '%s'"), uuidstr);
1971
        goto cleanup;
1972 1973
    }

1974 1975 1976
    ret = vm->def->maxmem;

cleanup:
1977 1978
    if (vm)
        virDomainObjUnlock(vm);
1979
    return ret;
1980 1981 1982
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
1983 1984 1985
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
1986

1987
    qemuDriverLock(driver);
1988
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1989 1990
    qemuDriverUnlock(driver);

1991
    if (!vm) {
1992 1993 1994
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1995
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1996
                         _("no domain with matching uuid '%s'"), uuidstr);
1997
        goto cleanup;
1998 1999 2000 2001
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2002
                         "%s", _("cannot set max memory lower than current memory"));
2003
        goto cleanup;;
2004 2005 2006
    }

    vm->def->maxmem = newmax;
2007 2008 2009
    ret = 0;

cleanup:
2010 2011
    if (vm)
        virDomainObjUnlock(vm);
2012
    return ret;
2013 2014 2015
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
2016 2017 2018
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2019

2020
    qemuDriverLock(driver);
2021
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2022
    qemuDriverUnlock(driver);
2023
    if (!vm) {
2024 2025 2026
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2027
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2028
                         _("no domain with matching uuid '%s'"), uuidstr);
2029
        goto cleanup;
2030 2031
    }

2032
    if (virDomainIsActive(vm)) {
2033
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
2034
                         "%s", _("cannot set memory of an active domain"));
2035
        goto cleanup;
2036 2037 2038 2039
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2040
                         "%s", _("cannot set memory higher than max memory"));
2041
        goto cleanup;
2042 2043 2044
    }

    vm->def->memory = newmem;
2045 2046 2047
    ret = 0;

cleanup:
2048 2049
    if (vm)
        virDomainObjUnlock(vm);
2050
    return ret;
2051 2052
}

2053
static int qemudDomainGetInfo(virDomainPtr dom,
2054
                              virDomainInfoPtr info) {
2055 2056 2057 2058
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;

2059
    qemuDriverLock(driver);
2060
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2061
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2062
    if (!vm) {
2063 2064
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2065
        goto cleanup;
D
Daniel P. Berrange 已提交
2066 2067
    }

2068
    info->state = vm->state;
D
Daniel P. Berrange 已提交
2069

2070
    if (!virDomainIsActive(vm)) {
2071
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2072
    } else {
2073
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
2074
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
2075
            goto cleanup;
D
Daniel P. Berrange 已提交
2076 2077 2078
        }
    }

2079 2080 2081
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
2082 2083 2084
    ret = 0;

cleanup:
2085 2086
    if (vm)
        virDomainObjUnlock(vm);
2087
    return ret;
D
Daniel P. Berrange 已提交
2088 2089 2090
}


D
Daniel P. Berrange 已提交
2091
static char *qemudEscape(const char *in, int shell)
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
{
    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 已提交
2113 2114 2115 2116
            if (shell)
                len += 5;
            else
                len += 1;
2117 2118 2119 2120 2121 2122 2123
            break;
        default:
            len += 1;
            break;
        }
    }

2124
    if (VIR_ALLOC_N(out, len + 1) < 0)
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
        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 已提交
2143 2144 2145 2146 2147 2148 2149 2150 2151
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

2163 2164 2165 2166 2167
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
2168 2169 2170 2171
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
2172

2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
#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];
};

2184
static int qemudDomainSave(virDomainPtr dom,
2185
                           const char *path) {
2186 2187 2188 2189 2190 2191 2192
    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;
2193
    struct qemud_save_header header;
2194
    int ret = -1;
2195
    virDomainEventPtr event = NULL;
2196 2197 2198 2199 2200

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

2201
    qemuDriverLock(driver);
2202 2203
    vm = virDomainFindByID(&driver->domains, dom->id);

D
Daniel P. Berrange 已提交
2204
    if (!vm) {
2205
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2206
                         _("no domain with matching id %d"), dom->id);
2207
        goto cleanup;
D
Daniel P. Berrange 已提交
2208
    }
2209

2210
    if (!virDomainIsActive(vm)) {
2211
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2212
                         "%s", _("domain is not running"));
2213
        goto cleanup;
D
Daniel P. Berrange 已提交
2214
    }
2215 2216 2217 2218 2219 2220

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
        if (qemudDomainSuspend(dom) != 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2221
                             "%s", _("failed to pause domain"));
2222
            goto cleanup;
2223 2224 2225 2226
        }
    }

    /* Get XML for the domain */
2227
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2228 2229
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2230
                         "%s", _("failed to get domain xml"));
2231
        goto cleanup;
2232 2233 2234 2235 2236 2237
    }
    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,
2238
                         _("failed to create '%s'"), path);
2239
        goto cleanup;
2240 2241 2242 2243
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2244
                         "%s", _("failed to write save header"));
2245
        goto cleanup;
2246 2247 2248 2249
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2250
                         "%s", _("failed to write xml"));
2251
        goto cleanup;
2252 2253
    }

2254 2255 2256 2257 2258 2259 2260
    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;
2261 2262 2263 2264 2265

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2266
                         "%s", _("out of memory"));
2267
        goto cleanup;
2268
    }
2269
    if (virAsprintf(&command, "migrate \"exec:"
2270
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
2271
                  "\"", safe_path) == -1) {
2272
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2273
                         "%s", _("out of memory"));
2274 2275
        command = NULL;
        goto cleanup;
2276 2277
    }

2278
    if (qemudMonitorCommand(vm, command, &info) < 0) {
2279
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2280
                         "%s", _("migrate operation failed"));
2281
        goto cleanup;
2282 2283
    }

2284 2285 2286 2287 2288 2289 2290 2291
    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"));
2292
        goto cleanup;
2293 2294
    }

2295 2296
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2297 2298 2299
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2300
    if (!vm->persistent) {
2301 2302
        virDomainRemoveInactive(&driver->domains,
                                vm);
2303 2304
        vm = NULL;
    }
2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315
    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);
2316 2317
    if (vm)
        virDomainObjUnlock(vm);
2318 2319
    if (event)
        qemuDomainEventQueue(driver, event);
2320
    qemuDriverUnlock(driver);
2321
    return ret;
D
Daniel P. Berrange 已提交
2322 2323 2324
}


2325
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
2326 2327
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2328
    int max;
2329
    int ret = -1;
2330

2331
    qemuDriverLock(driver);
2332
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2333 2334
    qemuDriverUnlock(driver);

2335
    if (!vm) {
2336 2337 2338
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2339
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2340
                         _("no domain with matching uuid '%s'"), uuidstr);
2341
        goto cleanup;
2342 2343
    }

2344
    if (virDomainIsActive(vm)) {
2345
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
2346
                         _("cannot change vcpu count of an active domain"));
2347
        goto cleanup;
2348 2349 2350 2351 2352
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
2353
        goto cleanup;
2354 2355 2356 2357 2358 2359
    }

    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);
2360
        goto cleanup;
2361 2362 2363
    }

    vm->def->vcpus = nvcpus;
2364 2365 2366
    ret = 0;

cleanup:
2367 2368
    if (vm)
        virDomainObjUnlock(vm);
2369
    return ret;
2370 2371
}

2372 2373 2374 2375 2376 2377 2378

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2379 2380
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2381 2382 2383
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;
2384
    int ret = -1;
2385

2386
    qemuDriverLock(driver);
2387
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2388 2389
    qemuDriverUnlock(driver);

2390
    if (!virDomainIsActive(vm)) {
2391 2392
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2393
        goto cleanup;
2394 2395 2396 2397 2398 2399
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
2400
        goto cleanup;
2401 2402 2403
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2404
        goto cleanup;
2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419

    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));
2420
            goto cleanup;
2421 2422 2423 2424
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2425
        goto cleanup;
2426
    }
2427
    ret = 0;
2428

2429
cleanup:
2430 2431
    if (vm)
        virDomainObjUnlock(vm);
2432
    return ret;
2433 2434 2435 2436 2437 2438 2439 2440
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2441 2442
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2443 2444
    virNodeInfo nodeinfo;
    int i, v, maxcpu;
2445
    int ret = -1;
2446

2447
    qemuDriverLock(driver);
2448
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2449 2450
    qemuDriverUnlock(driver);

2451
    if (!virDomainIsActive(vm)) {
2452 2453
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
2454
        goto cleanup;
2455 2456 2457
    }

    if (virNodeInfoPopulate(dom->conn, &nodeinfo) < 0)
2458
        goto cleanup;
2459 2460 2461 2462 2463 2464 2465 2466 2467

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

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

2468 2469 2470 2471 2472 2473 2474 2475
    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 */
            }
2476 2477
        }

2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
        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);
2495
                }
2496 2497 2498 2499
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
2500 2501 2502
            }
        }
    }
2503
    ret = maxinfo;
2504

2505
cleanup:
2506 2507
    if (vm)
        virDomainObjUnlock(vm);
2508
    return ret;
2509 2510 2511 2512
}
#endif /* HAVE_SCHED_GETAFFINITY */


2513
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
2514 2515
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2516
    const char *type;
2517
    int ret = -1;
2518

2519
    qemuDriverLock(driver);
2520
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2521 2522
    qemuDriverUnlock(driver);

2523
    if (!vm) {
2524 2525 2526
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2527
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2528
                         _("no domain with matching uuid '%s'"), uuidstr);
2529
        goto cleanup;
2530 2531
    }

2532
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2533 2534 2535
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
2536
        goto cleanup;
2537 2538
    }

2539
    ret = qemudGetMaxVCPUs(dom->conn, type);
2540

2541
cleanup:
2542 2543
    if (vm)
        virDomainObjUnlock(vm);
2544 2545 2546 2547
    return ret;
}


2548
static int qemudDomainRestore(virConnectPtr conn,
2549 2550 2551
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
2552
    virDomainObjPtr vm = NULL;
2553 2554 2555
    int fd = -1;
    int ret = -1;
    char *xml = NULL;
2556
    struct qemud_save_header header;
2557
    virDomainEventPtr event = NULL;
2558

2559
    qemuDriverLock(driver);
2560 2561 2562
    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2563
                         "%s", _("cannot read domain image"));
2564
        goto cleanup;
2565 2566 2567 2568
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2569
                         "%s", _("failed to read qemu header"));
2570
        goto cleanup;
2571 2572 2573 2574
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2575
                         "%s", _("image magic is incorrect"));
2576
        goto cleanup;
2577 2578 2579 2580
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2581
                         _("image version is not supported (%d > %d)"),
2582
                         header.version, QEMUD_SAVE_VERSION);
2583
        goto cleanup;
2584 2585
    }

2586
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2587
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2588
                         "%s", _("out of memory"));
2589
        goto cleanup;
2590 2591 2592 2593
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2594
                         "%s", _("failed to read XML"));
2595
        goto cleanup;
2596 2597 2598
    }

    /* Create a domain from this XML */
2599 2600
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
2601
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2602
                         "%s", _("failed to parse XML"));
2603
        goto cleanup;
2604 2605 2606
    }

    /* Ensure the name and UUID don't already exist in an active VM */
2607
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2608
    if (!vm)
2609
        vm = virDomainFindByName(&driver->domains, def->name);
2610
    if (vm && virDomainIsActive(vm)) {
2611
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2612
                         _("domain is already active as '%s'"), vm->def->name);
2613
        goto cleanup;
2614 2615
    }

2616 2617 2618
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2619
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2620
                         "%s", _("failed to assign new VM"));
2621
        goto cleanup;
2622
    }
2623
    def = NULL;
2624 2625

    /* Set the migration source and start it up. */
2626
    vm->stdin_fd = fd;
2627
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio");
2628
    close(fd);
2629
    fd = -1;
2630
    vm->stdin_fd = -1;
2631
    if (ret < 0) {
2632
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2633
                         "%s", _("failed to start VM"));
2634
        if (!vm->persistent) {
2635 2636
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2637 2638
            vm = NULL;
        }
2639
        goto cleanup;
2640 2641
    }

2642 2643 2644
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
2645

2646 2647 2648
    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2649
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
2650
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2651
                             "%s", _("failed to resume domain"));
2652
            goto cleanup;
2653
        }
2654
        VIR_FREE(info);
2655 2656
        vm->state = VIR_DOMAIN_RUNNING;
    }
2657
    ret = 0;
2658

2659 2660 2661 2662 2663
cleanup:
    virDomainDefFree(def);
    VIR_FREE(xml);
    if (fd != -1)
        close(fd);
2664 2665
    if (vm)
        virDomainObjUnlock(vm);
2666 2667
    if (event)
        qemuDomainEventQueue(driver, event);
2668
    qemuDriverUnlock(driver);
2669
    return ret;
D
Daniel P. Berrange 已提交
2670 2671 2672
}


2673
static char *qemudDomainDumpXML(virDomainPtr dom,
2674
                                int flags ATTRIBUTE_UNUSED) {
2675 2676 2677 2678
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;

2679
    qemuDriverLock(driver);
2680
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2681 2682
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
2683
    if (!vm) {
2684 2685
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2686
        goto cleanup;
D
Daniel P. Berrange 已提交
2687 2688
    }

2689 2690 2691 2692 2693 2694
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
2695 2696
    if (vm)
        virDomainObjUnlock(vm);
2697
    return ret;
D
Daniel P. Berrange 已提交
2698 2699 2700
}


2701
static int qemudListDefinedDomains(virConnectPtr conn,
2702
                            char **const names, int nnames) {
2703
    struct qemud_driver *driver = conn->privateData;
2704
    int got = 0, i;
2705

2706
    qemuDriverLock(driver);
2707
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
2708
        virDomainObjLock(driver->domains.objs[i]);
2709 2710
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2711
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
2712
                                 "%s", _("failed to allocate space for VM name string"));
2713
                virDomainObjUnlock(driver->domains.objs[i]);
2714 2715
                goto cleanup;
            }
2716
        }
2717
        virDomainObjUnlock(driver->domains.objs[i]);
D
Daniel P. Berrange 已提交
2718
    }
2719

2720
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2721
    return got;
2722 2723 2724

 cleanup:
    for (i = 0 ; i < got ; i++)
2725
        VIR_FREE(names[i]);
2726
    qemuDriverUnlock(driver);
2727
    return -1;
D
Daniel P. Berrange 已提交
2728 2729
}

2730
static int qemudNumDefinedDomains(virConnectPtr conn) {
2731
    struct qemud_driver *driver = conn->privateData;
2732 2733
    int n = 0, i;

2734
    qemuDriverLock(driver);
2735 2736
    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2737
            n++;
2738
    qemuDriverUnlock(driver);
2739

2740
    return n;
D
Daniel P. Berrange 已提交
2741 2742 2743
}


2744
static int qemudDomainStart(virDomainPtr dom) {
2745 2746 2747
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2748
    virDomainEventPtr event = NULL;
2749

2750
    qemuDriverLock(driver);
2751
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2752 2753
    qemuDriverUnlock(driver);

2754
    if (!vm) {
2755
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2756
                         "%s", _("no domain with matching uuid"));
2757
        goto cleanup;
2758 2759
    }

2760
    ret = qemudStartVMDaemon(dom->conn, driver, vm, NULL);
2761
    if (ret != -1)
2762 2763 2764
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
2765 2766

cleanup:
2767 2768
    if (vm)
        virDomainObjUnlock(vm);
2769 2770 2771 2772 2773
    if (event) {
        qemuDriverLock(driver);
        qemuDomainEventQueue(driver, event);
        qemuDriverUnlock(driver);
    }
2774
    return ret;
D
Daniel P. Berrange 已提交
2775 2776 2777
}


2778
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2779
    struct qemud_driver *driver = conn->privateData;
2780
    virDomainDefPtr def;
2781
    virDomainObjPtr vm = NULL;
2782
    virDomainPtr dom = NULL;
2783
    virDomainEventPtr event = NULL;
2784
    int newVM = 1;
2785

2786
    qemuDriverLock(driver);
2787 2788
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
2789
        goto cleanup;
2790

2791
    vm = virDomainFindByName(&driver->domains, def->name);
2792 2793
    if (vm) {
        virDomainObjUnlock(vm);
2794
        newVM = 0;
2795
    }
2796

2797 2798 2799 2800
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2801
        goto cleanup;
2802
    }
2803
    vm->persistent = 1;
2804

2805 2806
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2807
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2808 2809
        virDomainRemoveInactive(&driver->domains,
                                vm);
2810
        vm = NULL;
2811
        goto cleanup;
2812 2813
    }

2814 2815 2816 2817 2818
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
2819

2820
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2821
    if (dom) dom->id = vm->def->id;
2822 2823

cleanup:
2824 2825
    if (vm)
        virDomainObjUnlock(vm);
2826 2827
    if (event)
        qemuDomainEventQueue(driver, event);
2828
    qemuDriverUnlock(driver);
2829
    return dom;
D
Daniel P. Berrange 已提交
2830 2831
}

2832
static int qemudDomainUndefine(virDomainPtr dom) {
2833 2834
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2835
    virDomainEventPtr event = NULL;
2836
    int ret = -1;
D
Daniel P. Berrange 已提交
2837

2838
    qemuDriverLock(driver);
2839
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2840

D
Daniel P. Berrange 已提交
2841
    if (!vm) {
2842 2843
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2844
        goto cleanup;
D
Daniel P. Berrange 已提交
2845 2846
    }

2847
    if (virDomainIsActive(vm)) {
2848 2849
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
2850
        goto cleanup;
D
Daniel P. Berrange 已提交
2851 2852
    }

2853 2854 2855
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
2856
        goto cleanup;
2857 2858 2859
    }

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

2862 2863 2864
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
2865

2866 2867
    virDomainRemoveInactive(&driver->domains,
                            vm);
2868
    vm = NULL;
2869
    ret = 0;
D
Daniel P. Berrange 已提交
2870

2871
cleanup:
2872 2873
    if (vm)
        virDomainObjUnlock(vm);
2874 2875
    if (event)
        qemuDomainEventQueue(driver, event);
2876
    qemuDriverUnlock(driver);
2877
    return ret;
D
Daniel P. Berrange 已提交
2878 2879
}

2880
/* Return the disks name for use in monitor commands */
2881
static char *qemudDiskDeviceName(const virConnectPtr conn,
2882
                                 const virDomainDiskDefPtr disk) {
2883 2884 2885 2886 2887 2888

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

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
2889
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
2890 2891 2892 2893 2894 2895 2896
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
2897
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
2898
                ret = virAsprintf(&devname, "ide%d-hd%d", busid, devid);
2899
            else
2900
                ret = virAsprintf(&devname, "ide%d-cd%d", busid, devid);
2901 2902
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
2903
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
2904
                ret = virAsprintf(&devname, "scsi%d-hd%d", busid, devid);
2905
            else
2906
                ret = virAsprintf(&devname, "scsi%d-cd%d", busid, devid);
2907 2908
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
2909
            ret = virAsprintf(&devname, "floppy%d", devid);
2910 2911
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
2912
            ret = virAsprintf(&devname, "virtio%d", devid);
2913 2914
            break;
        default:
2915
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
2916 2917 2918 2919 2920 2921
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
2922
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2923 2924 2925 2926 2927 2928
        return NULL;
    }

    return devname;
}

2929 2930
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           virDomainObjPtr vm,
2931 2932
                                           virDomainDeviceDefPtr dev)
{
2933
    virDomainDiskDefPtr origdisk = NULL, newdisk;
2934
    char *cmd, *reply, *safe_path;
2935
    char *devname = NULL;
2936
    unsigned int qemuCmdFlags;
2937
    int i;
2938

2939
    origdisk = NULL;
2940
    newdisk = dev->data.disk;
2941 2942 2943 2944
    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];
2945
            break;
2946
        }
2947 2948 2949
    }

    if (!origdisk) {
2950
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2951 2952 2953 2954 2955 2956 2957 2958 2959
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
2960
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2961 2962 2963 2964 2965 2966
                         _("Cannot determine QEMU argv syntax %s"),
                         vm->def->emulator);
        return -1;
    }

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
2967
        if (!(devname = qemudDiskDeviceName(conn, newdisk)))
2968 2969 2970 2971 2972 2973 2974 2975 2976
            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 {
2977
            qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2978 2979 2980 2981 2982 2983 2984 2985
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
2986
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
2987 2988 2989
            return -1;
        }
    }
2990

2991
    if (newdisk->src) {
2992 2993
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
2994
            qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2995
            VIR_FREE(devname);
2996 2997
            return -1;
        }
2998
        if (virAsprintf(&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
2999
            qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
3000
            VIR_FREE(safe_path);
3001
            VIR_FREE(devname);
3002 3003
            return -1;
        }
3004
        VIR_FREE(safe_path);
3005

3006
    } else if (virAsprintf(&cmd, "eject %s", devname) == -1) {
3007
        qemudReportError(conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
3008
        VIR_FREE(devname);
3009 3010
        return -1;
    }
3011
    VIR_FREE(devname);
3012

3013
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3014
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3015
                         "%s", _("could not change cdrom media"));
3016
        VIR_FREE(cmd);
3017 3018
        return -1;
    }
3019 3020 3021 3022

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
3023
    DEBUG ("ejectable media change reply: %s", reply);
3024
    if (strstr(reply, "\ndevice ")) {
3025
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3026
                          _("changing cdrom media failed: %s"), reply);
3027 3028 3029 3030
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3031 3032
    VIR_FREE(reply);
    VIR_FREE(cmd);
3033

3034 3035
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
3036
    newdisk->src = NULL;
3037
    origdisk->type = newdisk->type;
3038 3039 3040
    return 0;
}

3041 3042 3043
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
3044 3045
{
    int ret, i;
3046
    char *cmd, *reply, *s;
3047 3048 3049 3050 3051
    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)) {
3052
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3053 3054 3055 3056 3057 3058
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3059
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3060 3061 3062 3063 3064
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3065
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3066 3067 3068 3069
                         "%s", _("out of memory"));
        return -1;
    }

3070 3071
    ret = virAsprintf(&cmd, "pci_add 0 storage file=%s,if=%s",
                      safe_path, type);
3072 3073
    VIR_FREE(safe_path);
    if (ret == -1) {
3074
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3075 3076 3077
        return ret;
    }

3078
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3079
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3080 3081 3082 3083 3084 3085 3086 3087
                         _("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... */
3088 3089 3090 3091 3092 3093
#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 已提交
3094
            qemudLog(QEMUD_WARN, "%s", _("Unable to parse slot number\n"));
3095
    } else {
3096
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
                          _("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;
}
3111

3112 3113 3114
static int qemudDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                                 virDomainObjPtr vm,
                                                 virDomainDeviceDefPtr dev)
3115
{
3116 3117
    int ret, i;
    char *safe_path;
3118 3119
    char *cmd, *reply;

3120 3121
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3122
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3123 3124 3125 3126 3127
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

3128
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3129
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3130
        return -1;
3131 3132
    }

3133 3134
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3135
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3136 3137 3138 3139
                         "%s", _("out of memory"));
        return -1;
    }

3140
    ret = virAsprintf(&cmd, "usb_add disk:%s", safe_path);
3141
    VIR_FREE(safe_path);
3142
    if (ret == -1) {
3143
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3144 3145 3146
        return ret;
    }

3147
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3148
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3149
                         "%s", _("cannot attach usb disk"));
3150 3151 3152 3153 3154 3155 3156 3157
        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 ")) {
3158
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3159
                          "%s",
3160
                          _("adding usb disk failed"));
3161 3162 3163 3164
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3165

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

3170 3171 3172 3173 3174
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3175 3176 3177
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3178 3179 3180 3181
{
    int ret;
    char *cmd, *reply;

3182
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
3183
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3184 3185
        return -1;
    }
3186

3187
    if (dev->data.hostdev->source.subsys.u.usb.vendor) {
3188 3189 3190
        ret = virAsprintf(&cmd, "usb_add host:%.4x:%.4x",
                          dev->data.hostdev->source.subsys.u.usb.vendor,
                          dev->data.hostdev->source.subsys.u.usb.product);
3191
    } else {
3192 3193 3194
        ret = virAsprintf(&cmd, "usb_add host:%.3d.%.3d",
                          dev->data.hostdev->source.subsys.u.usb.bus,
                          dev->data.hostdev->source.subsys.u.usb.device);
3195 3196
    }
    if (ret == -1) {
3197
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
3198 3199 3200
        return -1;
    }

3201
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3202
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3203 3204 3205 3206 3207 3208 3209 3210 3211
                         "%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 ")) {
3212
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3213 3214 3215 3216 3217 3218
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3219

3220
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
3221

3222 3223
    VIR_FREE(reply);
    VIR_FREE(cmd);
3224 3225 3226
    return 0;
}

3227 3228
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
3229 3230 3231 3232
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3233

3234
    qemuDriverLock(driver);
3235
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3236
    if (!vm) {
3237
        qemuDriverUnlock(driver);
3238 3239
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3240
        goto cleanup;
3241 3242 3243
    }

    if (!virDomainIsActive(vm)) {
3244
        qemuDriverUnlock(driver);
3245 3246
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
3247
        goto cleanup;
3248 3249
    }

3250 3251
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
3252
    qemuDriverUnlock(driver);
3253 3254 3255
    if (dev == NULL)
        goto cleanup;

3256

3257 3258
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
3259 3260
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
3261
            ret = qemudDomainChangeEjectableMedia(dom->conn, vm, dev);
3262 3263 3264
            break;
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
3265
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, vm, dev);
3266 3267
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
3268
                ret = qemudDomainAttachPciDiskDevice(dom->conn, vm, dev);
3269 3270 3271 3272 3273 3274
            }
            break;
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("this disk device type cannot be attached"));
            goto cleanup;
3275
        }
3276
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
3277 3278
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
3279
        ret = qemudDomainAttachHostDevice(dom->conn, vm, dev);
3280
    } else {
3281
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
3282
                         "%s", _("this device type cannot be attached"));
3283
        goto cleanup;
3284 3285
    }

3286
    qemudSaveDomainStatus(dom->conn, driver, vm);
3287
cleanup:
G
Guido Günther 已提交
3288 3289
    if (ret < 0)
        virDomainDeviceDefFree(dev);
3290 3291
    if (vm)
        virDomainObjUnlock(vm);
3292 3293 3294
    return ret;
}

3295 3296
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
3297 3298
{
    int i, ret = -1;
3299 3300
    char *cmd = NULL;
    char *reply = NULL;
3301 3302 3303 3304 3305 3306 3307 3308 3309 3310
    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) {
3311
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3312
                         _("disk %s not found"), dev->data.disk->dst);
3313
        goto cleanup;
3314 3315 3316
    }

    if (detach->slotnum < 1) {
3317
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3318
                         _("disk %s cannot be detached - invalid slot number %d"),
3319
                           detach->dst, detach->slotnum);
3320
        goto cleanup;
3321 3322
    }

3323
    if (virAsprintf(&cmd, "pci_del 0 %d", detach->slotnum) < 0) {
3324 3325
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        goto cleanup;
3326 3327
    }

3328
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3329
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3330
                          _("failed to execute detach disk %s command"), detach->dst);
3331
        goto cleanup;
3332 3333 3334 3335 3336 3337
    }

    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")) {
3338
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3339
                          _("failed to detach disk %s: invalid slot %d"),
3340 3341
                          detach->dst, detach->slotnum);
        goto cleanup;
3342 3343 3344 3345 3346
    }

    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) {
3347 3348
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            goto cleanup;
3349 3350 3351 3352 3353 3354 3355 3356
        }
        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;
3357 3358

cleanup:
3359 3360 3361 3362 3363 3364 3365
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
3366 3367 3368 3369
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
3370

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

    if (!virDomainIsActive(vm)) {
3381
        qemuDriverUnlock(driver);
3382
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
G
Guido Günther 已提交
3383
                         "%s", _("cannot detach device on inactive domain"));
3384
        goto cleanup;
3385 3386
    }

3387 3388
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
3389
    qemuDriverUnlock(driver);
3390 3391 3392
    if (dev == NULL)
        goto cleanup;

3393 3394 3395 3396 3397

    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))
3398
        ret = qemudDomainDetachPciDiskDevice(dom->conn, vm, dev);
3399
    else
3400 3401 3402
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

3403
    qemudSaveDomainStatus(dom->conn, driver, vm);
3404 3405
cleanup:
    virDomainDeviceDefFree(dev);
3406 3407
    if (vm)
        virDomainObjUnlock(vm);
3408 3409 3410
    return ret;
}

3411
static int qemudDomainGetAutostart(virDomainPtr dom,
3412
                                   int *autostart) {
3413 3414 3415
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3416

3417
    qemuDriverLock(driver);
3418
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3419 3420
    qemuDriverUnlock(driver);

3421
    if (!vm) {
3422 3423
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3424
        goto cleanup;
3425 3426 3427
    }

    *autostart = vm->autostart;
3428
    ret = 0;
3429

3430
cleanup:
3431 3432
    if (vm)
        virDomainObjUnlock(vm);
3433
    return ret;
3434 3435
}

3436
static int qemudDomainSetAutostart(virDomainPtr dom,
3437
                                   int autostart) {
3438 3439
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3440 3441
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
3442

3443
    qemuDriverLock(driver);
3444
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3445 3446
    qemuDriverUnlock(driver);

3447
    if (!vm) {
3448 3449
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
3450
        goto cleanup;
3451 3452
    }

3453 3454 3455
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
3456
        goto cleanup;
3457 3458
    }

3459 3460
    autostart = (autostart != 0);

3461 3462 3463 3464 3465
    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;
3466

3467 3468
        if (autostart) {
            int err;
3469

3470 3471 3472 3473 3474 3475
            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;
            }
3476

3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
            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;
            }
3490 3491
        }

3492
        vm->autostart = autostart;
3493
    }
3494
    ret = 0;
3495

3496 3497 3498
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
3499 3500
    if (vm)
        virDomainObjUnlock(vm);
3501
    return ret;
3502 3503
}

3504 3505 3506 3507 3508 3509 3510 3511 3512
/* 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)
{
3513
    struct qemud_driver *driver = dom->conn->privateData;
3514
    char *dummy, *info = NULL;
3515
    const char *p, *eol;
3516
    const char *qemu_dev_name = NULL;
3517
    size_t len;
3518
    int i, ret = -1;
3519
    virDomainObjPtr vm;
3520
    virDomainDiskDefPtr disk = NULL;
3521

3522
    qemuDriverLock(driver);
3523
    vm = virDomainFindByID(&driver->domains, dom->id);
3524
    qemuDriverUnlock(driver);
3525 3526 3527
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3528
        goto cleanup;
3529
    }
3530
    if (!virDomainIsActive (vm)) {
3531 3532
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
3533
        goto cleanup;
3534 3535
    }

3536 3537 3538 3539 3540 3541 3542 3543
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
3544 3545
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
3546
        goto cleanup;
3547 3548
    }

3549
    qemu_dev_name = qemudDiskDeviceName(dom->conn, disk);
3550
    if (!qemu_dev_name)
3551
        goto cleanup;
3552 3553
    len = strlen (qemu_dev_name);

3554
    if (qemudMonitorCommand (vm, "info blockstats", &info) < 0) {
3555 3556
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
3557
        goto cleanup;
3558 3559 3560 3561 3562 3563 3564 3565
    }
    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 已提交
3566
    if (strstr(info, "\ninfo ")) {
3567 3568 3569
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
3570
        goto cleanup;
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596
    }

    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) {
3597
                if (STRPREFIX (p, "rd_bytes=")) {
3598 3599 3600
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
3601
                } else if (STRPREFIX (p, "wr_bytes=")) {
3602 3603 3604
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
3605
                } else if (STRPREFIX (p, "rd_operations=")) {
3606 3607 3608
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
3609
                } else if (STRPREFIX (p, "wr_operations=")) {
3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
                    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++;
            }
3621
            ret = 0;
3622
            goto cleanup;
3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633
        }

        /* 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);
3634
 cleanup:
3635 3636
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
3637 3638
    if (vm)
        virDomainObjUnlock(vm);
3639
    return ret;
3640 3641
}

3642
#ifdef __linux__
3643 3644 3645 3646 3647
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
3648 3649
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3650
    int i;
3651
    int ret = -1;
3652

3653
    qemuDriverLock(driver);
3654
    vm = virDomainFindByID(&driver->domains, dom->id);
3655 3656
    qemuDriverUnlock(driver);

3657 3658
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
3659
                          _("no domain with matching id %d"), dom->id);
3660
        goto cleanup;
3661 3662
    }

3663
    if (!virDomainIsActive(vm)) {
3664
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3665
                         "%s", _("domain is not running"));
3666
        goto cleanup;
3667 3668 3669 3670
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
3671
                         "%s", _("NULL or empty path"));
3672
        goto cleanup;
3673 3674 3675
    }

    /* Check the path is one of the domain's network interfaces. */
3676 3677
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
3678 3679 3680 3681
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
3682 3683
    }

3684 3685 3686 3687 3688
    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);
3689

3690
cleanup:
3691 3692
    if (vm)
        virDomainObjUnlock(vm);
3693 3694
    return ret;
}
3695
#else
3696 3697 3698 3699
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
3700 3701 3702 3703
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
}
3704
#endif
3705

3706 3707 3708 3709 3710 3711 3712
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
3713 3714 3715
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
3716

3717
    qemuDriverLock(driver);
3718
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3719 3720
    qemuDriverUnlock(driver);

3721 3722
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
3723
                          "%s", _("no domain with matching uuid"));
3724
        goto cleanup;
3725 3726 3727 3728
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3729
                         "%s", _("NULL or empty path"));
3730
        goto cleanup;
3731 3732 3733
    }

    /* Check the path belongs to this domain. */
3734 3735
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
3736 3737 3738 3739
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
3740 3741
    }

3742 3743 3744 3745 3746 3747 3748 3749 3750
    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;
        }
3751

3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766
        /* 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"));
3767 3768
    }

3769 3770 3771
cleanup:
    if (fd >= 0)
        close (fd);
3772 3773
    if (vm)
        virDomainObjUnlock(vm);
3774 3775 3776
    return ret;
}

R
Richard W.M. Jones 已提交
3777 3778 3779 3780 3781 3782
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
3783 3784 3785
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char cmd[256], *info = NULL;
R
Richard W.M. Jones 已提交
3786 3787 3788
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

3789
    qemuDriverLock(driver);
3790
    vm = virDomainFindByID(&driver->domains, dom->id);
3791
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
3792 3793 3794 3795

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
3796 3797 3798 3799 3800 3801 3802
        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 已提交
3803 3804
    }

3805
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3806 3807
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
3808
        goto cleanup;
R
Richard W.M. Jones 已提交
3809 3810 3811 3812 3813 3814
    }

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

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
3820
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
R
Richard W.M. Jones 已提交
3821
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3822
                          "%s", _("'memsave' command failed"));
3823
        goto cleanup;
R
Richard W.M. Jones 已提交
3824 3825 3826 3827 3828 3829 3830 3831
    }

    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));
3832
        goto cleanup;
R
Richard W.M. Jones 已提交
3833 3834 3835
    }

    ret = 0;
3836 3837 3838

cleanup:
    VIR_FREE(info);
R
Richard W.M. Jones 已提交
3839 3840
    if (fd >= 0) close (fd);
    unlink (tmp);
3841 3842
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
3843 3844 3845
    return ret;
}

3846

3847 3848
static int
qemudDomainEventRegister (virConnectPtr conn,
3849
                          virConnectDomainEventCallback callback,
3850 3851
                          void *opaque,
                          virFreeCallback freecb)
3852
{
3853 3854 3855
    struct qemud_driver *driver = conn->privateData;
    int ret;

3856
    qemuDriverLock(driver);
3857 3858
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
3859
    qemuDriverUnlock(driver);
3860

3861
    return ret;
3862 3863 3864 3865
}

static int
qemudDomainEventDeregister (virConnectPtr conn,
3866
                            virConnectDomainEventCallback callback)
3867
{
3868 3869 3870
    struct qemud_driver *driver = conn->privateData;
    int ret;

3871
    qemuDriverLock(driver);
3872 3873 3874 3875 3876 3877
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
3878
    qemuDriverUnlock(driver);
3879

3880
    return ret;
3881 3882
}

3883 3884 3885 3886 3887
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
                                        virConnectDomainEventCallback cb,
                                        void *cbopaque,
                                        void *opaque)
3888
{
3889
    struct qemud_driver *driver = opaque;
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 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934
    /* 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);
3935 3936
}

D
Daniel Veillard 已提交
3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954
/* 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;
3955 3956
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
3957 3958 3959 3960 3961
    virDomainObjPtr vm = NULL;
    int this_port;
    char hostname [HOST_NAME_MAX+1];
    char migrateFrom [64];
    const char *p;
3962
    virDomainEventPtr event = NULL;
3963 3964 3965
    int ret = -1;;

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

3967
    qemuDriverLock(driver);
D
Daniel Veillard 已提交
3968 3969 3970
    if (!dom_xml) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                          "%s", _("no domain XML passed"));
3971
        goto cleanup;
D
Daniel Veillard 已提交
3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991
    }

    /* 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));
3992
            goto cleanup;
D
Daniel Veillard 已提交
3993 3994 3995
        }

        /* Caller frees */
3996
        if (virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port) < 0) {
D
Daniel Veillard 已提交
3997 3998
            qemudReportError (dconn, NULL, NULL, VIR_ERR_NO_MEMORY,
                              "%s", strerror (errno));
3999
            goto cleanup;
D
Daniel Veillard 已提交
4000 4001 4002 4003 4004 4005 4006 4007 4008
        }
    } 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"));
4009
            goto cleanup;
D
Daniel Veillard 已提交
4010 4011 4012 4013 4014 4015 4016 4017 4018
        }

        /* 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"));
4019
            goto cleanup;
D
Daniel Veillard 已提交
4020 4021 4022 4023
        }
    }

    /* Parse the domain XML. */
4024 4025
    if (!(def = virDomainDefParseString(dconn, driver->caps, dom_xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
D
Daniel Veillard 已提交
4026 4027
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to parse XML"));
4028
        goto cleanup;
D
Daniel Veillard 已提交
4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044
    }

    /* 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"));
4045
        goto cleanup;
D
Daniel Veillard 已提交
4046 4047 4048 4049 4050 4051 4052 4053 4054
    }
#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);
4055
            goto cleanup;
D
Daniel Veillard 已提交
4056 4057 4058 4059 4060 4061 4062 4063
        }
    }

    if (!(vm = virDomainAssignDef(dconn,
                                  &driver->domains,
                                  def))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to assign new VM"));
4064
        goto cleanup;
D
Daniel Veillard 已提交
4065
    }
4066
    def = NULL;
D
Daniel Veillard 已提交
4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077

    /* 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"));
4078
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4079
            virDomainRemoveInactive(&driver->domains, vm);
4080 4081
            vm = NULL;
        }
4082
        goto cleanup;
D
Daniel Veillard 已提交
4083
    }
4084 4085 4086 4087

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

4090 4091 4092 4093 4094
cleanup:
    virDomainDefFree(def);
    if (ret != 0) {
        VIR_FREE(*uri_out);
    }
4095 4096
    if (vm)
        virDomainObjUnlock(vm);
4097 4098
    if (event)
        qemuDomainEventQueue(driver, event);
4099
    qemuDriverUnlock(driver);
4100
    return ret;
D
Daniel Veillard 已提交
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112
}

/* 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)
{
4113 4114
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4115
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4116 4117
    char *safe_uri;
    char cmd[HOST_NAME_MAX+50];
4118 4119
    char *info = NULL;
    int ret = -1;
D
Daniel Veillard 已提交
4120

4121
    qemuDriverLock(driver);
4122
    vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel Veillard 已提交
4123 4124 4125
    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
4126
        goto cleanup;
D
Daniel Veillard 已提交
4127 4128 4129 4130 4131
    }

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

4135 4136 4137
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
        snprintf(cmd, sizeof cmd, "%s", "stop");
4138
        qemudMonitorCommand (vm, cmd, &info);
4139 4140 4141
        DEBUG ("stop reply: %s", info);
        VIR_FREE(info);

4142 4143 4144 4145 4146 4147
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
        event = NULL;
4148 4149
    }

D
Daniel Veillard 已提交
4150 4151 4152
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
4153
        qemudMonitorCommand (vm, cmd, &info);
D
Daniel Veillard 已提交
4154 4155 4156 4157 4158 4159 4160 4161 4162 4163

        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));
4164
        goto cleanup;
D
Daniel Veillard 已提交
4165 4166 4167 4168
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

4169
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
D
Daniel Veillard 已提交
4170 4171
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("migrate operation failed"));
4172
        goto cleanup;
D
Daniel Veillard 已提交
4173 4174 4175 4176 4177 4178 4179 4180
    }

    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);
4181
        goto cleanup;
D
Daniel Veillard 已提交
4182 4183 4184 4185
    }

    /* Clean up the source domain. */
    qemudShutdownVMDaemon (dom->conn, driver, vm);
4186 4187 4188 4189

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
4190
    if (!vm->persistent) {
D
Daniel Veillard 已提交
4191
        virDomainRemoveInactive(&driver->domains, vm);
4192 4193
        vm = NULL;
    }
4194
    ret = 0;
D
Daniel Veillard 已提交
4195

4196 4197
cleanup:
    VIR_FREE(info);
4198 4199
    if (vm)
        virDomainObjUnlock(vm);
4200 4201
    if (event)
        qemuDomainEventQueue(driver, event);
4202
    qemuDriverUnlock(driver);
4203
    return ret;
D
Daniel Veillard 已提交
4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215
}

/* 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)
{
4216 4217 4218
    struct qemud_driver *driver = dconn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
4219
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4220 4221
    char *info = NULL;

4222
    qemuDriverLock(driver);
4223
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
4224 4225 4226
    if (!vm) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching name %s"), dname);
4227
        goto cleanup;
D
Daniel Veillard 已提交
4228 4229 4230 4231 4232 4233 4234 4235 4236
    }

    /* 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;
4237 4238 4239
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
D
Daniel Veillard 已提交
4240 4241
    } else {
        qemudShutdownVMDaemon (dconn, driver, vm);
4242 4243 4244
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
4245
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4246
            virDomainRemoveInactive(&driver->domains, vm);
4247 4248
            vm = NULL;
        }
D
Daniel Veillard 已提交
4249
    }
4250 4251

cleanup:
4252 4253
    if (vm)
        virDomainObjUnlock(vm);
4254 4255
    if (event)
        qemuDomainEventQueue(driver, event);
4256
    qemuDriverUnlock(driver);
4257
    return dom;
D
Daniel Veillard 已提交
4258 4259
}

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


4335
static virStateDriver qemuStateDriver = {
4336 4337 4338 4339
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
4340
};
4341

4342
int qemuRegister(void) {
4343 4344 4345 4346
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}