qemu_driver.c 162.1 KB
Newer Older
D
Daniel P. Berrange 已提交
1 2 3
/*
 * driver.c: core driver methods for managing qemu guests
 *
4
 * Copyright (C) 2006, 2007, 2008, 2009 Red Hat, Inc.
D
Daniel P. Berrange 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 * Copyright (C) 2006 Daniel P. Berrange
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

24
#include <config.h>
25

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

47 48 49 50
#if HAVE_SCHED_H
#include <sched.h>
#endif

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

70

71 72
#define VIR_FROM_THIS VIR_FROM_QEMU

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

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


80 81
static int qemudShutdown(void);

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

91 92 93
static void qemuDomainEventFlush(int timer, void *opaque);
static void qemuDomainEventQueue(struct qemud_driver *driver,
                                 virDomainEventPtr event);
94

95 96
static void qemudDispatchVMEvent(int watch,
                                 int fd,
97 98 99
                                 int events,
                                 void *opaque);

100 101
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
102
                              virDomainObjPtr vm,
103 104
                              const char *migrateFrom,
                              int stdin_fd);
105

106 107
static void qemudShutdownVMDaemon(virConnectPtr conn,
                                  struct qemud_driver *driver,
108
                                  virDomainObjPtr vm);
109

110
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
111

112 113 114 115 116 117 118 119
static int qemudMonitorCommand(const virDomainObjPtr vm,
                               const char *cmd,
                               char **reply);
static int qemudMonitorCommandExtra(const virDomainObjPtr vm,
                                    const char *cmd,
                                    const char *extra,
                                    const char *extraPrompt,
                                    char **reply);
120 121 122
static int qemudDomainSetMemoryBalloon(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       unsigned long newmem);
123 124
static int qemudDetectVcpuPIDs(virConnectPtr conn,
                               virDomainObjPtr vm);
125

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


129
static int
130
qemudLogFD(virConnectPtr conn, struct qemud_driver *driver, const char* name)
131 132 133
{
    char logfile[PATH_MAX];
    mode_t logmode;
G
Guido Günther 已提交
134
    int ret, fd = -1;
135

136 137
    if ((ret = snprintf(logfile, sizeof(logfile), "%s/%s.log",
                        driver->logDir, name))
G
Guido Günther 已提交
138
        < 0 || ret >= sizeof(logfile)) {
139
        virReportOOMError(conn);
140 141 142 143
        return -1;
    }

    logmode = O_CREAT | O_WRONLY;
144 145
    /* Only logrotate files in /var/log, so only append if running privileged */
    if (driver->privileged)
146
        logmode |= O_APPEND;
147 148 149
    else
        logmode |= O_TRUNC;

150
    if ((fd = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
151 152 153
        virReportSystemError(conn, errno,
                             _("failed to create logfile %s"),
                             logfile);
154 155
        return -1;
    }
156
    if (virSetCloseExec(fd) < 0) {
157 158
        virReportSystemError(conn, errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
159 160 161 162 163 164 165
        close(fd);
        return -1;
    }
    return fd;
}


166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
static int
qemudLogReadFD(virConnectPtr conn, const char* logDir, const char* name, off_t pos)
{
    char logfile[PATH_MAX];
    mode_t logmode = O_RDONLY;
    int ret, fd = -1;

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


    if ((fd = open(logfile, logmode)) < 0) {
183 184 185
        virReportSystemError(conn, errno,
                             _("failed to create logfile %s"),
                             logfile);
186 187
        return -1;
    }
188
    if (virSetCloseExec(fd) < 0) {
189 190
        virReportSystemError(conn, errno, "%s",
                             _("Unable to set VM logfile close-on-exec flag"));
191 192 193 194
        close(fd);
        return -1;
    }
    if (lseek(fd, pos, SEEK_SET) < 0) {
195 196 197
        virReportSystemError(conn, errno,
                             _("Unable to seek to %lld in %s"),
                             (long long) pos, logfile);
198 199 200 201 202 203
        close(fd);
    }
    return fd;
}


204 205 206
static void
qemudAutostartConfigs(struct qemud_driver *driver) {
    unsigned int i;
207 208 209 210 211
    /* XXX: Figure out a better way todo this. The domain
     * startup code needs a connection handle in order
     * to lookup the bridge associated with a virtual
     * network
     */
212 213 214
    virConnectPtr conn = virConnectOpen(driver->privileged ?
                                        "qemu:///system" :
                                        "qemu:///session");
215
    /* Ignoring NULL conn which is mostly harmless here */
216

217
    qemuDriverLock(driver);
218
    for (i = 0 ; i < driver->domains.count ; i++) {
219
        virDomainObjPtr vm = driver->domains.objs[i];
220
        virDomainObjLock(vm);
221 222
        if (vm->autostart &&
            !virDomainIsActive(vm)) {
223
            int ret = qemudStartVMDaemon(conn, driver, vm, NULL, -1);
224 225
            if (ret < 0) {
                virErrorPtr err = virGetLastError();
226 227
                VIR_ERROR(_("Failed to autostart VM '%s': %s\n"),
                          vm->def->name,
228
                          err ? err->message : "");
229
            } else {
230 231 232 233 234 235
                virDomainEventPtr event =
                    virDomainEventNewFromObj(vm,
                                             VIR_DOMAIN_EVENT_STARTED,
                                             VIR_DOMAIN_EVENT_STARTED_BOOTED);
                if (event)
                    qemuDomainEventQueue(driver, event);
236
            }
237
        }
238
        virDomainObjUnlock(vm);
239
    }
240
    qemuDriverUnlock(driver);
241

242 243
    if (conn)
        virConnectClose(conn);
244 245
}

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

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

    if (virAsprintf(&file, "%s/%s.xml", driver->stateDir, vm->def->name) < 0) {
263
        virReportOOMError(conn);
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
        goto cleanup;
    }

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

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

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


283 284 285 286 287 288
static int qemudOpenMonitor(virConnectPtr conn,
                            struct qemud_driver* driver,
                            virDomainObjPtr vm,
                            const char *monitor,
                            int reconnect);

289 290 291 292

/*
 * Open an existing VM's monitor, re-detect VCPU threads
 * and re-reserve the security labels in use
293 294
 */
static int
295 296
qemuReconnectDomain(struct qemud_driver *driver,
                    virDomainObjPtr obj)
297
{
298
    int rc;
299

300 301 302 303 304
    if ((rc = qemudOpenMonitor(NULL, driver, obj, obj->monitorpath, 1)) != 0) {
        VIR_ERROR(_("Failed to reconnect monitor for %s: %d\n"),
                  obj->def->name, rc);
        goto error;
    }
305

306 307 308
    if (qemudDetectVcpuPIDs(NULL, obj) < 0) {
        goto error;
    }
309

310 311 312 313 314
    if (obj->def->seclabel.type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
        driver->securityDriver &&
        driver->securityDriver->domainReserveSecurityLabel &&
        driver->securityDriver->domainReserveSecurityLabel(NULL, obj) < 0)
        return -1;
315

316 317
    if (obj->def->id >= driver->nextvmid)
        driver->nextvmid = obj->def->id + 1;
318

319
    return 0;
320

321 322 323
error:
    return -1;
}
324

325 326 327 328 329 330 331 332 333 334
/**
 * qemudReconnectVMs
 *
 * Try to re-open the resources for live VMs that we care
 * about.
 */
static void
qemuReconnectDomains(struct qemud_driver *driver)
{
    int i;
335

336 337 338 339 340 341 342 343 344
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjPtr obj = driver->domains.objs[i];

        virDomainObjLock(obj);
        if (qemuReconnectDomain(driver, obj) < 0) {
            /* If we can't get the monitor back, then kill the VM
             * so user has ability to start it again later without
             * danger of ending up running twice */
            qemudShutdownVMDaemon(NULL, driver, obj);
345
        }
346
        virDomainObjUnlock(obj);
347 348 349
    }
}

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
static int
qemudSecurityInit(struct qemud_driver *qemud_drv)
{
    int ret;
    const char *doi, *model;
    virCapsPtr caps;
    virSecurityDriverPtr security_drv;

    ret = virSecurityDriverStartup(&security_drv,
                                   qemud_drv->securityDriverName);
    if (ret == -1) {
        VIR_ERROR0(_("Failed to start security driver"));
        return -1;
    }
    /* No security driver wanted to be enabled: just return */
    if (ret == -2) {
        VIR_INFO0(_("No security driver available"));
        return 0;
    }

    qemud_drv->securityDriver = security_drv;
    doi = virSecurityDriverGetDOI(security_drv);
    model = virSecurityDriverGetModel(security_drv);

    VIR_DEBUG("Initialized security driver \"%s\" with "
              "DOI \"%s\"", model, doi);

    /*
     * Add security policy host caps now that the security driver is
     * initialized.
     */
    caps = qemud_drv->caps;

    caps->host.secModel.model = strdup(model);
    if (!caps->host.secModel.model) {
        char ebuf[1024];
        VIR_ERROR(_("Failed to copy secModel model: %s"),
                  virStrerror(errno, ebuf, sizeof ebuf));
        return -1;
    }

    caps->host.secModel.doi = strdup(doi);
    if (!caps->host.secModel.doi) {
        char ebuf[1024];
        VIR_ERROR(_("Failed to copy secModel DOI: %s"),
                  virStrerror(errno, ebuf, sizeof ebuf));
        return -1;
    }

    return 0;
}
401

402 403 404 405 406 407
/**
 * qemudStartup:
 *
 * Initialization function for the QEmu daemon
 */
static int
408
qemudStartup(int privileged) {
409
    char *base = NULL;
D
Daniel P. Berrange 已提交
410
    char driverConf[PATH_MAX];
411

412
    if (VIR_ALLOC(qemu_driver) < 0)
413 414
        return -1;

415
    if (virMutexInit(&qemu_driver->lock) < 0) {
416
        VIR_ERROR("%s", _("cannot initialize mutex"));
417 418 419
        VIR_FREE(qemu_driver);
        return -1;
    }
420
    qemuDriverLock(qemu_driver);
421
    qemu_driver->privileged = privileged;
422

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

426 427
    /* Init callback list */
    if(VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
428
        goto out_of_memory;
429 430 431 432 433 434
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
        goto out_of_memory;

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

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

D
Daniel P. Berrange 已提交
441
        if ((base = strdup (SYSCONF_DIR "/libvirt")) == NULL)
442
            goto out_of_memory;
443 444 445 446

        if (virAsprintf(&qemu_driver->stateDir,
                      "%s/run/libvirt/qemu/", LOCAL_STATE_DIR) == -1)
            goto out_of_memory;
447
    } else {
448
        uid_t uid = geteuid();
449 450
        char *userdir = virGetUserDirectory(NULL, uid);
        if (!userdir)
451
            goto error;
452

453
        if (virAsprintf(&qemu_driver->logDir,
454 455
                        "%s/.libvirt/qemu/log", userdir) == -1) {
            VIR_FREE(userdir);
456
            goto out_of_memory;
457
        }
458

459 460
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
            VIR_FREE(userdir);
461
            goto out_of_memory;
462 463
        }
        VIR_FREE(userdir);
464 465 466 467 468 469

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

    if (virFileMakePath(qemu_driver->stateDir) < 0) {
470
        char ebuf[1024];
471 472
        VIR_ERROR(_("Failed to create state dir '%s': %s\n"),
                  qemu_driver->stateDir, virStrerror(errno, ebuf, sizeof ebuf));
473
        goto error;
474 475 476 477 478
    }

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

483
    if (virAsprintf(&qemu_driver->configDir, "%s/qemu", base) == -1)
484 485
        goto out_of_memory;

486
    if (virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) == -1)
487 488
        goto out_of_memory;

489
    VIR_FREE(base);
490 491 492

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

494
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
495 496 497
        goto error;
    }

498
    if (qemudSecurityInit(qemu_driver) < 0) {
499
        goto error;
D
Daniel P. Berrange 已提交
500 501
    }

502 503 504 505 506 507 508 509 510 511 512 513
    /* Get all the running persistent or transient configs first */
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->stateDir,
                                NULL,
                                1, NULL, NULL) < 0)
        goto error;

    qemuReconnectDomains(qemu_driver);

    /* Then inactive persistent configs */
514 515 516 517
    if (virDomainLoadAllConfigs(NULL,
                                qemu_driver->caps,
                                &qemu_driver->domains,
                                qemu_driver->configDir,
518
                                qemu_driver->autostartDir,
519
                                0, NULL, NULL) < 0)
520
        goto error;
521 522
    qemuDriverUnlock(qemu_driver);

523 524
    qemudAutostartConfigs(qemu_driver);

525

526 527
    return 0;

528
out_of_memory:
529
    virReportOOMError(NULL);
530 531 532
error:
    if (qemu_driver)
        qemuDriverUnlock(qemu_driver);
533
    VIR_FREE(base);
534
    qemudShutdown();
535 536 537
    return -1;
}

538 539 540 541
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
{
    struct qemud_driver *driver = opaque;

542 543 544 545 546 547 548 549
    if (newVM) {
        virDomainEventPtr event =
            virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
        if (event)
            qemuDomainEventQueue(driver, event);
    }
550 551
}

552 553 554 555 556 557 558 559
/**
 * qemudReload:
 *
 * Function to restart the QEmu daemon, it will recheck the configuration
 * files and update its state and the networking
 */
static int
qemudReload(void) {
560 561 562
    if (!qemu_driver)
        return 0;

563
    qemuDriverLock(qemu_driver);
564 565 566 567
    virDomainLoadAllConfigs(NULL,
                            qemu_driver->caps,
                            &qemu_driver->domains,
                            qemu_driver->configDir,
568
                            qemu_driver->autostartDir,
569
                            0, qemudNotifyLoadDomain, qemu_driver);
570
    qemuDriverUnlock(qemu_driver);
571

572
    qemudAutostartConfigs(qemu_driver);
573 574

    return 0;
575 576
}

577 578 579 580 581 582 583 584 585 586
/**
 * 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) {
587
    unsigned int i;
588
    int active = 0;
589

590 591 592
    if (!qemu_driver)
        return 0;

593 594 595 596 597 598 599 600
    qemuDriverLock(qemu_driver);
    for (i = 0 ; i < qemu_driver->domains.count ; i++) {
        virDomainObjPtr vm = qemu_driver->domains.objs[i];
        virDomainObjLock(vm);
        if (virDomainIsActive(vm))
            active = 1;
        virDomainObjUnlock(vm);
    }
601

602 603
    qemuDriverUnlock(qemu_driver);
    return active;
604 605
}

606 607 608 609 610 611 612
/**
 * qemudShutdown:
 *
 * Shutdown the QEmu daemon, it will stop all active domains and networks
 */
static int
qemudShutdown(void) {
613

614
    if (!qemu_driver)
615
        return -1;
616

617
    qemuDriverLock(qemu_driver);
618 619
    virCapabilitiesFree(qemu_driver->caps);

620
    virDomainObjListFree(&qemu_driver->domains);
621

622
    VIR_FREE(qemu_driver->securityDriverName);
623
    VIR_FREE(qemu_driver->logDir);
624 625
    VIR_FREE(qemu_driver->configDir);
    VIR_FREE(qemu_driver->autostartDir);
626
    VIR_FREE(qemu_driver->stateDir);
627
    VIR_FREE(qemu_driver->vncTLSx509certdir);
J
Jim Meyering 已提交
628
    VIR_FREE(qemu_driver->vncListen);
629
    VIR_FREE(qemu_driver->vncPassword);
630
    VIR_FREE(qemu_driver->vncSASLdir);
D
Daniel P. Berrange 已提交
631

632 633
    /* Free domain callback list */
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
634 635 636 637
    virDomainEventQueueFree(qemu_driver->domainEventQueue);

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

639 640 641
    if (qemu_driver->brctl)
        brShutdown(qemu_driver->brctl);

642
    qemuDriverUnlock(qemu_driver);
643
    virMutexDestroy(&qemu_driver->lock);
644
    VIR_FREE(qemu_driver);
645 646

    return 0;
647 648 649
}

/* Return -1 for error, 1 to continue reading and 0 for success */
650
typedef int qemudHandlerMonitorOutput(virConnectPtr conn,
651
                                      virDomainObjPtr vm,
652 653 654
                                      const char *output,
                                      int fd);

655 656 657
/*
 * Returns -1 for error, 0 on end-of-file, 1 for success
 */
658
static int
659
qemudReadMonitorOutput(virConnectPtr conn,
660
                       virDomainObjPtr vm,
661 662
                       int fd,
                       char *buf,
G
Guido Günther 已提交
663
                       size_t buflen,
664
                       qemudHandlerMonitorOutput func,
665 666
                       const char *what,
                       int timeout)
667
{
G
Guido Günther 已提交
668
    size_t got = 0;
669
    buf[0] = '\0';
670
    timeout *= 1000; /* poll wants milli seconds */
671

672
    /* Consume & discard the initial greeting */
673
    while (got < (buflen-1)) {
G
Guido Günther 已提交
674
        ssize_t ret;
675 676

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

678 679 680 681 682 683
        if (ret < 0) {
            struct pollfd pfd = { .fd = fd, .events = POLLIN };
            if (errno == EINTR)
                continue;

            if (errno != EAGAIN) {
684 685 686
                virReportSystemError(conn, errno,
                                     _("Failure while reading %s startup output"),
                                     what);
687 688 689
                return -1;
            }

690
            ret = poll(&pfd, 1, timeout);
691
            if (ret == 0) {
692
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
693
                                 _("Timed out while reading %s startup output"), what);
694 695 696
                return -1;
            } else if (ret == -1) {
                if (errno != EINTR) {
697 698 699
                    virReportSystemError(conn, errno,
                                         _("Failure while reading %s startup output"),
                                         what);
700 701 702 703 704 705 706 707
                    return -1;
                }
            } else {
                /* Make sure we continue loop & read any further data
                   available before dealing with EOF */
                if (pfd.revents & (POLLIN | POLLHUP))
                    continue;

708
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
709
                                 _("Failure while reading %s startup output"), what);
710 711
                return -1;
            }
712 713
        } else if (ret == 0) {
            return 0;
714 715 716
        } else {
            got += ret;
            buf[got] = '\0';
717 718 719 720 721 722
            ret = func(conn, vm, buf, fd);
            if (ret == -1)
                return -1;
            if (ret == 1)
                continue;
            return 1;
723 724 725
        }
    }

726
    qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
727
                     _("Out of space while reading %s startup output"), what);
728 729 730 731
    return -1;

}

732 733 734 735 736 737 738 739 740

/*
 * Returns -1 for error, 0 on success
 */
