qemu_driver.c 95.6 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 48 49 50
#if HAVE_NUMACTL
#include <numa.h>
#endif

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

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

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

71 72
static int qemudShutdown(void);

73 74 75
/* qemudDebug statements should be changed to use this macro instead. */
#define DEBUG(fmt,...) VIR_DEBUG(__FILE__, fmt, __VA_ARGS__)
#define DEBUG0(msg) VIR_DEBUG(__FILE__, "%s", msg)
76

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

79 80 81 82 83 84 85 86 87
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 已提交
88
    qemudLog(QEMUD_ERR,
89
             "%s", _("Failed to set close-on-exec file descriptor flag\n"));
90 91 92 93 94 95 96 97 98 99 100 101 102
    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 已提交
103
    qemudLog(QEMUD_ERR,
104
             "%s", _("Failed to set non-blocking file descriptor flag\n"));
105 106 107 108
    return -1;
}


109
static void qemudDispatchVMEvent(int fd, int events, void *opaque);
110 111
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
112 113
                              virDomainObjPtr vm,
                              const char *migrateFrom);
114

115 116
static void qemudShutdownVMDaemon(virConnectPtr conn,
                                  struct qemud_driver *driver,
117
                                  virDomainObjPtr vm);
118 119


120
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
121
static int qemudMonitorCommand (const struct qemud_driver *driver,
122
                                const virDomainObjPtr vm,
123 124
                                const char *cmd,
                                char **reply);
125

J
Jim Meyering 已提交
126
static struct qemud_driver *qemu_driver = NULL;
127 128


129 130 131 132 133 134 135 136
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;

    for (i = 0 ; i < driver->domains.count ; i++) {
        if (driver->domains.objs[i]->autostart &&
            !virDomainIsActive(driver->domains.objs[i]) &&
            qemudStartVMDaemon(NULL, driver, driver->domains.objs[i], NULL) < 0) {
137
            virErrorPtr err = virGetLastError();
138
            qemudLog(QEMUD_ERR, _("Failed to autostart VM '%s': %s\n"),
139
                     driver->domains.objs[i]->def->name, err->message);
140 141
        }
    }
142 143
}

144 145 146 147 148 149 150
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
qemudStartup(void) {
151 152 153
    uid_t uid = geteuid();
    struct passwd *pw;
    char *base = NULL;
D
Daniel P. Berrange 已提交
154
    char driverConf[PATH_MAX];
155

156
    if (VIR_ALLOC(qemu_driver) < 0)
157 158 159 160 161 162
        return -1;

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

    if (!uid) {
163 164 165
        if (asprintf(&qemu_driver->logDir,
                     "%s/log/libvirt/qemu", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
166

D
Daniel P. Berrange 已提交
167
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
168 169 170
            goto out_of_memory;
    } else {
        if (!(pw = getpwuid(uid))) {
171
            qemudLog(QEMUD_ERR, _("Failed to find user record for uid '%d': %s\n"),
172
                     uid, strerror(errno));
173
            goto out_nouid;
174 175
        }

176 177 178
        if (asprintf(&qemu_driver->logDir,
                     "%s/.libvirt/qemu/log", pw->pw_dir) == -1)
            goto out_of_memory;
179

180
        if (asprintf (&base, "%s/.libvirt", pw->pw_dir) == -1)
181 182 183 184 185 186
            goto out_of_memory;
    }

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

D
Daniel P. Berrange 已提交
191
    if (asprintf (&qemu_driver->configDir, "%s/qemu", base) == -1)
192 193
        goto out_of_memory;

D
Daniel P. Berrange 已提交
194
    if (asprintf (&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
195 196
        goto out_of_memory;

197
    VIR_FREE(base);
198 199 200

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

    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
203
        qemudShutdown();
D
Daniel P. Berrange 已提交
204 205 206
        return -1;
    }

207 208 209 210 211
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
                                qemu_driver->autostartDir) < 0) {
D
Daniel P. Berrange 已提交
212 213 214
        qemudShutdown();
        return -1;
    }
215 216 217 218 219
    qemudAutostartConfigs(qemu_driver);

    return 0;

 out_of_memory:
J
Jim Meyering 已提交
220
    qemudLog (QEMUD_ERR,
221
              "%s", _("qemudStartup: out of memory\n"));
222
 out_nouid:
223 224
    VIR_FREE(base);
    VIR_FREE(qemu_driver);
225 226 227
    return -1;
}

228 229 230 231 232 233 234 235
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
236 237 238
    if (!qemu_driver)
        return 0;

239 240 241 242 243 244
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
                            qemu_driver->autostartDir);

245
    qemudAutostartConfigs(qemu_driver);
246 247

    return 0;
248 249
}

250 251 252 253 254 255 256 257 258 259
/**
 * 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) {
260
    unsigned int i;
261

262 263 264 265 266
    if (!qemu_driver)
        return 0;

    for (i = 0 ; i < qemu_driver->domains.count ; i++)
        if (virDomainIsActive(qemu_driver->domains.objs[i]))
267 268
            return 1;

269 270 271 272
    /* Otherwise we're happy to deal with a shutdown */
    return 0;
}

273 274 275 276 277 278 279
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
280
    unsigned int i;
281

282
    if (!qemu_driver)
283
        return -1;
284

285 286
    virCapabilitiesFree(qemu_driver->caps);

287
    /* shutdown active VMs */
288 289 290 291 292
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr dom = qemu_driver->domains.objs[i];
        if (virDomainIsActive(dom))
            qemudShutdownVMDaemon(NULL, qemu_driver, dom);
        if (!dom->persistent)
293
            virDomainRemoveInactive(&qemu_driver->domains,
294
                                    dom);
295
    }
296

297
    virDomainObjListFree(&qemu_driver->domains);
298

299
    VIR_FREE(qemu_driver->logDir);
300 301 302
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
    VIR_FREE(qemu_driver->vncTLSx509certdir);
D
Daniel P. Berrange 已提交
303

304 305 306
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

307
    VIR_FREE(qemu_driver);
308 309

    return 0;
310 311 312
}

/* Return -1 for error, 1 to continue reading and 0 for success */
313 314
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
                                      struct qemud_driver *driver,
315
                                      virDomainObjPtr vm,
316 317 318 319
                                      const char *output,
                                      int fd);

static int
320 321
qemudReadMonitorOutput(virConnectPtr conn,
                       struct qemud_driver *driver,
322
                       virDomainObjPtr vm,
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
                       int fd,
                       char *buf,
                       int buflen,
                       qemudHandlerMonitorOutput func,
                       const char *what)
{
#define MONITOR_TIMEOUT 3000
    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) {
339
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
340
                             _("QEMU quit during %s startup\n%s"), what, buf);
341 342 343 344 345 346 347 348
            return -1;
        }
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
349
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
350
                                 _("Failure while reading %s startup output: %s"),
351 352 353 354 355 356
                                 what, strerror(errno));
                return -1;
            }

            ret = poll(&pfd, 1, MONITOR_TIMEOUT);
            if (ret == 0) {
357
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
358
                                 _("Timed out while reading %s startup output"), what);
359 360 361
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
362
                    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
363
                                     _("Failure while reading %s startup output: %s"),
364 365 366 367 368 369 370 371 372
                                     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;

373
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
374
                                 _("Failure while reading %s startup output"), what);
375 376 377 378 379
                return -1;
            }
        } else {
            got += ret;
            buf[got] = '\0';
380
            if ((ret = func(conn, driver, vm, buf, fd)) != 1)
381 382 383 384
                return ret;
        }
    }

385
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
386
                     _("Out of space while reading %s startup output"), what);
387 388 389 390 391 392
    return -1;

#undef MONITOR_TIMEOUT
}

static int
393 394
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
                        struct qemud_driver *driver ATTRIBUTE_UNUSED,
395
                        virDomainObjPtr vm,
396 397 398 399 400 401 402 403 404 405 406
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

