~ubuntu-branches/ubuntu/oneiric/libvirt/oneiric-updates

« back to all changes in this revision

Viewing changes to .pc/9026-security-avoid-memory-leak.patch/src/qemu/qemu_driver.c

  • Committer: Package Import Robot
  • Author(s): Serge Hallyn
  • Date: 2011-05-11 12:29:51 UTC
  • mfrom: (1.2.10) (3.4.30 sid)
  • Revision ID: package-import@ubuntu.com-20110511122951-ku5fk1tv37o5aymm
Tags: 0.9.1-1ubuntu1
* Resynchronize and merge from Debian unstable (LP: #794378). Remaining
  changes:
  - debian/control:
    * set X-Python-Version to 2.7, as 2.6 is not in oneiric.
    * set ubuntu maintainer
    * Build-Depends:
      - remove [linux-any] from all dependencies
      - remove [!linux-any] deps
      - swap libxen to libxen3, qemu to qemu-kvm, and open-iscsi to
        open-iscsi-utils in Build-Depends
      - remove virtualbox-ose Build-Depends
      - add parted and libapparmor-dev Build-Depends
    * convert Vcs-Git to Xs-Debian-Vcs-Git
    * libvirt-bin Depends: move netcat-openbsd, bridge-utils, dnsmasq-base
      (>= 2.46-1), and iptables from Recommends to Depends
    * libvirt-bin Recommends: move qemu to Suggests
    * libvirt-bin Suggests: add apparmor
    * libvirt0 Recommands: move lvm2 to Suggests
  - keep debian/libvirt-bin.apport
  - keep debian/libvirt-bin.cron.daily
  - debian/libvirt-bin.dirs:
    * add apparmor, cron.daily, and apport dirs
  - debian/libvirt-bin.examples:
    * add debian/libvirt-suspendonreboot
  - debian/libvirt-bin.install:
    * add /etc/apparmor.d files
    * add apport hook
  - debian/libvirt-bin.manpages:
    * add debian/libvirt-migrate-qemu-disks.1
  - debian/libvirt-bin.postinst:
    * replace libvirt groupname with libvirtd
    * add each admin user to libvirtd group
    * call apparmor_parser on usr.sbin.libvirtd and
      usr.lib.libvirt.virt-aa-helper
    * call 'libvirt-migrate-qemu-disks -a' after
      libvirt-bin has started if migrating from
      older than 0.8.3-1ubuntu1
  - debian/libvirt-bin.postrm:
    * replace libvirt groupname with libvirtd
    * remove usr.sbin.libvirtd and
      usr.lib.libvirt.virt-aa-helper
  - keep added files under debian/:
    * libvirt-bin.upstart
    * libvirt-migrate-qemu-disks
    * libvirt-migrate-qemu-disks.1
    * libvirt-suspendonreboot
    * apparmor profiles
  - debian/README.Debian:
    * add 'Apparmor Profile' section
    * add 'Disk migration' section
  - debian/rules:
    * move include of debhelper.mk to top of file so DEB_HOST_ARCH_OS
      is defined.
    * don't build with vbox since virtualbox-ose is in universe
      - remove WITH_VBOX, add explicit --without-vbox
    * add --with-apparmor to DEB_CONFIGURE_EXTRA_FLAGS
    * set DEB_DH_INSTALLINIT_ARGS to '--upstart-only'
    * remove unneeded binary-install/libvirt-bin:: and clean::
      sections (they only deal with sysvinit stuff)
    * add build/libvirt-bin:: section to install
      - apparmor files
      - apport hooks
      - libvirt-migrate-qemu-disks
* debian/patches/series:
  - don't apply Disable-CHECKSUM-rule.patch: our iptables can do this
  - don't apply Debian-specific Debianize-libvirt-guests.patch (sysvinit only)
  - don't apply Disable qemu-disable-network.diff.patch
* debian/patches:
  - drop 9007-fix-daemon-conf-ftbfs.patch (looks like it may be fixed)
  - drop patches applied upstream:
    * 9022-drop-booton-when-kernel-specified.patch
    * 9023-fix-lxc-console-hangup.patch
    * 9024-fix-broken-commandtest.patch
    * 9025-Pass-virSecurityManagerPtr-to-virSecurityDAC-Set-Res.patch
    * 9026-security-avoid-memory-leak.patch
    * 9027-CVE-2011-1146.patch
  - keep patches:
    * 9000-delayed_iff_up_bridge.patch
    * 9001-dont_clobber_existing_bridges.patch
    * 9002-better_default_uri_virsh.patch
    * 9003-better-default-arch.patch
    * 9004-libvirtd-group-name.patch
    * 9005-increase-unix-socket-timeout.patch
    * 9006-default-config-test-case.patch
    * 9011-move-ebtables-script.patch (refreshed)
    * 9014-skip-nodeinfotest.patch (modified to make it apply)
    * 9020-lp545795.patch (modified to make it still apply)
    * 9021-fix-uint64_t.patch
    * 9022-allows-lxc-containers-with-lxcguest.patch (renamed, modified
      to make it still apply, and added DEP-3 tags).
  - new patches:
    * 9023-disable-test-poll.patch - don't run broken test-poll

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/*
2
 
 * driver.c: core driver methods for managing qemu guests
3
 
 *
4
 
 * Copyright (C) 2006-2011 Red Hat, Inc.
5
 
 * Copyright (C) 2006 Daniel P. Berrange
6
 
 *
7
 
 * This library is free software; you can redistribute it and/or
8
 
 * modify it under the terms of the GNU Lesser General Public
9
 
 * License as published by the Free Software Foundation; either
10
 
 * version 2.1 of the License, or (at your option) any later version.
11
 
 *
12
 
 * This library is distributed in the hope that it will be useful,
13
 
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15
 
 * Lesser General Public License for more details.
16
 
 *
17
 
 * You should have received a copy of the GNU Lesser General Public
18
 
 * License along with this library; if not, write to the Free Software
19
 
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
20
 
 *
21
 
 * Author: Daniel P. Berrange <berrange@redhat.com>
22
 
 */
23
 
 
24
 
#include <config.h>
25
 
 
26
 
#include <sys/types.h>
27
 
#include <sys/poll.h>
28
 
#include <sys/time.h>
29
 
#include <dirent.h>
30
 
#include <limits.h>
31
 
#include <string.h>
32
 
#include <stdbool.h>
33
 
#include <stdio.h>
34
 
#include <stdarg.h>
35
 
#include <stdlib.h>
36
 
#include <unistd.h>
37
 
#include <errno.h>
38
 
#include <sys/utsname.h>
39
 
#include <sys/stat.h>
40
 
#include <fcntl.h>
41
 
#include <signal.h>
42
 
#include <paths.h>
43
 
#include <stdio.h>
44
 
#include <sys/wait.h>
45
 
#include <sys/ioctl.h>
46
 
#include <sys/un.h>
47
 
 
48
 
 
49
 
#include "virterror_internal.h"
50
 
#include "logging.h"
51
 
#include "datatypes.h"
52
 
#include "qemu_driver.h"
53
 
#include "qemu_conf.h"
54
 
#include "qemu_capabilities.h"
55
 
#include "qemu_command.h"
56
 
#include "qemu_cgroup.h"
57
 
#include "qemu_hostdev.h"
58
 
#include "qemu_hotplug.h"
59
 
#include "qemu_monitor.h"
60
 
#include "qemu_bridge_filter.h"
61
 
#include "qemu_audit.h"
62
 
#include "c-ctype.h"
63
 
#include "event.h"
64
 
#include "buf.h"
65
 
#include "util.h"
66
 
#include "nodeinfo.h"
67
 
#include "stats_linux.h"
68
 
#include "capabilities.h"
69
 
#include "memory.h"
70
 
#include "uuid.h"
71
 
#include "domain_conf.h"
72
 
#include "node_device_conf.h"
73
 
#include "pci.h"
74
 
#include "hostusb.h"
75
 
#include "processinfo.h"
76
 
#include "libvirt_internal.h"
77
 
#include "xml.h"
78
 
#include "cpu/cpu.h"
79
 
#include "macvtap.h"
80
 
#include "sysinfo.h"
81
 
#include "domain_nwfilter.h"
82
 
#include "hooks.h"
83
 
#include "storage_file.h"
84
 
#include "files.h"
85
 
#include "fdstream.h"
86
 
#include "configmake.h"
87
 
#include "threadpool.h"
88
 
 
89
 
#define VIR_FROM_THIS VIR_FROM_QEMU
90
 
 
91
 
#define QEMU_VNC_PORT_MIN  5900
92
 
#define QEMU_VNC_PORT_MAX  65535
93
 
 
94
 
#define QEMU_NB_MEM_PARAM  3
95
 
 
96
 
 
97
 
#define timeval_to_ms(tv)       (((tv).tv_sec * 1000ull) + ((tv).tv_usec / 1000))
98
 
 
99
 
struct watchdogEvent
100
 
{
101
 
    virDomainObjPtr vm;
102
 
    int action;
103
 
};
104
 
 
105
 
static void processWatchdogEvent(void *data, void *opaque);
106
 
 
107
 
static int qemudShutdown(void);
108
 
 
109
 
static void qemuDomainEventFlush(int timer, void *opaque);
110
 
static void qemuDomainEventQueue(struct qemud_driver *driver,
111
 
                                 virDomainEventPtr event);
112
 
 
113
 
static int qemudDomainObjStart(virConnectPtr conn,
114
 
                               struct qemud_driver *driver,
115
 
                               virDomainObjPtr vm,
116
 
                               bool start_paused);
117
 
 
118
 
static int qemudStartVMDaemon(virConnectPtr conn,
119
 
                              struct qemud_driver *driver,
120
 
                              virDomainObjPtr vm,
121
 
                              const char *migrateFrom,
122
 
                              bool start_paused,
123
 
                              int stdin_fd,
124
 
                              const char *stdin_path,
125
 
                              enum virVMOperationType vmop);
126
 
 
127
 
static void qemudShutdownVMDaemon(struct qemud_driver *driver,
128
 
                                  virDomainObjPtr vm,
129
 
                                  int migrated);
130
 
 
131
 
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
132
 
 
133
 
static int qemuDetectVcpuPIDs(struct qemud_driver *driver,
134
 
                              virDomainObjPtr vm);
135
 
 
136
 
static int qemudVMFiltersInstantiate(virConnectPtr conn,
137
 
                                     virDomainDefPtr def);
138
 
 
139
 
static struct qemud_driver *qemu_driver = NULL;
140
 
 
141
 
 
142
 
static int doStartCPUs(struct qemud_driver *driver, virDomainObjPtr vm, virConnectPtr conn)
143
 
{
144
 
    int ret;
145
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
146
 
 
147
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
148
 
    ret = qemuMonitorStartCPUs(priv->mon, conn);
149
 
    if (ret == 0) {
150
 
        vm->state = VIR_DOMAIN_RUNNING;
151
 
    }
152
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
153
 
 
154
 
    return ret;
155
 
}
156
 
 
157
 
static int doStopCPUs(struct qemud_driver *driver, virDomainObjPtr vm)
158
 
{
159
 
    int ret;
160
 
    int oldState = vm->state;
161
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
162
 
 
163
 
    vm->state = VIR_DOMAIN_PAUSED;
164
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
165
 
    ret = qemuMonitorStopCPUs(priv->mon);
166
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
167
 
    if (ret < 0) {
168
 
        vm->state = oldState;
169
 
    }
170
 
    return ret;
171
 
}
172
 
 
173
 
 
174
 
static int
175
 
qemudLogFD(struct qemud_driver *driver, const char* name, bool append)
176
 
{
177
 
    char *logfile;
178
 
    mode_t logmode;
179
 
    int fd = -1;
180
 
 
181
 
    if (virAsprintf(&logfile, "%s/%s.log", driver->logDir, name) < 0) {
182
 
        virReportOOMError();
183
 
        return -1;
184
 
    }
185
 
 
186
 
    logmode = O_CREAT | O_WRONLY;
187
 
    /* Only logrotate files in /var/log, so only append if running privileged */
188
 
    if (driver->privileged || append)
189
 
        logmode |= O_APPEND;
190
 
    else
191
 
        logmode |= O_TRUNC;
192
 
 
193
 
    if ((fd = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
194
 
        virReportSystemError(errno,
195
 
                             _("failed to create logfile %s"),
196
 
                             logfile);
197
 
        VIR_FREE(logfile);
198
 
        return -1;
199
 
    }
200
 
    VIR_FREE(logfile);
201
 
    if (virSetCloseExec(fd) < 0) {
202
 
        virReportSystemError(errno, "%s",
203
 
                             _("Unable to set VM logfile close-on-exec flag"));
204
 
        VIR_FORCE_CLOSE(fd);
205
 
        return -1;
206
 
    }
207
 
    return fd;
208
 
}
209
 
 
210
 
 
211
 
static int
212
 
qemudLogReadFD(const char* logDir, const char* name, off_t pos)
213
 
{
214
 
    char *logfile;
215
 
    mode_t logmode = O_RDONLY;
216
 
    int fd = -1;
217
 
 
218
 
    if (virAsprintf(&logfile, "%s/%s.log", logDir, name) < 0) {
219
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
220
 
                        _("failed to build logfile name %s/%s.log"),
221
 
                        logDir, name);
222
 
        return -1;
223
 
    }
224
 
 
225
 
    if ((fd = open(logfile, logmode)) < 0) {
226
 
        virReportSystemError(errno,
227
 
                             _("failed to create logfile %s"),
228
 
                             logfile);
229
 
        VIR_FREE(logfile);
230
 
        return -1;
231
 
    }
232
 
    if (virSetCloseExec(fd) < 0) {
233
 
        virReportSystemError(errno, "%s",
234
 
                             _("Unable to set VM logfile close-on-exec flag"));
235
 
        VIR_FORCE_CLOSE(fd);
236
 
        VIR_FREE(logfile);
237
 
        return -1;
238
 
    }
239
 
    if (pos < 0 || lseek(fd, pos, SEEK_SET) < 0) {
240
 
        virReportSystemError(pos < 0 ? 0 : errno,
241
 
                             _("Unable to seek to %lld in %s"),
242
 
                             (long long) pos, logfile);
243
 
        VIR_FORCE_CLOSE(fd);
244
 
    }
245
 
    VIR_FREE(logfile);
246
 
    return fd;
247
 
}
248
 
 
249
 
 
250
 
struct qemuAutostartData {
251
 
    struct qemud_driver *driver;
252
 
    virConnectPtr conn;
253
 
};
254
 
static void
255
 
qemuAutostartDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
256
 
{
257
 
    virDomainObjPtr vm = payload;
258
 
    struct qemuAutostartData *data = opaque;
259
 
    virErrorPtr err;
260
 
 
261
 
    virDomainObjLock(vm);
262
 
    virResetLastError();
263
 
    if (qemuDomainObjBeginJobWithDriver(data->driver, vm) < 0) {
264
 
        err = virGetLastError();
265
 
        VIR_ERROR(_("Failed to start job on VM '%s': %s"),
266
 
                  vm->def->name,
267
 
                  err ? err->message : _("unknown error"));
268
 
    } else {
269
 
        if (vm->autostart &&
270
 
            !virDomainObjIsActive(vm) &&
271
 
            qemudDomainObjStart(data->conn, data->driver, vm, false) < 0) {
272
 
            err = virGetLastError();
273
 
            VIR_ERROR(_("Failed to autostart VM '%s': %s"),
274
 
                      vm->def->name,
275
 
                      err ? err->message : _("unknown error"));
276
 
        }
277
 
 
278
 
        if (qemuDomainObjEndJob(vm) == 0)
279
 
            vm = NULL;
280
 
    }
281
 
 
282
 
    if (vm)
283
 
        virDomainObjUnlock(vm);
284
 
}
285
 
 
286
 
static void
287
 
qemudAutostartConfigs(struct qemud_driver *driver) {
288
 
    /* XXX: Figure out a better way todo this. The domain
289
 
     * startup code needs a connection handle in order
290
 
     * to lookup the bridge associated with a virtual
291
 
     * network
292
 
     */
293
 
    virConnectPtr conn = virConnectOpen(driver->privileged ?
294
 
                                        "qemu:///system" :
295
 
                                        "qemu:///session");
296
 
    /* Ignoring NULL conn which is mostly harmless here */
297
 
    struct qemuAutostartData data = { driver, conn };
298
 
 
299
 
    qemuDriverLock(driver);
300
 
    virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
301
 
    qemuDriverUnlock(driver);
302
 
 
303
 
    if (conn)
304
 
        virConnectClose(conn);
305
 
}
306
 
 
307
 
 
308
 
/**
309
 
 * qemudRemoveDomainStatus
310
 
 *
311
 
 * remove all state files of a domain from statedir
312
 
 *
313
 
 * Returns 0 on success
314
 
 */
315
 
static int
316
 
qemudRemoveDomainStatus(struct qemud_driver *driver,
317
 
                        virDomainObjPtr vm)
318
 
{
319
 
    char ebuf[1024];
320
 
    char *file = NULL;
321
 
 
322
 
    if (virAsprintf(&file, "%s/%s.xml", driver->stateDir, vm->def->name) < 0) {
323
 
        virReportOOMError();
324
 
        return(-1);
325
 
    }
326
 
 
327
 
    if (unlink(file) < 0 && errno != ENOENT && errno != ENOTDIR)
328
 
        VIR_WARN("Failed to remove domain XML for %s: %s",
329
 
                 vm->def->name, virStrerror(errno, ebuf, sizeof(ebuf)));
330
 
    VIR_FREE(file);
331
 
 
332
 
    if (virFileDeletePid(driver->stateDir, vm->def->name) != 0)
333
 
        VIR_WARN("Failed to remove PID file for %s: %s",
334
 
                 vm->def->name, virStrerror(errno, ebuf, sizeof(ebuf)));
335
 
 
336
 
 
337
 
    return 0;
338
 
}
339
 
 
340
 
 
341
 
/*
342
 
 * This is a callback registered with a qemuMonitorPtr  instance,
343
 
 * and to be invoked when the monitor console hits an end of file
344
 
 * condition, or error, thus indicating VM shutdown should be
345
 
 * performed
346
 
 */
347
 
static void
348
 
qemuHandleMonitorEOF(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
349
 
                     virDomainObjPtr vm,
350
 
                     int hasError) {
351
 
    struct qemud_driver *driver = qemu_driver;
352
 
    virDomainEventPtr event = NULL;
353
 
    qemuDomainObjPrivatePtr priv;
354
 
 
355
 
    VIR_DEBUG("Received EOF on %p '%s'", vm, vm->def->name);
356
 
 
357
 
    virDomainObjLock(vm);
358
 
 
359
 
    if (!virDomainObjIsActive(vm)) {
360
 
        VIR_DEBUG("Domain %p is not active, ignoring EOF", vm);
361
 
        virDomainObjUnlock(vm);
362
 
        return;
363
 
    }
364
 
 
365
 
    priv = vm->privateData;
366
 
    if (!hasError && priv->monJSON && !priv->gotShutdown) {
367
 
        VIR_DEBUG("Monitor connection to '%s' closed without SHUTDOWN event; "
368
 
                  "assuming the domain crashed", vm->def->name);
369
 
        hasError = 1;
370
 
    }
371
 
 
372
 
    event = virDomainEventNewFromObj(vm,
373
 
                                     VIR_DOMAIN_EVENT_STOPPED,
374
 
                                     hasError ?
375
 
                                     VIR_DOMAIN_EVENT_STOPPED_FAILED :
376
 
                                     VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
377
 
 
378
 
    qemudShutdownVMDaemon(driver, vm, 0);
379
 
    qemuDomainStopAudit(vm, hasError ? "failed" : "shutdown");
380
 
 
381
 
    if (!vm->persistent)
382
 
        virDomainRemoveInactive(&driver->domains, vm);
383
 
    else
384
 
        virDomainObjUnlock(vm);
385
 
 
386
 
    if (event) {
387
 
        qemuDriverLock(driver);
388
 
        qemuDomainEventQueue(driver, event);
389
 
        qemuDriverUnlock(driver);
390
 
    }
391
 
}
392
 
 
393
 
 
394
 
static virDomainDiskDefPtr
395
 
findDomainDiskByPath(virDomainObjPtr vm,
396
 
                     const char *path)
397
 
{
398
 
    int i;
399
 
 
400
 
    for (i = 0; i < vm->def->ndisks; i++) {
401
 
        virDomainDiskDefPtr disk;
402
 
 
403
 
        disk = vm->def->disks[i];
404
 
        if (disk->src != NULL && STREQ(disk->src, path))
405
 
            return disk;
406
 
    }
407
 
 
408
 
    qemuReportError(VIR_ERR_INTERNAL_ERROR,
409
 
                    _("no disk found with path %s"),
410
 
                    path);
411
 
    return NULL;
412
 
}
413
 
 
414
 
static virDomainDiskDefPtr
415
 
findDomainDiskByAlias(virDomainObjPtr vm,
416
 
                      const char *alias)
417
 
{
418
 
    int i;
419
 
 
420
 
    if (STRPREFIX(alias, QEMU_DRIVE_HOST_PREFIX))
421
 
        alias += strlen(QEMU_DRIVE_HOST_PREFIX);
422
 
 
423
 
    for (i = 0; i < vm->def->ndisks; i++) {
424
 
        virDomainDiskDefPtr disk;
425
 
 
426
 
        disk = vm->def->disks[i];
427
 
        if (disk->info.alias != NULL && STREQ(disk->info.alias, alias))
428
 
            return disk;
429
 
    }
430
 
 
431
 
    qemuReportError(VIR_ERR_INTERNAL_ERROR,
432
 
                    _("no disk found with alias %s"),
433
 
                    alias);
434
 
    return NULL;
435
 
}
436
 
 
437
 
static int
438
 
getVolumeQcowPassphrase(virConnectPtr conn,
439
 
                        virDomainDiskDefPtr disk,
440
 
                        char **secretRet,
441
 
                        size_t *secretLen)
442
 
{
443
 
    virSecretPtr secret;
444
 
    char *passphrase;
445
 
    unsigned char *data;
446
 
    size_t size;
447
 
    int ret = -1;
448
 
    virStorageEncryptionPtr enc;
449
 
 
450
 
    if (!disk->encryption) {
451
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
452
 
                        _("disk %s does not have any encryption information"),
453
 
                        disk->src);
454
 
        return -1;
455
 
    }
456
 
    enc = disk->encryption;
457
 
 
458
 
    if (!conn) {
459
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
460
 
                        "%s", _("cannot find secrets without a connection"));
461
 
        goto cleanup;
462
 
    }
463
 
 
464
 
    if (conn->secretDriver == NULL ||
465
 
        conn->secretDriver->lookupByUUID == NULL ||
466
 
        conn->secretDriver->getValue == NULL) {
467
 
        qemuReportError(VIR_ERR_NO_SUPPORT, "%s",
468
 
                        _("secret storage not supported"));
469
 
        goto cleanup;
470
 
    }
471
 
 
472
 
    if (enc->format != VIR_STORAGE_ENCRYPTION_FORMAT_QCOW ||
473
 
        enc->nsecrets != 1 ||
474
 
        enc->secrets[0]->type !=
475
 
        VIR_STORAGE_ENCRYPTION_SECRET_TYPE_PASSPHRASE) {
476
 
        qemuReportError(VIR_ERR_XML_ERROR,
477
 
                        _("invalid <encryption> for volume %s"), disk->src);
478
 
        goto cleanup;
479
 
    }
480
 
 
481
 
    secret = conn->secretDriver->lookupByUUID(conn,
482
 
                                              enc->secrets[0]->uuid);
483
 
    if (secret == NULL)
484
 
        goto cleanup;
485
 
    data = conn->secretDriver->getValue(secret, &size,
486
 
                                        VIR_SECRET_GET_VALUE_INTERNAL_CALL);
487
 
    virUnrefSecret(secret);
488
 
    if (data == NULL)
489
 
        goto cleanup;
490
 
 
491
 
    if (memchr(data, '\0', size) != NULL) {
492
 
        memset(data, 0, size);
493
 
        VIR_FREE(data);
494
 
        qemuReportError(VIR_ERR_XML_ERROR,
495
 
                        _("format='qcow' passphrase for %s must not contain a "
496
 
                          "'\\0'"), disk->src);
497
 
        goto cleanup;
498
 
    }
499
 
 
500
 
    if (VIR_ALLOC_N(passphrase, size + 1) < 0) {
501
 
        memset(data, 0, size);
502
 
        VIR_FREE(data);
503
 
        virReportOOMError();
504
 
        goto cleanup;
505
 
    }
506
 
    memcpy(passphrase, data, size);
507
 
    passphrase[size] = '\0';
508
 
 
509
 
    memset(data, 0, size);
510
 
    VIR_FREE(data);
511
 
 
512
 
    *secretRet = passphrase;
513
 
    *secretLen = size;
514
 
 
515
 
    ret = 0;
516
 
 
517
 
cleanup:
518
 
    return ret;
519
 
}
520
 
 
521
 
static int
522
 
findVolumeQcowPassphrase(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
523
 
                         virConnectPtr conn,
524
 
                         virDomainObjPtr vm,
525
 
                         const char *path,
526
 
                         char **secretRet,
527
 
                         size_t *secretLen)
528
 
{
529
 
    virDomainDiskDefPtr disk;
530
 
    int ret = -1;
531
 
 
532
 
    virDomainObjLock(vm);
533
 
    disk = findDomainDiskByPath(vm, path);
534
 
 
535
 
    if (!disk)
536
 
        goto cleanup;
537
 
 
538
 
    ret = getVolumeQcowPassphrase(conn, disk, secretRet, secretLen);
539
 
 
540
 
cleanup:
541
 
    virDomainObjUnlock(vm);
542
 
    return ret;
543
 
}
544
 
 
545
 
 
546
 
static int
547
 
qemuHandleDomainReset(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
548
 
                      virDomainObjPtr vm)
549
 
{
550
 
    struct qemud_driver *driver = qemu_driver;
551
 
    virDomainEventPtr event;
552
 
 
553
 
    virDomainObjLock(vm);
554
 
    event = virDomainEventRebootNewFromObj(vm);
555
 
    virDomainObjUnlock(vm);
556
 
 
557
 
    if (event) {
558
 
        qemuDriverLock(driver);
559
 
        qemuDomainEventQueue(driver, event);
560
 
        qemuDriverUnlock(driver);
561
 
    }
562
 
 
563
 
    return 0;
564
 
}
565
 
 
566
 
 
567
 
static int
568
 
qemuHandleDomainShutdown(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
569
 
                         virDomainObjPtr vm)
570
 
{
571
 
    virDomainObjLock(vm);
572
 
    ((qemuDomainObjPrivatePtr) vm->privateData)->gotShutdown = true;
573
 
    virDomainObjUnlock(vm);
574
 
 
575
 
    return 0;
576
 
}
577
 
 
578
 
 
579
 
static int
580
 
qemuHandleDomainStop(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
581
 
                     virDomainObjPtr vm)
582
 
{
583
 
    struct qemud_driver *driver = qemu_driver;
584
 
    virDomainEventPtr event = NULL;
585
 
 
586
 
    virDomainObjLock(vm);
587
 
    if (vm->state == VIR_DOMAIN_RUNNING) {
588
 
        VIR_DEBUG("Transitioned guest %s to paused state due to unknown event", vm->def->name);
589
 
 
590
 
        vm->state = VIR_DOMAIN_PAUSED;
591
 
        event = virDomainEventNewFromObj(vm,
592
 
                                         VIR_DOMAIN_EVENT_SUSPENDED,
593
 
                                         VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
594
 
 
595
 
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
596
 
            VIR_WARN("Unable to save status on vm %s after IO error", vm->def->name);
597
 
    }
598
 
    virDomainObjUnlock(vm);
599
 
 
600
 
    if (event) {
601
 
        qemuDriverLock(driver);
602
 
        if (event)
603
 
            qemuDomainEventQueue(driver, event);
604
 
        qemuDriverUnlock(driver);
605
 
    }
606
 
 
607
 
    return 0;
608
 
}
609
 
 
610
 
 
611
 
static int
612
 
qemuHandleDomainRTCChange(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
613
 
                          virDomainObjPtr vm,
614
 
                          long long offset)
615
 
{
616
 
    struct qemud_driver *driver = qemu_driver;
617
 
    virDomainEventPtr event;
618
 
 
619
 
    virDomainObjLock(vm);
620
 
    event = virDomainEventRTCChangeNewFromObj(vm, offset);
621
 
 
622
 
    if (vm->def->clock.offset == VIR_DOMAIN_CLOCK_OFFSET_VARIABLE)
623
 
        vm->def->clock.data.adjustment = offset;
624
 
 
625
 
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
626
 
        VIR_WARN0("unable to save domain status with RTC change");
627
 
 
628
 
    virDomainObjUnlock(vm);
629
 
 
630
 
    if (event) {
631
 
        qemuDriverLock(driver);
632
 
        qemuDomainEventQueue(driver, event);
633
 
        qemuDriverUnlock(driver);
634
 
    }
635
 
 
636
 
    return 0;
637
 
}
638
 
 
639
 
 
640
 
static int
641
 
qemuHandleDomainWatchdog(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
642
 
                         virDomainObjPtr vm,
643
 
                         int action)
644
 
{
645
 
    struct qemud_driver *driver = qemu_driver;
646
 
    virDomainEventPtr watchdogEvent = NULL;
647
 
    virDomainEventPtr lifecycleEvent = NULL;
648
 
 
649
 
    virDomainObjLock(vm);
650
 
    watchdogEvent = virDomainEventWatchdogNewFromObj(vm, action);
651
 
 
652
 
    if (action == VIR_DOMAIN_EVENT_WATCHDOG_PAUSE &&
653
 
        vm->state == VIR_DOMAIN_RUNNING) {
654
 
        VIR_DEBUG("Transitioned guest %s to paused state due to watchdog", vm->def->name);
655
 
 
656
 
        vm->state = VIR_DOMAIN_PAUSED;
657
 
        lifecycleEvent = virDomainEventNewFromObj(vm,
658
 
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
659
 
                                                  VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG);
660
 
 
661
 
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
662
 
            VIR_WARN("Unable to save status on vm %s after IO error", vm->def->name);
663
 
    }
664
 
 
665
 
    if (vm->def->watchdog->action == VIR_DOMAIN_WATCHDOG_ACTION_DUMP) {
666
 
        struct watchdogEvent *wdEvent;
667
 
        if (VIR_ALLOC(wdEvent) == 0) {
668
 
            wdEvent->action = VIR_DOMAIN_WATCHDOG_ACTION_DUMP;
669
 
            wdEvent->vm = vm;
670
 
            ignore_value(virThreadPoolSendJob(driver->workerPool, wdEvent));
671
 
        } else
672
 
            virReportOOMError();
673
 
    }
674
 
 
675
 
    virDomainObjUnlock(vm);
676
 
 
677
 
    if (watchdogEvent || lifecycleEvent) {
678
 
        qemuDriverLock(driver);
679
 
        if (watchdogEvent)
680
 
            qemuDomainEventQueue(driver, watchdogEvent);
681
 
        if (lifecycleEvent)
682
 
            qemuDomainEventQueue(driver, lifecycleEvent);
683
 
        qemuDriverUnlock(driver);
684
 
    }
685
 
 
686
 
    return 0;
687
 
}
688
 
 
689
 
 
690
 
static int
691
 
qemuHandleDomainIOError(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
692
 
                        virDomainObjPtr vm,
693
 
                        const char *diskAlias,
694
 
                        int action,
695
 
                        const char *reason)
696
 
{
697
 
    struct qemud_driver *driver = qemu_driver;
698
 
    virDomainEventPtr ioErrorEvent = NULL;
699
 
    virDomainEventPtr ioErrorEvent2 = NULL;
700
 
    virDomainEventPtr lifecycleEvent = NULL;
701
 
    const char *srcPath;
702
 
    const char *devAlias;
703
 
    virDomainDiskDefPtr disk;
704
 
 
705
 
    virDomainObjLock(vm);
706
 
    disk = findDomainDiskByAlias(vm, diskAlias);
707
 
 
708
 
    if (disk) {
709
 
        srcPath = disk->src;
710
 
        devAlias = disk->info.alias;
711
 
    } else {
712
 
        srcPath = "";
713
 
        devAlias = "";
714
 
    }
715
 
 
716
 
    ioErrorEvent = virDomainEventIOErrorNewFromObj(vm, srcPath, devAlias, action);
717
 
    ioErrorEvent2 = virDomainEventIOErrorReasonNewFromObj(vm, srcPath, devAlias, action, reason);
718
 
 
719
 
    if (action == VIR_DOMAIN_EVENT_IO_ERROR_PAUSE &&
720
 
        vm->state == VIR_DOMAIN_RUNNING) {
721
 
        VIR_DEBUG("Transitioned guest %s to paused state due to IO error", vm->def->name);
722
 
 
723
 
        vm->state = VIR_DOMAIN_PAUSED;
724
 
        lifecycleEvent = virDomainEventNewFromObj(vm,
725
 
                                                  VIR_DOMAIN_EVENT_SUSPENDED,
726
 
                                                  VIR_DOMAIN_EVENT_SUSPENDED_IOERROR);
727
 
 
728
 
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
729
 
            VIR_WARN("Unable to save status on vm %s after IO error", vm->def->name);
730
 
    }
731
 
    virDomainObjUnlock(vm);
732
 
 
733
 
    if (ioErrorEvent || ioErrorEvent2 || lifecycleEvent) {
734
 
        qemuDriverLock(driver);
735
 
        if (ioErrorEvent)
736
 
            qemuDomainEventQueue(driver, ioErrorEvent);
737
 
        if (ioErrorEvent2)
738
 
            qemuDomainEventQueue(driver, ioErrorEvent2);
739
 
        if (lifecycleEvent)
740
 
            qemuDomainEventQueue(driver, lifecycleEvent);
741
 
        qemuDriverUnlock(driver);
742
 
    }
743
 
 
744
 
    return 0;
745
 
}
746
 
 
747
 
 
748
 
static int
749
 
qemuHandleDomainGraphics(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
750
 
                         virDomainObjPtr vm,
751
 
                         int phase,
752
 
                         int localFamily,
753
 
                         const char *localNode,
754
 
                         const char *localService,
755
 
                         int remoteFamily,
756
 
                         const char *remoteNode,
757
 
                         const char *remoteService,
758
 
                         const char *authScheme,
759
 
                         const char *x509dname,
760
 
                         const char *saslUsername)
761
 
{
762
 
    struct qemud_driver *driver = qemu_driver;
763
 
    virDomainEventPtr event;
764
 
    virDomainEventGraphicsAddressPtr localAddr = NULL;
765
 
    virDomainEventGraphicsAddressPtr remoteAddr = NULL;
766
 
    virDomainEventGraphicsSubjectPtr subject = NULL;
767
 
    int i;
768
 
 
769
 
    virDomainObjLock(vm);
770
 
 
771
 
    if (VIR_ALLOC(localAddr) < 0)
772
 
        goto no_memory;
773
 
    localAddr->family = localFamily;
774
 
    if (!(localAddr->service = strdup(localService)) ||
775
 
        !(localAddr->node = strdup(localNode)))
776
 
        goto no_memory;
777
 
 
778
 
    if (VIR_ALLOC(remoteAddr) < 0)
779
 
        goto no_memory;
780
 
    remoteAddr->family = remoteFamily;
781
 
    if (!(remoteAddr->service = strdup(remoteService)) ||
782
 
        !(remoteAddr->node = strdup(remoteNode)))
783
 
        goto no_memory;
784
 
 
785
 
    if (VIR_ALLOC(subject) < 0)
786
 
        goto no_memory;
787
 
    if (x509dname) {
788
 
        if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0)
789
 
            goto no_memory;
790
 
        if (!(subject->identities[subject->nidentity].type = strdup("x509dname")) ||
791
 
            !(subject->identities[subject->nidentity].name = strdup(x509dname)))
792
 
            goto no_memory;
793
 
        subject->nidentity++;
794
 
    }
795
 
    if (saslUsername) {
796
 
        if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0)
797
 
            goto no_memory;
798
 
        if (!(subject->identities[subject->nidentity].type = strdup("saslUsername")) ||
799
 
            !(subject->identities[subject->nidentity].name = strdup(saslUsername)))
800
 
            goto no_memory;
801
 
        subject->nidentity++;
802
 
    }
803
 
 
804
 
    event = virDomainEventGraphicsNewFromObj(vm, phase, localAddr, remoteAddr, authScheme, subject);
805
 
    virDomainObjUnlock(vm);
806
 
 
807
 
    if (event) {
808
 
        qemuDriverLock(driver);
809
 
        qemuDomainEventQueue(driver, event);
810
 
        qemuDriverUnlock(driver);
811
 
    }
812
 
 
813
 
    return 0;
814
 
 
815
 
no_memory:
816
 
    virReportOOMError();
817
 
    if (localAddr) {
818
 
        VIR_FREE(localAddr->service);
819
 
        VIR_FREE(localAddr->node);
820
 
        VIR_FREE(localAddr);
821
 
    }
822
 
    if (remoteAddr) {
823
 
        VIR_FREE(remoteAddr->service);
824
 
        VIR_FREE(remoteAddr->node);
825
 
        VIR_FREE(remoteAddr);
826
 
    }
827
 
    if (subject) {
828
 
        for (i = 0 ; i < subject->nidentity ; i++) {
829
 
            VIR_FREE(subject->identities[i].type);
830
 
            VIR_FREE(subject->identities[i].name);
831
 
        }
832
 
        VIR_FREE(subject->identities);
833
 
        VIR_FREE(subject);
834
 
    }
835
 
 
836
 
    return -1;
837
 
}
838
 
 
839
 
 
840
 
static void qemuHandleMonitorDestroy(qemuMonitorPtr mon,
841
 
                                     virDomainObjPtr vm)
842
 
{
843
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
844
 
    if (priv->mon == mon)
845
 
        priv->mon = NULL;
846
 
    virDomainObjUnref(vm);
847
 
}
848
 
 
849
 
static qemuMonitorCallbacks monitorCallbacks = {
850
 
    .destroy = qemuHandleMonitorDestroy,
851
 
    .eofNotify = qemuHandleMonitorEOF,
852
 
    .diskSecretLookup = findVolumeQcowPassphrase,
853
 
    .domainShutdown = qemuHandleDomainShutdown,
854
 
    .domainStop = qemuHandleDomainStop,
855
 
    .domainReset = qemuHandleDomainReset,
856
 
    .domainRTCChange = qemuHandleDomainRTCChange,
857
 
    .domainWatchdog = qemuHandleDomainWatchdog,
858
 
    .domainIOError = qemuHandleDomainIOError,
859
 
    .domainGraphics = qemuHandleDomainGraphics,
860
 
};
861
 
 
862
 
static int
863
 
qemuConnectMonitor(struct qemud_driver *driver, virDomainObjPtr vm)
864
 
{
865
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
866
 
    int ret = -1;
867
 
 
868
 
    if (virSecurityManagerSetSocketLabel(driver->securityManager, vm) < 0) {
869
 
        VIR_ERROR(_("Failed to set security context for monitor for %s"),
870
 
                  vm->def->name);
871
 
        goto error;
872
 
    }
873
 
 
874
 
    /* Hold an extra reference because we can't allow 'vm' to be
875
 
     * deleted while the monitor is active */
876
 
    virDomainObjRef(vm);
877
 
 
878
 
    priv->mon = qemuMonitorOpen(vm,
879
 
                                priv->monConfig,
880
 
                                priv->monJSON,
881
 
                                &monitorCallbacks);
882
 
 
883
 
    if (priv->mon == NULL)
884
 
        virDomainObjUnref(vm);
885
 
 
886
 
    if (virSecurityManagerClearSocketLabel(driver->securityManager, vm) < 0) {
887
 
        VIR_ERROR(_("Failed to clear security context for monitor for %s"),
888
 
                  vm->def->name);
889
 
        goto error;
890
 
    }
891
 
 
892
 
    if (priv->mon == NULL) {
893
 
        VIR_INFO("Failed to connect monitor for %s", vm->def->name);
894
 
        goto error;
895
 
    }
896
 
 
897
 
 
898
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
899
 
    ret = qemuMonitorSetCapabilities(priv->mon);
900
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
901
 
 
902
 
error:
903
 
 
904
 
    return ret;
905
 
}
906
 
 
907
 
struct virReconnectDomainData {
908
 
    virConnectPtr conn;
909
 
    struct qemud_driver *driver;
910
 
};
911
 
/*
912
 
 * Open an existing VM's monitor, re-detect VCPU threads
913
 
 * and re-reserve the security labels in use
914
 
 */
915
 
static void
916
 
qemuReconnectDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
917
 
{
918
 
    virDomainObjPtr obj = payload;
919
 
    struct virReconnectDomainData *data = opaque;
920
 
    struct qemud_driver *driver = data->driver;
921
 
    qemuDomainObjPrivatePtr priv;
922
 
    unsigned long long qemuCmdFlags;
923
 
    virConnectPtr conn = data->conn;
924
 
 
925
 
    virDomainObjLock(obj);
926
 
 
927
 
    VIR_DEBUG("Reconnect monitor to %p '%s'", obj, obj->def->name);
928
 
 
929
 
    priv = obj->privateData;
930
 
 
931
 
    /* Hold an extra reference because we can't allow 'vm' to be
932
 
     * deleted if qemuConnectMonitor() failed */
933
 
    virDomainObjRef(obj);
934
 
 
935
 
    /* XXX check PID liveliness & EXE path */
936
 
    if (qemuConnectMonitor(driver, obj) < 0)
937
 
        goto error;
938
 
 
939
 
    if (qemuUpdateActivePciHostdevs(driver, obj->def) < 0) {
940
 
        goto error;
941
 
    }
942
 
 
943
 
    /* XXX we should be persisting the original flags in the XML
944
 
     * not re-detecting them, since the binary may have changed
945
 
     * since launch time */
946
 
    if (qemuCapsExtractVersionInfo(obj->def->emulator, obj->def->os.arch,
947
 
                                   NULL,
948
 
                                   &qemuCmdFlags) >= 0 &&
949
 
        (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
950
 
        priv->persistentAddrs = 1;
951
 
 
952
 
        if (!(priv->pciaddrs = qemuDomainPCIAddressSetCreate(obj->def)) ||
953
 
            qemuAssignDevicePCISlots(obj->def, priv->pciaddrs) < 0)
954
 
            goto error;
955
 
    }
956
 
 
957
 
    if (virSecurityManagerReserveLabel(driver->securityManager, obj) < 0)
958
 
        goto error;
959
 
 
960
 
    if (qemudVMFiltersInstantiate(conn, obj->def))
961
 
        goto error;
962
 
 
963
 
    if (obj->def->id >= driver->nextvmid)
964
 
        driver->nextvmid = obj->def->id + 1;
965
 
 
966
 
    if (virDomainObjUnref(obj) > 0)
967
 
        virDomainObjUnlock(obj);
968
 
    return;
969
 
 
970
 
error:
971
 
    if (!virDomainObjIsActive(obj)) {
972
 
        if (virDomainObjUnref(obj) > 0)
973
 
            virDomainObjUnlock(obj);
974
 
        return;
975
 
    }
976
 
 
977
 
    if (virDomainObjUnref(obj) > 0) {
978
 
        /* We can't get the monitor back, so must kill the VM
979
 
         * to remove danger of it ending up running twice if
980
 
         * user tries to start it again later */
981
 
        qemudShutdownVMDaemon(driver, obj, 0);
982
 
        if (!obj->persistent)
983
 
            virDomainRemoveInactive(&driver->domains, obj);
984
 
        else
985
 
            virDomainObjUnlock(obj);
986
 
    }
987
 
}
988
 
 
989
 
/**
990
 
 * qemudReconnectDomains
991
 
 *
992
 
 * Try to re-open the resources for live VMs that we care
993
 
 * about.
994
 
 */
995
 
static void
996
 
qemuReconnectDomains(virConnectPtr conn, struct qemud_driver *driver)
997
 
{
998
 
    struct virReconnectDomainData data = {conn, driver};
999
 
    virHashForEach(driver->domains.objs, qemuReconnectDomain, &data);
1000
 
}
1001
 
 
1002
 
 
1003
 
static int
1004
 
qemuSecurityInit(struct qemud_driver *driver)
1005
 
{
1006
 
    virSecurityManagerPtr mgr = virSecurityManagerNew(driver->securityDriverName,
1007
 
                                                      driver->allowDiskFormatProbing);
1008
 
    if (!mgr)
1009
 
        goto error;
1010
 
 
1011
 
    if (driver->privileged) {
1012
 
        virSecurityManagerPtr dac = virSecurityManagerNewDAC(driver->user,
1013
 
                                                             driver->group,
1014
 
                                                             driver->allowDiskFormatProbing,
1015
 
                                                             driver->dynamicOwnership);
1016
 
        if (!dac)
1017
 
            goto error;
1018
 
 
1019
 
        if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
1020
 
                                                                   dac)))
1021
 
            goto error;
1022
 
    } else {
1023
 
        driver->securityManager = mgr;
1024
 
    }
1025
 
 
1026
 
    return 0;
1027
 
 
1028
 
error:
1029
 
    VIR_ERROR0(_("Failed to initialize security drivers"));
1030
 
    virSecurityManagerFree(mgr);
1031
 
    return -1;
1032
 
}
1033
 
 
1034
 
 
1035
 
static virCapsPtr
1036
 
qemuCreateCapabilities(virCapsPtr oldcaps,
1037
 
                       struct qemud_driver *driver)
1038
 
{
1039
 
    virCapsPtr caps;
1040
 
 
1041
 
    /* Basic host arch / guest machine capabilities */
1042
 
    if (!(caps = qemuCapsInit(oldcaps))) {
1043
 
        virReportOOMError();
1044
 
        return NULL;
1045
 
    }
1046
 
 
1047
 
    if (driver->allowDiskFormatProbing) {
1048
 
        caps->defaultDiskDriverName = NULL;
1049
 
        caps->defaultDiskDriverType = NULL;
1050
 
    } else {
1051
 
        caps->defaultDiskDriverName = "qemu";
1052
 
        caps->defaultDiskDriverType = "raw";
1053
 
    }
1054
 
 
1055
 
    qemuDomainSetPrivateDataHooks(caps);
1056
 
    qemuDomainSetNamespaceHooks(caps);
1057
 
 
1058
 
    if (virGetHostUUID(caps->host.host_uuid)) {
1059
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
1060
 
                         "%s", _("cannot get the host uuid"));
1061
 
        goto err_exit;
1062
 
    }
1063
 
 
1064
 
    /* Security driver data */
1065
 
    const char *doi, *model;
1066
 
 
1067
 
    doi = virSecurityManagerGetDOI(driver->securityManager);
1068
 
    model = virSecurityManagerGetModel(driver->securityManager);
1069
 
    if (STRNEQ(model, "none")) {
1070
 
        if (!(caps->host.secModel.model = strdup(model)))
1071
 
            goto no_memory;
1072
 
        if (!(caps->host.secModel.doi = strdup(doi)))
1073
 
            goto no_memory;
1074
 
    }
1075
 
 
1076
 
    VIR_DEBUG("Initialized caps for security driver \"%s\" with "
1077
 
              "DOI \"%s\"", model, doi);
1078
 
 
1079
 
    return caps;
1080
 
 
1081
 
no_memory:
1082
 
    virReportOOMError();
1083
 
err_exit:
1084
 
    virCapabilitiesFree(caps);
1085
 
    return NULL;
1086
 
}
1087
 
 
1088
 
static void qemuDomainSnapshotLoad(void *payload,
1089
 
                                   const char *name ATTRIBUTE_UNUSED,
1090
 
                                   void *data)
1091
 
{
1092
 
    virDomainObjPtr vm = (virDomainObjPtr)payload;
1093
 
    char *baseDir = (char *)data;
1094
 
    char *snapDir = NULL;
1095
 
    DIR *dir = NULL;
1096
 
    struct dirent *entry;
1097
 
    char *xmlStr;
1098
 
    int ret;
1099
 
    char *fullpath;
1100
 
    virDomainSnapshotDefPtr def = NULL;
1101
 
    char ebuf[1024];
1102
 
 
1103
 
    virDomainObjLock(vm);
1104
 
    if (virAsprintf(&snapDir, "%s/%s", baseDir, vm->def->name) < 0) {
1105
 
        VIR_ERROR(_("Failed to allocate memory for snapshot directory for domain %s"),
1106
 
                   vm->def->name);
1107
 
        goto cleanup;
1108
 
    }
1109
 
 
1110
 
    VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
1111
 
             snapDir);
1112
 
 
1113
 
    if (!(dir = opendir(snapDir))) {
1114
 
        if (errno != ENOENT)
1115
 
            VIR_ERROR(_("Failed to open snapshot directory %s for domain %s: %s"),
1116
 
                      snapDir, vm->def->name,
1117
 
                      virStrerror(errno, ebuf, sizeof(ebuf)));
1118
 
        goto cleanup;
1119
 
    }
1120
 
 
1121
 
    while ((entry = readdir(dir))) {
1122
 
        if (entry->d_name[0] == '.')
1123
 
            continue;
1124
 
 
1125
 
        /* NB: ignoring errors, so one malformed config doesn't
1126
 
           kill the whole process */
1127
 
        VIR_INFO("Loading snapshot file '%s'", entry->d_name);
1128
 
 
1129
 
        if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
1130
 
            VIR_ERROR0(_("Failed to allocate memory for path"));
1131
 
            continue;
1132
 
        }
1133
 
 
1134
 
        ret = virFileReadAll(fullpath, 1024*1024*1, &xmlStr);
1135
 
        if (ret < 0) {
1136
 
            /* Nothing we can do here, skip this one */
1137
 
            VIR_ERROR(_("Failed to read snapshot file %s: %s"), fullpath,
1138
 
                      virStrerror(errno, ebuf, sizeof(ebuf)));
1139
 
            VIR_FREE(fullpath);
1140
 
            continue;
1141
 
        }
1142
 
 
1143
 
        def = virDomainSnapshotDefParseString(xmlStr, 0);
1144
 
        if (def == NULL) {
1145
 
            /* Nothing we can do here, skip this one */
1146
 
            VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"), fullpath);
1147
 
            VIR_FREE(fullpath);
1148
 
            VIR_FREE(xmlStr);
1149
 
            continue;
1150
 
        }
1151
 
 
1152
 
        virDomainSnapshotAssignDef(&vm->snapshots, def);
1153
 
 
1154
 
        VIR_FREE(fullpath);
1155
 
        VIR_FREE(xmlStr);
1156
 
    }
1157
 
 
1158
 
    /* FIXME: qemu keeps internal track of snapshots.  We can get access
1159
 
     * to this info via the "info snapshots" monitor command for running
1160
 
     * domains, or via "qemu-img snapshot -l" for shutoff domains.  It would
1161
 
     * be nice to update our internal state based on that, but there is a
1162
 
     * a problem.  qemu doesn't track all of the same metadata that we do.
1163
 
     * In particular we wouldn't be able to fill in the <parent>, which is
1164
 
     * pretty important in our metadata.
1165
 
     */
1166
 
 
1167
 
    virResetLastError();
1168
 
 
1169
 
cleanup:
1170
 
    if (dir)
1171
 
        closedir(dir);
1172
 
    VIR_FREE(snapDir);
1173
 
    virDomainObjUnlock(vm);
1174
 
}
1175
 
 
1176
 
/**
1177
 
 * qemudStartup:
1178
 
 *
1179
 
 * Initialization function for the QEmu daemon
1180
 
 */
1181
 
static int
1182
 
qemudStartup(int privileged) {
1183
 
    char *base = NULL;
1184
 
    char *driverConf = NULL;
1185
 
    int rc;
1186
 
    virConnectPtr conn = NULL;
1187
 
 
1188
 
    if (VIR_ALLOC(qemu_driver) < 0)
1189
 
        return -1;
1190
 
 
1191
 
    if (virMutexInit(&qemu_driver->lock) < 0) {
1192
 
        VIR_ERROR0(_("cannot initialize mutex"));
1193
 
        VIR_FREE(qemu_driver);
1194
 
        return -1;
1195
 
    }
1196
 
    qemuDriverLock(qemu_driver);
1197
 
    qemu_driver->privileged = privileged;
1198
 
 
1199
 
    /* Don't have a dom0 so start from 1 */
1200
 
    qemu_driver->nextvmid = 1;
1201
 
 
1202
 
    if (virDomainObjListInit(&qemu_driver->domains) < 0)
1203
 
        goto out_of_memory;
1204
 
 
1205
 
    /* Init callback list */
1206
 
    if (VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
1207
 
        goto out_of_memory;
1208
 
    if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
1209
 
        goto out_of_memory;
1210
 
 
1211
 
    if ((qemu_driver->domainEventTimer =
1212
 
         virEventAddTimeout(-1, qemuDomainEventFlush, qemu_driver, NULL)) < 0)
1213
 
        goto error;
1214
 
 
1215
 
    /* Allocate bitmap for vnc port reservation */
1216
 
    if ((qemu_driver->reservedVNCPorts =
1217
 
         virBitmapAlloc(QEMU_VNC_PORT_MAX - QEMU_VNC_PORT_MIN)) == NULL)
1218
 
        goto out_of_memory;
1219
 
 
1220
 
    /* read the host sysinfo */
1221
 
    if (privileged)
1222
 
        qemu_driver->hostsysinfo = virSysinfoRead();
1223
 
 
1224
 
    if (privileged) {
1225
 
        if (virAsprintf(&qemu_driver->logDir,
1226
 
                        "%s/log/libvirt/qemu", LOCALSTATEDIR) == -1)
1227
 
            goto out_of_memory;
1228
 
 
1229
 
        if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
1230
 
            goto out_of_memory;
1231
 
 
1232
 
        if (virAsprintf(&qemu_driver->stateDir,
1233
 
                      "%s/run/libvirt/qemu", LOCALSTATEDIR) == -1)
1234
 
            goto out_of_memory;
1235
 
 
1236
 
        if (virAsprintf(&qemu_driver->libDir,
1237
 
                      "%s/lib/libvirt/qemu", LOCALSTATEDIR) == -1)
1238
 
            goto out_of_memory;
1239
 
 
1240
 
        if (virAsprintf(&qemu_driver->cacheDir,
1241
 
                      "%s/cache/libvirt/qemu", LOCALSTATEDIR) == -1)
1242
 
            goto out_of_memory;
1243
 
        if (virAsprintf(&qemu_driver->saveDir,
1244
 
                      "%s/lib/libvirt/qemu/save", LOCALSTATEDIR) == -1)
1245
 
            goto out_of_memory;
1246
 
        if (virAsprintf(&qemu_driver->snapshotDir,
1247
 
                        "%s/lib/libvirt/qemu/snapshot", LOCALSTATEDIR) == -1)
1248
 
            goto out_of_memory;
1249
 
        if (virAsprintf(&qemu_driver->autoDumpPath,
1250
 
                        "%s/lib/libvirt/qemu/dump", LOCALSTATEDIR) == -1)
1251
 
            goto out_of_memory;
1252
 
    } else {
1253
 
        uid_t uid = geteuid();
1254
 
        char *userdir = virGetUserDirectory(uid);
1255
 
        if (!userdir)
1256
 
            goto error;
1257
 
 
1258
 
        if (virAsprintf(&qemu_driver->logDir,
1259
 
                        "%s/.libvirt/qemu/log", userdir) == -1) {
1260
 
            VIR_FREE(userdir);
1261
 
            goto out_of_memory;
1262
 
        }
1263
 
 
1264
 
        if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
1265
 
            VIR_FREE(userdir);
1266
 
            goto out_of_memory;
1267
 
        }
1268
 
        VIR_FREE(userdir);
1269
 
 
1270
 
        if (virAsprintf(&qemu_driver->stateDir, "%s/qemu/run", base) == -1)
1271
 
            goto out_of_memory;
1272
 
        if (virAsprintf(&qemu_driver->libDir, "%s/qemu/lib", base) == -1)
1273
 
            goto out_of_memory;
1274
 
        if (virAsprintf(&qemu_driver->cacheDir, "%s/qemu/cache", base) == -1)
1275
 
            goto out_of_memory;
1276
 
        if (virAsprintf(&qemu_driver->saveDir, "%s/qemu/save", base) == -1)
1277
 
            goto out_of_memory;
1278
 
        if (virAsprintf(&qemu_driver->snapshotDir, "%s/qemu/snapshot", base) == -1)
1279
 
            goto out_of_memory;
1280
 
        if (virAsprintf(&qemu_driver->autoDumpPath, "%s/qemu/dump", base) == -1)
1281
 
            goto out_of_memory;
1282
 
    }
1283
 
 
1284
 
    if (virFileMakePath(qemu_driver->stateDir) != 0) {
1285
 
        char ebuf[1024];
1286
 
        VIR_ERROR(_("Failed to create state dir '%s': %s"),
1287
 
                  qemu_driver->stateDir, virStrerror(errno, ebuf, sizeof ebuf));
1288
 
        goto error;
1289
 
    }
1290
 
    if (virFileMakePath(qemu_driver->libDir) != 0) {
1291
 
        char ebuf[1024];
1292
 
        VIR_ERROR(_("Failed to create lib dir '%s': %s"),
1293
 
                  qemu_driver->libDir, virStrerror(errno, ebuf, sizeof ebuf));
1294
 
        goto error;
1295
 
    }
1296
 
    if (virFileMakePath(qemu_driver->cacheDir) != 0) {
1297
 
        char ebuf[1024];
1298
 
        VIR_ERROR(_("Failed to create cache dir '%s': %s"),
1299
 
                  qemu_driver->cacheDir, virStrerror(errno, ebuf, sizeof ebuf));
1300
 
        goto error;
1301
 
    }
1302
 
    if (virFileMakePath(qemu_driver->saveDir) != 0) {
1303
 
        char ebuf[1024];
1304
 
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
1305
 
                  qemu_driver->saveDir, virStrerror(errno, ebuf, sizeof ebuf));
1306
 
        goto error;
1307
 
    }
1308
 
    if (virFileMakePath(qemu_driver->snapshotDir) != 0) {
1309
 
        char ebuf[1024];
1310
 
        VIR_ERROR(_("Failed to create save dir '%s': %s"),
1311
 
                  qemu_driver->snapshotDir, virStrerror(errno, ebuf, sizeof ebuf));
1312
 
        goto error;
1313
 
    }
1314
 
    if (virFileMakePath(qemu_driver->autoDumpPath) != 0) {
1315
 
        char ebuf[1024];
1316
 
        VIR_ERROR(_("Failed to create dump dir '%s': %s"),
1317
 
                  qemu_driver->autoDumpPath, virStrerror(errno, ebuf, sizeof ebuf));
1318
 
        goto error;
1319
 
    }
1320
 
 
1321
 
    /* Configuration paths are either ~/.libvirt/qemu/... (session) or
1322
 
     * /etc/libvirt/qemu/... (system).
1323
 
     */
1324
 
    if (virAsprintf(&driverConf, "%s/qemu.conf", base) < 0 ||
1325
 
        virAsprintf(&qemu_driver->configDir, "%s/qemu", base) < 0 ||
1326
 
        virAsprintf(&qemu_driver->autostartDir, "%s/qemu/autostart", base) < 0)
1327
 
        goto out_of_memory;
1328
 
 
1329
 
    VIR_FREE(base);
1330
 
 
1331
 
    rc = virCgroupForDriver("qemu", &qemu_driver->cgroup, privileged, 1);
1332
 
    if (rc < 0) {
1333
 
        char buf[1024];
1334
 
        VIR_INFO("Unable to create cgroup for driver: %s, disabling cgroups",
1335
 
                 virStrerror(-rc, buf, sizeof(buf)));
1336
 
    }
1337
 
 
1338
 
    if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
1339
 
        goto error;
1340
 
    }
1341
 
    VIR_FREE(driverConf);
1342
 
 
1343
 
    if (qemuSecurityInit(qemu_driver) < 0)
1344
 
        goto error;
1345
 
 
1346
 
    if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
1347
 
                                                    qemu_driver)) == NULL)
1348
 
        goto error;
1349
 
 
1350
 
    if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
1351
 
        goto error;
1352
 
 
1353
 
    if (privileged) {
1354
 
        if (chown(qemu_driver->libDir, qemu_driver->user, qemu_driver->group) < 0) {
1355
 
            virReportSystemError(errno,
1356
 
                                 _("unable to set ownership of '%s' to user %d:%d"),
1357
 
                                 qemu_driver->libDir, qemu_driver->user, qemu_driver->group);
1358
 
            goto error;
1359
 
        }
1360
 
        if (chown(qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group) < 0) {
1361
 
            virReportSystemError(errno,
1362
 
                                 _("unable to set ownership of '%s' to %d:%d"),
1363
 
                                 qemu_driver->cacheDir, qemu_driver->user, qemu_driver->group);
1364
 
            goto error;
1365
 
        }
1366
 
        if (chown(qemu_driver->saveDir, qemu_driver->user, qemu_driver->group) < 0) {
1367
 
            virReportSystemError(errno,
1368
 
                                 _("unable to set ownership of '%s' to %d:%d"),
1369
 
                                 qemu_driver->saveDir, qemu_driver->user, qemu_driver->group);
1370
 
            goto error;
1371
 
        }
1372
 
        if (chown(qemu_driver->snapshotDir, qemu_driver->user, qemu_driver->group) < 0) {
1373
 
            virReportSystemError(errno,
1374
 
                                 _("unable to set ownership of '%s' to %d:%d"),
1375
 
                                 qemu_driver->snapshotDir, qemu_driver->user, qemu_driver->group);
1376
 
            goto error;
1377
 
        }
1378
 
    }
1379
 
 
1380
 
    /* If hugetlbfs is present, then we need to create a sub-directory within
1381
 
     * it, since we can't assume the root mount point has permissions that
1382
 
     * will let our spawned QEMU instances use it.
1383
 
     *
1384
 
     * NB the check for '/', since user may config "" to disable hugepages
1385
 
     * even when mounted
1386
 
     */
1387
 
    if (qemu_driver->hugetlbfs_mount &&
1388
 
        qemu_driver->hugetlbfs_mount[0] == '/') {
1389
 
        char *mempath = NULL;
1390
 
        if (virAsprintf(&mempath, "%s/libvirt/qemu", qemu_driver->hugetlbfs_mount) < 0)
1391
 
            goto out_of_memory;
1392
 
 
1393
 
        if ((rc = virFileMakePath(mempath)) != 0) {
1394
 
            virReportSystemError(rc,
1395
 
                                 _("unable to create hugepage path %s"), mempath);
1396
 
            VIR_FREE(mempath);
1397
 
            goto error;
1398
 
        }
1399
 
        if (qemu_driver->privileged &&
1400
 
            chown(mempath, qemu_driver->user, qemu_driver->group) < 0) {
1401
 
            virReportSystemError(errno,
1402
 
                                 _("unable to set ownership on %s to %d:%d"),
1403
 
                                 mempath, qemu_driver->user, qemu_driver->group);
1404
 
            VIR_FREE(mempath);
1405
 
            goto error;
1406
 
        }
1407
 
 
1408
 
        qemu_driver->hugepage_path = mempath;
1409
 
    }
1410
 
 
1411
 
    /* Get all the running persistent or transient configs first */
1412
 
    if (virDomainLoadAllConfigs(qemu_driver->caps,
1413
 
                                &qemu_driver->domains,
1414
 
                                qemu_driver->stateDir,
1415
 
                                NULL,
1416
 
                                1, NULL, NULL) < 0)
1417
 
        goto error;
1418
 
 
1419
 
    conn = virConnectOpen(qemu_driver->privileged ?
1420
 
                          "qemu:///system" :
1421
 
                          "qemu:///session");
1422
 
 
1423
 
    qemuReconnectDomains(conn, qemu_driver);
1424
 
 
1425
 
    /* Then inactive persistent configs */
1426
 
    if (virDomainLoadAllConfigs(qemu_driver->caps,
1427
 
                                &qemu_driver->domains,
1428
 
                                qemu_driver->configDir,
1429
 
                                qemu_driver->autostartDir,
1430
 
                                0, NULL, NULL) < 0)
1431
 
        goto error;
1432
 
 
1433
 
 
1434
 
    virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
1435
 
                   qemu_driver->snapshotDir);
1436
 
 
1437
 
    qemuDriverUnlock(qemu_driver);
1438
 
 
1439
 
    qemudAutostartConfigs(qemu_driver);
1440
 
 
1441
 
    qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
1442
 
    if (!qemu_driver->workerPool)
1443
 
        goto error;
1444
 
 
1445
 
    if (conn)
1446
 
        virConnectClose(conn);
1447
 
 
1448
 
    return 0;
1449
 
 
1450
 
out_of_memory:
1451
 
    virReportOOMError();
1452
 
error:
1453
 
    if (qemu_driver)
1454
 
        qemuDriverUnlock(qemu_driver);
1455
 
    if (conn)
1456
 
        virConnectClose(conn);
1457
 
    VIR_FREE(base);
1458
 
    VIR_FREE(driverConf);
1459
 
    qemudShutdown();
1460
 
    return -1;
1461
 
}
1462
 
 
1463
 
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
1464
 
{
1465
 
    struct qemud_driver *driver = opaque;
1466
 
 
1467
 
    if (newVM) {
1468
 
        virDomainEventPtr event =
1469
 
            virDomainEventNewFromObj(vm,
1470
 
                                     VIR_DOMAIN_EVENT_DEFINED,
1471
 
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED);
1472
 
        if (event)
1473
 
            qemuDomainEventQueue(driver, event);
1474
 
    }
1475
 
}
1476
 
 
1477
 
/**
1478
 
 * qemudReload:
1479
 
 *
1480
 
 * Function to restart the QEmu daemon, it will recheck the configuration
1481
 
 * files and update its state and the networking
1482
 
 */
1483
 
static int
1484
 
qemudReload(void) {
1485
 
    if (!qemu_driver)
1486
 
        return 0;
1487
 
 
1488
 
    qemuDriverLock(qemu_driver);
1489
 
    virDomainLoadAllConfigs(qemu_driver->caps,
1490
 
                            &qemu_driver->domains,
1491
 
                            qemu_driver->configDir,
1492
 
                            qemu_driver->autostartDir,
1493
 
                            0, qemudNotifyLoadDomain, qemu_driver);
1494
 
    qemuDriverUnlock(qemu_driver);
1495
 
 
1496
 
    qemudAutostartConfigs(qemu_driver);
1497
 
 
1498
 
    return 0;
1499
 
}
1500
 
 
1501
 
/**
1502
 
 * qemudActive:
1503
 
 *
1504
 
 * Checks if the QEmu daemon is active, i.e. has an active domain or
1505
 
 * an active network
1506
 
 *
1507
 
 * Returns 1 if active, 0 otherwise
1508
 
 */
1509
 
static int
1510
 
qemudActive(void) {
1511
 
    int active = 0;
1512
 
 
1513
 
    if (!qemu_driver)
1514
 
        return 0;
1515
 
 
1516
 
    /* XXX having to iterate here is not great because it requires many locks */
1517
 
    qemuDriverLock(qemu_driver);
1518
 
    active = virDomainObjListNumOfDomains(&qemu_driver->domains, 1);
1519
 
    qemuDriverUnlock(qemu_driver);
1520
 
    return active;
1521
 
}
1522
 
 
1523
 
/**
1524
 
 * qemudShutdown:
1525
 
 *
1526
 
 * Shutdown the QEmu daemon, it will stop all active domains and networks
1527
 
 */
1528
 
static int
1529
 
qemudShutdown(void) {
1530
 
    int i;
1531
 
 
1532
 
    if (!qemu_driver)
1533
 
        return -1;
1534
 
 
1535
 
    qemuDriverLock(qemu_driver);
1536
 
    pciDeviceListFree(qemu_driver->activePciHostdevs);
1537
 
    virCapabilitiesFree(qemu_driver->caps);
1538
 
 
1539
 
    virDomainObjListDeinit(&qemu_driver->domains);
1540
 
    virBitmapFree(qemu_driver->reservedVNCPorts);
1541
 
 
1542
 
    virSysinfoDefFree(qemu_driver->hostsysinfo);
1543
 
 
1544
 
    VIR_FREE(qemu_driver->configDir);
1545
 
    VIR_FREE(qemu_driver->autostartDir);
1546
 
    VIR_FREE(qemu_driver->logDir);
1547
 
    VIR_FREE(qemu_driver->stateDir);
1548
 
    VIR_FREE(qemu_driver->libDir);
1549
 
    VIR_FREE(qemu_driver->cacheDir);
1550
 
    VIR_FREE(qemu_driver->saveDir);
1551
 
    VIR_FREE(qemu_driver->snapshotDir);
1552
 
    VIR_FREE(qemu_driver->autoDumpPath);
1553
 
    VIR_FREE(qemu_driver->vncTLSx509certdir);
1554
 
    VIR_FREE(qemu_driver->vncListen);
1555
 
    VIR_FREE(qemu_driver->vncPassword);
1556
 
    VIR_FREE(qemu_driver->vncSASLdir);
1557
 
    VIR_FREE(qemu_driver->spiceTLSx509certdir);
1558
 
    VIR_FREE(qemu_driver->spiceListen);
1559
 
    VIR_FREE(qemu_driver->spicePassword);
1560
 
    VIR_FREE(qemu_driver->hugetlbfs_mount);
1561
 
    VIR_FREE(qemu_driver->hugepage_path);
1562
 
    VIR_FREE(qemu_driver->saveImageFormat);
1563
 
    VIR_FREE(qemu_driver->dumpImageFormat);
1564
 
 
1565
 
    virSecurityManagerFree(qemu_driver->securityManager);
1566
 
 
1567
 
    ebtablesContextFree(qemu_driver->ebtables);
1568
 
 
1569
 
    if (qemu_driver->cgroupDeviceACL) {
1570
 
        for (i = 0 ; qemu_driver->cgroupDeviceACL[i] != NULL ; i++)
1571
 
            VIR_FREE(qemu_driver->cgroupDeviceACL[i]);
1572
 
        VIR_FREE(qemu_driver->cgroupDeviceACL);
1573
 
    }
1574
 
 
1575
 
    /* Free domain callback list */
1576
 
    virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
1577
 
    virDomainEventQueueFree(qemu_driver->domainEventQueue);
1578
 
 
1579
 
    if (qemu_driver->domainEventTimer != -1)
1580
 
        virEventRemoveTimeout(qemu_driver->domainEventTimer);
1581
 
 
1582
 
    if (qemu_driver->brctl)
1583
 
        brShutdown(qemu_driver->brctl);
1584
 
 
1585
 
    virCgroupFree(&qemu_driver->cgroup);
1586
 
 
1587
 
    qemuDriverUnlock(qemu_driver);
1588
 
    virMutexDestroy(&qemu_driver->lock);
1589
 
    virThreadPoolFree(qemu_driver->workerPool);
1590
 
    VIR_FREE(qemu_driver);
1591
 
 
1592
 
    return 0;
1593
 
}
1594
 
 
1595
 
typedef int qemuLogHandleOutput(virDomainObjPtr vm,
1596
 
                                const char *output,
1597
 
                                int fd);
1598
 
 
1599
 
/*
1600
 
 * Returns -1 for error, 0 on success
1601
 
 */
1602
 
static int
1603
 
qemudReadLogOutput(virDomainObjPtr vm,
1604
 
                   int fd,
1605
 
                   char *buf,
1606
 
                   size_t buflen,
1607
 
                   qemuLogHandleOutput func,
1608
 
                   const char *what,
1609
 
                   int timeout)
1610
 
{
1611
 
    int retries = (timeout*10);
1612
 
    int got = 0;
1613
 
    buf[0] = '\0';
1614
 
 
1615
 
    while (retries) {
1616
 
        ssize_t func_ret, ret;
1617
 
        int isdead = 0;
1618
 
 
1619
 
        func_ret = func(vm, buf, fd);
1620
 
 
1621
 
        if (kill(vm->pid, 0) == -1 && errno == ESRCH)
1622
 
            isdead = 1;
1623
 
 
1624
 
        /* Any failures should be detected before we read the log, so we
1625
 
         * always have something useful to report on failure. */
1626
 
        ret = saferead(fd, buf+got, buflen-got-1);
1627
 
        if (ret < 0) {
1628
 
            virReportSystemError(errno,
1629
 
                                 _("Failure while reading %s log output"),
1630
 
                                 what);
1631
 
            return -1;
1632
 
        }
1633
 
 
1634
 
        got += ret;
1635
 
        buf[got] = '\0';
1636
 
        if (got == buflen-1) {
1637
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
1638
 
                            _("Out of space while reading %s log output: %s"),
1639
 
                            what, buf);
1640
 
            return -1;
1641
 
        }
1642
 
 
1643
 
        if (isdead) {
1644
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
1645
 
                            _("Process exited while reading %s log output: %s"),
1646
 
                            what, buf);
1647
 
            return -1;
1648
 
        }
1649
 
 
1650
 
        if (func_ret <= 0)
1651
 
            return func_ret;
1652
 
 
1653
 
        usleep(100*1000);
1654
 
        retries--;
1655
 
    }
1656
 
 
1657
 
    qemuReportError(VIR_ERR_INTERNAL_ERROR,
1658
 
                    _("Timed out while reading %s log output: %s"),
1659
 
                    what, buf);
1660
 
    return -1;
1661
 
}
1662
 
 
1663
 
 
1664
 
/*
1665
 
 * Look at a chunk of data from the QEMU stdout logs and try to
1666
 
 * find a TTY device, as indicated by a line like
1667
 
 *
1668
 
 * char device redirected to /dev/pts/3
1669
 
 *
1670
 
 * Returns -1 for error, 0 success, 1 continue reading
1671
 
 */
1672
 
static int
1673
 
qemudExtractTTYPath(const char *haystack,
1674
 
                    size_t *offset,
1675
 
                    char **path)
1676
 
{
1677
 
    static const char needle[] = "char device redirected to";
1678
 
    char *tmp, *dev;
1679
 
 
1680
 
    VIR_FREE(*path);
1681
 
    /* First look for our magic string */
1682
 
    if (!(tmp = strstr(haystack + *offset, needle))) {
1683
 
        return 1;
1684
 
    }
1685
 
    tmp += sizeof(needle);
1686
 
    dev = tmp;
1687
 
 
1688
 
    /*
1689
 
     * And look for first whitespace character and nul terminate
1690
 
     * to mark end of the pty path
1691
 
     */
1692
 
    while (*tmp) {
1693
 
        if (c_isspace(*tmp)) {
1694
 
            *path = strndup(dev, tmp-dev);
1695
 
            if (*path == NULL) {
1696
 
                virReportOOMError();
1697
 
                return -1;
1698
 
            }
1699
 
 
1700
 
            /* ... now further update offset till we get EOL */
1701
 
            *offset = tmp - haystack;
1702
 
            return 0;
1703
 
        }
1704
 
        tmp++;
1705
 
    }
1706
 
 
1707
 
    /*
1708
 
     * We found a path, but didn't find any whitespace,
1709
 
     * so it must be still incomplete - we should at
1710
 
     * least see a \n - indicate that we want to carry
1711
 
     * on trying again
1712
 
     */
1713
 
    return 1;
1714
 
}
1715
 
 
1716
 
static int
1717
 
qemudFindCharDevicePTYsMonitor(virDomainObjPtr vm,
1718
 
                               virHashTablePtr paths)
1719
 
{
1720
 
    int i;
1721
 
 
1722
 
#define LOOKUP_PTYS(array, arraylen, idprefix)                            \
1723
 
    for (i = 0 ; i < (arraylen) ; i++) {                                  \
1724
 
        virDomainChrDefPtr chr = (array)[i];                              \
1725
 
        if (chr->source.type == VIR_DOMAIN_CHR_TYPE_PTY) {                \
1726
 
            char id[16];                                                  \
1727
 
                                                                          \
1728
 
            if (snprintf(id, sizeof(id), idprefix "%i", i) >= sizeof(id)) \
1729
 
                return -1;                                                \
1730
 
                                                                          \
1731
 
            const char *path = (const char *) virHashLookup(paths, id);   \
1732
 
            if (path == NULL) {                                           \
1733
 
                if (chr->source.data.file.path == NULL) {                 \
1734
 
                    /* neither the log output nor 'info chardev' had a */ \
1735
 
                    /* pty path for this chardev, report an error */      \
1736
 
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,               \
1737
 
                                    _("no assigned pty for device %s"), id); \
1738
 
                    return -1;                                            \
1739
 
                } else {                                                  \
1740
 
                    /* 'info chardev' had no pty path for this chardev, */\
1741
 
                    /* but the log output had, so we're fine */           \
1742
 
                    continue;                                             \
1743
 
                }                                                         \
1744
 
            }                                                             \
1745
 
                                                                          \
1746
 
            VIR_FREE(chr->source.data.file.path);                         \
1747
 
            chr->source.data.file.path = strdup(path);                    \
1748
 
                                                                          \
1749
 
            if (chr->source.data.file.path == NULL) {                     \
1750
 
                virReportOOMError();                                      \
1751
 
                return -1;                                                \
1752
 
            }                                                             \
1753
 
        }                                                                 \
1754
 
    }
1755
 
 
1756
 
    LOOKUP_PTYS(vm->def->serials,   vm->def->nserials,   "serial");
1757
 
    LOOKUP_PTYS(vm->def->parallels, vm->def->nparallels, "parallel");
1758
 
    LOOKUP_PTYS(vm->def->channels,  vm->def->nchannels,  "channel");
1759
 
    if (vm->def->console)
1760
 
        LOOKUP_PTYS(&vm->def->console, 1,  "console");
1761
 
#undef LOOKUP_PTYS
1762
 
 
1763
 
    return 0;
1764
 
}
1765
 
 
1766
 
static int
1767
 
qemudFindCharDevicePTYs(virDomainObjPtr vm,
1768
 
                        const char *output,
1769
 
                        int fd ATTRIBUTE_UNUSED)
1770
 
{
1771
 
    size_t offset = 0;
1772
 
    int ret, i;
1773
 
 
1774
 
    /* The order in which QEMU prints out the PTY paths is
1775
 
       the order in which it procsses its serial and parallel
1776
 
       device args. This code must match that ordering.... */
1777
 
 
1778
 
    /* first comes the serial devices */
1779
 
    for (i = 0 ; i < vm->def->nserials ; i++) {
1780
 
        virDomainChrDefPtr chr = vm->def->serials[i];
1781
 
        if (chr->source.type == VIR_DOMAIN_CHR_TYPE_PTY) {
1782
 
            if ((ret = qemudExtractTTYPath(output, &offset,
1783
 
                                           &chr->source.data.file.path)) != 0)
1784
 
                return ret;
1785
 
        }
1786
 
    }
1787
 
 
1788
 
    /* then the parallel devices */
1789
 
    for (i = 0 ; i < vm->def->nparallels ; i++) {
1790
 
        virDomainChrDefPtr chr = vm->def->parallels[i];
1791
 
        if (chr->source.type == VIR_DOMAIN_CHR_TYPE_PTY) {
1792
 
            if ((ret = qemudExtractTTYPath(output, &offset,
1793
 
                                           &chr->source.data.file.path)) != 0)
1794
 
                return ret;
1795
 
        }
1796
 
    }
1797
 
 
1798
 
    /* then the channel devices */
1799
 
    for (i = 0 ; i < vm->def->nchannels ; i++) {
1800
 
        virDomainChrDefPtr chr = vm->def->channels[i];
1801
 
        if (chr->source.type == VIR_DOMAIN_CHR_TYPE_PTY) {
1802
 
            if ((ret = qemudExtractTTYPath(output, &offset,
1803
 
                                           &chr->source.data.file.path)) != 0)
1804
 
                return ret;
1805
 
        }
1806
 
    }
1807
 
 
1808
 
    return 0;
1809
 
}
1810
 
 
1811
 
static void qemudFreePtyPath(void *payload, const char *name ATTRIBUTE_UNUSED)
1812
 
{
1813
 
    VIR_FREE(payload);
1814
 
}
1815
 
 
1816
 
static void
1817
 
qemuReadLogFD(int logfd, char *buf, int maxlen, int off)
1818
 
{
1819
 
    int ret;
1820
 
    char *tmpbuf = buf + off;
1821
 
 
1822
 
    ret = saferead(logfd, tmpbuf, maxlen - off - 1);
1823
 
    if (ret < 0) {
1824
 
        ret = 0;
1825
 
    }
1826
 
 
1827
 
    tmpbuf[ret] = '\0';
1828
 
}
1829
 
 
1830
 
static int
1831
 
qemudWaitForMonitor(struct qemud_driver* driver,
1832
 
                    virDomainObjPtr vm, off_t pos)
1833
 
{
1834
 
    char buf[4096] = ""; /* Plenty of space to get startup greeting */
1835
 
    int logfd;
1836
 
    int ret = -1;
1837
 
    virHashTablePtr paths = NULL;
1838
 
 
1839
 
    if ((logfd = qemudLogReadFD(driver->logDir, vm->def->name, pos)) < 0)
1840
 
        return -1;
1841
 
 
1842
 
    if (qemudReadLogOutput(vm, logfd, buf, sizeof(buf),
1843
 
                           qemudFindCharDevicePTYs,
1844
 
                           "console", 30) < 0)
1845
 
        goto closelog;
1846
 
 
1847
 
    VIR_DEBUG("Connect monitor to %p '%s'", vm, vm->def->name);
1848
 
    if (qemuConnectMonitor(driver, vm) < 0) {
1849
 
        goto cleanup;
1850
 
    }
1851
 
 
1852
 
    /* Try to get the pty path mappings again via the monitor. This is much more
1853
 
     * reliable if it's available.
1854
 
     * Note that the monitor itself can be on a pty, so we still need to try the
1855
 
     * log output method. */
1856
 
    paths = virHashCreate(0);
1857
 
    if (paths == NULL) {
1858
 
        virReportOOMError();
1859
 
        goto cleanup;
1860
 
    }
1861
 
 
1862
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1863
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
1864
 
    ret = qemuMonitorGetPtyPaths(priv->mon, paths);
1865
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1866
 
 
1867
 
    VIR_DEBUG("qemuMonitorGetPtyPaths returned %i", ret);
1868
 
    if (ret == 0) {
1869
 
        ret = qemudFindCharDevicePTYsMonitor(vm, paths);
1870
 
    }
1871
 
 
1872
 
cleanup:
1873
 
    if (paths) {
1874
 
        virHashFree(paths, qemudFreePtyPath);
1875
 
    }
1876
 
 
1877
 
    if (kill(vm->pid, 0) == -1 && errno == ESRCH) {
1878
 
        /* VM is dead, any other error raised in the interim is probably
1879
 
         * not as important as the qemu cmdline output */
1880
 
        qemuReadLogFD(logfd, buf, sizeof(buf), strlen(buf));
1881
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
1882
 
                        _("process exited while connecting to monitor: %s"),
1883
 
                        buf);
1884
 
        ret = -1;
1885
 
    }
1886
 
 
1887
 
closelog:
1888
 
    if (VIR_CLOSE(logfd) < 0) {
1889
 
        char ebuf[4096];
1890
 
        VIR_WARN("Unable to close logfile: %s",
1891
 
                 virStrerror(errno, ebuf, sizeof ebuf));
1892
 
    }
1893
 
 
1894
 
    return ret;
1895
 
}
1896
 
 
1897
 
static int
1898
 
qemuDetectVcpuPIDs(struct qemud_driver *driver,
1899
 
                   virDomainObjPtr vm) {
1900
 
    pid_t *cpupids = NULL;
1901
 
    int ncpupids;
1902
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
1903
 
 
1904
 
    if (vm->def->virtType != VIR_DOMAIN_VIRT_KVM) {
1905
 
        priv->nvcpupids = 1;
1906
 
        if (VIR_ALLOC_N(priv->vcpupids, priv->nvcpupids) < 0) {
1907
 
            virReportOOMError();
1908
 
            return -1;
1909
 
        }
1910
 
        priv->vcpupids[0] = vm->pid;
1911
 
        return 0;
1912
 
    }
1913
 
 
1914
 
    /* What follows is now all KVM specific */
1915
 
 
1916
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
1917
 
    if ((ncpupids = qemuMonitorGetCPUInfo(priv->mon, &cpupids)) < 0) {
1918
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
1919
 
        return -1;
1920
 
    }
1921
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
1922
 
 
1923
 
    /* Treat failure to get VCPU<->PID mapping as non-fatal */
1924
 
    if (ncpupids == 0)
1925
 
        return 0;
1926
 
 
1927
 
    if (ncpupids != vm->def->vcpus) {
1928
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
1929
 
                        _("got wrong number of vCPU pids from QEMU monitor. "
1930
 
                          "got %d, wanted %d"),
1931
 
                        ncpupids, vm->def->vcpus);
1932
 
        VIR_FREE(cpupids);
1933
 
        return -1;
1934
 
    }
1935
 
 
1936
 
    priv->nvcpupids = ncpupids;
1937
 
    priv->vcpupids = cpupids;
1938
 
    return 0;
1939
 
}
1940
 
 
1941
 
/*
1942
 
 * To be run between fork/exec of QEMU only
1943
 
 */
1944
 
static int
1945
 
qemudInitCpuAffinity(virDomainObjPtr vm)
1946
 
{
1947
 
    int i, hostcpus, maxcpu = QEMUD_CPUMASK_LEN;
1948
 
    virNodeInfo nodeinfo;
1949
 
    unsigned char *cpumap;
1950
 
    int cpumaplen;
1951
 
 
1952
 
    DEBUG0("Setting CPU affinity");
1953
 
 
1954
 
    if (nodeGetInfo(NULL, &nodeinfo) < 0)
1955
 
        return -1;
1956
 
 
1957
 
    /* setaffinity fails if you set bits for CPUs which
1958
 
     * aren't present, so we have to limit ourselves */
1959
 
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
1960
 
    if (maxcpu > hostcpus)
1961
 
        maxcpu = hostcpus;
1962
 
 
1963
 
    cpumaplen = VIR_CPU_MAPLEN(maxcpu);
1964
 
    if (VIR_ALLOC_N(cpumap, cpumaplen) < 0) {
1965
 
        virReportOOMError();
1966
 
        return -1;
1967
 
    }
1968
 
 
1969
 
    if (vm->def->cpumask) {
1970
 
        /* XXX why don't we keep 'cpumask' in the libvirt cpumap
1971
 
         * format to start with ?!?! */
1972
 
        for (i = 0 ; i < maxcpu && i < vm->def->cpumasklen ; i++)
1973
 
            if (vm->def->cpumask[i])
1974
 
                VIR_USE_CPU(cpumap, i);
1975
 
    } else {
1976
 
        /* You may think this is redundant, but we can't assume libvirtd
1977
 
         * itself is running on all pCPUs, so we need to explicitly set
1978
 
         * the spawned QEMU instance to all pCPUs if no map is given in
1979
 
         * its config file */
1980
 
        for (i = 0 ; i < maxcpu ; i++)
1981
 
            VIR_USE_CPU(cpumap, i);
1982
 
    }
1983
 
 
1984
 
    /* We are pressuming we are running between fork/exec of QEMU
1985
 
     * so use '0' to indicate our own process ID. No threads are
1986
 
     * running at this point
1987
 
     */
1988
 
    if (virProcessInfoSetAffinity(0, /* Self */
1989
 
                                  cpumap, cpumaplen, maxcpu) < 0) {
1990
 
        VIR_FREE(cpumap);
1991
 
        return -1;
1992
 
    }
1993
 
    VIR_FREE(cpumap);
1994
 
 
1995
 
    return 0;
1996
 
}
1997
 
 
1998
 
 
1999
 
static int
2000
 
qemuInitPasswords(virConnectPtr conn,
2001
 
                  struct qemud_driver *driver,
2002
 
                  virDomainObjPtr vm,
2003
 
                  unsigned long long qemuCmdFlags) {
2004
 
    int ret = 0;
2005
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
2006
 
 
2007
 
    if (vm->def->ngraphics == 1) {
2008
 
        if (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC) {
2009
 
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
2010
 
                                                    VIR_DOMAIN_GRAPHICS_TYPE_VNC,
2011
 
                                                    &vm->def->graphics[0]->data.vnc.auth,
2012
 
                                                    driver->vncPassword);
2013
 
        } else if (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE) {
2014
 
            ret = qemuDomainChangeGraphicsPasswords(driver, vm,
2015
 
                                                    VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
2016
 
                                                    &vm->def->graphics[0]->data.spice.auth,
2017
 
                                                    driver->spicePassword);
2018
 
        }
2019
 
    }
2020
 
 
2021
 
    if (ret < 0)
2022
 
        goto cleanup;
2023
 
 
2024
 
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
2025
 
        int i;
2026
 
 
2027
 
        for (i = 0 ; i < vm->def->ndisks ; i++) {
2028
 
            char *secret;
2029
 
            size_t secretLen;
2030
 
 
2031
 
            if (!vm->def->disks[i]->encryption ||
2032
 
                !vm->def->disks[i]->src)
2033
 
                continue;
2034
 
 
2035
 
            if (getVolumeQcowPassphrase(conn,
2036
 
                                        vm->def->disks[i],
2037
 
                                        &secret, &secretLen) < 0)
2038
 
                goto cleanup;
2039
 
 
2040
 
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
2041
 
            ret = qemuMonitorSetDrivePassphrase(priv->mon,
2042
 
                                                vm->def->disks[i]->info.alias,
2043
 
                                                secret);
2044
 
            VIR_FREE(secret);
2045
 
            qemuDomainObjExitMonitorWithDriver(driver, vm);
2046
 
            if (ret < 0)
2047
 
                goto cleanup;
2048
 
        }
2049
 
    }
2050
 
 
2051
 
cleanup:
2052
 
    return ret;
2053
 
}
2054
 
 
2055
 
 
2056
 
#define QEMU_PCI_VENDOR_INTEL     0x8086
2057
 
#define QEMU_PCI_VENDOR_LSI_LOGIC 0x1000
2058
 
#define QEMU_PCI_VENDOR_REDHAT    0x1af4
2059
 
#define QEMU_PCI_VENDOR_CIRRUS    0x1013
2060
 
#define QEMU_PCI_VENDOR_REALTEK   0x10ec
2061
 
#define QEMU_PCI_VENDOR_AMD       0x1022
2062
 
#define QEMU_PCI_VENDOR_ENSONIQ   0x1274
2063
 
#define QEMU_PCI_VENDOR_VMWARE    0x15ad
2064
 
#define QEMU_PCI_VENDOR_QEMU      0x1234
2065
 
 
2066
 
#define QEMU_PCI_PRODUCT_DISK_VIRTIO 0x1001
2067
 
 
2068
 
#define QEMU_PCI_PRODUCT_BALLOON_VIRTIO 0x1002
2069
 
 
2070
 
#define QEMU_PCI_PRODUCT_NIC_NE2K     0x8029
2071
 
#define QEMU_PCI_PRODUCT_NIC_PCNET    0x2000
2072
 
#define QEMU_PCI_PRODUCT_NIC_RTL8139  0x8139
2073
 
#define QEMU_PCI_PRODUCT_NIC_E1000    0x100E
2074
 
#define QEMU_PCI_PRODUCT_NIC_VIRTIO   0x1000
2075
 
 
2076
 
#define QEMU_PCI_PRODUCT_VGA_CIRRUS 0x00b8
2077
 
#define QEMU_PCI_PRODUCT_VGA_VMWARE 0x0405
2078
 
#define QEMU_PCI_PRODUCT_VGA_STDVGA 0x1111
2079
 
 
2080
 
#define QEMU_PCI_PRODUCT_AUDIO_AC97    0x2415
2081
 
#define QEMU_PCI_PRODUCT_AUDIO_ES1370  0x5000
2082
 
 
2083
 
#define QEMU_PCI_PRODUCT_CONTROLLER_PIIX 0x7010
2084
 
#define QEMU_PCI_PRODUCT_CONTROLLER_LSI  0x0012
2085
 
 
2086
 
#define QEMU_PCI_PRODUCT_WATCHDOG_I63000ESB 0x25ab
2087
 
 
2088
 
static int
2089
 
qemuAssignNextPCIAddress(virDomainDeviceInfo *info,
2090
 
                         int vendor,
2091
 
                         int product,
2092
 
                         qemuMonitorPCIAddress *addrs,
2093
 
                         int naddrs)
2094
 
{
2095
 
    int found = 0;
2096
 
    int i;
2097
 
 
2098
 
    VIR_DEBUG("Look for %x:%x out of %d", vendor, product, naddrs);
2099
 
 
2100
 
    for (i = 0 ; (i < naddrs) && !found; i++) {
2101
 
        VIR_DEBUG("Maybe %x:%x", addrs[i].vendor, addrs[i].product);
2102
 
        if (addrs[i].vendor == vendor &&
2103
 
            addrs[i].product == product) {
2104
 
            VIR_DEBUG("Match %d", i);
2105
 
            found = 1;
2106
 
            break;
2107
 
        }
2108
 
    }
2109
 
    if (!found) {
2110
 
        return -1;
2111
 
    }
2112
 
 
2113
 
    /* Blank it out so this device isn't matched again */
2114
 
    addrs[i].vendor = 0;
2115
 
    addrs[i].product = 0;
2116
 
 
2117
 
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2118
 
        info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
2119
 
 
2120
 
    if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI) {
2121
 
        info->addr.pci.domain = addrs[i].addr.domain;
2122
 
        info->addr.pci.bus = addrs[i].addr.bus;
2123
 
        info->addr.pci.slot = addrs[i].addr.slot;
2124
 
        info->addr.pci.function = addrs[i].addr.function;
2125
 
    }
2126
 
 
2127
 
    return 0;
2128
 
}
2129
 
 
2130
 
static int
2131
 
qemuGetPCIDiskVendorProduct(virDomainDiskDefPtr def,
2132
 
                            unsigned *vendor,
2133
 
                            unsigned *product)
2134
 
{
2135
 
    switch (def->bus) {
2136
 
    case VIR_DOMAIN_DISK_BUS_VIRTIO:
2137
 
        *vendor = QEMU_PCI_VENDOR_REDHAT;
2138
 
        *product = QEMU_PCI_PRODUCT_DISK_VIRTIO;
2139
 
        break;
2140
 
 
2141
 
    default:
2142
 
        return -1;
2143
 
    }
2144
 
 
2145
 
    return 0;
2146
 
}
2147
 
 
2148
 
static int
2149
 
qemuGetPCINetVendorProduct(virDomainNetDefPtr def,
2150
 
                            unsigned *vendor,
2151
 
                            unsigned *product)
2152
 
{
2153
 
    if (!def->model)
2154
 
        return -1;
2155
 
 
2156
 
    if (STREQ(def->model, "ne2k_pci")) {
2157
 
        *vendor = QEMU_PCI_VENDOR_REALTEK;
2158
 
        *product = QEMU_PCI_PRODUCT_NIC_NE2K;
2159
 
    } else if (STREQ(def->model, "pcnet")) {
2160
 
        *vendor = QEMU_PCI_VENDOR_AMD;
2161
 
        *product = QEMU_PCI_PRODUCT_NIC_PCNET;
2162
 
    } else if (STREQ(def->model, "rtl8139")) {
2163
 
        *vendor = QEMU_PCI_VENDOR_REALTEK;
2164
 
        *product = QEMU_PCI_PRODUCT_NIC_RTL8139;
2165
 
    } else if (STREQ(def->model, "e1000")) {
2166
 
        *vendor = QEMU_PCI_VENDOR_INTEL;
2167
 
        *product = QEMU_PCI_PRODUCT_NIC_E1000;
2168
 
    } else if (STREQ(def->model, "virtio")) {
2169
 
        *vendor = QEMU_PCI_VENDOR_REDHAT;
2170
 
        *product = QEMU_PCI_PRODUCT_NIC_VIRTIO;
2171
 
    } else {
2172
 
        VIR_INFO("Unexpected NIC model %s, cannot get PCI address",
2173
 
                 def->model);
2174
 
        return -1;
2175
 
    }
2176
 
    return 0;
2177
 
}
2178
 
 
2179
 
static int
2180
 
qemuGetPCIControllerVendorProduct(virDomainControllerDefPtr def,
2181
 
                                  unsigned *vendor,
2182
 
                                  unsigned *product)
2183
 
{
2184
 
    switch (def->type) {
2185
 
    case VIR_DOMAIN_CONTROLLER_TYPE_SCSI:
2186
 
        *vendor = QEMU_PCI_VENDOR_LSI_LOGIC;
2187
 
        *product = QEMU_PCI_PRODUCT_CONTROLLER_LSI;
2188
 
        break;
2189
 
 
2190
 
    case VIR_DOMAIN_CONTROLLER_TYPE_FDC:
2191
 
        /* XXX we could put in the ISA bridge address, but
2192
 
           that's not technically the FDC's address */
2193
 
        return -1;
2194
 
 
2195
 
    case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
2196
 
        *vendor = QEMU_PCI_VENDOR_INTEL;
2197
 
        *product = QEMU_PCI_PRODUCT_CONTROLLER_PIIX;
2198
 
        break;
2199
 
 
2200
 
    default:
2201
 
        VIR_INFO("Unexpected controller type %s, cannot get PCI address",
2202
 
                 virDomainControllerTypeToString(def->type));
2203
 
        return -1;
2204
 
    }
2205
 
 
2206
 
    return 0;
2207
 
}
2208
 
 
2209
 
static int
2210
 
qemuGetPCIVideoVendorProduct(virDomainVideoDefPtr def,
2211
 
                             unsigned *vendor,
2212
 
                             unsigned *product)
2213
 
{
2214
 
    switch (def->type) {
2215
 
    case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
2216
 
        *vendor = QEMU_PCI_VENDOR_CIRRUS;
2217
 
        *product = QEMU_PCI_PRODUCT_VGA_CIRRUS;
2218
 
        break;
2219
 
 
2220
 
    case VIR_DOMAIN_VIDEO_TYPE_VGA:
2221
 
        *vendor = QEMU_PCI_VENDOR_QEMU;
2222
 
        *product = QEMU_PCI_PRODUCT_VGA_STDVGA;
2223
 
        break;
2224
 
 
2225
 
    case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
2226
 
        *vendor = QEMU_PCI_VENDOR_VMWARE;
2227
 
        *product = QEMU_PCI_PRODUCT_VGA_VMWARE;
2228
 
        break;
2229
 
 
2230
 
    default:
2231
 
        return -1;
2232
 
    }
2233
 
    return 0;
2234
 
}
2235
 
 
2236
 
static int
2237
 
qemuGetPCISoundVendorProduct(virDomainSoundDefPtr def,
2238
 
                             unsigned *vendor,
2239
 
                             unsigned *product)
2240
 
{
2241
 
    switch (def->model) {
2242
 
    case VIR_DOMAIN_SOUND_MODEL_ES1370:
2243
 
        *vendor = QEMU_PCI_VENDOR_ENSONIQ;
2244
 
        *product = QEMU_PCI_PRODUCT_AUDIO_ES1370;
2245
 
        break;
2246
 
 
2247
 
    case VIR_DOMAIN_SOUND_MODEL_AC97:
2248
 
        *vendor = QEMU_PCI_VENDOR_INTEL;
2249
 
        *product = QEMU_PCI_PRODUCT_AUDIO_AC97;
2250
 
        break;
2251
 
 
2252
 
    default:
2253
 
        return -1;
2254
 
    }
2255
 
 
2256
 
    return 0;
2257
 
}
2258
 
 
2259
 
static int
2260
 
qemuGetPCIWatchdogVendorProduct(virDomainWatchdogDefPtr def,
2261
 
                                unsigned *vendor,
2262
 
                                unsigned *product)
2263
 
{
2264
 
    switch (def->model) {
2265
 
    case VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB:
2266
 
        *vendor = QEMU_PCI_VENDOR_INTEL;
2267
 
        *product = QEMU_PCI_PRODUCT_WATCHDOG_I63000ESB;
2268
 
        break;
2269
 
 
2270
 
    default:
2271
 
        return -1;
2272
 
    }
2273
 
 
2274
 
    return 0;
2275
 
}
2276
 
 
2277
 
 
2278
 
static int
2279
 
qemuGetPCIMemballoonVendorProduct(virDomainMemballoonDefPtr def,
2280
 
                                  unsigned *vendor,
2281
 
                                  unsigned *product)
2282
 
{
2283
 
    switch (def->model) {
2284
 
    case VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO:
2285
 
        *vendor = QEMU_PCI_VENDOR_REDHAT;
2286
 
        *product = QEMU_PCI_PRODUCT_BALLOON_VIRTIO;
2287
 
        break;
2288
 
 
2289
 
    default:
2290
 
        return -1;
2291
 
    }
2292
 
 
2293
 
    return 0;
2294
 
}
2295
 
 
2296
 
 
2297
 
/*
2298
 
 * This entire method assumes that PCI devices in 'info pci'
2299
 
 * match ordering of devices specified on the command line
2300
 
 * wrt to devices of matching vendor+product
2301
 
 *
2302
 
 * XXXX this might not be a valid assumption if we assign
2303
 
 * some static addrs on CLI. Have to check that...
2304
 
 */
2305
 
static int
2306
 
qemuDetectPCIAddresses(virDomainObjPtr vm,
2307
 
                       qemuMonitorPCIAddress *addrs,
2308
 
                       int naddrs)
2309
 
{
2310
 
    unsigned int vendor = 0, product = 0;
2311
 
    int i;
2312
 
 
2313
 
    /* XXX should all these vendor/product IDs be kept in the
2314
 
     * actual device data structure instead ?
2315
 
     */
2316
 
 
2317
 
    for (i = 0 ; i < vm->def->ndisks ; i++) {
2318
 
        if (qemuGetPCIDiskVendorProduct(vm->def->disks[i], &vendor, &product) < 0)
2319
 
            continue;
2320
 
 
2321
 
        if (qemuAssignNextPCIAddress(&(vm->def->disks[i]->info),
2322
 
                                     vendor, product,
2323
 
                                     addrs, naddrs) < 0) {
2324
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2325
 
                            _("cannot find PCI address for VirtIO disk %s"),
2326
 
                            vm->def->disks[i]->dst);
2327
 
            return -1;
2328
 
        }
2329
 
    }
2330
 
 
2331
 
    for (i = 0 ; i < vm->def->nnets ; i++) {
2332
 
        if (qemuGetPCINetVendorProduct(vm->def->nets[i], &vendor, &product) < 0)
2333
 
            continue;
2334
 
 
2335
 
        if (qemuAssignNextPCIAddress(&(vm->def->nets[i]->info),
2336
 
                                     vendor, product,
2337
 
                                     addrs,  naddrs) < 0) {
2338
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2339
 
                            _("cannot find PCI address for %s NIC"),
2340
 
                            vm->def->nets[i]->model);
2341
 
            return -1;
2342
 
        }
2343
 
    }
2344
 
 
2345
 
    for (i = 0 ; i < vm->def->ncontrollers ; i++) {
2346
 
        if (qemuGetPCIControllerVendorProduct(vm->def->controllers[i], &vendor, &product) < 0)
2347
 
            continue;
2348
 
 
2349
 
        if (qemuAssignNextPCIAddress(&(vm->def->controllers[i]->info),
2350
 
                                     vendor, product,
2351
 
                                     addrs,  naddrs) < 0) {
2352
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2353
 
                            _("cannot find PCI address for controller %s"),
2354
 
                            virDomainControllerTypeToString(vm->def->controllers[i]->type));
2355
 
            return -1;
2356
 
        }
2357
 
    }
2358
 
 
2359
 
    for (i = 0 ; i < vm->def->nvideos ; i++) {
2360
 
        if (qemuGetPCIVideoVendorProduct(vm->def->videos[i], &vendor, &product) < 0)
2361
 
            continue;
2362
 
 
2363
 
        if (qemuAssignNextPCIAddress(&(vm->def->videos[i]->info),
2364
 
                                     vendor, product,
2365
 
                                     addrs,  naddrs) < 0) {
2366
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2367
 
                            _("cannot find PCI address for video adapter %s"),
2368
 
                            virDomainVideoTypeToString(vm->def->videos[i]->type));
2369
 
            return -1;
2370
 
        }
2371
 
    }
2372
 
 
2373
 
    for (i = 0 ; i < vm->def->nsounds ; i++) {
2374
 
        if (qemuGetPCISoundVendorProduct(vm->def->sounds[i], &vendor, &product) < 0)
2375
 
            continue;
2376
 
 
2377
 
        if (qemuAssignNextPCIAddress(&(vm->def->sounds[i]->info),
2378
 
                                    vendor, product,
2379
 
                                     addrs,  naddrs) < 0) {
2380
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2381
 
                            _("cannot find PCI address for sound adapter %s"),
2382
 
                            virDomainSoundModelTypeToString(vm->def->sounds[i]->model));
2383
 
            return -1;
2384
 
        }
2385
 
    }
2386
 
 
2387
 
 
2388
 
    if (vm->def->watchdog &&
2389
 
        qemuGetPCIWatchdogVendorProduct(vm->def->watchdog, &vendor, &product) == 0) {
2390
 
        if (qemuAssignNextPCIAddress(&(vm->def->watchdog->info),
2391
 
                                     vendor, product,
2392
 
                                     addrs,  naddrs) < 0) {
2393
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2394
 
                            _("cannot find PCI address for watchdog %s"),
2395
 
                            virDomainWatchdogModelTypeToString(vm->def->watchdog->model));
2396
 
            return -1;
2397
 
        }
2398
 
    }
2399
 
 
2400
 
    if (vm->def->memballoon &&
2401
 
        qemuGetPCIMemballoonVendorProduct(vm->def->memballoon, &vendor, &product) == 0) {
2402
 
        if (qemuAssignNextPCIAddress(&(vm->def->memballoon->info),
2403
 
                                     vendor, product,
2404
 
                                     addrs, naddrs) < 0) {
2405
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2406
 
                            _("cannot find PCI address for balloon %s"),
2407
 
                            virDomainMemballoonModelTypeToString(vm->def->memballoon->model));
2408
 
            return -1;
2409
 
        }
2410
 
    }
2411
 
 
2412
 
    /* XXX console (virtio) */
2413
 
 
2414
 
 
2415
 
    /* ... and now things we don't have in our xml */
2416
 
 
2417
 
    /* XXX USB controller ? */
2418
 
 
2419
 
    /* XXX what about other PCI devices (ie bridges) */
2420
 
 
2421
 
    return 0;
2422
 
}
2423
 
 
2424
 
static int
2425
 
qemuInitPCIAddresses(struct qemud_driver *driver,
2426
 
                     virDomainObjPtr vm)
2427
 
{
2428
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
2429
 
    int naddrs;
2430
 
    int ret;
2431
 
    qemuMonitorPCIAddress *addrs = NULL;
2432
 
 
2433
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2434
 
    naddrs = qemuMonitorGetAllPCIAddresses(priv->mon,
2435
 
                                           &addrs);
2436
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2437
 
 
2438
 
    ret = qemuDetectPCIAddresses(vm, addrs, naddrs);
2439
 
 
2440
 
    VIR_FREE(addrs);
2441
 
 
2442
 
    return ret;
2443
 
}
2444
 
 
2445
 
 
2446
 
static int qemudNextFreePort(struct qemud_driver *driver,
2447
 
                             int startPort) {
2448
 
    int i;
2449
 
 
2450
 
    for (i = startPort ; i < QEMU_VNC_PORT_MAX; i++) {
2451
 
        int fd;
2452
 
        int reuse = 1;
2453
 
        struct sockaddr_in addr;
2454
 
        bool used = false;
2455
 
 
2456
 
        if (virBitmapGetBit(driver->reservedVNCPorts,
2457
 
                            i - QEMU_VNC_PORT_MIN, &used) < 0)
2458
 
            VIR_DEBUG("virBitmapGetBit failed on bit %d", i - QEMU_VNC_PORT_MIN);
2459
 
 
2460
 
        if (used)
2461
 
            continue;
2462
 
 
2463
 
        addr.sin_family = AF_INET;
2464
 
        addr.sin_port = htons(i);
2465
 
        addr.sin_addr.s_addr = htonl(INADDR_ANY);
2466
 
        fd = socket(PF_INET, SOCK_STREAM, 0);
2467
 
        if (fd < 0)
2468
 
            return -1;
2469
 
 
2470
 
        if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&reuse, sizeof(reuse)) < 0) {
2471
 
            VIR_FORCE_CLOSE(fd);
2472
 
            break;
2473
 
        }
2474
 
 
2475
 
        if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == 0) {
2476
 
            /* Not in use, lets grab it */
2477
 
            VIR_FORCE_CLOSE(fd);
2478
 
            /* Add port to bitmap of reserved ports */
2479
 
            if (virBitmapSetBit(driver->reservedVNCPorts,
2480
 
                                i - QEMU_VNC_PORT_MIN) < 0) {
2481
 
                VIR_DEBUG("virBitmapSetBit failed on bit %d",
2482
 
                          i - QEMU_VNC_PORT_MIN);
2483
 
            }
2484
 
            return i;
2485
 
        }
2486
 
        VIR_FORCE_CLOSE(fd);
2487
 
 
2488
 
        if (errno == EADDRINUSE) {
2489
 
            /* In use, try next */
2490
 
            continue;
2491
 
        }
2492
 
        /* Some other bad failure, get out.. */
2493
 
        break;
2494
 
    }
2495
 
    return -1;
2496
 
}
2497
 
 
2498
 
 
2499
 
static void
2500
 
qemuReturnPort(struct qemud_driver *driver,
2501
 
                int port)
2502
 
{
2503
 
    if (port < QEMU_VNC_PORT_MIN)
2504
 
        return;
2505
 
 
2506
 
    if (virBitmapClearBit(driver->reservedVNCPorts,
2507
 
                          port - QEMU_VNC_PORT_MIN) < 0)
2508
 
        VIR_DEBUG("Could not mark port %d as unused", port);
2509
 
}
2510
 
 
2511
 
 
2512
 
static int
2513
 
qemuAssignPCIAddresses(virDomainDefPtr def)
2514
 
{
2515
 
    int ret = -1;
2516
 
    unsigned long long qemuCmdFlags = 0;
2517
 
    qemuDomainPCIAddressSetPtr addrs = NULL;
2518
 
 
2519
 
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
2520
 
                                   NULL,
2521
 
                                   &qemuCmdFlags) < 0)
2522
 
        goto cleanup;
2523
 
 
2524
 
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
2525
 
        if (!(addrs = qemuDomainPCIAddressSetCreate(def)))
2526
 
            goto cleanup;
2527
 
 
2528
 
        if (qemuAssignDevicePCISlots(def, addrs) < 0)
2529
 
            goto cleanup;
2530
 
    }
2531
 
 
2532
 
    ret = 0;
2533
 
 
2534
 
cleanup:
2535
 
    qemuDomainPCIAddressSetFree(addrs);
2536
 
 
2537
 
    return ret;
2538
 
}
2539
 
 
2540
 
 
2541
 
static int
2542
 
qemuPrepareChardevDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
2543
 
                         virDomainChrDefPtr dev,
2544
 
                         void *opaque ATTRIBUTE_UNUSED)
2545
 
{
2546
 
    int fd;
2547
 
    if (dev->source.type != VIR_DOMAIN_CHR_TYPE_FILE)
2548
 
        return 0;
2549
 
 
2550
 
    if ((fd = open(dev->source.data.file.path,
2551
 
                   O_CREAT | O_APPEND, S_IRUSR|S_IWUSR)) < 0) {
2552
 
        virReportSystemError(errno,
2553
 
                             _("Unable to pre-create chardev file '%s'"),
2554
 
                             dev->source.data.file.path);
2555
 
        return -1;
2556
 
    }
2557
 
 
2558
 
    VIR_FORCE_CLOSE(fd);
2559
 
 
2560
 
    return 0;
2561
 
}
2562
 
 
2563
 
 
2564
 
struct qemudHookData {
2565
 
    virConnectPtr conn;
2566
 
    virDomainObjPtr vm;
2567
 
    struct qemud_driver *driver;
2568
 
};
2569
 
 
2570
 
static int qemudSecurityHook(void *data) {
2571
 
    struct qemudHookData *h = data;
2572
 
 
2573
 
    /* This must take place before exec(), so that all QEMU
2574
 
     * memory allocation is on the correct NUMA node
2575
 
     */
2576
 
    if (qemuAddToCgroup(h->driver, h->vm->def) < 0)
2577
 
        return -1;
2578
 
 
2579
 
    /* This must be done after cgroup placement to avoid resetting CPU
2580
 
     * affinity */
2581
 
    if (qemudInitCpuAffinity(h->vm) < 0)
2582
 
        return -1;
2583
 
 
2584
 
    if (virSecurityManagerSetProcessLabel(h->driver->securityManager, h->vm) < 0)
2585
 
        return -1;
2586
 
 
2587
 
    return 0;
2588
 
}
2589
 
 
2590
 
static int
2591
 
qemuPrepareMonitorChr(struct qemud_driver *driver,
2592
 
                      virDomainChrSourceDefPtr monConfig,
2593
 
                      const char *vm)
2594
 
{
2595
 
    monConfig->type = VIR_DOMAIN_CHR_TYPE_UNIX;
2596
 
    monConfig->data.nix.listen = true;
2597
 
 
2598
 
    if (virAsprintf(&monConfig->data.nix.path, "%s/%s.monitor",
2599
 
                    driver->libDir, vm) < 0) {
2600
 
        virReportOOMError();
2601
 
        return -1;
2602
 
    }
2603
 
 
2604
 
    return 0;
2605
 
}
2606
 
 
2607
 
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
2608
 
                                              char *snapshotDir);
2609
 
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
2610
 
                                                char *snapshotDir);
2611
 
 
2612
 
 
2613
 
#define START_POSTFIX ": starting up\n"
2614
 
#define SHUTDOWN_POSTFIX ": shutting down\n"
2615
 
 
2616
 
static int qemudStartVMDaemon(virConnectPtr conn,
2617
 
                              struct qemud_driver *driver,
2618
 
                              virDomainObjPtr vm,
2619
 
                              const char *migrateFrom,
2620
 
                              bool start_paused,
2621
 
                              int stdin_fd,
2622
 
                              const char *stdin_path,
2623
 
                              enum virVMOperationType vmop) {
2624
 
    int ret;
2625
 
    unsigned long long qemuCmdFlags;
2626
 
    off_t pos = -1;
2627
 
    char ebuf[1024];
2628
 
    char *pidfile = NULL;
2629
 
    int logfile = -1;
2630
 
    char *timestamp;
2631
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
2632
 
    virCommandPtr cmd = NULL;
2633
 
 
2634
 
    struct qemudHookData hookData;
2635
 
    hookData.conn = conn;
2636
 
    hookData.vm = vm;
2637
 
    hookData.driver = driver;
2638
 
 
2639
 
    DEBUG0("Beginning VM startup process");
2640
 
 
2641
 
    if (virDomainObjIsActive(vm)) {
2642
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
2643
 
                        "%s", _("VM is already active"));
2644
 
        return -1;
2645
 
    }
2646
 
 
2647
 
    /* Do this upfront, so any part of the startup process can add
2648
 
     * runtime state to vm->def that won't be persisted. This let's us
2649
 
     * report implicit runtime defaults in the XML, like vnc listen/socket
2650
 
     */
2651
 
    DEBUG0("Setting current domain def as transient");
2652
 
    if (virDomainObjSetDefTransient(driver->caps, vm, true) < 0)
2653
 
        goto cleanup;
2654
 
 
2655
 
    vm->def->id = driver->nextvmid++;
2656
 
 
2657
 
    /* Must be run before security labelling */
2658
 
    DEBUG0("Preparing host devices");
2659
 
    if (qemuPrepareHostDevices(driver, vm->def) < 0)
2660
 
        goto cleanup;
2661
 
 
2662
 
    DEBUG0("Preparing chr devices");
2663
 
    if (virDomainChrDefForeach(vm->def,
2664
 
                               true,
2665
 
                               qemuPrepareChardevDevice,
2666
 
                               NULL) < 0)
2667
 
        goto cleanup;
2668
 
 
2669
 
    /* If you are using a SecurityDriver with dynamic labelling,
2670
 
       then generate a security label for isolation */
2671
 
    DEBUG0("Generating domain security label (if required)");
2672
 
    if (virSecurityManagerGenLabel(driver->securityManager, vm) < 0) {
2673
 
        qemuDomainSecurityLabelAudit(vm, false);
2674
 
        goto cleanup;
2675
 
    }
2676
 
    qemuDomainSecurityLabelAudit(vm, true);
2677
 
 
2678
 
    DEBUG0("Generating setting domain security labels (if required)");
2679
 
    if (virSecurityManagerSetAllLabel(driver->securityManager,
2680
 
                                      vm, stdin_path) < 0)
2681
 
        goto cleanup;
2682
 
 
2683
 
    if (stdin_fd != -1) {
2684
 
        /* if there's an fd to migrate from, and it's a pipe, put the
2685
 
         * proper security label on it
2686
 
         */
2687
 
        struct stat stdin_sb;
2688
 
 
2689
 
        DEBUG0("setting security label on pipe used for migration");
2690
 
 
2691
 
        if (fstat(stdin_fd, &stdin_sb) < 0) {
2692
 
            virReportSystemError(errno,
2693
 
                                 _("cannot stat fd %d"), stdin_fd);
2694
 
            goto cleanup;
2695
 
        }
2696
 
        if (S_ISFIFO(stdin_sb.st_mode) &&
2697
 
            virSecurityManagerSetFDLabel(driver->securityManager, vm, stdin_fd) < 0)
2698
 
            goto cleanup;
2699
 
    }
2700
 
 
2701
 
    /* Ensure no historical cgroup for this VM is lying around bogus
2702
 
     * settings */
2703
 
    DEBUG0("Ensuring no historical cgroup is lying around");
2704
 
    qemuRemoveCgroup(driver, vm, 1);
2705
 
 
2706
 
    if (vm->def->ngraphics == 1) {
2707
 
        if (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
2708
 
            !vm->def->graphics[0]->data.vnc.socket &&
2709
 
            vm->def->graphics[0]->data.vnc.autoport) {
2710
 
            int port = qemudNextFreePort(driver, QEMU_VNC_PORT_MIN);
2711
 
            if (port < 0) {
2712
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
2713
 
                                "%s", _("Unable to find an unused VNC port"));
2714
 
                goto cleanup;
2715
 
            }
2716
 
            vm->def->graphics[0]->data.vnc.port = port;
2717
 
        } else if (vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE &&
2718
 
                   vm->def->graphics[0]->data.spice.autoport) {
2719
 
            int port = qemudNextFreePort(driver, QEMU_VNC_PORT_MIN);
2720
 
            int tlsPort = -1;
2721
 
            if (port < 0) {
2722
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
2723
 
                                "%s", _("Unable to find an unused SPICE port"));
2724
 
                goto cleanup;
2725
 
            }
2726
 
 
2727
 
            if (driver->spiceTLS) {
2728
 
                tlsPort = qemudNextFreePort(driver, port + 1);
2729
 
                if (tlsPort < 0) {
2730
 
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
2731
 
                                    "%s", _("Unable to find an unused SPICE TLS port"));
2732
 
                    qemuReturnPort(driver, port);
2733
 
                    goto cleanup;
2734
 
                }
2735
 
            }
2736
 
 
2737
 
            vm->def->graphics[0]->data.spice.port = port;
2738
 
            vm->def->graphics[0]->data.spice.tlsPort = tlsPort;
2739
 
        }
2740
 
    }
2741
 
 
2742
 
    if (virFileMakePath(driver->logDir) != 0) {
2743
 
        virReportSystemError(errno,
2744
 
                             _("cannot create log directory %s"),
2745
 
                             driver->logDir);
2746
 
        goto cleanup;
2747
 
    }
2748
 
 
2749
 
    DEBUG0("Creating domain log file");
2750
 
    if ((logfile = qemudLogFD(driver, vm->def->name, false)) < 0)
2751
 
        goto cleanup;
2752
 
 
2753
 
    DEBUG0("Determining emulator version");
2754
 
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
2755
 
                                   NULL,
2756
 
                                   &qemuCmdFlags) < 0)
2757
 
        goto cleanup;
2758
 
 
2759
 
    DEBUG0("Setting up domain cgroup (if required)");
2760
 
    if (qemuSetupCgroup(driver, vm) < 0)
2761
 
        goto cleanup;
2762
 
 
2763
 
    if (VIR_ALLOC(priv->monConfig) < 0) {
2764
 
        virReportOOMError();
2765
 
        goto cleanup;
2766
 
    }
2767
 
 
2768
 
    DEBUG0("Preparing monitor state");
2769
 
    if (qemuPrepareMonitorChr(driver, priv->monConfig, vm->def->name) < 0)
2770
 
        goto cleanup;
2771
 
 
2772
 
#if HAVE_YAJL
2773
 
    if (qemuCmdFlags & QEMUD_CMD_FLAG_MONITOR_JSON)
2774
 
        priv->monJSON = 1;
2775
 
    else
2776
 
#endif
2777
 
        priv->monJSON = 0;
2778
 
 
2779
 
    priv->monitor_warned = 0;
2780
 
    priv->gotShutdown = false;
2781
 
 
2782
 
    if ((ret = virFileDeletePid(driver->stateDir, vm->def->name)) != 0) {
2783
 
        virReportSystemError(ret,
2784
 
                             _("Cannot remove stale PID file for %s"),
2785
 
                             vm->def->name);
2786
 
        goto cleanup;
2787
 
    }
2788
 
 
2789
 
    if (!(pidfile = virFilePid(driver->stateDir, vm->def->name))) {
2790
 
        virReportSystemError(errno,
2791
 
                             "%s", _("Failed to build pidfile path."));
2792
 
        goto cleanup;
2793
 
    }
2794
 
 
2795
 
    /*
2796
 
     * Normally PCI addresses are assigned in the virDomainCreate
2797
 
     * or virDomainDefine methods. We might still need to assign
2798
 
     * some here to cope with the question of upgrades. Regardless
2799
 
     * we also need to populate the PCi address set cache for later
2800
 
     * use in hotplug
2801
 
     */
2802
 
    if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
2803
 
        DEBUG0("Assigning domain PCI addresses");
2804
 
        /* Populate cache with current addresses */
2805
 
        if (priv->pciaddrs) {
2806
 
            qemuDomainPCIAddressSetFree(priv->pciaddrs);
2807
 
            priv->pciaddrs = NULL;
2808
 
        }
2809
 
        if (!(priv->pciaddrs = qemuDomainPCIAddressSetCreate(vm->def)))
2810
 
            goto cleanup;
2811
 
 
2812
 
 
2813
 
        /* Assign any remaining addresses */
2814
 
        if (qemuAssignDevicePCISlots(vm->def, priv->pciaddrs) < 0)
2815
 
            goto cleanup;
2816
 
 
2817
 
        priv->persistentAddrs = 1;
2818
 
    } else {
2819
 
        priv->persistentAddrs = 0;
2820
 
    }
2821
 
 
2822
 
    DEBUG0("Building emulator command line");
2823
 
    if (!(cmd = qemuBuildCommandLine(conn, driver, vm->def, priv->monConfig,
2824
 
                                     priv->monJSON != 0, qemuCmdFlags,
2825
 
                                     migrateFrom, stdin_fd,
2826
 
                                     vm->current_snapshot, vmop)))
2827
 
        goto cleanup;
2828
 
 
2829
 
    if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
2830
 
        goto cleanup;
2831
 
 
2832
 
    /* now that we know it is about to start call the hook if present */
2833
 
    if (virHookPresent(VIR_HOOK_DRIVER_QEMU)) {
2834
 
        char *xml = virDomainDefFormat(vm->def, 0);
2835
 
        int hookret;
2836
 
 
2837
 
        hookret = virHookCall(VIR_HOOK_DRIVER_QEMU, vm->def->name,
2838
 
                    VIR_HOOK_QEMU_OP_START, VIR_HOOK_SUBOP_BEGIN, NULL, xml);
2839
 
        VIR_FREE(xml);
2840
 
 
2841
 
        /*
2842
 
         * If the script raised an error abort the launch
2843
 
         */
2844
 
        if (hookret < 0)
2845
 
            goto cleanup;
2846
 
    }
2847
 
 
2848
 
    if ((timestamp = virTimestamp()) == NULL) {
2849
 
        virReportOOMError();
2850
 
        goto cleanup;
2851
 
    } else {
2852
 
        if (safewrite(logfile, timestamp, strlen(timestamp)) < 0 ||
2853
 
            safewrite(logfile, START_POSTFIX, strlen(START_POSTFIX)) < 0) {
2854
 
            VIR_WARN("Unable to write timestamp to logfile: %s",
2855
 
                     virStrerror(errno, ebuf, sizeof ebuf));
2856
 
        }
2857
 
 
2858
 
        VIR_FREE(timestamp);
2859
 
    }
2860
 
 
2861
 
    virCommandWriteArgLog(cmd, logfile);
2862
 
 
2863
 
    if ((pos = lseek(logfile, 0, SEEK_END)) < 0)
2864
 
        VIR_WARN("Unable to seek to end of logfile: %s",
2865
 
                 virStrerror(errno, ebuf, sizeof ebuf));
2866
 
 
2867
 
    VIR_DEBUG("Clear emulator capabilities: %d",
2868
 
              driver->clearEmulatorCapabilities);
2869
 
    if (driver->clearEmulatorCapabilities)
2870
 
        virCommandClearCaps(cmd);
2871
 
 
2872
 
    virCommandSetPreExecHook(cmd, qemudSecurityHook, &hookData);
2873
 
 
2874
 
    virCommandSetOutputFD(cmd, &logfile);
2875
 
    virCommandSetErrorFD(cmd, &logfile);
2876
 
    virCommandNonblockingFDs(cmd);
2877
 
    virCommandSetPidFile(cmd, pidfile);
2878
 
    virCommandDaemonize(cmd);
2879
 
 
2880
 
    ret = virCommandRun(cmd, NULL);
2881
 
    VIR_FREE(pidfile);
2882
 
 
2883
 
    /* wait for qemu process to to show up */
2884
 
    if (ret == 0) {
2885
 
        if (virFileReadPid(driver->stateDir, vm->def->name, &vm->pid)) {
2886
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
2887
 
                            _("Domain %s didn't show up"), vm->def->name);
2888
 
            ret = -1;
2889
 
        }
2890
 
#if 0
2891
 
    } else if (ret == -2) {
2892
 
        /*
2893
 
         * XXX this is bogus. It isn't safe to set vm->pid = child
2894
 
         * because the child no longer exists.
2895
 
         */
2896
 
 
2897
 
        /* The virExec process that launches the daemon failed. Pending on
2898
 
         * when it failed (we can't determine for sure), there may be
2899
 
         * extra info in the domain log (if the hook failed for example).
2900
 
         *
2901
 
         * Pretend like things succeeded, and let 'WaitForMonitor' report
2902
 
         * the log contents for us.
2903
 
         */
2904
 
        vm->pid = child;
2905
 
        ret = 0;
2906
 
#endif
2907
 
    }
2908
 
 
2909
 
    if (migrateFrom)
2910
 
        start_paused = true;
2911
 
    vm->state = start_paused ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
2912
 
 
2913
 
    if (ret == -1) /* The VM failed to start; tear filters before taps */
2914
 
        virDomainConfVMNWFilterTeardown(vm);
2915
 
 
2916
 
    if (ret == -1) /* The VM failed to start */
2917
 
        goto cleanup;
2918
 
 
2919
 
    DEBUG0("Waiting for monitor to show up");
2920
 
    if (qemudWaitForMonitor(driver, vm, pos) < 0)
2921
 
        goto cleanup;
2922
 
 
2923
 
    DEBUG0("Detecting VCPU PIDs");
2924
 
    if (qemuDetectVcpuPIDs(driver, vm) < 0)
2925
 
        goto cleanup;
2926
 
 
2927
 
    DEBUG0("Setting any required VM passwords");
2928
 
    if (qemuInitPasswords(conn, driver, vm, qemuCmdFlags) < 0)
2929
 
        goto cleanup;
2930
 
 
2931
 
    /* If we have -device, then addresses are assigned explicitly.
2932
 
     * If not, then we have to detect dynamic ones here */
2933
 
    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
2934
 
        DEBUG0("Determining domain device PCI addresses");
2935
 
        if (qemuInitPCIAddresses(driver, vm) < 0)
2936
 
            goto cleanup;
2937
 
    }
2938
 
 
2939
 
    DEBUG0("Setting initial memory amount");
2940
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
2941
 
    if (qemuMonitorSetBalloon(priv->mon, vm->def->mem.cur_balloon) < 0) {
2942
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
2943
 
        goto cleanup;
2944
 
    }
2945
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
2946
 
 
2947
 
    if (!start_paused) {
2948
 
        DEBUG0("Starting domain CPUs");
2949
 
        /* Allow the CPUS to start executing */
2950
 
        if (doStartCPUs(driver, vm, conn) < 0) {
2951
 
            if (virGetLastError() == NULL)
2952
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
2953
 
                                "%s", _("resume operation failed"));
2954
 
            goto cleanup;
2955
 
        }
2956
 
    }
2957
 
 
2958
 
 
2959
 
    DEBUG0("Writing domain status to disk");
2960
 
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
2961
 
        goto cleanup;
2962
 
 
2963
 
    virCommandFree(cmd);
2964
 
    VIR_FORCE_CLOSE(logfile);
2965
 
 
2966
 
    return 0;
2967
 
 
2968
 
cleanup:
2969
 
    /* We jump here if we failed to start the VM for any reason, or
2970
 
     * if we failed to initialize the now running VM. kill it off and
2971
 
     * pretend we never started it */
2972
 
    virCommandFree(cmd);
2973
 
    VIR_FORCE_CLOSE(logfile);
2974
 
    qemudShutdownVMDaemon(driver, vm, 0);
2975
 
 
2976
 
    return -1;
2977
 
}
2978
 
 
2979
 
static void qemudShutdownVMDaemon(struct qemud_driver *driver,
2980
 
                                  virDomainObjPtr vm,
2981
 
                                  int migrated) {
2982
 
    int ret;
2983
 
    int retries = 0;
2984
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
2985
 
    virErrorPtr orig_err;
2986
 
    virDomainDefPtr def;
2987
 
    int i;
2988
 
    int logfile = -1;
2989
 
    char *timestamp;
2990
 
    char ebuf[1024];
2991
 
 
2992
 
    VIR_DEBUG("Shutting down VM '%s' pid=%d migrated=%d",
2993
 
              vm->def->name, vm->pid, migrated);
2994
 
 
2995
 
    if (!virDomainObjIsActive(vm)) {
2996
 
        VIR_DEBUG("VM '%s' not active", vm->def->name);
2997
 
        return;
2998
 
    }
2999
 
 
3000
 
    if ((logfile = qemudLogFD(driver, vm->def->name, true)) < 0) {
3001
 
        /* To not break the normal domain shutdown process, skip the
3002
 
         * timestamp log writing if failed on opening log file. */
3003
 
        VIR_WARN("Unable to open logfile: %s",
3004
 
                  virStrerror(errno, ebuf, sizeof ebuf));
3005
 
    } else {
3006
 
        if ((timestamp = virTimestamp()) == NULL) {
3007
 
            virReportOOMError();
3008
 
        } else {
3009
 
            if (safewrite(logfile, timestamp, strlen(timestamp)) < 0 ||
3010
 
                safewrite(logfile, SHUTDOWN_POSTFIX,
3011
 
                          strlen(SHUTDOWN_POSTFIX)) < 0) {
3012
 
                VIR_WARN("Unable to write timestamp to logfile: %s",
3013
 
                         virStrerror(errno, ebuf, sizeof ebuf));
3014
 
            }
3015
 
 
3016
 
            VIR_FREE(timestamp);
3017
 
        }
3018
 
 
3019
 
        if (VIR_CLOSE(logfile) < 0)
3020
 
             VIR_WARN("Unable to close logfile: %s",
3021
 
                      virStrerror(errno, ebuf, sizeof ebuf));
3022
 
    }
3023
 
 
3024
 
    /* This method is routinely used in clean up paths. Disable error
3025
 
     * reporting so we don't squash a legit error. */
3026
 
    orig_err = virSaveLastError();
3027
 
 
3028
 
    virDomainConfVMNWFilterTeardown(vm);
3029
 
 
3030
 
    if (driver->macFilter) {
3031
 
        def = vm->def;
3032
 
        for (i = 0 ; i < def->nnets ; i++) {
3033
 
            virDomainNetDefPtr net = def->nets[i];
3034
 
            if (net->ifname == NULL)
3035
 
                continue;
3036
 
            if ((errno = networkDisallowMacOnPort(driver, net->ifname,
3037
 
                                                  net->mac))) {
3038
 
                virReportSystemError(errno,
3039
 
             _("failed to remove ebtables rule to allow MAC address on  '%s'"),
3040
 
                                     net->ifname);
3041
 
            }
3042
 
        }
3043
 
    }
3044
 
 
3045
 
    /* This will safely handle a non-running guest with pid=0 or pid=-1*/
3046
 
    if (virKillProcess(vm->pid, 0) == 0 &&
3047
 
        virKillProcess(vm->pid, SIGTERM) < 0)
3048
 
        virReportSystemError(errno,
3049
 
                             _("Failed to send SIGTERM to %s (%d)"),
3050
 
                             vm->def->name, vm->pid);
3051
 
 
3052
 
    if (priv->mon)
3053
 
        qemuMonitorClose(priv->mon);
3054
 
 
3055
 
    if (priv->monConfig) {
3056
 
        if (priv->monConfig->type == VIR_DOMAIN_CHR_TYPE_UNIX)
3057
 
            unlink(priv->monConfig->data.nix.path);
3058
 
        virDomainChrSourceDefFree(priv->monConfig);
3059
 
        priv->monConfig = NULL;
3060
 
    }
3061
 
 
3062
 
    /* shut it off for sure */
3063
 
    virKillProcess(vm->pid, SIGKILL);
3064
 
 
3065
 
    /* now that we know it's stopped call the hook if present */
3066
 
    if (virHookPresent(VIR_HOOK_DRIVER_QEMU)) {
3067
 
        char *xml = virDomainDefFormat(vm->def, 0);
3068
 
 
3069
 
        /* we can't stop the operation even if the script raised an error */
3070
 
        virHookCall(VIR_HOOK_DRIVER_QEMU, vm->def->name,
3071
 
                    VIR_HOOK_QEMU_OP_STOPPED, VIR_HOOK_SUBOP_END, NULL, xml);
3072
 
        VIR_FREE(xml);
3073
 
    }
3074
 
 
3075
 
    /* Reset Security Labels */
3076
 
    virSecurityManagerRestoreAllLabel(driver->securityManager,
3077
 
                                      vm, migrated);
3078
 
    virSecurityManagerReleaseLabel(driver->securityManager, vm);
3079
 
 
3080
 
    /* Clear out dynamically assigned labels */
3081
 
    if (vm->def->seclabel.type == VIR_DOMAIN_SECLABEL_DYNAMIC) {
3082
 
        VIR_FREE(vm->def->seclabel.model);
3083
 
        VIR_FREE(vm->def->seclabel.label);
3084
 
        VIR_FREE(vm->def->seclabel.imagelabel);
3085
 
    }
3086
 
 
3087
 
    virDomainDefClearDeviceAliases(vm->def);
3088
 
    if (!priv->persistentAddrs) {
3089
 
        virDomainDefClearPCIAddresses(vm->def);
3090
 
        qemuDomainPCIAddressSetFree(priv->pciaddrs);
3091
 
        priv->pciaddrs = NULL;
3092
 
    }
3093
 
 
3094
 
    qemuDomainReAttachHostDevices(driver, vm->def);
3095
 
 
3096
 
#if WITH_MACVTAP
3097
 
    def = vm->def;
3098
 
    for (i = 0; i < def->nnets; i++) {
3099
 
        virDomainNetDefPtr net = def->nets[i];
3100
 
        if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
3101
 
            delMacvtap(net->ifname, net->mac, net->data.direct.linkdev,
3102
 
                       &net->data.direct.virtPortProfile);
3103
 
            VIR_FREE(net->ifname);
3104
 
        }
3105
 
    }
3106
 
#endif
3107
 
 
3108
 
retry:
3109
 
    if ((ret = qemuRemoveCgroup(driver, vm, 0)) < 0) {
3110
 
        if (ret == -EBUSY && (retries++ < 5)) {
3111
 
            usleep(200*1000);
3112
 
            goto retry;
3113
 
        }
3114
 
        VIR_WARN("Failed to remove cgroup for %s",
3115
 
                 vm->def->name);
3116
 
    }
3117
 
 
3118
 
    qemudRemoveDomainStatus(driver, vm);
3119
 
 
3120
 
    /* Remove VNC port from port reservation bitmap, but only if it was
3121
 
       reserved by the driver (autoport=yes)
3122
 
    */
3123
 
    if ((vm->def->ngraphics == 1) &&
3124
 
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
3125
 
        vm->def->graphics[0]->data.vnc.autoport) {
3126
 
        qemuReturnPort(driver, vm->def->graphics[0]->data.vnc.port);
3127
 
    }
3128
 
    if ((vm->def->ngraphics == 1) &&
3129
 
        vm->def->graphics[0]->type == VIR_DOMAIN_GRAPHICS_TYPE_SPICE &&
3130
 
        vm->def->graphics[0]->data.spice.autoport) {
3131
 
        qemuReturnPort(driver, vm->def->graphics[0]->data.spice.port);
3132
 
        qemuReturnPort(driver, vm->def->graphics[0]->data.spice.tlsPort);
3133
 
    }
3134
 
 
3135
 
    vm->pid = -1;
3136
 
    vm->def->id = -1;
3137
 
    vm->state = VIR_DOMAIN_SHUTOFF;
3138
 
    VIR_FREE(priv->vcpupids);
3139
 
    priv->nvcpupids = 0;
3140
 
 
3141
 
    if (vm->newDef) {
3142
 
        virDomainDefFree(vm->def);
3143
 
        vm->def = vm->newDef;
3144
 
        vm->def->id = -1;
3145
 
        vm->newDef = NULL;
3146
 
    }
3147
 
 
3148
 
    if (orig_err) {
3149
 
        virSetError(orig_err);
3150
 
        virFreeError(orig_err);
3151
 
    }
3152
 
}
3153
 
 
3154
 
static virDrvOpenStatus qemudOpen(virConnectPtr conn,
3155
 
                                  virConnectAuthPtr auth ATTRIBUTE_UNUSED,
3156
 
                                  int flags ATTRIBUTE_UNUSED) {
3157
 
    if (conn->uri == NULL) {
3158
 
        if (qemu_driver == NULL)
3159
 
            return VIR_DRV_OPEN_DECLINED;
3160
 
 
3161
 
        conn->uri = xmlParseURI(qemu_driver->privileged ?
3162
 
                                "qemu:///system" :
3163
 
                                "qemu:///session");
3164
 
        if (!conn->uri) {
3165
 
            virReportOOMError();
3166
 
            return VIR_DRV_OPEN_ERROR;
3167
 
        }
3168
 
    } else {
3169
 
        /* If URI isn't 'qemu' its definitely not for us */
3170
 
        if (conn->uri->scheme == NULL ||
3171
 
            STRNEQ(conn->uri->scheme, "qemu"))
3172
 
            return VIR_DRV_OPEN_DECLINED;
3173
 
 
3174
 
        /* Allow remote driver to deal with URIs with hostname server */
3175
 
        if (conn->uri->server != NULL)
3176
 
            return VIR_DRV_OPEN_DECLINED;
3177
 
 
3178
 
        if (qemu_driver == NULL) {
3179
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3180
 
                            _("qemu state driver is not active"));
3181
 
            return VIR_DRV_OPEN_ERROR;
3182
 
        }
3183
 
 
3184
 
        if (conn->uri->path == NULL) {
3185
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
3186
 
                            _("no QEMU URI path given, try %s"),
3187
 
                            qemu_driver->privileged
3188
 
                            ? "qemu:///system"
3189
 
                            : "qemu:///session");
3190
 
                return VIR_DRV_OPEN_ERROR;
3191
 
        }
3192
 
 
3193
 
        if (qemu_driver->privileged) {
3194
 
            if (STRNEQ (conn->uri->path, "/system") &&
3195
 
                STRNEQ (conn->uri->path, "/session")) {
3196
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
3197
 
                                _("unexpected QEMU URI path '%s', try qemu:///system"),
3198
 
                                conn->uri->path);
3199
 
                return VIR_DRV_OPEN_ERROR;
3200
 
            }
3201
 
        } else {
3202
 
            if (STRNEQ (conn->uri->path, "/session")) {
3203
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
3204
 
                                _("unexpected QEMU URI path '%s', try qemu:///session"),
3205
 
                                conn->uri->path);
3206
 
                return VIR_DRV_OPEN_ERROR;
3207
 
            }
3208
 
        }
3209
 
    }
3210
 
    conn->privateData = qemu_driver;
3211
 
 
3212
 
    return VIR_DRV_OPEN_SUCCESS;
3213
 
}
3214
 
 
3215
 
static int qemudClose(virConnectPtr conn) {
3216
 
    struct qemud_driver *driver = conn->privateData;
3217
 
 
3218
 
    /* Get rid of callbacks registered for this conn */
3219
 
    qemuDriverLock(driver);
3220
 
    virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
3221
 
    qemuDriverUnlock(driver);
3222
 
 
3223
 
    conn->privateData = NULL;
3224
 
 
3225
 
    return 0;
3226
 
}
3227
 
 
3228
 
/* Which features are supported by this driver? */
3229
 
static int
3230
 
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
3231
 
{
3232
 
    switch (feature) {
3233
 
    case VIR_DRV_FEATURE_MIGRATION_V2:
3234
 
    case VIR_DRV_FEATURE_MIGRATION_P2P:
3235
 
        return 1;
3236
 
    default:
3237
 
        return 0;
3238
 
    }
3239
 
}
3240
 
 
3241
 
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
3242
 
    return "QEMU";
3243
 
}
3244
 
 
3245
 
 
3246
 
static int qemuIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
3247
 
{
3248
 
    /* Trivially secure, since always inside the daemon */
3249
 
    return 1;
3250
 
}
3251
 
 
3252
 
static int qemuIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
3253
 
{
3254
 
    /* Not encrypted, but remote driver takes care of that */
3255
 
    return 0;
3256
 
}
3257
 
 
3258
 
 
3259
 
static int kvmGetMaxVCPUs(void) {
3260
 
    int maxvcpus = 1;
3261
 
 
3262
 
    int r, fd;
3263
 
 
3264
 
    fd = open(KVM_DEVICE, O_RDONLY);
3265
 
    if (fd < 0) {
3266
 
        virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
3267
 
        return -1;
3268
 
    }
3269
 
 
3270
 
    r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS);
3271
 
    if (r > 0)
3272
 
        maxvcpus = r;
3273
 
 
3274
 
    VIR_FORCE_CLOSE(fd);
3275
 
    return maxvcpus;
3276
 
}
3277
 
 
3278
 
 
3279
 
static char *
3280
 
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
3281
 
{
3282
 
    struct qemud_driver *driver = conn->privateData;
3283
 
 
3284
 
    virCheckFlags(0, NULL);
3285
 
 
3286
 
    if (!driver->hostsysinfo) {
3287
 
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3288
 
                        _("Host SMBIOS information is not available"));
3289
 
        return NULL;
3290
 
    }
3291
 
 
3292
 
    return virSysinfoFormat(driver->hostsysinfo, "");
3293
 
}
3294
 
 
3295
 
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
3296
 
    if (!type)
3297
 
        return 16;
3298
 
 
3299
 
    if (STRCASEEQ(type, "qemu"))
3300
 
        return 16;
3301
 
 
3302
 
    if (STRCASEEQ(type, "kvm"))
3303
 
        return kvmGetMaxVCPUs();
3304
 
 
3305
 
    if (STRCASEEQ(type, "kqemu"))
3306
 
        return 1;
3307
 
 
3308
 
    qemuReportError(VIR_ERR_INVALID_ARG,
3309
 
                    _("unknown type '%s'"), type);
3310
 
    return -1;
3311
 
}
3312
 
 
3313
 
 
3314
 
static char *qemudGetCapabilities(virConnectPtr conn) {
3315
 
    struct qemud_driver *driver = conn->privateData;
3316
 
    virCapsPtr caps = NULL;
3317
 
    char *xml = NULL;
3318
 
 
3319
 
    qemuDriverLock(driver);
3320
 
 
3321
 
    if ((caps = qemuCreateCapabilities(qemu_driver->caps,
3322
 
                                       qemu_driver)) == NULL) {
3323
 
        virCapabilitiesFree(caps);
3324
 
        goto cleanup;
3325
 
    }
3326
 
 
3327
 
    virCapabilitiesFree(qemu_driver->caps);
3328
 
    qemu_driver->caps = caps;
3329
 
 
3330
 
    if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
3331
 
        virReportOOMError();
3332
 
 
3333
 
cleanup:
3334
 
    qemuDriverUnlock(driver);
3335
 
 
3336
 
    return xml;
3337
 
}
3338
 
 
3339
 
 
3340
 
static int
3341
 
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
3342
 
                    int tid)
3343
 
{
3344
 
    char *proc;
3345
 
    FILE *pidinfo;
3346
 
    unsigned long long usertime, systime;
3347
 
    int cpu;
3348
 
    int ret;
3349
 
 
3350
 
    if (tid)
3351
 
        ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
3352
 
    else
3353
 
        ret = virAsprintf(&proc, "/proc/%d/stat", pid);
3354
 
    if (ret < 0)
3355
 
        return -1;
3356
 
 
3357
 
    if (!(pidinfo = fopen(proc, "r"))) {
3358
 
        /* VM probably shut down, so fake 0 */
3359
 
        if (cpuTime)
3360
 
            *cpuTime = 0;
3361
 
        if (lastCpu)
3362
 
            *lastCpu = 0;
3363
 
        VIR_FREE(proc);
3364
 
        return 0;
3365
 
    }
3366
 
    VIR_FREE(proc);
3367
 
 
3368
 
    /* See 'man proc' for information about what all these fields are. We're
3369
 
     * only interested in a very few of them */
3370
 
    if (fscanf(pidinfo,
3371
 
               /* pid -> stime */
3372
 
               "%*d %*s %*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %llu %llu"
3373
 
               /* cutime -> endcode */
3374
 
               "%*d %*d %*d %*d %*d %*u %*u %*d %*u %*u %*u %*u"
3375
 
               /* startstack -> processor */
3376
 
               "%*u %*u %*u %*u %*u %*u %*u %*u %*u %*u %*d %d",
3377
 
               &usertime, &systime, &cpu) != 3) {
3378
 
        VIR_FORCE_FCLOSE(pidinfo);
3379
 
        VIR_WARN0("cannot parse process status data");
3380
 
        errno = -EINVAL;
3381
 
        return -1;
3382
 
    }
3383
 
 
3384
 
    /* We got jiffies
3385
 
     * We want nanoseconds
3386
 
     * _SC_CLK_TCK is jiffies per second
3387
 
     * So calulate thus....
3388
 
     */
3389
 
    if (cpuTime)
3390
 
        *cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
3391
 
    if (lastCpu)
3392
 
        *lastCpu = cpu;
3393
 
 
3394
 
 
3395
 
    VIR_DEBUG("Got status for %d/%d user=%llu sys=%llu cpu=%d",
3396
 
              pid, tid, usertime, systime, cpu);
3397
 
 
3398
 
    VIR_FORCE_FCLOSE(pidinfo);
3399
 
 
3400
 
    return 0;
3401
 
}
3402
 
 
3403
 
 
3404
 
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
3405
 
                                          int id) {
3406
 
    struct qemud_driver *driver = conn->privateData;
3407
 
    virDomainObjPtr vm;
3408
 
    virDomainPtr dom = NULL;
3409
 
 
3410
 
    qemuDriverLock(driver);
3411
 
    vm  = virDomainFindByID(&driver->domains, id);
3412
 
    qemuDriverUnlock(driver);
3413
 
 
3414
 
    if (!vm) {
3415
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3416
 
                        _("no domain with matching id %d"), id);
3417
 
        goto cleanup;
3418
 
    }
3419
 
 
3420
 
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3421
 
    if (dom) dom->id = vm->def->id;
3422
 
 
3423
 
cleanup:
3424
 
    if (vm)
3425
 
        virDomainObjUnlock(vm);
3426
 
    return dom;
3427
 
}
3428
 
 
3429
 
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
3430
 
                                            const unsigned char *uuid) {
3431
 
    struct qemud_driver *driver = conn->privateData;
3432
 
    virDomainObjPtr vm;
3433
 
    virDomainPtr dom = NULL;
3434
 
 
3435
 
    qemuDriverLock(driver);
3436
 
    vm = virDomainFindByUUID(&driver->domains, uuid);
3437
 
    qemuDriverUnlock(driver);
3438
 
 
3439
 
    if (!vm) {
3440
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3441
 
        virUUIDFormat(uuid, uuidstr);
3442
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3443
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3444
 
        goto cleanup;
3445
 
    }
3446
 
 
3447
 
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3448
 
    if (dom) dom->id = vm->def->id;
3449
 
 
3450
 
cleanup:
3451
 
    if (vm)
3452
 
        virDomainObjUnlock(vm);
3453
 
    return dom;
3454
 
}
3455
 
 
3456
 
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
3457
 
                                            const char *name) {
3458
 
    struct qemud_driver *driver = conn->privateData;
3459
 
    virDomainObjPtr vm;
3460
 
    virDomainPtr dom = NULL;
3461
 
 
3462
 
    qemuDriverLock(driver);
3463
 
    vm = virDomainFindByName(&driver->domains, name);
3464
 
    qemuDriverUnlock(driver);
3465
 
 
3466
 
    if (!vm) {
3467
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3468
 
                        _("no domain with matching name '%s'"), name);
3469
 
        goto cleanup;
3470
 
    }
3471
 
 
3472
 
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3473
 
    if (dom) dom->id = vm->def->id;
3474
 
 
3475
 
cleanup:
3476
 
    if (vm)
3477
 
        virDomainObjUnlock(vm);
3478
 
    return dom;
3479
 
}
3480
 
 
3481
 
 
3482
 
static int qemuDomainIsActive(virDomainPtr dom)
3483
 
{
3484
 
    struct qemud_driver *driver = dom->conn->privateData;
3485
 
    virDomainObjPtr obj;
3486
 
    int ret = -1;
3487
 
 
3488
 
    qemuDriverLock(driver);
3489
 
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
3490
 
    qemuDriverUnlock(driver);
3491
 
    if (!obj) {
3492
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3493
 
        virUUIDFormat(dom->uuid, uuidstr);
3494
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3495
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3496
 
        goto cleanup;
3497
 
    }
3498
 
    ret = virDomainObjIsActive(obj);
3499
 
 
3500
 
cleanup:
3501
 
    if (obj)
3502
 
        virDomainObjUnlock(obj);
3503
 
    return ret;
3504
 
}
3505
 
 
3506
 
static int qemuDomainIsPersistent(virDomainPtr dom)
3507
 
{
3508
 
    struct qemud_driver *driver = dom->conn->privateData;
3509
 
    virDomainObjPtr obj;
3510
 
    int ret = -1;
3511
 
 
3512
 
    qemuDriverLock(driver);
3513
 
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
3514
 
    qemuDriverUnlock(driver);
3515
 
    if (!obj) {
3516
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3517
 
        virUUIDFormat(dom->uuid, uuidstr);
3518
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3519
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3520
 
        goto cleanup;
3521
 
    }
3522
 
    ret = obj->persistent;
3523
 
 
3524
 
cleanup:
3525
 
    if (obj)
3526
 
        virDomainObjUnlock(obj);
3527
 
    return ret;
3528
 
}
3529
 
 
3530
 
static int qemuDomainIsUpdated(virDomainPtr dom)
3531
 
{
3532
 
    struct qemud_driver *driver = dom->conn->privateData;
3533
 
    virDomainObjPtr obj;
3534
 
    int ret = -1;
3535
 
 
3536
 
    qemuDriverLock(driver);
3537
 
    obj = virDomainFindByUUID(&driver->domains, dom->uuid);
3538
 
    qemuDriverUnlock(driver);
3539
 
    if (!obj) {
3540
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3541
 
        virUUIDFormat(dom->uuid, uuidstr);
3542
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3543
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3544
 
        goto cleanup;
3545
 
    }
3546
 
    ret = obj->updated;
3547
 
 
3548
 
cleanup:
3549
 
    if (obj)
3550
 
        virDomainObjUnlock(obj);
3551
 
    return ret;
3552
 
}
3553
 
 
3554
 
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
3555
 
    struct qemud_driver *driver = conn->privateData;
3556
 
    int ret = -1;
3557
 
 
3558
 
    qemuDriverLock(driver);
3559
 
    if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
3560
 
        goto cleanup;
3561
 
 
3562
 
    *version = driver->qemuVersion;
3563
 
    ret = 0;
3564
 
 
3565
 
cleanup:
3566
 
    qemuDriverUnlock(driver);
3567
 
    return ret;
3568
 
}
3569
 
 
3570
 
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
3571
 
    struct qemud_driver *driver = conn->privateData;
3572
 
    int n;
3573
 
 
3574
 
    qemuDriverLock(driver);
3575
 
    n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
3576
 
    qemuDriverUnlock(driver);
3577
 
 
3578
 
    return n;
3579
 
}
3580
 
 
3581
 
static int qemudNumDomains(virConnectPtr conn) {
3582
 
    struct qemud_driver *driver = conn->privateData;
3583
 
    int n;
3584
 
 
3585
 
    qemuDriverLock(driver);
3586
 
    n = virDomainObjListNumOfDomains(&driver->domains, 1);
3587
 
    qemuDriverUnlock(driver);
3588
 
 
3589
 
    return n;
3590
 
}
3591
 
 
3592
 
static virDomainPtr qemudDomainCreate(virConnectPtr conn, const char *xml,
3593
 
                                      unsigned int flags) {
3594
 
    struct qemud_driver *driver = conn->privateData;
3595
 
    virDomainDefPtr def;
3596
 
    virDomainObjPtr vm = NULL;
3597
 
    virDomainPtr dom = NULL;
3598
 
    virDomainEventPtr event = NULL;
3599
 
 
3600
 
    virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);
3601
 
 
3602
 
    qemuDriverLock(driver);
3603
 
    if (!(def = virDomainDefParseString(driver->caps, xml,
3604
 
                                        VIR_DOMAIN_XML_INACTIVE)))
3605
 
        goto cleanup;
3606
 
 
3607
 
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
3608
 
        goto cleanup;
3609
 
 
3610
 
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
3611
 
        goto cleanup;
3612
 
 
3613
 
    if (qemudCanonicalizeMachine(driver, def) < 0)
3614
 
        goto cleanup;
3615
 
 
3616
 
    if (qemuAssignPCIAddresses(def) < 0)
3617
 
        goto cleanup;
3618
 
 
3619
 
    if (!(vm = virDomainAssignDef(driver->caps,
3620
 
                                  &driver->domains,
3621
 
                                  def, false)))
3622
 
        goto cleanup;
3623
 
 
3624
 
    def = NULL;
3625
 
 
3626
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3627
 
        goto cleanup; /* XXXX free the 'vm' we created ? */
3628
 
 
3629
 
    if (qemudStartVMDaemon(conn, driver, vm, NULL,
3630
 
                           (flags & VIR_DOMAIN_START_PAUSED) != 0,
3631
 
                           -1, NULL, VIR_VM_OP_CREATE) < 0) {
3632
 
        qemuDomainStartAudit(vm, "booted", false);
3633
 
        if (qemuDomainObjEndJob(vm) > 0)
3634
 
            virDomainRemoveInactive(&driver->domains,
3635
 
                                    vm);
3636
 
        vm = NULL;
3637
 
        goto cleanup;
3638
 
    }
3639
 
 
3640
 
    event = virDomainEventNewFromObj(vm,
3641
 
                                     VIR_DOMAIN_EVENT_STARTED,
3642
 
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
3643
 
    qemuDomainStartAudit(vm, "booted", true);
3644
 
 
3645
 
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3646
 
    if (dom) dom->id = vm->def->id;
3647
 
 
3648
 
    if (vm &&
3649
 
        qemuDomainObjEndJob(vm) == 0)
3650
 
        vm = NULL;
3651
 
 
3652
 
cleanup:
3653
 
    virDomainDefFree(def);
3654
 
    if (vm)
3655
 
        virDomainObjUnlock(vm);
3656
 
    if (event)
3657
 
        qemuDomainEventQueue(driver, event);
3658
 
    qemuDriverUnlock(driver);
3659
 
    return dom;
3660
 
}
3661
 
 
3662
 
 
3663
 
static int qemudDomainSuspend(virDomainPtr dom) {
3664
 
    struct qemud_driver *driver = dom->conn->privateData;
3665
 
    virDomainObjPtr vm;
3666
 
    int ret = -1;
3667
 
    virDomainEventPtr event = NULL;
3668
 
    qemuDomainObjPrivatePtr priv;
3669
 
 
3670
 
    qemuDriverLock(driver);
3671
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3672
 
 
3673
 
    if (!vm) {
3674
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3675
 
        virUUIDFormat(dom->uuid, uuidstr);
3676
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3677
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3678
 
        goto cleanup;
3679
 
    }
3680
 
    if (!virDomainObjIsActive(vm)) {
3681
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3682
 
                        "%s", _("domain is not running"));
3683
 
        goto cleanup;
3684
 
    }
3685
 
 
3686
 
    priv = vm->privateData;
3687
 
 
3688
 
    if (priv->jobActive == QEMU_JOB_MIGRATION_OUT) {
3689
 
        if (vm->state != VIR_DOMAIN_PAUSED) {
3690
 
            VIR_DEBUG("Requesting domain pause on %s",
3691
 
                      vm->def->name);
3692
 
            priv->jobSignals |= QEMU_JOB_SIGNAL_SUSPEND;
3693
 
        }
3694
 
        ret = 0;
3695
 
        goto cleanup;
3696
 
    } else {
3697
 
        if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3698
 
            goto cleanup;
3699
 
 
3700
 
        if (!virDomainObjIsActive(vm)) {
3701
 
            qemuReportError(VIR_ERR_OPERATION_INVALID,
3702
 
                            "%s", _("domain is not running"));
3703
 
            goto endjob;
3704
 
        }
3705
 
        if (vm->state != VIR_DOMAIN_PAUSED) {
3706
 
            if (doStopCPUs(driver, vm) < 0) {
3707
 
                goto endjob;
3708
 
            }
3709
 
            event = virDomainEventNewFromObj(vm,
3710
 
                                             VIR_DOMAIN_EVENT_SUSPENDED,
3711
 
                                             VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
3712
 
        }
3713
 
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
3714
 
            goto endjob;
3715
 
        ret = 0;
3716
 
    }
3717
 
 
3718
 
endjob:
3719
 
    if (qemuDomainObjEndJob(vm) == 0)
3720
 
        vm = NULL;
3721
 
 
3722
 
cleanup:
3723
 
    if (vm)
3724
 
        virDomainObjUnlock(vm);
3725
 
 
3726
 
    if (event)
3727
 
        qemuDomainEventQueue(driver, event);
3728
 
    qemuDriverUnlock(driver);
3729
 
    return ret;
3730
 
}
3731
 
 
3732
 
 
3733
 
static int qemudDomainResume(virDomainPtr dom) {
3734
 
    struct qemud_driver *driver = dom->conn->privateData;
3735
 
    virDomainObjPtr vm;
3736
 
    int ret = -1;
3737
 
    virDomainEventPtr event = NULL;
3738
 
 
3739
 
    qemuDriverLock(driver);
3740
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3741
 
 
3742
 
    if (!vm) {
3743
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3744
 
        virUUIDFormat(dom->uuid, uuidstr);
3745
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3746
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3747
 
        goto cleanup;
3748
 
    }
3749
 
 
3750
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3751
 
        goto cleanup;
3752
 
 
3753
 
    if (!virDomainObjIsActive(vm)) {
3754
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3755
 
                        "%s", _("domain is not running"));
3756
 
        goto endjob;
3757
 
    }
3758
 
    if (vm->state == VIR_DOMAIN_PAUSED) {
3759
 
        if (doStartCPUs(driver, vm, dom->conn) < 0) {
3760
 
            if (virGetLastError() == NULL)
3761
 
                qemuReportError(VIR_ERR_OPERATION_FAILED,
3762
 
                                "%s", _("resume operation failed"));
3763
 
            goto endjob;
3764
 
        }
3765
 
        event = virDomainEventNewFromObj(vm,
3766
 
                                         VIR_DOMAIN_EVENT_RESUMED,
3767
 
                                         VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
3768
 
    }
3769
 
    if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
3770
 
        goto endjob;
3771
 
    ret = 0;
3772
 
 
3773
 
endjob:
3774
 
    if (qemuDomainObjEndJob(vm) == 0)
3775
 
        vm = NULL;
3776
 
 
3777
 
cleanup:
3778
 
    if (vm)
3779
 
        virDomainObjUnlock(vm);
3780
 
    if (event)
3781
 
        qemuDomainEventQueue(driver, event);
3782
 
    qemuDriverUnlock(driver);
3783
 
    return ret;
3784
 
}
3785
 
 
3786
 
 
3787
 
static int qemudDomainShutdown(virDomainPtr dom) {
3788
 
    struct qemud_driver *driver = dom->conn->privateData;
3789
 
    virDomainObjPtr vm;
3790
 
    int ret = -1;
3791
 
 
3792
 
    qemuDriverLock(driver);
3793
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3794
 
    qemuDriverUnlock(driver);
3795
 
 
3796
 
    if (!vm) {
3797
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3798
 
        virUUIDFormat(dom->uuid, uuidstr);
3799
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3800
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3801
 
        goto cleanup;
3802
 
    }
3803
 
 
3804
 
    if (qemuDomainObjBeginJob(vm) < 0)
3805
 
        goto cleanup;
3806
 
 
3807
 
    if (!virDomainObjIsActive(vm)) {
3808
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3809
 
                        "%s", _("domain is not running"));
3810
 
        goto endjob;
3811
 
    }
3812
 
 
3813
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
3814
 
    qemuDomainObjEnterMonitor(vm);
3815
 
    ret = qemuMonitorSystemPowerdown(priv->mon);
3816
 
    qemuDomainObjExitMonitor(vm);
3817
 
 
3818
 
endjob:
3819
 
    if (qemuDomainObjEndJob(vm) == 0)
3820
 
        vm = NULL;
3821
 
 
3822
 
cleanup:
3823
 
    if (vm)
3824
 
        virDomainObjUnlock(vm);
3825
 
    return ret;
3826
 
}
3827
 
 
3828
 
 
3829
 
static int qemudDomainDestroy(virDomainPtr dom) {
3830
 
    struct qemud_driver *driver = dom->conn->privateData;
3831
 
    virDomainObjPtr vm;
3832
 
    int ret = -1;
3833
 
    virDomainEventPtr event = NULL;
3834
 
 
3835
 
    qemuDriverLock(driver);
3836
 
    vm  = virDomainFindByUUID(&driver->domains, dom->uuid);
3837
 
    if (!vm) {
3838
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3839
 
        virUUIDFormat(dom->uuid, uuidstr);
3840
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3841
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3842
 
        goto cleanup;
3843
 
    }
3844
 
 
3845
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3846
 
        goto cleanup;
3847
 
 
3848
 
    if (!virDomainObjIsActive(vm)) {
3849
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3850
 
                        "%s", _("domain is not running"));
3851
 
        goto endjob;
3852
 
    }
3853
 
 
3854
 
    qemudShutdownVMDaemon(driver, vm, 0);
3855
 
    event = virDomainEventNewFromObj(vm,
3856
 
                                     VIR_DOMAIN_EVENT_STOPPED,
3857
 
                                     VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
3858
 
    qemuDomainStopAudit(vm, "destroyed");
3859
 
 
3860
 
    if (!vm->persistent) {
3861
 
        if (qemuDomainObjEndJob(vm) > 0)
3862
 
            virDomainRemoveInactive(&driver->domains,
3863
 
                                    vm);
3864
 
        vm = NULL;
3865
 
    }
3866
 
    ret = 0;
3867
 
 
3868
 
endjob:
3869
 
    if (vm &&
3870
 
        qemuDomainObjEndJob(vm) == 0)
3871
 
        vm = NULL;
3872
 
 
3873
 
cleanup:
3874
 
    if (vm)
3875
 
        virDomainObjUnlock(vm);
3876
 
    if (event)
3877
 
        qemuDomainEventQueue(driver, event);
3878
 
    qemuDriverUnlock(driver);
3879
 
    return ret;
3880
 
}
3881
 
 
3882
 
 
3883
 
static char *qemudDomainGetOSType(virDomainPtr dom) {
3884
 
    struct qemud_driver *driver = dom->conn->privateData;
3885
 
    virDomainObjPtr vm;
3886
 
    char *type = NULL;
3887
 
 
3888
 
    qemuDriverLock(driver);
3889
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3890
 
    qemuDriverUnlock(driver);
3891
 
    if (!vm) {
3892
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3893
 
        virUUIDFormat(dom->uuid, uuidstr);
3894
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3895
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3896
 
        goto cleanup;
3897
 
    }
3898
 
 
3899
 
    if (!(type = strdup(vm->def->os.type)))
3900
 
        virReportOOMError();
3901
 
 
3902
 
cleanup:
3903
 
    if (vm)
3904
 
        virDomainObjUnlock(vm);
3905
 
    return type;
3906
 
}
3907
 
 
3908
 
/* Returns max memory in kb, 0 if error */
3909
 
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
3910
 
    struct qemud_driver *driver = dom->conn->privateData;
3911
 
    virDomainObjPtr vm;
3912
 
    unsigned long ret = 0;
3913
 
 
3914
 
    qemuDriverLock(driver);
3915
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3916
 
    qemuDriverUnlock(driver);
3917
 
 
3918
 
    if (!vm) {
3919
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3920
 
        virUUIDFormat(dom->uuid, uuidstr);
3921
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3922
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3923
 
        goto cleanup;
3924
 
    }
3925
 
 
3926
 
    ret = vm->def->mem.max_balloon;
3927
 
 
3928
 
cleanup:
3929
 
    if (vm)
3930
 
        virDomainObjUnlock(vm);
3931
 
    return ret;
3932
 
}
3933
 
 
3934
 
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
3935
 
    struct qemud_driver *driver = dom->conn->privateData;
3936
 
    qemuDomainObjPrivatePtr priv;
3937
 
    virDomainObjPtr vm;
3938
 
    int ret = -1, r;
3939
 
 
3940
 
    qemuDriverLock(driver);
3941
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3942
 
    qemuDriverUnlock(driver);
3943
 
    if (!vm) {
3944
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
3945
 
        virUUIDFormat(dom->uuid, uuidstr);
3946
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
3947
 
                        _("no domain with matching uuid '%s'"), uuidstr);
3948
 
        goto cleanup;
3949
 
    }
3950
 
 
3951
 
    if (newmem > vm->def->mem.max_balloon) {
3952
 
        qemuReportError(VIR_ERR_INVALID_ARG,
3953
 
                        "%s", _("cannot set memory higher than max memory"));
3954
 
        goto cleanup;
3955
 
    }
3956
 
 
3957
 
    if (qemuDomainObjBeginJob(vm) < 0)
3958
 
        goto cleanup;
3959
 
 
3960
 
    if (!virDomainObjIsActive(vm)) {
3961
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3962
 
                        "%s", _("domain is not running"));
3963
 
        goto endjob;
3964
 
    }
3965
 
 
3966
 
    priv = vm->privateData;
3967
 
    qemuDomainObjEnterMonitor(vm);
3968
 
    r = qemuMonitorSetBalloon(priv->mon, newmem);
3969
 
    qemuDomainObjExitMonitor(vm);
3970
 
    if (r < 0)
3971
 
        goto endjob;
3972
 
 
3973
 
    /* Lack of balloon support is a fatal error */
3974
 
    if (r == 0) {
3975
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
3976
 
                        "%s", _("cannot set memory of an active domain"));
3977
 
        goto endjob;
3978
 
    }
3979
 
 
3980
 
    ret = 0;
3981
 
endjob:
3982
 
    if (qemuDomainObjEndJob(vm) == 0)
3983
 
        vm = NULL;
3984
 
 
3985
 
cleanup:
3986
 
    if (vm)
3987
 
        virDomainObjUnlock(vm);
3988
 
    return ret;
3989
 
}
3990
 
 
3991
 
static int qemudDomainGetInfo(virDomainPtr dom,
3992
 
                              virDomainInfoPtr info) {
3993
 
    struct qemud_driver *driver = dom->conn->privateData;
3994
 
    virDomainObjPtr vm;
3995
 
    int ret = -1;
3996
 
    int err;
3997
 
    unsigned long balloon;
3998
 
 
3999
 
    qemuDriverLock(driver);
4000
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4001
 
    qemuDriverUnlock(driver);
4002
 
    if (!vm) {
4003
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
4004
 
        virUUIDFormat(dom->uuid, uuidstr);
4005
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
4006
 
                        _("no domain with matching uuid '%s'"), uuidstr);
4007
 
        goto cleanup;
4008
 
    }
4009
 
 
4010
 
    info->state = vm->state;
4011
 
 
4012
 
    if (!virDomainObjIsActive(vm)) {
4013
 
        info->cpuTime = 0;
4014
 
    } else {
4015
 
        if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
4016
 
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
4017
 
                            _("cannot read cputime for domain"));
4018
 
            goto cleanup;
4019
 
        }
4020
 
    }
4021
 
 
4022
 
    info->maxMem = vm->def->mem.max_balloon;
4023
 
 
4024
 
    if (virDomainObjIsActive(vm)) {
4025
 
        qemuDomainObjPrivatePtr priv = vm->privateData;
4026
 
 
4027
 
        if ((vm->def->memballoon != NULL) &&
4028
 
            (vm->def->memballoon->model == VIR_DOMAIN_MEMBALLOON_MODEL_NONE)) {
4029
 
            info->memory = vm->def->mem.max_balloon;
4030
 
        } else if (!priv->jobActive) {
4031
 
            if (qemuDomainObjBeginJob(vm) < 0)
4032
 
                goto cleanup;
4033
 
            if (!virDomainObjIsActive(vm))
4034
 
                err = 0;
4035
 
            else {
4036
 
                qemuDomainObjEnterMonitor(vm);
4037
 
                err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
4038
 
                qemuDomainObjExitMonitor(vm);
4039
 
            }
4040
 
            if (qemuDomainObjEndJob(vm) == 0) {
4041
 
                vm = NULL;
4042
 
                goto cleanup;
4043
 
            }
4044
 
 
4045
 
            if (err < 0)
4046
 
                goto cleanup;
4047
 
            if (err == 0)
4048
 
                /* Balloon not supported, so maxmem is always the allocation */
4049
 
                info->memory = vm->def->mem.max_balloon;
4050
 
            else
4051
 
                info->memory = balloon;
4052
 
        } else {
4053
 
            info->memory = vm->def->mem.cur_balloon;
4054
 
        }
4055
 
    } else {
4056
 
        info->memory = vm->def->mem.cur_balloon;
4057
 
    }
4058
 
 
4059
 
    info->nrVirtCpu = vm->def->vcpus;
4060
 
    ret = 0;
4061
 
 
4062
 
cleanup:
4063
 
    if (vm)
4064
 
        virDomainObjUnlock(vm);
4065
 
    return ret;
4066
 
}
4067
 
 
4068
 
 
4069
 
/** qemuDomainMigrateOffline:
4070
 
 * Pause domain for non-live migration.
4071
 
 */
4072
 
static int
4073
 
qemuDomainMigrateOffline(struct qemud_driver *driver,
4074
 
                         virDomainObjPtr vm)
4075
 
{
4076
 
    int ret;
4077
 
 
4078
 
    ret = doStopCPUs(driver, vm);
4079
 
    if (ret == 0) {
4080
 
        virDomainEventPtr event;
4081
 
 
4082
 
        event = virDomainEventNewFromObj(vm,
4083
 
                                         VIR_DOMAIN_EVENT_SUSPENDED,
4084
 
                                         VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
4085
 
        if (event)
4086
 
            qemuDomainEventQueue(driver, event);
4087
 
    }
4088
 
 
4089
 
    return ret;
4090
 
}
4091
 
 
4092
 
 
4093
 
static int
4094
 
qemuDomainWaitForMigrationComplete(struct qemud_driver *driver, virDomainObjPtr vm)
4095
 
{
4096
 
    int ret = -1;
4097
 
    int status;
4098
 
    unsigned long long memProcessed;
4099
 
    unsigned long long memRemaining;
4100
 
    unsigned long long memTotal;
4101
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
4102
 
 
4103
 
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
4104
 
 
4105
 
    while (priv->jobInfo.type == VIR_DOMAIN_JOB_UNBOUNDED) {
4106
 
        /* Poll every 50ms for progress & to allow cancellation */
4107
 
        struct timespec ts = { .tv_sec = 0, .tv_nsec = 50 * 1000 * 1000ull };
4108
 
        struct timeval now;
4109
 
        int rc;
4110
 
        const char *job;
4111
 
 
4112
 
        switch (priv->jobActive) {
4113
 
            case QEMU_JOB_MIGRATION_OUT:
4114
 
                job = _("migration job");
4115
 
                break;
4116
 
            case QEMU_JOB_SAVE:
4117
 
                job = _("domain save job");
4118
 
                break;
4119
 
            case QEMU_JOB_DUMP:
4120
 
                job = _("domain core dump job");
4121
 
                break;
4122
 
            default:
4123
 
                job = _("job");
4124
 
        }
4125
 
 
4126
 
 
4127
 
        if (!virDomainObjIsActive(vm)) {
4128
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, _("%s: %s"),
4129
 
                            job, _("guest unexpectedly quit"));
4130
 
            goto cleanup;
4131
 
        }
4132
 
 
4133
 
        if (priv->jobSignals & QEMU_JOB_SIGNAL_CANCEL) {
4134
 
            priv->jobSignals ^= QEMU_JOB_SIGNAL_CANCEL;
4135
 
            VIR_DEBUG0("Cancelling job at client request");
4136
 
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
4137
 
            rc = qemuMonitorMigrateCancel(priv->mon);
4138
 
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4139
 
            if (rc < 0) {
4140
 
                VIR_WARN0("Unable to cancel job");
4141
 
            }
4142
 
        } else if (priv->jobSignals & QEMU_JOB_SIGNAL_SUSPEND) {
4143
 
            priv->jobSignals ^= QEMU_JOB_SIGNAL_SUSPEND;
4144
 
            VIR_DEBUG0("Pausing domain for non-live migration");
4145
 
            if (qemuDomainMigrateOffline(driver, vm) < 0)
4146
 
                VIR_WARN0("Unable to pause domain");
4147
 
        } else if (priv->jobSignals & QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME) {
4148
 
            unsigned long long ms = priv->jobSignalsData.migrateDowntime;
4149
 
 
4150
 
            priv->jobSignals ^= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
4151
 
            priv->jobSignalsData.migrateDowntime = 0;
4152
 
            VIR_DEBUG("Setting migration downtime to %llums", ms);
4153
 
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
4154
 
            rc = qemuMonitorSetMigrationDowntime(priv->mon, ms);
4155
 
            qemuDomainObjExitMonitorWithDriver(driver, vm);
4156
 
            if (rc < 0)
4157
 
                VIR_WARN0("Unable to set migration downtime");
4158
 
        }
4159
 
 
4160
 
        /* Repeat check because the job signals might have caused
4161
 
         * guest to die
4162
 
         */
4163
 
        if (!virDomainObjIsActive(vm)) {
4164
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, _("%s: %s"),
4165
 
                            job, _("guest unexpectedly quit"));
4166
 
            goto cleanup;
4167
 
        }
4168
 
 
4169
 
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
4170
 
        rc = qemuMonitorGetMigrationStatus(priv->mon,
4171
 
                                           &status,
4172
 
                                           &memProcessed,
4173
 
                                           &memRemaining,
4174
 
                                           &memTotal);
4175
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
4176
 
 
4177
 
        if (rc < 0) {
4178
 
            priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
4179
 
            goto cleanup;
4180
 
        }
4181
 
 
4182
 
        if (gettimeofday(&now, NULL) < 0) {
4183
 
            priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
4184
 
            virReportSystemError(errno, "%s",
4185
 
                                 _("cannot get time of day"));
4186
 
            goto cleanup;
4187
 
        }
4188
 
        priv->jobInfo.timeElapsed = timeval_to_ms(now) - priv->jobStart;
4189
 
 
4190
 
        switch (status) {
4191
 
        case QEMU_MONITOR_MIGRATION_STATUS_INACTIVE:
4192
 
            priv->jobInfo.type = VIR_DOMAIN_JOB_NONE;
4193
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
4194
 
                            _("%s: %s"), job, _("is not active"));
4195
 
            break;
4196
 
 
4197
 
        case QEMU_MONITOR_MIGRATION_STATUS_ACTIVE:
4198
 
            priv->jobInfo.dataTotal = memTotal;
4199
 
            priv->jobInfo.dataRemaining = memRemaining;
4200
 
            priv->jobInfo.dataProcessed = memProcessed;
4201
 
 
4202
 
            priv->jobInfo.memTotal = memTotal;
4203
 
            priv->jobInfo.memRemaining = memRemaining;
4204
 
            priv->jobInfo.memProcessed = memProcessed;
4205
 
            break;
4206
 
 
4207
 
        case QEMU_MONITOR_MIGRATION_STATUS_COMPLETED:
4208
 
            priv->jobInfo.type = VIR_DOMAIN_JOB_COMPLETED;
4209
 
            ret = 0;
4210
 
            break;
4211
 
 
4212
 
        case QEMU_MONITOR_MIGRATION_STATUS_ERROR:
4213
 
            priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
4214
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
4215
 
                            _("%s: %s"), job, _("unexpectedly failed"));
4216
 
            break;
4217
 
 
4218
 
        case QEMU_MONITOR_MIGRATION_STATUS_CANCELLED:
4219
 
            priv->jobInfo.type = VIR_DOMAIN_JOB_CANCELLED;
4220
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
4221
 
                            _("%s: %s"), job, _("canceled by client"));
4222
 
            break;
4223
 
        }
4224
 
 
4225
 
        virDomainObjUnlock(vm);
4226
 
        qemuDriverUnlock(driver);
4227
 
 
4228
 
        nanosleep(&ts, NULL);
4229
 
 
4230
 
        qemuDriverLock(driver);
4231
 
        virDomainObjLock(vm);
4232
 
    }
4233
 
 
4234
 
cleanup:
4235
 
    return ret;
4236
 
}
4237
 
 
4238
 
 
4239
 
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
4240
 
#define QEMUD_SAVE_VERSION 2
4241
 
 
4242
 
enum qemud_save_formats {
4243
 
    QEMUD_SAVE_FORMAT_RAW = 0,
4244
 
    QEMUD_SAVE_FORMAT_GZIP = 1,
4245
 
    QEMUD_SAVE_FORMAT_BZIP2 = 2,
4246
 
    /*
4247
 
     * Deprecated by xz and never used as part of a release
4248
 
     * QEMUD_SAVE_FORMAT_LZMA
4249
 
     */
4250
 
    QEMUD_SAVE_FORMAT_XZ = 3,
4251
 
    QEMUD_SAVE_FORMAT_LZOP = 4,
4252
 
    /* Note: add new members only at the end.
4253
 
       These values are used in the on-disk format.
4254
 
       Do not change or re-use numbers. */
4255
 
 
4256
 
    QEMUD_SAVE_FORMAT_LAST
4257
 
};
4258
 
 
4259
 
VIR_ENUM_DECL(qemudSaveCompression)
4260
 
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
4261
 
              "raw",
4262
 
              "gzip",
4263
 
              "bzip2",
4264
 
              "xz",
4265
 
              "lzop")
4266
 
 
4267
 
struct qemud_save_header {
4268
 
    char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
4269
 
    int version;
4270
 
    int xml_len;
4271
 
    int was_running;
4272
 
    int compressed;
4273
 
    int unused[15];
4274
 
};
4275
 
 
4276
 
struct fileOpHookData {
4277
 
    virDomainPtr dom;
4278
 
    const char *path;
4279
 
    char *xml;
4280
 
    struct qemud_save_header *header;
4281
 
};
4282
 
 
4283
 
/* return -errno on failure, or 0 on success */
4284
 
static int qemudDomainSaveFileOpHook(int fd, void *data) {
4285
 
    struct fileOpHookData *hdata = data;
4286
 
    int ret = 0;
4287
 
 
4288
 
    if (safewrite(fd, hdata->header, sizeof(*hdata->header)) != sizeof(*hdata->header)) {
4289
 
        ret = -errno;
4290
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
4291
 
                        _("failed to write header to domain save file '%s'"),
4292
 
                        hdata->path);
4293
 
        goto endjob;
4294
 
    }
4295
 
 
4296
 
    if (safewrite(fd, hdata->xml, hdata->header->xml_len) != hdata->header->xml_len) {
4297
 
        ret = -errno;
4298
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
4299
 
                         _("failed to write xml to '%s'"), hdata->path);
4300
 
        goto endjob;
4301
 
    }
4302
 
endjob:
4303
 
    return ret;
4304
 
}
4305
 
 
4306
 
/* This internal function expects the driver lock to already be held on
4307
 
 * entry and the vm must be active.
4308
 
 */
4309
 
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
4310
 
                               virDomainObjPtr vm, const char *path,
4311
 
                               int compressed)
4312
 
{
4313
 
    char *xml = NULL;
4314
 
    struct qemud_save_header header;
4315
 
    struct fileOpHookData hdata;
4316
 
    int bypassSecurityDriver = 0;
4317
 
    int ret = -1;
4318
 
    int rc;
4319
 
    virDomainEventPtr event = NULL;
4320
 
    qemuDomainObjPrivatePtr priv;
4321
 
    struct stat sb;
4322
 
    int is_reg = 0;
4323
 
    unsigned long long offset;
4324
 
    virCgroupPtr cgroup = NULL;
4325
 
 
4326
 
    memset(&header, 0, sizeof(header));
4327
 
    memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
4328
 
    header.version = QEMUD_SAVE_VERSION;
4329
 
 
4330
 
    header.compressed = compressed;
4331
 
 
4332
 
    priv = vm->privateData;
4333
 
 
4334
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
4335
 
        goto cleanup;
4336
 
 
4337
 
    priv->jobActive = QEMU_JOB_SAVE;
4338
 
 
4339
 
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
4340
 
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
4341
 
 
4342
 
    /* Pause */
4343
 
    if (vm->state == VIR_DOMAIN_RUNNING) {
4344
 
        header.was_running = 1;
4345
 
        if (doStopCPUs(driver, vm) < 0)
4346
 
            goto endjob;
4347
 
 
4348
 
        if (!virDomainObjIsActive(vm)) {
4349
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4350
 
                            _("guest unexpectedly quit"));
4351
 
            goto endjob;
4352
 
        }
4353
 
    }
4354
 
 
4355
 
    /* Get XML for the domain */
4356
 
    xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
4357
 
    if (!xml) {
4358
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
4359
 
                        "%s", _("failed to get domain xml"));
4360
 
        goto endjob;
4361
 
    }
4362
 
    header.xml_len = strlen(xml) + 1;
4363
 
 
4364
 
    /* path might be a pre-existing block dev, in which case
4365
 
     * we need to skip the create step, and also avoid unlink
4366
 
     * in the failure case */
4367
 
    if (stat(path, &sb) < 0) {
4368
 
        /* Avoid throwing an error here, since it is possible
4369
 
         * that with NFS we can't actually stat() the file.
4370
 
         * The subsequent codepaths will still raise an error
4371
 
         * if a truely fatal problem is hit */
4372
 
        is_reg = 1;
4373
 
    } else {
4374
 
        is_reg = S_ISREG(sb.st_mode);
4375
 
    }
4376
 
 
4377
 
    offset = sizeof(header) + header.xml_len;
4378
 
 
4379
 
    /* Due to way we append QEMU state on our header with dd,
4380
 
     * we need to ensure there's a 512 byte boundary. Unfortunately
4381
 
     * we don't have an explicit offset in the header, so we fake
4382
 
     * it by padding the XML string with NULLs.
4383
 
     */
4384
 
    if (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS) {
4385
 
        unsigned long long pad =
4386
 
            QEMU_MONITOR_MIGRATE_TO_FILE_BS -
4387
 
            (offset % QEMU_MONITOR_MIGRATE_TO_FILE_BS);
4388
 
 
4389
 
        if (VIR_REALLOC_N(xml, header.xml_len + pad) < 0) {
4390
 
            virReportOOMError();
4391
 
            goto endjob;
4392
 
        }
4393
 
        memset(xml + header.xml_len, 0, pad);
4394
 
        offset += pad;
4395
 
        header.xml_len += pad;
4396
 
    }
4397
 
 
4398
 
    /* Setup hook data needed by virFileOperation hook function */
4399
 
    hdata.dom = dom;
4400
 
    hdata.path = path;
4401
 
    hdata.xml = xml;
4402
 
    hdata.header = &header;
4403
 
 
4404
 
    /* Write header to file, followed by XML */
4405
 
 
4406
 
    /* First try creating the file as root */
4407
 
    if (!is_reg) {
4408
 
        int fd = open(path, O_WRONLY | O_TRUNC);
4409
 
        if (fd < 0) {
4410
 
            virReportSystemError(errno, _("unable to open %s"), path);
4411
 
            goto endjob;
4412
 
        }
4413
 
        if (qemudDomainSaveFileOpHook(fd, &hdata) < 0) {
4414
 
            VIR_FORCE_CLOSE(fd);
4415
 
            goto endjob;
4416
 
        }
4417
 
        if (VIR_CLOSE(fd) < 0) {
4418
 
            virReportSystemError(errno, _("unable to close %s"), path);
4419
 
            goto endjob;
4420
 
        }
4421
 
    } else {
4422
 
        if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
4423
 
                                  S_IRUSR|S_IWUSR,
4424
 
                                  getuid(), getgid(),
4425
 
                                  qemudDomainSaveFileOpHook, &hdata,
4426
 
                                  0)) < 0) {
4427
 
            /* If we failed as root, and the error was permission-denied
4428
 
               (EACCES or EPERM), assume it's on a network-connected share
4429
 
               where root access is restricted (eg, root-squashed NFS). If the
4430
 
               qemu user (driver->user) is non-root, just set a flag to
4431
 
               bypass security driver shenanigans, and retry the operation
4432
 
               after doing setuid to qemu user */
4433
 
 
4434
 
            if (((rc != -EACCES) && (rc != -EPERM)) ||
4435
 
                driver->user == getuid()) {
4436
 
                virReportSystemError(-rc, _("Failed to create domain save file '%s'"),
4437
 
                                     path);
4438
 
                goto endjob;
4439
 
            }
4440
 
 
4441
 
            /* On Linux we can also verify the FS-type of the directory. */
4442
 
            switch (virStorageFileIsSharedFS(path)) {
4443
 
                case 1:
4444
 
                   /* it was on a network share, so we'll continue
4445
 
                    * as outlined above
4446
 
                    */
4447
 
                   break;
4448
 
 
4449
 
                case -1:
4450
 
                   virReportSystemError(errno,
4451
 
                                        _("Failed to create domain save file "
4452
 
                                          "'%s': couldn't determine fs type"),
4453
 
                                        path);
4454
 
                   goto endjob;
4455
 
                   break;
4456
 
 
4457
 
                case 0:
4458
 
                default:
4459
 
                   /* local file - log the error returned by virFileOperation */
4460
 
                   virReportSystemError(-rc,
4461
 
                                        _("Failed to create domain save file '%s'"),
4462
 
                                        path);
4463
 
                   goto endjob;
4464
 
                   break;
4465
 
 
4466
 
            }
4467
 
 
4468
 
            /* Retry creating the file as driver->user */
4469
 
 
4470
 
            if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
4471
 
                                       S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP,
4472
 
                                       driver->user, driver->group,
4473
 
                                       qemudDomainSaveFileOpHook, &hdata,
4474
 
                                       VIR_FILE_OP_AS_UID)) < 0) {
4475
 
                virReportSystemError(-rc, _("Error from child process creating '%s'"),
4476
 
                                 path);
4477
 
                goto endjob;
4478
 
            }
4479
 
 
4480
 
            /* Since we had to setuid to create the file, and the fstype
4481
 
               is NFS, we assume it's a root-squashing NFS share, and that
4482
 
               the security driver stuff would have failed anyway */
4483
 
 
4484
 
            bypassSecurityDriver = 1;
4485
 
        }
4486
 
    }
4487
 
 
4488
 
 
4489
 
    if (!is_reg &&
4490
 
        qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
4491
 
        if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) != 0) {
4492
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
4493
 
                            _("Unable to find cgroup for %s"),
4494
 
                            vm->def->name);
4495
 
            goto endjob;
4496
 
        }
4497
 
        rc = virCgroupAllowDevicePath(cgroup, path);
4498
 
        if (rc != 0) {
4499
 
            virReportSystemError(-rc,
4500
 
                                 _("Unable to allow device %s for %s"),
4501
 
                                 path, vm->def->name);
4502
 
            goto endjob;
4503
 
        }
4504
 
    }
4505
 
 
4506
 
    if ((!bypassSecurityDriver) &&
4507
 
        virSecurityManagerSetSavedStateLabel(driver->securityManager,
4508
 
                                             vm, path) < 0)
4509
 
        goto endjob;
4510
 
 
4511
 
    if (header.compressed == QEMUD_SAVE_FORMAT_RAW) {
4512
 
        const char *args[] = { "cat", NULL };
4513
 
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
4514
 
        rc = qemuMonitorMigrateToFile(priv->mon,
4515
 
                                      QEMU_MONITOR_MIGRATE_BACKGROUND,
4516
 
                                      args, path, offset);
4517
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
4518
 
    } else {
4519
 
        const char *prog = qemudSaveCompressionTypeToString(header.compressed);
4520
 
        const char *args[] = {
4521
 
            prog,
4522
 
            "-c",
4523
 
            NULL
4524
 
        };
4525
 
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
4526
 
        rc = qemuMonitorMigrateToFile(priv->mon,
4527
 
                                      QEMU_MONITOR_MIGRATE_BACKGROUND,
4528
 
                                      args, path, offset);
4529
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
4530
 
    }
4531
 
 
4532
 
    if (rc < 0)
4533
 
        goto endjob;
4534
 
 
4535
 
    rc = qemuDomainWaitForMigrationComplete(driver, vm);
4536
 
 
4537
 
    if (rc < 0)
4538
 
        goto endjob;
4539
 
 
4540
 
    if ((!bypassSecurityDriver) &&
4541
 
        virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4542
 
                                                 vm, path) < 0)
4543
 
        VIR_WARN("failed to restore save state label on %s", path);
4544
 
 
4545
 
    if (cgroup != NULL) {
4546
 
        rc = virCgroupDenyDevicePath(cgroup, path);
4547
 
        if (rc != 0)
4548
 
            VIR_WARN("Unable to deny device %s for %s %d",
4549
 
                     path, vm->def->name, rc);
4550
 
    }
4551
 
 
4552
 
    ret = 0;
4553
 
 
4554
 
    /* Shut it down */
4555
 
    qemudShutdownVMDaemon(driver, vm, 0);
4556
 
    qemuDomainStopAudit(vm, "saved");
4557
 
    event = virDomainEventNewFromObj(vm,
4558
 
                                     VIR_DOMAIN_EVENT_STOPPED,
4559
 
                                     VIR_DOMAIN_EVENT_STOPPED_SAVED);
4560
 
    if (!vm->persistent) {
4561
 
        if (qemuDomainObjEndJob(vm) > 0)
4562
 
            virDomainRemoveInactive(&driver->domains,
4563
 
                                    vm);
4564
 
        vm = NULL;
4565
 
    }
4566
 
 
4567
 
endjob:
4568
 
    if (vm) {
4569
 
        if (ret != 0) {
4570
 
            if (header.was_running && virDomainObjIsActive(vm)) {
4571
 
                rc = doStartCPUs(driver, vm, dom->conn);
4572
 
                if (rc < 0)
4573
 
                    VIR_WARN0("Unable to resume guest CPUs after save failure");
4574
 
            }
4575
 
 
4576
 
            if (cgroup != NULL) {
4577
 
                rc = virCgroupDenyDevicePath(cgroup, path);
4578
 
                if (rc != 0)
4579
 
                    VIR_WARN("Unable to deny device %s for %s: %d",
4580
 
                             path, vm->def->name, rc);
4581
 
            }
4582
 
 
4583
 
            if ((!bypassSecurityDriver) &&
4584
 
                virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4585
 
                                                         vm, path) < 0)
4586
 
                VIR_WARN("failed to restore save state label on %s", path);
4587
 
        }
4588
 
 
4589
 
        if (qemuDomainObjEndJob(vm) == 0)
4590
 
            vm = NULL;
4591
 
    }
4592
 
 
4593
 
cleanup:
4594
 
    VIR_FREE(xml);
4595
 
    if (ret != 0 && is_reg)
4596
 
        unlink(path);
4597
 
    if (event)
4598
 
        qemuDomainEventQueue(driver, event);
4599
 
    virCgroupFree(&cgroup);
4600
 
    return ret;
4601
 
}
4602
 
 
4603
 
/* Returns true if a compression program is available in PATH */
4604
 
static bool qemudCompressProgramAvailable(enum qemud_save_formats compress)
4605
 
{
4606
 
    const char *prog;
4607
 
    char *c;
4608
 
 
4609
 
    if (compress == QEMUD_SAVE_FORMAT_RAW)
4610
 
        return true;
4611
 
    prog = qemudSaveCompressionTypeToString(compress);
4612
 
    c = virFindFileInPath(prog);
4613
 
    if (!c)
4614
 
        return false;
4615
 
    VIR_FREE(c);
4616
 
    return true;
4617
 
}
4618
 
 
4619
 
static int qemudDomainSave(virDomainPtr dom, const char *path)
4620
 
{
4621
 
    struct qemud_driver *driver = dom->conn->privateData;
4622
 
    int compressed;
4623
 
    int ret = -1;
4624
 
    virDomainObjPtr vm = NULL;
4625
 
 
4626
 
    qemuDriverLock(driver);
4627
 
 
4628
 
    if (driver->saveImageFormat == NULL)
4629
 
        compressed = QEMUD_SAVE_FORMAT_RAW;
4630
 
    else {
4631
 
        compressed = qemudSaveCompressionTypeFromString(driver->saveImageFormat);
4632
 
        if (compressed < 0) {
4633
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
4634
 
                            "%s", _("Invalid save image format specified "
4635
 
                                    "in configuration file"));
4636
 
            return -1;
4637
 
        }
4638
 
        if (!qemudCompressProgramAvailable(compressed)) {
4639
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
4640
 
                            "%s", _("Compression program for image format "
4641
 
                                    "in configuration file isn't available"));
4642
 
            return -1;
4643
 
        }
4644
 
    }
4645
 
 
4646
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4647
 
    if (!vm) {
4648
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
4649
 
        virUUIDFormat(dom->uuid, uuidstr);
4650
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
4651
 
                        _("no domain with matching uuid '%s'"), uuidstr);
4652
 
        goto cleanup;
4653
 
    }
4654
 
 
4655
 
    if (!virDomainObjIsActive(vm)) {
4656
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4657
 
                        "%s", _("domain is not running"));
4658
 
        goto cleanup;
4659
 
    }
4660
 
 
4661
 
    ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);
4662
 
 
4663
 
cleanup:
4664
 
    if (vm)
4665
 
        virDomainObjUnlock(vm);
4666
 
    qemuDriverUnlock(driver);
4667
 
 
4668
 
    return ret;
4669
 
}
4670
 
 
4671
 
static char *
4672
 
qemuDomainManagedSavePath(struct qemud_driver *driver, virDomainObjPtr vm) {
4673
 
    char *ret;
4674
 
 
4675
 
    if (virAsprintf(&ret, "%s/%s.save", driver->saveDir, vm->def->name) < 0) {
4676
 
        virReportOOMError();
4677
 
        return(NULL);
4678
 
    }
4679
 
 
4680
 
    return(ret);
4681
 
}
4682
 
 
4683
 
static int
4684
 
qemuDomainManagedSave(virDomainPtr dom, unsigned int flags)
4685
 
{
4686
 
    struct qemud_driver *driver = dom->conn->privateData;
4687
 
    virDomainObjPtr vm = NULL;
4688
 
    char *name = NULL;
4689
 
    int ret = -1;
4690
 
    int compressed;
4691
 
 
4692
 
    virCheckFlags(0, -1);
4693
 
 
4694
 
    qemuDriverLock(driver);
4695
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4696
 
    if (!vm) {
4697
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
4698
 
        virUUIDFormat(dom->uuid, uuidstr);
4699
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
4700
 
                        _("no domain with matching uuid '%s'"), uuidstr);
4701
 
        goto cleanup;
4702
 
    }
4703
 
 
4704
 
    if (!virDomainObjIsActive(vm)) {
4705
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4706
 
                        "%s", _("domain is not running"));
4707
 
        goto cleanup;
4708
 
    }
4709
 
 
4710
 
    name = qemuDomainManagedSavePath(driver, vm);
4711
 
    if (name == NULL)
4712
 
        goto cleanup;
4713
 
 
4714
 
    VIR_DEBUG("Saving state to %s", name);
4715
 
 
4716
 
    compressed = QEMUD_SAVE_FORMAT_RAW;
4717
 
    ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
4718
 
 
4719
 
cleanup:
4720
 
    if (vm)
4721
 
        virDomainObjUnlock(vm);
4722
 
    qemuDriverUnlock(driver);
4723
 
    VIR_FREE(name);
4724
 
 
4725
 
    return ret;
4726
 
}
4727
 
 
4728
 
static int
4729
 
qemuDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
4730
 
{
4731
 
    struct qemud_driver *driver = dom->conn->privateData;
4732
 
    virDomainObjPtr vm = NULL;
4733
 
    int ret = -1;
4734
 
    char *name = NULL;
4735
 
 
4736
 
    virCheckFlags(0, -1);
4737
 
 
4738
 
    qemuDriverLock(driver);
4739
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4740
 
    if (!vm) {
4741
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
4742
 
        virUUIDFormat(dom->uuid, uuidstr);
4743
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
4744
 
                        _("no domain with matching uuid '%s'"), uuidstr);
4745
 
        goto cleanup;
4746
 
    }
4747
 
 
4748
 
    name = qemuDomainManagedSavePath(driver, vm);
4749
 
    if (name == NULL)
4750
 
        goto cleanup;
4751
 
 
4752
 
    ret = virFileExists(name);
4753
 
 
4754
 
cleanup:
4755
 
    VIR_FREE(name);
4756
 
    if (vm)
4757
 
        virDomainObjUnlock(vm);
4758
 
    qemuDriverUnlock(driver);
4759
 
    return ret;
4760
 
}
4761
 
 
4762
 
static int
4763
 
qemuDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
4764
 
{
4765
 
    struct qemud_driver *driver = dom->conn->privateData;
4766
 
    virDomainObjPtr vm = NULL;
4767
 
    int ret = -1;
4768
 
    char *name = NULL;
4769
 
 
4770
 
    virCheckFlags(0, -1);
4771
 
 
4772
 
    qemuDriverLock(driver);
4773
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4774
 
    if (!vm) {
4775
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
4776
 
        virUUIDFormat(dom->uuid, uuidstr);
4777
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
4778
 
                        _("no domain with matching uuid '%s'"), uuidstr);
4779
 
        goto cleanup;
4780
 
    }
4781
 
 
4782
 
    name = qemuDomainManagedSavePath(driver, vm);
4783
 
    if (name == NULL)
4784
 
        goto cleanup;
4785
 
 
4786
 
    ret = unlink(name);
4787
 
 
4788
 
cleanup:
4789
 
    VIR_FREE(name);
4790
 
    if (vm)
4791
 
        virDomainObjUnlock(vm);
4792
 
    qemuDriverUnlock(driver);
4793
 
    return ret;
4794
 
}
4795
 
 
4796
 
static int doCoreDump(struct qemud_driver *driver,
4797
 
                      virDomainObjPtr vm,
4798
 
                      const char *path,
4799
 
                      enum qemud_save_formats compress)
4800
 
{
4801
 
    int fd = -1;
4802
 
    int ret = -1;
4803
 
    qemuDomainObjPrivatePtr priv;
4804
 
 
4805
 
    priv = vm->privateData;
4806
 
 
4807
 
    /* Create an empty file with appropriate ownership.  */
4808
 
    if ((fd = open(path, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR)) < 0) {
4809
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
4810
 
                        _("failed to create '%s'"), path);
4811
 
        goto cleanup;
4812
 
    }
4813
 
 
4814
 
    if (VIR_CLOSE(fd) < 0) {
4815
 
        virReportSystemError(errno,
4816
 
                             _("unable to save file %s"),
4817
 
                             path);
4818
 
        goto cleanup;
4819
 
    }
4820
 
 
4821
 
    if (virSecurityManagerSetSavedStateLabel(driver->securityManager,
4822
 
                                             vm, path) < 0)
4823
 
        goto cleanup;
4824
 
 
4825
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
4826
 
    if (compress == QEMUD_SAVE_FORMAT_RAW) {
4827
 
        const char *args[] = {
4828
 
            "cat",
4829
 
            NULL,
4830
 
        };
4831
 
        ret = qemuMonitorMigrateToFile(priv->mon,
4832
 
                                       QEMU_MONITOR_MIGRATE_BACKGROUND,
4833
 
                                       args, path, 0);
4834
 
    } else {
4835
 
        const char *prog = qemudSaveCompressionTypeToString(compress);
4836
 
        const char *args[] = {
4837
 
            prog,
4838
 
            "-c",
4839
 
            NULL,
4840
 
        };
4841
 
        ret = qemuMonitorMigrateToFile(priv->mon,
4842
 
                                       QEMU_MONITOR_MIGRATE_BACKGROUND,
4843
 
                                       args, path, 0);
4844
 
    }
4845
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
4846
 
    if (ret < 0)
4847
 
        goto cleanup;
4848
 
 
4849
 
    ret = qemuDomainWaitForMigrationComplete(driver, vm);
4850
 
 
4851
 
    if (ret < 0)
4852
 
        goto cleanup;
4853
 
 
4854
 
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4855
 
                                                 vm, path) < 0)
4856
 
        goto cleanup;
4857
 
 
4858
 
cleanup:
4859
 
    if (ret != 0)
4860
 
        unlink(path);
4861
 
    return ret;
4862
 
}
4863
 
 
4864
 
static enum qemud_save_formats
4865
 
getCompressionType(struct qemud_driver *driver)
4866
 
{
4867
 
    int compress = QEMUD_SAVE_FORMAT_RAW;
4868
 
 
4869
 
    /*
4870
 
     * We reuse "save" flag for "dump" here. Then, we can support the same
4871
 
     * format in "save" and "dump".
4872
 
     */
4873
 
    if (driver->dumpImageFormat) {
4874
 
        compress = qemudSaveCompressionTypeFromString(driver->dumpImageFormat);
4875
 
        if (compress < 0) {
4876
 
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
4877
 
                            _("Invalid dump image format specified in "
4878
 
                              "configuration file, using raw"));
4879
 
            return QEMUD_SAVE_FORMAT_RAW;
4880
 
        }
4881
 
        if (!qemudCompressProgramAvailable(compress)) {
4882
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
4883
 
                            "%s", _("Compression program for dump image format "
4884
 
                                    "in configuration file isn't available, "
4885
 
                                    "using raw"));
4886
 
            return QEMUD_SAVE_FORMAT_RAW;
4887
 
        }
4888
 
    }
4889
 
    return compress;
4890
 
}
4891
 
 
4892
 
static int qemudDomainCoreDump(virDomainPtr dom,
4893
 
                               const char *path,
4894
 
                               int flags ATTRIBUTE_UNUSED) {
4895
 
    struct qemud_driver *driver = dom->conn->privateData;
4896
 
    virDomainObjPtr vm;
4897
 
    int resume = 0, paused = 0;
4898
 
    int ret = -1;
4899
 
    virDomainEventPtr event = NULL;
4900
 
    qemuDomainObjPrivatePtr priv;
4901
 
 
4902
 
    qemuDriverLock(driver);
4903
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4904
 
 
4905
 
    if (!vm) {
4906
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
4907
 
        virUUIDFormat(dom->uuid, uuidstr);
4908
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
4909
 
                        _("no domain with matching uuid '%s'"), uuidstr);
4910
 
        goto cleanup;
4911
 
    }
4912
 
    priv = vm->privateData;
4913
 
 
4914
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
4915
 
        goto cleanup;
4916
 
 
4917
 
    if (!virDomainObjIsActive(vm)) {
4918
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
4919
 
                        "%s", _("domain is not running"));
4920
 
        goto endjob;
4921
 
    }
4922
 
 
4923
 
    priv->jobActive = QEMU_JOB_DUMP;
4924
 
 
4925
 
    /* Migrate will always stop the VM, so the resume condition is
4926
 
       independent of whether the stop command is issued.  */
4927
 
    resume = (vm->state == VIR_DOMAIN_RUNNING);
4928
 
 
4929
 
    /* Pause domain for non-live dump */
4930
 
    if (!(flags & VIR_DUMP_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
4931
 
        if (doStopCPUs(driver, vm) < 0)
4932
 
            goto endjob;
4933
 
        paused = 1;
4934
 
 
4935
 
        if (!virDomainObjIsActive(vm)) {
4936
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4937
 
                            _("guest unexpectedly quit"));
4938
 
            goto endjob;
4939
 
        }
4940
 
    }
4941
 
 
4942
 
    ret = doCoreDump(driver, vm, path, getCompressionType(driver));
4943
 
    if (ret < 0)
4944
 
        goto endjob;
4945
 
 
4946
 
    paused = 1;
4947
 
 
4948
 
endjob:
4949
 
    if ((ret == 0) && (flags & VIR_DUMP_CRASH)) {
4950
 
        qemudShutdownVMDaemon(driver, vm, 0);
4951
 
        qemuDomainStopAudit(vm, "crashed");
4952
 
        event = virDomainEventNewFromObj(vm,
4953
 
                                         VIR_DOMAIN_EVENT_STOPPED,
4954
 
                                         VIR_DOMAIN_EVENT_STOPPED_CRASHED);
4955
 
    }
4956
 
 
4957
 
    /* Since the monitor is always attached to a pty for libvirt, it
4958
 
       will support synchronous operations so we always get here after
4959
 
       the migration is complete.  */
4960
 
    else if (resume && paused && virDomainObjIsActive(vm)) {
4961
 
        if (doStartCPUs(driver, vm, dom->conn) < 0) {
4962
 
            if (virGetLastError() == NULL)
4963
 
                qemuReportError(VIR_ERR_OPERATION_FAILED,
4964
 
                                "%s", _("resuming after dump failed"));
4965
 
        }
4966
 
    }
4967
 
 
4968
 
    if (qemuDomainObjEndJob(vm) == 0)
4969
 
        vm = NULL;
4970
 
    else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
4971
 
        virDomainRemoveInactive(&driver->domains,
4972
 
                                vm);
4973
 
        vm = NULL;
4974
 
    }
4975
 
 
4976
 
cleanup:
4977
 
    if (vm)
4978
 
        virDomainObjUnlock(vm);
4979
 
    if (event)
4980
 
        qemuDomainEventQueue(driver, event);
4981
 
    qemuDriverUnlock(driver);
4982
 
    return ret;
4983
 
}
4984
 
 
4985
 
static void processWatchdogEvent(void *data, void *opaque)
4986
 
{
4987
 
    int ret;
4988
 
    struct watchdogEvent *wdEvent = data;
4989
 
    struct qemud_driver *driver = opaque;
4990
 
 
4991
 
    switch (wdEvent->action) {
4992
 
    case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
4993
 
        {
4994
 
            char *dumpfile;
4995
 
 
4996
 
            if (virAsprintf(&dumpfile, "%s/%s-%u",
4997
 
                            driver->autoDumpPath,
4998
 
                            wdEvent->vm->def->name,
4999
 
                            (unsigned int)time(NULL)) < 0) {
5000
 
                virReportOOMError();
5001
 
                break;
5002
 
            }
5003
 
 
5004
 
            qemuDriverLock(driver);
5005
 
            virDomainObjLock(wdEvent->vm);
5006
 
 
5007
 
            if (qemuDomainObjBeginJobWithDriver(driver, wdEvent->vm) < 0)
5008
 
                break;
5009
 
 
5010
 
            if (!virDomainObjIsActive(wdEvent->vm)) {
5011
 
                qemuReportError(VIR_ERR_OPERATION_INVALID,
5012
 
                                "%s", _("domain is not running"));
5013
 
                break;
5014
 
            }
5015
 
 
5016
 
            ret = doCoreDump(driver,
5017
 
                             wdEvent->vm,
5018
 
                             dumpfile,
5019
 
                             getCompressionType(driver));
5020
 
            if (ret < 0)
5021
 
                qemuReportError(VIR_ERR_OPERATION_FAILED,
5022
 
                                "%s", _("Dump failed"));
5023
 
 
5024
 
            ret = doStartCPUs(driver, wdEvent->vm, NULL);
5025
 
 
5026
 
            if (ret < 0)
5027
 
                qemuReportError(VIR_ERR_OPERATION_FAILED,
5028
 
                                "%s", _("Resuming after dump failed"));
5029
 
 
5030
 
            if (qemuDomainObjEndJob(wdEvent->vm) > 0)
5031
 
                virDomainObjUnlock(wdEvent->vm);
5032
 
 
5033
 
            qemuDriverUnlock(driver);
5034
 
 
5035
 
            VIR_FREE(dumpfile);
5036
 
        }
5037
 
        break;
5038
 
    }
5039
 
 
5040
 
    VIR_FREE(wdEvent);
5041
 
}
5042
 
 
5043
 
static int qemudDomainHotplugVcpus(virDomainObjPtr vm, unsigned int nvcpus)
5044
 
{
5045
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
5046
 
    int i, rc;
5047
 
    int ret = -1;
5048
 
 
5049
 
    qemuDomainObjEnterMonitor(vm);
5050
 
 
5051
 
    /* We need different branches here, because we want to offline
5052
 
     * in reverse order to onlining, so any partial fail leaves us in a
5053
 
     * reasonably sensible state */
5054
 
    if (nvcpus > vm->def->vcpus) {
5055
 
        for (i = vm->def->vcpus ; i < nvcpus ; i++) {
5056
 
            /* Online new CPU */
5057
 
            rc = qemuMonitorSetCPU(priv->mon, i, 1);
5058
 
            if (rc == 0)
5059
 
                goto unsupported;
5060
 
            if (rc < 0)
5061
 
                goto cleanup;
5062
 
 
5063
 
            vm->def->vcpus++;
5064
 
        }
5065
 
    } else {
5066
 
        for (i = vm->def->vcpus - 1 ; i >= nvcpus ; i--) {
5067
 
            /* Offline old CPU */
5068
 
            rc = qemuMonitorSetCPU(priv->mon, i, 0);
5069
 
            if (rc == 0)
5070
 
                goto unsupported;
5071
 
            if (rc < 0)
5072
 
                goto cleanup;
5073
 
 
5074
 
            vm->def->vcpus--;
5075
 
        }
5076
 
    }
5077
 
 
5078
 
    ret = 0;
5079
 
 
5080
 
cleanup:
5081
 
    qemuDomainObjExitMonitor(vm);
5082
 
    return ret;
5083
 
 
5084
 
unsupported:
5085
 
    qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5086
 
                    _("cannot change vcpu count of this domain"));
5087
 
    goto cleanup;
5088
 
}
5089
 
 
5090
 
 
5091
 
static int
5092
 
qemudDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
5093
 
                         unsigned int flags)
5094
 
{
5095
 
    struct qemud_driver *driver = dom->conn->privateData;
5096
 
    virDomainObjPtr vm;
5097
 
    virDomainDefPtr persistentDef;
5098
 
    const char * type;
5099
 
    int max;
5100
 
    int ret = -1;
5101
 
 
5102
 
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
5103
 
                  VIR_DOMAIN_VCPU_CONFIG |
5104
 
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);
5105
 
 
5106
 
    /* At least one of LIVE or CONFIG must be set.  MAXIMUM cannot be
5107
 
     * mixed with LIVE.  */
5108
 
    if ((flags & (VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG)) == 0 ||
5109
 
        (flags & (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) ==
5110
 
         (VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_LIVE)) {
5111
 
        qemuReportError(VIR_ERR_INVALID_ARG,
5112
 
                        _("invalid flag combination: (0x%x)"), flags);
5113
 
        return -1;
5114
 
    }
5115
 
    if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
5116
 
        qemuReportError(VIR_ERR_INVALID_ARG,
5117
 
                        _("argument out of range: %d"), nvcpus);
5118
 
        return -1;
5119
 
    }
5120
 
 
5121
 
    qemuDriverLock(driver);
5122
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5123
 
    qemuDriverUnlock(driver);
5124
 
 
5125
 
    if (!vm) {
5126
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
5127
 
        virUUIDFormat(dom->uuid, uuidstr);
5128
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
5129
 
                        _("no domain with matching uuid '%s'"), uuidstr);
5130
 
        goto cleanup;
5131
 
    }
5132
 
 
5133
 
    if (qemuDomainObjBeginJob(vm) < 0)
5134
 
        goto cleanup;
5135
 
 
5136
 
    if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
5137
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5138
 
                         "%s", _("domain is not running"));
5139
 
        goto endjob;
5140
 
    }
5141
 
 
5142
 
    if (!vm->persistent && (flags & VIR_DOMAIN_VCPU_CONFIG)) {
5143
 
        qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
5144
 
                        _("cannot change persistent config of a transient domain"));
5145
 
        goto endjob;
5146
 
    }
5147
 
 
5148
 
    if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
5149
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
5150
 
                        _("unknown virt type in domain definition '%d'"),
5151
 
                        vm->def->virtType);
5152
 
        goto endjob;
5153
 
    }
5154
 
 
5155
 
    if ((max = qemudGetMaxVCPUs(NULL, type)) < 0) {
5156
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5157
 
                        _("could not determine max vcpus for the domain"));
5158
 
        goto endjob;
5159
 
    }
5160
 
 
5161
 
    if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
5162
 
        max = vm->def->maxvcpus;
5163
 
    }
5164
 
 
5165
 
    if (nvcpus > max) {
5166
 
        qemuReportError(VIR_ERR_INVALID_ARG,
5167
 
                        _("requested vcpus is greater than max allowable"
5168
 
                          " vcpus for the domain: %d > %d"), nvcpus, max);
5169
 
        goto endjob;
5170
 
    }
5171
 
 
5172
 
    if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
5173
 
        goto endjob;
5174
 
 
5175
 
    switch (flags) {
5176
 
    case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
5177
 
        persistentDef->maxvcpus = nvcpus;
5178
 
        if (nvcpus < persistentDef->vcpus)
5179
 
            persistentDef->vcpus = nvcpus;
5180
 
        ret = 0;
5181
 
        break;
5182
 
 
5183
 
    case VIR_DOMAIN_VCPU_CONFIG:
5184
 
        persistentDef->vcpus = nvcpus;
5185
 
        ret = 0;
5186
 
        break;
5187
 
 
5188
 
    case VIR_DOMAIN_VCPU_LIVE:
5189
 
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
5190
 
        break;
5191
 
 
5192
 
    case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
5193
 
        ret = qemudDomainHotplugVcpus(vm, nvcpus);
5194
 
        if (ret == 0) {
5195
 
            persistentDef->vcpus = nvcpus;
5196
 
        }
5197
 
        break;
5198
 
    }
5199
 
 
5200
 
    /* Save the persistent config to disk */
5201
 
    if (flags & VIR_DOMAIN_VCPU_CONFIG)
5202
 
        ret = virDomainSaveConfig(driver->configDir, persistentDef);
5203
 
 
5204
 
endjob:
5205
 
    if (qemuDomainObjEndJob(vm) == 0)
5206
 
        vm = NULL;
5207
 
 
5208
 
cleanup:
5209
 
    if (vm)
5210
 
        virDomainObjUnlock(vm);
5211
 
    return ret;
5212
 
}
5213
 
 
5214
 
static int
5215
 
qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
5216
 
{
5217
 
    return qemudDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
5218
 
}
5219
 
 
5220
 
 
5221
 
static int
5222
 
qemudDomainPinVcpu(virDomainPtr dom,
5223
 
                   unsigned int vcpu,
5224
 
                   unsigned char *cpumap,
5225
 
                   int maplen) {
5226
 
    struct qemud_driver *driver = dom->conn->privateData;
5227
 
    virDomainObjPtr vm;
5228
 
    int maxcpu, hostcpus;
5229
 
    virNodeInfo nodeinfo;
5230
 
    int ret = -1;
5231
 
    qemuDomainObjPrivatePtr priv;
5232
 
 
5233
 
    qemuDriverLock(driver);
5234
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5235
 
    qemuDriverUnlock(driver);
5236
 
 
5237
 
    if (!vm) {
5238
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
5239
 
        virUUIDFormat(dom->uuid, uuidstr);
5240
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
5241
 
                        _("no domain with matching uuid '%s'"), uuidstr);
5242
 
        goto cleanup;
5243
 
    }
5244
 
 
5245
 
    if (!virDomainObjIsActive(vm)) {
5246
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5247
 
                        "%s",_("cannot pin vcpus on an inactive domain"));
5248
 
        goto cleanup;
5249
 
    }
5250
 
 
5251
 
    priv = vm->privateData;
5252
 
 
5253
 
    if (vcpu > (priv->nvcpupids-1)) {
5254
 
        qemuReportError(VIR_ERR_INVALID_ARG,
5255
 
                        _("vcpu number out of range %d > %d"),
5256
 
                        vcpu, priv->nvcpupids);
5257
 
        goto cleanup;
5258
 
    }
5259
 
 
5260
 
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
5261
 
        goto cleanup;
5262
 
 
5263
 
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
5264
 
    maxcpu = maplen * 8;
5265
 
    if (maxcpu > hostcpus)
5266
 
        maxcpu = hostcpus;
5267
 
 
5268
 
    if (priv->vcpupids != NULL) {
5269
 
        if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
5270
 
                                      cpumap, maplen, maxcpu) < 0)
5271
 
            goto cleanup;
5272
 
    } else {
5273
 
        qemuReportError(VIR_ERR_NO_SUPPORT,
5274
 
                        "%s", _("cpu affinity is not supported"));
5275
 
        goto cleanup;
5276
 
    }
5277
 
    ret = 0;
5278
 
 
5279
 
cleanup:
5280
 
    if (vm)
5281
 
        virDomainObjUnlock(vm);
5282
 
    return ret;
5283
 
}
5284
 
 
5285
 
static int
5286
 
qemudDomainGetVcpus(virDomainPtr dom,
5287
 
                    virVcpuInfoPtr info,
5288
 
                    int maxinfo,
5289
 
                    unsigned char *cpumaps,
5290
 
                    int maplen) {
5291
 
    struct qemud_driver *driver = dom->conn->privateData;
5292
 
    virDomainObjPtr vm;
5293
 
    virNodeInfo nodeinfo;
5294
 
    int i, v, maxcpu, hostcpus;
5295
 
    int ret = -1;
5296
 
    qemuDomainObjPrivatePtr priv;
5297
 
 
5298
 
    qemuDriverLock(driver);
5299
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5300
 
    qemuDriverUnlock(driver);
5301
 
 
5302
 
    if (!vm) {
5303
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
5304
 
        virUUIDFormat(dom->uuid, uuidstr);
5305
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
5306
 
                        _("no domain with matching uuid '%s'"), uuidstr);
5307
 
        goto cleanup;
5308
 
    }
5309
 
 
5310
 
    if (!virDomainObjIsActive(vm)) {
5311
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
5312
 
                        "%s",
5313
 
                        _("cannot list vcpu pinning for an inactive domain"));
5314
 
        goto cleanup;
5315
 
    }
5316
 
 
5317
 
    priv = vm->privateData;
5318
 
 
5319
 
    if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
5320
 
        goto cleanup;
5321
 
 
5322
 
    hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
5323
 
    maxcpu = maplen * 8;
5324
 
    if (maxcpu > hostcpus)
5325
 
        maxcpu = hostcpus;
5326
 
 
5327
 
    /* Clamp to actual number of vcpus */
5328
 
    if (maxinfo > priv->nvcpupids)
5329
 
        maxinfo = priv->nvcpupids;
5330
 
 
5331
 
    if (maxinfo >= 1) {
5332
 
        if (info != NULL) {
5333
 
            memset(info, 0, sizeof(*info) * maxinfo);
5334
 
            for (i = 0 ; i < maxinfo ; i++) {
5335
 
                info[i].number = i;
5336
 
                info[i].state = VIR_VCPU_RUNNING;
5337
 
 
5338
 
                if (priv->vcpupids != NULL &&
5339
 
                    qemudGetProcessInfo(&(info[i].cpuTime),
5340
 
                                        &(info[i].cpu),
5341
 
                                        vm->pid,
5342
 
                                        priv->vcpupids[i]) < 0) {
5343
 
                    virReportSystemError(errno, "%s",
5344
 
                                         _("cannot get vCPU placement & pCPU time"));
5345
 
                    goto cleanup;
5346
 
                }
5347
 
            }
5348
 
        }
5349
 
 
5350
 
        if (cpumaps != NULL) {
5351
 
            memset(cpumaps, 0, maplen * maxinfo);
5352
 
            if (priv->vcpupids != NULL) {
5353
 
                for (v = 0 ; v < maxinfo ; v++) {
5354
 
                    unsigned char *cpumap = VIR_GET_CPUMAP(cpumaps, maplen, v);
5355
 
 
5356
 
                    if (virProcessInfoGetAffinity(priv->vcpupids[v],
5357
 
                                                  cpumap, maplen, maxcpu) < 0)
5358
 
                        goto cleanup;
5359
 
                }
5360
 
            } else {
5361
 
                qemuReportError(VIR_ERR_NO_SUPPORT,
5362
 
                                "%s", _("cpu affinity is not available"));
5363
 
                goto cleanup;
5364
 
            }
5365
 
        }
5366
 
    }
5367
 
    ret = maxinfo;
5368
 
 
5369
 
cleanup:
5370
 
    if (vm)
5371
 
        virDomainObjUnlock(vm);
5372
 
    return ret;
5373
 
}
5374
 
 
5375
 
 
5376
 
static int
5377
 
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
5378
 
{
5379
 
    struct qemud_driver *driver = dom->conn->privateData;
5380
 
    virDomainObjPtr vm;
5381
 
    virDomainDefPtr def;
5382
 
    int ret = -1;
5383
 
 
5384
 
    virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
5385
 
                  VIR_DOMAIN_VCPU_CONFIG |
5386
 
                  VIR_DOMAIN_VCPU_MAXIMUM, -1);
5387
 
 
5388
 
    /* Exactly one of LIVE or CONFIG must be set.  */
5389
 
    if (!(flags & VIR_DOMAIN_VCPU_LIVE) == !(flags & VIR_DOMAIN_VCPU_CONFIG)) {
5390
 
        qemuReportError(VIR_ERR_INVALID_ARG,
5391
 
                        _("invalid flag combination: (0x%x)"), flags);
5392
 
        return -1;
5393
 
    }
5394
 
 
5395
 
    qemuDriverLock(driver);
5396
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5397
 
    qemuDriverUnlock(driver);
5398
 
 
5399
 
    if (!vm) {
5400
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
5401
 
        virUUIDFormat(dom->uuid, uuidstr);
5402
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
5403
 
                        _("no domain with matching uuid '%s'"), uuidstr);
5404
 
        goto cleanup;
5405
 
    }
5406
 
 
5407
 
    if (flags & VIR_DOMAIN_VCPU_LIVE) {
5408
 
        if (!virDomainObjIsActive(vm)) {
5409
 
            qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
5410
 
                            _("domain not active"));
5411
 
            goto cleanup;
5412
 
        }
5413
 
        def = vm->def;
5414
 
    } else {
5415
 
        def = vm->newDef ? vm->newDef : vm->def;
5416
 
    }
5417
 
 
5418
 
    ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
5419
 
 
5420
 
cleanup:
5421
 
    if (vm)
5422
 
        virDomainObjUnlock(vm);
5423
 
    return ret;
5424
 
}
5425
 
 
5426
 
static int
5427
 
qemudDomainGetMaxVcpus(virDomainPtr dom)
5428
 
{
5429
 
    return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
5430
 
                                          VIR_DOMAIN_VCPU_MAXIMUM));
5431
 
}
5432
 
 
5433
 
static int qemudDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
5434
 
{
5435
 
    struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
5436
 
    virDomainObjPtr vm;
5437
 
    int ret = -1;
5438
 
 
5439
 
    qemuDriverLock(driver);
5440
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5441
 
 
5442
 
    memset(seclabel, 0, sizeof(*seclabel));
5443
 
 
5444
 
    if (!vm) {
5445
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
5446
 
        virUUIDFormat(dom->uuid, uuidstr);
5447
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
5448
 
                        _("no domain with matching uuid '%s'"), uuidstr);
5449
 
        goto cleanup;
5450
 
    }
5451
 
 
5452
 
    if (!virDomainVirtTypeToString(vm->def->virtType)) {
5453
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
5454
 
                        _("unknown virt type in domain definition '%d'"),
5455
 
                        vm->def->virtType);
5456
 
        goto cleanup;
5457
 
    }
5458
 
 
5459
 
    /*
5460
 
     * Theoretically, the pid can be replaced during this operation and
5461
 
     * return the label of a different process.  If atomicity is needed,
5462
 
     * further validation will be required.
5463
 
     *
5464
 
     * Comment from Dan Berrange:
5465
 
     *
5466
 
     *   Well the PID as stored in the virDomainObjPtr can't be changed
5467
 
     *   because you've got a locked object.  The OS level PID could have
5468
 
     *   exited, though and in extreme circumstances have cycled through all
5469
 
     *   PIDs back to ours. We could sanity check that our PID still exists
5470
 
     *   after reading the label, by checking that our FD connecting to the
5471
 
     *   QEMU monitor hasn't seen SIGHUP/ERR on poll().
5472
 
     */
5473
 
    if (virDomainObjIsActive(vm)) {
5474
 
        if (virSecurityManagerGetProcessLabel(driver->securityManager,
5475
 
                                              vm, seclabel) < 0) {
5476
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
5477
 
                            "%s", _("Failed to get security label"));
5478
 
            goto cleanup;
5479
 
        }
5480
 
    }
5481
 
 
5482
 
    ret = 0;
5483
 
 
5484
 
cleanup:
5485
 
    if (vm)
5486
 
        virDomainObjUnlock(vm);
5487
 
    qemuDriverUnlock(driver);
5488
 
    return ret;
5489
 
}
5490
 
 
5491
 
static int qemudNodeGetSecurityModel(virConnectPtr conn,
5492
 
                                     virSecurityModelPtr secmodel)
5493
 
{
5494
 
    struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
5495
 
    char *p;
5496
 
    int ret = 0;
5497
 
 
5498
 
    qemuDriverLock(driver);
5499
 
    memset(secmodel, 0, sizeof(*secmodel));
5500
 
 
5501
 
    /* NULL indicates no driver, which we treat as
5502
 
     * success, but simply return no data in *secmodel */
5503
 
    if (driver->caps->host.secModel.model == NULL)
5504
 
        goto cleanup;
5505
 
 
5506
 
    p = driver->caps->host.secModel.model;
5507
 
    if (strlen(p) >= VIR_SECURITY_MODEL_BUFLEN-1) {
5508
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
5509
 
                        _("security model string exceeds max %d bytes"),
5510
 
                        VIR_SECURITY_MODEL_BUFLEN-1);
5511
 
        ret = -1;
5512
 
        goto cleanup;
5513
 
    }
5514
 
    strcpy(secmodel->model, p);
5515
 
 
5516
 
    p = driver->caps->host.secModel.doi;
5517
 
    if (strlen(p) >= VIR_SECURITY_DOI_BUFLEN-1) {
5518
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
5519
 
                        _("security DOI string exceeds max %d bytes"),
5520
 
                        VIR_SECURITY_DOI_BUFLEN-1);
5521
 
        ret = -1;
5522
 
        goto cleanup;
5523
 
    }
5524
 
    strcpy(secmodel->doi, p);
5525
 
 
5526
 
cleanup:
5527
 
    qemuDriverUnlock(driver);
5528
 
    return ret;
5529
 
}
5530
 
 
5531
 
/* qemudOpenAsUID() - pipe/fork/setuid/open a file, and return the
5532
 
   pipe fd to caller, so that it can read from the file. Also return
5533
 
   the pid of the child process, so the caller can wait for it to exit
5534
 
   after it's finished reading (to avoid a zombie, if nothing
5535
 
   else). */
5536
 
 
5537
 
static int
5538
 
qemudOpenAsUID(const char *path, uid_t uid, gid_t gid, pid_t *child_pid)
5539
 
{
5540
 
    int pipefd[2];
5541
 
    int fd = -1;
5542
 
 
5543
 
    *child_pid = -1;
5544
 
 
5545
 
    if (pipe(pipefd) < 0) {
5546
 
        virReportSystemError(errno,
5547
 
                             _("failed to create pipe to read '%s'"),
5548
 
                             path);
5549
 
        pipefd[0] = pipefd[1] = -1;
5550
 
        goto parent_cleanup;
5551
 
    }
5552
 
 
5553
 
    int forkRet = virFork(child_pid);
5554
 
 
5555
 
    if (*child_pid < 0) {
5556
 
        virReportSystemError(errno,
5557
 
                             _("failed to fork child to read '%s'"),
5558
 
                             path);
5559
 
        goto parent_cleanup;
5560
 
    }
5561
 
 
5562
 
    if (*child_pid > 0) {
5563
 
 
5564
 
        /* parent */
5565
 
 
5566
 
        /* parent doesn't need the write side of the pipe */
5567
 
        VIR_FORCE_CLOSE(pipefd[1]);
5568
 
 
5569
 
        if (forkRet < 0) {
5570
 
            virReportSystemError(errno,
5571
 
                                 _("failed in parent after forking child to read '%s'"),
5572
 
                                 path);
5573
 
            goto parent_cleanup;
5574
 
        }
5575
 
        /* caller gets the read side of the pipe */
5576
 
        fd = pipefd[0];
5577
 
        pipefd[0] = -1;
5578
 
parent_cleanup:
5579
 
        VIR_FORCE_CLOSE(pipefd[0]);
5580
 
        VIR_FORCE_CLOSE(pipefd[1]);
5581
 
        if ((fd < 0) && (*child_pid > 0)) {
5582
 
            /* a child process was started and subsequently an error
5583
 
               occurred in the parent, so we need to wait for it to
5584
 
               exit, but its status is inconsequential. */
5585
 
            while ((waitpid(*child_pid, NULL, 0) == -1)
5586
 
                   && (errno == EINTR)) {
5587
 
                /* empty */
5588
 
            }
5589
 
            *child_pid = -1;
5590
 
        }
5591
 
        return fd;
5592
 
    }
5593
 
 
5594
 
    /* child */
5595
 
 
5596
 
    /* setuid to the qemu user, then open the file, read it,
5597
 
       and stuff it into the pipe for the parent process to
5598
 
       read */
5599
 
    int exit_code;
5600
 
    char *buf = NULL;
5601
 
    size_t bufsize = 1024 * 1024;
5602
 
    int bytesread;
5603
 
 
5604
 
    /* child doesn't need the read side of the pipe */
5605
 
    VIR_FORCE_CLOSE(pipefd[0]);
5606
 
 
5607
 
    if (forkRet < 0) {
5608
 
        exit_code = errno;
5609
 
        virReportSystemError(errno,
5610
 
                             _("failed in child after forking to read '%s'"),
5611
 
                             path);
5612
 
        goto child_cleanup;
5613
 
    }
5614
 
 
5615
 
    if (virSetUIDGID(uid, gid) < 0) {
5616
 
       exit_code = errno;
5617
 
       goto child_cleanup;
5618
 
    }
5619
 
 
5620
 
    if ((fd = open(path, O_RDONLY)) < 0) {
5621
 
        exit_code = errno;
5622
 
        virReportSystemError(errno,
5623
 
                             _("cannot open '%s' as uid %d"),
5624
 
                             path, uid);
5625
 
        goto child_cleanup;
5626
 
    }
5627
 
 
5628
 
    if (VIR_ALLOC_N(buf, bufsize) < 0) {
5629
 
        exit_code = ENOMEM;
5630
 
        virReportOOMError();
5631
 
        goto child_cleanup;
5632
 
    }
5633
 
 
5634
 
    /* read from fd and write to pipefd[1] until EOF */
5635
 
    do {
5636
 
        if ((bytesread = saferead(fd, buf, bufsize)) < 0) {
5637
 
            exit_code = errno;
5638
 
            virReportSystemError(errno,
5639
 
                                 _("child failed reading from '%s'"),
5640
 
                                 path);
5641
 
            goto child_cleanup;
5642
 
        }
5643
 
        if (safewrite(pipefd[1], buf, bytesread) != bytesread) {
5644
 
            exit_code = errno;
5645
 
            virReportSystemError(errno, "%s",
5646
 
                                 _("child failed writing to pipe"));
5647
 
            goto child_cleanup;
5648
 
        }
5649
 
    } while (bytesread > 0);
5650
 
    exit_code = 0;
5651
 
 
5652
 
child_cleanup:
5653
 
    VIR_FREE(buf);
5654
 
    VIR_FORCE_CLOSE(fd);
5655
 
    VIR_FORCE_CLOSE(pipefd[1]);
5656
 
    _exit(exit_code);
5657
 
}
5658
 
 
5659
 
static int qemudDomainSaveImageClose(int fd, pid_t read_pid, int *status)
5660
 
{
5661
 
    int ret = 0;
5662
 
 
5663
 
    if (VIR_CLOSE(fd) < 0) {
5664
 
        virReportSystemError(errno, "%s",
5665
 
                             _("cannot close file"));
5666
 
    }
5667
 
 
5668
 
    if (read_pid != -1) {
5669
 
        /* reap the process that read the file */
5670
 
        while ((ret = waitpid(read_pid, status, 0)) == -1
5671
 
               && errno == EINTR) {
5672
 
            /* empty */
5673
 
        }
5674
 
    } else if (status) {
5675
 
        *status = 0;
5676
 
    }
5677
 
 
5678
 
    return ret;
5679
 
}
5680
 
 
5681
 
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5)
5682
 
qemudDomainSaveImageOpen(struct qemud_driver *driver,
5683
 
                         const char *path,
5684
 
                         virDomainDefPtr *ret_def,
5685
 
                         struct qemud_save_header *ret_header,
5686
 
                         pid_t *ret_read_pid)
5687
 
{
5688
 
    int fd;
5689
 
    pid_t read_pid = -1;
5690
 
    struct qemud_save_header header;
5691
 
    char *xml = NULL;
5692
 
    virDomainDefPtr def = NULL;
5693
 
 
5694
 
    if ((fd = open(path, O_RDONLY)) < 0) {
5695
 
        if ((driver->user == 0) || (getuid() != 0)) {
5696
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
5697
 
                            "%s", _("cannot read domain image"));
5698
 
            goto error;
5699
 
        }
5700
 
 
5701
 
        /* Opening as root failed, but qemu runs as a different user
5702
 
           that might have better luck. Create a pipe, then fork a
5703
 
           child process to run as the qemu user, which will hopefully
5704
 
           have the necessary authority to read the file. */
5705
 
        if ((fd = qemudOpenAsUID(path,
5706
 
                                 driver->user, driver->group, &read_pid)) < 0) {
5707
 
            /* error already reported */
5708
 
            goto error;
5709
 
        }
5710
 
    }
5711
 
 
5712
 
    if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
5713
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5714
 
                        "%s", _("failed to read qemu header"));
5715
 
        goto error;
5716
 
    }
5717
 
 
5718
 
    if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
5719
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5720
 
                        "%s", _("image magic is incorrect"));
5721
 
        goto error;
5722
 
    }
5723
 
 
5724
 
    if (header.version > QEMUD_SAVE_VERSION) {
5725
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5726
 
                        _("image version is not supported (%d > %d)"),
5727
 
                        header.version, QEMUD_SAVE_VERSION);
5728
 
        goto error;
5729
 
    }
5730
 
 
5731
 
    if (header.xml_len <= 0) {
5732
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5733
 
                        _("invalid XML length: %d"), header.xml_len);
5734
 
        goto error;
5735
 
    }
5736
 
 
5737
 
    if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
5738
 
        virReportOOMError();
5739
 
        goto error;
5740
 
    }
5741
 
 
5742
 
    if (saferead(fd, xml, header.xml_len) != header.xml_len) {
5743
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5744
 
                        "%s", _("failed to read XML"));
5745
 
        goto error;
5746
 
    }
5747
 
 
5748
 
    /* Create a domain from this XML */
5749
 
    if (!(def = virDomainDefParseString(driver->caps, xml,
5750
 
                                        VIR_DOMAIN_XML_INACTIVE))) {
5751
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5752
 
                        "%s", _("failed to parse XML"));
5753
 
        goto error;
5754
 
    }
5755
 
 
5756
 
    VIR_FREE(xml);
5757
 
 
5758
 
    *ret_def = def;
5759
 
    *ret_header = header;
5760
 
    *ret_read_pid = read_pid;
5761
 
 
5762
 
    return fd;
5763
 
 
5764
 
error:
5765
 
    virDomainDefFree(def);
5766
 
    VIR_FREE(xml);
5767
 
    qemudDomainSaveImageClose(fd, read_pid, NULL);
5768
 
 
5769
 
    return -1;
5770
 
}
5771
 
 
5772
 
static int ATTRIBUTE_NONNULL(6)
5773
 
qemudDomainSaveImageStartVM(virConnectPtr conn,
5774
 
                            struct qemud_driver *driver,
5775
 
                            virDomainObjPtr vm,
5776
 
                            int fd,
5777
 
                            pid_t read_pid,
5778
 
                            const struct qemud_save_header *header,
5779
 
                            const char *path)
5780
 
{
5781
 
    int ret = -1;
5782
 
    virDomainEventPtr event;
5783
 
    int intermediatefd = -1;
5784
 
    pid_t intermediate_pid = -1;
5785
 
    int childstat;
5786
 
    int wait_ret;
5787
 
    int status;
5788
 
 
5789
 
    if (header->version == 2) {
5790
 
        const char *intermediate_argv[3] = { NULL, "-dc", NULL };
5791
 
        const char *prog = qemudSaveCompressionTypeToString(header->compressed);
5792
 
        if (prog == NULL) {
5793
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
5794
 
                            _("Invalid compressed save format %d"),
5795
 
                            header->compressed);
5796
 
            goto out;
5797
 
        }
5798
 
 
5799
 
        if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
5800
 
            intermediate_argv[0] = prog;
5801
 
            intermediatefd = fd;
5802
 
            fd = -1;
5803
 
            if (virExec(intermediate_argv, NULL, NULL,
5804
 
                        &intermediate_pid, intermediatefd, &fd, NULL, 0) < 0) {
5805
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
5806
 
                                _("Failed to start decompression binary %s"),
5807
 
                                intermediate_argv[0]);
5808
 
                goto out;
5809
 
            }
5810
 
        }
5811
 
    }
5812
 
 
5813
 
    /* Set the migration source and start it up. */
5814
 
    ret = qemudStartVMDaemon(conn, driver, vm, "stdio", true, fd, path,
5815
 
                             VIR_VM_OP_RESTORE);
5816
 
 
5817
 
    if (intermediate_pid != -1) {
5818
 
        if (ret < 0) {
5819
 
            /* if there was an error setting up qemu, the intermediate process will
5820
 
             * wait forever to write to stdout, so we must manually kill it.
5821
 
             */
5822
 
            VIR_FORCE_CLOSE(intermediatefd);
5823
 
            VIR_FORCE_CLOSE(fd);
5824
 
            kill(intermediate_pid, SIGTERM);
5825
 
        }
5826
 
 
5827
 
        /* Wait for intermediate process to exit */
5828
 
        while (waitpid(intermediate_pid, &childstat, 0) == -1 &&
5829
 
               errno == EINTR) {
5830
 
            /* empty */
5831
 
        }
5832
 
    }
5833
 
    VIR_FORCE_CLOSE(intermediatefd);
5834
 
 
5835
 
    wait_ret = qemudDomainSaveImageClose(fd, read_pid, &status);
5836
 
    fd = -1;
5837
 
    if (read_pid != -1) {
5838
 
        if (wait_ret == -1) {
5839
 
            virReportSystemError(errno,
5840
 
                                 _("failed to wait for process reading '%s'"),
5841
 
                                 path);
5842
 
            ret = -1;
5843
 
        } else if (!WIFEXITED(status)) {
5844
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
5845
 
                            _("child process exited abnormally reading '%s'"),
5846
 
                            path);
5847
 
            ret = -1;
5848
 
        } else {
5849
 
            int exit_status = WEXITSTATUS(status);
5850
 
            if (exit_status != 0) {
5851
 
                virReportSystemError(exit_status,
5852
 
                                     _("child process returned error reading '%s'"),
5853
 
                                     path);
5854
 
                ret = -1;
5855
 
            }
5856
 
        }
5857
 
    }
5858
 
 
5859
 
    if (ret < 0) {
5860
 
        qemuDomainStartAudit(vm, "restored", false);
5861
 
        goto out;
5862
 
    }
5863
 
 
5864
 
    event = virDomainEventNewFromObj(vm,
5865
 
                                     VIR_DOMAIN_EVENT_STARTED,
5866
 
                                     VIR_DOMAIN_EVENT_STARTED_RESTORED);
5867
 
    qemuDomainStartAudit(vm, "restored", true);
5868
 
    if (event)
5869
 
        qemuDomainEventQueue(driver, event);
5870
 
 
5871
 
 
5872
 
    /* If it was running before, resume it now. */
5873
 
    if (header->was_running) {
5874
 
        if (doStartCPUs(driver, vm, conn) < 0) {
5875
 
            if (virGetLastError() == NULL)
5876
 
                qemuReportError(VIR_ERR_OPERATION_FAILED,
5877
 
                                "%s", _("failed to resume domain"));
5878
 
            goto out;
5879
 
        }
5880
 
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
5881
 
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
5882
 
            goto out;
5883
 
        }
5884
 
    }
5885
 
 
5886
 
    ret = 0;
5887
 
 
5888
 
out:
5889
 
    if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
5890
 
                                                 vm, path) < 0)
5891
 
        VIR_WARN("failed to restore save state label on %s", path);
5892
 
 
5893
 
    return ret;
5894
 
}
5895
 
 
5896
 
static int qemudDomainRestore(virConnectPtr conn,
5897
 
                              const char *path) {
5898
 
    struct qemud_driver *driver = conn->privateData;
5899
 
    virDomainDefPtr def = NULL;
5900
 
    virDomainObjPtr vm = NULL;
5901
 
    int fd = -1;
5902
 
    pid_t read_pid = -1;
5903
 
    int ret = -1;
5904
 
    struct qemud_save_header header;
5905
 
 
5906
 
    qemuDriverLock(driver);
5907
 
 
5908
 
    fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
5909
 
    if (fd < 0)
5910
 
        goto cleanup;
5911
 
 
5912
 
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
5913
 
        goto cleanup;
5914
 
 
5915
 
    if (!(vm = virDomainAssignDef(driver->caps,
5916
 
                                  &driver->domains,
5917
 
                                  def, true))) {
5918
 
        /* virDomainAssignDef already set the error */
5919
 
        goto cleanup;
5920
 
    }
5921
 
    def = NULL;
5922
 
 
5923
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
5924
 
        goto cleanup;
5925
 
 
5926
 
    ret = qemudDomainSaveImageStartVM(conn, driver, vm, fd,
5927
 
                                      read_pid, &header, path);
5928
 
 
5929
 
    if (qemuDomainObjEndJob(vm) == 0)
5930
 
        vm = NULL;
5931
 
    else if (ret < 0 && !vm->persistent) {
5932
 
        virDomainRemoveInactive(&driver->domains, vm);
5933
 
        vm = NULL;
5934
 
    }
5935
 
 
5936
 
cleanup:
5937
 
    virDomainDefFree(def);
5938
 
    qemudDomainSaveImageClose(fd, read_pid, NULL);
5939
 
    if (vm)
5940
 
        virDomainObjUnlock(vm);
5941
 
    qemuDriverUnlock(driver);
5942
 
    return ret;
5943
 
}
5944
 
 
5945
 
static int qemudDomainObjRestore(virConnectPtr conn,
5946
 
                                 struct qemud_driver *driver,
5947
 
                                 virDomainObjPtr vm,
5948
 
                                 const char *path)
5949
 
{
5950
 
    virDomainDefPtr def = NULL;
5951
 
    int fd = -1;
5952
 
    pid_t read_pid = -1;
5953
 
    int ret = -1;
5954
 
    struct qemud_save_header header;
5955
 
 
5956
 
    fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
5957
 
    if (fd < 0)
5958
 
        goto cleanup;
5959
 
 
5960
 
    if (STRNEQ(vm->def->name, def->name) ||
5961
 
        memcmp(vm->def->uuid, def->uuid, VIR_UUID_BUFLEN)) {
5962
 
        char vm_uuidstr[VIR_UUID_STRING_BUFLEN];
5963
 
        char def_uuidstr[VIR_UUID_STRING_BUFLEN];
5964
 
        virUUIDFormat(vm->def->uuid, vm_uuidstr);
5965
 
        virUUIDFormat(def->uuid, def_uuidstr);
5966
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
5967
 
                        _("cannot restore domain '%s' uuid %s from a file"
5968
 
                          " which belongs to domain '%s' uuid %s"),
5969
 
                        vm->def->name, vm_uuidstr,
5970
 
                        def->name, def_uuidstr);
5971
 
        goto cleanup;
5972
 
    }
5973
 
 
5974
 
    virDomainObjAssignDef(vm, def, true);
5975
 
    def = NULL;
5976
 
 
5977
 
    ret = qemudDomainSaveImageStartVM(conn, driver, vm, fd,
5978
 
                                      read_pid, &header, path);
5979
 
 
5980
 
cleanup:
5981
 
    virDomainDefFree(def);
5982
 
    qemudDomainSaveImageClose(fd, read_pid, NULL);
5983
 
    return ret;
5984
 
}
5985
 
 
5986
 
 
5987
 
static char *qemudVMDumpXML(struct qemud_driver *driver,
5988
 
                            virDomainObjPtr vm,
5989
 
                            int flags)
5990
 
{
5991
 
    char *ret = NULL;
5992
 
    virCPUDefPtr cpu = NULL;
5993
 
    virDomainDefPtr def;
5994
 
    virCPUDefPtr def_cpu;
5995
 
 
5996
 
    if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
5997
 
        def = vm->newDef;
5998
 
    else
5999
 
        def = vm->def;
6000
 
    def_cpu = def->cpu;
6001
 
 
6002
 
    /* Update guest CPU requirements according to host CPU */
6003
 
    if ((flags & VIR_DOMAIN_XML_UPDATE_CPU) && def_cpu && def_cpu->model) {
6004
 
        if (!driver->caps || !driver->caps->host.cpu) {
6005
 
            qemuReportError(VIR_ERR_OPERATION_FAILED,
6006
 
                            "%s", _("cannot get host CPU capabilities"));
6007
 
            goto cleanup;
6008
 
        }
6009
 
 
6010
 
        if (!(cpu = virCPUDefCopy(def_cpu))
6011
 
            || cpuUpdate(cpu, driver->caps->host.cpu))
6012
 
            goto cleanup;
6013
 
        def->cpu = cpu;
6014
 
    }
6015
 
 
6016
 
    ret = virDomainDefFormat(def, flags);
6017
 
 
6018
 
cleanup:
6019
 
    def->cpu = def_cpu;
6020
 
    virCPUDefFree(cpu);
6021
 
    return ret;
6022
 
}
6023
 
 
6024
 
 
6025
 
static char *qemudDomainDumpXML(virDomainPtr dom,
6026
 
                                int flags) {
6027
 
    struct qemud_driver *driver = dom->conn->privateData;
6028
 
    virDomainObjPtr vm;
6029
 
    char *ret = NULL;
6030
 
    unsigned long balloon;
6031
 
    int err;
6032
 
 
6033
 
    qemuDriverLock(driver);
6034
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6035
 
 
6036
 
    if (!vm) {
6037
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6038
 
        virUUIDFormat(dom->uuid, uuidstr);
6039
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6040
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6041
 
        goto cleanup;
6042
 
    }
6043
 
 
6044
 
    /* Refresh current memory based on balloon info if supported */
6045
 
    if ((vm->def->memballoon != NULL) &&
6046
 
        (vm->def->memballoon->model != VIR_DOMAIN_MEMBALLOON_MODEL_NONE) &&
6047
 
        (virDomainObjIsActive(vm))) {
6048
 
        qemuDomainObjPrivatePtr priv = vm->privateData;
6049
 
        /* Don't delay if someone's using the monitor, just use
6050
 
         * existing most recent data instead */
6051
 
        if (!priv->jobActive) {
6052
 
            if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6053
 
                goto cleanup;
6054
 
 
6055
 
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
6056
 
            err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
6057
 
            qemuDomainObjExitMonitorWithDriver(driver, vm);
6058
 
            if (qemuDomainObjEndJob(vm) == 0) {
6059
 
                vm = NULL;
6060
 
                goto cleanup;
6061
 
            }
6062
 
            if (err < 0)
6063
 
                goto cleanup;
6064
 
            if (err > 0)
6065
 
                vm->def->mem.cur_balloon = balloon;
6066
 
            /* err == 0 indicates no balloon support, so ignore it */
6067
 
        }
6068
 
    }
6069
 
 
6070
 
    ret = qemudVMDumpXML(driver, vm, flags);
6071
 
 
6072
 
cleanup:
6073
 
    if (vm)
6074
 
        virDomainObjUnlock(vm);
6075
 
    qemuDriverUnlock(driver);
6076
 
    return ret;
6077
 
}
6078
 
 
6079
 
 
6080
 
static char *qemuDomainXMLFromNative(virConnectPtr conn,
6081
 
                                     const char *format,
6082
 
                                     const char *config,
6083
 
                                     unsigned int flags ATTRIBUTE_UNUSED) {
6084
 
    struct qemud_driver *driver = conn->privateData;
6085
 
    virDomainDefPtr def = NULL;
6086
 
    char *xml = NULL;
6087
 
 
6088
 
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
6089
 
        qemuReportError(VIR_ERR_INVALID_ARG,
6090
 
                        _("unsupported config type %s"), format);
6091
 
        goto cleanup;
6092
 
    }
6093
 
 
6094
 
    qemuDriverLock(driver);
6095
 
    def = qemuParseCommandLineString(driver->caps, config);
6096
 
    qemuDriverUnlock(driver);
6097
 
    if (!def)
6098
 
        goto cleanup;
6099
 
 
6100
 
    xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
6101
 
 
6102
 
cleanup:
6103
 
    virDomainDefFree(def);
6104
 
    return xml;
6105
 
}
6106
 
 
6107
 
static char *qemuDomainXMLToNative(virConnectPtr conn,
6108
 
                                   const char *format,
6109
 
                                   const char *xmlData,
6110
 
                                   unsigned int flags ATTRIBUTE_UNUSED) {
6111
 
    struct qemud_driver *driver = conn->privateData;
6112
 
    virDomainDefPtr def = NULL;
6113
 
    virDomainChrSourceDef monConfig;
6114
 
    unsigned long long qemuCmdFlags;
6115
 
    virCommandPtr cmd = NULL;
6116
 
    char *ret = NULL;
6117
 
    int i;
6118
 
 
6119
 
    qemuDriverLock(driver);
6120
 
 
6121
 
    if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
6122
 
        qemuReportError(VIR_ERR_INVALID_ARG,
6123
 
                        _("unsupported config type %s"), format);
6124
 
        goto cleanup;
6125
 
    }
6126
 
 
6127
 
    def = virDomainDefParseString(driver->caps, xmlData, 0);
6128
 
    if (!def)
6129
 
        goto cleanup;
6130
 
 
6131
 
    /* Since we're just exporting args, we can't do bridge/network/direct
6132
 
     * setups, since libvirt will normally create TAP/macvtap devices
6133
 
     * directly. We convert those configs into generic 'ethernet'
6134
 
     * config and assume the user has suitable 'ifup-qemu' scripts
6135
 
     */
6136
 
    for (i = 0 ; i < def->nnets ; i++) {
6137
 
        virDomainNetDefPtr net = def->nets[i];
6138
 
        int bootIndex = net->bootIndex;
6139
 
        if (net->type == VIR_DOMAIN_NET_TYPE_NETWORK ||
6140
 
            net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
6141
 
            VIR_FREE(net->data.network.name);
6142
 
 
6143
 
            memset(net, 0, sizeof *net);
6144
 
 
6145
 
            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
6146
 
            net->data.ethernet.dev = NULL;
6147
 
            net->data.ethernet.script = NULL;
6148
 
            net->data.ethernet.ipaddr = NULL;
6149
 
        } else if (net->type == VIR_DOMAIN_NET_TYPE_BRIDGE) {
6150
 
            char *brname = net->data.bridge.brname;
6151
 
            char *script = net->data.bridge.script;
6152
 
            char *ipaddr = net->data.bridge.ipaddr;
6153
 
 
6154
 
            memset(net, 0, sizeof *net);
6155
 
 
6156
 
            net->type = VIR_DOMAIN_NET_TYPE_ETHERNET;
6157
 
            net->data.ethernet.dev = brname;
6158
 
            net->data.ethernet.script = script;
6159
 
            net->data.ethernet.ipaddr = ipaddr;
6160
 
        }
6161
 
        net->bootIndex = bootIndex;
6162
 
    }
6163
 
    for (i = 0 ; i < def->ngraphics ; i++) {
6164
 
        if (def->graphics[i]->type == VIR_DOMAIN_GRAPHICS_TYPE_VNC &&
6165
 
            def->graphics[i]->data.vnc.autoport)
6166
 
            def->graphics[i]->data.vnc.port = QEMU_VNC_PORT_MIN;
6167
 
    }
6168
 
 
6169
 
    if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
6170
 
                                   NULL,
6171
 
                                   &qemuCmdFlags) < 0)
6172
 
        goto cleanup;
6173
 
 
6174
 
    if (qemuPrepareMonitorChr(driver, &monConfig, def->name) < 0)
6175
 
        goto cleanup;
6176
 
 
6177
 
    if (!(cmd = qemuBuildCommandLine(conn, driver, def,
6178
 
                                     &monConfig, false, qemuCmdFlags,
6179
 
                                     NULL, -1, NULL, VIR_VM_OP_NO_OP)))
6180
 
        goto cleanup;
6181
 
 
6182
 
    ret = virCommandToString(cmd);
6183
 
 
6184
 
cleanup:
6185
 
    qemuDriverUnlock(driver);
6186
 
 
6187
 
    virCommandFree(cmd);
6188
 
    virDomainDefFree(def);
6189
 
    return ret;
6190
 
}
6191
 
 
6192
 
 
6193
 
static int qemudListDefinedDomains(virConnectPtr conn,
6194
 
                            char **const names, int nnames) {
6195
 
    struct qemud_driver *driver = conn->privateData;
6196
 
    int n;
6197
 
 
6198
 
    qemuDriverLock(driver);
6199
 
    n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
6200
 
    qemuDriverUnlock(driver);
6201
 
    return n;
6202
 
}
6203
 
 
6204
 
static int qemudNumDefinedDomains(virConnectPtr conn) {
6205
 
    struct qemud_driver *driver = conn->privateData;
6206
 
    int n;
6207
 
 
6208
 
    qemuDriverLock(driver);
6209
 
    n = virDomainObjListNumOfDomains(&driver->domains, 0);
6210
 
    qemuDriverUnlock(driver);
6211
 
 
6212
 
    return n;
6213
 
}
6214
 
 
6215
 
 
6216
 
static int qemudDomainObjStart(virConnectPtr conn,
6217
 
                               struct qemud_driver *driver,
6218
 
                               virDomainObjPtr vm,
6219
 
                               bool start_paused)
6220
 
{
6221
 
    int ret = -1;
6222
 
    char *managed_save;
6223
 
 
6224
 
    /*
6225
 
     * If there is a managed saved state restore it instead of starting
6226
 
     * from scratch. In any case the old state is removed.
6227
 
     */
6228
 
    managed_save = qemuDomainManagedSavePath(driver, vm);
6229
 
    if ((managed_save) && (virFileExists(managed_save))) {
6230
 
        ret = qemudDomainObjRestore(conn, driver, vm, managed_save);
6231
 
 
6232
 
        if (unlink(managed_save) < 0) {
6233
 
            VIR_WARN("Failed to remove the managed state %s", managed_save);
6234
 
        }
6235
 
 
6236
 
        if (ret == 0)
6237
 
            goto cleanup;
6238
 
    }
6239
 
 
6240
 
    ret = qemudStartVMDaemon(conn, driver, vm, NULL, start_paused, -1, NULL,
6241
 
                             VIR_VM_OP_CREATE);
6242
 
    qemuDomainStartAudit(vm, "booted", ret >= 0);
6243
 
    if (ret >= 0) {
6244
 
        virDomainEventPtr event =
6245
 
            virDomainEventNewFromObj(vm,
6246
 
                                     VIR_DOMAIN_EVENT_STARTED,
6247
 
                                     VIR_DOMAIN_EVENT_STARTED_BOOTED);
6248
 
        if (event)
6249
 
            qemuDomainEventQueue(driver, event);
6250
 
    }
6251
 
 
6252
 
cleanup:
6253
 
    VIR_FREE(managed_save);
6254
 
    return ret;
6255
 
}
6256
 
 
6257
 
static int
6258
 
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
6259
 
{
6260
 
    struct qemud_driver *driver = dom->conn->privateData;
6261
 
    virDomainObjPtr vm;
6262
 
    int ret = -1;
6263
 
 
6264
 
    virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);
6265
 
 
6266
 
    qemuDriverLock(driver);
6267
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6268
 
 
6269
 
    if (!vm) {
6270
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6271
 
        virUUIDFormat(dom->uuid, uuidstr);
6272
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6273
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6274
 
        goto cleanup;
6275
 
    }
6276
 
 
6277
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6278
 
        goto cleanup;
6279
 
 
6280
 
    if (virDomainObjIsActive(vm)) {
6281
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6282
 
                        "%s", _("domain is already running"));
6283
 
        goto endjob;
6284
 
    }
6285
 
 
6286
 
    ret = qemudDomainObjStart(dom->conn, driver, vm,
6287
 
                              (flags & VIR_DOMAIN_START_PAUSED) != 0);
6288
 
 
6289
 
endjob:
6290
 
    if (qemuDomainObjEndJob(vm) == 0)
6291
 
        vm = NULL;
6292
 
 
6293
 
cleanup:
6294
 
    if (vm)
6295
 
        virDomainObjUnlock(vm);
6296
 
    qemuDriverUnlock(driver);
6297
 
    return ret;
6298
 
}
6299
 
 
6300
 
static int
6301
 
qemudDomainStart(virDomainPtr dom)
6302
 
{
6303
 
    return qemudDomainStartWithFlags(dom, 0);
6304
 
}
6305
 
 
6306
 
static int
6307
 
qemudCanonicalizeMachineFromInfo(virDomainDefPtr def,
6308
 
                                 virCapsGuestDomainInfoPtr info,
6309
 
                                 char **canonical)
6310
 
{
6311
 
    int i;
6312
 
 
6313
 
    *canonical = NULL;
6314
 
 
6315
 
    for (i = 0; i < info->nmachines; i++) {
6316
 
        virCapsGuestMachinePtr machine = info->machines[i];
6317
 
 
6318
 
        if (!machine->canonical)
6319
 
            continue;
6320
 
 
6321
 
        if (STRNEQ(def->os.machine, machine->name))
6322
 
            continue;
6323
 
 
6324
 
        if (!(*canonical = strdup(machine->canonical))) {
6325
 
            virReportOOMError();
6326
 
            return -1;
6327
 
        }
6328
 
 
6329
 
        break;
6330
 
    }
6331
 
 
6332
 
    return 0;
6333
 
}
6334
 
 
6335
 
static int
6336
 
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
6337
 
{
6338
 
    virCapsGuestMachinePtr *machines = NULL;
6339
 
    int i, nmachines = 0;
6340
 
 
6341
 
    if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
6342
 
        return -1;
6343
 
 
6344
 
    for (i = 0; i < nmachines; i++) {
6345
 
        if (!machines[i]->canonical)
6346
 
            continue;
6347
 
 
6348
 
        if (STRNEQ(def->os.machine, machines[i]->name))
6349
 
            continue;
6350
 
 
6351
 
        *canonical = machines[i]->canonical;
6352
 
        machines[i]->canonical = NULL;
6353
 
        break;
6354
 
    }
6355
 
 
6356
 
    virCapabilitiesFreeMachines(machines, nmachines);
6357
 
 
6358
 
    return 0;
6359
 
}
6360
 
 
6361
 
int
6362
 
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
6363
 
{
6364
 
    char *canonical = NULL;
6365
 
    int i;
6366
 
 
6367
 
    for (i = 0; i < driver->caps->nguests; i++) {
6368
 
        virCapsGuestPtr guest = driver->caps->guests[i];
6369
 
        virCapsGuestDomainInfoPtr info;
6370
 
        int j;
6371
 
 
6372
 
        for (j = 0; j < guest->arch.ndomains; j++) {
6373
 
            info = &guest->arch.domains[j]->info;
6374
 
 
6375
 
            if (!info->emulator || !STREQ(info->emulator, def->emulator))
6376
 
                continue;
6377
 
 
6378
 
            if (!info->nmachines)
6379
 
                info = &guest->arch.defaultInfo;
6380
 
 
6381
 
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
6382
 
                return -1;
6383
 
            goto out;
6384
 
        }
6385
 
 
6386
 
        info = &guest->arch.defaultInfo;
6387
 
 
6388
 
        if (info->emulator && STREQ(info->emulator, def->emulator)) {
6389
 
            if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
6390
 
                return -1;
6391
 
            goto out;
6392
 
        }
6393
 
    }
6394
 
 
6395
 
    if (qemudCanonicalizeMachineDirect(def, &canonical) < 0)
6396
 
        return -1;
6397
 
 
6398
 
out:
6399
 
    if (canonical) {
6400
 
        VIR_FREE(def->os.machine);
6401
 
        def->os.machine = canonical;
6402
 
    }
6403
 
    return 0;
6404
 
}
6405
 
 
6406
 
static virDomainPtr qemudDomainDefine(virConnectPtr conn, const char *xml) {
6407
 
    struct qemud_driver *driver = conn->privateData;
6408
 
    virDomainDefPtr def;
6409
 
    virDomainObjPtr vm = NULL;
6410
 
    virDomainPtr dom = NULL;
6411
 
    virDomainEventPtr event = NULL;
6412
 
    int dupVM;
6413
 
 
6414
 
    qemuDriverLock(driver);
6415
 
    if (!(def = virDomainDefParseString(driver->caps, xml,
6416
 
                                        VIR_DOMAIN_XML_INACTIVE)))
6417
 
        goto cleanup;
6418
 
 
6419
 
    if (virSecurityManagerVerify(driver->securityManager, def) < 0)
6420
 
        goto cleanup;
6421
 
 
6422
 
    if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
6423
 
        goto cleanup;
6424
 
 
6425
 
    if (qemudCanonicalizeMachine(driver, def) < 0)
6426
 
        goto cleanup;
6427
 
 
6428
 
    if (qemuAssignPCIAddresses(def) < 0)
6429
 
        goto cleanup;
6430
 
 
6431
 
    if (!(vm = virDomainAssignDef(driver->caps,
6432
 
                                  &driver->domains,
6433
 
                                  def, false))) {
6434
 
        goto cleanup;
6435
 
    }
6436
 
    def = NULL;
6437
 
    vm->persistent = 1;
6438
 
 
6439
 
    if (virDomainSaveConfig(driver->configDir,
6440
 
                            vm->newDef ? vm->newDef : vm->def) < 0) {
6441
 
        virDomainRemoveInactive(&driver->domains,
6442
 
                                vm);
6443
 
        vm = NULL;
6444
 
        goto cleanup;
6445
 
    }
6446
 
 
6447
 
    event = virDomainEventNewFromObj(vm,
6448
 
                                     VIR_DOMAIN_EVENT_DEFINED,
6449
 
                                     !dupVM ?
6450
 
                                     VIR_DOMAIN_EVENT_DEFINED_ADDED :
6451
 
                                     VIR_DOMAIN_EVENT_DEFINED_UPDATED);
6452
 
 
6453
 
    dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
6454
 
    if (dom) dom->id = vm->def->id;
6455
 
 
6456
 
cleanup:
6457
 
    virDomainDefFree(def);
6458
 
    if (vm)
6459
 
        virDomainObjUnlock(vm);
6460
 
    if (event)
6461
 
        qemuDomainEventQueue(driver, event);
6462
 
    qemuDriverUnlock(driver);
6463
 
    return dom;
6464
 
}
6465
 
 
6466
 
static int qemudDomainUndefine(virDomainPtr dom) {
6467
 
    struct qemud_driver *driver = dom->conn->privateData;
6468
 
    virDomainObjPtr vm;
6469
 
    virDomainEventPtr event = NULL;
6470
 
    int ret = -1;
6471
 
 
6472
 
    qemuDriverLock(driver);
6473
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6474
 
 
6475
 
    if (!vm) {
6476
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6477
 
        virUUIDFormat(dom->uuid, uuidstr);
6478
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6479
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6480
 
        goto cleanup;
6481
 
    }
6482
 
 
6483
 
    if (virDomainObjIsActive(vm)) {
6484
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6485
 
                        "%s", _("cannot delete active domain"));
6486
 
        goto cleanup;
6487
 
    }
6488
 
 
6489
 
    if (!vm->persistent) {
6490
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6491
 
                        "%s", _("cannot undefine transient domain"));
6492
 
        goto cleanup;
6493
 
    }
6494
 
 
6495
 
    if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
6496
 
        goto cleanup;
6497
 
 
6498
 
    event = virDomainEventNewFromObj(vm,
6499
 
                                     VIR_DOMAIN_EVENT_UNDEFINED,
6500
 
                                     VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
6501
 
 
6502
 
    virDomainRemoveInactive(&driver->domains,
6503
 
                            vm);
6504
 
    vm = NULL;
6505
 
    ret = 0;
6506
 
 
6507
 
cleanup:
6508
 
    if (vm)
6509
 
        virDomainObjUnlock(vm);
6510
 
    if (event)
6511
 
        qemuDomainEventQueue(driver, event);
6512
 
    qemuDriverUnlock(driver);
6513
 
    return ret;
6514
 
}
6515
 
 
6516
 
 
6517
 
static int qemudDomainAttachDevice(virDomainPtr dom,
6518
 
                                   const char *xml)
6519
 
{
6520
 
    struct qemud_driver *driver = dom->conn->privateData;
6521
 
    virDomainObjPtr vm;
6522
 
    virDomainDeviceDefPtr dev = NULL;
6523
 
    unsigned long long qemuCmdFlags;
6524
 
    virCgroupPtr cgroup = NULL;
6525
 
    int ret = -1;
6526
 
 
6527
 
    qemuDriverLock(driver);
6528
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6529
 
    if (!vm) {
6530
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6531
 
        virUUIDFormat(dom->uuid, uuidstr);
6532
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6533
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6534
 
        goto cleanup;
6535
 
    }
6536
 
 
6537
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6538
 
        goto cleanup;
6539
 
 
6540
 
    if (!virDomainObjIsActive(vm)) {
6541
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6542
 
                        "%s", _("cannot attach device on inactive domain"));
6543
 
        goto endjob;
6544
 
    }
6545
 
 
6546
 
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
6547
 
                                  VIR_DOMAIN_XML_INACTIVE);
6548
 
    if (dev == NULL)
6549
 
        goto endjob;
6550
 
 
6551
 
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
6552
 
                                   NULL,
6553
 
                                   &qemuCmdFlags) < 0)
6554
 
        goto endjob;
6555
 
 
6556
 
    if (dev->type == VIR_DOMAIN_DEVICE_DISK) {
6557
 
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
6558
 
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
6559
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6560
 
                                _("Unable to find cgroup for %s"),
6561
 
                                vm->def->name);
6562
 
                goto endjob;
6563
 
            }
6564
 
            if (qemuSetupDiskCgroup(driver, cgroup, dev->data.disk) < 0)
6565
 
                goto endjob;
6566
 
        }
6567
 
 
6568
 
        switch (dev->data.disk->device) {
6569
 
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
6570
 
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
6571
 
            ret = qemuDomainChangeEjectableMedia(driver, vm,
6572
 
                                                 dev->data.disk,
6573
 
                                                 qemuCmdFlags,
6574
 
                                                 false);
6575
 
            if (ret == 0)
6576
 
                dev->data.disk = NULL;
6577
 
            break;
6578
 
 
6579
 
        case VIR_DOMAIN_DISK_DEVICE_DISK:
6580
 
            if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_USB) {
6581
 
                ret = qemuDomainAttachUsbMassstorageDevice(driver, vm,
6582
 
                                                           dev->data.disk, qemuCmdFlags);
6583
 
                if (ret == 0)
6584
 
                    dev->data.disk = NULL;
6585
 
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
6586
 
                ret = qemuDomainAttachPciDiskDevice(driver, vm,
6587
 
                                                    dev->data.disk, qemuCmdFlags);
6588
 
                if (ret == 0)
6589
 
                    dev->data.disk = NULL;
6590
 
            } else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
6591
 
                ret = qemuDomainAttachSCSIDisk(driver, vm,
6592
 
                                               dev->data.disk, qemuCmdFlags);
6593
 
                if (ret == 0)
6594
 
                    dev->data.disk = NULL;
6595
 
            } else {
6596
 
                qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6597
 
                                _("disk bus '%s' cannot be hotplugged."),
6598
 
                                virDomainDiskBusTypeToString(dev->data.disk->bus));
6599
 
                /* fallthrough */
6600
 
            }
6601
 
            break;
6602
 
 
6603
 
        default:
6604
 
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6605
 
                            _("disk device type '%s' cannot be hotplugged"),
6606
 
                            virDomainDiskDeviceTypeToString(dev->data.disk->device));
6607
 
            /* Fallthrough */
6608
 
        }
6609
 
        if (ret != 0 && cgroup) {
6610
 
            if (qemuTeardownDiskCgroup(driver, cgroup, dev->data.disk) < 0)
6611
 
                VIR_WARN("Failed to teardown cgroup for disk path %s",
6612
 
                         NULLSTR(dev->data.disk->src));
6613
 
        }
6614
 
    } else if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
6615
 
        if (dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
6616
 
            ret = qemuDomainAttachPciControllerDevice(driver, vm,
6617
 
                                                      dev->data.controller, qemuCmdFlags);
6618
 
            if (ret == 0)
6619
 
                dev->data.controller = NULL;
6620
 
        } else {
6621
 
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6622
 
                            _("disk controller bus '%s' cannot be hotplugged."),
6623
 
                            virDomainControllerTypeToString(dev->data.controller->type));
6624
 
            /* fallthrough */
6625
 
        }
6626
 
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
6627
 
        ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
6628
 
                                        dev->data.net, qemuCmdFlags);
6629
 
        if (ret == 0)
6630
 
            dev->data.net = NULL;
6631
 
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
6632
 
        ret = qemuDomainAttachHostDevice(driver, vm,
6633
 
                                         dev->data.hostdev, qemuCmdFlags);
6634
 
        if (ret == 0)
6635
 
            dev->data.hostdev = NULL;
6636
 
    } else {
6637
 
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6638
 
                        _("device type '%s' cannot be attached"),
6639
 
                        virDomainDeviceTypeToString(dev->type));
6640
 
        goto endjob;
6641
 
    }
6642
 
 
6643
 
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
6644
 
        ret = -1;
6645
 
 
6646
 
endjob:
6647
 
    if (qemuDomainObjEndJob(vm) == 0)
6648
 
        vm = NULL;
6649
 
 
6650
 
cleanup:
6651
 
    if (cgroup)
6652
 
        virCgroupFree(&cgroup);
6653
 
 
6654
 
    virDomainDeviceDefFree(dev);
6655
 
    if (vm)
6656
 
        virDomainObjUnlock(vm);
6657
 
    qemuDriverUnlock(driver);
6658
 
    return ret;
6659
 
}
6660
 
 
6661
 
static int qemudDomainAttachDeviceFlags(virDomainPtr dom,
6662
 
                                        const char *xml,
6663
 
                                        unsigned int flags) {
6664
 
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
6665
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6666
 
                        "%s", _("cannot modify the persistent configuration of a domain"));
6667
 
        return -1;
6668
 
    }
6669
 
 
6670
 
    return qemudDomainAttachDevice(dom, xml);
6671
 
}
6672
 
 
6673
 
 
6674
 
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
6675
 
                                       const char *xml,
6676
 
                                       unsigned int flags)
6677
 
{
6678
 
    struct qemud_driver *driver = dom->conn->privateData;
6679
 
    virDomainObjPtr vm;
6680
 
    virDomainDeviceDefPtr dev = NULL;
6681
 
    unsigned long long qemuCmdFlags;
6682
 
    virCgroupPtr cgroup = NULL;
6683
 
    int ret = -1;
6684
 
    bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
6685
 
 
6686
 
    virCheckFlags(VIR_DOMAIN_DEVICE_MODIFY_CURRENT |
6687
 
                  VIR_DOMAIN_DEVICE_MODIFY_LIVE |
6688
 
                  VIR_DOMAIN_DEVICE_MODIFY_CONFIG |
6689
 
                  VIR_DOMAIN_DEVICE_MODIFY_FORCE, -1);
6690
 
 
6691
 
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
6692
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6693
 
                        "%s", _("cannot modify the persistent configuration of a domain"));
6694
 
        return -1;
6695
 
    }
6696
 
 
6697
 
    qemuDriverLock(driver);
6698
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6699
 
    if (!vm) {
6700
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6701
 
        virUUIDFormat(dom->uuid, uuidstr);
6702
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6703
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6704
 
        goto cleanup;
6705
 
    }
6706
 
 
6707
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6708
 
        goto cleanup;
6709
 
 
6710
 
    if (!virDomainObjIsActive(vm)) {
6711
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6712
 
                        "%s", _("cannot attach device on inactive domain"));
6713
 
        goto endjob;
6714
 
    }
6715
 
 
6716
 
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
6717
 
                                  VIR_DOMAIN_XML_INACTIVE);
6718
 
    if (dev == NULL)
6719
 
        goto endjob;
6720
 
 
6721
 
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
6722
 
                                   NULL,
6723
 
                                   &qemuCmdFlags) < 0)
6724
 
        goto endjob;
6725
 
 
6726
 
    switch (dev->type) {
6727
 
    case VIR_DOMAIN_DEVICE_DISK:
6728
 
        if (qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_DEVICES)) {
6729
 
            if (virCgroupForDomain(driver->cgroup, vm->def->name, &cgroup, 0) !=0 ) {
6730
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
6731
 
                                _("Unable to find cgroup for %s"),
6732
 
                                vm->def->name);
6733
 
                goto endjob;
6734
 
            }
6735
 
            if (qemuSetupDiskCgroup(driver, cgroup, dev->data.disk) < 0)
6736
 
                goto endjob;
6737
 
        }
6738
 
 
6739
 
        switch (dev->data.disk->device) {
6740
 
        case VIR_DOMAIN_DISK_DEVICE_CDROM:
6741
 
        case VIR_DOMAIN_DISK_DEVICE_FLOPPY:
6742
 
            ret = qemuDomainChangeEjectableMedia(driver, vm,
6743
 
                                                 dev->data.disk,
6744
 
                                                 qemuCmdFlags,
6745
 
                                                 force);
6746
 
            if (ret == 0)
6747
 
                dev->data.disk = NULL;
6748
 
            break;
6749
 
 
6750
 
 
6751
 
        default:
6752
 
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6753
 
                            _("disk bus '%s' cannot be updated."),
6754
 
                            virDomainDiskBusTypeToString(dev->data.disk->bus));
6755
 
            break;
6756
 
        }
6757
 
 
6758
 
        if (ret != 0 && cgroup) {
6759
 
            if (qemuTeardownDiskCgroup(driver, cgroup, dev->data.disk) < 0)
6760
 
                VIR_WARN("Failed to teardown cgroup for disk path %s",
6761
 
                         NULLSTR(dev->data.disk->src));
6762
 
        }
6763
 
        break;
6764
 
 
6765
 
    case VIR_DOMAIN_DEVICE_GRAPHICS:
6766
 
        ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
6767
 
        break;
6768
 
 
6769
 
    default:
6770
 
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6771
 
                        _("disk device type '%s' cannot be updated"),
6772
 
                        virDomainDiskDeviceTypeToString(dev->data.disk->device));
6773
 
        break;
6774
 
    }
6775
 
 
6776
 
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
6777
 
        ret = -1;
6778
 
 
6779
 
endjob:
6780
 
    if (qemuDomainObjEndJob(vm) == 0)
6781
 
        vm = NULL;
6782
 
 
6783
 
cleanup:
6784
 
    if (cgroup)
6785
 
        virCgroupFree(&cgroup);
6786
 
 
6787
 
    virDomainDeviceDefFree(dev);
6788
 
    if (vm)
6789
 
        virDomainObjUnlock(vm);
6790
 
    qemuDriverUnlock(driver);
6791
 
    return ret;
6792
 
}
6793
 
 
6794
 
 
6795
 
static int qemudDomainDetachDevice(virDomainPtr dom,
6796
 
                                   const char *xml) {
6797
 
    struct qemud_driver *driver = dom->conn->privateData;
6798
 
    virDomainObjPtr vm;
6799
 
    unsigned long long qemuCmdFlags;
6800
 
    virDomainDeviceDefPtr dev = NULL;
6801
 
    int ret = -1;
6802
 
 
6803
 
    qemuDriverLock(driver);
6804
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6805
 
    if (!vm) {
6806
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6807
 
        virUUIDFormat(dom->uuid, uuidstr);
6808
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6809
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6810
 
        goto cleanup;
6811
 
    }
6812
 
 
6813
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6814
 
        goto cleanup;
6815
 
 
6816
 
    if (!virDomainObjIsActive(vm)) {
6817
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6818
 
                        "%s", _("cannot detach device on inactive domain"));
6819
 
        goto endjob;
6820
 
    }
6821
 
 
6822
 
    dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
6823
 
                                  VIR_DOMAIN_XML_INACTIVE);
6824
 
    if (dev == NULL)
6825
 
        goto endjob;
6826
 
 
6827
 
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
6828
 
                                   NULL,
6829
 
                                   &qemuCmdFlags) < 0)
6830
 
        goto endjob;
6831
 
 
6832
 
    if (dev->type == VIR_DOMAIN_DEVICE_DISK &&
6833
 
        dev->data.disk->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
6834
 
        if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_VIRTIO) {
6835
 
            ret = qemuDomainDetachPciDiskDevice(driver, vm, dev, qemuCmdFlags);
6836
 
        }
6837
 
        else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
6838
 
            ret = qemuDomainDetachSCSIDiskDevice(driver, vm, dev,
6839
 
                                                 qemuCmdFlags);
6840
 
        }
6841
 
        else {
6842
 
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6843
 
                            _("This type of disk cannot be hot unplugged"));
6844
 
        }
6845
 
    } else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
6846
 
        ret = qemuDomainDetachNetDevice(driver, vm, dev, qemuCmdFlags);
6847
 
    } else if (dev->type == VIR_DOMAIN_DEVICE_CONTROLLER) {
6848
 
        if (dev->data.controller->type == VIR_DOMAIN_CONTROLLER_TYPE_SCSI) {
6849
 
            ret = qemuDomainDetachPciControllerDevice(driver, vm, dev,
6850
 
                                                      qemuCmdFlags);
6851
 
        } else {
6852
 
            qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6853
 
                            _("disk controller bus '%s' cannot be hotunplugged."),
6854
 
                            virDomainControllerTypeToString(dev->data.controller->type));
6855
 
            /* fallthrough */
6856
 
        }
6857
 
    } else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
6858
 
        ret = qemuDomainDetachHostDevice(driver, vm, dev, qemuCmdFlags);
6859
 
    } else {
6860
 
        qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6861
 
                        "%s", _("This type of device cannot be hot unplugged"));
6862
 
    }
6863
 
 
6864
 
    if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
6865
 
        ret = -1;
6866
 
 
6867
 
endjob:
6868
 
    if (qemuDomainObjEndJob(vm) == 0)
6869
 
        vm = NULL;
6870
 
 
6871
 
cleanup:
6872
 
    virDomainDeviceDefFree(dev);
6873
 
    if (vm)
6874
 
        virDomainObjUnlock(vm);
6875
 
    qemuDriverUnlock(driver);
6876
 
    return ret;
6877
 
}
6878
 
 
6879
 
static int qemudDomainDetachDeviceFlags(virDomainPtr dom,
6880
 
                                        const char *xml,
6881
 
                                        unsigned int flags) {
6882
 
    if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
6883
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6884
 
                        "%s", _("cannot modify the persistent configuration of a domain"));
6885
 
        return -1;
6886
 
    }
6887
 
 
6888
 
    return qemudDomainDetachDevice(dom, xml);
6889
 
}
6890
 
 
6891
 
static int qemudDomainGetAutostart(virDomainPtr dom,
6892
 
                                   int *autostart) {
6893
 
    struct qemud_driver *driver = dom->conn->privateData;
6894
 
    virDomainObjPtr vm;
6895
 
    int ret = -1;
6896
 
 
6897
 
    qemuDriverLock(driver);
6898
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6899
 
    qemuDriverUnlock(driver);
6900
 
 
6901
 
    if (!vm) {
6902
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6903
 
        virUUIDFormat(dom->uuid, uuidstr);
6904
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6905
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6906
 
        goto cleanup;
6907
 
    }
6908
 
 
6909
 
    *autostart = vm->autostart;
6910
 
    ret = 0;
6911
 
 
6912
 
cleanup:
6913
 
    if (vm)
6914
 
        virDomainObjUnlock(vm);
6915
 
    return ret;
6916
 
}
6917
 
 
6918
 
static int qemudDomainSetAutostart(virDomainPtr dom,
6919
 
                                   int autostart) {
6920
 
    struct qemud_driver *driver = dom->conn->privateData;
6921
 
    virDomainObjPtr vm;
6922
 
    char *configFile = NULL, *autostartLink = NULL;
6923
 
    int ret = -1;
6924
 
 
6925
 
    qemuDriverLock(driver);
6926
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6927
 
 
6928
 
    if (!vm) {
6929
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
6930
 
        virUUIDFormat(dom->uuid, uuidstr);
6931
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
6932
 
                        _("no domain with matching uuid '%s'"), uuidstr);
6933
 
        goto cleanup;
6934
 
    }
6935
 
 
6936
 
    if (!vm->persistent) {
6937
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6938
 
                        "%s", _("cannot set autostart for transient domain"));
6939
 
        goto cleanup;
6940
 
    }
6941
 
 
6942
 
    autostart = (autostart != 0);
6943
 
 
6944
 
    if (vm->autostart != autostart) {
6945
 
        if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
6946
 
            goto cleanup;
6947
 
        if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
6948
 
            goto cleanup;
6949
 
 
6950
 
        if (autostart) {
6951
 
            int err;
6952
 
 
6953
 
            if ((err = virFileMakePath(driver->autostartDir))) {
6954
 
                virReportSystemError(err,
6955
 
                                     _("cannot create autostart directory %s"),
6956
 
                                     driver->autostartDir);
6957
 
                goto cleanup;
6958
 
            }
6959
 
 
6960
 
            if (symlink(configFile, autostartLink) < 0) {
6961
 
                virReportSystemError(errno,
6962
 
                                     _("Failed to create symlink '%s to '%s'"),
6963
 
                                     autostartLink, configFile);
6964
 
                goto cleanup;
6965
 
            }
6966
 
        } else {
6967
 
            if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
6968
 
                virReportSystemError(errno,
6969
 
                                     _("Failed to delete symlink '%s'"),
6970
 
                                     autostartLink);
6971
 
                goto cleanup;
6972
 
            }
6973
 
        }
6974
 
 
6975
 
        vm->autostart = autostart;
6976
 
    }
6977
 
    ret = 0;
6978
 
 
6979
 
cleanup:
6980
 
    VIR_FREE(configFile);
6981
 
    VIR_FREE(autostartLink);
6982
 
    if (vm)
6983
 
        virDomainObjUnlock(vm);
6984
 
    qemuDriverUnlock(driver);
6985
 
    return ret;
6986
 
}
6987
 
 
6988
 
 
6989
 
static char *qemuGetSchedulerType(virDomainPtr dom,
6990
 
                                  int *nparams)
6991
 
{
6992
 
    struct qemud_driver *driver = dom->conn->privateData;
6993
 
    char *ret = NULL;
6994
 
 
6995
 
    qemuDriverLock(driver);
6996
 
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
6997
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
6998
 
                        "%s", _("cgroup CPU controller is not mounted"));
6999
 
        goto cleanup;
7000
 
    }
7001
 
 
7002
 
    if (nparams)
7003
 
        *nparams = 1;
7004
 
 
7005
 
    ret = strdup("posix");
7006
 
    if (!ret)
7007
 
        virReportOOMError();
7008
 
 
7009
 
cleanup:
7010
 
    qemuDriverUnlock(driver);
7011
 
    return ret;
7012
 
}
7013
 
 
7014
 
 
7015
 
static int qemuDomainSetMemoryParameters(virDomainPtr dom,
7016
 
                                         virMemoryParameterPtr params,
7017
 
                                         int nparams,
7018
 
                                         unsigned int flags ATTRIBUTE_UNUSED)
7019
 
{
7020
 
    struct qemud_driver *driver = dom->conn->privateData;
7021
 
    int i;
7022
 
    virCgroupPtr group = NULL;
7023
 
    virDomainObjPtr vm = NULL;
7024
 
    int ret = -1;
7025
 
 
7026
 
    qemuDriverLock(driver);
7027
 
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
7028
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7029
 
                        "%s", _("cgroup memory controller is not mounted"));
7030
 
        goto cleanup;
7031
 
    }
7032
 
 
7033
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7034
 
 
7035
 
    if (vm == NULL) {
7036
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7037
 
                        _("No such domain %s"), dom->uuid);
7038
 
        goto cleanup;
7039
 
    }
7040
 
 
7041
 
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7042
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7043
 
                        _("cannot find cgroup for domain %s"), vm->def->name);
7044
 
        goto cleanup;
7045
 
    }
7046
 
 
7047
 
    ret = 0;
7048
 
    for (i = 0; i < nparams; i++) {
7049
 
        virMemoryParameterPtr param = &params[i];
7050
 
 
7051
 
        if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
7052
 
            int rc;
7053
 
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
7054
 
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
7055
 
                                _("invalid type for memory hard_limit tunable, expected a 'ullong'"));
7056
 
                ret = -1;
7057
 
                continue;
7058
 
            }
7059
 
 
7060
 
            rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
7061
 
            if (rc != 0) {
7062
 
                virReportSystemError(-rc, "%s",
7063
 
                                     _("unable to set memory hard_limit tunable"));
7064
 
                ret = -1;
7065
 
            }
7066
 
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
7067
 
            int rc;
7068
 
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
7069
 
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
7070
 
                                _("invalid type for memory soft_limit tunable, expected a 'ullong'"));
7071
 
                ret = -1;
7072
 
                continue;
7073
 
            }
7074
 
 
7075
 
            rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
7076
 
            if (rc != 0) {
7077
 
                virReportSystemError(-rc, "%s",
7078
 
                                     _("unable to set memory soft_limit tunable"));
7079
 
                ret = -1;
7080
 
            }
7081
 
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
7082
 
            int rc;
7083
 
            if (param->type != VIR_DOMAIN_MEMORY_PARAM_ULLONG) {
7084
 
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
7085
 
                                _("invalid type for swap_hard_limit tunable, expected a 'ullong'"));
7086
 
                ret = -1;
7087
 
                continue;
7088
 
            }
7089
 
 
7090
 
            rc = virCgroupSetSwapHardLimit(group, params[i].value.ul);
7091
 
            if (rc != 0) {
7092
 
                virReportSystemError(-rc, "%s",
7093
 
                                     _("unable to set swap_hard_limit tunable"));
7094
 
                ret = -1;
7095
 
            }
7096
 
        } else if (STREQ(param->field, VIR_DOMAIN_MEMORY_MIN_GUARANTEE)) {
7097
 
            qemuReportError(VIR_ERR_INVALID_ARG,
7098
 
                            _("Memory tunable `%s' not implemented"), param->field);
7099
 
            ret = -1;
7100
 
        } else {
7101
 
            qemuReportError(VIR_ERR_INVALID_ARG,
7102
 
                            _("Parameter `%s' not supported"), param->field);
7103
 
            ret = -1;
7104
 
        }
7105
 
    }
7106
 
 
7107
 
cleanup:
7108
 
    virCgroupFree(&group);
7109
 
    if (vm)
7110
 
        virDomainObjUnlock(vm);
7111
 
    qemuDriverUnlock(driver);
7112
 
    return ret;
7113
 
}
7114
 
 
7115
 
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
7116
 
                                         virMemoryParameterPtr params,
7117
 
                                         int *nparams,
7118
 
                                         unsigned int flags ATTRIBUTE_UNUSED)
7119
 
{
7120
 
    struct qemud_driver *driver = dom->conn->privateData;
7121
 
    int i;
7122
 
    virCgroupPtr group = NULL;
7123
 
    virDomainObjPtr vm = NULL;
7124
 
    unsigned long long val;
7125
 
    int ret = -1;
7126
 
    int rc;
7127
 
 
7128
 
    qemuDriverLock(driver);
7129
 
 
7130
 
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
7131
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7132
 
                        "%s", _("cgroup memory controller is not mounted"));
7133
 
        goto cleanup;
7134
 
    }
7135
 
 
7136
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7137
 
 
7138
 
    if (vm == NULL) {
7139
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7140
 
                        _("No such domain %s"), dom->uuid);
7141
 
        goto cleanup;
7142
 
    }
7143
 
 
7144
 
    if ((*nparams) == 0) {
7145
 
        /* Current number of memory parameters supported by cgroups */
7146
 
        *nparams = QEMU_NB_MEM_PARAM;
7147
 
        ret = 0;
7148
 
        goto cleanup;
7149
 
    }
7150
 
 
7151
 
    if ((*nparams) != QEMU_NB_MEM_PARAM) {
7152
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7153
 
                        "%s", _("Invalid parameter count"));
7154
 
        goto cleanup;
7155
 
    }
7156
 
 
7157
 
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7158
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7159
 
                        _("cannot find cgroup for domain %s"), vm->def->name);
7160
 
        goto cleanup;
7161
 
    }
7162
 
 
7163
 
    for (i = 0; i < *nparams; i++) {
7164
 
        virMemoryParameterPtr param = &params[i];
7165
 
        val = 0;
7166
 
        param->value.ul = 0;
7167
 
        param->type = VIR_DOMAIN_MEMORY_PARAM_ULLONG;
7168
 
 
7169
 
        switch(i) {
7170
 
        case 0: /* fill memory hard limit here */
7171
 
            rc = virCgroupGetMemoryHardLimit(group, &val);
7172
 
            if (rc != 0) {
7173
 
                virReportSystemError(-rc, "%s",
7174
 
                                     _("unable to get memory hard limit"));
7175
 
                goto cleanup;
7176
 
            }
7177
 
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT) == NULL) {
7178
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7179
 
                                "%s", _("Field memory hard limit too long for destination"));
7180
 
                goto cleanup;
7181
 
            }
7182
 
            param->value.ul = val;
7183
 
            break;
7184
 
 
7185
 
        case 1: /* fill memory soft limit here */
7186
 
            rc = virCgroupGetMemorySoftLimit(group, &val);
7187
 
            if (rc != 0) {
7188
 
                virReportSystemError(-rc, "%s",
7189
 
                                     _("unable to get memory soft limit"));
7190
 
                goto cleanup;
7191
 
            }
7192
 
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT) == NULL) {
7193
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7194
 
                                "%s", _("Field memory soft limit too long for destination"));
7195
 
                goto cleanup;
7196
 
            }
7197
 
            param->value.ul = val;
7198
 
            break;
7199
 
 
7200
 
        case 2: /* fill swap hard limit here */
7201
 
            rc = virCgroupGetSwapHardLimit(group, &val);
7202
 
            if (rc != 0) {
7203
 
                virReportSystemError(-rc, "%s",
7204
 
                                     _("unable to get swap hard limit"));
7205
 
                goto cleanup;
7206
 
            }
7207
 
            if (virStrcpyStatic(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT) == NULL) {
7208
 
                qemuReportError(VIR_ERR_INTERNAL_ERROR,
7209
 
                                "%s", _("Field swap hard limit too long for destination"));
7210
 
                goto cleanup;
7211
 
            }
7212
 
            param->value.ul = val;
7213
 
            break;
7214
 
 
7215
 
        default:
7216
 
            break;
7217
 
            /* should not hit here */
7218
 
        }
7219
 
    }
7220
 
 
7221
 
    ret = 0;
7222
 
 
7223
 
cleanup:
7224
 
    if (group)
7225
 
        virCgroupFree(&group);
7226
 
    if (vm)
7227
 
        virDomainObjUnlock(vm);
7228
 
    qemuDriverUnlock(driver);
7229
 
    return ret;
7230
 
}
7231
 
 
7232
 
static int qemuSetSchedulerParameters(virDomainPtr dom,
7233
 
                                      virSchedParameterPtr params,
7234
 
                                      int nparams)
7235
 
{
7236
 
    struct qemud_driver *driver = dom->conn->privateData;
7237
 
    int i;
7238
 
    virCgroupPtr group = NULL;
7239
 
    virDomainObjPtr vm = NULL;
7240
 
    int ret = -1;
7241
 
 
7242
 
    qemuDriverLock(driver);
7243
 
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
7244
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7245
 
                        "%s", _("cgroup CPU controller is not mounted"));
7246
 
        goto cleanup;
7247
 
    }
7248
 
 
7249
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7250
 
 
7251
 
    if (vm == NULL) {
7252
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7253
 
                        _("No such domain %s"), dom->uuid);
7254
 
        goto cleanup;
7255
 
    }
7256
 
 
7257
 
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7258
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7259
 
                        _("cannot find cgroup for domain %s"), vm->def->name);
7260
 
        goto cleanup;
7261
 
    }
7262
 
 
7263
 
    for (i = 0; i < nparams; i++) {
7264
 
        virSchedParameterPtr param = &params[i];
7265
 
 
7266
 
        if (STREQ(param->field, "cpu_shares")) {
7267
 
            int rc;
7268
 
            if (param->type != VIR_DOMAIN_SCHED_FIELD_ULLONG) {
7269
 
                qemuReportError(VIR_ERR_INVALID_ARG, "%s",
7270
 
                                _("invalid type for cpu_shares tunable, expected a 'ullong'"));
7271
 
                goto cleanup;
7272
 
            }
7273
 
 
7274
 
            rc = virCgroupSetCpuShares(group, params[i].value.ul);
7275
 
            if (rc != 0) {
7276
 
                virReportSystemError(-rc, "%s",
7277
 
                                     _("unable to set cpu shares tunable"));
7278
 
                goto cleanup;
7279
 
            }
7280
 
        } else {
7281
 
            qemuReportError(VIR_ERR_INVALID_ARG,
7282
 
                            _("Invalid parameter `%s'"), param->field);
7283
 
            goto cleanup;
7284
 
        }
7285
 
    }
7286
 
    ret = 0;
7287
 
 
7288
 
cleanup:
7289
 
    virCgroupFree(&group);
7290
 
    if (vm)
7291
 
        virDomainObjUnlock(vm);
7292
 
    qemuDriverUnlock(driver);
7293
 
    return ret;
7294
 
}
7295
 
 
7296
 
static int qemuGetSchedulerParameters(virDomainPtr dom,
7297
 
                                      virSchedParameterPtr params,
7298
 
                                      int *nparams)
7299
 
{
7300
 
    struct qemud_driver *driver = dom->conn->privateData;
7301
 
    virCgroupPtr group = NULL;
7302
 
    virDomainObjPtr vm = NULL;
7303
 
    unsigned long long val;
7304
 
    int ret = -1;
7305
 
    int rc;
7306
 
 
7307
 
    qemuDriverLock(driver);
7308
 
    if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_CPU)) {
7309
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7310
 
                        "%s", _("cgroup CPU controller is not mounted"));
7311
 
        goto cleanup;
7312
 
    }
7313
 
 
7314
 
    if ((*nparams) != 1) {
7315
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7316
 
                        "%s", _("Invalid parameter count"));
7317
 
        goto cleanup;
7318
 
    }
7319
 
 
7320
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7321
 
 
7322
 
    if (vm == NULL) {
7323
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7324
 
                        _("No such domain %s"), dom->uuid);
7325
 
        goto cleanup;
7326
 
    }
7327
 
 
7328
 
    if (virCgroupForDomain(driver->cgroup, vm->def->name, &group, 0) != 0) {
7329
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7330
 
                        _("cannot find cgroup for domain %s"), vm->def->name);
7331
 
        goto cleanup;
7332
 
    }
7333
 
 
7334
 
    rc = virCgroupGetCpuShares(group, &val);
7335
 
    if (rc != 0) {
7336
 
        virReportSystemError(-rc, "%s",
7337
 
                             _("unable to get cpu shares tunable"));
7338
 
        goto cleanup;
7339
 
    }
7340
 
    params[0].value.ul = val;
7341
 
    params[0].type = VIR_DOMAIN_SCHED_FIELD_ULLONG;
7342
 
    if (virStrcpyStatic(params[0].field, "cpu_shares") == NULL) {
7343
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7344
 
                        "%s", _("Field cpu_shares too long for destination"));
7345
 
        goto cleanup;
7346
 
    }
7347
 
 
7348
 
    ret = 0;
7349
 
 
7350
 
cleanup:
7351
 
    virCgroupFree(&group);
7352
 
    if (vm)
7353
 
        virDomainObjUnlock(vm);
7354
 
    qemuDriverUnlock(driver);
7355
 
    return ret;
7356
 
}
7357
 
 
7358
 
 
7359
 
/* This uses the 'info blockstats' monitor command which was
7360
 
 * integrated into both qemu & kvm in late 2007.  If the command is
7361
 
 * not supported we detect this and return the appropriate error.
7362
 
 */
7363
 
static int
7364
 
qemudDomainBlockStats (virDomainPtr dom,
7365
 
                       const char *path,
7366
 
                       struct _virDomainBlockStats *stats)
7367
 
{
7368
 
    struct qemud_driver *driver = dom->conn->privateData;
7369
 
    int i, ret = -1;
7370
 
    virDomainObjPtr vm;
7371
 
    virDomainDiskDefPtr disk = NULL;
7372
 
 
7373
 
    qemuDriverLock(driver);
7374
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7375
 
    qemuDriverUnlock(driver);
7376
 
    if (!vm) {
7377
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
7378
 
        virUUIDFormat(dom->uuid, uuidstr);
7379
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
7380
 
                        _("no domain with matching uuid '%s'"), uuidstr);
7381
 
        goto cleanup;
7382
 
    }
7383
 
 
7384
 
    if (qemuDomainObjBeginJob(vm) < 0)
7385
 
        goto cleanup;
7386
 
 
7387
 
    if (!virDomainObjIsActive (vm)) {
7388
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7389
 
                        "%s", _("domain is not running"));
7390
 
        goto endjob;
7391
 
    }
7392
 
 
7393
 
    for (i = 0 ; i < vm->def->ndisks ; i++) {
7394
 
        if (STREQ(path, vm->def->disks[i]->dst)) {
7395
 
            disk = vm->def->disks[i];
7396
 
            break;
7397
 
        }
7398
 
    }
7399
 
 
7400
 
    if (!disk) {
7401
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7402
 
                        _("invalid path: %s"), path);
7403
 
        goto endjob;
7404
 
    }
7405
 
 
7406
 
    if (!disk->info.alias) {
7407
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
7408
 
                        _("missing disk device alias name for %s"), disk->dst);
7409
 
        goto endjob;
7410
 
    }
7411
 
 
7412
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
7413
 
    qemuDomainObjEnterMonitor(vm);
7414
 
    ret = qemuMonitorGetBlockStatsInfo(priv->mon,
7415
 
                                       disk->info.alias,
7416
 
                                       &stats->rd_req,
7417
 
                                       &stats->rd_bytes,
7418
 
                                       &stats->wr_req,
7419
 
                                       &stats->wr_bytes,
7420
 
                                       &stats->errs);
7421
 
    qemuDomainObjExitMonitor(vm);
7422
 
 
7423
 
endjob:
7424
 
    if (qemuDomainObjEndJob(vm) == 0)
7425
 
        vm = NULL;
7426
 
 
7427
 
cleanup:
7428
 
    if (vm)
7429
 
        virDomainObjUnlock(vm);
7430
 
    return ret;
7431
 
}
7432
 
 
7433
 
#ifdef __linux__
7434
 
static int
7435
 
qemudDomainInterfaceStats (virDomainPtr dom,
7436
 
                           const char *path,
7437
 
                           struct _virDomainInterfaceStats *stats)
7438
 
{
7439
 
    struct qemud_driver *driver = dom->conn->privateData;
7440
 
    virDomainObjPtr vm;
7441
 
    int i;
7442
 
    int ret = -1;
7443
 
 
7444
 
    qemuDriverLock(driver);
7445
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7446
 
    qemuDriverUnlock(driver);
7447
 
 
7448
 
    if (!vm) {
7449
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
7450
 
        virUUIDFormat(dom->uuid, uuidstr);
7451
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
7452
 
                        _("no domain with matching uuid '%s'"), uuidstr);
7453
 
        goto cleanup;
7454
 
    }
7455
 
 
7456
 
    if (!virDomainObjIsActive(vm)) {
7457
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7458
 
                        "%s", _("domain is not running"));
7459
 
        goto cleanup;
7460
 
    }
7461
 
 
7462
 
    /* Check the path is one of the domain's network interfaces. */
7463
 
    for (i = 0 ; i < vm->def->nnets ; i++) {
7464
 
        if (vm->def->nets[i]->ifname &&
7465
 
            STREQ (vm->def->nets[i]->ifname, path)) {
7466
 
            ret = 0;
7467
 
            break;
7468
 
        }
7469
 
    }
7470
 
 
7471
 
    if (ret == 0)
7472
 
        ret = linuxDomainInterfaceStats(path, stats);
7473
 
    else
7474
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7475
 
                        _("invalid path, '%s' is not a known interface"), path);
7476
 
 
7477
 
cleanup:
7478
 
    if (vm)
7479
 
        virDomainObjUnlock(vm);
7480
 
    return ret;
7481
 
}
7482
 
#else
7483
 
static int
7484
 
qemudDomainInterfaceStats (virDomainPtr dom,
7485
 
                           const char *path ATTRIBUTE_UNUSED,
7486
 
                           struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED)
7487
 
    qemuReportError(VIR_ERR_NO_SUPPORT,
7488
 
                    "%s", __FUNCTION__);
7489
 
    return -1;
7490
 
}
7491
 
#endif
7492
 
 
7493
 
static int
7494
 
qemudDomainMemoryStats (virDomainPtr dom,
7495
 
                        struct _virDomainMemoryStat *stats,
7496
 
                        unsigned int nr_stats)
7497
 
{
7498
 
    struct qemud_driver *driver = dom->conn->privateData;
7499
 
    virDomainObjPtr vm;
7500
 
    unsigned int ret = -1;
7501
 
 
7502
 
    qemuDriverLock(driver);
7503
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7504
 
    qemuDriverUnlock(driver);
7505
 
 
7506
 
    if (!vm) {
7507
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
7508
 
        virUUIDFormat(dom->uuid, uuidstr);
7509
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
7510
 
                        _("no domain with matching uuid '%s'"), uuidstr);
7511
 
        goto cleanup;
7512
 
    }
7513
 
 
7514
 
    if (qemuDomainObjBeginJob(vm) < 0)
7515
 
        goto cleanup;
7516
 
 
7517
 
    if (virDomainObjIsActive(vm)) {
7518
 
        qemuDomainObjPrivatePtr priv = vm->privateData;
7519
 
        qemuDomainObjEnterMonitor(vm);
7520
 
        ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
7521
 
        qemuDomainObjExitMonitor(vm);
7522
 
    } else {
7523
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7524
 
                        "%s", _("domain is not running"));
7525
 
    }
7526
 
 
7527
 
    if (qemuDomainObjEndJob(vm) == 0)
7528
 
        vm = NULL;
7529
 
 
7530
 
cleanup:
7531
 
    if (vm)
7532
 
        virDomainObjUnlock(vm);
7533
 
    return ret;
7534
 
}
7535
 
 
7536
 
static int
7537
 
qemudDomainBlockPeek (virDomainPtr dom,
7538
 
                      const char *path,
7539
 
                      unsigned long long offset, size_t size,
7540
 
                      void *buffer,
7541
 
                      unsigned int flags ATTRIBUTE_UNUSED)
7542
 
{
7543
 
    struct qemud_driver *driver = dom->conn->privateData;
7544
 
    virDomainObjPtr vm;
7545
 
    int fd = -1, ret = -1, i;
7546
 
 
7547
 
    qemuDriverLock(driver);
7548
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7549
 
    qemuDriverUnlock(driver);
7550
 
 
7551
 
    if (!vm) {
7552
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
7553
 
        virUUIDFormat(dom->uuid, uuidstr);
7554
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
7555
 
                        _("no domain with matching uuid '%s'"), uuidstr);
7556
 
        goto cleanup;
7557
 
    }
7558
 
 
7559
 
    if (!path || path[0] == '\0') {
7560
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7561
 
                        "%s", _("NULL or empty path"));
7562
 
        goto cleanup;
7563
 
    }
7564
 
 
7565
 
    /* Check the path belongs to this domain. */
7566
 
    for (i = 0 ; i < vm->def->ndisks ; i++) {
7567
 
        if (vm->def->disks[i]->src != NULL &&
7568
 
            STREQ (vm->def->disks[i]->src, path)) {
7569
 
            ret = 0;
7570
 
            break;
7571
 
        }
7572
 
    }
7573
 
 
7574
 
    if (ret == 0) {
7575
 
        ret = -1;
7576
 
        /* The path is correct, now try to open it and get its size. */
7577
 
        fd = open (path, O_RDONLY);
7578
 
        if (fd == -1) {
7579
 
            virReportSystemError(errno,
7580
 
                                 _("%s: failed to open"), path);
7581
 
            goto cleanup;
7582
 
        }
7583
 
 
7584
 
        /* Seek and read. */
7585
 
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
7586
 
         * be 64 bits on all platforms.
7587
 
         */
7588
 
        if (lseek (fd, offset, SEEK_SET) == (off_t) -1 ||
7589
 
            saferead (fd, buffer, size) == (ssize_t) -1) {
7590
 
            virReportSystemError(errno,
7591
 
                                 _("%s: failed to seek or read"), path);
7592
 
            goto cleanup;
7593
 
        }
7594
 
 
7595
 
        ret = 0;
7596
 
    } else {
7597
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7598
 
                        "%s", _("invalid path"));
7599
 
    }
7600
 
 
7601
 
cleanup:
7602
 
    VIR_FORCE_CLOSE(fd);
7603
 
    if (vm)
7604
 
        virDomainObjUnlock(vm);
7605
 
    return ret;
7606
 
}
7607
 
 
7608
 
static int
7609
 
qemudDomainMemoryPeek (virDomainPtr dom,
7610
 
                       unsigned long long offset, size_t size,
7611
 
                       void *buffer,
7612
 
                       unsigned int flags)
7613
 
{
7614
 
    struct qemud_driver *driver = dom->conn->privateData;
7615
 
    virDomainObjPtr vm;
7616
 
    char *tmp = NULL;
7617
 
    int fd = -1, ret = -1;
7618
 
 
7619
 
    qemuDriverLock(driver);
7620
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7621
 
    qemuDriverUnlock(driver);
7622
 
 
7623
 
    if (!vm) {
7624
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
7625
 
        virUUIDFormat(dom->uuid, uuidstr);
7626
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
7627
 
                        _("no domain with matching uuid '%s'"), uuidstr);
7628
 
        goto cleanup;
7629
 
    }
7630
 
 
7631
 
    if (flags != VIR_MEMORY_VIRTUAL && flags != VIR_MEMORY_PHYSICAL) {
7632
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7633
 
                        "%s", _("flags parameter must be VIR_MEMORY_VIRTUAL or VIR_MEMORY_PHYSICAL"));
7634
 
        goto cleanup;
7635
 
    }
7636
 
 
7637
 
    if (qemuDomainObjBeginJob(vm) < 0)
7638
 
        goto cleanup;
7639
 
 
7640
 
    if (!virDomainObjIsActive(vm)) {
7641
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7642
 
                        "%s", _("domain is not running"));
7643
 
        goto endjob;
7644
 
    }
7645
 
 
7646
 
    if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
7647
 
        virReportOOMError();
7648
 
        goto endjob;
7649
 
    }
7650
 
 
7651
 
    /* Create a temporary filename. */
7652
 
    if ((fd = mkstemp (tmp)) == -1) {
7653
 
        virReportSystemError(errno,
7654
 
                             _("mkstemp(\"%s\") failed"), tmp);
7655
 
        goto endjob;
7656
 
    }
7657
 
 
7658
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
7659
 
    qemuDomainObjEnterMonitor(vm);
7660
 
    if (flags == VIR_MEMORY_VIRTUAL) {
7661
 
        if (qemuMonitorSaveVirtualMemory(priv->mon, offset, size, tmp) < 0) {
7662
 
            qemuDomainObjExitMonitor(vm);
7663
 
            goto endjob;
7664
 
        }
7665
 
    } else {
7666
 
        if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
7667
 
            qemuDomainObjExitMonitor(vm);
7668
 
            goto endjob;
7669
 
        }
7670
 
    }
7671
 
    qemuDomainObjExitMonitor(vm);
7672
 
 
7673
 
    /* Read the memory file into buffer. */
7674
 
    if (saferead (fd, buffer, size) == (ssize_t) -1) {
7675
 
        virReportSystemError(errno,
7676
 
                             _("failed to read temporary file "
7677
 
                               "created with template %s"), tmp);
7678
 
        goto endjob;
7679
 
    }
7680
 
 
7681
 
    ret = 0;
7682
 
 
7683
 
endjob:
7684
 
    if (qemuDomainObjEndJob(vm) == 0)
7685
 
        vm = NULL;
7686
 
 
7687
 
cleanup:
7688
 
    VIR_FREE(tmp);
7689
 
    VIR_FORCE_CLOSE(fd);
7690
 
    unlink (tmp);
7691
 
    if (vm)
7692
 
        virDomainObjUnlock(vm);
7693
 
    return ret;
7694
 
}
7695
 
 
7696
 
 
7697
 
static int qemuDomainGetBlockInfo(virDomainPtr dom,
7698
 
                                  const char *path,
7699
 
                                  virDomainBlockInfoPtr info,
7700
 
                                  unsigned int flags) {
7701
 
    struct qemud_driver *driver = dom->conn->privateData;
7702
 
    virDomainObjPtr vm;
7703
 
    int ret = -1;
7704
 
    int fd = -1;
7705
 
    off_t end;
7706
 
    virStorageFileMetadata meta;
7707
 
    virDomainDiskDefPtr disk = NULL;
7708
 
    struct stat sb;
7709
 
    int i;
7710
 
    int format;
7711
 
 
7712
 
    virCheckFlags(0, -1);
7713
 
 
7714
 
    qemuDriverLock(driver);
7715
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7716
 
    qemuDriverUnlock(driver);
7717
 
    if (!vm) {
7718
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
7719
 
        virUUIDFormat(dom->uuid, uuidstr);
7720
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
7721
 
                        _("no domain with matching uuid '%s'"), uuidstr);
7722
 
        goto cleanup;
7723
 
    }
7724
 
 
7725
 
    if (!path || path[0] == '\0') {
7726
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7727
 
                        "%s", _("NULL or empty path"));
7728
 
        goto cleanup;
7729
 
    }
7730
 
 
7731
 
    /* Check the path belongs to this domain. */
7732
 
    for (i = 0 ; i < vm->def->ndisks ; i++) {
7733
 
        if (vm->def->disks[i]->src != NULL &&
7734
 
            STREQ (vm->def->disks[i]->src, path)) {
7735
 
            disk = vm->def->disks[i];
7736
 
            break;
7737
 
        }
7738
 
    }
7739
 
 
7740
 
    if (!disk) {
7741
 
        qemuReportError(VIR_ERR_INVALID_ARG,
7742
 
                        _("invalid path %s not assigned to domain"), path);
7743
 
        goto cleanup;
7744
 
    }
7745
 
 
7746
 
    /* The path is correct, now try to open it and get its size. */
7747
 
    fd = open (path, O_RDONLY);
7748
 
    if (fd == -1) {
7749
 
        virReportSystemError(errno,
7750
 
                             _("failed to open path '%s'"), path);
7751
 
        goto cleanup;
7752
 
    }
7753
 
 
7754
 
    /* Probe for magic formats */
7755
 
    if (disk->driverType) {
7756
 
        if ((format = virStorageFileFormatTypeFromString(disk->driverType)) < 0) {
7757
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
7758
 
                            _("unknown disk format %s for %s"),
7759
 
                            disk->driverType, disk->src);
7760
 
            goto cleanup;
7761
 
        }
7762
 
    } else {
7763
 
        if (driver->allowDiskFormatProbing) {
7764
 
            if ((format = virStorageFileProbeFormat(disk->src)) < 0)
7765
 
                goto cleanup;
7766
 
        } else {
7767
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR,
7768
 
                            _("no disk format for %s and probing is disabled"),
7769
 
                            disk->src);
7770
 
            goto cleanup;
7771
 
        }
7772
 
    }
7773
 
 
7774
 
    if (virStorageFileGetMetadataFromFD(path, fd,
7775
 
                                        format,
7776
 
                                        &meta) < 0)
7777
 
        goto cleanup;
7778
 
 
7779
 
    /* Get info for normal formats */
7780
 
    if (fstat(fd, &sb) < 0) {
7781
 
        virReportSystemError(errno,
7782
 
                             _("cannot stat file '%s'"), path);
7783
 
        goto cleanup;
7784
 
    }
7785
 
 
7786
 
    if (S_ISREG(sb.st_mode)) {
7787
 
#ifndef WIN32
7788
 
        info->physical = (unsigned long long)sb.st_blocks *
7789
 
            (unsigned long long)DEV_BSIZE;
7790
 
#else
7791
 
        info->physical = sb.st_size;
7792
 
#endif
7793
 
        /* Regular files may be sparse, so logical size (capacity) is not same
7794
 
         * as actual physical above
7795
 
         */
7796
 
        info->capacity = sb.st_size;
7797
 
    } else {
7798
 
        /* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
7799
 
         * be 64 bits on all platforms.
7800
 
         */
7801
 
        end = lseek (fd, 0, SEEK_END);
7802
 
        if (end == (off_t)-1) {
7803
 
            virReportSystemError(errno,
7804
 
                                 _("failed to seek to end of %s"), path);
7805
 
            goto cleanup;
7806
 
        }
7807
 
        info->physical = end;
7808
 
        info->capacity = end;
7809
 
    }
7810
 
 
7811
 
    /* If the file we probed has a capacity set, then override
7812
 
     * what we calculated from file/block extents */
7813
 
    if (meta.capacity)
7814
 
        info->capacity = meta.capacity;
7815
 
 
7816
 
    /* Set default value .. */
7817
 
    info->allocation = info->physical;
7818
 
 
7819
 
    /* ..but if guest is running & not using raw
7820
 
       disk format and on a block device, then query
7821
 
       highest allocated extent from QEMU */
7822
 
    if (disk->type == VIR_DOMAIN_DISK_TYPE_BLOCK &&
7823
 
        format != VIR_STORAGE_FILE_RAW &&
7824
 
        S_ISBLK(sb.st_mode)) {
7825
 
        qemuDomainObjPrivatePtr priv = vm->privateData;
7826
 
        if (qemuDomainObjBeginJob(vm) < 0)
7827
 
            goto cleanup;
7828
 
        if (!virDomainObjIsActive(vm))
7829
 
            ret = 0;
7830
 
        else {
7831
 
            qemuDomainObjEnterMonitor(vm);
7832
 
            ret = qemuMonitorGetBlockExtent(priv->mon,
7833
 
                                            disk->info.alias,
7834
 
                                            &info->allocation);
7835
 
            qemuDomainObjExitMonitor(vm);
7836
 
        }
7837
 
 
7838
 
        if (qemuDomainObjEndJob(vm) == 0)
7839
 
            vm = NULL;
7840
 
    } else {
7841
 
        ret = 0;
7842
 
    }
7843
 
 
7844
 
cleanup:
7845
 
    VIR_FORCE_CLOSE(fd);
7846
 
    if (vm)
7847
 
        virDomainObjUnlock(vm);
7848
 
    return ret;
7849
 
}
7850
 
 
7851
 
 
7852
 
static int
7853
 
qemuDomainEventRegister(virConnectPtr conn,
7854
 
                        virConnectDomainEventCallback callback,
7855
 
                        void *opaque,
7856
 
                        virFreeCallback freecb)
7857
 
{
7858
 
    struct qemud_driver *driver = conn->privateData;
7859
 
    int ret;
7860
 
 
7861
 
    qemuDriverLock(driver);
7862
 
    ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
7863
 
                                        callback, opaque, freecb);
7864
 
    qemuDriverUnlock(driver);
7865
 
 
7866
 
    return ret;
7867
 
}
7868
 
 
7869
 
 
7870
 
static int
7871
 
qemuDomainEventDeregister(virConnectPtr conn,
7872
 
                          virConnectDomainEventCallback callback)
7873
 
{
7874
 
    struct qemud_driver *driver = conn->privateData;
7875
 
    int ret;
7876
 
 
7877
 
    qemuDriverLock(driver);
7878
 
    if (driver->domainEventDispatching)
7879
 
        ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
7880
 
                                                   callback);
7881
 
    else
7882
 
        ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
7883
 
                                               callback);
7884
 
    qemuDriverUnlock(driver);
7885
 
 
7886
 
    return ret;
7887
 
}
7888
 
 
7889
 
 
7890
 
static int
7891
 
qemuDomainEventRegisterAny(virConnectPtr conn,
7892
 
                           virDomainPtr dom,
7893
 
                           int eventID,
7894
 
                           virConnectDomainEventGenericCallback callback,
7895
 
                           void *opaque,
7896
 
                           virFreeCallback freecb)
7897
 
{
7898
 
    struct qemud_driver *driver = conn->privateData;
7899
 
    int ret;
7900
 
 
7901
 
    qemuDriverLock(driver);
7902
 
    ret = virDomainEventCallbackListAddID(conn,
7903
 
                                          driver->domainEventCallbacks,
7904
 
                                          dom, eventID,
7905
 
                                          callback, opaque, freecb);
7906
 
    qemuDriverUnlock(driver);
7907
 
 
7908
 
    return ret;
7909
 
}
7910
 
 
7911
 
 
7912
 
static int
7913
 
qemuDomainEventDeregisterAny(virConnectPtr conn,
7914
 
                             int callbackID)
7915
 
{
7916
 
    struct qemud_driver *driver = conn->privateData;
7917
 
    int ret;
7918
 
 
7919
 
    qemuDriverLock(driver);
7920
 
    if (driver->domainEventDispatching)
7921
 
        ret = virDomainEventCallbackListMarkDeleteID(conn, driver->domainEventCallbacks,
7922
 
                                                     callbackID);
7923
 
    else
7924
 
        ret = virDomainEventCallbackListRemoveID(conn, driver->domainEventCallbacks,
7925
 
                                                 callbackID);
7926
 
    qemuDriverUnlock(driver);
7927
 
 
7928
 
    return ret;
7929
 
}
7930
 
 
7931
 
 
7932
 
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
7933
 
                                        virDomainEventPtr event,
7934
 
                                        virConnectDomainEventGenericCallback cb,
7935
 
                                        void *cbopaque,
7936
 
                                        void *opaque)
7937
 
{
7938
 
    struct qemud_driver *driver = opaque;
7939
 
 
7940
 
    /* Drop the lock whle dispatching, for sake of re-entrancy */
7941
 
    qemuDriverUnlock(driver);
7942
 
    virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
7943
 
    qemuDriverLock(driver);
7944
 
}
7945
 
 
7946
 
static void qemuDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
7947
 
{
7948
 
    struct qemud_driver *driver = opaque;
7949
 
    virDomainEventQueue tempQueue;
7950
 
 
7951
 
    qemuDriverLock(driver);
7952
 
 
7953
 
    driver->domainEventDispatching = 1;
7954
 
 
7955
 
    /* Copy the queue, so we're reentrant safe */
7956
 
    tempQueue.count = driver->domainEventQueue->count;
7957
 
    tempQueue.events = driver->domainEventQueue->events;
7958
 
    driver->domainEventQueue->count = 0;
7959
 
    driver->domainEventQueue->events = NULL;
7960
 
 
7961
 
    virEventUpdateTimeout(driver->domainEventTimer, -1);
7962
 
    virDomainEventQueueDispatch(&tempQueue,
7963
 
                                driver->domainEventCallbacks,
7964
 
                                qemuDomainEventDispatchFunc,
7965
 
                                driver);
7966
 
 
7967
 
    /* Purge any deleted callbacks */
7968
 
    virDomainEventCallbackListPurgeMarked(driver->domainEventCallbacks);
7969
 
 
7970
 
    driver->domainEventDispatching = 0;
7971
 
    qemuDriverUnlock(driver);
7972
 
}
7973
 
 
7974
 
 
7975
 
/* driver must be locked before calling */
7976
 
static void qemuDomainEventQueue(struct qemud_driver *driver,
7977
 
                                 virDomainEventPtr event)
7978
 
{
7979
 
    if (virDomainEventQueuePush(driver->domainEventQueue,
7980
 
                                event) < 0)
7981
 
        virDomainEventFree(event);
7982
 
    if (qemu_driver->domainEventQueue->count == 1)
7983
 
        virEventUpdateTimeout(driver->domainEventTimer, 0);
7984
 
}
7985
 
 
7986
 
/* Migration support. */
7987
 
 
7988
 
static bool ATTRIBUTE_NONNULL(1)
7989
 
qemuDomainIsMigratable(virDomainDefPtr def)
7990
 
{
7991
 
    if (def->nhostdevs > 0) {
7992
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
7993
 
            "%s", _("Domain with assigned host devices cannot be migrated"));
7994
 
        return false;
7995
 
    }
7996
 
 
7997
 
    return true;
7998
 
}
7999
 
 
8000
 
/* Prepare is the first step, and it runs on the destination host.
8001
 
 *
8002
 
 * This version starts an empty VM listening on a localhost TCP port, and
8003
 
 * sets up the corresponding virStream to handle the incoming data.
8004
 
 */
8005
 
static int
8006
 
qemudDomainMigratePrepareTunnel(virConnectPtr dconn,
8007
 
                                virStreamPtr st,
8008
 
                                unsigned long flags,
8009
 
                                const char *dname,
8010
 
                                unsigned long resource ATTRIBUTE_UNUSED,
8011
 
                                const char *dom_xml)
8012
 
{
8013
 
    struct qemud_driver *driver = dconn->privateData;
8014
 
    virDomainDefPtr def = NULL;
8015
 
    virDomainObjPtr vm = NULL;
8016
 
    char *migrateFrom;
8017
 
    virDomainEventPtr event = NULL;
8018
 
    int ret = -1;
8019
 
    int internalret;
8020
 
    char *unixfile = NULL;
8021
 
    unsigned long long qemuCmdFlags;
8022
 
    qemuDomainObjPrivatePtr priv = NULL;
8023
 
    struct timeval now;
8024
 
 
8025
 
    if (gettimeofday(&now, NULL) < 0) {
8026
 
        virReportSystemError(errno, "%s",
8027
 
                             _("cannot get time of day"));
8028
 
        return -1;
8029
 
    }
8030
 
 
8031
 
    qemuDriverLock(driver);
8032
 
    if (!dom_xml) {
8033
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8034
 
                        "%s", _("no domain XML passed"));
8035
 
        goto cleanup;
8036
 
    }
8037
 
    if (!(flags & VIR_MIGRATE_TUNNELLED)) {
8038
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8039
 
                         "%s", _("PrepareTunnel called but no TUNNELLED flag set"));
8040
 
        goto cleanup;
8041
 
    }
8042
 
    if (st == NULL) {
8043
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8044
 
                        "%s", _("tunnelled migration requested but NULL stream passed"));
8045
 
        goto cleanup;
8046
 
    }
8047
 
 
8048
 
    /* Parse the domain XML. */
8049
 
    if (!(def = virDomainDefParseString(driver->caps, dom_xml,
8050
 
                                        VIR_DOMAIN_XML_INACTIVE))) {
8051
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8052
 
                        "%s", _("failed to parse XML, libvirt version may be "
8053
 
                                "different between source and destination host"));
8054
 
        goto cleanup;
8055
 
    }
8056
 
 
8057
 
    if (!qemuDomainIsMigratable(def))
8058
 
        goto cleanup;
8059
 
 
8060
 
    /* Target domain name, maybe renamed. */
8061
 
    if (dname) {
8062
 
        VIR_FREE(def->name);
8063
 
        def->name = strdup(dname);
8064
 
        if (def->name == NULL)
8065
 
            goto cleanup;
8066
 
    }
8067
 
 
8068
 
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
8069
 
        goto cleanup;
8070
 
 
8071
 
    if (!(vm = virDomainAssignDef(driver->caps,
8072
 
                                  &driver->domains,
8073
 
                                  def, true))) {
8074
 
        /* virDomainAssignDef already set the error */
8075
 
        goto cleanup;
8076
 
    }
8077
 
    def = NULL;
8078
 
    priv = vm->privateData;
8079
 
 
8080
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
8081
 
        goto cleanup;
8082
 
    priv->jobActive = QEMU_JOB_MIGRATION_OUT;
8083
 
 
8084
 
    /* Domain starts inactive, even if the domain XML had an id field. */
8085
 
    vm->def->id = -1;
8086
 
 
8087
 
    if (virAsprintf(&unixfile, "%s/qemu.tunnelmigrate.dest.%s",
8088
 
                    driver->libDir, vm->def->name) < 0) {
8089
 
        virReportOOMError();
8090
 
        goto endjob;
8091
 
    }
8092
 
    unlink(unixfile);
8093
 
 
8094
 
    /* check that this qemu version supports the interactive exec */
8095
 
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
8096
 
                                   NULL, &qemuCmdFlags) < 0) {
8097
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8098
 
                        _("Cannot determine QEMU argv syntax %s"),
8099
 
                        vm->def->emulator);
8100
 
        goto endjob;
8101
 
    }
8102
 
    if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_UNIX)
8103
 
        internalret = virAsprintf(&migrateFrom, "unix:%s", unixfile);
8104
 
    else if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_EXEC)
8105
 
        internalret = virAsprintf(&migrateFrom, "exec:nc -U -l %s", unixfile);
8106
 
    else {
8107
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8108
 
                        "%s", _("Destination qemu is too old to support tunnelled migration"));
8109
 
        goto endjob;
8110
 
    }
8111
 
    if (internalret < 0) {
8112
 
        virReportOOMError();
8113
 
        goto endjob;
8114
 
    }
8115
 
    /* Start the QEMU daemon, with the same command-line arguments plus
8116
 
     * -incoming unix:/path/to/file or exec:nc -U /path/to/file
8117
 
     */
8118
 
    internalret = qemudStartVMDaemon(dconn, driver, vm, migrateFrom, true,
8119
 
                                     -1, NULL, VIR_VM_OP_MIGRATE_IN_START);
8120
 
    VIR_FREE(migrateFrom);
8121
 
    if (internalret < 0) {
8122
 
        qemuDomainStartAudit(vm, "migrated", false);
8123
 
        /* Note that we don't set an error here because qemudStartVMDaemon
8124
 
         * should have already done that.
8125
 
         */
8126
 
        if (!vm->persistent) {
8127
 
            virDomainRemoveInactive(&driver->domains, vm);
8128
 
            vm = NULL;
8129
 
        }
8130
 
        goto endjob;
8131
 
    }
8132
 
 
8133
 
    if (virFDStreamConnectUNIX(st,
8134
 
                               unixfile,
8135
 
                               false) < 0) {
8136
 
        qemuDomainStartAudit(vm, "migrated", false);
8137
 
        qemudShutdownVMDaemon(driver, vm, 0);
8138
 
        if (!vm->persistent) {
8139
 
            if (qemuDomainObjEndJob(vm) > 0)
8140
 
                virDomainRemoveInactive(&driver->domains, vm);
8141
 
            vm = NULL;
8142
 
        }
8143
 
        virReportSystemError(errno,
8144
 
                             _("cannot open unix socket '%s' for tunnelled migration"),
8145
 
                             unixfile);
8146
 
        goto endjob;
8147
 
    }
8148
 
 
8149
 
    qemuDomainStartAudit(vm, "migrated", true);
8150
 
 
8151
 
    event = virDomainEventNewFromObj(vm,
8152
 
                                     VIR_DOMAIN_EVENT_STARTED,
8153
 
                                     VIR_DOMAIN_EVENT_STARTED_MIGRATED);
8154
 
    ret = 0;
8155
 
 
8156
 
endjob:
8157
 
    if (vm &&
8158
 
        qemuDomainObjEndJob(vm) == 0)
8159
 
        vm = NULL;
8160
 
 
8161
 
    /* We set a fake job active which is held across
8162
 
     * API calls until the finish() call. This prevents
8163
 
     * any other APIs being invoked while incoming
8164
 
     * migration is taking place
8165
 
     */
8166
 
    if (vm &&
8167
 
        virDomainObjIsActive(vm)) {
8168
 
        priv->jobActive = QEMU_JOB_MIGRATION_IN;
8169
 
        priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
8170
 
        priv->jobStart = timeval_to_ms(now);
8171
 
    }
8172
 
 
8173
 
cleanup:
8174
 
    virDomainDefFree(def);
8175
 
    if (unixfile)
8176
 
        unlink(unixfile);
8177
 
    VIR_FREE(unixfile);
8178
 
    if (vm)
8179
 
        virDomainObjUnlock(vm);
8180
 
    if (event)
8181
 
        qemuDomainEventQueue(driver, event);
8182
 
    qemuDriverUnlock(driver);
8183
 
    return ret;
8184
 
}
8185
 
 
8186
 
/* Prepare is the first step, and it runs on the destination host.
8187
 
 *
8188
 
 * This starts an empty VM listening on a TCP port.
8189
 
 */
8190
 
static int ATTRIBUTE_NONNULL (5)
8191
 
qemudDomainMigratePrepare2 (virConnectPtr dconn,
8192
 
                            char **cookie ATTRIBUTE_UNUSED,
8193
 
                            int *cookielen ATTRIBUTE_UNUSED,
8194
 
                            const char *uri_in,
8195
 
                            char **uri_out,
8196
 
                            unsigned long flags,
8197
 
                            const char *dname,
8198
 
                            unsigned long resource ATTRIBUTE_UNUSED,
8199
 
                            const char *dom_xml)
8200
 
{
8201
 
    static int port = 0;
8202
 
    struct qemud_driver *driver = dconn->privateData;
8203
 
    virDomainDefPtr def = NULL;
8204
 
    virDomainObjPtr vm = NULL;
8205
 
    int this_port;
8206
 
    char *hostname = NULL;
8207
 
    char migrateFrom [64];
8208
 
    const char *p;
8209
 
    virDomainEventPtr event = NULL;
8210
 
    int ret = -1;
8211
 
    int internalret;
8212
 
    qemuDomainObjPrivatePtr priv = NULL;
8213
 
    struct timeval now;
8214
 
 
8215
 
    if (gettimeofday(&now, NULL) < 0) {
8216
 
        virReportSystemError(errno, "%s",
8217
 
                             _("cannot get time of day"));
8218
 
        return -1;
8219
 
    }
8220
 
 
8221
 
    virCheckFlags(VIR_MIGRATE_LIVE |
8222
 
                  VIR_MIGRATE_PEER2PEER |
8223
 
                  VIR_MIGRATE_TUNNELLED |
8224
 
                  VIR_MIGRATE_PERSIST_DEST |
8225
 
                  VIR_MIGRATE_UNDEFINE_SOURCE |
8226
 
                  VIR_MIGRATE_PAUSED |
8227
 
                  VIR_MIGRATE_NON_SHARED_DISK |
8228
 
                  VIR_MIGRATE_NON_SHARED_INC, -1);
8229
 
 
8230
 
    *uri_out = NULL;
8231
 
 
8232
 
    qemuDriverLock(driver);
8233
 
    if (flags & VIR_MIGRATE_TUNNELLED) {
8234
 
        /* this is a logical error; we never should have gotten here with
8235
 
         * VIR_MIGRATE_TUNNELLED set
8236
 
         */
8237
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8238
 
                        "%s", _("Tunnelled migration requested but invalid RPC method called"));
8239
 
        goto cleanup;
8240
 
    }
8241
 
 
8242
 
    if (!dom_xml) {
8243
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8244
 
                        "%s", _("no domain XML passed"));
8245
 
        goto cleanup;
8246
 
    }
8247
 
 
8248
 
    /* The URI passed in may be NULL or a string "tcp://somehostname:port".
8249
 
     *
8250
 
     * If the URI passed in is NULL then we allocate a port number
8251
 
     * from our pool of port numbers and return a URI of
8252
 
     * "tcp://ourhostname:port".
8253
 
     *
8254
 
     * If the URI passed in is not NULL then we try to parse out the
8255
 
     * port number and use that (note that the hostname is assumed
8256
 
     * to be a correct hostname which refers to the target machine).
8257
 
     */
8258
 
    if (uri_in == NULL) {
8259
 
        this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
8260
 
        if (port == QEMUD_MIGRATION_NUM_PORTS) port = 0;
8261
 
 
8262
 
        /* Get hostname */
8263
 
        if ((hostname = virGetHostname(NULL)) == NULL)
8264
 
            goto cleanup;
8265
 
 
8266
 
        if (STRPREFIX(hostname, "localhost")) {
8267
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8268
 
                            _("hostname on destination resolved to localhost, but migration requires an FQDN"));
8269
 
            goto cleanup;
8270
 
        }
8271
 
 
8272
 
        /* XXX this really should have been a properly well-formed
8273
 
         * URI, but we can't add in tcp:// now without breaking
8274
 
         * compatability with old targets. We at least make the
8275
 
         * new targets accept both syntaxes though.
8276
 
         */
8277
 
        /* Caller frees */
8278
 
        internalret = virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port);
8279
 
        if (internalret < 0) {
8280
 
            virReportOOMError();
8281
 
            goto cleanup;
8282
 
        }
8283
 
    } else {
8284
 
        /* Check the URI starts with "tcp:".  We will escape the
8285
 
         * URI when passing it to the qemu monitor, so bad
8286
 
         * characters in hostname part don't matter.
8287
 
         */
8288
 
        if (!STRPREFIX (uri_in, "tcp:")) {
8289
 
            qemuReportError (VIR_ERR_INVALID_ARG,
8290
 
                             "%s", _("only tcp URIs are supported for KVM/QEMU migrations"));
8291
 
            goto cleanup;
8292
 
        }
8293
 
 
8294
 
        /* Get the port number. */
8295
 
        p = strrchr (uri_in, ':');
8296
 
        if (p == strchr(uri_in, ':')) {
8297
 
            /* Generate a port */
8298
 
            this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
8299
 
            if (port == QEMUD_MIGRATION_NUM_PORTS)
8300
 
                port = 0;
8301
 
 
8302
 
            /* Caller frees */
8303
 
            if (virAsprintf(uri_out, "%s:%d", uri_in, this_port) < 0) {
8304
 
                virReportOOMError();
8305
 
                goto cleanup;
8306
 
            }
8307
 
 
8308
 
        } else {
8309
 
            p++; /* definitely has a ':' in it, see above */
8310
 
            this_port = virParseNumber (&p);
8311
 
            if (this_port == -1 || p-uri_in != strlen (uri_in)) {
8312
 
                qemuReportError(VIR_ERR_INVALID_ARG,
8313
 
                                "%s", _("URI ended with incorrect ':port'"));
8314
 
                goto cleanup;
8315
 
            }
8316
 
        }
8317
 
    }
8318
 
 
8319
 
    if (*uri_out)
8320
 
        VIR_DEBUG("Generated uri_out=%s", *uri_out);
8321
 
 
8322
 
    /* Parse the domain XML. */
8323
 
    if (!(def = virDomainDefParseString(driver->caps, dom_xml,
8324
 
                                        VIR_DOMAIN_XML_INACTIVE))) {
8325
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8326
 
                        "%s", _("failed to parse XML"));
8327
 
        goto cleanup;
8328
 
    }
8329
 
 
8330
 
    if (!qemuDomainIsMigratable(def))
8331
 
        goto cleanup;
8332
 
 
8333
 
    /* Target domain name, maybe renamed. */
8334
 
    if (dname) {
8335
 
        VIR_FREE(def->name);
8336
 
        def->name = strdup(dname);
8337
 
        if (def->name == NULL)
8338
 
            goto cleanup;
8339
 
    }
8340
 
 
8341
 
    if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
8342
 
        goto cleanup;
8343
 
 
8344
 
    if (!(vm = virDomainAssignDef(driver->caps,
8345
 
                                  &driver->domains,
8346
 
                                  def, true))) {
8347
 
        /* virDomainAssignDef already set the error */
8348
 
        goto cleanup;
8349
 
    }
8350
 
    def = NULL;
8351
 
    priv = vm->privateData;
8352
 
 
8353
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
8354
 
        goto cleanup;
8355
 
    priv->jobActive = QEMU_JOB_MIGRATION_OUT;
8356
 
 
8357
 
    /* Domain starts inactive, even if the domain XML had an id field. */
8358
 
    vm->def->id = -1;
8359
 
 
8360
 
    /* Start the QEMU daemon, with the same command-line arguments plus
8361
 
     * -incoming tcp:0.0.0.0:port
8362
 
     */
8363
 
    snprintf (migrateFrom, sizeof (migrateFrom), "tcp:0.0.0.0:%d", this_port);
8364
 
    if (qemudStartVMDaemon (dconn, driver, vm, migrateFrom, true,
8365
 
                            -1, NULL, VIR_VM_OP_MIGRATE_IN_START) < 0) {
8366
 
        qemuDomainStartAudit(vm, "migrated", false);
8367
 
        /* Note that we don't set an error here because qemudStartVMDaemon
8368
 
         * should have already done that.
8369
 
         */
8370
 
        if (!vm->persistent) {
8371
 
            if (qemuDomainObjEndJob(vm) > 0)
8372
 
                virDomainRemoveInactive(&driver->domains, vm);
8373
 
            vm = NULL;
8374
 
        }
8375
 
        goto endjob;
8376
 
    }
8377
 
 
8378
 
    qemuDomainStartAudit(vm, "migrated", true);
8379
 
    event = virDomainEventNewFromObj(vm,
8380
 
                                     VIR_DOMAIN_EVENT_STARTED,
8381
 
                                     VIR_DOMAIN_EVENT_STARTED_MIGRATED);
8382
 
    ret = 0;
8383
 
 
8384
 
endjob:
8385
 
    if (vm &&
8386
 
        qemuDomainObjEndJob(vm) == 0)
8387
 
        vm = NULL;
8388
 
 
8389
 
    /* We set a fake job active which is held across
8390
 
     * API calls until the finish() call. This prevents
8391
 
     * any other APIs being invoked while incoming
8392
 
     * migration is taking place
8393
 
     */
8394
 
    if (vm &&
8395
 
        virDomainObjIsActive(vm)) {
8396
 
        priv->jobActive = QEMU_JOB_MIGRATION_IN;
8397
 
        priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
8398
 
        priv->jobStart = timeval_to_ms(now);
8399
 
    }
8400
 
 
8401
 
cleanup:
8402
 
    VIR_FREE(hostname);
8403
 
    virDomainDefFree(def);
8404
 
    if (ret != 0)
8405
 
        VIR_FREE(*uri_out);
8406
 
    if (vm)
8407
 
        virDomainObjUnlock(vm);
8408
 
    if (event)
8409
 
        qemuDomainEventQueue(driver, event);
8410
 
    qemuDriverUnlock(driver);
8411
 
    return ret;
8412
 
 
8413
 
}
8414
 
 
8415
 
 
8416
 
/* Perform migration using QEMU's native TCP migrate support,
8417
 
 * not encrypted obviously
8418
 
 */
8419
 
static int doNativeMigrate(struct qemud_driver *driver,
8420
 
                           virDomainObjPtr vm,
8421
 
                           const char *uri,
8422
 
                           unsigned int flags,
8423
 
                           const char *dname ATTRIBUTE_UNUSED,
8424
 
                           unsigned long resource)
8425
 
{
8426
 
    int ret = -1;
8427
 
    xmlURIPtr uribits = NULL;
8428
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
8429
 
    unsigned int background_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
8430
 
 
8431
 
    /* Issue the migrate command. */
8432
 
    if (STRPREFIX(uri, "tcp:") && !STRPREFIX(uri, "tcp://")) {
8433
 
        /* HACK: source host generates bogus URIs, so fix them up */
8434
 
        char *tmpuri;
8435
 
        if (virAsprintf(&tmpuri, "tcp://%s", uri + strlen("tcp:")) < 0) {
8436
 
            virReportOOMError();
8437
 
            goto cleanup;
8438
 
        }
8439
 
        uribits = xmlParseURI(tmpuri);
8440
 
        VIR_FREE(tmpuri);
8441
 
    } else {
8442
 
        uribits = xmlParseURI(uri);
8443
 
    }
8444
 
    if (!uribits) {
8445
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8446
 
                        _("cannot parse URI %s"), uri);
8447
 
        goto cleanup;
8448
 
    }
8449
 
 
8450
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8451
 
    if (resource > 0 &&
8452
 
        qemuMonitorSetMigrationSpeed(priv->mon, resource) < 0) {
8453
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8454
 
        goto cleanup;
8455
 
    }
8456
 
 
8457
 
    if (flags & VIR_MIGRATE_NON_SHARED_DISK)
8458
 
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_DISK;
8459
 
 
8460
 
    if (flags & VIR_MIGRATE_NON_SHARED_INC)
8461
 
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_INC;
8462
 
 
8463
 
    if (qemuMonitorMigrateToHost(priv->mon, background_flags, uribits->server,
8464
 
                                 uribits->port) < 0) {
8465
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8466
 
        goto cleanup;
8467
 
    }
8468
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8469
 
 
8470
 
    if (qemuDomainWaitForMigrationComplete(driver, vm) < 0)
8471
 
        goto cleanup;
8472
 
 
8473
 
    ret = 0;
8474
 
 
8475
 
cleanup:
8476
 
    xmlFreeURI(uribits);
8477
 
    return ret;
8478
 
}
8479
 
 
8480
 
 
8481
 
#define TUNNEL_SEND_BUF_SIZE 65536
8482
 
 
8483
 
static int doTunnelSendAll(virStreamPtr st,
8484
 
                           int sock)
8485
 
{
8486
 
    char *buffer;
8487
 
    int nbytes = TUNNEL_SEND_BUF_SIZE;
8488
 
 
8489
 
    if (VIR_ALLOC_N(buffer, TUNNEL_SEND_BUF_SIZE) < 0) {
8490
 
        virReportOOMError();
8491
 
        virStreamAbort(st);
8492
 
        return -1;
8493
 
    }
8494
 
 
8495
 
    /* XXX should honour the 'resource' parameter here */
8496
 
    for (;;) {
8497
 
        nbytes = saferead(sock, buffer, nbytes);
8498
 
        if (nbytes < 0) {
8499
 
            virReportSystemError(errno, "%s",
8500
 
                                 _("tunnelled migration failed to read from qemu"));
8501
 
            virStreamAbort(st);
8502
 
            VIR_FREE(buffer);
8503
 
            return -1;
8504
 
        }
8505
 
        else if (nbytes == 0)
8506
 
            /* EOF; get out of here */
8507
 
            break;
8508
 
 
8509
 
        if (virStreamSend(st, buffer, nbytes) < 0) {
8510
 
            qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
8511
 
                            _("Failed to write migration data to remote libvirtd"));
8512
 
            VIR_FREE(buffer);
8513
 
            return -1;
8514
 
        }
8515
 
    }
8516
 
 
8517
 
    VIR_FREE(buffer);
8518
 
 
8519
 
    if (virStreamFinish(st) < 0)
8520
 
        /* virStreamFinish set the error for us */
8521
 
        return -1;
8522
 
 
8523
 
    return 0;
8524
 
}
8525
 
 
8526
 
static int doTunnelMigrate(virDomainPtr dom,
8527
 
                           struct qemud_driver *driver,
8528
 
                           virConnectPtr dconn,
8529
 
                           virDomainObjPtr vm,
8530
 
                           const char *dom_xml,
8531
 
                           const char *uri,
8532
 
                           unsigned long flags,
8533
 
                           const char *dname,
8534
 
                           unsigned long resource)
8535
 
{
8536
 
    qemuDomainObjPrivatePtr priv = vm->privateData;
8537
 
    int client_sock = -1;
8538
 
    int qemu_sock = -1;
8539
 
    struct sockaddr_un sa_qemu, sa_client;
8540
 
    socklen_t addrlen;
8541
 
    virDomainPtr ddomain = NULL;
8542
 
    int retval = -1;
8543
 
    virStreamPtr st = NULL;
8544
 
    char *unixfile = NULL;
8545
 
    int internalret;
8546
 
    unsigned long long qemuCmdFlags;
8547
 
    int status;
8548
 
    unsigned long long transferred, remaining, total;
8549
 
    unsigned int background_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
8550
 
 
8551
 
    /*
8552
 
     * The order of operations is important here to avoid touching
8553
 
     * the source VM until we are very sure we can successfully
8554
 
     * start the migration operation.
8555
 
     *
8556
 
     *   1. setup local support infrastructure (eg sockets)
8557
 
     *   2. setup destination fully
8558
 
     *   3. start migration on source
8559
 
     */
8560
 
 
8561
 
 
8562
 
    /* Stage 1. setup local support infrastructure */
8563
 
 
8564
 
    if (virAsprintf(&unixfile, "%s/qemu.tunnelmigrate.src.%s",
8565
 
                    driver->libDir, vm->def->name) < 0) {
8566
 
        virReportOOMError();
8567
 
        goto cleanup;
8568
 
    }
8569
 
 
8570
 
    qemu_sock = socket(AF_UNIX, SOCK_STREAM, 0);
8571
 
    if (qemu_sock < 0) {
8572
 
        virReportSystemError(errno, "%s",
8573
 
                             _("cannot open tunnelled migration socket"));
8574
 
        goto cleanup;
8575
 
    }
8576
 
    memset(&sa_qemu, 0, sizeof(sa_qemu));
8577
 
    sa_qemu.sun_family = AF_UNIX;
8578
 
    if (virStrcpy(sa_qemu.sun_path, unixfile,
8579
 
                  sizeof(sa_qemu.sun_path)) == NULL) {
8580
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8581
 
                        _("Unix socket '%s' too big for destination"),
8582
 
                        unixfile);
8583
 
        goto cleanup;
8584
 
    }
8585
 
    unlink(unixfile);
8586
 
    if (bind(qemu_sock, (struct sockaddr *)&sa_qemu, sizeof(sa_qemu)) < 0) {
8587
 
        virReportSystemError(errno,
8588
 
                             _("Cannot bind to unix socket '%s' for tunnelled migration"),
8589
 
                             unixfile);
8590
 
        goto cleanup;
8591
 
    }
8592
 
    if (listen(qemu_sock, 1) < 0) {
8593
 
        virReportSystemError(errno,
8594
 
                             _("Cannot listen on unix socket '%s' for tunnelled migration"),
8595
 
                             unixfile);
8596
 
        goto cleanup;
8597
 
    }
8598
 
 
8599
 
    if (chown(unixfile, qemu_driver->user, qemu_driver->group) < 0) {
8600
 
        virReportSystemError(errno,
8601
 
                             _("Cannot change unix socket '%s' owner"),
8602
 
                             unixfile);
8603
 
        goto cleanup;
8604
 
    }
8605
 
 
8606
 
    /* check that this qemu version supports the unix migration */
8607
 
    if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
8608
 
                                   NULL, &qemuCmdFlags) < 0) {
8609
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
8610
 
                        _("Cannot extract Qemu version from '%s'"),
8611
 
                        vm->def->emulator);
8612
 
        goto cleanup;
8613
 
    }
8614
 
 
8615
 
    if (!(qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_UNIX) &&
8616
 
        !(qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_EXEC)) {
8617
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8618
 
                        "%s", _("Source qemu is too old to support tunnelled migration"));
8619
 
        goto cleanup;
8620
 
    }
8621
 
 
8622
 
 
8623
 
    /* Stage 2. setup destination fully
8624
 
     *
8625
 
     * Once stage 2 has completed successfully, we *must* call finish
8626
 
     * to cleanup the target whether we succeed or fail
8627
 
     */
8628
 
    st = virStreamNew(dconn, 0);
8629
 
    if (st == NULL)
8630
 
        /* virStreamNew only fails on OOM, and it reports the error itself */
8631
 
        goto cleanup;
8632
 
 
8633
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8634
 
    internalret = dconn->driver->domainMigratePrepareTunnel(dconn, st,
8635
 
                                                            flags, dname,
8636
 
                                                            resource, dom_xml);
8637
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8638
 
 
8639
 
    if (internalret < 0)
8640
 
        /* domainMigratePrepareTunnel sets the error for us */
8641
 
        goto cleanup;
8642
 
 
8643
 
    /* the domain may have shutdown or crashed while we had the locks dropped
8644
 
     * in qemuDomainObjEnterRemoteWithDriver, so check again
8645
 
     */
8646
 
    if (!virDomainObjIsActive(vm)) {
8647
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8648
 
                        _("guest unexpectedly quit"));
8649
 
        goto cleanup;
8650
 
    }
8651
 
 
8652
 
    /*   3. start migration on source */
8653
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8654
 
    if (flags & VIR_MIGRATE_NON_SHARED_DISK)
8655
 
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_DISK;
8656
 
    if (flags & VIR_MIGRATE_NON_SHARED_INC)
8657
 
        background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_INC;
8658
 
    if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_UNIX){
8659
 
        internalret = qemuMonitorMigrateToUnix(priv->mon, background_flags,
8660
 
                                               unixfile);
8661
 
    }
8662
 
    else if (qemuCmdFlags & QEMUD_CMD_FLAG_MIGRATE_QEMU_EXEC) {
8663
 
        const char *args[] = { "nc", "-U", unixfile, NULL };
8664
 
        internalret = qemuMonitorMigrateToCommand(priv->mon, QEMU_MONITOR_MIGRATE_BACKGROUND, args);
8665
 
    } else {
8666
 
        internalret = -1;
8667
 
    }
8668
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8669
 
    if (internalret < 0) {
8670
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8671
 
                        "%s", _("tunnelled migration monitor command failed"));
8672
 
        goto finish;
8673
 
    }
8674
 
 
8675
 
    if (!virDomainObjIsActive(vm)) {
8676
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8677
 
                        _("guest unexpectedly quit"));
8678
 
        goto cleanup;
8679
 
    }
8680
 
 
8681
 
    /* From this point onwards we *must* call cancel to abort the
8682
 
     * migration on source if anything goes wrong */
8683
 
 
8684
 
    /* it is also possible that the migrate didn't fail initially, but
8685
 
     * rather failed later on.  Check the output of "info migrate"
8686
 
     */
8687
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
8688
 
    if (qemuMonitorGetMigrationStatus(priv->mon,
8689
 
                                      &status,
8690
 
                                      &transferred,
8691
 
                                      &remaining,
8692
 
                                      &total) < 0) {
8693
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8694
 
        goto cancel;
8695
 
    }
8696
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
8697
 
 
8698
 
    if (status == QEMU_MONITOR_MIGRATION_STATUS_ERROR) {
8699
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8700
 
                        "%s",_("migrate failed"));
8701
 
        goto cancel;
8702
 
    }
8703
 
 
8704
 
    addrlen = sizeof(sa_client);
8705
 
    while ((client_sock = accept(qemu_sock, (struct sockaddr *)&sa_client, &addrlen)) < 0) {
8706
 
        if (errno == EAGAIN || errno == EINTR)
8707
 
            continue;
8708
 
        virReportSystemError(errno, "%s",
8709
 
                             _("tunnelled migration failed to accept from qemu"));
8710
 
        goto cancel;
8711
 
    }
8712
 
 
8713
 
    retval = doTunnelSendAll(st, client_sock);
8714
 
 
8715
 
cancel:
8716
 
    if (retval != 0 && virDomainObjIsActive(vm)) {
8717
 
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
8718
 
        qemuMonitorMigrateCancel(priv->mon);
8719
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
8720
 
    }
8721
 
 
8722
 
finish:
8723
 
    dname = dname ? dname : dom->name;
8724
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8725
 
    ddomain = dconn->driver->domainMigrateFinish2
8726
 
        (dconn, dname, NULL, 0, uri, flags, retval);
8727
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8728
 
 
8729
 
cleanup:
8730
 
    VIR_FORCE_CLOSE(client_sock);
8731
 
    VIR_FORCE_CLOSE(qemu_sock);
8732
 
 
8733
 
    if (ddomain)
8734
 
        virUnrefDomain(ddomain);
8735
 
 
8736
 
    if (unixfile) {
8737
 
        unlink(unixfile);
8738
 
        VIR_FREE(unixfile);
8739
 
    }
8740
 
 
8741
 
    if (st)
8742
 
        /* don't call virStreamFree(), because that resets any pending errors */
8743
 
        virUnrefStream(st);
8744
 
    return retval;
8745
 
}
8746
 
 
8747
 
 
8748
 
/* This is essentially a simplified re-impl of
8749
 
 * virDomainMigrateVersion2 from libvirt.c, but running in source
8750
 
 * libvirtd context, instead of client app context */
8751
 
static int doNonTunnelMigrate(virDomainPtr dom,
8752
 
                              struct qemud_driver *driver,
8753
 
                              virConnectPtr dconn,
8754
 
                              virDomainObjPtr vm,
8755
 
                              const char *dom_xml,
8756
 
                              const char *uri ATTRIBUTE_UNUSED,
8757
 
                              unsigned long flags,
8758
 
                              const char *dname,
8759
 
                              unsigned long resource)
8760
 
{
8761
 
    virDomainPtr ddomain = NULL;
8762
 
    int retval = -1;
8763
 
    char *uri_out = NULL;
8764
 
    int rc;
8765
 
 
8766
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8767
 
    /* NB we don't pass 'uri' into this, since that's the libvirtd
8768
 
     * URI in this context - so we let dest pick it */
8769
 
    rc = dconn->driver->domainMigratePrepare2(dconn,
8770
 
                                              NULL, /* cookie */
8771
 
                                              0, /* cookielen */
8772
 
                                              NULL, /* uri */
8773
 
                                              &uri_out,
8774
 
                                              flags, dname,
8775
 
                                              resource, dom_xml);
8776
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8777
 
    if (rc < 0)
8778
 
        /* domainMigratePrepare2 sets the error for us */
8779
 
        goto cleanup;
8780
 
 
8781
 
    /* the domain may have shutdown or crashed while we had the locks dropped
8782
 
     * in qemuDomainObjEnterRemoteWithDriver, so check again
8783
 
     */
8784
 
    if (!virDomainObjIsActive(vm)) {
8785
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8786
 
                        _("guest unexpectedly quit"));
8787
 
        goto cleanup;
8788
 
    }
8789
 
 
8790
 
    if (uri_out == NULL) {
8791
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8792
 
                        _("domainMigratePrepare2 did not set uri"));
8793
 
        goto cleanup;
8794
 
    }
8795
 
 
8796
 
    if (doNativeMigrate(driver, vm, uri_out, flags, dname, resource) < 0)
8797
 
        goto finish;
8798
 
 
8799
 
    retval = 0;
8800
 
 
8801
 
finish:
8802
 
    dname = dname ? dname : dom->name;
8803
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8804
 
    ddomain = dconn->driver->domainMigrateFinish2
8805
 
        (dconn, dname, NULL, 0, uri_out, flags, retval);
8806
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8807
 
 
8808
 
    if (ddomain)
8809
 
        virUnrefDomain(ddomain);
8810
 
 
8811
 
cleanup:
8812
 
    return retval;
8813
 
}
8814
 
 
8815
 
 
8816
 
static int doPeer2PeerMigrate(virDomainPtr dom,
8817
 
                              struct qemud_driver *driver,
8818
 
                              virDomainObjPtr vm,
8819
 
                              const char *uri,
8820
 
                              unsigned long flags,
8821
 
                              const char *dname,
8822
 
                              unsigned long resource)
8823
 
{
8824
 
    int ret = -1;
8825
 
    virConnectPtr dconn = NULL;
8826
 
    char *dom_xml;
8827
 
    bool p2p;
8828
 
 
8829
 
    /* the order of operations is important here; we make sure the
8830
 
     * destination side is completely setup before we touch the source
8831
 
     */
8832
 
 
8833
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8834
 
    dconn = virConnectOpen(uri);
8835
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8836
 
    if (dconn == NULL) {
8837
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8838
 
                        _("Failed to connect to remote libvirt URI %s"), uri);
8839
 
        return -1;
8840
 
    }
8841
 
 
8842
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8843
 
    p2p = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
8844
 
                                   VIR_DRV_FEATURE_MIGRATION_P2P);
8845
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8846
 
    if (!p2p) {
8847
 
        qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
8848
 
                        _("Destination libvirt does not support peer-to-peer migration protocol"));
8849
 
        goto cleanup;
8850
 
    }
8851
 
 
8852
 
    /* domain may have been stopped while we were talking to remote daemon */
8853
 
    if (!virDomainObjIsActive(vm)) {
8854
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8855
 
                        _("guest unexpectedly quit"));
8856
 
        goto cleanup;
8857
 
    }
8858
 
 
8859
 
    dom_xml = qemudVMDumpXML(driver, vm,
8860
 
                             VIR_DOMAIN_XML_SECURE |
8861
 
                             VIR_DOMAIN_XML_UPDATE_CPU);
8862
 
    if (!dom_xml) {
8863
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
8864
 
                        "%s", _("failed to get domain xml"));
8865
 
        goto cleanup;
8866
 
    }
8867
 
 
8868
 
    if (flags & VIR_MIGRATE_TUNNELLED)
8869
 
        ret = doTunnelMigrate(dom, driver, dconn, vm, dom_xml, uri, flags, dname, resource);
8870
 
    else
8871
 
        ret = doNonTunnelMigrate(dom, driver, dconn, vm, dom_xml, uri, flags, dname, resource);
8872
 
 
8873
 
cleanup:
8874
 
    VIR_FREE(dom_xml);
8875
 
    /* don't call virConnectClose(), because that resets any pending errors */
8876
 
    qemuDomainObjEnterRemoteWithDriver(driver, vm);
8877
 
    virUnrefConnect(dconn);
8878
 
    qemuDomainObjExitRemoteWithDriver(driver, vm);
8879
 
 
8880
 
    return ret;
8881
 
}
8882
 
 
8883
 
 
8884
 
/* Perform is the second step, and it runs on the source host. */
8885
 
static int
8886
 
qemudDomainMigratePerform (virDomainPtr dom,
8887
 
                           const char *cookie ATTRIBUTE_UNUSED,
8888
 
                           int cookielen ATTRIBUTE_UNUSED,
8889
 
                           const char *uri,
8890
 
                           unsigned long flags,
8891
 
                           const char *dname,
8892
 
                           unsigned long resource)
8893
 
{
8894
 
    struct qemud_driver *driver = dom->conn->privateData;
8895
 
    virDomainObjPtr vm;
8896
 
    virDomainEventPtr event = NULL;
8897
 
    int ret = -1;
8898
 
    int resume = 0;
8899
 
    qemuDomainObjPrivatePtr priv;
8900
 
 
8901
 
    virCheckFlags(VIR_MIGRATE_LIVE |
8902
 
                  VIR_MIGRATE_PEER2PEER |
8903
 
                  VIR_MIGRATE_TUNNELLED |
8904
 
                  VIR_MIGRATE_PERSIST_DEST |
8905
 
                  VIR_MIGRATE_UNDEFINE_SOURCE |
8906
 
                  VIR_MIGRATE_PAUSED |
8907
 
                  VIR_MIGRATE_NON_SHARED_DISK |
8908
 
                  VIR_MIGRATE_NON_SHARED_INC, -1);
8909
 
 
8910
 
    qemuDriverLock(driver);
8911
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
8912
 
    if (!vm) {
8913
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
8914
 
        virUUIDFormat(dom->uuid, uuidstr);
8915
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
8916
 
                        _("no domain with matching uuid '%s'"), uuidstr);
8917
 
        goto cleanup;
8918
 
    }
8919
 
    priv = vm->privateData;
8920
 
 
8921
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
8922
 
        goto cleanup;
8923
 
    priv->jobActive = QEMU_JOB_MIGRATION_OUT;
8924
 
 
8925
 
    if (!virDomainObjIsActive(vm)) {
8926
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
8927
 
                        "%s", _("domain is not running"));
8928
 
        goto endjob;
8929
 
    }
8930
 
 
8931
 
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
8932
 
    priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
8933
 
 
8934
 
    resume = vm->state == VIR_DOMAIN_RUNNING;
8935
 
    if (!(flags & VIR_MIGRATE_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
8936
 
        if (qemuDomainMigrateOffline(driver, vm) < 0)
8937
 
            goto endjob;
8938
 
    }
8939
 
 
8940
 
    if ((flags & (VIR_MIGRATE_TUNNELLED | VIR_MIGRATE_PEER2PEER))) {
8941
 
        if (doPeer2PeerMigrate(dom, driver, vm, uri, flags, dname, resource) < 0)
8942
 
            /* doPeer2PeerMigrate already set the error, so just get out */
8943
 
            goto endjob;
8944
 
    } else {
8945
 
        if (doNativeMigrate(driver, vm, uri, flags, dname, resource) < 0)
8946
 
            goto endjob;
8947
 
    }
8948
 
 
8949
 
    /* Clean up the source domain. */
8950
 
    qemudShutdownVMDaemon(driver, vm, 1);
8951
 
    qemuDomainStopAudit(vm, "migrated");
8952
 
    resume = 0;
8953
 
 
8954
 
    event = virDomainEventNewFromObj(vm,
8955
 
                                     VIR_DOMAIN_EVENT_STOPPED,
8956
 
                                     VIR_DOMAIN_EVENT_STOPPED_MIGRATED);
8957
 
    if (!vm->persistent || (flags & VIR_MIGRATE_UNDEFINE_SOURCE)) {
8958
 
        virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm);
8959
 
        if (qemuDomainObjEndJob(vm) > 0)
8960
 
            virDomainRemoveInactive(&driver->domains, vm);
8961
 
        vm = NULL;
8962
 
    }
8963
 
    ret = 0;
8964
 
 
8965
 
endjob:
8966
 
    if (resume && vm->state == VIR_DOMAIN_PAUSED) {
8967
 
        /* we got here through some sort of failure; start the domain again */
8968
 
        if (doStartCPUs(driver, vm, dom->conn) < 0) {
8969
 
            /* Hm, we already know we are in error here.  We don't want to
8970
 
             * overwrite the previous error, though, so we just throw something
8971
 
             * to the logs and hope for the best
8972
 
             */
8973
 
            VIR_ERROR(_("Failed to resume guest %s after failure"),
8974
 
                      vm->def->name);
8975
 
        }
8976
 
 
8977
 
        event = virDomainEventNewFromObj(vm,
8978
 
                                         VIR_DOMAIN_EVENT_RESUMED,
8979
 
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
8980
 
    }
8981
 
    if (vm &&
8982
 
        qemuDomainObjEndJob(vm) == 0)
8983
 
        vm = NULL;
8984
 
 
8985
 
cleanup:
8986
 
    if (vm)
8987
 
        virDomainObjUnlock(vm);
8988
 
    if (event)
8989
 
        qemuDomainEventQueue(driver, event);
8990
 
    qemuDriverUnlock(driver);
8991
 
    return ret;
8992
 
}
8993
 
 
8994
 
#if WITH_MACVTAP
8995
 
static void
8996
 
qemudVPAssociatePortProfiles(virDomainDefPtr def) {
8997
 
    int i;
8998
 
    int last_good_net = -1;
8999
 
    virDomainNetDefPtr net;
9000
 
 
9001
 
    for (i = 0; i < def->nnets; i++) {
9002
 
        net = def->nets[i];
9003
 
        if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
9004
 
            if (vpAssociatePortProfileId(net->ifname,
9005
 
                                         net->mac,
9006
 
                                         net->data.direct.linkdev,
9007
 
                                         &net->data.direct.virtPortProfile,
9008
 
                                         def->uuid,
9009
 
                                         VIR_VM_OP_MIGRATE_IN_FINISH) != 0)
9010
 
                goto err_exit;
9011
 
        }
9012
 
        last_good_net = i;
9013
 
    }
9014
 
 
9015
 
    return;
9016
 
 
9017
 
err_exit:
9018
 
    for (i = 0; i < last_good_net; i++) {
9019
 
        net = def->nets[i];
9020
 
        if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
9021
 
            vpDisassociatePortProfileId(net->ifname,
9022
 
                                        net->mac,
9023
 
                                        net->data.direct.linkdev,
9024
 
                                        &net->data.direct.virtPortProfile,
9025
 
                                        VIR_VM_OP_MIGRATE_IN_FINISH);
9026
 
        }
9027
 
    }
9028
 
}
9029
 
#else /* !WITH_MACVTAP */
9030
 
static void
9031
 
qemudVPAssociatePortProfiles(virDomainDefPtr def ATTRIBUTE_UNUSED) { }
9032
 
#endif /* WITH_MACVTAP */
9033
 
 
9034
 
/* Finish is the third and final step, and it runs on the destination host. */
9035
 
static virDomainPtr
9036
 
qemudDomainMigrateFinish2 (virConnectPtr dconn,
9037
 
                           const char *dname,
9038
 
                           const char *cookie ATTRIBUTE_UNUSED,
9039
 
                           int cookielen ATTRIBUTE_UNUSED,
9040
 
                           const char *uri ATTRIBUTE_UNUSED,
9041
 
                           unsigned long flags,
9042
 
                           int retcode)
9043
 
{
9044
 
    struct qemud_driver *driver = dconn->privateData;
9045
 
    virDomainObjPtr vm;
9046
 
    virDomainPtr dom = NULL;
9047
 
    virDomainEventPtr event = NULL;
9048
 
    virErrorPtr orig_err;
9049
 
    int newVM = 1;
9050
 
    qemuDomainObjPrivatePtr priv = NULL;
9051
 
 
9052
 
    virCheckFlags(VIR_MIGRATE_LIVE |
9053
 
                  VIR_MIGRATE_PEER2PEER |
9054
 
                  VIR_MIGRATE_TUNNELLED |
9055
 
                  VIR_MIGRATE_PERSIST_DEST |
9056
 
                  VIR_MIGRATE_UNDEFINE_SOURCE |
9057
 
                  VIR_MIGRATE_PAUSED |
9058
 
                  VIR_MIGRATE_NON_SHARED_DISK |
9059
 
                  VIR_MIGRATE_NON_SHARED_INC, NULL);
9060
 
 
9061
 
    /* Migration failed. Save the current error so nothing squashes it */
9062
 
    orig_err = virSaveLastError();
9063
 
 
9064
 
    qemuDriverLock(driver);
9065
 
    vm = virDomainFindByName(&driver->domains, dname);
9066
 
    if (!vm) {
9067
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9068
 
                        _("no domain with matching name '%s'"), dname);
9069
 
        goto cleanup;
9070
 
    }
9071
 
 
9072
 
    priv = vm->privateData;
9073
 
    if (priv->jobActive != QEMU_JOB_MIGRATION_IN) {
9074
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9075
 
                        _("domain '%s' is not processing incoming migration"), dname);
9076
 
        goto cleanup;
9077
 
    }
9078
 
    priv->jobActive = QEMU_JOB_NONE;
9079
 
    memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
9080
 
 
9081
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
9082
 
        goto cleanup;
9083
 
 
9084
 
    /* Did the migration go as planned?  If yes, return the domain
9085
 
     * object, but if no, clean up the empty qemu process.
9086
 
     */
9087
 
    if (retcode == 0) {
9088
 
        if (!virDomainObjIsActive(vm)) {
9089
 
            qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
9090
 
                            _("guest unexpectedly quit"));
9091
 
            goto cleanup;
9092
 
        }
9093
 
 
9094
 
        qemudVPAssociatePortProfiles(vm->def);
9095
 
 
9096
 
        if (flags & VIR_MIGRATE_PERSIST_DEST) {
9097
 
            if (vm->persistent)
9098
 
                newVM = 0;
9099
 
            vm->persistent = 1;
9100
 
 
9101
 
            if (virDomainSaveConfig(driver->configDir, vm->def) < 0) {
9102
 
                /* Hmpf.  Migration was successful, but making it persistent
9103
 
                 * was not.  If we report successful, then when this domain
9104
 
                 * shuts down, management tools are in for a surprise.  On the
9105
 
                 * other hand, if we report failure, then the management tools
9106
 
                 * might try to restart the domain on the source side, even
9107
 
                 * though the domain is actually running on the destination.
9108
 
                 * Return a NULL dom pointer, and hope that this is a rare
9109
 
                 * situation and management tools are smart.
9110
 
                 */
9111
 
                vm = NULL;
9112
 
                goto endjob;
9113
 
            }
9114
 
 
9115
 
            event = virDomainEventNewFromObj(vm,
9116
 
                                             VIR_DOMAIN_EVENT_DEFINED,
9117
 
                                             newVM ?
9118
 
                                             VIR_DOMAIN_EVENT_DEFINED_ADDED :
9119
 
                                             VIR_DOMAIN_EVENT_DEFINED_UPDATED);
9120
 
            if (event)
9121
 
                qemuDomainEventQueue(driver, event);
9122
 
            event = NULL;
9123
 
 
9124
 
        }
9125
 
        dom = virGetDomain (dconn, vm->def->name, vm->def->uuid);
9126
 
 
9127
 
        if (!(flags & VIR_MIGRATE_PAUSED)) {
9128
 
            /* run 'cont' on the destination, which allows migration on qemu
9129
 
             * >= 0.10.6 to work properly.  This isn't strictly necessary on
9130
 
             * older qemu's, but it also doesn't hurt anything there
9131
 
             */
9132
 
            if (doStartCPUs(driver, vm, dconn) < 0) {
9133
 
                if (virGetLastError() == NULL)
9134
 
                    qemuReportError(VIR_ERR_INTERNAL_ERROR,
9135
 
                                    "%s", _("resume operation failed"));
9136
 
                goto endjob;
9137
 
            }
9138
 
        }
9139
 
 
9140
 
        event = virDomainEventNewFromObj(vm,
9141
 
                                         VIR_DOMAIN_EVENT_RESUMED,
9142
 
                                         VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
9143
 
        if (vm->state == VIR_DOMAIN_PAUSED) {
9144
 
            qemuDomainEventQueue(driver, event);
9145
 
            event = virDomainEventNewFromObj(vm,
9146
 
                                             VIR_DOMAIN_EVENT_SUSPENDED,
9147
 
                                             VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
9148
 
        }
9149
 
        if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
9150
 
            VIR_WARN("Failed to save status on vm %s", vm->def->name);
9151
 
            goto endjob;
9152
 
        }
9153
 
    } else {
9154
 
        qemudShutdownVMDaemon(driver, vm, 1);
9155
 
        qemuDomainStopAudit(vm, "failed");
9156
 
        event = virDomainEventNewFromObj(vm,
9157
 
                                         VIR_DOMAIN_EVENT_STOPPED,
9158
 
                                         VIR_DOMAIN_EVENT_STOPPED_FAILED);
9159
 
        if (!vm->persistent) {
9160
 
            if (qemuDomainObjEndJob(vm) > 0)
9161
 
                virDomainRemoveInactive(&driver->domains, vm);
9162
 
            vm = NULL;
9163
 
        }
9164
 
    }
9165
 
 
9166
 
endjob:
9167
 
    if (vm &&
9168
 
        qemuDomainObjEndJob(vm) == 0)
9169
 
        vm = NULL;
9170
 
 
9171
 
cleanup:
9172
 
    if (orig_err) {
9173
 
        virSetError(orig_err);
9174
 
        virFreeError(orig_err);
9175
 
    }
9176
 
    if (vm)
9177
 
        virDomainObjUnlock(vm);
9178
 
    if (event)
9179
 
        qemuDomainEventQueue(driver, event);
9180
 
    qemuDriverUnlock(driver);
9181
 
    return dom;
9182
 
}
9183
 
 
9184
 
static int
9185
 
qemudNodeDeviceGetPciInfo (virNodeDevicePtr dev,
9186
 
                           unsigned *domain,
9187
 
                           unsigned *bus,
9188
 
                           unsigned *slot,
9189
 
                           unsigned *function)
9190
 
{
9191
 
    virNodeDeviceDefPtr def = NULL;
9192
 
    virNodeDevCapsDefPtr cap;
9193
 
    char *xml = NULL;
9194
 
    int ret = -1;
9195
 
 
9196
 
    xml = virNodeDeviceGetXMLDesc(dev, 0);
9197
 
    if (!xml)
9198
 
        goto out;
9199
 
 
9200
 
    def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
9201
 
    if (!def)
9202
 
        goto out;
9203
 
 
9204
 
    cap = def->caps;
9205
 
    while (cap) {
9206
 
        if (cap->type == VIR_NODE_DEV_CAP_PCI_DEV) {
9207
 
            *domain   = cap->data.pci_dev.domain;
9208
 
            *bus      = cap->data.pci_dev.bus;
9209
 
            *slot     = cap->data.pci_dev.slot;
9210
 
            *function = cap->data.pci_dev.function;
9211
 
            break;
9212
 
        }
9213
 
 
9214
 
        cap = cap->next;
9215
 
    }
9216
 
 
9217
 
    if (!cap) {
9218
 
        qemuReportError(VIR_ERR_INVALID_ARG,
9219
 
                        _("device %s is not a PCI device"), dev->name);
9220
 
        goto out;
9221
 
    }
9222
 
 
9223
 
    ret = 0;
9224
 
out:
9225
 
    virNodeDeviceDefFree(def);
9226
 
    VIR_FREE(xml);
9227
 
    return ret;
9228
 
}
9229
 
 
9230
 
static int
9231
 
qemudNodeDeviceDettach (virNodeDevicePtr dev)
9232
 
{
9233
 
    struct qemud_driver *driver = dev->conn->privateData;
9234
 
    pciDevice *pci;
9235
 
    unsigned domain, bus, slot, function;
9236
 
    int ret = -1;
9237
 
 
9238
 
    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
9239
 
        return -1;
9240
 
 
9241
 
    pci = pciGetDevice(domain, bus, slot, function);
9242
 
    if (!pci)
9243
 
        return -1;
9244
 
 
9245
 
    qemuDriverLock(driver);
9246
 
    if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
9247
 
        goto out;
9248
 
 
9249
 
    ret = 0;
9250
 
out:
9251
 
    qemuDriverUnlock(driver);
9252
 
    pciFreeDevice(pci);
9253
 
    return ret;
9254
 
}
9255
 
 
9256
 
static int
9257
 
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
9258
 
{
9259
 
    struct qemud_driver *driver = dev->conn->privateData;
9260
 
    pciDevice *pci;
9261
 
    unsigned domain, bus, slot, function;
9262
 
    int ret = -1;
9263
 
 
9264
 
    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
9265
 
        return -1;
9266
 
 
9267
 
    pci = pciGetDevice(domain, bus, slot, function);
9268
 
    if (!pci)
9269
 
        return -1;
9270
 
 
9271
 
    qemuDriverLock(driver);
9272
 
    if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
9273
 
        goto out;
9274
 
 
9275
 
    ret = 0;
9276
 
out:
9277
 
    qemuDriverUnlock(driver);
9278
 
    pciFreeDevice(pci);
9279
 
    return ret;
9280
 
}
9281
 
 
9282
 
static int
9283
 
qemudNodeDeviceReset (virNodeDevicePtr dev)
9284
 
{
9285
 
    struct qemud_driver *driver = dev->conn->privateData;
9286
 
    pciDevice *pci;
9287
 
    unsigned domain, bus, slot, function;
9288
 
    int ret = -1;
9289
 
 
9290
 
    if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
9291
 
        return -1;
9292
 
 
9293
 
    pci = pciGetDevice(domain, bus, slot, function);
9294
 
    if (!pci)
9295
 
        return -1;
9296
 
 
9297
 
    qemuDriverLock(driver);
9298
 
 
9299
 
    if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
9300
 
        goto out;
9301
 
 
9302
 
    ret = 0;
9303
 
out:
9304
 
    qemuDriverUnlock(driver);
9305
 
    pciFreeDevice(pci);
9306
 
    return ret;
9307
 
}
9308
 
 
9309
 
static int
9310
 
qemuCPUCompare(virConnectPtr conn,
9311
 
               const char *xmlDesc,
9312
 
               unsigned int flags ATTRIBUTE_UNUSED)
9313
 
{
9314
 
    struct qemud_driver *driver = conn->privateData;
9315
 
    int ret = VIR_CPU_COMPARE_ERROR;
9316
 
 
9317
 
    qemuDriverLock(driver);
9318
 
 
9319
 
    if (!driver->caps || !driver->caps->host.cpu) {
9320
 
        qemuReportError(VIR_ERR_NO_SUPPORT,
9321
 
                        "%s", _("cannot get host CPU capabilities"));
9322
 
    }
9323
 
    else
9324
 
        ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
9325
 
 
9326
 
    qemuDriverUnlock(driver);
9327
 
 
9328
 
    return ret;
9329
 
}
9330
 
 
9331
 
 
9332
 
static char *
9333
 
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
9334
 
                const char **xmlCPUs,
9335
 
                unsigned int ncpus,
9336
 
                unsigned int flags ATTRIBUTE_UNUSED)
9337
 
{
9338
 
    char *cpu;
9339
 
 
9340
 
    cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);
9341
 
 
9342
 
    return cpu;
9343
 
}
9344
 
 
9345
 
 
9346
 
static int qemuDomainGetJobInfo(virDomainPtr dom,
9347
 
                                virDomainJobInfoPtr info) {
9348
 
    struct qemud_driver *driver = dom->conn->privateData;
9349
 
    virDomainObjPtr vm;
9350
 
    int ret = -1;
9351
 
    qemuDomainObjPrivatePtr priv;
9352
 
 
9353
 
    qemuDriverLock(driver);
9354
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9355
 
    qemuDriverUnlock(driver);
9356
 
    if (!vm) {
9357
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9358
 
        virUUIDFormat(dom->uuid, uuidstr);
9359
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9360
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9361
 
        goto cleanup;
9362
 
    }
9363
 
 
9364
 
    priv = vm->privateData;
9365
 
 
9366
 
    if (virDomainObjIsActive(vm)) {
9367
 
        if (priv->jobActive) {
9368
 
            struct timeval now;
9369
 
 
9370
 
            memcpy(info, &priv->jobInfo, sizeof(*info));
9371
 
 
9372
 
            /* Refresh elapsed time again just to ensure it
9373
 
             * is fully updated. This is primarily for benefit
9374
 
             * of incoming migration which we don't currently
9375
 
             * monitor actively in the background thread
9376
 
             */
9377
 
            if (gettimeofday(&now, NULL) < 0) {
9378
 
                virReportSystemError(errno, "%s",
9379
 
                                     _("cannot get time of day"));
9380
 
                goto cleanup;
9381
 
            }
9382
 
            info->timeElapsed = timeval_to_ms(now) - priv->jobStart;
9383
 
        } else {
9384
 
            memset(info, 0, sizeof(*info));
9385
 
            info->type = VIR_DOMAIN_JOB_NONE;
9386
 
        }
9387
 
    } else {
9388
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
9389
 
                        "%s", _("domain is not running"));
9390
 
        goto cleanup;
9391
 
    }
9392
 
 
9393
 
    ret = 0;
9394
 
 
9395
 
cleanup:
9396
 
    if (vm)
9397
 
        virDomainObjUnlock(vm);
9398
 
    return ret;
9399
 
}
9400
 
 
9401
 
 
9402
 
static int qemuDomainAbortJob(virDomainPtr dom) {
9403
 
    struct qemud_driver *driver = dom->conn->privateData;
9404
 
    virDomainObjPtr vm;
9405
 
    int ret = -1;
9406
 
    qemuDomainObjPrivatePtr priv;
9407
 
 
9408
 
    qemuDriverLock(driver);
9409
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9410
 
    qemuDriverUnlock(driver);
9411
 
    if (!vm) {
9412
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9413
 
        virUUIDFormat(dom->uuid, uuidstr);
9414
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9415
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9416
 
        goto cleanup;
9417
 
    }
9418
 
 
9419
 
    priv = vm->privateData;
9420
 
 
9421
 
    if (virDomainObjIsActive(vm)) {
9422
 
        if (priv->jobActive) {
9423
 
            VIR_DEBUG("Requesting cancellation of job on vm %s", vm->def->name);
9424
 
            priv->jobSignals |= QEMU_JOB_SIGNAL_CANCEL;
9425
 
        } else {
9426
 
            qemuReportError(VIR_ERR_OPERATION_INVALID,
9427
 
                            "%s", _("no job is active on the domain"));
9428
 
            goto cleanup;
9429
 
        }
9430
 
    } else {
9431
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
9432
 
                        "%s", _("domain is not running"));
9433
 
        goto cleanup;
9434
 
    }
9435
 
 
9436
 
    ret = 0;
9437
 
 
9438
 
cleanup:
9439
 
    if (vm)
9440
 
        virDomainObjUnlock(vm);
9441
 
    return ret;
9442
 
}
9443
 
 
9444
 
 
9445
 
static int
9446
 
qemuDomainMigrateSetMaxDowntime(virDomainPtr dom,
9447
 
                                unsigned long long downtime,
9448
 
                                unsigned int flags)
9449
 
{
9450
 
    struct qemud_driver *driver = dom->conn->privateData;
9451
 
    virDomainObjPtr vm;
9452
 
    qemuDomainObjPrivatePtr priv;
9453
 
    int ret = -1;
9454
 
 
9455
 
    virCheckFlags(0, -1);
9456
 
 
9457
 
    qemuDriverLock(driver);
9458
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9459
 
 
9460
 
    if (!vm) {
9461
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9462
 
        virUUIDFormat(dom->uuid, uuidstr);
9463
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9464
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9465
 
        goto cleanup;
9466
 
    }
9467
 
 
9468
 
    if (!virDomainObjIsActive(vm)) {
9469
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
9470
 
                        "%s", _("domain is not running"));
9471
 
        goto cleanup;
9472
 
    }
9473
 
 
9474
 
    priv = vm->privateData;
9475
 
 
9476
 
    if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
9477
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
9478
 
                        "%s", _("domain is not being migrated"));
9479
 
        goto cleanup;
9480
 
    }
9481
 
 
9482
 
    VIR_DEBUG("Requesting migration downtime change to %llums", downtime);
9483
 
    priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
9484
 
    priv->jobSignalsData.migrateDowntime = downtime;
9485
 
    ret = 0;
9486
 
 
9487
 
cleanup:
9488
 
    if (vm)
9489
 
        virDomainObjUnlock(vm);
9490
 
    qemuDriverUnlock(driver);
9491
 
    return ret;
9492
 
}
9493
 
 
9494
 
static char *qemuFindQemuImgBinary(void)
9495
 
{
9496
 
    char *ret;
9497
 
 
9498
 
    ret = virFindFileInPath("kvm-img");
9499
 
    if (ret == NULL)
9500
 
        ret = virFindFileInPath("qemu-img");
9501
 
    if (ret == NULL)
9502
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
9503
 
                        "%s", _("unable to find kvm-img or qemu-img"));
9504
 
 
9505
 
    return ret;
9506
 
}
9507
 
 
9508
 
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
9509
 
                                           virDomainSnapshotObjPtr snapshot,
9510
 
                                           char *snapshotDir)
9511
 
{
9512
 
    int fd = -1;
9513
 
    char *newxml = NULL;
9514
 
    int ret = -1;
9515
 
    char *snapDir = NULL;
9516
 
    char *snapFile = NULL;
9517
 
    int err;
9518
 
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9519
 
 
9520
 
    virUUIDFormat(vm->def->uuid, uuidstr);
9521
 
    newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
9522
 
    if (newxml == NULL) {
9523
 
        virReportOOMError();
9524
 
        return -1;
9525
 
    }
9526
 
 
9527
 
    if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
9528
 
        virReportOOMError();
9529
 
        goto cleanup;
9530
 
    }
9531
 
    err = virFileMakePath(snapDir);
9532
 
    if (err < 0) {
9533
 
        virReportSystemError(err, _("cannot create snapshot directory '%s'"),
9534
 
                             snapDir);
9535
 
        goto cleanup;
9536
 
    }
9537
 
 
9538
 
    if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
9539
 
        virReportOOMError();
9540
 
        goto cleanup;
9541
 
    }
9542
 
    fd = open(snapFile, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR);
9543
 
    if (fd < 0) {
9544
 
        qemuReportError(VIR_ERR_OPERATION_FAILED,
9545
 
                        _("failed to create snapshot file '%s'"), snapFile);
9546
 
        goto cleanup;
9547
 
    }
9548
 
    if (safewrite(fd, newxml, strlen(newxml)) != strlen(newxml)) {
9549
 
        virReportSystemError(errno, _("Failed to write snapshot data to %s"),
9550
 
                             snapFile);
9551
 
        goto cleanup;
9552
 
    }
9553
 
 
9554
 
    ret = 0;
9555
 
 
9556
 
cleanup:
9557
 
    VIR_FREE(snapFile);
9558
 
    VIR_FREE(snapDir);
9559
 
    VIR_FREE(newxml);
9560
 
    VIR_FORCE_CLOSE(fd);
9561
 
    return ret;
9562
 
}
9563
 
 
9564
 
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
9565
 
                                              char *snapshotDir)
9566
 
{
9567
 
    if (vm->current_snapshot) {
9568
 
        vm->current_snapshot->def->active = 1;
9569
 
 
9570
 
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
9571
 
                                               snapshotDir);
9572
 
    }
9573
 
 
9574
 
    return 0;
9575
 
}
9576
 
 
9577
 
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
9578
 
                                                char *snapshotDir)
9579
 
{
9580
 
    if (vm->current_snapshot) {
9581
 
        vm->current_snapshot->def->active = 0;
9582
 
 
9583
 
        return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
9584
 
                                               snapshotDir);
9585
 
    }
9586
 
 
9587
 
    return 0;
9588
 
}
9589
 
 
9590
 
 
9591
 
static int qemuDomainSnapshotIsAllowed(virDomainObjPtr vm)
9592
 
{
9593
 
    int i;
9594
 
 
9595
 
    /* FIXME: we need to figure out what else here might succeed; in
9596
 
     * particular, if it's a raw device but on LVM, we could probably make
9597
 
     * that succeed as well
9598
 
     */
9599
 
    for (i = 0; i < vm->def->ndisks; i++) {
9600
 
        if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK &&
9601
 
            (!vm->def->disks[i]->driverType ||
9602
 
             STRNEQ(vm->def->disks[i]->driverType, "qcow2"))) {
9603
 
            qemuReportError(VIR_ERR_OPERATION_INVALID,
9604
 
                            _("Disk '%s' does not support snapshotting"),
9605
 
                            vm->def->disks[i]->src);
9606
 
            return 0;
9607
 
        }
9608
 
    }
9609
 
 
9610
 
    return 1;
9611
 
}
9612
 
 
9613
 
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
9614
 
                                                        const char *xmlDesc,
9615
 
                                                        unsigned int flags)
9616
 
{
9617
 
    struct qemud_driver *driver = domain->conn->privateData;
9618
 
    virDomainObjPtr vm = NULL;
9619
 
    virDomainSnapshotObjPtr snap = NULL;
9620
 
    virDomainSnapshotPtr snapshot = NULL;
9621
 
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9622
 
    virDomainSnapshotDefPtr def;
9623
 
    const char *qemuimgarg[] = { NULL, "snapshot", "-c", NULL, NULL, NULL };
9624
 
    int i;
9625
 
 
9626
 
    virCheckFlags(0, NULL);
9627
 
 
9628
 
    qemuDriverLock(driver);
9629
 
    virUUIDFormat(domain->uuid, uuidstr);
9630
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9631
 
    if (!vm) {
9632
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9633
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9634
 
        goto cleanup;
9635
 
    }
9636
 
 
9637
 
    /* in a perfect world, we would allow qemu to tell us this.  The problem
9638
 
     * is that qemu only does this check device-by-device; so if you had a
9639
 
     * domain that booted from a large qcow2 device, but had a secondary raw
9640
 
     * device attached, you wouldn't find out that you can't snapshot your
9641
 
     * guest until *after* it had spent the time to snapshot the boot device.
9642
 
     * This is probably a bug in qemu, but we'll work around it here for now.
9643
 
     */
9644
 
    if (!qemuDomainSnapshotIsAllowed(vm))
9645
 
        goto cleanup;
9646
 
 
9647
 
    if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
9648
 
        goto cleanup;
9649
 
 
9650
 
    if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
9651
 
        goto cleanup;
9652
 
 
9653
 
    /* actually do the snapshot */
9654
 
    if (!virDomainObjIsActive(vm)) {
9655
 
        qemuimgarg[0] = qemuFindQemuImgBinary();
9656
 
        if (qemuimgarg[0] == NULL)
9657
 
            /* qemuFindQemuImgBinary set the error */
9658
 
            goto cleanup;
9659
 
 
9660
 
        qemuimgarg[3] = snap->def->name;
9661
 
 
9662
 
        for (i = 0; i < vm->def->ndisks; i++) {
9663
 
            /* FIXME: we also need to handle LVM here */
9664
 
            /* FIXME: if we fail halfway through this loop, we are in an
9665
 
             * inconsistent state.  I'm not quite sure what to do about that
9666
 
             */
9667
 
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
9668
 
                if (!vm->def->disks[i]->driverType ||
9669
 
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
9670
 
                    qemuReportError(VIR_ERR_OPERATION_INVALID,
9671
 
                                    _("Disk device '%s' does not support snapshotting"),
9672
 
                                    vm->def->disks[i]->info.alias);
9673
 
                    goto cleanup;
9674
 
                }
9675
 
 
9676
 
                qemuimgarg[4] = vm->def->disks[i]->src;
9677
 
 
9678
 
                if (virRun(qemuimgarg, NULL) < 0) {
9679
 
                    virReportSystemError(errno,
9680
 
                                         _("Failed to run '%s' to create snapshot '%s' from disk '%s'"),
9681
 
                                         qemuimgarg[0], snap->def->name,
9682
 
                                         vm->def->disks[i]->src);
9683
 
                    goto cleanup;
9684
 
                }
9685
 
            }
9686
 
        }
9687
 
    }
9688
 
    else {
9689
 
        qemuDomainObjPrivatePtr priv;
9690
 
        int ret;
9691
 
 
9692
 
        if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
9693
 
            goto cleanup;
9694
 
        priv = vm->privateData;
9695
 
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
9696
 
        ret = qemuMonitorCreateSnapshot(priv->mon, def->name);
9697
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
9698
 
        if (qemuDomainObjEndJob(vm) == 0) {
9699
 
            vm = NULL;
9700
 
            goto cleanup;
9701
 
        }
9702
 
        if (ret < 0)
9703
 
            goto cleanup;
9704
 
    }
9705
 
 
9706
 
    snap->def->state = vm->state;
9707
 
 
9708
 
    /* FIXME: if we fail after this point, there's not a whole lot we can
9709
 
     * do; we've successfully taken the snapshot, and we are now running
9710
 
     * on it, so we have to go forward the best we can
9711
 
     */
9712
 
 
9713
 
    if (vm->current_snapshot) {
9714
 
        def->parent = strdup(vm->current_snapshot->def->name);
9715
 
        if (def->parent == NULL) {
9716
 
            virReportOOMError();
9717
 
            goto cleanup;
9718
 
        }
9719
 
    }
9720
 
 
9721
 
    /* Now we set the new current_snapshot for the domain */
9722
 
    vm->current_snapshot = snap;
9723
 
 
9724
 
    if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
9725
 
                                        driver->snapshotDir) < 0)
9726
 
        /* qemuDomainSnapshotWriteMetadata set the error */
9727
 
        goto cleanup;
9728
 
 
9729
 
    snapshot = virGetDomainSnapshot(domain, snap->def->name);
9730
 
 
9731
 
cleanup:
9732
 
    VIR_FREE(qemuimgarg[0]);
9733
 
    if (vm)
9734
 
        virDomainObjUnlock(vm);
9735
 
    qemuDriverUnlock(driver);
9736
 
    return snapshot;
9737
 
}
9738
 
 
9739
 
static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
9740
 
                                       int nameslen,
9741
 
                                       unsigned int flags)
9742
 
{
9743
 
    struct qemud_driver *driver = domain->conn->privateData;
9744
 
    virDomainObjPtr vm = NULL;
9745
 
    int n = -1;
9746
 
 
9747
 
    virCheckFlags(0, -1);
9748
 
 
9749
 
    qemuDriverLock(driver);
9750
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9751
 
    if (!vm) {
9752
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9753
 
        virUUIDFormat(domain->uuid, uuidstr);
9754
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9755
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9756
 
        goto cleanup;
9757
 
    }
9758
 
 
9759
 
    n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen);
9760
 
 
9761
 
cleanup:
9762
 
    if (vm)
9763
 
        virDomainObjUnlock(vm);
9764
 
    qemuDriverUnlock(driver);
9765
 
    return n;
9766
 
}
9767
 
 
9768
 
static int qemuDomainSnapshotNum(virDomainPtr domain,
9769
 
                                 unsigned int flags)
9770
 
{
9771
 
    struct qemud_driver *driver = domain->conn->privateData;
9772
 
    virDomainObjPtr vm = NULL;
9773
 
    int n = -1;
9774
 
 
9775
 
    virCheckFlags(0, -1);
9776
 
 
9777
 
    qemuDriverLock(driver);
9778
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9779
 
    if (!vm) {
9780
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9781
 
        virUUIDFormat(domain->uuid, uuidstr);
9782
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9783
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9784
 
        goto cleanup;
9785
 
    }
9786
 
 
9787
 
    n = virDomainSnapshotObjListNum(&vm->snapshots);
9788
 
 
9789
 
cleanup:
9790
 
    if (vm)
9791
 
        virDomainObjUnlock(vm);
9792
 
    qemuDriverUnlock(driver);
9793
 
    return n;
9794
 
}
9795
 
 
9796
 
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
9797
 
                                                           const char *name,
9798
 
                                                           unsigned int flags)
9799
 
{
9800
 
    struct qemud_driver *driver = domain->conn->privateData;
9801
 
    virDomainObjPtr vm;
9802
 
    virDomainSnapshotObjPtr snap = NULL;
9803
 
    virDomainSnapshotPtr snapshot = NULL;
9804
 
 
9805
 
    virCheckFlags(0, NULL);
9806
 
 
9807
 
    qemuDriverLock(driver);
9808
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9809
 
    if (!vm) {
9810
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9811
 
        virUUIDFormat(domain->uuid, uuidstr);
9812
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9813
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9814
 
        goto cleanup;
9815
 
    }
9816
 
 
9817
 
    snap = virDomainSnapshotFindByName(&vm->snapshots, name);
9818
 
    if (!snap) {
9819
 
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
9820
 
                        _("no snapshot with matching name '%s'"), name);
9821
 
        goto cleanup;
9822
 
    }
9823
 
 
9824
 
    snapshot = virGetDomainSnapshot(domain, snap->def->name);
9825
 
 
9826
 
cleanup:
9827
 
    if (vm)
9828
 
        virDomainObjUnlock(vm);
9829
 
    qemuDriverUnlock(driver);
9830
 
    return snapshot;
9831
 
}
9832
 
 
9833
 
static int qemuDomainHasCurrentSnapshot(virDomainPtr domain,
9834
 
                                        unsigned int flags)
9835
 
{
9836
 
    struct qemud_driver *driver = domain->conn->privateData;
9837
 
    virDomainObjPtr vm;
9838
 
    int ret = -1;
9839
 
 
9840
 
    virCheckFlags(0, -1);
9841
 
 
9842
 
    qemuDriverLock(driver);
9843
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9844
 
    if (!vm) {
9845
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9846
 
        virUUIDFormat(domain->uuid, uuidstr);
9847
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9848
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9849
 
        goto cleanup;
9850
 
    }
9851
 
 
9852
 
    ret = (vm->current_snapshot != NULL);
9853
 
 
9854
 
cleanup:
9855
 
    if (vm)
9856
 
        virDomainObjUnlock(vm);
9857
 
    qemuDriverUnlock(driver);
9858
 
    return ret;
9859
 
}
9860
 
 
9861
 
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
9862
 
                                                      unsigned int flags)
9863
 
{
9864
 
    struct qemud_driver *driver = domain->conn->privateData;
9865
 
    virDomainObjPtr vm;
9866
 
    virDomainSnapshotPtr snapshot = NULL;
9867
 
 
9868
 
    virCheckFlags(0, NULL);
9869
 
 
9870
 
    qemuDriverLock(driver);
9871
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9872
 
    if (!vm) {
9873
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
9874
 
        virUUIDFormat(domain->uuid, uuidstr);
9875
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9876
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9877
 
        goto cleanup;
9878
 
    }
9879
 
 
9880
 
    if (!vm->current_snapshot) {
9881
 
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
9882
 
                        _("the domain does not have a current snapshot"));
9883
 
        goto cleanup;
9884
 
    }
9885
 
 
9886
 
    snapshot = virGetDomainSnapshot(domain, vm->current_snapshot->def->name);
9887
 
 
9888
 
cleanup:
9889
 
    if (vm)
9890
 
        virDomainObjUnlock(vm);
9891
 
    qemuDriverUnlock(driver);
9892
 
    return snapshot;
9893
 
}
9894
 
 
9895
 
static char *qemuDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
9896
 
                                       unsigned int flags)
9897
 
{
9898
 
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
9899
 
    virDomainObjPtr vm = NULL;
9900
 
    char *xml = NULL;
9901
 
    virDomainSnapshotObjPtr snap = NULL;
9902
 
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9903
 
 
9904
 
    virCheckFlags(0, NULL);
9905
 
 
9906
 
    qemuDriverLock(driver);
9907
 
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
9908
 
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
9909
 
    if (!vm) {
9910
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9911
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9912
 
        goto cleanup;
9913
 
    }
9914
 
 
9915
 
    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
9916
 
    if (!snap) {
9917
 
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
9918
 
                        _("no domain snapshot with matching name '%s'"),
9919
 
                        snapshot->name);
9920
 
        goto cleanup;
9921
 
    }
9922
 
 
9923
 
    xml = virDomainSnapshotDefFormat(uuidstr, snap->def, 0);
9924
 
 
9925
 
cleanup:
9926
 
    if (vm)
9927
 
        virDomainObjUnlock(vm);
9928
 
    qemuDriverUnlock(driver);
9929
 
    return xml;
9930
 
}
9931
 
 
9932
 
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
9933
 
                                      unsigned int flags)
9934
 
{
9935
 
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
9936
 
    virDomainObjPtr vm = NULL;
9937
 
    int ret = -1;
9938
 
    virDomainSnapshotObjPtr snap = NULL;
9939
 
    char uuidstr[VIR_UUID_STRING_BUFLEN];
9940
 
    virDomainEventPtr event = NULL;
9941
 
    qemuDomainObjPrivatePtr priv;
9942
 
    int rc;
9943
 
 
9944
 
    virCheckFlags(0, -1);
9945
 
 
9946
 
    qemuDriverLock(driver);
9947
 
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
9948
 
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
9949
 
    if (!vm) {
9950
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
9951
 
                        _("no domain with matching uuid '%s'"), uuidstr);
9952
 
        goto cleanup;
9953
 
    }
9954
 
 
9955
 
    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
9956
 
    if (!snap) {
9957
 
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
9958
 
                        _("no domain snapshot with matching name '%s'"),
9959
 
                        snapshot->name);
9960
 
        goto cleanup;
9961
 
    }
9962
 
 
9963
 
    vm->current_snapshot = snap;
9964
 
 
9965
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
9966
 
        goto cleanup;
9967
 
 
9968
 
    if (snap->def->state == VIR_DOMAIN_RUNNING
9969
 
        || snap->def->state == VIR_DOMAIN_PAUSED) {
9970
 
 
9971
 
        if (virDomainObjIsActive(vm)) {
9972
 
            priv = vm->privateData;
9973
 
            qemuDomainObjEnterMonitorWithDriver(driver, vm);
9974
 
            rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
9975
 
            qemuDomainObjExitMonitorWithDriver(driver, vm);
9976
 
            if (rc < 0)
9977
 
                goto endjob;
9978
 
        }
9979
 
        else {
9980
 
            if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
9981
 
                goto endjob;
9982
 
 
9983
 
            rc = qemudStartVMDaemon(snapshot->domain->conn, driver, vm, NULL,
9984
 
                                    false, -1, NULL, VIR_VM_OP_CREATE);
9985
 
            qemuDomainStartAudit(vm, "from-snapshot", rc >= 0);
9986
 
            if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
9987
 
                goto endjob;
9988
 
            if (rc < 0)
9989
 
                goto endjob;
9990
 
        }
9991
 
 
9992
 
        if (snap->def->state == VIR_DOMAIN_PAUSED) {
9993
 
            /* qemu unconditionally starts the domain running again after
9994
 
             * loadvm, so let's pause it to keep consistency
9995
 
             */
9996
 
            rc = doStopCPUs(driver, vm);
9997
 
            if (rc < 0)
9998
 
                goto endjob;
9999
 
        }
10000
 
 
10001
 
        event = virDomainEventNewFromObj(vm,
10002
 
                                         VIR_DOMAIN_EVENT_STARTED,
10003
 
                                         VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
10004
 
    }
10005
 
    else {
10006
 
        /* qemu is a little funny with running guests and the restoration
10007
 
         * of snapshots.  If the snapshot was taken online,
10008
 
         * then after a "loadvm" monitor command, the VM is set running
10009
 
         * again.  If the snapshot was taken offline, then after a "loadvm"
10010
 
         * monitor command the VM is left paused.  Unpausing it leads to
10011
 
         * the memory state *before* the loadvm with the disk *after* the
10012
 
         * loadvm, which obviously is bound to corrupt something.
10013
 
         * Therefore we destroy the domain and set it to "off" in this case.
10014
 
         */
10015
 
 
10016
 
        if (virDomainObjIsActive(vm)) {
10017
 
            qemudShutdownVMDaemon(driver, vm, 0);
10018
 
            qemuDomainStopAudit(vm, "from-snapshot");
10019
 
            event = virDomainEventNewFromObj(vm,
10020
 
                                             VIR_DOMAIN_EVENT_STOPPED,
10021
 
                                             VIR_DOMAIN_EVENT_STOPPED_FROM_SNAPSHOT);
10022
 
            if (!vm->persistent) {
10023
 
                if (qemuDomainObjEndJob(vm) > 0)
10024
 
                    virDomainRemoveInactive(&driver->domains, vm);
10025
 
                vm = NULL;
10026
 
                goto cleanup;
10027
 
            }
10028
 
        }
10029
 
 
10030
 
        if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
10031
 
            goto endjob;
10032
 
    }
10033
 
 
10034
 
    vm->state = snap->def->state;
10035
 
 
10036
 
    ret = 0;
10037
 
 
10038
 
endjob:
10039
 
    if (vm && qemuDomainObjEndJob(vm) == 0)
10040
 
        vm = NULL;
10041
 
 
10042
 
cleanup:
10043
 
    if (event)
10044
 
        qemuDomainEventQueue(driver, event);
10045
 
    if (vm)
10046
 
        virDomainObjUnlock(vm);
10047
 
    qemuDriverUnlock(driver);
10048
 
 
10049
 
    return ret;
10050
 
}
10051
 
 
10052
 
static int qemuDomainSnapshotDiscard(struct qemud_driver *driver,
10053
 
                                     virDomainObjPtr vm,
10054
 
                                     virDomainSnapshotObjPtr snap)
10055
 
{
10056
 
    const char *qemuimgarg[] = { NULL, "snapshot", "-d", NULL, NULL, NULL };
10057
 
    char *snapFile = NULL;
10058
 
    int ret = -1;
10059
 
    int i;
10060
 
    qemuDomainObjPrivatePtr priv;
10061
 
    virDomainSnapshotObjPtr parentsnap;
10062
 
 
10063
 
    if (!virDomainObjIsActive(vm)) {
10064
 
        qemuimgarg[0] = qemuFindQemuImgBinary();
10065
 
        if (qemuimgarg[0] == NULL)
10066
 
            /* qemuFindQemuImgBinary set the error */
10067
 
            goto cleanup;
10068
 
 
10069
 
        qemuimgarg[3] = snap->def->name;
10070
 
 
10071
 
        for (i = 0; i < vm->def->ndisks; i++) {
10072
 
            /* FIXME: we also need to handle LVM here */
10073
 
            if (vm->def->disks[i]->device == VIR_DOMAIN_DISK_DEVICE_DISK) {
10074
 
                if (!vm->def->disks[i]->driverType ||
10075
 
                    STRNEQ(vm->def->disks[i]->driverType, "qcow2")) {
10076
 
                    /* we continue on even in the face of error, since other
10077
 
                     * disks in this VM may have this snapshot in place
10078
 
                     */
10079
 
                    continue;
10080
 
                }
10081
 
 
10082
 
                qemuimgarg[4] = vm->def->disks[i]->src;
10083
 
 
10084
 
                if (virRun(qemuimgarg, NULL) < 0) {
10085
 
                    /* we continue on even in the face of error, since other
10086
 
                     * disks in this VM may have this snapshot in place
10087
 
                     */
10088
 
                    continue;
10089
 
                }
10090
 
            }
10091
 
        }
10092
 
    }
10093
 
    else {
10094
 
        priv = vm->privateData;
10095
 
        qemuDomainObjEnterMonitorWithDriver(driver, vm);
10096
 
        /* we continue on even in the face of error */
10097
 
        qemuMonitorDeleteSnapshot(priv->mon, snap->def->name);
10098
 
        qemuDomainObjExitMonitorWithDriver(driver, vm);
10099
 
    }
10100
 
 
10101
 
    if (snap == vm->current_snapshot) {
10102
 
        if (snap->def->parent) {
10103
 
            parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
10104
 
                                                     snap->def->parent);
10105
 
            if (!parentsnap) {
10106
 
                qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
10107
 
                                _("no domain snapshot parent with matching name '%s'"),
10108
 
                                snap->def->parent);
10109
 
                goto cleanup;
10110
 
            }
10111
 
 
10112
 
            /* Now we set the new current_snapshot for the domain */
10113
 
            vm->current_snapshot = parentsnap;
10114
 
        }
10115
 
        else
10116
 
            vm->current_snapshot = NULL;
10117
 
    }
10118
 
 
10119
 
    if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
10120
 
                    vm->def->name, snap->def->name) < 0) {
10121
 
        virReportOOMError();
10122
 
        goto cleanup;
10123
 
    }
10124
 
    unlink(snapFile);
10125
 
 
10126
 
    virDomainSnapshotObjListRemove(&vm->snapshots, snap);
10127
 
 
10128
 
    ret = 0;
10129
 
 
10130
 
cleanup:
10131
 
    VIR_FREE(snapFile);
10132
 
    VIR_FREE(qemuimgarg[0]);
10133
 
 
10134
 
    return ret;
10135
 
}
10136
 
 
10137
 
struct snap_remove {
10138
 
    struct qemud_driver *driver;
10139
 
    virDomainObjPtr vm;
10140
 
    char *parent;
10141
 
    int err;
10142
 
};
10143
 
 
10144
 
static void qemuDomainSnapshotDiscardChildren(void *payload,
10145
 
                                              const char *name ATTRIBUTE_UNUSED,
10146
 
                                              void *data)
10147
 
{
10148
 
    virDomainSnapshotObjPtr snap = payload;
10149
 
    struct snap_remove *curr = data;
10150
 
    struct snap_remove this;
10151
 
 
10152
 
    if (snap->def->parent && STREQ(snap->def->parent, curr->parent)) {
10153
 
        this.driver = curr->driver;
10154
 
        this.vm = curr->vm;
10155
 
        this.parent = snap->def->name;
10156
 
        this.err = 0;
10157
 
        virHashForEach(curr->vm->snapshots.objs,
10158
 
                       qemuDomainSnapshotDiscardChildren, &this);
10159
 
 
10160
 
        if (this.err)
10161
 
            curr->err = this.err;
10162
 
        else
10163
 
            this.err = qemuDomainSnapshotDiscard(curr->driver, curr->vm, snap);
10164
 
    }
10165
 
}
10166
 
 
10167
 
struct snap_reparent {
10168
 
    struct qemud_driver *driver;
10169
 
    virDomainSnapshotObjPtr snap;
10170
 
    virDomainObjPtr vm;
10171
 
    int err;
10172
 
};
10173
 
 
10174
 
static void
10175
 
qemuDomainSnapshotReparentChildren(void *payload,
10176
 
                                   const char *name ATTRIBUTE_UNUSED,
10177
 
                                   void *data)
10178
 
{
10179
 
    virDomainSnapshotObjPtr snap = payload;
10180
 
    struct snap_reparent *rep = data;
10181
 
 
10182
 
    if (rep->err < 0) {
10183
 
        return;
10184
 
    }
10185
 
 
10186
 
    if (snap->def->parent && STREQ(snap->def->parent, rep->snap->def->name)) {
10187
 
        VIR_FREE(snap->def->parent);
10188
 
 
10189
 
        if (rep->snap->def->parent != NULL) {
10190
 
            snap->def->parent = strdup(rep->snap->def->parent);
10191
 
 
10192
 
            if (snap->def->parent == NULL) {
10193
 
                virReportOOMError();
10194
 
                rep->err = -1;
10195
 
                return;
10196
 
            }
10197
 
        }
10198
 
 
10199
 
        rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
10200
 
                                                   rep->driver->snapshotDir);
10201
 
    }
10202
 
}
10203
 
 
10204
 
static int qemuDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
10205
 
                                    unsigned int flags)
10206
 
{
10207
 
    struct qemud_driver *driver = snapshot->domain->conn->privateData;
10208
 
    virDomainObjPtr vm = NULL;
10209
 
    int ret = -1;
10210
 
    virDomainSnapshotObjPtr snap = NULL;
10211
 
    char uuidstr[VIR_UUID_STRING_BUFLEN];
10212
 
    struct snap_remove rem;
10213
 
    struct snap_reparent rep;
10214
 
 
10215
 
    virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);
10216
 
 
10217
 
    qemuDriverLock(driver);
10218
 
    virUUIDFormat(snapshot->domain->uuid, uuidstr);
10219
 
    vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
10220
 
    if (!vm) {
10221
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
10222
 
                        _("no domain with matching uuid '%s'"), uuidstr);
10223
 
        goto cleanup;
10224
 
    }
10225
 
 
10226
 
    snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
10227
 
    if (!snap) {
10228
 
        qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
10229
 
                        _("no domain snapshot with matching name '%s'"),
10230
 
                        snapshot->name);
10231
 
        goto cleanup;
10232
 
    }
10233
 
 
10234
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
10235
 
        goto cleanup;
10236
 
 
10237
 
    if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN) {
10238
 
        rem.driver = driver;
10239
 
        rem.vm = vm;
10240
 
        rem.parent = snap->def->name;
10241
 
        rem.err = 0;
10242
 
        virHashForEach(vm->snapshots.objs, qemuDomainSnapshotDiscardChildren,
10243
 
                       &rem);
10244
 
        if (rem.err < 0)
10245
 
            goto endjob;
10246
 
    } else {
10247
 
        rep.driver = driver;
10248
 
        rep.snap = snap;
10249
 
        rep.vm = vm;
10250
 
        rep.err = 0;
10251
 
        virHashForEach(vm->snapshots.objs, qemuDomainSnapshotReparentChildren,
10252
 
                       &rep);
10253
 
        if (rep.err < 0)
10254
 
            goto endjob;
10255
 
    }
10256
 
 
10257
 
    ret = qemuDomainSnapshotDiscard(driver, vm, snap);
10258
 
 
10259
 
endjob:
10260
 
    if (qemuDomainObjEndJob(vm) == 0)
10261
 
        vm = NULL;
10262
 
 
10263
 
cleanup:
10264
 
    if (vm)
10265
 
        virDomainObjUnlock(vm);
10266
 
    qemuDriverUnlock(driver);
10267
 
    return ret;
10268
 
}
10269
 
 
10270
 
static int qemuDomainMonitorCommand(virDomainPtr domain, const char *cmd,
10271
 
                                    char **result, unsigned int flags)
10272
 
{
10273
 
    struct qemud_driver *driver = domain->conn->privateData;
10274
 
    virDomainObjPtr vm = NULL;
10275
 
    int ret = -1;
10276
 
    qemuDomainObjPrivatePtr priv;
10277
 
    bool hmp;
10278
 
 
10279
 
    virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
10280
 
 
10281
 
    qemuDriverLock(driver);
10282
 
    vm = virDomainFindByUUID(&driver->domains, domain->uuid);
10283
 
    if (!vm) {
10284
 
        char uuidstr[VIR_UUID_STRING_BUFLEN];
10285
 
        virUUIDFormat(domain->uuid, uuidstr);
10286
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
10287
 
                        _("no domain with matching uuid '%s'"), uuidstr);
10288
 
        goto cleanup;
10289
 
    }
10290
 
 
10291
 
    if (!virDomainObjIsActive(vm)) {
10292
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
10293
 
                        "%s", _("domain is not running"));
10294
 
        goto cleanup;
10295
 
   }
10296
 
 
10297
 
    priv = vm->privateData;
10298
 
 
10299
 
    if (!priv->monitor_warned) {
10300
 
        VIR_INFO("Qemu monitor command '%s' executed; libvirt results may be unpredictable!",
10301
 
                 cmd);
10302
 
        priv->monitor_warned = 1;
10303
 
    }
10304
 
 
10305
 
    hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);
10306
 
 
10307
 
    if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
10308
 
        goto cleanup;
10309
 
    qemuDomainObjEnterMonitorWithDriver(driver, vm);
10310
 
    ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
10311
 
    qemuDomainObjExitMonitorWithDriver(driver, vm);
10312
 
    if (qemuDomainObjEndJob(vm) == 0) {
10313
 
        vm = NULL;
10314
 
        goto cleanup;
10315
 
    }
10316
 
 
10317
 
cleanup:
10318
 
    if (vm)
10319
 
        virDomainObjUnlock(vm);
10320
 
    qemuDriverUnlock(driver);
10321
 
    return ret;
10322
 
}
10323
 
 
10324
 
 
10325
 
static int
10326
 
qemuDomainOpenConsole(virDomainPtr dom,
10327
 
                      const char *devname,
10328
 
                      virStreamPtr st,
10329
 
                      unsigned int flags)
10330
 
{
10331
 
    struct qemud_driver *driver = dom->conn->privateData;
10332
 
    virDomainObjPtr vm = NULL;
10333
 
    char uuidstr[VIR_UUID_STRING_BUFLEN];
10334
 
    int ret = -1;
10335
 
    int i;
10336
 
    virDomainChrDefPtr chr = NULL;
10337
 
 
10338
 
    virCheckFlags(0, -1);
10339
 
 
10340
 
    qemuDriverLock(driver);
10341
 
    virUUIDFormat(dom->uuid, uuidstr);
10342
 
    vm = virDomainFindByUUID(&driver->domains, dom->uuid);
10343
 
    if (!vm) {
10344
 
        qemuReportError(VIR_ERR_NO_DOMAIN,
10345
 
                        _("no domain with matching uuid '%s'"), uuidstr);
10346
 
        goto cleanup;
10347
 
    }
10348
 
 
10349
 
    if (!virDomainObjIsActive(vm)) {
10350
 
        qemuReportError(VIR_ERR_OPERATION_INVALID,
10351
 
                        "%s", _("domain is not running"));
10352
 
        goto cleanup;
10353
 
    }
10354
 
 
10355
 
    if (devname) {
10356
 
        if (vm->def->console &&
10357
 
            STREQ(devname, vm->def->console->info.alias))
10358
 
            chr = vm->def->console;
10359
 
        for (i = 0 ; !chr && i < vm->def->nserials ; i++) {
10360
 
            if (STREQ(devname, vm->def->serials[i]->info.alias))
10361
 
                chr = vm->def->serials[i];
10362
 
        }
10363
 
        for (i = 0 ; !chr && i < vm->def->nparallels ; i++) {
10364
 
            if (STREQ(devname, vm->def->parallels[i]->info.alias))
10365
 
                chr = vm->def->parallels[i];
10366
 
        }
10367
 
    } else {
10368
 
        if (vm->def->console)
10369
 
            chr = vm->def->console;
10370
 
        else if (vm->def->nserials)
10371
 
            chr = vm->def->serials[0];
10372
 
    }
10373
 
 
10374
 
    if (!chr) {
10375
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
10376
 
                        _("cannot find character device %s"),
10377
 
                        NULLSTR(devname));
10378
 
        goto cleanup;
10379
 
    }
10380
 
 
10381
 
    if (chr->source.type != VIR_DOMAIN_CHR_TYPE_PTY) {
10382
 
        qemuReportError(VIR_ERR_INTERNAL_ERROR,
10383
 
                        _("character device %s is not using a PTY"),
10384
 
                        NULLSTR(devname));
10385
 
        goto cleanup;
10386
 
    }
10387
 
 
10388
 
    if (virFDStreamOpenFile(st, chr->source.data.file.path, O_RDWR) < 0)
10389
 
        goto cleanup;
10390
 
 
10391
 
    ret = 0;
10392
 
cleanup:
10393
 
    if (vm)
10394
 
        virDomainObjUnlock(vm);
10395
 
    qemuDriverUnlock(driver);
10396
 
    return ret;
10397
 
}
10398
 
 
10399
 
 
10400
 
static virDriver qemuDriver = {
10401
 
    VIR_DRV_QEMU,
10402
 
    "QEMU",
10403
 
    qemudOpen, /* open */
10404
 
    qemudClose, /* close */
10405
 
    qemudSupportsFeature, /* supports_feature */
10406
 
    qemudGetType, /* type */
10407
 
    qemudGetVersion, /* version */
10408
 
    NULL, /* libvirtVersion (impl. in libvirt.c) */
10409
 
    virGetHostname, /* getHostname */
10410
 
    qemuGetSysinfo, /* getSysinfo */
10411
 
    qemudGetMaxVCPUs, /* getMaxVcpus */
10412
 
    nodeGetInfo, /* nodeGetInfo */
10413
 
    qemudGetCapabilities, /* getCapabilities */
10414
 
    qemudListDomains, /* listDomains */
10415
 
    qemudNumDomains, /* numOfDomains */
10416
 
    qemudDomainCreate, /* domainCreateXML */
10417
 
    qemudDomainLookupByID, /* domainLookupByID */
10418
 
    qemudDomainLookupByUUID, /* domainLookupByUUID */
10419
 
    qemudDomainLookupByName, /* domainLookupByName */
10420
 
    qemudDomainSuspend, /* domainSuspend */
10421
 
    qemudDomainResume, /* domainResume */
10422
 
    qemudDomainShutdown, /* domainShutdown */
10423
 
    NULL, /* domainReboot */
10424
 
    qemudDomainDestroy, /* domainDestroy */
10425
 
    qemudDomainGetOSType, /* domainGetOSType */
10426
 
    qemudDomainGetMaxMemory, /* domainGetMaxMemory */
10427
 
    NULL, /* domainSetMaxMemory */
10428
 
    qemudDomainSetMemory, /* domainSetMemory */
10429
 
    qemudDomainGetInfo, /* domainGetInfo */
10430
 
    qemudDomainSave, /* domainSave */
10431
 
    qemudDomainRestore, /* domainRestore */
10432
 
    qemudDomainCoreDump, /* domainCoreDump */
10433
 
    qemudDomainSetVcpus, /* domainSetVcpus */
10434
 
    qemudDomainSetVcpusFlags, /* domainSetVcpusFlags */
10435
 
    qemudDomainGetVcpusFlags, /* domainGetVcpusFlags */
10436
 
    qemudDomainPinVcpu, /* domainPinVcpu */
10437
 
    qemudDomainGetVcpus, /* domainGetVcpus */
10438
 
    qemudDomainGetMaxVcpus, /* domainGetMaxVcpus */
10439
 
    qemudDomainGetSecurityLabel, /* domainGetSecurityLabel */
10440
 
    qemudNodeGetSecurityModel, /* nodeGetSecurityModel */
10441
 
    qemudDomainDumpXML, /* domainDumpXML */
10442
 
    qemuDomainXMLFromNative, /* domainXmlFromNative */
10443
 
    qemuDomainXMLToNative, /* domainXMLToNative */
10444
 
    qemudListDefinedDomains, /* listDefinedDomains */
10445
 
    qemudNumDefinedDomains, /* numOfDefinedDomains */
10446
 
    qemudDomainStart, /* domainCreate */
10447
 
    qemudDomainStartWithFlags, /* domainCreateWithFlags */
10448
 
    qemudDomainDefine, /* domainDefineXML */
10449
 
    qemudDomainUndefine, /* domainUndefine */
10450
 
    qemudDomainAttachDevice, /* domainAttachDevice */
10451
 
    qemudDomainAttachDeviceFlags, /* domainAttachDeviceFlags */
10452
 
    qemudDomainDetachDevice, /* domainDetachDevice */
10453
 
    qemudDomainDetachDeviceFlags, /* domainDetachDeviceFlags */
10454
 
    qemuDomainUpdateDeviceFlags, /* domainUpdateDeviceFlags */
10455
 
    qemudDomainGetAutostart, /* domainGetAutostart */
10456
 
    qemudDomainSetAutostart, /* domainSetAutostart */
10457
 
    qemuGetSchedulerType, /* domainGetSchedulerType */
10458
 
    qemuGetSchedulerParameters, /* domainGetSchedulerParameters */
10459
 
    qemuSetSchedulerParameters, /* domainSetSchedulerParameters */
10460
 
    NULL, /* domainMigratePrepare (v1) */
10461
 
    qemudDomainMigratePerform, /* domainMigratePerform */
10462
 
    NULL, /* domainMigrateFinish */
10463
 
    qemudDomainBlockStats, /* domainBlockStats */
10464
 
    qemudDomainInterfaceStats, /* domainInterfaceStats */
10465
 
    qemudDomainMemoryStats, /* domainMemoryStats */
10466
 
    qemudDomainBlockPeek, /* domainBlockPeek */
10467
 
    qemudDomainMemoryPeek, /* domainMemoryPeek */
10468
 
    qemuDomainGetBlockInfo, /* domainGetBlockInfo */
10469
 
    nodeGetCellsFreeMemory, /* nodeGetCellsFreeMemory */
10470
 
    nodeGetFreeMemory,  /* getFreeMemory */
10471
 
    qemuDomainEventRegister, /* domainEventRegister */
10472
 
    qemuDomainEventDeregister, /* domainEventDeregister */
10473
 
    qemudDomainMigratePrepare2, /* domainMigratePrepare2 */
10474
 
    qemudDomainMigrateFinish2, /* domainMigrateFinish2 */
10475
 
    qemudNodeDeviceDettach, /* nodeDeviceDettach */
10476
 
    qemudNodeDeviceReAttach, /* nodeDeviceReAttach */
10477
 
    qemudNodeDeviceReset, /* nodeDeviceReset */
10478
 
    qemudDomainMigratePrepareTunnel, /* domainMigratePrepareTunnel */
10479
 
    qemuIsEncrypted, /* isEncrypted */
10480
 
    qemuIsSecure, /* isSecure */
10481
 
    qemuDomainIsActive, /* domainIsActive */
10482
 
    qemuDomainIsPersistent, /* domainIsPersistent */
10483
 
    qemuDomainIsUpdated, /* domainIsUpdated */
10484
 
    qemuCPUCompare, /* cpuCompare */
10485
 
    qemuCPUBaseline, /* cpuBaseline */
10486
 
    qemuDomainGetJobInfo, /* domainGetJobInfo */
10487
 
    qemuDomainAbortJob, /* domainAbortJob */
10488
 
    qemuDomainMigrateSetMaxDowntime, /* domainMigrateSetMaxDowntime */
10489
 
    qemuDomainEventRegisterAny, /* domainEventRegisterAny */
10490
 
    qemuDomainEventDeregisterAny, /* domainEventDeregisterAny */
10491
 
    qemuDomainManagedSave, /* domainManagedSave */
10492
 
    qemuDomainHasManagedSaveImage, /* domainHasManagedSaveImage */
10493
 
    qemuDomainManagedSaveRemove, /* domainManagedSaveRemove */
10494
 
    qemuDomainSnapshotCreateXML, /* domainSnapshotCreateXML */
10495
 
    qemuDomainSnapshotDumpXML, /* domainSnapshotDumpXML */
10496
 
    qemuDomainSnapshotNum, /* domainSnapshotNum */
10497
 
    qemuDomainSnapshotListNames, /* domainSnapshotListNames */
10498
 
    qemuDomainSnapshotLookupByName, /* domainSnapshotLookupByName */
10499
 
    qemuDomainHasCurrentSnapshot, /* domainHasCurrentSnapshot */
10500
 
    qemuDomainSnapshotCurrent, /* domainSnapshotCurrent */
10501
 
    qemuDomainRevertToSnapshot, /* domainRevertToSnapshot */
10502
 
    qemuDomainSnapshotDelete, /* domainSnapshotDelete */
10503
 
    qemuDomainMonitorCommand, /* qemuDomainMonitorCommand */
10504
 
    qemuDomainSetMemoryParameters, /* domainSetMemoryParameters */
10505
 
    qemuDomainGetMemoryParameters, /* domainGetMemoryParameters */
10506
 
    qemuDomainOpenConsole, /* domainOpenConsole */
10507
 
};
10508
 
 
10509
 
 
10510
 
static virStateDriver qemuStateDriver = {
10511
 
    .name = "QEMU",
10512
 
    .initialize = qemudStartup,
10513
 
    .cleanup = qemudShutdown,
10514
 
    .reload = qemudReload,
10515
 
    .active = qemudActive,
10516
 
};
10517
 
 
10518
 
static int
10519
 
qemudVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
10520
 
                     virHashIterator iter, void *data)
10521
 
{
10522
 
    virHashForEach(qemu_driver->domains.objs, iter, data);
10523
 
 
10524
 
    return 0;
10525
 
}
10526
 
 
10527
 
static int
10528
 
qemudVMFiltersInstantiate(virConnectPtr conn,
10529
 
                          virDomainDefPtr def)
10530
 
{
10531
 
    int err = 0;
10532
 
    int i;
10533
 
 
10534
 
    if (!conn)
10535
 
        return 1;
10536
 
 
10537
 
    for (i = 0 ; i < def->nnets ; i++) {
10538
 
        virDomainNetDefPtr net = def->nets[i];
10539
 
        if ((net->filter) && (net->ifname)) {
10540
 
           if (virDomainConfNWFilterInstantiate(conn, net)) {
10541
 
                err = 1;
10542
 
                break;
10543
 
            }
10544
 
        }
10545
 
    }
10546
 
 
10547
 
    return err;
10548
 
}
10549
 
 
10550
 
 
10551
 
static void
10552
 
qemudVMDriverLock(void) {
10553
 
    qemuDriverLock(qemu_driver);
10554
 
};
10555
 
 
10556
 
 
10557
 
static void
10558
 
qemudVMDriverUnlock(void) {
10559
 
    qemuDriverUnlock(qemu_driver);
10560
 
};
10561
 
 
10562
 
 
10563
 
static virNWFilterCallbackDriver qemuCallbackDriver = {
10564
 
    .name = "QEMU",
10565
 
    .vmFilterRebuild = qemudVMFilterRebuild,
10566
 
    .vmDriverLock = qemudVMDriverLock,
10567
 
    .vmDriverUnlock = qemudVMDriverUnlock,
10568
 
};
10569
 
 
10570
 
int qemuRegister(void) {
10571
 
    virRegisterDriver(&qemuDriver);
10572
 
    virRegisterStateDriver(&qemuStateDriver);
10573
 
    virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);
10574
 
    return 0;
10575
 
}