static int
qemudReadLogOutput(virConnectPtr conn,
                   virDomainObjPtr vm,
                   int fd,
                   char *buf,
G
Guido Günther 已提交
741
                   size_t buflen,
742 743 744 745
                   qemudHandlerMonitorOutput func,
                   const char *what,
                   int timeout)
{
746
    int retries = (timeout*10);
747
    int got = 0;
748 749 750
    buf[0] = '\0';

    while (retries) {
751
        ssize_t func_ret, ret;
752
        int isdead = 0;
G
Guido Günther 已提交
753

754 755
        func_ret = func(conn, vm, buf, fd);

756 757
        if (kill(vm->pid, 0) == -1 && errno == ESRCH)
            isdead = 1;
758

759 760
        /* Any failures should be detected before we read the log, so we
         * always have something useful to report on failure. */
761 762
        ret = saferead(fd, buf+got, buflen-got-1);
        if (ret < 0) {
763 764 765 766 767 768
            virReportSystemError(conn, errno,
                                 _("Failure while reading %s log output"),
                                 what);
            return -1;
        }

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
        got += ret;
        buf[got] = '\0';
        if (got == buflen-1) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Out of space while reading %s log output"),
                             what);
            return -1;
        }

        if (isdead) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             _("Process exited while reading %s log output"),
                             what);
            return -1;
        }

785 786
        if (func_ret <= 0)
            return func_ret;
787 788 789 790 791 792 793 794 795 796

        usleep(100*1000);
        retries--;
    }
    if (retries == 0)
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Timed out while reading %s log output"), what);
    return -1;
}

797
static int
798
qemudCheckMonitorPrompt(virConnectPtr conn ATTRIBUTE_UNUSED,
799
                        virDomainObjPtr vm,
800 801 802 803 804 805 806 807 808 809 810
                        const char *output,
                        int fd)
{
    if (strstr(output, "(qemu) ") == NULL)
        return 1; /* keep reading */

    vm->monitor = fd;

    return 0;
}

811
static int qemudOpenMonitor(virConnectPtr conn,
812
                            struct qemud_driver* driver,
813
                            virDomainObjPtr vm,
814 815
                            const char *monitor,
                            int reconnect) {
816 817 818 819
    int monfd;
    char buf[1024];
    int ret = -1;

D
Daniel Veillard 已提交
820
    if ((monfd = open(monitor, O_RDWR)) < 0) {
821
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
822
                         _("Unable to open monitor path %s"), monitor);
823 824
        return -1;
    }
825
    if (virSetCloseExec(monfd) < 0) {
826
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
827
                         "%s", _("Unable to set monitor close-on-exec flag"));
828 829
        goto error;
    }
830
    if (virSetNonBlock(monfd) < 0) {
831
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
832
                         "%s", _("Unable to put monitor into non-blocking mode"));
833 834 835
        goto error;
    }

836
    if (!reconnect) {
837 838 839 840
        if (qemudReadMonitorOutput(conn,
                                   vm, monfd,
                                   buf, sizeof(buf),
                                   qemudCheckMonitorPrompt,
841
                                   "monitor", 10) <= 0)
842 843 844
            ret = -1;
        else
            ret = 0;
845 846 847 848 849 850 851
    } else {
        vm->monitor = monfd;
        ret = 0;
    }

    if (ret != 0)
         goto error;
852

853
    if (!(vm->monitorpath = strdup(monitor))) {
854
        virReportOOMError(conn);
855 856 857
        goto error;
    }

858 859 860
    if ((vm->monitorWatch = virEventAddHandle(vm->monitor, 0,
                                              qemudDispatchVMEvent,
                                              driver, NULL)) < 0)
861 862 863
        goto error;


864 865 866 867
    /* Keep monitor open upon success */
    if (ret == 0)
        return ret;

868 869 870 871 872
 error:
    close(monfd);
    return ret;
}

873
/* Returns -1 for error, 0 success, 1 continue reading */
874 875
static int qemudExtractMonitorPath(virConnectPtr conn,
                                   const char *haystack,
876
                                   size_t *offset,
877
                                   char **path) {
878
    static const char needle[] = "char device redirected to";
879
    char *tmp, *dev;
880

881
    VIR_FREE(*path);
882
    /* First look for our magic string */
883 884 885 886 887
    if (!(tmp = strstr(haystack + *offset, needle))) {
        return 1;
    }
    tmp += sizeof(needle);
    dev = tmp;
888

889 890 891 892 893
    /*
     * And look for first whitespace character and nul terminate
     * to mark end of the pty path
     */
    while (*tmp) {
894
        if (c_isspace(*tmp)) {
895
            if (VIR_ALLOC_N(*path, (tmp-dev)+1) < 0) {
896
                virReportOOMError(conn);
897 898 899 900
                return -1;
            }
            strncpy(*path, dev, (tmp-dev));
            (*path)[(tmp-dev)] = '\0';
901
            /* ... now further update offset till we get EOL */
902
            *offset = tmp - haystack;
903 904
            return 0;
        }
905
        tmp++;
906 907 908 909 910
    }

    /*
     * We found a path, but didn't find any whitespace,
     * so it must be still incomplete - we should at
911 912
     * least see a \n - indicate that we want to carry
     * on trying again
913
     */
914
    return 1;
915 916 917
}

static int
918
qemudFindCharDevicePTYs(virConnectPtr conn,
919
                        virDomainObjPtr vm,
920 921
                        const char *output,
                        int fd ATTRIBUTE_UNUSED)
922
{
923
    struct qemud_driver* driver = conn->privateData;
924
    char *monitor = NULL;
925
    size_t offset = 0;
926
    int ret, i;
927 928 929 930 931

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

933
    /* So first comes the monitor device */
934 935
    if ((ret = qemudExtractMonitorPath(conn, output, &offset, &monitor)) != 0)
        goto cleanup;
936

937
    /* then the serial devices */
938 939
    for (i = 0 ; i < vm->def->nserials ; i++) {
        virDomainChrDefPtr chr = vm->def->serials[i];
940 941 942 943
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
944 945 946 947
        }
    }

    /* and finally the parallel devices */
948 949
    for (i = 0 ; i < vm->def->nparallels ; i++) {
        virDomainChrDefPtr chr = vm->def->parallels[i];
950 951 952 953
        if (chr->type == VIR_DOMAIN_CHR_TYPE_PTY) {
            if ((ret = qemudExtractMonitorPath(conn, output, &offset,
                                               &chr->data.file.path)) != 0)
                goto cleanup;
954 955 956 957
        }
    }

    /* Got them all, so now open the monitor console */
958
    ret = qemudOpenMonitor(conn, driver, vm, monitor, 0);
959 960 961 962

cleanup:
    VIR_FREE(monitor);
    return ret;
963 964
}

965
static int qemudWaitForMonitor(virConnectPtr conn,
966 967 968
                               struct qemud_driver* driver,
                               virDomainObjPtr vm, off_t pos)
{
969
    char buf[4096]; /* Plenty of space to get startup greeting */
970 971 972 973 974
    int logfd;
    int ret;

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

977 978 979
    ret = qemudReadLogOutput(conn, vm, logfd, buf, sizeof(buf),
                             qemudFindCharDevicePTYs,
                             "console", 3);
980
    if (close(logfd) < 0) {
981
        char ebuf[4096];
982
        VIR_WARN(_("Unable to close logfile: %s\n"),
983 984
                 virStrerror(errno, ebuf, sizeof ebuf));
    }
985

986
    if (ret == 0) /* success */
987 988 989 990 991 992
        return 0;

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

995 996
static int
qemudDetectVcpuPIDs(virConnectPtr conn,
997
                    virDomainObjPtr vm) {
998 999 1000 1001 1002 1003
    char *qemucpus = NULL;
    char *line;
    int lastVcpu = -1;

    /* Only KVM has seperate threads for CPUs,
       others just use main QEMU process for CPU */
1004
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM)
1005 1006 1007 1008 1009
        vm->nvcpupids = 1;
    else
        vm->nvcpupids = vm->def->vcpus;

    if (VIR_ALLOC_N(vm->vcpupids, vm->nvcpupids) < 0) {
1010
        virReportOOMError(conn);
1011 1012 1013
        return -1;
    }

1014
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
1015 1016 1017 1018
        vm->vcpupids[0] = vm->pid;
        return 0;
    }

1019
    if (qemudMonitorCommand(vm, "info cpus", &qemucpus) < 0) {
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
        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;

1078
    VIR_FREE(qemucpus);
1079 1080 1081 1082
    return 0;

error:
    VIR_FREE(vm->vcpupids);
1083 1084
    vm->nvcpupids = 0;
    VIR_FREE(qemucpus);
1085 1086 1087 1088 1089 1090 1091 1092

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

1093 1094
static int
qemudInitCpus(virConnectPtr conn,
D
Daniel Veillard 已提交
1095 1096
              virDomainObjPtr vm,
              const char *migrateFrom) {
1097 1098 1099 1100 1101 1102
    char *info = NULL;
#if HAVE_SCHED_GETAFFINITY
    cpu_set_t mask;
    int i, maxcpu = QEMUD_CPUMASK_LEN;
    virNodeInfo nodeinfo;

1103
    if (nodeGetInfo(conn, &nodeinfo) < 0)
1104 1105 1106 1107 1108 1109 1110 1111
        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 已提交
1112 1113 1114 1115 1116 1117
    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++)
1118
            CPU_SET(i, &mask);
D
Daniel P. Berrange 已提交
1119
    }
1120 1121 1122 1123

    for (i = 0 ; i < vm->nvcpupids ; i++) {
        if (sched_setaffinity(vm->vcpupids[i],
                              sizeof(mask), &mask) < 0) {
1124 1125
            virReportSystemError(conn, errno, "%s",
                                 _("failed to set CPU affinity"));
1126 1127 1128 1129 1130
            return -1;
        }
    }
#endif /* HAVE_SCHED_GETAFFINITY */

D
Daniel Veillard 已提交
1131 1132
    if (migrateFrom == NULL) {
        /* Allow the CPUS to start executing */
1133
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
D
Daniel Veillard 已提交
1134 1135 1136 1137 1138
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("resume operation failed"));
            return -1;
        }
        VIR_FREE(info);
1139 1140 1141 1142 1143 1144
    }

    return 0;
}


1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
static int
qemudInitPasswords(virConnectPtr conn,
                   struct qemud_driver *driver,
                   virDomainObjPtr vm) {
    char *info = NULL;

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

1157 1158 1159
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        (vm->def->graphics[0]->data.vnc.passwd || driver->vncPassword)) {
1160 1161

        if (qemudMonitorCommandExtra(vm, "change vnc password",
1162 1163
                                     vm->def->graphics[0]->data.vnc.passwd ?
                                     vm->def->graphics[0]->data.vnc.passwd :
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
                                     driver->vncPassword,
                                     QEMU_PASSWD_PROMPT,
                                     &info) < 0) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                             "%s", _("setting VNC password failed"));
            return -1;
        }
        VIR_FREE(info);
    }

    return 0;
}


1178
static int qemudNextFreeVNCPort(struct qemud_driver *driver ATTRIBUTE_UNUSED) {
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    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;
}

1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
static int qemuPrepareHostDevices(virConnectPtr conn,
                                  virDomainDefPtr def) {
    int i;

    /* We have to use 2 loops here. *All* devices must
     * be detached before we reset any of them, because
     * in some cases you have to reset the whole PCI,
     * which impacts all devices on it
     */

    for (i = 0 ; i < def->nhostdevs ; i++) {
        virDomainHostdevDefPtr hostdev = def->hostdevs[i];

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
        if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
            continue;

1232
        if (hostdev->managed) {
1233 1234 1235 1236 1237 1238 1239 1240 1241 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
            pciDevice *dev = pciGetDevice(conn,
                                          hostdev->source.subsys.u.pci.domain,
                                          hostdev->source.subsys.u.pci.bus,
                                          hostdev->source.subsys.u.pci.slot,
                                          hostdev->source.subsys.u.pci.function);
            if (!dev)
                goto error;

            if (pciDettachDevice(conn, dev) < 0) {
                pciFreeDevice(conn, dev);
                goto error;
            }

            pciFreeDevice(conn, dev);
        } /* else {
             XXX validate that non-managed device isn't in use, eg
             by checking that device is either un-bound, or bound
             to pci-stub.ko
        } */
    }

    /* Now that all the PCI hostdevs have be dettached, we can safely
     * reset them */
    for (i = 0 ; i < def->nhostdevs ; i++) {
        virDomainHostdevDefPtr hostdev = def->hostdevs[i];
        pciDevice *dev;

        if (hostdev->mode != VIR_DOMAIN_HOSTDEV_MODE_SUBSYS)
            continue;
        if (hostdev->source.subsys.type != VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_PCI)
            continue;

        dev = pciGetDevice(conn,
                           hostdev->source.subsys.u.pci.domain,
                           hostdev->source.subsys.u.pci.bus,
                           hostdev->source.subsys.u.pci.slot,
                           hostdev->source.subsys.u.pci.function);
        if (!dev)
            goto error;

        if (pciResetDevice(conn, dev) < 0) {
            pciFreeDevice(conn, dev);
            goto error;
        }

        pciFreeDevice(conn, dev);
    }

    return 0;

error:
    return -1;
}

1287 1288 1289 1290 1291 1292 1293 1294 1295
static int qemudDomainSetSecurityLabel(virConnectPtr conn, struct qemud_driver *driver, virDomainObjPtr vm)
{
    if (vm->def->seclabel.label != NULL)
        if (driver->securityDriver && driver->securityDriver->domainSetSecurityLabel)
            return driver->securityDriver->domainSetSecurityLabel(conn, driver->securityDriver,
                                                                 vm);
    return 0;
}

1296 1297 1298
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
                                            const char *name);

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
struct gemudHookData {
        virConnectPtr conn;
        virDomainObjPtr vm;
        struct qemud_driver *driver;
};

static int qemudSecurityHook(void *data) {
        struct gemudHookData *h = (struct gemudHookData *) data;

        if (qemudDomainSetSecurityLabel(h->conn, h->driver, h->vm) < 0) {
                qemudReportError(h->conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("Failed to set security label"));
                return -1;
        }
        return 0;
}

1316 1317
static int qemudStartVMDaemon(virConnectPtr conn,
                              struct qemud_driver *driver,
1318
                              virDomainObjPtr vm,
1319 1320
                              const char *migrateFrom,
                              int stdin_fd) {
1321
    const char **argv = NULL, **tmp;
1322
    const char **progenv = NULL;
1323
    int i, ret;
1324
    struct stat sb;
1325 1326
    int *tapfds = NULL;
    int ntapfds = 0;
1327
    unsigned int qemuCmdFlags;
1328
    fd_set keepfd;
1329
    const char *emulator;
G
Guido Günther 已提交
1330
    pid_t child;
1331
    int pos = -1;
1332
    char ebuf[1024];
1333
    char *pidfile = NULL;
1334
    int logfile;
1335

1336 1337 1338 1339 1340
    struct gemudHookData hookData;
    hookData.conn = conn;
    hookData.vm = vm;
    hookData.driver = driver;

1341
    FD_ZERO(&keepfd);
1342

1343
    if (virDomainIsActive(vm)) {
1344
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_INVALID,
1345
                         "%s", _("VM is already active"));
1346 1347 1348
        return -1;
    }

1349 1350 1351 1352 1353 1354 1355 1356
    /* If you are using a SecurityDriver with dynamic labelling,
       then generate a security label for isolation */
    if (vm->def->seclabel.type == VIR_DOMAIN_SECLABEL_DYNAMIC &&
        driver->securityDriver &&
        driver->securityDriver->domainGenSecurityLabel &&
        driver->securityDriver->domainGenSecurityLabel(conn, vm) < 0)
        return -1;

1357 1358 1359
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics[0]->data.vnc.autoport) {
1360
        int port = qemudNextFreeVNCPort(driver);
1361
        if (port < 0) {
1362
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1363
                             "%s", _("Unable to find an unused VNC port"));
1364
            goto cleanup;
1365
        }
1366
        vm->def->graphics[0]->data.vnc.port = port;
1367
    }
1368

1369
    if (virFileMakePath(driver->logDir) < 0) {
1370 1371 1372
        virReportSystemError(conn, errno,
                             _("cannot create log directory %s"),
                             driver->logDir);
1373
        goto cleanup;
1374 1375
    }

1376
    if ((logfile = qemudLogFD(conn, driver, vm->def->name)) < 0)
1377
        goto cleanup;
1378

1379 1380
    emulator = vm->def->emulator;

1381 1382 1383 1384
    /* 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
     */
1385
    if (stat(emulator, &sb) < 0) {
1386 1387 1388
        virReportSystemError(conn, errno,
                             _("Cannot find QEMU binary %s"),
                             emulator);
1389
        goto cleanup;
1390 1391
    }

1392
    if (qemudExtractVersionInfo(emulator,
1393
                                NULL,
1394
                                &qemuCmdFlags) < 0)
1395
        goto cleanup;
1396

1397
    if (qemuPrepareHostDevices(conn, vm->def) < 0)
1398
        goto cleanup;
1399

D
Daniel P. Berrange 已提交
1400 1401 1402 1403 1404 1405 1406
    if ((ret = virFileDeletePid(driver->stateDir, vm->def->name)) != 0) {
        virReportSystemError(conn, ret,
                             _("Cannot remove stale PID file for %s"),
                             vm->def->name);
        goto cleanup;
    }

1407 1408 1409 1410 1411
    if (!(pidfile = virFilePid(driver->stateDir, vm->def->name))) {
        virReportSystemError(conn, errno,
                             "%s", _("Failed to build pidfile path."));
        goto cleanup;
    }
D
Daniel P. Berrange 已提交
1412

1413
    vm->def->id = driver->nextvmid++;
1414
    if (qemudBuildCommandLine(conn, driver, vm->def,
1415
                              qemuCmdFlags, &argv, &progenv,
1416 1417
                              &tapfds, &ntapfds, migrateFrom) < 0)
        goto cleanup;
1418

1419 1420
    tmp = progenv;
    while (*tmp) {
1421
        if (safewrite(logfile, *tmp, strlen(*tmp)) < 0)
1422
            VIR_WARN(_("Unable to write envv to logfile: %s\n"),
1423
                     virStrerror(errno, ebuf, sizeof ebuf));
1424
        if (safewrite(logfile, " ", 1) < 0)
1425
            VIR_WARN(_("Unable to write envv to logfile: %s\n"),
1426
                     virStrerror(errno, ebuf, sizeof ebuf));
1427 1428
        tmp++;
    }
1429 1430
    tmp = argv;
    while (*tmp) {
1431
        if (safewrite(logfile, *tmp, strlen(*tmp)) < 0)
1432
            VIR_WARN(_("Unable to write argv to logfile: %s\n"),
1433
                     virStrerror(errno, ebuf, sizeof ebuf));
1434
        if (safewrite(logfile, " ", 1) < 0)
1435
            VIR_WARN(_("Unable to write argv to logfile: %s\n"),
1436
                     virStrerror(errno, ebuf, sizeof ebuf));
1437 1438
        tmp++;
    }
1439
    if (safewrite(logfile, "\n", 1) < 0)
1440
        VIR_WARN(_("Unable to write argv to logfile: %s\n"),
1441
                 virStrerror(errno, ebuf, sizeof ebuf));