407 408
static int qemudOpenMonitor(virConnectPtr conn,
                            struct qemud_driver *driver,
409
                            virDomainObjPtr vm,
410
                            const char *monitor) {
411 412 413 414
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
415
    if ((monfd = open(monitor, O_RDWR)) < 0) {
416
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
417
                         _("Unable to open monitor path %s"), monitor);
418 419 420
        return -1;
    }
    if (qemudSetCloseExec(monfd) < 0) {
421
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
422
                         "%s", _("Unable to set monitor close-on-exec flag"));
423 424 425
        goto error;
    }
    if (qemudSetNonBlock(monfd) < 0) {
426
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
427
                         "%s", _("Unable to put monitor into non-blocking mode"));
428 429 430
        goto error;
    }

431 432
    ret = qemudReadMonitorOutput(conn,
                                 driver, vm, monfd,
433 434 435
                                 buf, sizeof(buf),
                                 qemudCheckMonitorPrompt,
                                 "monitor");
436 437 438 439 440

    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

441 442 443 444 445
 error:
    close(monfd);
    return ret;
}

446 447
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
448
                                   size_t *offset,
449
                                   char **path) {
450
    static const char needle[] = "char device redirected to";
451
    char *tmp, *dev;
452

453
    VIR_FREE(*path);
454
    /* First look for our magic string */
455 456 457 458 459
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
460

461 462 463 464 465
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
466
        if (c_isspace(*tmp)) {
467 468 469 470 471 472 473
            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';
474
            /* ... now further update offset till we get EOL */
475
            *offset = tmp - haystack;
476 477
            return 0;
        }
478
        tmp++;
479 480 481 482 483
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
484 485
     * least see a \n - indicate that we want to carry
     * on trying again
486
     */
487
    return 1;
488 489 490
}

static int
491 492
qemudFindCharDevicePTYs(virConnectPtr conn,
                        struct qemud_driver *driver,
493
                        virDomainObjPtr vm,
494 495
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
496
{
497
    char *monitor = NULL;
498
    size_t offset = 0;
499
    int ret, i;
500 501 502 503 504

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

506
    /* So first comes the monitor device */
507 508
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
509

510
    /* then the serial devices */
511 512
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
513 514 515 516
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
517 518 519 520
        }
    }

    /* and finally the parallel devices */
521 522
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
523 524 525 526
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
527 528 529 530
        }
    }

    /* Got them all, so now open the monitor console */
531 532 533 534 535
    ret = qemudOpenMonitor(conn, driver, vm, monitor);

cleanup:
    VIR_FREE(monitor);
    return ret;
536 537
}

538 539
static int qemudWaitForMonitor(virConnectPtr conn,
                               struct qemud_driver *driver,
540
                               virDomainObjPtr vm) {
541
    char buf[1024]; /* Plenty of space to get startup greeting */
542
    int ret = qemudReadMonitorOutput(conn,
543
                                     driver, vm, vm->stderr_fd,
544
                                     buf, sizeof(buf),
545
                                     qemudFindCharDevicePTYs,
546 547 548
                                     "console");

    buf[sizeof(buf)-1] = '\0';
549 550

    if (safewrite(vm->logfile, buf, strlen(buf)) < 0) {
551
        /* Log, but ignore failures to write logfile for VM */
552
        qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
553 554 555 556 557
                 strerror(errno));
    }
    return ret;
}

558 559 560
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
                    struct qemud_driver *driver,
561
                    virDomainObjPtr vm) {
562 563 564 565 566 567
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
568
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
569 570 571 572 573 574 575 576 577 578
        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;
    }

579
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

    if (qemudMonitorCommand(driver, vm, "info cpus", &qemucpus) < 0) {
        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;

643
    VIR_FREE(qemucpus);
644 645 646 647
    return 0;

error:
    VIR_FREE(vm->vcpupids);
648 649
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
650 651 652 653 654 655 656 657

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

658 659 660
static int
qemudInitCpus(virConnectPtr conn,
              struct qemud_driver *driver,
661
              virDomainObjPtr vm) {
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    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 已提交
677 678 679 680 681 682
    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++)
683
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
684
    }
685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702

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

    /* Allow the CPUS to start executing */
    if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("resume operation failed"));
        return -1;
    }
703
    VIR_FREE(info);
704 705 706 707 708

    return 0;
}


709
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
    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;
}

745 746
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
747 748
                              virDomainObjPtr vm,
                              const char *migrateFrom) {
749
    const char **argv = NULL, **tmp;
750
    const char **progenv = NULL;
751
    int i, ret;
752
    char logfile[PATH_MAX];
753
    struct stat sb;
754 755
    int *tapfds = NULL;
    int ntapfds = 0;
756
    unsigned int qemuCmdFlags;
757
    fd_set keepfd;
758
    const char *emulator;
759 760

    FD_ZERO(&keepfd);
761

762
    if (virDomainIsActive(vm)) {
763
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
764
                         "%s", _("VM is already active"));
765 766 767
        return -1;
    }

768 769 770
    if (vm->def->graphics &&
        vm->def->graphics->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics->data.vnc.autoport) {
771
        int port = qemudNextFreeVNCPort(driver);
772
        if (port < 0) {
773
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
774
                             "%s", _("Unable to find an unused VNC port"));
775 776
            return -1;
        }
777 778
        vm->def->graphics->data.vnc.port = port;
    }
779

780
    if ((strlen(driver->logDir) + /* path */
781 782 783 784
         1 + /* Separator */
         strlen(vm->def->name) + /* basename */
         4 + /* suffix .log */
         1 /* NULL */) > PATH_MAX) {
785
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
786
                         _("config file path too long: %s/%s.log"),
787
                         driver->logDir, vm->def->name);
788 789
        return -1;
    }
790
    strcpy(logfile, driver->logDir);
791 792 793 794
    strcat(logfile, "/");
    strcat(logfile, vm->def->name);
    strcat(logfile, ".log");

795
    if (virFileMakePath(driver->logDir) < 0) {
796
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
797
                         _("cannot create log directory %s: %s"),
798
                         driver->logDir, strerror(errno));
799 800 801 802 803
        return -1;
    }

    if ((vm->logfile = open(logfile, O_CREAT | O_TRUNC | O_WRONLY,
                            S_IRUSR | S_IWUSR)) < 0) {
804
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
805
                         _("failed to create logfile %s: %s"),
806 807 808
                         logfile, strerror(errno));
        return -1;
    }
809 810
    if (qemudSetCloseExec(vm->logfile) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
811
                         _("Unable to set VM logfile close-on-exec flag %s"),
812 813 814 815 816
                         strerror(errno));
        close(vm->logfile);
        vm->logfile = -1;
        return -1;
    }
817

818 819 820 821 822 823
    emulator = vm->def->emulator;
    if (!emulator)
        emulator = virDomainDefDefaultEmulator(conn, vm->def, driver->caps);
    if (!emulator)
        return -1;

824 825 826 827
    /* 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
     */
828
    if (stat(emulator, &sb) < 0) {
829 830
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot find QEMU binary %s: %s"),
831
                         emulator,
832 833 834 835
                         strerror(errno));
        return -1;
    }

836
    if (qemudExtractVersionInfo(emulator,
837 838 839 840
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
841
                         emulator);
842 843
        return -1;
    }
844

845
    if (qemudBuildCommandLine(conn, driver, vm,
846
                              qemuCmdFlags, &argv, &progenv,
847
                              &tapfds, &ntapfds, migrateFrom) < 0) {
848 849 850 851 852
        close(vm->logfile);
        vm->logfile = -1;
        return -1;
    }

853 854 855 856 857 858 859 860 861 862
    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++;
    }
863 864
    tmp = argv;
    while (*tmp) {
865
        if (safewrite(vm->logfile, *tmp, strlen(*tmp)) < 0)
866
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
867
                     errno, strerror(errno));
868
        if (safewrite(vm->logfile, " ", 1) < 0)
869
            qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
870 871 872
                     errno, strerror(errno));
        tmp++;
    }
873
    if (safewrite(vm->logfile, "\n", 1) < 0)
874
        qemudLog(QEMUD_WARN, _("Unable to write argv to logfile %d: %s\n"),
875 876
                 errno, strerror(errno));