1442

1443
    if ((pos = lseek(logfile, 0, SEEK_END)) < 0)
1444
        VIR_WARN(_("Unable to seek to end of logfile: %s\n"),
1445
                 virStrerror(errno, ebuf, sizeof ebuf));
1446

1447 1448 1449
    for (i = 0 ; i < ntapfds ; i++)
        FD_SET(tapfds[i], &keepfd);

1450
    ret = virExecDaemonize(conn, argv, progenv, &keepfd, &child,
1451
                           stdin_fd, &logfile, &logfile,
1452
                           VIR_EXEC_NONBLOCK,
1453 1454 1455
                           qemudSecurityHook, &hookData,
                           pidfile);
    VIR_FREE(pidfile);
G
Guido Günther 已提交
1456 1457 1458

    /* wait for qemu process to to show up */
    if (ret == 0) {
1459
        if (virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) {
1460
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
1461
                             _("Domain %s didn't show up\n"), vm->def->name);
1462
            ret = -1;
G
Guido Günther 已提交
1463
        }
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
    } else if (ret == -2) {
        /* The virExec process that launches the daemon failed. Pending on
         * when it failed (we can't determine for sure), there may be
         * extra info in the domain log (if the hook failed for example).
         *
         * Pretend like things succeeded, and let 'WaitForMonitor' report
         * the log contents for us.
         */
        vm->pid = child;
        ret = 0;
    }
1475 1476

    vm->state = migrateFrom ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
1477

1478
    for (i = 0 ; argv[i] ; i++)
1479 1480
        VIR_FREE(argv[i]);
    VIR_FREE(argv);
1481

1482 1483 1484 1485
    for (i = 0 ; progenv[i] ; i++)
        VIR_FREE(progenv[i]);
    VIR_FREE(progenv);

1486 1487 1488
    if (tapfds) {
        for (i = 0 ; i < ntapfds ; i++) {
            close(tapfds[i]);
1489
        }
1490
        VIR_FREE(tapfds);
1491 1492
    }

1493 1494 1495 1496 1497 1498 1499 1500
    if (ret == -1)
        goto cleanup;

    if ((qemudWaitForMonitor(conn, driver, vm, pos) < 0) ||
        (qemudDetectVcpuPIDs(conn, vm) < 0) ||
        (qemudInitCpus(conn, vm, migrateFrom) < 0) ||
        (qemudInitPasswords(conn, driver, vm) < 0) ||
        (qemudDomainSetMemoryBalloon(conn, vm, vm->def->memory) < 0) ||
1501
        (virDomainSaveStatus(conn, driver->stateDir, vm) < 0)) {
1502 1503 1504
        qemudShutdownVMDaemon(conn, driver, vm);
        ret = -1;
        /* No need for 'goto cleanup' now since qemudShutdownVMDaemon does enough */
1505 1506
    }

1507
    return ret;
1508 1509 1510 1511 1512 1513 1514

cleanup:
    if (vm->def->seclabel.type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        VIR_FREE(vm->def->seclabel.model);
        VIR_FREE(vm->def->seclabel.label);
        VIR_FREE(vm->def->seclabel.imagelabel);
    }
1515 1516 1517 1518
    if ((vm->def->ngraphics == 1) &&
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
        vm->def->graphics[0]->data.vnc.autoport)
        vm->def->graphics[0]->data.vnc.port = -1;
1519 1520
    if (logfile != -1)
        close(logfile);
1521 1522
    vm->def->id = -1;
    return -1;
1523 1524 1525
}


1526
static void qemudShutdownVMDaemon(virConnectPtr conn ATTRIBUTE_UNUSED,
1527 1528
                                  struct qemud_driver *driver,
                                  virDomainObjPtr vm) {
D
Daniel P. Berrange 已提交
1529 1530
    int ret;

1531
    if (!virDomainIsActive(vm))
1532
        return;
1533

1534
    VIR_DEBUG(_("Shutting down VM '%s'\n"), vm->def->name);
1535

G
Guido Günther 已提交
1536 1537
    if (virKillProcess(vm->pid, 0) == 0 &&
        virKillProcess(vm->pid, SIGTERM) < 0)
1538 1539 1540
        virReportSystemError(conn, errno,
                             _("Failed to send SIGTERM to %s (%d)"),
                             vm->def->name, vm->pid);
1541

1542 1543 1544
    if (vm->monitorWatch != -1) {
        virEventRemoveHandle(vm->monitorWatch);
        vm->monitorWatch = -1;
1545
    }
1546 1547 1548 1549 1550

    if (vm->monitor != -1)
        close(vm->monitor);
    vm->monitor = -1;

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

1554 1555 1556 1557
    /* Reset Security Labels */
    if (driver->securityDriver)
        driver->securityDriver->domainRestoreSecurityLabel(conn, vm);

1558 1559 1560 1561 1562 1563 1564
    /* Clear out dynamically assigned labels */
    if (vm->def->seclabel.type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
        VIR_FREE(vm->def->seclabel.model);
        VIR_FREE(vm->def->seclabel.label);
        VIR_FREE(vm->def->seclabel.imagelabel);
    }

1565
    if (qemudRemoveDomainStatus(conn, driver, vm) < 0) {
1566
        VIR_WARN(_("Failed to remove domain status for %s"),
1567 1568
                 vm->def->name);
    }
D
Daniel P. Berrange 已提交
1569 1570 1571 1572 1573 1574
    if ((ret = virFileDeletePid(driver->stateDir, vm->def->name)) != 0) {
        char ebuf[1024];
        VIR_WARN(_("Failed to remove PID file for %s: %s"),
                 vm->def->name, virStrerror(errno, ebuf, sizeof ebuf));
    }

1575
    vm->pid = -1;
1576
    vm->def->id = -1;
1577
    vm->state = VIR_DOMAIN_SHUTOFF;
1578
    VIR_FREE(vm->vcpupids);
1579
    vm->nvcpupids = 0;
1580 1581

    if (vm->newDef) {
1582
        virDomainDefFree(vm->def);
1583
        vm->def = vm->newDef;
1584
        vm->def->id = -1;
1585 1586 1587 1588 1589
        vm->newDef = NULL;
    }
}


1590
static void
1591
qemudDispatchVMEvent(int watch, int fd, int events, void *opaque) {
1592
    struct qemud_driver *driver = opaque;
1593
    virDomainObjPtr vm = NULL;
1594
    virDomainEventPtr event = NULL;
1595
    unsigned int i;
1596
    int quit = 0, failed = 0;
1597

1598
    qemuDriverLock(driver);
1599
    for (i = 0 ; i < driver->domains.count ; i++) {
1600 1601 1602
        virDomainObjPtr tmpvm = driver->domains.objs[i];
        virDomainObjLock(tmpvm);
        if (virDomainIsActive(tmpvm) &&
1603
            tmpvm->monitorWatch == watch) {
1604
            vm = tmpvm;
1605
            break;
1606
        }
1607
        virDomainObjUnlock(tmpvm);
1608 1609 1610
    }

    if (!vm)
1611
        goto cleanup;
1612

1613
    if (vm->monitor != fd) {
1614 1615
        failed = 1;
    } else {
1616
        if (events & (VIR_EVENT_HANDLE_HANGUP | VIR_EVENT_HANDLE_ERROR))
1617
            quit = 1;
1618
        else {
1619 1620
            VIR_ERROR(_("unhandled fd event %d for %s"),
                      events, vm->def->name);
1621
            failed = 1;
1622
        }
1623 1624
    }

1625
    if (failed || quit) {
1626 1627 1628 1629 1630
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         quit ?
                                         VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN :
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641
        qemudShutdownVMDaemon(NULL, driver, vm);
        if (!vm->persistent) {
            virDomainRemoveInactive(&driver->domains,
                                    vm);
            vm = NULL;
        }
    }

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
1642 1643
    if (event)
        qemuDomainEventQueue(driver, event);
1644
    qemuDriverUnlock(driver);
1645 1646
}

1647
static int
1648 1649 1650 1651 1652
qemudMonitorCommandExtra(const virDomainObjPtr vm,
                         const char *cmd,
                         const char *extra,
                         const char *extraPrompt,
                         char **reply) {
D
Daniel P. Berrange 已提交
1653 1654
    int size = 0;
    char *buf = NULL;
1655
    size_t cmdlen = strlen(cmd);
1656
    size_t extralen = extra ? strlen(extra) : 0;
D
Daniel P. Berrange 已提交
1657

1658 1659 1660
    if (safewrite(vm->monitor, cmd, cmdlen) != cmdlen)
        return -1;
    if (safewrite(vm->monitor, "\r", 1) != 1)
D
Daniel P. Berrange 已提交
1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672
        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 已提交
1673

1674 1675
            if (got == 0)
                goto error;
D
Daniel P. Berrange 已提交
1676 1677 1678 1679 1680
            if (got < 0) {
                if (errno == EINTR)
                    continue;
                if (errno == EAGAIN)
                    break;
1681
                goto error;
1682
            }
1683
            if (VIR_REALLOC_N(buf, size+got+1) < 0)
1684 1685
                goto error;

D
Daniel P. Berrange 已提交
1686 1687 1688 1689
            memmove(buf+size, data, got);
            buf[size+got] = '\0';
            size += got;
        }
1690

D
Daniel P. Berrange 已提交
1691
        /* Look for QEMU prompt to indicate completion */
1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716
        if (buf) {
            if (extra) {
                if (strstr(buf, extraPrompt) != NULL) {
                    if (safewrite(vm->monitor, extra, extralen) != extralen)
                        return -1;
                    if (safewrite(vm->monitor, "\r", 1) != 1)
                        return -1;
                    extra = NULL;
                }
            } else if ((tmp = strstr(buf, QEMU_CMD_PROMPT)) != NULL) {
                char *commptr = NULL, *nlptr = NULL;
                /* Preserve the newline */
                tmp[1] = '\0';

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

1718 1719
                break;
            }
D
Daniel P. Berrange 已提交
1720 1721 1722 1723 1724 1725
        }
    pollagain:
        /* Need to wait for more data */
        if (poll(&fd, 1, -1) < 0) {
            if (errno == EINTR)
                goto pollagain;
1726
            goto error;
D
Daniel P. Berrange 已提交
1727 1728 1729 1730
        }
    }
    *reply = buf;
    return 0;
1731 1732

 error:
1733
    VIR_FREE(buf);
1734
    return -1;
D
Daniel P. Berrange 已提交
1735 1736
}

1737 1738 1739 1740 1741 1742 1743 1744
static int
qemudMonitorCommand(const virDomainObjPtr vm,
                    const char *cmd,
                    char **reply) {
    return qemudMonitorCommandExtra(vm, cmd, NULL, NULL, reply);
}


1745

1746
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
1747
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
1748
                                  int flags ATTRIBUTE_UNUSED) {
1749
    if (conn->uri == NULL) {
1750 1751 1752
        if (qemu_driver == NULL)
            return VIR_DRV_OPEN_DECLINED;

1753
        conn->uri = xmlParseURI(qemu_driver->privileged ?
1754 1755
                                "qemu:///system" :
                                "qemu:///session");
1756
        if (!conn->uri) {
1757
            virReportOOMError(conn);
1758 1759
            return VIR_DRV_OPEN_ERROR;
        }
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
    } else {
        /* If URI isn't 'qemu' its definitely not for us */
        if (conn->uri->scheme == NULL ||
            STRNEQ(conn->uri->scheme, "qemu"))
            return VIR_DRV_OPEN_DECLINED;

        /* Allow remote driver to deal with URIs with hostname server */
        if (conn->uri->server != NULL)
            return VIR_DRV_OPEN_DECLINED;

1770
        if (qemu_driver->privileged) {
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
            if (STRNEQ (conn->uri->path, "/system") &&
                STRNEQ (conn->uri->path, "/session")) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("unexpected QEMU URI path '%s', try qemu:///system"),
                                 conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        } else {
            if (STRNEQ (conn->uri->path, "/session")) {
                qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("unexpected QEMU URI path '%s', try qemu:///session"),
                                 conn->uri->path);
                return VIR_DRV_OPEN_ERROR;
            }
        }
1786

1787 1788 1789 1790 1791 1792
        /* URI was good, but driver isn't active */
        if (qemu_driver == NULL) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                             _("qemu state driver is not active"));
            return VIR_DRV_OPEN_ERROR;
        }
1793

1794 1795 1796 1797 1798 1799 1800
    }
    conn->privateData = qemu_driver;

    return VIR_DRV_OPEN_SUCCESS;
}

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

    /* Get rid of callbacks registered for this conn */
1804
    qemuDriverLock(driver);
1805
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
1806
    qemuDriverUnlock(driver);
1807 1808 1809 1810 1811 1812

    conn->privateData = NULL;

    return 0;
}

D
Daniel Veillard 已提交
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
/* Which features are supported by this driver? */
static int
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
{
    switch (feature) {
    case VIR_DRV_FEATURE_MIGRATION_V2: return 1;
    default: return 0;
    }
}

1823
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
1824
    return "QEMU";
1825 1826
}

1827 1828 1829 1830 1831

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

    int r, fd;
1832

1833 1834
    fd = open(KVM_DEVICE, O_RDONLY);
    if (fd < 0) {
1835 1836
        virReportSystemError(NULL, errno, _("Unable to open %s"), KVM_DEVICE);
        return -1;
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
    }

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

    close(fd);
    return maxvcpus;
}


1848
static int qemudGetMaxVCPUs(virConnectPtr conn, const char *type) {
1849 1850 1851
    if (!type)
        return 16;

1852
    if (STRCASEEQ(type, "qemu"))
1853 1854
        return 16;

1855
    if (STRCASEEQ(type, "kvm"))
1856
        return kvmGetMaxVCPUs();
1857

1858
    if (STRCASEEQ(type, "kqemu"))
1859
        return 1;
1860 1861 1862

    qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                     _("unknown type '%s'"), type);
1863 1864 1865
    return -1;
}

1866

1867
static char *qemudGetCapabilities(virConnectPtr conn) {
1868
    struct qemud_driver *driver = conn->privateData;
1869
    char *xml = NULL;
1870

1871
    qemuDriverLock(driver);
1872 1873 1874
    virCapabilitiesFree(qemu_driver->caps);
    if ((qemu_driver->caps = qemudCapsInit()) == NULL ||
        (xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
1875
        virReportOOMError(conn);
1876
    qemuDriverUnlock(driver);
1877

1878
    return xml;
1879 1880 1881
}


D
Daniel P. Berrange 已提交
1882 1883 1884
static int qemudGetProcessInfo(unsigned long long *cpuTime, int pid) {
    char proc[PATH_MAX];
    FILE *pidinfo;
1885
    unsigned long long usertime, systime;
D
Daniel P. Berrange 已提交
1886 1887 1888 1889 1890 1891

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

    if (!(pidinfo = fopen(proc, "r"))) {
1892
        /*printf("cannot read pid info");*/
D
Daniel P. Berrange 已提交
1893 1894 1895 1896 1897
        /* VM probably shut down, so fake 0 */
        *cpuTime = 0;
        return 0;
    }

1898
    if (fscanf(pidinfo, "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu", &usertime, &systime) != 2) {
1899
        qemudDebug("not enough arg");
D
Daniel P. Berrange 已提交
1900 1901 1902 1903 1904 1905 1906 1907
        return -1;
    }

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

1910
    qemudDebug("Got %llu %llu %llu", usertime, systime, *cpuTime);
D
Daniel P. Berrange 已提交
1911 1912 1913 1914 1915 1916 1917

    fclose(pidinfo);

    return 0;
}


1918
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
1919
                                          int id) {
1920 1921 1922 1923
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;

1924
    qemuDriverLock(driver);
1925
    vm  = virDomainFindByID(&driver->domains, id);
1926
    qemuDriverUnlock(driver);
1927 1928

    if (!vm) {
1929 1930
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching id %d"), id);
1931
        goto cleanup;
1932 1933
    }

1934
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1935
    if (dom) dom->id = vm->def->id;
1936 1937

cleanup:
1938 1939
    if (vm)
        virDomainObjUnlock(vm);
1940 1941
    return dom;
}
1942

1943
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
1944
                                            const unsigned char *uuid) {
1945 1946 1947
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1948

1949
    qemuDriverLock(driver);
1950
    vm = virDomainFindByUUID(&driver->domains, uuid);
1951 1952
    qemuDriverUnlock(driver);

1953
    if (!vm) {
1954 1955 1956
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(uuid, uuidstr);
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN,
1957
                         _("no domain with matching uuid '%s'"), uuidstr);
1958
        goto cleanup;
1959 1960
    }

1961
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1962
    if (dom) dom->id = vm->def->id;
1963 1964

cleanup:
1965 1966
    if (vm)
        virDomainObjUnlock(vm);
1967 1968
    return dom;
}
1969

1970
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
1971
                                            const char *name) {
1972 1973 1974
    struct qemud_driver *driver = conn->privateData;
    virDomainObjPtr vm;
    virDomainPtr dom = NULL;
1975

1976
    qemuDriverLock(driver);
1977
    vm = virDomainFindByName(&driver->domains, name);
1978 1979
    qemuDriverUnlock(driver);

1980
    if (!vm) {
1981 1982
        qemudReportError(conn, NULL, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching name '%s'"), name);
1983
        goto cleanup;
1984 1985
    }

1986
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
1987
    if (dom) dom->id = vm->def->id;
1988 1989

cleanup:
1990 1991
    if (vm)
        virDomainObjUnlock(vm);
1992 1993 1994
    return dom;
}

1995
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
1996 1997 1998
    struct qemud_driver *driver = conn->privateData;
    int ret = -1;

1999
    qemuDriverLock(driver);
2000
    if (qemudExtractVersion(conn, driver) < 0)
2001
        goto cleanup;
2002

2003
    *version = qemu_driver->qemuVersion;
2004 2005 2006
    ret = 0;

cleanup:
2007
    qemuDriverUnlock(driver);
2008
    return ret;
D
Daniel P. Berrange 已提交
2009 2010
}

2011 2012 2013
static char *
qemudGetHostname (virConnectPtr conn)
{
2014
    char *result;
2015

2016 2017
    result = virGetHostname();
    if (result == NULL) {
2018 2019
        virReportSystemError (conn, errno,
                              "%s", _("failed to determine host name"));
2020 2021 2022
        return NULL;
    }
    /* Caller frees this string. */
2023
    return result;
2024 2025
}

2026
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
2027
    struct qemud_driver *driver = conn->privateData;
2028 2029
    int got = 0, i;

2030 2031 2032
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count && got < nids ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
2033 2034
        if (virDomainIsActive(driver->domains.objs[i]))
            ids[got++] = driver->domains.objs[i]->def->id;
2035 2036 2037
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
2038

D
Daniel P. Berrange 已提交
2039 2040
    return got;
}
2041

2042
static int qemudNumDomains(virConnectPtr conn) {
2043
    struct qemud_driver *driver = conn->privateData;
2044 2045
    int n = 0, i;

2046 2047 2048
    qemuDriverLock(driver);
    for (i = 0 ; i < driver->domains.count ; i++) {
        virDomainObjLock(driver->domains.objs[i]);
2049
        if (virDomainIsActive(driver->domains.objs[i]))
2050
            n++;
2051 2052 2053
        virDomainObjUnlock(driver->domains.objs[i]);
    }
    qemuDriverUnlock(driver);
2054

2055
    return n;
D
Daniel P. Berrange 已提交
2056
}
2057

2058
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
2059
                                      unsigned int flags ATTRIBUTE_UNUSED) {
2060
    struct qemud_driver *driver = conn->privateData;
2061
    virDomainDefPtr def;
2062
    virDomainObjPtr vm = NULL;
2063
    virDomainPtr dom = NULL;
2064
    virDomainEventPtr event = NULL;
D
Daniel P. Berrange 已提交
2065

2066
    qemuDriverLock(driver);
2067 2068
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
2069
        goto cleanup;
2070

2071 2072 2073
    if (virSecurityDriverVerify(conn, def) < 0)
        goto cleanup;

2074
    /* See if a VM with matching UUID already exists */
2075
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
2076
    if (vm) {
2077 2078 2079 2080 2081 2082 2083 2084 2085
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain '%s' is already defined with uuid %s"),
                             vm->def->name, uuidstr);
            goto cleanup;
        }
2086

2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104
        /* UUID & name match, but if VM is already active, refuse it */
        if (virDomainIsActive(vm)) {
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain is already active as '%s'"), vm->def->name);
            goto cleanup;
        }
        virDomainObjUnlock(vm);
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        vm = virDomainFindByName(&driver->domains, def->name);
        if (vm) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain '%s' is already defined with uuid %s"),
                             def->name, uuidstr);
            goto cleanup;
        }
2105
    }
2106

2107 2108
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
2109 2110 2111 2112
                                  def)))
        goto cleanup;

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

2114
    if (qemudStartVMDaemon(conn, driver, vm, NULL, -1) < 0) {
2115 2116
        virDomainRemoveInactive(&driver->domains,
                                vm);
2117
        vm = NULL;
2118
        goto cleanup;
D
Daniel P. Berrange 已提交
2119
    }
2120 2121 2122 2123

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

2125
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
2126
    if (dom) dom->id = vm->def->id;
2127 2128 2129

cleanup:
    virDomainDefFree(def);
2130 2131
    if (vm)
        virDomainObjUnlock(vm);
2132 2133
    if (event)
        qemuDomainEventQueue(driver, event);
2134
    qemuDriverUnlock(driver);
2135
    return dom;
D
Daniel P. Berrange 已提交
2136 2137 2138
}


2139
static int qemudDomainSuspend(virDomainPtr dom) {
2140
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
2141
    char *info;
2142 2143
    virDomainObjPtr vm;
    int ret = -1;
2144
    virDomainEventPtr event = NULL;
2145

2146
    qemuDriverLock(driver);
2147
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2148

D
Daniel P. Berrange 已提交
2149
    if (!vm) {
2150 2151 2152 2153
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2154
        goto cleanup;
D
Daniel P. Berrange 已提交
2155
    }
2156
    if (!virDomainIsActive(vm)) {
2157
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
2158
                         "%s", _("domain is not running"));
2159
        goto cleanup;
D
Daniel P. Berrange 已提交
2160
    }
2161
    if (vm->state != VIR_DOMAIN_PAUSED) {
2162
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
2163 2164 2165 2166 2167 2168
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("suspend operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
2169 2170 2171
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
2172
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
2173
    }
2174
    if (virDomainSaveStatus(dom->conn, driver->stateDir, vm) < 0)
2175
        goto cleanup;
2176 2177 2178
    ret = 0;

cleanup:
2179 2180
    if (vm)
        virDomainObjUnlock(vm);
2181

2182
    if (event)
2183
        qemuDomainEventQueue(driver, event);
2184
    qemuDriverUnlock(driver);
2185
    return ret;
D
Daniel P. Berrange 已提交
2186 2187 2188
}


2189
static int qemudDomainResume(virDomainPtr dom) {
2190
    struct qemud_driver *driver = dom->conn->privateData;
D
Daniel P. Berrange 已提交
2191
    char *info;
2192 2193
    virDomainObjPtr vm;
    int ret = -1;
2194
    virDomainEventPtr event = NULL;
2195

2196
    qemuDriverLock(driver);
2197
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2198

D
Daniel P. Berrange 已提交
2199
    if (!vm) {
2200 2201 2202 2203
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2204
        goto cleanup;
D
Daniel P. Berrange 已提交
2205
    }
2206
    if (!virDomainIsActive(vm)) {
2207
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
2208
                         "%s", _("domain is not running"));
2209
        goto cleanup;
D
Daniel P. Berrange 已提交
2210
    }
2211
    if (vm->state == VIR_DOMAIN_PAUSED) {
2212
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
2213 2214 2215 2216 2217 2218
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("resume operation failed"));
            goto cleanup;
        }
        vm->state = VIR_DOMAIN_RUNNING;
        qemudDebug("Reply %s", info);
2219 2220 2221
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
2222
        VIR_FREE(info);
D
Daniel P. Berrange 已提交
2223
    }
2224
    if (virDomainSaveStatus(dom->conn, driver->stateDir, vm) < 0)
2225
        goto cleanup;
2226 2227 2228
    ret = 0;

cleanup:
2229 2230
    if (vm)
        virDomainObjUnlock(vm);
2231
    if (event)
2232
        qemuDomainEventQueue(driver, event);
2233
    qemuDriverUnlock(driver);
2234
    return ret;
D
Daniel P. Berrange 已提交
2235 2236 2237
}


2238
static int qemudDomainShutdown(virDomainPtr dom) {
2239 2240
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2241
    char* info;
2242
    int ret = -1;
2243

2244
    qemuDriverLock(driver);
2245
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2246 2247
    qemuDriverUnlock(driver);

2248
    if (!vm) {
2249 2250 2251 2252
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2253
        goto cleanup;
2254 2255
    }

2256
    if (qemudMonitorCommand(vm, "system_powerdown", &info) < 0) {
2257
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2258
                         "%s", _("shutdown operation failed"));
2259
        goto cleanup;
2260
    }
D
Daniel Veillard 已提交
2261
    VIR_FREE(info);
2262 2263 2264
    ret = 0;

cleanup:
2265 2266
    if (vm)
        virDomainObjUnlock(vm);
2267
    return ret;
2268 2269 2270
}


2271
static int qemudDomainDestroy(virDomainPtr dom) {
2272 2273 2274
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2275
    virDomainEventPtr event = NULL;
2276

2277
    qemuDriverLock(driver);
2278
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel P. Berrange 已提交
2279
    if (!vm) {
2280 2281 2282 2283
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2284
        goto cleanup;
D
Daniel P. Berrange 已提交
2285
    }
2286 2287 2288 2289 2290
    if (!virDomainIsActive(vm)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("domain is not running"));
        goto cleanup;
    }
2291

2292
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2293 2294 2295
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
2296
    if (!vm->persistent) {
2297 2298
        virDomainRemoveInactive(&driver->domains,
                                vm);
2299 2300
        vm = NULL;
    }
2301 2302 2303
    ret = 0;

cleanup:
2304 2305
    if (vm)
        virDomainObjUnlock(vm);
2306 2307
    if (event)
        qemuDomainEventQueue(driver, event);
2308
    qemuDriverUnlock(driver);
2309
    return ret;
D
Daniel P. Berrange 已提交
2310 2311 2312
}


2313
static char *qemudDomainGetOSType(virDomainPtr dom) {
2314 2315 2316
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *type = NULL;
2317

2318
    qemuDriverLock(driver);
2319
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2320
    qemuDriverUnlock(driver);
2321
    if (!vm) {
2322 2323 2324 2325
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2326
        goto cleanup;
2327 2328
    }

2329
    if (!(type = strdup(vm->def->os.type)))
2330
        virReportOOMError(dom->conn);
2331 2332

cleanup:
2333 2334
    if (vm)
        virDomainObjUnlock(vm);
2335 2336 2337
    return type;
}

2338 2339
/* Returns max memory in kb, 0 if error */
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
2340 2341 2342
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    unsigned long ret = 0;
2343

2344
    qemuDriverLock(driver);
2345
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2346 2347
    qemuDriverUnlock(driver);

2348
    if (!vm) {
2349 2350
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2351
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
2352
                         _("no domain with matching uuid '%s'"), uuidstr);
2353
        goto cleanup;
2354 2355
    }

2356 2357 2358
    ret = vm->def->maxmem;

cleanup:
2359 2360
    if (vm)
        virDomainObjUnlock(vm);
2361
    return ret;
2362 2363 2364
}

static int qemudDomainSetMaxMemory(virDomainPtr dom, unsigned long newmax) {
2365 2366 2367
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2368

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

2373
    if (!vm) {
2374 2375
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2376
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
2377
                         _("no domain with matching uuid '%s'"), uuidstr);
2378
        goto cleanup;
2379 2380 2381 2382
    }

    if (newmax < vm->def->memory) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2383
                         "%s", _("cannot set max memory lower than current memory"));
2384
        goto cleanup;;
2385 2386 2387
    }

    vm->def->maxmem = newmax;
2388 2389 2390
    ret = 0;

cleanup:
2391 2392
    if (vm)
        virDomainObjUnlock(vm);
2393
    return ret;
2394 2395
}

2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410

/* The reply from QEMU contains 'ballon: actual=421' where value is in MB */
#define BALLOON_PREFIX "balloon: actual="

/*
 * Returns: 0 if balloon not supported, +1 if balloon query worked
 * or -1 on failure
 */
static int qemudDomainGetMemoryBalloon(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       unsigned long *currmem) {
    char *reply = NULL;
    int ret = -1;
    char *offset;

2411 2412 2413
    if (!virDomainIsActive(vm))
        return 0;

2414 2415 2416 2417 2418 2419
    if (qemudMonitorCommand(vm, "info balloon", &reply) < 0) {
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("could not query memory balloon allocation"));
        goto cleanup;
    }

2420
    DEBUG ("%s: balloon reply: '%s'", vm->def->name, reply);
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 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
    if ((offset = strstr(reply, BALLOON_PREFIX)) != NULL) {
        unsigned int memMB;
        char *end;
        offset += strlen(BALLOON_PREFIX);
        if (virStrToLong_ui(offset, &end, 10, &memMB) < 0) {
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("could not parse memory balloon allocation"));
            goto cleanup;
        }
        *currmem = memMB * 1024;
        ret = 1;
    } else {
        /* We don't raise an error here, since its to be expected that
         * many QEMU's don't support ballooning
         */
        ret = 0;
    }

cleanup:
    VIR_FREE(reply);
    return ret;
}

/*
 * Returns: 0 if balloon not supported, +1 if balloon query worked
 * or -1 on failure
 */
static int qemudDomainSetMemoryBalloon(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       unsigned long newmem) {
    char *cmd;
    char *reply = NULL;
    int ret = -1;

    /*
     * 'newmem' is in KB, QEMU monitor works in MB, and we all wish
     * we just worked in bytes with unsigned long long everywhere.
     */
    if (virAsprintf(&cmd, "balloon %lu", (newmem / 1024)) < 0) {
        virReportOOMError(conn);
        goto cleanup;
    }

    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                         "%s", _("could not balloon memory allocation"));
        VIR_FREE(cmd);
        goto cleanup;
    }
    VIR_FREE(cmd);

    /* If the command failed qemu prints: 'unknown command'
     * No message is printed on success it seems */
2474
    DEBUG ("%s: balloon reply: %s",vm->def->name,  reply);
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
    if (strstr(reply, "\nunknown command:")) {
        /* Don't set error - it is expected memory balloon fails on many qemu */
        ret = 0;
    } else {
        ret = 1;
    }

cleanup:
    VIR_FREE(reply);
    return ret;
}


2488
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
2489 2490 2491
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2492

2493
    qemuDriverLock(driver);
2494
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2495
    qemuDriverUnlock(driver);
2496
    if (!vm) {
2497 2498
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2499
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
2500
                         _("no domain with matching uuid '%s'"), uuidstr);
2501
        goto cleanup;
2502 2503 2504 2505
    }

    if (newmem > vm->def->maxmem) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
2506
                         "%s", _("cannot set memory higher than max memory"));
2507
        goto cleanup;
2508 2509
    }

2510 2511 2512 2513 2514 2515 2516 2517 2518
    if (virDomainIsActive(vm)) {
        ret = qemudDomainSetMemoryBalloon(dom->conn, vm, newmem);
        if (ret == 0)
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                             "%s", _("cannot set memory of an active domain"));
    } else {
        vm->def->memory = newmem;
        ret = 0;
    }
2519 2520

cleanup:
2521 2522
    if (vm)
        virDomainObjUnlock(vm);
2523
    return ret;
2524 2525
}

2526
static int qemudDomainGetInfo(virDomainPtr dom,
2527
                              virDomainInfoPtr info) {
2528 2529 2530
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
2531 2532
    int err;
    unsigned long balloon;
2533

2534
    qemuDriverLock(driver);
2535
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2536
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
2537
    if (!vm) {
2538 2539 2540 2541
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2542
        goto cleanup;
D
Daniel P. Berrange 已提交
2543 2544
    }

2545
    info->state = vm->state;
D
Daniel P. Berrange 已提交
2546

2547
    if (!virDomainIsActive(vm)) {
2548
        info->cpuTime = 0;
D
Daniel P. Berrange 已提交
2549
    } else {
2550
        if (qemudGetProcessInfo(&(info->cpuTime), vm->pid) < 0) {
2551
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED, ("cannot read cputime for domain"));
2552
            goto cleanup;
D
Daniel P. Berrange 已提交
2553 2554 2555
        }
    }

2556 2557 2558 2559
    err = qemudDomainGetMemoryBalloon(dom->conn, vm, &balloon);
    if (err < 0)
        goto cleanup;

2560
    info->maxMem = vm->def->maxmem;
2561 2562 2563 2564 2565
    if (err == 0)
        /* Balloon not supported, so maxmem is always the allocation */
        info->memory = vm->def->maxmem;
    else
        info->memory = balloon;
2566
    info->nrVirtCpu = vm->def->vcpus;
2567 2568 2569
    ret = 0;

cleanup:
2570 2571
    if (vm)
        virDomainObjUnlock(vm);
2572
    return ret;
D
Daniel P. Berrange 已提交
2573 2574 2575
}


D
Daniel P. Berrange 已提交
2576
static char *qemudEscape(const char *in, int shell)
2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597
{
    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 已提交
2598 2599 2600 2601
            if (shell)
                len += 5;
            else
                len += 1;
2602 2603 2604 2605 2606 2607 2608
            break;
        default:
            len += 1;
            break;
        }
    }

2609
    if (VIR_ALLOC_N(out, len + 1) < 0)
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627
        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 已提交
2628 2629 2630 2631 2632 2633 2634 2635 2636
            if (shell) {
                out[j++] = '\'';
                out[j++] = '\\';
                out[j++] = '\\';
                out[j++] = '\'';
                out[j++] = '\'';
            } else {
                out[j++] = in[i];
            }
2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
            break;
        default:
            out[j++] = in[i];
            break;
        }
    }
    out[j] = '\0';

    return out;
}

2648 2649 2650 2651 2652
static char *qemudEscapeMonitorArg(const char *in)
{
    return qemudEscape(in, 0);
}

D
Daniel P. Berrange 已提交
2653 2654 2655 2656
static char *qemudEscapeShellArg(const char *in)
{
    return qemudEscape(in, 1);
}
2657

2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668
#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];
};

2669
static int qemudDomainSave(virDomainPtr dom,
2670
                           const char *path) {
2671 2672 2673 2674 2675 2676 2677
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *command = NULL;
    char *info = NULL;
    int fd = -1;
    char *safe_path = NULL;
    char *xml = NULL;
2678
    struct qemud_save_header header;
2679
    int ret = -1;
2680
    virDomainEventPtr event = NULL;
2681 2682 2683 2684 2685

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

2686
    qemuDriverLock(driver);
2687
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2688

D
Daniel P. Berrange 已提交
2689
    if (!vm) {
2690 2691 2692 2693
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
2694
        goto cleanup;
D
Daniel P. Berrange 已提交
2695
    }
2696

2697
    if (!virDomainIsActive(vm)) {
2698
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
2699
                         "%s", _("domain is not running"));
2700
        goto cleanup;
D
Daniel P. Berrange 已提交
2701
    }
2702 2703 2704 2705

    /* Pause */
    if (vm->state == VIR_DOMAIN_RUNNING) {
        header.was_running = 1;
2706
        if (qemudMonitorCommand(vm, "stop", &info) < 0) {
2707
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2708
                             "%s", _("suspend operation failed"));
2709
            goto cleanup;
2710
        }
2711 2712 2713
        vm->state = VIR_DOMAIN_PAUSED;
        qemudDebug("Reply %s", info);
        VIR_FREE(info);
2714 2715 2716
    }

    /* Get XML for the domain */
2717
    xml = virDomainDefFormat(dom->conn, vm->def, VIR_DOMAIN_XML_SECURE);
2718 2719
    if (!xml) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2720
                         "%s", _("failed to get domain xml"));
2721
        goto cleanup;
2722 2723 2724 2725 2726 2727
    }
    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,
2728
                         _("failed to create '%s'"), path);
2729
        goto cleanup;
2730 2731 2732 2733
    }

    if (safewrite(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2734
                         "%s", _("failed to write save header"));
2735
        goto cleanup;
2736 2737 2738 2739
    }

    if (safewrite(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2740
                         "%s", _("failed to write xml"));
2741
        goto cleanup;
2742 2743
    }

2744
    if (close(fd) < 0) {
2745 2746 2747
        virReportSystemError(dom->conn, errno,
                             _("unable to save file %s"),
                             path);
2748 2749 2750
        goto cleanup;
    }
    fd = -1;
2751 2752 2753 2754

    /* Migrate to file */
    safe_path = qemudEscapeShellArg(path);
    if (!safe_path) {
2755
        virReportOOMError(dom->conn);
2756
        goto cleanup;
2757
    }
2758
    if (virAsprintf(&command, "migrate \"exec:"
2759
                  "dd of='%s' oflag=append conv=notrunc 2>/dev/null"
2760
                  "\"", safe_path) == -1) {
2761
        virReportOOMError(dom->conn);
2762 2763
        command = NULL;
        goto cleanup;
2764 2765
    }

2766
    if (qemudMonitorCommand(vm, command, &info) < 0) {
2767
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
2768
                         "%s", _("migrate operation failed"));
2769
        goto cleanup;
2770 2771
    }

2772
    DEBUG ("%s: migrate reply: %s", vm->def->name, info);
2773 2774 2775 2776 2777 2778 2779

    /* 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"));
2780
        goto cleanup;
2781 2782
    }

2783 2784
    /* Shut it down */
    qemudShutdownVMDaemon(dom->conn, driver, vm);