877 878 879
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;

880 881 882
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

883
    ret = virExec(conn, argv, progenv, &keepfd, &vm->pid,
884 885
                  vm->stdin_fd, &vm->stdout_fd, &vm->stderr_fd,
                  VIR_EXEC_NONBLOCK);
886
    if (ret == 0) {
887 888
        vm->def->id = driver->nextvmid++;
        vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
889 890
    }

891
    for (i = 0 ; argv[i] ; i++)
892 893
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
894

895 896 897 898
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

899 900 901
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
902
        }
903
        VIR_FREE(tapfds);
904 905
    }

906
    if (ret == 0) {
907
        if ((virEventAddHandle(vm->stdout_fd,
908 909 910
                               POLLIN | POLLERR | POLLHUP,
                               qemudDispatchVMEvent,
                               driver) < 0) ||
911
            (virEventAddHandle(vm->stderr_fd,
912 913 914 915 916 917
                               POLLIN | POLLERR | POLLHUP,
                               qemudDispatchVMEvent,
                               driver) < 0) ||
            (qemudWaitForMonitor(conn, driver, vm) < 0) ||
            (qemudDetectVcpuPIDs(conn, driver, vm) < 0) ||
            (qemudInitCpus(conn, driver, vm) < 0)) {
918 919 920
            qemudShutdownVMDaemon(conn, driver, vm);
            return -1;
        }
921 922
    }

923
    return ret;
924 925
}

926
static int qemudVMData(struct qemud_driver *driver ATTRIBUTE_UNUSED,
927
                       virDomainObjPtr vm, int fd) {
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
    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';

944
        if (safewrite(vm->logfile, buf, ret) < 0) {
945
            /* Log, but ignore failures to write logfile for VM */
946
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
947 948 949 950 951 952
                     strerror(errno));
        }
    }
}


953
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
954 955
                                  struct qemud_driver *driver, virDomainObjPtr vm) {
    if (!virDomainIsActive(vm))
956
        return;
957

958
    qemudLog(QEMUD_INFO, _("Shutting down VM '%s'\n"), vm->def->name);
959 960 961

    kill(vm->pid, SIGTERM);

962 963
    qemudVMData(driver, vm, vm->stdout_fd);
    qemudVMData(driver, vm, vm->stderr_fd);
964

965 966
    virEventRemoveHandle(vm->stdout_fd);
    virEventRemoveHandle(vm->stderr_fd);
967 968

    if (close(vm->logfile) < 0)
969
        qemudLog(QEMUD_WARN, _("Unable to close logfile %d: %s\n"),
970
                 errno, strerror(errno));
971 972
    close(vm->stdout_fd);
    close(vm->stderr_fd);
973 974 975
    if (vm->monitor != -1)
        close(vm->monitor);
    vm->logfile = -1;
976 977
    vm->stdout_fd = -1;
    vm->stderr_fd = -1;
978 979 980 981 982
    vm->monitor = -1;

    if (waitpid(vm->pid, NULL, WNOHANG) != vm->pid) {
        kill(vm->pid, SIGKILL);
        if (waitpid(vm->pid, NULL, 0) != vm->pid) {
J
Jim Meyering 已提交
983
            qemudLog(QEMUD_WARN,
984
                     "%s", _("Got unexpected pid, damn\n"));
985 986 987 988
        }
    }

    vm->pid = -1;
989
    vm->def->id = -1;
990
    vm->state = VIR_DOMAIN_SHUTOFF;
991
    VIR_FREE(vm->vcpupids);
992
    vm->nvcpupids = 0;
993 994

    if (vm->newDef) {
995
        virDomainDefFree(vm->def);
996
        vm->def = vm->newDef;
997
        vm->def->id = -1;
998 999 1000 1001
        vm->newDef = NULL;
    }
}

1002
static int qemudDispatchVMLog(struct qemud_driver *driver, virDomainObjPtr vm, int fd) {
1003 1004
    if (qemudVMData(driver, vm, fd) < 0) {
        qemudShutdownVMDaemon(NULL, driver, vm);
1005
        if (!vm->persistent)
1006 1007
            virDomainRemoveInactive(&driver->domains,
                                    vm);
1008
    }
1009 1010 1011
    return 0;
}

1012
static int qemudDispatchVMFailure(struct qemud_driver *driver, virDomainObjPtr vm,
1013
                                  int fd ATTRIBUTE_UNUSED) {
1014
    qemudShutdownVMDaemon(NULL, driver, vm);
1015
    if (!vm->persistent)
1016 1017
        virDomainRemoveInactive(&driver->domains,
                                vm);
1018 1019 1020 1021 1022
    return 0;
}


static void qemudDispatchVMEvent(int fd, int events, void *opaque) {
1023
    struct qemud_driver *driver = (struct qemud_driver *)opaque;
1024 1025 1026 1027 1028 1029 1030 1031
    virDomainObjPtr vm = NULL;
    unsigned int i;

    for (i = 0 ; i < driver->domains.count ; i++) {
        if (virDomainIsActive(driver->domains.objs[i]) &&
            (driver->domains.objs[i]->stdout_fd == fd ||
             driver->domains.objs[i]->stderr_fd == fd)) {
            vm = driver->domains.objs[i];
1032
            break;
1033
        }
1034 1035 1036 1037 1038
    }

    if (!vm)
        return;

1039
    if (events == POLLIN)
1040
        qemudDispatchVMLog(driver, vm, fd);
1041
    else
1042
        qemudDispatchVMFailure(driver, vm, fd);
1043 1044
}

1045 1046
static int
qemudMonitorCommand (const struct qemud_driver *driver ATTRIBUTE_UNUSED,
1047
                     const virDomainObjPtr vm,
1048 1049
                     const char *cmd,
                     char **reply) {
D
Daniel P. Berrange 已提交
1050 1051
    int size = 0;
    char *buf = NULL;
1052
    size_t cmdlen = strlen(cmd);
D
Daniel P. Berrange 已提交
1053

1054 1055 1056
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
        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 已提交
1069

1070 1071
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1072 1073 1074 1075 1076
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1077
                goto error;
1078
            }
1079
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1080 1081
                goto error;

D
Daniel P. Berrange 已提交
1082 1083 1084 1085
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1086

D
Daniel P. Berrange 已提交
1087
        /* Look for QEMU prompt to indicate completion */
D
Daniel P. Berrange 已提交
1088
        if (buf && ((tmp = strstr(buf, "\n(qemu) ")) != NULL)) {
D
Daniel P. Berrange 已提交
1089 1090 1091 1092 1093 1094 1095 1096
            tmp[0] = '\0';
            break;
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1097
            goto error;
D
Daniel P. Berrange 已提交
1098 1099 1100
        }
    }

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

D
Daniel P. Berrange 已提交
1106 1107
    *reply = buf;
    return 0;
1108 1109 1110 1111 1112

 error:
    if (buf) {
        /* Log, but ignore failures to write logfile for VM */
        if (safewrite(vm->logfile, buf, strlen(buf)) < 0)
1113
            qemudLog(QEMUD_WARN, _("Unable to log VM console data: %s\n"),
1114
                     strerror(errno));
1115
        VIR_FREE(buf);
1116 1117
    }
    return -1;
D
Daniel P. Berrange 已提交
1118 1119
}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
/**
 * qemudProbe:
 *
 * Probe for the availability of the qemu driver, assume the
 * presence of QEmu emulation if the binaries are installed
 */
static const char *qemudProbe(void)
{
    if ((virFileExists("/usr/bin/qemu")) ||
        (virFileExists("/usr/bin/qemu-kvm")) ||
1130
        (virFileExists("/usr/bin/xenner"))) {
1131
        if (getuid() == 0) {
1132 1133 1134 1135
            return("qemu:///system");
        } else {
            return("qemu:///session");
        }
1136 1137 1138
    }
    return(NULL);
}
1139

1140
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1141
                                  xmlURIPtr uri,