2785 2786 2787
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
2788
    if (!vm->persistent) {
2789 2790
        virDomainRemoveInactive(&driver->domains,
                                vm);
2791 2792
        vm = NULL;
    }
2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
    ret = 0;

cleanup:
    if (fd != -1)
        close(fd);
    VIR_FREE(xml);
    VIR_FREE(safe_path);
    VIR_FREE(command);
    VIR_FREE(info);
    if (ret != 0)
        unlink(path);
2804 2805
    if (vm)
        virDomainObjUnlock(vm);
2806 2807
    if (event)
        qemuDomainEventQueue(driver, event);
2808
    qemuDriverUnlock(driver);
2809
    return ret;
D
Daniel P. Berrange 已提交
2810 2811 2812
}


2813
static int qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus) {
2814 2815
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2816
    int max;
2817
    int ret = -1;
2818
    const char *type;
2819

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

2824
    if (!vm) {
2825 2826
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
2827
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
2828
                         _("no domain with matching uuid '%s'"), uuidstr);
2829
        goto cleanup;
2830 2831
    }

2832
    if (virDomainIsActive(vm)) {
2833
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID, "%s",
2834
                         _("cannot change vcpu count of an active domain"));
2835
        goto cleanup;
2836 2837
    }

2838 2839 2840 2841 2842 2843 2844 2845
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
        goto cleanup;
    }

    if ((max = qemudGetMaxVCPUs(dom->conn, type)) < 0) {
2846 2847
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR, "%s",
                         _("could not determine max vcpus for the domain"));
2848
        goto cleanup;
2849 2850 2851 2852 2853 2854
    }

    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);
2855
        goto cleanup;
2856 2857 2858
    }

    vm->def->vcpus = nvcpus;
2859 2860 2861
    ret = 0;

cleanup:
2862 2863
    if (vm)
        virDomainObjUnlock(vm);
2864
    return ret;
2865 2866
}

2867 2868 2869 2870 2871 2872 2873

#if HAVE_SCHED_GETAFFINITY
static int
qemudDomainPinVcpu(virDomainPtr dom,
                   unsigned int vcpu,
                   unsigned char *cpumap,
                   int maplen) {
2874 2875
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2876 2877 2878
    cpu_set_t mask;
    int i, maxcpu;
    virNodeInfo nodeinfo;
2879
    int ret = -1;
2880

2881
    qemuDriverLock(driver);
2882
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2883 2884
    qemuDriverUnlock(driver);

2885 2886 2887 2888 2889 2890 2891 2892
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

2893
    if (!virDomainIsActive(vm)) {
2894
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
2895
                         "%s",_("cannot pin vcpus on an inactive domain"));
2896
        goto cleanup;
2897 2898 2899 2900 2901 2902
    }

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

2906
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
2907
        goto cleanup;
2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920

    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) {
2921 2922
            virReportSystemError(dom->conn, errno, "%s",
                                 _("cannot set affinity"));
2923
            goto cleanup;
2924 2925 2926 2927
        }
    } else {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("cpu affinity is not supported"));
2928
        goto cleanup;
2929
    }
2930
    ret = 0;
2931

2932
cleanup:
2933 2934
    if (vm)
        virDomainObjUnlock(vm);
2935
    return ret;
2936 2937 2938 2939 2940 2941 2942 2943
}

static int
qemudDomainGetVcpus(virDomainPtr dom,
                    virVcpuInfoPtr info,
                    int maxinfo,
                    unsigned char *cpumaps,
                    int maplen) {
2944 2945
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
2946 2947
    virNodeInfo nodeinfo;
    int i, v, maxcpu;
2948
    int ret = -1;
2949

2950
    qemuDriverLock(driver);
2951
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
2952 2953
    qemuDriverUnlock(driver);

2954 2955 2956 2957 2958 2959 2960 2961
    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

2962
    if (!virDomainIsActive(vm)) {
2963
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
2964
                         "%s",_("cannot pin vcpus on an inactive domain"));
2965
        goto cleanup;
2966 2967
    }

2968
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
2969
        goto cleanup;
2970 2971 2972 2973 2974 2975 2976 2977 2978

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

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

2979 2980 2981 2982 2983 2984 2985 2986
    if (maxinfo >= 1) {
        if (info != NULL) {
            memset(info, 0, sizeof(*info) * maxinfo);
            for (i = 0 ; i < maxinfo ; i++) {
                info[i].number = i;
                info[i].state = VIR_VCPU_RUNNING;
                /* XXX cpu time, current pCPU mapping */
            }
2987 2988
        }

2989 2990 2991 2992 2993 2994 2995 2996 2997
        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) {
2998 2999
                        virReportSystemError(dom->conn, errno, "%s",
                                             _("cannot get affinity"));
3000 3001 3002 3003 3004 3005
                        goto cleanup;
                    }

                    for (i = 0 ; i < maxcpu ; i++)
                        if (CPU_ISSET(i, &mask))
                            VIR_USE_CPU(cpumap, i);
3006
                }
3007 3008 3009 3010
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 "%s", _("cpu affinity is not available"));
                goto cleanup;
3011 3012 3013
            }
        }
    }
3014
    ret = maxinfo;
3015

3016
cleanup:
3017 3018
    if (vm)
        virDomainObjUnlock(vm);
3019
    return ret;
3020 3021 3022 3023
}
#endif /* HAVE_SCHED_GETAFFINITY */


3024
static int qemudDomainGetMaxVcpus(virDomainPtr dom) {
3025 3026
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3027
    const char *type;
3028
    int ret = -1;
3029

3030
    qemuDriverLock(driver);
3031
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3032 3033
    qemuDriverUnlock(driver);

3034
    if (!vm) {
3035 3036
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3037
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
3038
                         _("no domain with matching uuid '%s'"), uuidstr);
3039
        goto cleanup;
3040 3041
    }

3042
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
3043 3044 3045
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("unknown virt type in domain definition '%d'"),
                         vm->def->virtType);
3046
        goto cleanup;
3047 3048
    }

3049
    ret = qemudGetMaxVCPUs(dom->conn, type);
3050

3051
cleanup:
3052 3053
    if (vm)
        virDomainObjUnlock(vm);
3054 3055 3056
    return ret;
}

3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
static int qemudDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
{
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
    virDomainObjPtr vm;
    const char *type;
    int ret = -1;

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

    if (!vm) {
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
3070
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
                         _("no domain with matching uuid '%s'"), uuidstr);
        goto cleanup;
    }

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

    /*
     * Theoretically, the pid can be replaced during this operation and
     * return the label of a different process.  If atomicity is needed,
     * further validation will be required.
     *
     * Comment from Dan Berrange:
     *
     *   Well the PID as stored in the virDomainObjPtr can't be changed
     *   because you've got a locked object.  The OS level PID could have
     *   exited, though and in extreme circumstances have cycled through all
     *   PIDs back to ours. We could sanity check that our PID still exists
     *   after reading the label, by checking that our FD connecting to the
     *   QEMU monitor hasn't seen SIGHUP/ERR on poll().
     */
    if (virDomainIsActive(vm)) {
        if (driver->securityDriver && driver->securityDriver->domainGetSecurityLabel) {
            if (driver->securityDriver->domainGetSecurityLabel(dom->conn, vm, seclabel) == -1) {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                                 _("Failed to get security label"));
                goto cleanup;
            }
        }
    }

    ret = 0;

cleanup:
    if (vm)
        virDomainObjUnlock(vm);
3111
    qemuDriverUnlock(driver);
3112 3113 3114
    return ret;
}

3115 3116
static int qemudNodeGetSecurityModel(virConnectPtr conn,
                                     virSecurityModelPtr secmodel)
3117 3118 3119
{
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
    char *p;
3120
    int ret = 0;
3121

3122 3123 3124 3125 3126
    qemuDriverLock(driver);
    if (!driver->securityDriver) {
        ret = -2;
        goto cleanup;
    }
3127

3128 3129 3130 3131 3132
    p = driver->caps->host.secModel.model;
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("security model string exceeds max %d bytes"),
                         VIR_SECURITY_MODEL_BUFLEN-1);
3133 3134
        ret = -1;
        goto cleanup;
3135 3136 3137 3138 3139 3140 3141 3142
    }
    strcpy(secmodel->model, p);

    p = driver->caps->host.secModel.doi;
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("security DOI string exceeds max %d bytes"),
                         VIR_SECURITY_DOI_BUFLEN-1);
3143 3144
        ret = -1;
        goto cleanup;
3145 3146
    }
    strcpy(secmodel->doi, p);
3147 3148 3149 3150

cleanup:
    qemuDriverUnlock(driver);
    return ret;
3151 3152 3153
}

/* TODO: check seclabel restore */
3154
static int qemudDomainRestore(virConnectPtr conn,
3155 3156 3157
                              const char *path) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
3158
    virDomainObjPtr vm = NULL;
3159 3160 3161
    int fd = -1;
    int ret = -1;
    char *xml = NULL;
3162
    struct qemud_save_header header;
3163
    virDomainEventPtr event = NULL;
3164

3165
    qemuDriverLock(driver);
3166 3167 3168
    /* Verify the header and read the XML */
    if ((fd = open(path, O_RDONLY)) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3169
                         "%s", _("cannot read domain image"));
3170
        goto cleanup;
3171 3172 3173 3174
    }

    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3175
                         "%s", _("failed to read qemu header"));
3176
        goto cleanup;
3177 3178 3179 3180
    }

    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3181
                         "%s", _("image magic is incorrect"));
3182
        goto cleanup;
3183 3184 3185 3186
    }

    if (header.version > QEMUD_SAVE_VERSION) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3187
                         _("image version is not supported (%d > %d)"),
3188
                         header.version, QEMUD_SAVE_VERSION);
3189
        goto cleanup;
3190 3191
    }

3192
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
3193
        virReportOOMError(conn);
3194
        goto cleanup;
3195 3196 3197 3198
    }

    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3199
                         "%s", _("failed to read XML"));
3200
        goto cleanup;
3201 3202 3203
    }

    /* Create a domain from this XML */
3204 3205
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
3206
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3207
                         "%s", _("failed to parse XML"));
3208
        goto cleanup;
3209 3210
    }

3211
    /* See if a VM with matching UUID already exists */
3212
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
3213
    if (vm) {
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain '%s' is already defined with uuid %s"),
                             vm->def->name, uuidstr);
            goto cleanup;
        }

        /* UUID & name match, but if VM is already active, refuse it */
3225
        if (virDomainIsActive(vm)) {
3226
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_INVALID,
3227 3228
                             _("domain is already active as '%s'"), vm->def->name);
            goto cleanup;
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240
        }
        virDomainObjUnlock(vm);
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        vm = virDomainFindByName(&driver->domains, def->name);
        if (vm) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain '%s' is already defined with uuid %s"),
                             def->name, uuidstr);
            goto cleanup;
3241
        }
3242 3243
    }

3244 3245 3246
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
3247
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3248
                         "%s", _("failed to assign new VM"));
3249
        goto cleanup;
3250
    }
3251
    def = NULL;
3252 3253

    /* Set the migration source and start it up. */
3254
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio", fd);
3255
    close(fd);
3256
    fd = -1;
3257
    if (ret < 0) {
3258
        if (!vm->persistent) {
3259 3260
            virDomainRemoveInactive(&driver->domains,
                                    vm);
3261 3262
            vm = NULL;
        }
3263
        goto cleanup;
3264 3265
    }

3266 3267 3268
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STARTED,
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
3269

3270 3271 3272
    /* If it was running before, resume it now. */
    if (header.was_running) {
        char *info;
3273
        if (qemudMonitorCommand(vm, "cont", &info) < 0) {
3274
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
3275
                             "%s", _("failed to resume domain"));
3276
            goto cleanup;
3277
        }
3278
        VIR_FREE(info);
3279 3280
        vm->state = VIR_DOMAIN_RUNNING;
    }
3281
    ret = 0;
3282

3283 3284 3285 3286 3287
cleanup:
    virDomainDefFree(def);
    VIR_FREE(xml);
    if (fd != -1)
        close(fd);
3288 3289
    if (vm)
        virDomainObjUnlock(vm);
3290 3291
    if (event)
        qemuDomainEventQueue(driver, event);
3292
    qemuDriverUnlock(driver);
3293
    return ret;
D
Daniel P. Berrange 已提交
3294 3295 3296
}


3297
static char *qemudDomainDumpXML(virDomainPtr dom,
3298
                                int flags) {
3299 3300 3301
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char *ret = NULL;
3302 3303
    unsigned long balloon;
    int err;
3304

3305
    qemuDriverLock(driver);
3306
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3307 3308
    qemuDriverUnlock(driver);

D
Daniel P. Berrange 已提交
3309
    if (!vm) {
3310 3311 3312 3313
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
3314
        goto cleanup;
D
Daniel P. Berrange 已提交
3315 3316
    }

3317 3318 3319 3320 3321 3322 3323
    /* Refresh current memory based on balloon info */
    err = qemudDomainGetMemoryBalloon(dom->conn, vm, &balloon);
    if (err < 0)
        goto cleanup;
    if (err > 0)
        vm->def->memory = balloon;

3324 3325 3326 3327 3328 3329
    ret = virDomainDefFormat(dom->conn,
                             (flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef ?
                             vm->newDef : vm->def,
                             flags);

cleanup:
3330 3331
    if (vm)
        virDomainObjUnlock(vm);
3332
    return ret;
D
Daniel P. Berrange 已提交
3333 3334 3335
}


3336 3337 3338 3339
static char *qemuDomainXMLFromNative(virConnectPtr conn,
                                     const char *format,
                                     const char *config,
                                     unsigned int flags ATTRIBUTE_UNUSED) {
3340
    struct qemud_driver *driver = conn->privateData;
3341 3342 3343 3344 3345 3346 3347 3348 3349
    virDomainDefPtr def = NULL;
    char *xml = NULL;

    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                         _("unsupported config type %s"), format);
        goto cleanup;
    }

3350
    def = qemuParseCommandLineString(conn, driver->caps, config);
3351 3352 3353 3354 3355 3356 3357 3358 3359 3360
    if (!def)
        goto cleanup;

    xml = virDomainDefFormat(conn, def, VIR_DOMAIN_XML_INACTIVE);

cleanup:
    virDomainDefFree(def);
    return xml;
}

3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376
static char *qemuDomainXMLToNative(virConnectPtr conn,
                                   const char *format,
                                   const char *xmlData,
                                   unsigned int flags ATTRIBUTE_UNUSED) {
    struct qemud_driver *driver = conn->privateData;
    virDomainDefPtr def = NULL;
    const char *emulator;
    unsigned int qemuCmdFlags;
    struct stat sb;
    const char **retargv = NULL;
    const char **retenv = NULL;
    const char **tmp;
    virBuffer buf = VIR_BUFFER_INITIALIZER;
    char *ret = NULL;
    int i;

3377 3378
    qemuDriverLock(driver);

3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                         _("unsupported config type %s"), format);
        goto cleanup;
    }

    def = virDomainDefParseString(conn, driver->caps, xmlData, 0);
    if (!def)
        goto cleanup;

    /* Since we're just exporting args, we can't do bridge/network
     * setups, since libvirt will normally create TAP devices
     * directly. We convert those configs into generic 'ethernet'
     * config and assume the user has suitable 'ifup-qemu' scripts
     */
    for (i = 0 ; i < def->nnets ; i++) {
        virDomainNetDefPtr net = def->nets[i];
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK) {
            VIR_FREE(net->data.network.name);

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = NULL;
            net->data.ethernet.script = NULL;
            net->data.ethernet.ipaddr = NULL;
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
            char *brname = net->data.bridge.brname;
            char *script = net->data.bridge.script;
            char *ipaddr = net->data.bridge.ipaddr;

            memset(net, 0, sizeof *net);

            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
            net->data.ethernet.dev = brname;
            net->data.ethernet.script = script;
            net->data.ethernet.ipaddr = ipaddr;
        }
    }
    for (i = 0 ; i < def->ngraphics ; i++) {
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
            def->graphics[i]->data.vnc.autoport)
            def->graphics[i]->data.vnc.port = 5900;
    }
    emulator = def->emulator;

    /* 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
     */
    if (stat(emulator, &sb) < 0) {
        virReportSystemError(conn, errno,
                             _("Cannot find QEMU binary %s"),
                             emulator);
        goto cleanup;
    }

    if (qemudExtractVersionInfo(emulator,
                                NULL,
                                &qemuCmdFlags) < 0) {
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                         _("Cannot determine QEMU argv syntax %s"),
                         emulator);
        goto cleanup;
    }


    if (qemudBuildCommandLine(conn, driver, def,
                              qemuCmdFlags,
                              &retargv, &retenv,
                              NULL, NULL, /* Don't want it to create TAP devices */
                              NULL) < 0) {
        goto cleanup;
    }

    tmp = retenv;
    while (*tmp) {
        virBufferAdd(&buf, *tmp, strlen(*tmp));
        virBufferAddLit(&buf, " ");
        tmp++;
    }
    tmp = retargv;
    while (*tmp) {
        virBufferAdd(&buf, *tmp, strlen(*tmp));
        virBufferAddLit(&buf, " ");
        tmp++;
    }

    if (virBufferError(&buf))
        goto cleanup;

    ret = virBufferContentAndReset(&buf);

cleanup:
3473
    qemuDriverUnlock(driver);
3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486
    for (tmp = retargv ; tmp && *tmp ; tmp++)
        VIR_FREE(*tmp);
    VIR_FREE(retargv);

    for (tmp = retenv ; tmp && *tmp ; tmp++)
        VIR_FREE(*tmp);
    VIR_FREE(retenv);

    virDomainDefFree(def);
    return ret;
}


3487
static int qemudListDefinedDomains(virConnectPtr conn,
3488
                            char **const names, int nnames) {
3489
    struct qemud_driver *driver = conn->privateData;
3490
    int got = 0, i;
3491

3492
    qemuDriverLock(driver);
3493
    for (i = 0 ; i < driver->domains.count && got < nnames ; i++) {
3494
        virDomainObjLock(driver->domains.objs[i]);
3495 3496
        if (!virDomainIsActive(driver->domains.objs[i])) {
            if (!(names[got++] = strdup(driver->domains.objs[i]->def->name))) {
3497
                virReportOOMError(conn);
3498
                virDomainObjUnlock(driver->domains.objs[i]);
3499 3500
                goto cleanup;
            }
3501
        }
3502
        virDomainObjUnlock(driver->domains.objs[i]);
D
Daniel P. Berrange 已提交
3503
    }
3504

3505
    qemuDriverUnlock(driver);
D
Daniel P. Berrange 已提交
3506
    return got;
3507 3508 3509

 cleanup:
    for (i = 0 ; i < got ; i++)
3510
        VIR_FREE(names[i]);
3511
    qemuDriverUnlock(driver);
3512
    return -1;
D
Daniel P. Berrange 已提交
3513 3514
}

3515
static int qemudNumDefinedDomains(virConnectPtr conn) {
3516
    struct qemud_driver *driver = conn->privateData;
3517 3518
    int n = 0, i;

3519
    qemuDriverLock(driver);
3520 3521
    for (i = 0 ; i < driver->domains.count ; i++)
        if (!virDomainIsActive(driver->domains.objs[i]))
3522
            n++;
3523
    qemuDriverUnlock(driver);
3524

3525
    return n;
D
Daniel P. Berrange 已提交
3526 3527 3528
}


3529
static int qemudDomainStart(virDomainPtr dom) {
3530 3531 3532
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
3533
    virDomainEventPtr event = NULL;
3534

3535
    qemuDriverLock(driver);
3536
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3537

3538
    if (!vm) {
3539 3540 3541 3542
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
3543
        goto cleanup;
3544 3545
    }

3546
    ret = qemudStartVMDaemon(dom->conn, driver, vm, NULL, -1);
3547
    if (ret != -1)
3548 3549 3550
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STARTED,
                                         VIR_DOMAIN_EVENT_STARTED_BOOTED);
3551 3552

cleanup:
3553 3554
    if (vm)
        virDomainObjUnlock(vm);
3555
    if (event)
3556
        qemuDomainEventQueue(driver, event);
3557
    qemuDriverUnlock(driver);
3558
    return ret;
D
Daniel P. Berrange 已提交
3559 3560 3561
}


3562
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
3563
    struct qemud_driver *driver = conn->privateData;
3564
    virDomainDefPtr def;
3565
    virDomainObjPtr vm = NULL;
3566
    virDomainPtr dom = NULL;
3567
    virDomainEventPtr event = NULL;
3568
    int newVM = 1;
3569

3570
    qemuDriverLock(driver);
3571 3572
    if (!(def = virDomainDefParseString(conn, driver->caps, xml,
                                        VIR_DOMAIN_XML_INACTIVE)))
3573
        goto cleanup;
3574

3575 3576 3577
    if (virSecurityDriverVerify(conn, def) < 0)
        goto cleanup;

3578 3579
    /* See if a VM with matching UUID already exists */
    vm = virDomainFindByUUID(&driver->domains, def->uuid);
3580
    if (vm) {
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591
        /* UUID matches, but if names don't match, refuse it */
        if (STRNEQ(vm->def->name, def->name)) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain '%s' is already defined with uuid %s"),
                             vm->def->name, uuidstr);
            goto cleanup;
        }

        /* UUID & name match */
3592
        virDomainObjUnlock(vm);
3593
        newVM = 0;
3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
    } else {
        /* UUID does not match, but if a name matches, refuse it */
        vm = virDomainFindByName(&driver->domains, def->name);
        if (vm) {
            char uuidstr[VIR_UUID_STRING_BUFLEN];
            virUUIDFormat(vm->def->uuid, uuidstr);
            qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                             _("domain '%s' is already defined with uuid %s"),
                             def->name, uuidstr);
            goto cleanup;
        }
3605
    }
3606

3607 3608 3609
    if (!(vm = virDomainAssignDef(conn,
                                  &driver->domains,
                                  def))) {
3610
        goto cleanup;
3611
    }
3612
    def = NULL;
3613
    vm->persistent = 1;
3614

3615 3616
    if (virDomainSaveConfig(conn,
                            driver->configDir,
3617
                            vm->newDef ? vm->newDef : vm->def) < 0) {
3618 3619
        virDomainRemoveInactive(&driver->domains,
                                vm);
3620
        vm = NULL;
3621
        goto cleanup;
3622 3623
    }

3624 3625 3626 3627 3628
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_DEFINED,
                                     newVM ?
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
3629

3630
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3631
    if (dom) dom->id = vm->def->id;
3632 3633

cleanup:
3634
    virDomainDefFree(def);
3635 3636
    if (vm)
        virDomainObjUnlock(vm);
3637 3638
    if (event)
        qemuDomainEventQueue(driver, event);
3639
    qemuDriverUnlock(driver);
3640
    return dom;
D
Daniel P. Berrange 已提交
3641 3642
}

3643
static int qemudDomainUndefine(virDomainPtr dom) {
3644 3645
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
3646
    virDomainEventPtr event = NULL;
3647
    int ret = -1;
D
Daniel P. Berrange 已提交
3648

3649
    qemuDriverLock(driver);
3650
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3651

D
Daniel P. Berrange 已提交
3652
    if (!vm) {
3653 3654 3655 3656
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
3657
        goto cleanup;
D
Daniel P. Berrange 已提交
3658 3659
    }

3660
    if (virDomainIsActive(vm)) {
3661
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
3662
                         "%s", _("cannot delete active domain"));
3663
        goto cleanup;
D
Daniel P. Berrange 已提交
3664 3665
    }

3666 3667 3668
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot undefine transient domain"));
3669
        goto cleanup;
3670 3671 3672
    }

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

3675 3676 3677
    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_UNDEFINED,
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
3678

3679 3680
    virDomainRemoveInactive(&driver->domains,
                            vm);
3681
    vm = NULL;
3682
    ret = 0;
D
Daniel P. Berrange 已提交
3683

3684
cleanup:
3685 3686
    if (vm)
        virDomainObjUnlock(vm);
3687 3688
    if (event)
        qemuDomainEventQueue(driver, event);
3689
    qemuDriverUnlock(driver);
3690
    return ret;
D
Daniel P. Berrange 已提交
3691 3692
}

3693
/* Return the disks name for use in monitor commands */
3694
static char *qemudDiskDeviceName(const virConnectPtr conn,
3695
                                 const virDomainDiskDefPtr disk) {
3696 3697 3698 3699 3700 3701

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

    if (virDiskNameToBusDeviceIndex(disk, &busid, &devid) < 0) {
3702
        qemudReportError(conn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
3703 3704 3705 3706 3707 3708 3709
                         _("cannot convert disk '%s' to bus/device index"),
                         disk->dst);
        return NULL;
    }

    switch (disk->bus) {
        case VIR_DOMAIN_DISK_BUS_IDE:
3710
            if (disk->device== VIR_DOMAIN_DISK_DEVICE_DISK)
3711
                ret = virAsprintf(&devname, "ide%d-hd%d", busid, devid);
3712
            else
3713
                ret = virAsprintf(&devname, "ide%d-cd%d", busid, devid);
3714 3715
            break;
        case VIR_DOMAIN_DISK_BUS_SCSI:
3716
            if (disk->device == VIR_DOMAIN_DISK_DEVICE_DISK)
3717
                ret = virAsprintf(&devname, "scsi%d-hd%d", busid, devid);
3718
            else
3719
                ret = virAsprintf(&devname, "scsi%d-cd%d", busid, devid);
3720 3721
            break;
        case VIR_DOMAIN_DISK_BUS_FDC:
3722
            ret = virAsprintf(&devname, "floppy%d", devid);
3723 3724
            break;
        case VIR_DOMAIN_DISK_BUS_VIRTIO:
3725
            ret = virAsprintf(&devname, "virtio%d", devid);
3726 3727
            break;
        default:
3728
            qemudReportError(conn, NULL, NULL, VIR_ERR_NO_SUPPORT,
3729 3730 3731 3732 3733 3734
                             _("Unsupported disk name mapping for bus '%s'"),
                             virDomainDiskBusTypeToString(disk->bus));
            return NULL;
    }

    if (ret == -1) {
3735
        virReportOOMError(conn);
3736 3737 3738 3739 3740 3741
        return NULL;
    }

    return devname;
}

3742 3743
static int qemudDomainChangeEjectableMedia(virConnectPtr conn,
                                           virDomainObjPtr vm,
3744 3745
                                           virDomainDeviceDefPtr dev)
{
3746
    virDomainDiskDefPtr origdisk = NULL, newdisk;
3747
    char *cmd, *reply, *safe_path;
3748
    char *devname = NULL;
3749
    unsigned int qemuCmdFlags;
3750
    int i;
3751

3752
    origdisk = NULL;
3753
    newdisk = dev->data.disk;
3754 3755 3756 3757
    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];
3758
            break;
3759
        }
3760 3761 3762
    }

    if (!origdisk) {
3763
        qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3764 3765 3766 3767 3768 3769 3770 3771
                         _("No device with bus '%s' and target '%s'"),
                         virDomainDiskBusTypeToString(newdisk->bus),
                         newdisk->dst);
        return -1;
    }

    if (qemudExtractVersionInfo(vm->def->emulator,
                                NULL,
3772
                                &qemuCmdFlags) < 0)
3773 3774 3775
        return -1;

    if (qemuCmdFlags & QEMUD_CMD_FLAG_DRIVE) {
3776
        if (!(devname = qemudDiskDeviceName(conn, newdisk)))
3777 3778 3779 3780 3781 3782 3783 3784 3785
            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 {
3786
            qemudReportError(conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
3787 3788 3789 3790 3791 3792 3793 3794
                             _("Emulator version does not support removable "
                               "media for device '%s' and target '%s'"),
                               virDomainDiskDeviceTypeToString(newdisk->device),
                               newdisk->dst);
            return -1;
        }

        if (!devname) {
3795
            virReportOOMError(conn);
3796 3797 3798
            return -1;
        }
    }
3799

3800
    if (newdisk->src) {
3801 3802
        safe_path = qemudEscapeMonitorArg(newdisk->src);
        if (!safe_path) {
3803
            virReportOOMError(conn);
3804
            VIR_FREE(devname);
3805 3806
            return -1;
        }
3807
        if (virAsprintf(&cmd, "change %s \"%s\"", devname, safe_path) == -1) {
3808
            virReportOOMError(conn);
3809
            VIR_FREE(safe_path);
3810
            VIR_FREE(devname);
3811 3812
            return -1;
        }
3813
        VIR_FREE(safe_path);
3814

3815
    } else if (virAsprintf(&cmd, "eject %s", devname) == -1) {
3816
        virReportOOMError(conn);
3817
        VIR_FREE(devname);
3818 3819
        return -1;
    }
3820
    VIR_FREE(devname);
3821

3822
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3823
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3824
                         "%s", _("could not change cdrom media"));
3825
        VIR_FREE(cmd);
3826 3827
        return -1;
    }
3828 3829 3830 3831

    /* If the command failed qemu prints:
     * device not found, device is locked ...
     * No message is printed on success it seems */
3832
    DEBUG ("%s: ejectable media change reply: %s", vm->def->name, reply);
3833
    if (strstr(reply, "\ndevice ")) {
3834
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
C
Cole Robinson 已提交
3835
                          _("changing cdrom media failed: %s"), reply);
3836 3837 3838 3839
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3840 3841
    VIR_FREE(reply);
    VIR_FREE(cmd);
3842

3843 3844
    VIR_FREE(origdisk->src);
    origdisk->src = newdisk->src;
3845
    newdisk->src = NULL;
3846
    origdisk->type = newdisk->type;
3847 3848 3849
    return 0;
}

3850 3851 3852
static int qemudDomainAttachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm,
                                          virDomainDeviceDefPtr dev)
3853 3854
{
    int ret, i;
3855
    char *cmd, *reply, *s;
3856 3857 3858 3859 3860
    char *safe_path;
    const char* type = virDomainDiskBusTypeToString(dev->data.disk->bus);

    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3861
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3862 3863 3864 3865 3866 3867
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3868
        virReportOOMError(conn);
3869 3870 3871 3872 3873
        return -1;
    }

    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3874
        virReportOOMError(conn);
3875 3876 3877
        return -1;
    }

3878 3879
    ret = virAsprintf(&cmd, "pci_add 0 storage file=%s,if=%s",
                      safe_path, type);
3880 3881
    VIR_FREE(safe_path);
    if (ret == -1) {
3882
        virReportOOMError(conn);
3883 3884 3885
        return ret;
    }

3886
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3887
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3888 3889 3890 3891 3892
                         _("cannot attach %s disk"), type);
        VIR_FREE(cmd);
        return -1;
    }

3893
    DEBUG ("%s: pci_add reply: %s", vm->def->name, reply);
3894 3895
    /* If the command succeeds qemu prints:
     * OK bus 0... */
3896 3897 3898 3899 3900 3901
#define PCI_ATTACH_OK_MSG "OK bus 0, slot "
    if ((s=strstr(reply, PCI_ATTACH_OK_MSG))) {
        char* dummy = s;
        s += strlen(PCI_ATTACH_OK_MSG);

        if (virStrToLong_i ((const char*)s, &dummy, 10, &dev->data.disk->slotnum) == -1)
3902
            VIR_WARN("%s", _("Unable to parse slot number\n"));
3903
    } else {
3904
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
                          _("adding %s disk failed"), type);
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }

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

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

3920 3921 3922
static int qemudDomainAttachUsbMassstorageDevice(virConnectPtr conn,
                                                 virDomainObjPtr vm,
                                                 virDomainDeviceDefPtr dev)
3923
{
3924 3925
    int ret, i;
    char *safe_path;
3926 3927
    char *cmd, *reply;

3928 3929
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(vm->def->disks[i]->dst, dev->data.disk->dst)) {
3930
            qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3931 3932 3933 3934 3935
                           _("target %s already exists"), dev->data.disk->dst);
            return -1;
        }
    }

3936
    if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks+1) < 0) {
3937
        virReportOOMError(conn);
3938
        return -1;
3939 3940
    }

3941 3942
    safe_path = qemudEscapeMonitorArg(dev->data.disk->src);
    if (!safe_path) {
3943
        virReportOOMError(conn);
3944 3945 3946
        return -1;
    }

3947
    ret = virAsprintf(&cmd, "usb_add disk:%s", safe_path);
3948
    VIR_FREE(safe_path);
3949
    if (ret == -1) {
3950
        virReportOOMError(conn);
3951 3952 3953
        return ret;
    }

3954
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
3955
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3956
                         "%s", _("cannot attach usb disk"));
3957 3958 3959 3960
        VIR_FREE(cmd);
        return -1;
    }

3961
    DEBUG ("%s: attach_usb reply: %s",vm->def->name,  reply);
3962 3963 3964
    /* If the command failed qemu prints:
     * Could not add ... */
    if (strstr(reply, "Could not add ")) {
3965
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
3966
                          "%s",
3967
                          _("adding usb disk failed"));
3968 3969 3970 3971
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
3972

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

3977 3978 3979 3980 3981
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return 0;
}

3982 3983 3984
static int qemudDomainAttachHostDevice(virConnectPtr conn,
                                       virDomainObjPtr vm,
                                       virDomainDeviceDefPtr dev)
3985 3986 3987 3988
{
    int ret;
    char *cmd, *reply;

3989
    if (VIR_REALLOC_N(vm->def->hostdevs, vm->def->nhostdevs+1) < 0) {
3990
        virReportOOMError(conn);
3991 3992
        return -1;
    }
3993

3994
    if (dev->data.hostdev->source.subsys.u.usb.vendor) {
3995 3996 3997
        ret = virAsprintf(&cmd, "usb_add host:%.4x:%.4x",
                          dev->data.hostdev->source.subsys.u.usb.vendor,
                          dev->data.hostdev->source.subsys.u.usb.product);
3998
    } else {
3999 4000 4001
        ret = virAsprintf(&cmd, "usb_add host:%.3d.%.3d",
                          dev->data.hostdev->source.subsys.u.usb.bus,
                          dev->data.hostdev->source.subsys.u.usb.device);
4002 4003
    }
    if (ret == -1) {
4004
        virReportOOMError(conn);
4005 4006 4007
        return -1;
    }

4008
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
4009
        qemudReportError(conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
4010 4011 4012 4013 4014
                         "%s", _("cannot attach usb device"));
        VIR_FREE(cmd);
        return -1;
    }

4015
    DEBUG ("%s: attach_usb reply: %s", vm->def->name, reply);
4016 4017 4018
    /* If the command failed qemu prints:
     * Could not add ... */
    if (strstr(reply, "Could not add ")) {
4019
        qemudReportError (conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
4020 4021 4022 4023 4024 4025
                          "%s",
                          _("adding usb device failed"));
        VIR_FREE(reply);
        VIR_FREE(cmd);
        return -1;
    }
4026

4027
    vm->def->hostdevs[vm->def->nhostdevs++] = dev->data.hostdev;
4028

4029 4030
    VIR_FREE(reply);
    VIR_FREE(cmd);
4031 4032 4033
    return 0;
}

4034 4035
static int qemudDomainAttachDevice(virDomainPtr dom,
                                   const char *xml) {
4036 4037 4038 4039
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
4040

4041
    qemuDriverLock(driver);
4042
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4043
    if (!vm) {
4044 4045 4046 4047
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4048
        goto cleanup;
4049 4050 4051
    }

    if (!virDomainIsActive(vm)) {
4052
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
4053
                         "%s", _("cannot attach device on inactive domain"));
4054
        goto cleanup;
4055 4056
    }

4057 4058
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
4059 4060 4061
    if (dev == NULL)
        goto cleanup;

4062

4063 4064
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
        switch (dev->data.disk->device) {
4065 4066
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
4067
            ret = qemudDomainChangeEjectableMedia(dom->conn, vm, dev);
4068
            break;
4069

4070 4071
        case VIR_DOMAIN_DISK_DEVICE_DISK:
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
4072
                ret = qemudDomainAttachUsbMassstorageDevice(dom->conn, vm, dev);
4073 4074
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
                       dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
4075
                ret = qemudDomainAttachPciDiskDevice(dom->conn, vm, dev);
4076 4077 4078 4079 4080
            } else {
                qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                                 _("disk bus '%s' cannot be hotplugged."),
                                 virDomainDiskBusTypeToString(dev->data.disk->bus));
                goto cleanup;
4081
            }
4082
            if (driver->securityDriver)
4083
                driver->securityDriver->domainSetSecurityImageLabel(dom->conn, vm, dev->data.disk);
4084
            break;
4085

4086 4087
        default:
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
4088 4089
                             _("disk device type '%s' cannot be hotplugged"),
                             virDomainDiskDeviceTypeToString(dev->data.disk->device));
4090
            goto cleanup;
4091
        }
4092
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV &&
4093 4094
               dev->data.hostdev->mode == VIR_DOMAIN_HOSTDEV_MODE_SUBSYS &&
               dev->data.hostdev->source.subsys.type == VIR_DOMAIN_HOSTDEV_SUBSYS_TYPE_USB) {
4095
        ret = qemudDomainAttachHostDevice(dom->conn, vm, dev);
4096
    } else {
4097
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
4098 4099
                         _("device type '%s' cannot be attached"),
                         virDomainDeviceTypeToString(dev->type));
4100
        goto cleanup;
4101 4102
    }

4103
    if (!ret && virDomainSaveStatus(dom->conn, driver->stateDir, vm) < 0)
4104 4105
        ret = -1;

4106
cleanup:
G
Guido Günther 已提交
4107 4108
    if (ret < 0)
        virDomainDeviceDefFree(dev);
4109 4110
    if (vm)
        virDomainObjUnlock(vm);