1142
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1143
                                  int flags ATTRIBUTE_UNUSED) {
1144 1145 1146
    uid_t uid = getuid();

    if (qemu_driver == NULL)
1147
        goto decline;
1148

1149 1150 1151 1152 1153 1154
    if (uri == NULL || uri->scheme == NULL || uri->path == NULL)
        goto decline;

    if (STRNEQ (uri->scheme, "qemu"))
        goto decline;

1155
    if (uid != 0) {
1156 1157
        if (STRNEQ (uri->path, "/session"))
            goto decline;
1158
    } else { /* root */
1159 1160
        if (STRNEQ (uri->path, "/system") &&
            STRNEQ (uri->path, "/session"))
1161
            goto decline;
1162 1163 1164 1165 1166
    }

    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
1167 1168

 decline:
1169
    return VIR_DRV_OPEN_DECLINED;
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
}

static int qemudClose(virConnectPtr conn) {
    /*struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;*/

    conn->privateData = NULL;

    return 0;
}

static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1181
    return "QEMU";
1182 1183
}

1184 1185 1186 1187 1188

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

    int r, fd;
1189

1190 1191
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1192
        qemudLog(QEMUD_WARN, _("Unable to open %s: %s\n"), KVM_DEVICE, strerror(errno));
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
        return maxvcpus;
    }

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

    close(fd);
    return maxvcpus;
}


1205
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1206 1207 1208
    if (!type)
        return 16;

1209
    if (STRCASEEQ(type, "qemu"))
1210 1211 1212 1213
        return 16;

    /* XXX future KVM will support SMP. Need to probe
       kernel to figure out KVM module version i guess */
1214
    if (STRCASEEQ(type, "kvm"))
1215
        return kvmGetMaxVCPUs();
1216

1217
    if (STRCASEEQ(type, "kqemu"))
1218
        return 1;
1219 1220 1221

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1222 1223 1224
    return -1;
}

1225 1226 1227
static int qemudGetNodeInfo(virConnectPtr conn,
                            virNodeInfoPtr nodeinfo) {
    return virNodeInfoPopulate(conn, nodeinfo);
1228 1229 1230
}


1231 1232 1233
static char *qemudGetCapabilities(virConnectPtr conn) {
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *xml;
1234

1235
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL) {
1236 1237
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
                 "%s", _("failed to allocate space for capabilities support"));
1238 1239 1240
        return NULL;
    }

1241
    return xml;
1242 1243 1244
}


1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
#if HAVE_NUMACTL
static int
qemudNodeGetCellsFreeMemory(virConnectPtr conn,
                            unsigned long long *freeMems,
                            int startCell,
                            int maxCells)
{
    int n, lastCell, numCells;

    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
        return -1;
    }
    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"));
            return -1;
        }
        freeMems[numCells++] = mem;
    }
    return numCells;
}

static unsigned long long
qemudNodeGetFreeMemory (virConnectPtr conn)
{
    unsigned long long freeMem = 0;
    int n;
    if (numa_available() < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("NUMA not supported on this host"));
        return -1;
    }

    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"));
            return -1;
        }
        freeMem += mem;
    }

    return freeMem;
}

#endif
1300

D
Daniel P. Berrange 已提交
1301 1302 1303
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1304
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1305 1306 1307 1308 1309 1310

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

    if (!(pidinfo = fopen(proc, "r"))) {
1311
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1312 1313 1314 1315 1316
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1317
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1318
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1319 1320 1321 1322 1323 1324 1325 1326
        return -1;
    }

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

1329
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1330 1331 1332 1333 1334 1335 1336

    fclose(pidinfo);

    return 0;
}


1337
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1338
                                          int id) {
1339
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1340
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, id);
1341 1342 1343
    virDomainPtr dom;

    if (!vm) {
1344
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1345 1346 1347
        return NULL;
    }

1348
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1349
    if (dom) dom->id = vm->def->id;
1350 1351
    return dom;
}
1352
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1353
                                            const unsigned char *uuid) {
1354
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1355
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, uuid);
1356 1357 1358
    virDomainPtr dom;

    if (!vm) {
1359
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1360 1361 1362
        return NULL;
    }

1363
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1364
    if (dom) dom->id = vm->def->id;
1365 1366
    return dom;
}
1367
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1368
                                            const char *name) {
1369
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1370
    virDomainObjPtr vm = virDomainFindByName(&driver->domains, name);
1371 1372 1373
    virDomainPtr dom;

    if (!vm) {
1374
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN, NULL);
1375 1376 1377
        return NULL;
    }

1378
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1379
    if (dom) dom->id = vm->def->id;
1380 1381 1382
    return dom;
}

1383
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1384
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1385
    if (qemudExtractVersion(conn, driver) < 0)
1386 1387
        return -1;

1388 1389
    *version = qemu_driver->qemuVersion;
    return 0;
D
Daniel P. Berrange 已提交
1390 1391
}

1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
static char *
qemudGetHostname (virConnectPtr conn)
{
    int r;
    char hostname[HOST_NAME_MAX+1], *str;

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

1414
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
1415
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1416 1417 1418 1419 1420 1421
    int got = 0, i;

    for (i = 0 ; i < driver->domains.count && got < nids ; i++)
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;

D
Daniel P. Berrange 已提交
1422 1423
    return got;
}
1424
static int qemudNumDomains(virConnectPtr conn) {
1425
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
1426 1427 1428 1429
    int n = 0, i;

    for (i = 0 ; i < driver->domains.count ; i++)
        if (virDomainIsActive(driver->domains.objs[i]))
1430
            n++;
1431

1432
    return n;
D
Daniel P. Berrange 已提交
1433
}
1434
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
1435
                                      unsigned int flags ATTRIBUTE_UNUSED) {
1436 1437
    virDomainDefPtr def;
    virDomainObjPtr vm;
1438 1439
    virDomainPtr dom;
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
D
Daniel P. Berrange 已提交
1440

1441
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
1442 1443
        return NULL;

1444
    vm = virDomainFindByName(&driver->domains, def->name);
1445
    if (vm) {
1446
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1447
                         _("domain '%s' is already defined"),
1448 1449 1450 1451
                         def->name);
        virDomainDefFree(def);
        return NULL;
    }
1452
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
1453 1454 1455 1456 1457
    if (vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(def->uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
1458
                         _("domain with uuid '%s' is already defined"),
1459 1460 1461 1462
                         uuidstr);
        virDomainDefFree(def);
        return NULL;
    }
1463

1464 1465 1466 1467
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
D
Daniel P. Berrange 已提交
1468 1469 1470
        return NULL;
    }

1471 1472 1473
    if (qemudStartVMDaemon(conn, driver, vm, NULL) < 0) {
        virDomainRemoveInactive(&driver->domains,
                                vm);
D
Daniel P. Berrange 已提交
1474 1475 1476
        return NULL;
    }

1477
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1478
    if (dom) dom->id = vm->def->id;
1479
    return dom;
D
Daniel P. Berrange 已提交
1480 1481 1482
}


1483
static int qemudDomainSuspend(virDomainPtr dom) {
1484
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
D
Daniel P. Berrange 已提交
1485
    char *info;
1486
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1487
    if (!vm) {
1488
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN, _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1489 1490
        return -1;
    }
1491
    if (!virDomainIsActive(vm)) {
1492 1493
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
D
Daniel P. Berrange 已提交
1494 1495
        return -1;
    }
1496
    if (vm->state == VIR_DOMAIN_PAUSED)
D
Daniel P. Berrange 已提交
1497
        return 0;
D
Daniel P. Berrange 已提交
1498

1499
    if (qemudMonitorCommand(driver, vm, "stop", &info) < 0) {
1500 1501
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("suspend operation failed"));
D
Daniel P. Berrange 已提交
1502 1503
        return -1;
    }
1504
    vm->state = VIR_DOMAIN_PAUSED;
1505
    qemudDebug("Reply %s", info);
1506
    VIR_FREE(info);
D
Daniel P. Berrange 已提交
1507 1508 1509 1510
    return 0;
}