4111
    qemuDriverUnlock(driver);
4112 4113 4114
    return ret;
}

4115 4116
static int qemudDomainDetachPciDiskDevice(virConnectPtr conn,
                                          virDomainObjPtr vm, virDomainDeviceDefPtr dev)
4117 4118
{
    int i, ret = -1;
4119 4120
    char *cmd = NULL;
    char *reply = NULL;
4121 4122 4123 4124 4125 4126 4127 4128 4129 4130
    virDomainDiskDefPtr detach = NULL;

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

    if (!detach) {
4131
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
4132
                         _("disk %s not found"), dev->data.disk->dst);
4133
        goto cleanup;
4134 4135 4136
    }

    if (detach->slotnum < 1) {
4137
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
4138
                         _("disk %s cannot be detached - invalid slot number %d"),
4139
                           detach->dst, detach->slotnum);
4140
        goto cleanup;
4141 4142
    }

4143
    if (virAsprintf(&cmd, "pci_del 0 %d", detach->slotnum) < 0) {
4144
        virReportOOMError(conn);
4145
        goto cleanup;
4146 4147
    }

4148
    if (qemudMonitorCommand(vm, cmd, &reply) < 0) {
4149
        qemudReportError(conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
4150
                          _("failed to execute detach disk %s command"), detach->dst);
4151
        goto cleanup;
4152 4153
    }

4154
    DEBUG ("%s: pci_del reply: %s",vm->def->name,  reply);
4155 4156 4157
    /* If the command fails due to a wrong slot qemu prints: invalid slot,
     * nothing is printed on success */
    if (strstr(reply, "invalid slot")) {
4158
        qemudReportError (conn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
4159
                          _("failed to detach disk %s: invalid slot %d"),
4160 4161
                          detach->dst, detach->slotnum);
        goto cleanup;
4162 4163 4164 4165 4166
    }

    if (vm->def->ndisks > 1) {
        vm->def->disks[i] = vm->def->disks[--vm->def->ndisks];
        if (VIR_REALLOC_N(vm->def->disks, vm->def->ndisks) < 0) {
4167
            virReportOOMError(conn);
4168
            goto cleanup;
4169 4170 4171 4172 4173 4174 4175 4176
        }
        qsort(vm->def->disks, vm->def->ndisks, sizeof(*vm->def->disks),
              virDomainDiskQSort);
    } else {
        VIR_FREE(vm->def->disks[0]);
        vm->def->ndisks = 0;
    }
    ret = 0;
4177 4178

cleanup:
4179 4180 4181 4182 4183 4184 4185
    VIR_FREE(reply);
    VIR_FREE(cmd);
    return ret;
}

static int qemudDomainDetachDevice(virDomainPtr dom,
                                   const char *xml) {
4186 4187 4188 4189
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    virDomainDeviceDefPtr dev = NULL;
    int ret = -1;
4190

4191
    qemuDriverLock(driver);
4192
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4193
    if (!vm) {
4194 4195 4196 4197
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4198
        goto cleanup;
4199 4200 4201
    }

    if (!virDomainIsActive(vm)) {
4202
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
G
Guido Günther 已提交
4203
                         "%s", _("cannot detach device on inactive domain"));
4204
        goto cleanup;
4205 4206
    }

4207 4208
    dev = virDomainDeviceDefParse(dom->conn, driver->caps, vm->def, xml,
                                  VIR_DOMAIN_XML_INACTIVE);
4209 4210 4211
    if (dev == NULL)
        goto cleanup;

4212 4213 4214 4215

    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
        (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI ||
4216
         dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO)) {
4217
        ret = qemudDomainDetachPciDiskDevice(dom->conn, vm, dev);
4218
        if (driver->securityDriver)
4219
            driver->securityDriver->domainRestoreSecurityImageLabel(dom->conn, dev->data.disk);
4220
    }
4221
    else
4222 4223 4224
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                         "%s", _("only SCSI or virtio disk device can be detached dynamically"));

4225
    if (!ret && virDomainSaveStatus(dom->conn, driver->stateDir, vm) < 0)
4226 4227
        ret = -1;

4228 4229
cleanup:
    virDomainDeviceDefFree(dev);
4230 4231
    if (vm)
        virDomainObjUnlock(vm);
4232
    qemuDriverUnlock(driver);
4233 4234 4235
    return ret;
}

4236
static int qemudDomainGetAutostart(virDomainPtr dom,
4237
                                   int *autostart) {
4238 4239 4240
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int ret = -1;
4241

4242
    qemuDriverLock(driver);
4243
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4244 4245
    qemuDriverUnlock(driver);

4246
    if (!vm) {
4247 4248 4249 4250
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4251
        goto cleanup;
4252 4253 4254
    }

    *autostart = vm->autostart;
4255
    ret = 0;
4256

4257
cleanup:
4258 4259
    if (vm)
        virDomainObjUnlock(vm);
4260
    return ret;
4261 4262
}

4263
static int qemudDomainSetAutostart(virDomainPtr dom,
4264
                                   int autostart) {
4265 4266
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4267 4268
    char *configFile = NULL, *autostartLink = NULL;
    int ret = -1;
4269

4270
    qemuDriverLock(driver);
4271
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4272

4273
    if (!vm) {
4274 4275 4276 4277
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4278
        goto cleanup;
4279 4280
    }

4281 4282 4283
    if (!vm->persistent) {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INTERNAL_ERROR,
                         "%s", _("cannot set autostart for transient domain"));
4284
        goto cleanup;
4285 4286
    }

4287 4288
    autostart = (autostart != 0);

4289 4290 4291 4292 4293
    if (vm->autostart != autostart) {
        if ((configFile = virDomainConfigFile(dom->conn, driver->configDir, vm->def->name)) == NULL)
            goto cleanup;
        if ((autostartLink = virDomainConfigFile(dom->conn, driver->autostartDir, vm->def->name)) == NULL)
            goto cleanup;
4294

4295 4296
        if (autostart) {
            int err;
4297

4298
            if ((err = virFileMakePath(driver->autostartDir))) {
4299 4300 4301
                virReportSystemError(dom->conn, err,
                                     _("cannot create autostart directory %s"),
                                     driver->autostartDir);
4302 4303
                goto cleanup;
            }
4304

4305
            if (symlink(configFile, autostartLink) < 0) {
4306 4307 4308
                virReportSystemError(dom->conn, errno,
                                     _("Failed to create symlink '%s to '%s'"),
                                     autostartLink, configFile);
4309 4310 4311 4312
                goto cleanup;
            }
        } else {
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
4313 4314 4315
                virReportSystemError(dom->conn, errno,
                                     _("Failed to delete symlink '%s'"),
                                     autostartLink);
4316 4317
                goto cleanup;
            }
4318 4319
        }

4320
        vm->autostart = autostart;
4321
    }
4322
    ret = 0;
4323

4324 4325 4326
cleanup:
    VIR_FREE(configFile);
    VIR_FREE(autostartLink);
4327 4328
    if (vm)
        virDomainObjUnlock(vm);
4329
    qemuDriverUnlock(driver);
4330
    return ret;
4331 4332
}

4333 4334 4335 4336 4337 4338 4339 4340 4341
/* 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)
{
4342
    struct qemud_driver *driver = dom->conn->privateData;
4343
    char *dummy, *info = NULL;
4344
    const char *p, *eol;
4345
    const char *qemu_dev_name = NULL;
4346
    size_t len;
4347
    int i, ret = -1;
4348
    virDomainObjPtr vm;
4349
    virDomainDiskDefPtr disk = NULL;
4350

4351
    qemuDriverLock(driver);
4352
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4353
    qemuDriverUnlock(driver);
4354
    if (!vm) {
4355 4356 4357 4358
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4359
        goto cleanup;
4360
    }
4361
    if (!virDomainIsActive (vm)) {
4362
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
4363
                          "%s", _("domain is not running"));
4364
        goto cleanup;
4365 4366
    }

4367 4368 4369 4370 4371 4372 4373 4374
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (STREQ(path, vm->def->disks[i]->dst)) {
            disk = vm->def->disks[i];
            break;
        }
    }

    if (!disk) {
4375 4376
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path: %s"), path);
4377
        goto cleanup;
4378 4379
    }

4380
    qemu_dev_name = qemudDiskDeviceName(dom->conn, disk);
4381
    if (!qemu_dev_name)
4382
        goto cleanup;
4383 4384
    len = strlen (qemu_dev_name);

4385
    if (qemudMonitorCommand (vm, "info blockstats", &info) < 0) {
4386 4387
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("'info blockstats' command failed"));
4388
        goto cleanup;
4389
    }
4390
    DEBUG ("%s: info blockstats reply: %s", vm->def->name, info);
4391 4392 4393 4394 4395 4396

    /* If the command isn't supported then qemu prints the supported
     * info commands, so the output starts "info ".  Since this is
     * unlikely to be the name of a block device, we can use this
     * to detect if qemu supports the command.
     */
C
Cole Robinson 已提交
4397
    if (strstr(info, "\ninfo ")) {
4398 4399 4400
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                          "%s",
                          _("'info blockstats' not supported by this qemu"));
4401
        goto cleanup;
4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427
    }

    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) {
4428
                if (STRPREFIX (p, "rd_bytes=")) {
4429 4430
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_bytes) == -1)
4431 4432
                        DEBUG ("%s: error reading rd_bytes: %s",
                               vm->def->name, p);
4433
                } else if (STRPREFIX (p, "wr_bytes=")) {
4434 4435
                    p += 9;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_bytes) == -1)
4436 4437
                        DEBUG ("%s: error reading wr_bytes: %s",
                               vm->def->name, p);
4438
                } else if (STRPREFIX (p, "rd_operations=")) {
4439 4440
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->rd_req) == -1)
4441 4442
                        DEBUG ("%s: error reading rd_req: %s",
                               vm->def->name, p);
4443
                } else if (STRPREFIX (p, "wr_operations=")) {
4444 4445
                    p += 14;
                    if (virStrToLong_ll (p, &dummy, 10, &stats->wr_req) == -1)
4446 4447
                        DEBUG ("%s: error reading wr_req: %s",
                               vm->def->name, p);
4448
                } else
4449
                    DEBUG ("%s: unknown block stat near %s", vm->def->name, p);
4450 4451 4452 4453 4454 4455

                /* Skip to next label. */
                p = strchr (p, ' ');
                if (!p || p >= eol) break;
                p++;
            }
4456
            ret = 0;
4457
            goto cleanup;
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468
        }

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

    /* If we reach here then the device was not found. */
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                      _("device not found: %s (%s)"), path, qemu_dev_name);
4469
 cleanup:
4470 4471
    VIR_FREE(qemu_dev_name);
    VIR_FREE(info);
4472 4473
    if (vm)
        virDomainObjUnlock(vm);
4474
    return ret;
4475 4476
}

4477
#ifdef __linux__
4478 4479 4480 4481 4482
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path,
                           struct _virDomainInterfaceStats *stats)
{
4483 4484
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4485
    int i;
4486
    int ret = -1;
4487

4488
    qemuDriverLock(driver);
4489
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4490 4491
    qemuDriverUnlock(driver);

4492
    if (!vm) {
4493 4494 4495 4496
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4497
        goto cleanup;
4498 4499
    }

4500
    if (!virDomainIsActive(vm)) {
4501
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
4502
                         "%s", _("domain is not running"));
4503
        goto cleanup;
4504 4505 4506 4507
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
4508
                         "%s", _("NULL or empty path"));
4509
        goto cleanup;
4510 4511 4512
    }

    /* Check the path is one of the domain's network interfaces. */
4513 4514
    for (i = 0 ; i < vm->def->nnets ; i++) {
        if (vm->def->nets[i]->ifname &&
4515 4516 4517 4518
            STREQ (vm->def->nets[i]->ifname, path)) {
            ret = 0;
            break;
        }
4519 4520
    }

4521 4522 4523 4524 4525
    if (ret == 0)
        ret = linuxDomainInterfaceStats (dom->conn, path, stats);
    else
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
                          _("invalid path, '%s' is not a known interface"), path);
4526

4527
cleanup:
4528 4529
    if (vm)
        virDomainObjUnlock(vm);
4530 4531
    return ret;
}
4532
#else
4533 4534 4535 4536
static int
qemudDomainInterfaceStats (virDomainPtr dom,
                           const char *path ATTRIBUTE_UNUSED,
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
4537 4538 4539 4540
    qemudReportError (dom->conn, dom, NULL, VIR_ERR_NO_SUPPORT,
                      "%s", __FUNCTION__);
    return -1;
}
4541
#endif
4542

4543 4544 4545 4546 4547 4548 4549
static int
qemudDomainBlockPeek (virDomainPtr dom,
                      const char *path,
                      unsigned long long offset, size_t size,
                      void *buffer,
                      unsigned int flags ATTRIBUTE_UNUSED)
{
4550 4551 4552
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    int fd = -1, ret = -1, i;
4553

4554
    qemuDriverLock(driver);
4555
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4556 4557
    qemuDriverUnlock(driver);

4558
    if (!vm) {
4559 4560 4561 4562
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4563
        goto cleanup;
4564 4565 4566 4567
    }

    if (!path || path[0] == '\0') {
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_INVALID_ARG,
J
Jim Meyering 已提交
4568
                         "%s", _("NULL or empty path"));
4569
        goto cleanup;
4570 4571 4572
    }

    /* Check the path belongs to this domain. */
4573 4574
    for (i = 0 ; i < vm->def->ndisks ; i++) {
        if (vm->def->disks[i]->src != NULL &&
4575 4576 4577 4578
            STREQ (vm->def->disks[i]->src, path)) {
            ret = 0;
            break;
        }
4579 4580
    }

4581 4582 4583 4584 4585
    if (ret == 0) {
        ret = -1;
        /* The path is correct, now try to open it and get its size. */
        fd = open (path, O_RDONLY);
        if (fd == -1) {
4586 4587
            virReportSystemError (dom->conn, errno,
                                  _("%s: failed to open"), path);
4588 4589
            goto cleanup;
        }
4590

4591 4592 4593 4594 4595 4596
        /* 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) {
4597 4598
            virReportSystemError (dom->conn, errno,
                                  _("%s: failed to seek or read"), path);
4599 4600 4601 4602 4603 4604 4605
            goto cleanup;
        }

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

4608 4609 4610
cleanup:
    if (fd >= 0)
        close (fd);
4611 4612
    if (vm)
        virDomainObjUnlock(vm);
4613 4614 4615
    return ret;
}

R
Richard W.M. Jones 已提交
4616 4617 4618 4619 4620 4621
static int
qemudDomainMemoryPeek (virDomainPtr dom,
                       unsigned long long offset, size_t size,
                       void *buffer,
                       unsigned int flags)
{
4622 4623 4624
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
    char cmd[256], *info = NULL;
R
Richard W.M. Jones 已提交
4625 4626 4627
    char tmp[] = TEMPDIR "/qemu.mem.XXXXXX";
    int fd = -1, ret = -1;

4628
    qemuDriverLock(driver);
4629
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4630
    qemuDriverUnlock(driver);
R
Richard W.M. Jones 已提交
4631 4632

    if (!vm) {
4633 4634 4635 4636
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4637 4638 4639 4640 4641 4642 4643
        goto cleanup;
    }

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

4646
    if (!virDomainIsActive(vm)) {
4647
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
R
Richard W.M. Jones 已提交
4648
                         "%s", _("domain is not running"));
4649
        goto cleanup;
R
Richard W.M. Jones 已提交
4650 4651 4652 4653
    }

    /* Create a temporary filename. */
    if ((fd = mkstemp (tmp)) == -1) {
4654 4655
        virReportSystemError (dom->conn, errno,
                              _("mkstemp(\"%s\") failed"), tmp);
4656
        goto cleanup;
R
Richard W.M. Jones 已提交
4657 4658 4659 4660
    }

    /* Issue the memsave command. */
    snprintf (cmd, sizeof cmd, "memsave %llu %zi \"%s\"", offset, size, tmp);
4661
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
R
Richard W.M. Jones 已提交
4662
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
4663
                          "%s", _("'memsave' command failed"));
4664
        goto cleanup;
R
Richard W.M. Jones 已提交
4665 4666
    }

4667
    DEBUG ("%s: memsave reply: %s", vm->def->name, info);
R
Richard W.M. Jones 已提交
4668 4669 4670

    /* Read the memory file into buffer. */
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
4671 4672 4673
        virReportSystemError (dom->conn, errno,
                              _("failed to read temporary file "
                                "created with template %s"), tmp);
4674
        goto cleanup;
R
Richard W.M. Jones 已提交
4675 4676 4677
    }

    ret = 0;
4678 4679 4680

cleanup:
    VIR_FREE(info);
R
Richard W.M. Jones 已提交
4681 4682
    if (fd >= 0) close (fd);
    unlink (tmp);
4683 4684
    if (vm)
        virDomainObjUnlock(vm);
R
Richard W.M. Jones 已提交
4685 4686 4687
    return ret;
}

4688

4689 4690
static int
qemudDomainEventRegister (virConnectPtr conn,
4691
                          virConnectDomainEventCallback callback,
4692 4693
                          void *opaque,
                          virFreeCallback freecb)
4694
{
4695 4696 4697
    struct qemud_driver *driver = conn->privateData;
    int ret;

4698
    qemuDriverLock(driver);
4699 4700
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
                                        callback, opaque, freecb);
4701
    qemuDriverUnlock(driver);
4702

4703
    return ret;
4704 4705 4706 4707
}

static int
qemudDomainEventDeregister (virConnectPtr conn,
4708
                            virConnectDomainEventCallback callback)
4709
{
4710 4711 4712
    struct qemud_driver *driver = conn->privateData;
    int ret;

4713
    qemuDriverLock(driver);
4714 4715 4716 4717 4718 4719
    if (driver->domainEventDispatching)
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
                                                   callback);
    else
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
                                               callback);
4720
    qemuDriverUnlock(driver);
4721

4722
    return ret;
4723 4724
}

4725 4726 4727 4728 4729
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
                                        virDomainEventPtr event,
                                        virConnectDomainEventCallback cb,
                                        void *cbopaque,
                                        void *opaque)
4730
{
4731
    struct qemud_driver *driver = opaque;
4732

4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776
    /* Drop the lock whle dispatching, for sake of re-entrancy */
    qemuDriverUnlock(driver);
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
    qemuDriverLock(driver);
}

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

    qemuDriverLock(driver);

    driver->domainEventDispatching = 1;

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

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

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

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


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

D
Daniel Veillard 已提交
4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796
/* Migration support. */

/* Prepare is the first step, and it runs on the destination host.
 *
 * This starts an empty VM listening on a TCP port.
 */