1511
static int qemudDomainResume(virDomainPtr dom) {
1512
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
D
Daniel P. Berrange 已提交
1513
    char *info;
1514
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
D
Daniel P. Berrange 已提交
1515
    if (!vm) {
1516 1517
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1518 1519
        return -1;
    }
1520
    if (!virDomainIsActive(vm)) {
1521 1522
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
D
Daniel P. Berrange 已提交
1523 1524
        return -1;
    }
1525
    if (vm->state == VIR_DOMAIN_RUNNING)
D
Daniel P. Berrange 已提交
1526
        return 0;
1527
    if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
1528 1529
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("resume operation failed"));
D
Daniel P. Berrange 已提交
1530 1531
        return -1;
    }
1532
    vm->state = VIR_DOMAIN_RUNNING;
1533
    qemudDebug("Reply %s", info);
1534
    VIR_FREE(info);
D
Daniel P. Berrange 已提交
1535
    return 0;
D
Daniel P. Berrange 已提交
1536 1537 1538
}


1539 1540
static int qemudDomainShutdown(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1541
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
1542 1543 1544 1545
    char* info;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1546
                         _("no domain with matching id %d"), dom->id);
1547 1548 1549 1550 1551
        return -1;
    }

    if (qemudMonitorCommand(driver, vm, "system_powerdown", &info) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1552
                         "%s", _("shutdown operation failed"));
1553 1554
        return -1;
    }
D
Daniel Veillard 已提交
1555
    VIR_FREE(info);
1556 1557 1558 1559 1560
    return 0;

}


1561
static int qemudDomainDestroy(virDomainPtr dom) {
1562
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1563
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
1564

D
Daniel P. Berrange 已提交
1565
    if (!vm) {
1566
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1567
                         _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1568 1569
        return -1;
    }
1570

1571
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1572
    if (!vm->persistent)
1573 1574
        virDomainRemoveInactive(&driver->domains,
                                vm);
1575

1576
    return 0;
D
Daniel P. Berrange 已提交
1577 1578 1579
}


1580 1581
static char *qemudDomainGetOSType(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1582
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1583 1584 1585 1586
    char *type;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1587
                         "%s", _("no domain with matching uuid"));
1588 1589 1590 1591
        return NULL;
    }

    if (!(type = strdup(vm->def->os.type))) {
1592 1593
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY,
                         "%s", _("failed to allocate space for ostype"));
1594 1595 1596 1597 1598
        return NULL;
    }
    return type;
}

1599 1600 1601
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1602
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1603 1604

    if (!vm) {
1605 1606 1607
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1608
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1609
                         _("no domain with matching uuid '%s'"), uuidstr);
1610 1611 1612 1613 1614 1615 1616 1617
        return 0;
    }

    return vm->def->maxmem;
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1618
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1619 1620

    if (!vm) {
1621 1622 1623
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1624
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1625
                         _("no domain with matching uuid '%s'"), uuidstr);
1626 1627 1628 1629 1630
        return -1;
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1631
                         "%s", _("cannot set max memory lower than current memory"));
1632 1633 1634 1635 1636 1637 1638 1639 1640
        return -1;
    }

    vm->def->maxmem = newmax;
    return 0;
}

static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1641
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1642 1643

    if (!vm) {
1644 1645 1646
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1647
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1648
                         _("no domain with matching uuid '%s'"), uuidstr);
1649 1650 1651
        return -1;
    }

1652
    if (virDomainIsActive(vm)) {
1653
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
1654
                         "%s", _("cannot set memory of an active domain"));
1655 1656 1657 1658 1659
        return -1;
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
1660
                         "%s", _("cannot set memory higher than max memory"));
1661 1662 1663 1664 1665 1666 1667
        return -1;
    }

    vm->def->memory = newmem;
    return 0;
}

1668
static int qemudDomainGetInfo(virDomainPtr dom,
1669
                              virDomainInfoPtr info) {
1670
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1671
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
1672
    if (!vm) {
1673 1674
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
D
Daniel P. Berrange 已提交
1675 1676 1677
        return -1;
    }

1678
    info->state = vm->state;
D
Daniel P. Berrange 已提交
1679

1680
    if (!virDomainIsActive(vm)) {
1681
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
1682
    } else {
1683
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
1684
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
D
Daniel P. Berrange 已提交
1685 1686 1687 1688
            return -1;
        }
    }

1689 1690 1691
    info->maxMem = vm->def->maxmem;
    info->memory = vm->def->memory;
    info->nrVirtCpu = vm->def->vcpus;
D
Daniel P. Berrange 已提交
1692 1693 1694 1695
    return 0;
}


D
Daniel P. Berrange 已提交
1696
static char *qemudEscape(const char *in, int shell)
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717
{
    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 已提交
1718 1719 1720 1721
            if (shell)
                len += 5;
            else
                len += 1;
1722 1723 1724 1725 1726 1727 1728
            break;
        default:
            len += 1;
            break;
        }
    }

1729
    if (VIR_ALLOC_N(out, len + 1) < 0)
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
        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 已提交
1748 1749 1750 1751 1752 1753 1754 1755 1756
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

1768 1769 1770 1771 1772
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
1773 1774 1775 1776
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
1777

1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
#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];
};

1789
static int qemudDomainSave(virDomainPtr dom,
1790
                           const char *path) {
1791
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1792
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
    char *command, *info;
    int fd;
    char *safe_path;
    char *xml;
    struct qemud_save_header header;

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

D
Daniel P. Berrange 已提交
1803
    if (!vm) {
1804
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1805
                         _("no domain with matching id %d"), dom->id);
D
Daniel P. Berrange 已提交
1806 1807
        return -1;
    }
1808

1809
    if (!virDomainIsActive(vm)) {
1810
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1811
                         "%s", _("domain is not running"));
D
Daniel P. Berrange 已提交
1812 1813
        return -1;
    }
1814 1815 1816 1817 1818 1819

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
        if (qemudDomainSuspend(dom) != 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1820
                             "%s", _("failed to pause domain"));
1821 1822 1823 1824 1825
            return -1;
        }
    }

    /* Get XML for the domain */
1826
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
1827 1828
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1829
                         "%s", _("failed to get domain xml"));
1830 1831 1832 1833 1834 1835 1836
        return -1;
    }
    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,
1837
                         _("failed to create '%s'"), path);
1838
        VIR_FREE(xml);
1839 1840 1841 1842 1843
        return -1;
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1844
                         "%s", _("failed to write save header"));
1845
        close(fd);
1846
        VIR_FREE(xml);
1847 1848 1849 1850 1851
        return -1;
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1852
                         "%s", _("failed to write xml"));
1853
        close(fd);
1854
        VIR_FREE(xml);
1855 1856 1857 1858
        return -1;
    }

    close(fd);
1859
    VIR_FREE(xml);
1860 1861 1862 1863 1864

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1865
                         "%s", _("out of memory"));
1866 1867 1868 1869
        return -1;
    }
    if (asprintf (&command, "migrate \"exec:"
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
1870
                  "\"", safe_path) == -1) {
1871
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1872
                         "%s", _("out of memory"));
1873
        VIR_FREE(safe_path);
1874 1875 1876 1877 1878 1879
        return -1;
    }
    free(safe_path);

    if (qemudMonitorCommand(driver, vm, command, &info) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
1880
                         "%s", _("migrate operation failed"));
1881
        VIR_FREE(command);
1882 1883 1884
        return -1;
    }

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    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"));
        VIR_FREE(info);
        VIR_FREE(command);
        return -1;
    }

1898 1899
    VIR_FREE(info);
    VIR_FREE(command);
1900 1901 1902

    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
1903
    if (!vm->persistent)
1904 1905
        virDomainRemoveInactive(&driver->domains,
                                vm);
1906 1907

    return 0;
D
Daniel P. Berrange 已提交
1908 1909 1910
}


1911
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
1912 1913
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1914 1915 1916
    int max;

    if (!vm) {
1917 1918 1919
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
1920
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
1921
                         _("no domain with matching uuid '%s'"), uuidstr);
1922 1923 1924
        return -1;
    }

1925
    if (virDomainIsActive(vm)) {
1926
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT, "%s",
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947
                         _("cannot change vcpu count of an active domain"));
        return -1;
    }

    if ((max = qemudDomainGetMaxVcpus(dom)) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
        return -1;
    }

    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);
        return -1;
    }

    vm->def->vcpus = nvcpus;
    return 0;
}

1948 1949 1950 1951 1952 1953 1954 1955

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
1956
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
1957 1958 1959 1960
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;

1961
    if (!virDomainIsActive(vm)) {
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
        return -1;
    }

    if (vcpu > (vm->nvcpupids-1)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         _("vcpu number out of range %d > %d"),
                         vcpu, vm->nvcpupids);
        return -1;
    }

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

    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));
            return -1;
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
        return -1;
    }

    return 0;
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2009
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2010 2011 2012
    virNodeInfo nodeinfo;
    int i, v, maxcpu;

2013
    if (!virDomainIsActive(vm)) {
2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                         "%s",_("cannot pin vcpus on an inactive domain"));
        return -1;
    }

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

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

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

    if (maxinfo < 1)
        return 0;

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

    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));
                    return -1;
                }

                for (i = 0 ; i < maxcpu ; i++)
                    if (CPU_ISSET(i, &mask))
                        VIR_USE_CPU(cpumap, i);
            }
        } else {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("cpu affinity is not available"));
            return -1;
        }
    }

    return maxinfo;
}
#endif /* HAVE_SCHED_GETAFFINITY */


2072 2073
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2074
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2075 2076 2077 2078
    const char *type;
    int ret;

    if (!vm) {
2079 2080 2081
        char uuidstr[VIR_UUID_STRING_BUFLEN];

        virUUIDFormat(dom->uuid, uuidstr);
2082
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2083
                         _("no domain with matching uuid '%s'"), uuidstr);
2084 2085 2086
        return -1;
    }

2087
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
        return -1;
    }

    if ((ret = qemudGetMaxVCPUs(dom->conn, type)) < 0) {
        return -1;
    }

    return ret;
}


2102
static int qemudDomainRestore(virConnectPtr conn,
2103 2104
                       const char *path) {
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
2105 2106
    virDomainDefPtr def;
    virDomainObjPtr vm;
2107
    int fd;
2108
    int ret;
2109 2110 2111 2112 2113 2114
    char *xml;
    struct qemud_save_header header;

    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2115
                         "%s", _("cannot read domain image"));
2116 2117 2118 2119 2120
        return -1;
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2121
                         "%s", _("failed to read qemu header"));
2122 2123 2124 2125 2126 2127
        close(fd);
        return -1;
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2128
                         "%s", _("image magic is incorrect"));
2129 2130 2131 2132 2133 2134
        close(fd);
        return -1;
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2135
                         _("image version is not supported (%d > %d)"),
2136 2137 2138 2139 2140
                         header.version, QEMUD_SAVE_VERSION);
        close(fd);
        return -1;
    }

2141
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
2142
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2143
                         "%s", _("out of memory"));
2144 2145 2146 2147 2148 2149
        close(fd);
        return -1;
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2150
                         "%s", _("failed to read XML"));
2151
        close(fd);
2152
        VIR_FREE(xml);
2153 2154 2155 2156
        return -1;
    }

    /* Create a domain from this XML */
2157
    if (!(def = virDomainDefParseString(conn, driver->caps, xml))) {
2158
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2159
                         "%s", _("failed to parse XML"));
2160
        close(fd);
2161
        VIR_FREE(xml);
2162 2163
        return -1;
    }
2164
    VIR_FREE(xml);
2165 2166

    /* Ensure the name and UUID don't already exist in an active VM */
2167
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2168
    if (!vm)
2169
        vm = virDomainFindByName(&driver->domains, def->name);
2170
    if (vm && virDomainIsActive(vm)) {
2171
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2172
                         _("domain is already active as '%s'"), vm->def->name);
2173 2174 2175 2176
        close(fd);
        return -1;
    }

2177 2178 2179
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
2180
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2181
                         "%s", _("failed to assign new VM"));
2182
        virDomainDefFree(def);
2183 2184 2185 2186 2187
        close(fd);
        return -1;
    }

    /* Set the migration source and start it up. */
2188
    vm->stdin_fd = fd;
2189
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio");
2190
    close(fd);
2191
    vm->stdin_fd = -1;
2192
    if (ret < 0) {
2193
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2194
                         "%s", _("failed to start VM"));
2195
        if (!vm->persistent)
2196 2197
            virDomainRemoveInactive(&driver->domains,
                                    vm);
2198 2199 2200 2201 2202 2203
        return -1;
    }

    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
2204
        if (qemudMonitorCommand(driver, vm, "cont", &info) < 0) {
2205
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
2206
                             "%s", _("failed to resume domain"));
2207 2208
            return -1;
        }
2209
        VIR_FREE(info);
2210 2211 2212 2213
        vm->state = VIR_DOMAIN_RUNNING;
    }

    return 0;
D
Daniel P. Berrange 已提交
2214 2215 2216
}


2217
static char *qemudDomainDumpXML(virDomainPtr dom,
2218
                                int flags ATTRIBUTE_UNUSED) {
2219
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2220
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
2221
    if (!vm) {
2222 2223
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2224
        return NULL;
D
Daniel P. Berrange 已提交
2225 2226
    }

2227 2228 2229 2230
    return virDomainDefFormat(dom->conn,
                              (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                              vm->newDef : vm->def,
                              flags);
D
Daniel P. Berrange 已提交
2231 2232 2233
}


2234
static int qemudListDefinedDomains(virConnectPtr conn,
2235 2236 2237
                            char **const names, int nnames) {
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    int got = 0, i;
2238 2239 2240 2241

    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
2242
                qemudReportError(conn, NULL, NULL, VIR_ERR_NO_MEMORY,
2243
                                 "%s", _("failed to allocate space for VM name string"));
2244 2245
                goto cleanup;
            }
2246
        }
D
Daniel P. Berrange 已提交
2247
    }
2248

D
Daniel P. Berrange 已提交
2249
    return got;
2250 2251 2252

 cleanup:
    for (i = 0 ; i < got ; i++)
2253
        VIR_FREE(names[i]);
2254
    return -1;
D
Daniel P. Berrange 已提交
2255 2256
}

2257
static int qemudNumDefinedDomains(virConnectPtr conn) {
2258
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
2259 2260 2261 2262
    int n = 0, i;

    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
2263
            n++;
2264

2265
    return n;
D
Daniel P. Berrange 已提交
2266 2267 2268
}


2269
static int qemudDomainStart(virDomainPtr dom) {
2270
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2271
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2272 2273

    if (!vm) {
2274
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2275
                         "%s", _("no domain with matching uuid"));
2276
        return -1;
2277 2278
    }

2279
    return qemudStartVMDaemon(dom->conn, driver, vm, NULL);
D
Daniel P. Berrange 已提交
2280 2281 2282
}


2283
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
2284
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
2285 2286
    virDomainDefPtr def;
    virDomainObjPtr vm;
2287
    virDomainPtr dom;
2288

2289
    if (!(def = virDomainDefParseString(conn, driver->caps, xml)))
2290 2291
        return NULL;

2292 2293 2294 2295
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
        virDomainDefFree(def);
2296 2297
        return NULL;
    }
2298
    vm->persistent = 1;
2299

2300 2301
    if (virDomainSaveConfig(conn,
                            driver->configDir,
2302
                            vm->newDef ? vm->newDef : vm->def) < 0) {
2303 2304
        virDomainRemoveInactive(&driver->domains,
                                vm);
2305 2306 2307
        return NULL;
    }

2308
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2309
    if (dom) dom->id = vm->def->id;
2310
    return dom;
D
Daniel P. Berrange 已提交
2311 2312
}