static int
qemudDomainMigratePrepare2 (virConnectPtr dconn,
                            char **cookie ATTRIBUTE_UNUSED,
                            int *cookielen ATTRIBUTE_UNUSED,
                            const char *uri_in,
                            char **uri_out,
                            unsigned long flags ATTRIBUTE_UNUSED,
                            const char *dname,
                            unsigned long resource ATTRIBUTE_UNUSED,
                            const char *dom_xml)
{
    static int port = 0;
4797 4798
    struct qemud_driver *driver = dconn->privateData;
    virDomainDefPtr def = NULL;
D
Daniel Veillard 已提交
4799 4800 4801 4802 4803
    virDomainObjPtr vm = NULL;
    int this_port;
    char hostname [HOST_NAME_MAX+1];
    char migrateFrom [64];
    const char *p;
4804
    virDomainEventPtr event = NULL;
4805 4806 4807
    int ret = -1;;

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

4809
    qemuDriverLock(driver);
D
Daniel Veillard 已提交
4810 4811 4812
    if (!dom_xml) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_INTERNAL_ERROR,
                          "%s", _("no domain XML passed"));
4813
        goto cleanup;
D
Daniel Veillard 已提交
4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831
    }

    /* The URI passed in may be NULL or a string "tcp://somehostname:port".
     *
     * If the URI passed in is NULL then we allocate a port number
     * from our pool of port numbers and return a URI of
     * "tcp://ourhostname:port".
     *
     * If the URI passed in is not NULL then we try to parse out the
     * port number and use that (note that the hostname is assumed
     * to be a correct hostname which refers to the target machine).
     */
    if (uri_in == NULL) {
        this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
        if (port == QEMUD_MIGRATION_NUM_PORTS) port = 0;

        /* Get hostname */
        if (gethostname (hostname, HOST_NAME_MAX+1) == -1) {
4832 4833
            virReportSystemError (dconn, errno,
                                  "%s", _("failed to determine host name"));
4834
            goto cleanup;
D
Daniel Veillard 已提交
4835 4836 4837
        }

        /* Caller frees */
4838
        if (virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port) < 0) {
4839
            virReportOOMError (dconn);
4840
            goto cleanup;
D
Daniel Veillard 已提交
4841 4842 4843 4844 4845 4846
        }
    } else {
        /* Check the URI starts with "tcp:".  We will escape the
         * URI when passing it to the qemu monitor, so bad
         * characters in hostname part don't matter.
         */
4847
        if (!STRPREFIX (uri_in, "tcp:")) {
D
Daniel Veillard 已提交
4848 4849
            qemudReportError (dconn, NULL, NULL, VIR_ERR_INVALID_ARG,
                  "%s", _("only tcp URIs are supported for KVM migrations"));
4850
            goto cleanup;
D
Daniel Veillard 已提交
4851 4852 4853 4854 4855 4856 4857 4858 4859
        }

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

    /* Parse the domain XML. */
4865 4866
    if (!(def = virDomainDefParseString(dconn, driver->caps, dom_xml,
                                        VIR_DOMAIN_XML_INACTIVE))) {
D
Daniel Veillard 已提交
4867 4868
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to parse XML"));
4869
        goto cleanup;
D
Daniel Veillard 已提交
4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885
    }

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

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

    if (!vm) vm = virDomainFindByName(&driver->domains, dname);
    if (vm) {
        if (virDomainIsActive(vm)) {
            qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                              _("domain with the same name or UUID already exists as '%s'"),
                              vm->def->name);
4896
            goto cleanup;
D
Daniel Veillard 已提交
4897
        }
4898
        virDomainObjUnlock(vm);
D
Daniel Veillard 已提交
4899 4900 4901 4902 4903 4904 4905
    }

    if (!(vm = virDomainAssignDef(dconn,
                                  &driver->domains,
                                  def))) {
        qemudReportError (dconn, NULL, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("failed to assign new VM"));
4906
        goto cleanup;
D
Daniel Veillard 已提交
4907
    }
4908
    def = NULL;
D
Daniel Veillard 已提交
4909 4910 4911 4912 4913 4914 4915 4916

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

    /* Start the QEMU daemon, with the same command-line arguments plus
     * -incoming tcp:0.0.0.0:port
     */
    snprintf (migrateFrom, sizeof (migrateFrom), "tcp:0.0.0.0:%d", this_port);
4917
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom, -1) < 0) {
4918
        if (!vm->persistent) {
D
Daniel Veillard 已提交
4919
            virDomainRemoveInactive(&driver->domains, vm);
4920 4921
            vm = NULL;
        }
4922
        goto cleanup;
D
Daniel Veillard 已提交
4923
    }
4924 4925 4926 4927

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

4930 4931 4932 4933 4934
cleanup:
    virDomainDefFree(def);
    if (ret != 0) {
        VIR_FREE(*uri_out);
    }
4935 4936
    if (vm)
        virDomainObjUnlock(vm);
4937 4938
    if (event)
        qemuDomainEventQueue(driver, event);
4939
    qemuDriverUnlock(driver);
4940
    return ret;
D
Daniel Veillard 已提交
4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952
}

/* Perform is the second step, and it runs on the source host. */
static int
qemudDomainMigratePerform (virDomainPtr dom,
                           const char *cookie ATTRIBUTE_UNUSED,
                           int cookielen ATTRIBUTE_UNUSED,
                           const char *uri,
                           unsigned long flags ATTRIBUTE_UNUSED,
                           const char *dname ATTRIBUTE_UNUSED,
                           unsigned long resource)
{
4953 4954
    struct qemud_driver *driver = dom->conn->privateData;
    virDomainObjPtr vm;
4955
    virDomainEventPtr event = NULL;
D
Daniel Veillard 已提交
4956 4957
    char *safe_uri;
    char cmd[HOST_NAME_MAX+50];
4958 4959
    char *info = NULL;
    int ret = -1;
4960
    int paused = 0;
D
Daniel Veillard 已提交
4961

4962
    qemuDriverLock(driver);
4963
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
D
Daniel Veillard 已提交
4964
    if (!vm) {
4965 4966 4967 4968
        char uuidstr[VIR_UUID_STRING_BUFLEN];
        virUUIDFormat(dom->uuid, uuidstr);
        qemudReportError(dom->conn, dom, NULL, VIR_ERR_NO_DOMAIN,
                         _("no domain with matching uuid '%s'"), uuidstr);
4969
        goto cleanup;
D
Daniel Veillard 已提交
4970 4971 4972
    }

    if (!virDomainIsActive(vm)) {
4973
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_INVALID,
D
Daniel Veillard 已提交
4974
                          "%s", _("domain is not running"));
4975
        goto cleanup;
D
Daniel Veillard 已提交
4976 4977
    }

4978 4979
    if (!(flags & VIR_MIGRATE_LIVE)) {
        /* Pause domain for non-live migration */
4980 4981 4982 4983 4984
        if (qemudMonitorCommand (vm, "stop", &info) < 0) {
            qemudReportError(dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                             "%s", _("off-line migration specified, but suspend operation failed"));
            goto cleanup;
        }
4985
        DEBUG ("%s: stop reply: %s", vm->def->name, info);
4986
        VIR_FREE(info);
4987
        paused = 1;
4988

4989 4990 4991 4992 4993 4994
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_SUSPENDED,
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
        if (event)
            qemuDomainEventQueue(driver, event);
        event = NULL;
4995 4996
    }

D
Daniel Veillard 已提交
4997 4998 4999
    if (resource > 0) {
        /* Issue migrate_set_speed command.  Don't worry if it fails. */
        snprintf (cmd, sizeof cmd, "migrate_set_speed %lum", resource);
5000
        qemudMonitorCommand (vm, cmd, &info);
D
Daniel Veillard 已提交
5001

5002
        DEBUG ("%s: migrate_set_speed reply: %s", vm->def->name, info);
D
Daniel Veillard 已提交
5003 5004 5005 5006 5007 5008
        VIR_FREE (info);
    }

    /* Issue the migrate command. */
    safe_uri = qemudEscapeMonitorArg (uri);
    if (!safe_uri) {
5009
        virReportOOMError (dom->conn);
5010
        goto cleanup;
D
Daniel Veillard 已提交
5011 5012 5013 5014
    }
    snprintf (cmd, sizeof cmd, "migrate \"%s\"", safe_uri);
    VIR_FREE (safe_uri);

5015
    if (qemudMonitorCommand (vm, cmd, &info) < 0) {
D
Daniel Veillard 已提交
5016 5017
        qemudReportError (dom->conn, dom, NULL, VIR_ERR_OPERATION_FAILED,
                          "%s", _("migrate operation failed"));
5018
        goto cleanup;
D
Daniel Veillard 已提交
5019 5020
    }

5021
    DEBUG ("%s: migrate reply: %s", vm->def->name, info);
D
Daniel Veillard 已提交
5022 5023 5024 5025 5026

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

    /* Clean up the source domain. */
    qemudShutdownVMDaemon (dom->conn, driver, vm);
5032
    paused = 0;
5033 5034 5035 5036

    event = virDomainEventNewFromObj(vm,
                                     VIR_DOMAIN_EVENT_STOPPED,
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
5037
    if (!vm->persistent) {
D
Daniel Veillard 已提交
5038
        virDomainRemoveInactive(&driver->domains, vm);
5039 5040
        vm = NULL;
    }
5041
    ret = 0;
D
Daniel Veillard 已提交
5042

5043
cleanup:
5044 5045 5046
    /* Note that we have to free info *first*, since we are re-using the
     * variable below (and otherwise might cause a memory leak)
     */
5047
    VIR_FREE(info);
5048 5049 5050 5051 5052 5053 5054 5055

    if (paused) {
        /* we got here through some sort of failure; start the domain again */
        if (qemudMonitorCommand (vm, "cont", &info) < 0) {
            /* Hm, we already know we are in error here.  We don't want to
             * overwrite the previous error, though, so we just throw something
             * to the logs and hope for the best
             */
5056 5057
            VIR_ERROR(_("Failed to resume guest %s after failure\n"),
                      vm->def->name);
5058 5059
        }
        else {
5060
            DEBUG ("%s: cont reply: %s", vm->def->name, info);
5061 5062 5063 5064 5065 5066 5067 5068
            VIR_FREE(info);
        }

        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
    }

5069 5070
    if (vm)
        virDomainObjUnlock(vm);
5071 5072
    if (event)
        qemuDomainEventQueue(driver, event);
5073
    qemuDriverUnlock(driver);
5074
    return ret;
D
Daniel Veillard 已提交
5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086
}

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

5093
    qemuDriverLock(driver);
5094
    vm = virDomainFindByName(&driver->domains, dname);
D
Daniel Veillard 已提交
5095
    if (!vm) {
5096 5097
        qemudReportError (dconn, NULL, NULL, VIR_ERR_NO_DOMAIN,
                          _("no domain with matching name '%s'"), dname);
5098
        goto cleanup;
D
Daniel Veillard 已提交
5099 5100 5101 5102 5103 5104 5105 5106 5107
    }

    /* Did the migration go as planned?  If yes, return the domain
     * object, but if no, clean up the empty qemu process.
     */
    if (retcode == 0) {
        dom = virGetDomain (dconn, vm->def->name, vm->def->uuid);
        VIR_FREE(info);
        vm->state = VIR_DOMAIN_RUNNING;
5108 5109 5110
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_RESUMED,
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
D
Daniel Veillard 已提交
5111 5112
    } else {
        qemudShutdownVMDaemon (dconn, driver, vm);
5113 5114 5115
        event = virDomainEventNewFromObj(vm,
                                         VIR_DOMAIN_EVENT_STOPPED,
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
5116
        if (!vm->persistent) {
D
Daniel Veillard 已提交
5117
            virDomainRemoveInactive(&driver->domains, vm);
5118 5119
            vm = NULL;
        }
D
Daniel Veillard 已提交
5120
    }
5121 5122

cleanup:
5123 5124
    if (vm)
        virDomainObjUnlock(vm);
5125 5126
    if (event)
        qemuDomainEventQueue(driver, event);
5127
    qemuDriverUnlock(driver);
5128
    return dom;
D
Daniel Veillard 已提交
5129 5130
}

5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146
static int
qemudNodeDeviceGetPciInfo (virNodeDevicePtr dev,
                           unsigned *domain,
                           unsigned *bus,
                           unsigned *slot,
                           unsigned *function)
{
    virNodeDeviceDefPtr def = NULL;
    virNodeDevCapsDefPtr cap;
    char *xml = NULL;
    int ret = -1;

    xml = virNodeDeviceGetXMLDesc(dev, 0);
    if (!xml)
        goto out;

5147
    def = virNodeDeviceDefParseString(dev->conn, xml, EXISTING_DEVICE);
5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245
    if (!def)
        goto out;

    cap = def->caps;
    while (cap) {
        if (cap->type == VIR_NODE_DEV_CAP_PCI_DEV) {
            *domain   = cap->data.pci_dev.domain;
            *bus      = cap->data.pci_dev.bus;
            *slot     = cap->data.pci_dev.slot;
            *function = cap->data.pci_dev.function;
            break;
        }

        cap = cap->next;
    }

    if (!cap) {
        qemudReportError(dev->conn, NULL, NULL, VIR_ERR_INVALID_ARG,
                         _("device %s is not a PCI device"), dev->name);
        goto out;
    }

    ret = 0;
out:
    virNodeDeviceDefFree(def);
    VIR_FREE(xml);
    return ret;
}

static int
qemudNodeDeviceDettach (virNodeDevicePtr dev)
{
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

    pci = pciGetDevice(dev->conn, domain, bus, slot, function);
    if (!pci)
        return -1;

    if (pciDettachDevice(dev->conn, pci) < 0)
        goto out;

    ret = 0;
out:
    pciFreeDevice(dev->conn, pci);
    return ret;
}

static int
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
{
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

    pci = pciGetDevice(dev->conn, domain, bus, slot, function);
    if (!pci)
        return -1;

    if (pciReAttachDevice(dev->conn, pci) < 0)
        goto out;

    ret = 0;
out:
    pciFreeDevice(dev->conn, pci);
    return ret;
}

static int
qemudNodeDeviceReset (virNodeDevicePtr dev)
{
    pciDevice *pci;
    unsigned domain, bus, slot, function;
    int ret = -1;

    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
        return -1;

    pci = pciGetDevice(dev->conn, domain, bus, slot, function);
    if (!pci)
        return -1;

    if (pciResetDevice(dev->conn, pci) < 0)
        goto out;

    ret = 0;
out:
    pciFreeDevice(dev->conn, pci);
    return ret;
}

5246 5247 5248 5249 5250
static virDriver qemuDriver = {
    VIR_DRV_QEMU,
    "QEMU",
    qemudOpen, /* open */
    qemudClose, /* close */
D
Daniel Veillard 已提交
5251
    qemudSupportsFeature, /* supports_feature */
5252 5253
    qemudGetType, /* type */
    qemudGetVersion, /* version */
5254
    qemudGetHostname, /* getHostname */
5255
    qemudGetMaxVCPUs, /* getMaxVcpus */
5256
    nodeGetInfo, /* nodeGetInfo */
5257 5258 5259
    qemudGetCapabilities, /* getCapabilities */
    qemudListDomains, /* listDomains */
    qemudNumDomains, /* numOfDomains */
5260
    qemudDomainCreate, /* domainCreateXML */
5261 5262 5263 5264 5265
    qemudDomainLookupByID, /* domainLookupByID */
    qemudDomainLookupByUUID, /* domainLookupByUUID */
    qemudDomainLookupByName, /* domainLookupByName */
    qemudDomainSuspend, /* domainSuspend */
    qemudDomainResume, /* domainResume */
5266
    qemudDomainShutdown, /* domainShutdown */
5267 5268 5269
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */
    qemudDomainGetOSType, /* domainGetOSType */
5270 5271 5272
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
    qemudDomainSetMaxMemory, /* domainSetMaxMemory */
    qemudDomainSetMemory, /* domainSetMemory */
5273 5274 5275 5276
    qemudDomainGetInfo, /* domainGetInfo */
    qemudDomainSave, /* domainSave */
    qemudDomainRestore, /* domainRestore */
    NULL, /* domainCoreDump */
5277
    qemudDomainSetVcpus, /* domainSetVcpus */
5278 5279 5280 5281
#if HAVE_SCHED_GETAFFINITY
    qemudDomainPinVcpu, /* domainPinVcpu */
    qemudDomainGetVcpus, /* domainGetVcpus */
#else
5282 5283
    NULL, /* domainPinVcpu */
    NULL, /* domainGetVcpus */
5284
#endif
5285
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
5286 5287
    qemudDomainGetSecurityLabel, /* domainGetSecurityLabel */
    qemudNodeGetSecurityModel, /* nodeGetSecurityModel */
5288
    qemudDomainDumpXML, /* domainDumpXML */
5289
    qemuDomainXMLFromNative, /* domainXmlFromNative */
5290
    qemuDomainXMLToNative, /* domainXMLToNative */
5291 5292
    qemudListDefinedDomains, /* listDefinedDomains */
    qemudNumDefinedDomains, /* numOfDefinedDomains */
5293 5294 5295
    qemudDomainStart, /* domainCreate */
    qemudDomainDefine, /* domainDefineXML */
    qemudDomainUndefine, /* domainUndefine */
5296
    qemudDomainAttachDevice, /* domainAttachDevice */
5297
    qemudDomainDetachDevice, /* domainDetachDevice */
5298 5299 5300 5301 5302
    qemudDomainGetAutostart, /* domainGetAutostart */
    qemudDomainSetAutostart, /* domainSetAutostart */
    NULL, /* domainGetSchedulerType */
    NULL, /* domainGetSchedulerParameters */
    NULL, /* domainSetSchedulerParameters */
D
Daniel Veillard 已提交
5303 5304
    NULL, /* domainMigratePrepare (v1) */
    qemudDomainMigratePerform, /* domainMigratePerform */
5305
    NULL, /* domainMigrateFinish */
5306
    qemudDomainBlockStats, /* domainBlockStats */
5307
    qemudDomainInterfaceStats, /* domainInterfaceStats */
5308
    qemudDomainBlockPeek, /* domainBlockPeek */
R
Richard W.M. Jones 已提交
5309
    qemudDomainMemoryPeek, /* domainMemoryPeek */
5310 5311
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
    nodeGetFreeMemory,  /* getFreeMemory */
5312 5313
    qemudDomainEventRegister, /* domainEventRegister */
    qemudDomainEventDeregister, /* domainEventDeregister */
D
Daniel Veillard 已提交
5314 5315
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
5316 5317 5318
    qemudNodeDeviceDettach, /* nodeDeviceDettach */
    qemudNodeDeviceReAttach, /* nodeDeviceReAttach */
    qemudNodeDeviceReset, /* nodeDeviceReset */
5319 5320 5321
};


5322
static virStateDriver qemuStateDriver = {
5323 5324 5325 5326
    .initialize = qemudStartup,
    .cleanup = qemudShutdown,
    .reload = qemudReload,
    .active = qemudActive,
5327
};
5328

5329
int qemuRegister(void) {
5330 5331 5332 5333
    virRegisterDriver(&qemuDriver);
    virRegisterStateDriver(&qemuStateDriver);
    return 0;
}