2313
static int qemudDomainUndefine(virDomainPtr dom) {
2314
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2315
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
2316 2317

    if (!vm) {
2318 2319
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
D
Daniel P. Berrange 已提交
2320 2321 2322
        return -1;
    }

2323
    if (virDomainIsActive(vm)) {
2324 2325
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot delete active domain"));
D
Daniel P. Berrange 已提交
2326 2327 2328
        return -1;
    }

2329 2330 2331 2332 2333 2334 2335
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
        return -1;
    }

    if (virDomainDeleteConfig(dom->conn, driver->configDir, driver->autostartDir, vm) < 0)
D
Daniel P. Berrange 已提交
2336 2337
        return -1;

2338 2339
    virDomainRemoveInactive(&driver->domains,
                            vm);
D
Daniel P. Berrange 已提交
2340 2341 2342 2343

    return 0;
}

2344
/* Return the disks name for use in monitor commands */
2345 2346
static char *qemudDiskDeviceName(const virDomainPtr dom,
                                 const virDomainDiskDefPtr disk) {
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360

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

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
2361 2362 2363 2364
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
                ret = asprintf(&devname, "ide%d-hd%d", busid, devid);
            else
                ret = asprintf(&devname, "ide%d-cd%d", busid, devid);
2365 2366
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
2367 2368 2369 2370
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
                ret = asprintf(&devname, "scsi%d-hd%d", busid, devid);
            else
                ret = asprintf(&devname, "scsi%d-cd%d", busid, devid);
2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
            ret = asprintf(&devname, "floppy%d", devid);
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
            ret = asprintf(&devname, "virtio%d", devid);
            break;
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return NULL;
    }

    return devname;
}

static int qemudDomainChangeEjectableMedia(virDomainPtr dom,
                                           virDomainDeviceDefPtr dev)
{
2396
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2397
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2398
    virDomainDiskDefPtr origdisk, newdisk;
2399
    char *cmd, *reply, *safe_path;
2400
    char *devname = NULL;
2401
    unsigned int qemuCmdFlags;
2402
    int i;
2403 2404 2405 2406 2407 2408 2409

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

2410
    origdisk = NULL;
2411
    newdisk = dev->data.disk;
2412 2413 2414 2415
    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];
2416
            break;
2417
        }
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
    }

    if (!origdisk) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

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

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
        if (!(devname = qemudDiskDeviceName(dom, newdisk)))
            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 {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
            qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
            return -1;
        }
    }
2461

2462
    if (newdisk->src) {
2463 2464
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
2465 2466
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
            VIR_FREE(devname);
2467 2468
            return -1;
        }
2469 2470
        if (asprintf (&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
2471
            VIR_FREE(safe_path);
2472
            VIR_FREE(devname);
2473 2474
            return -1;
        }
2475
        VIR_FREE(safe_path);
2476

2477 2478 2479
    } else if (asprintf(&cmd, "eject %s", devname) == -1) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_MEMORY, NULL);
        VIR_FREE(devname);
2480 2481
        return -1;
    }
2482
    VIR_FREE(devname);
2483 2484

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
2485 2486
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("cannot change cdrom media"));
2487
        VIR_FREE(cmd);
2488 2489
        return -1;
    }
2490 2491 2492 2493

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
2494
    DEBUG ("ejectable media change reply: %s", reply);
2495 2496 2497 2498 2499 2500 2501
    if (strstr(reply, "\ndevice ")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("changing cdrom media failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2502 2503
    VIR_FREE(reply);
    VIR_FREE(cmd);
2504

2505 2506
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
2507
    newdisk->src = NULL;
2508
    origdisk->type = newdisk->type;
2509 2510 2511 2512
    return 0;
}


2513 2514 2515
static int qemudDomainAttachUsbMassstorageDevice(virDomainPtr dom, virDomainDeviceDefPtr dev)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2516
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2517 2518 2519 2520 2521 2522 2523 2524 2525
    int ret;
    char *cmd, *reply;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

2526 2527 2528
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return -1;
2529 2530
    }

2531 2532 2533 2534 2535 2536 2537 2538
    ret = asprintf(&cmd, "usb_add disk:%s", dev->data.disk->src);
    if (ret == -1) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return ret;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2539
                         "%s", _("cannot attach usb disk"));
2540 2541 2542 2543 2544 2545 2546 2547 2548 2549
        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 ")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s",
2550
                          _("adding usb disk failed"));
2551 2552 2553 2554
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2555

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

2560 2561 2562 2563 2564
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

2565 2566 2567
static int qemudDomainAttachHostDevice(virDomainPtr dom, virDomainDeviceDefPtr dev)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2568
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2569 2570 2571 2572 2573 2574 2575 2576
    int ret;
    char *cmd, *reply;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }
2577 2578 2579 2580
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return -1;
    }
2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613

    if (dev->data.hostdev->source.subsys.usb.vendor) {
        ret = asprintf(&cmd, "usb_add host:%.4x:%.4x",
                       dev->data.hostdev->source.subsys.usb.vendor,
                       dev->data.hostdev->source.subsys.usb.product);
    } else {
        ret = asprintf(&cmd, "usb_add host:%.3d.%.3d",
                       dev->data.hostdev->source.subsys.usb.bus,
                       dev->data.hostdev->source.subsys.usb.device);
    }
    if (ret == -1) {
        qemudReportError(dom->conn, NULL, NULL, VIR_ERR_NO_MEMORY, NULL);
        return -1;
    }

    if (qemudMonitorCommand(driver, vm, cmd, &reply) < 0) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%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 ")) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
2614

2615
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
2616

2617 2618
    VIR_FREE(reply);
    VIR_FREE(cmd);
2619 2620 2621
    return 0;
}

2622 2623 2624
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2625
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646
    virDomainDeviceDefPtr dev;
    int ret = 0;

    if (!vm) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
        return -1;
    }

    if (!virDomainIsActive(vm)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot attach device on inactive domain"));
        return -1;
    }

    dev = virDomainDeviceDefParse(dom->conn, vm->def, xml);
    if (dev == NULL) {
        return -1;
    }

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
2647 2648 2649
        (dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_CDROM ||
         dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_FLOPPY)) {
                ret = qemudDomainChangeEjectableMedia(dom, dev);
2650
    } else if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
2651
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
2652 2653
        dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
                ret = qemudDomainAttachUsbMassstorageDevice(dom, dev);
2654 2655 2656 2657 2658 2659
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
        dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
        dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
                ret = qemudDomainAttachHostDevice(dom, dev);
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
2660
                         "%s", _("this device type cannot be attached"));
2661 2662 2663 2664 2665 2666 2667
        ret = -1;
    }

    VIR_FREE(dev);
    return ret;
}

2668
static int qemudDomainGetAutostart(virDomainPtr dom,
2669 2670
                            int *autostart) {
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2671
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2672 2673

    if (!vm) {
2674 2675
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2676 2677 2678 2679 2680 2681 2682 2683
        return -1;
    }

    *autostart = vm->autostart;

    return 0;
}

2684
static int qemudDomainSetAutostart(virDomainPtr dom,
2685
                                   int autostart) {
2686
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2687
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2688 2689
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
2690 2691

    if (!vm) {
2692 2693
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                         "%s", _("no domain with matching uuid"));
2694 2695 2696
        return -1;
    }

2697 2698 2699 2700 2701 2702
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
        return -1;
    }

2703 2704 2705 2706 2707
    autostart = (autostart != 0);

    if (vm->autostart == autostart)
        return 0;

2708 2709 2710 2711 2712
    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;

2713 2714 2715
    if (autostart) {
        int err;

2716
        if ((err = virFileMakePath(driver->autostartDir))) {
2717
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2718
                             _("cannot create autostart directory %s: %s"),
2719
                             driver->autostartDir, strerror(err));
2720
            goto cleanup;
2721 2722
        }

2723
        if (symlink(configFile, autostartLink) < 0) {
2724
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2725 2726 2727
                             _("Failed to create symlink '%s to '%s': %s"),
                             autostartLink, configFile, strerror(errno));
            goto cleanup;
2728 2729
        }
    } else {
2730
        if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
2731
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
2732
                             _("Failed to delete symlink '%s': %s"),
2733 2734
                             autostartLink, strerror(errno));
            goto cleanup;
2735 2736 2737
        }
    }

2738
    vm->autostart = autostart;
2739
    ret = 0;
2740

2741 2742 2743 2744 2745
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);

    return ret;
2746 2747
}

2748 2749 2750 2751 2752 2753 2754 2755 2756
/* 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)
{
2757
    struct qemud_driver *driver =
2758 2759 2760 2761 2762
        (struct qemud_driver *)dom->conn->privateData;
    char *dummy, *info;
    const char *p, *eol;
    char qemu_dev_name[32];
    size_t len;
2763
    const virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
2764 2765 2766 2767 2768 2769

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
        return -1;
    }
2770
    if (!virDomainIsActive (vm)) {
2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("domain is not running"));
        return -1;
    }

    /*
     * QEMU internal block device names are different from the device
     * names we use in libvirt, so we need to map between them:
     *
     *   hd[a-]   to  ide0-hd[0-]
     *   cdrom    to  ide1-cd0
     *   fd[a-]   to  floppy[0-]
     */
J
Jim Meyering 已提交
2784
    if (STRPREFIX (path, "hd") && c_islower(path[2]))
2785 2786 2787 2788
        snprintf (qemu_dev_name, sizeof (qemu_dev_name),
                  "ide0-hd%d", path[2] - 'a');
    else if (STREQ (path, "cdrom"))
        strcpy (qemu_dev_name, "ide1-cd0");
J
Jim Meyering 已提交
2789
    else if (STRPREFIX (path, "fd") && c_islower(path[2]))
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
        snprintf (qemu_dev_name, sizeof (qemu_dev_name),
                  "floppy%d", path[2] - 'a');
    else {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
        return -1;
    }

    len = strlen (qemu_dev_name);

    if (qemudMonitorCommand (driver, vm, "info blockstats", &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
        return -1;
    }

    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.
     */
2813
    if (STRPREFIX (info, "info ")) {
2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844
        free (info);
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
        return -1;
    }

    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) {
2845
                if (STRPREFIX (p, "rd_bytes=")) {
2846 2847 2848
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
                        DEBUG ("error reading rd_bytes: %s", p);
2849
                } else if (STRPREFIX (p, "wr_bytes=")) {
2850 2851 2852
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
                        DEBUG ("error reading wr_bytes: %s", p);
2853
                } else if (STRPREFIX (p, "rd_operations=")) {
2854 2855 2856
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
                        DEBUG ("error reading rd_req: %s", p);
2857
                } else if (STRPREFIX (p, "wr_operations=")) {
2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
                    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++;
            }

            goto done;
        }

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

    /* If we reach here then the device was not found. */
    free (info);
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                      _("device not found: %s (%s)"), path, qemu_dev_name);
    return -1;

 done:
    free (info);
    return 0;
}

2890 2891 2892 2893 2894 2895 2896
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
#ifdef __linux__
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2897
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
2898
    int i;
2899 2900 2901

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
2902
                          _("no domain with matching id %d"), dom->id);
2903 2904 2905
        return -1;
    }

2906
    if (!virDomainIsActive(vm)) {
2907
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2908
                         "%s", _("domain is not running"));
2909 2910 2911 2912 2913
        return -1;
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2914
                         "%s", _("NULL or empty path"));
2915 2916 2917 2918
        return -1;
    }

    /* Check the path is one of the domain's network interfaces. */
2919 2920 2921
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
            STREQ (vm->def->nets[i]->ifname, path))
2922
            goto ok;
2923 2924 2925
    }

    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2926
                      _("invalid path, '%s' is not a known interface"), path);
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
    return -1;
 ok:

    return linuxDomainInterfaceStats (dom->conn, path, stats);
#else
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
#endif
}

2938 2939 2940 2941 2942 2943 2944 2945
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
2946
    virDomainObjPtr vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2947
    int fd, ret = -1, i;
2948 2949 2950

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
J
Jim Meyering 已提交
2951
                          "%s", _("no domain with matching uuid"));
2952 2953 2954 2955 2956
        return -1;
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
2957
                         "%s", _("NULL or empty path"));
2958 2959 2960 2961
        return -1;
    }

    /* Check the path belongs to this domain. */
2962 2963 2964 2965
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
            STREQ (vm->def->disks[i]->src, path))
            goto found;
2966 2967
    }
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
2968
                      "%s", _("invalid path"));
2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
    return -1;

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

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

    ret = 0;
 done:
    if (fd >= 0) close (fd);
    return ret;
}

R
Richard W.M. Jones 已提交
2997 2998 2999 3000 3001 3002 3003
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
3004
    virDomainObjPtr vm = virDomainFindByID(&driver->domains, dom->id);
R
Richard W.M. Jones 已提交
3005 3006 3007 3008 3009 3010
    char cmd[256], *info;
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

    if (flags != VIR_MEMORY_VIRTUAL) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
3011
                          "%s", _("QEMU driver only supports virtual memory addrs"));
R
Richard W.M. Jones 已提交
3012 3013 3014 3015 3016 3017 3018 3019 3020
        return -1;
    }

    if (!vm) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_DOMAIN,
                          _("no domain with matching id %d"), dom->id);
        return -1;
    }

3021
    if (!virDomainIsActive(vm)) {
R
Richard W.M. Jones 已提交
3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
        return -1;
    }

    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_SYSTEM_ERROR,
                          "%s", strerror (errno));
        return -1;
    }

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
    if (qemudMonitorCommand (driver, vm, cmd, &info) < 0) {
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3038
                          "%s", _("'memsave' command failed"));
R
Richard W.M. Jones 已提交
3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058
        goto done;
    }

    DEBUG ("memsave reply: %s", info);
    free (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));
        goto done;
    }

    ret = 0;
done:
    if (fd >= 0) close (fd);
    unlink (tmp);
    return ret;
}

3059

3060 3061 3062 3063
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    LIBVIR_VERSION_NUMBER,
3064
    qemudProbe, /* probe */
3065 3066
    qemudOpen, /* open */
    qemudClose, /* close */
3067
    NULL, /* supports_feature */
3068 3069
    qemudGetType, /* type */
    qemudGetVersion, /* version */
3070
    qemudGetHostname, /* hostname */
3071
    NULL, /* URI  */
3072 3073 3074 3075 3076
    qemudGetMaxVCPUs, /* getMaxVcpus */
    qemudGetNodeInfo, /* nodeGetInfo */
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
3077
    qemudDomainCreate, /* domainCreateXML */
3078 3079 3080 3081 3082
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
3083
    qemudDomainShutdown, /* domainShutdown */
3084 3085 3086
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
3087 3088 3089
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
3090 3091 3092 3093
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
3094
    qemudDomainSetVcpus, /* domainSetVcpus */
3095 3096 3097 3098
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
3099 3100
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
3101
#endif
3102
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
3103 3104 3105 3106 3107 3108
    qemudDomainDumpXML, /* domainDumpXML */
    qemudListDefinedDomains, /* listDomains */
    qemudNumDefinedDomains, /* numOfDomains */
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
3109
    qemudDomainAttachDevice, /* domainAttachDevice */
3110 3111 3112 3113 3114 3115
    NULL, /* domainDetachDevice */
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
3116 3117 3118
    NULL, /* domainMigratePrepare */
    NULL, /* domainMigratePerform */
    NULL, /* domainMigrateFinish */
3119
    qemudDomainBlockStats, /* domainBlockStats */
3120
    qemudDomainInterfaceStats, /* domainInterfaceStats */
3121
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
3122
    qemudDomainMemoryPeek, /* domainMemoryPeek */
3123 3124 3125 3126
#if HAVE_NUMACTL
    qemudNodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    qemudNodeGetFreeMemory,  /* getFreeMemory */
#else
3127
    NULL, /* nodeGetCellsFreeMemory */
3128
    NULL, /* getFreeMemory */
3129
#endif
3130 3131 3132
};


3133
static virStateDriver qemuStateDriver = {
3134 3135 3136 3137
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
3138
};
3139

3140 3141 3142 3143 3144 3145
int qemudRegister(void) {
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}