2
* driver.c: core driver methods for managing qemu guests
4
* Copyright (C) 2006-2011 Red Hat, Inc.
5
* Copyright (C) 2006 Daniel P. Berrange
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.
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.
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
21
* Author: Daniel P. Berrange <berrange@redhat.com>
26
#include <sys/types.h>
38
#include <sys/utsname.h>
45
#include <sys/ioctl.h>
49
#include "virterror_internal.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"
67
#include "stats_linux.h"
68
#include "capabilities.h"
71
#include "domain_conf.h"
72
#include "node_device_conf.h"
75
#include "processinfo.h"
76
#include "libvirt_internal.h"
81
#include "domain_nwfilter.h"
83
#include "storage_file.h"
86
#include "configmake.h"
87
#include "threadpool.h"
89
#define VIR_FROM_THIS VIR_FROM_QEMU
91
#define QEMU_VNC_PORT_MIN 5900
92
#define QEMU_VNC_PORT_MAX 65535
94
#define QEMU_NB_MEM_PARAM 3
97
#define timeval_to_ms(tv) (((tv).tv_sec * 1000ull) + ((tv).tv_usec / 1000))
105
static void processWatchdogEvent(void *data, void *opaque);
107
static int qemudShutdown(void);
109
static void qemuDomainEventFlush(int timer, void *opaque);
110
static void qemuDomainEventQueue(struct qemud_driver *driver,
111
virDomainEventPtr event);
113
static int qemudDomainObjStart(virConnectPtr conn,
114
struct qemud_driver *driver,
118
static int qemudStartVMDaemon(virConnectPtr conn,
119
struct qemud_driver *driver,
121
const char *migrateFrom,
124
const char *stdin_path,
125
enum virVMOperationType vmop);
127
static void qemudShutdownVMDaemon(struct qemud_driver *driver,
131
static int qemudDomainGetMaxVcpus(virDomainPtr dom);
133
static int qemuDetectVcpuPIDs(struct qemud_driver *driver,
136
static int qemudVMFiltersInstantiate(virConnectPtr conn,
137
virDomainDefPtr def);
139
static struct qemud_driver *qemu_driver = NULL;
142
static int doStartCPUs(struct qemud_driver *driver, virDomainObjPtr vm, virConnectPtr conn)
145
qemuDomainObjPrivatePtr priv = vm->privateData;
147
qemuDomainObjEnterMonitorWithDriver(driver, vm);
148
ret = qemuMonitorStartCPUs(priv->mon, conn);
150
vm->state = VIR_DOMAIN_RUNNING;
152
qemuDomainObjExitMonitorWithDriver(driver, vm);
157
static int doStopCPUs(struct qemud_driver *driver, virDomainObjPtr vm)
160
int oldState = vm->state;
161
qemuDomainObjPrivatePtr priv = vm->privateData;
163
vm->state = VIR_DOMAIN_PAUSED;
164
qemuDomainObjEnterMonitorWithDriver(driver, vm);
165
ret = qemuMonitorStopCPUs(priv->mon);
166
qemuDomainObjExitMonitorWithDriver(driver, vm);
168
vm->state = oldState;
175
qemudLogFD(struct qemud_driver *driver, const char* name, bool append)
181
if (virAsprintf(&logfile, "%s/%s.log", driver->logDir, name) < 0) {
186
logmode = O_CREAT | O_WRONLY;
187
/* Only logrotate files in /var/log, so only append if running privileged */
188
if (driver->privileged || append)
193
if ((fd = open(logfile, logmode, S_IRUSR | S_IWUSR)) < 0) {
194
virReportSystemError(errno,
195
_("failed to create logfile %s"),
201
if (virSetCloseExec(fd) < 0) {
202
virReportSystemError(errno, "%s",
203
_("Unable to set VM logfile close-on-exec flag"));
212
qemudLogReadFD(const char* logDir, const char* name, off_t pos)
215
mode_t logmode = O_RDONLY;
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"),
225
if ((fd = open(logfile, logmode)) < 0) {
226
virReportSystemError(errno,
227
_("failed to create logfile %s"),
232
if (virSetCloseExec(fd) < 0) {
233
virReportSystemError(errno, "%s",
234
_("Unable to set VM logfile close-on-exec flag"));
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);
250
struct qemuAutostartData {
251
struct qemud_driver *driver;
255
qemuAutostartDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
257
virDomainObjPtr vm = payload;
258
struct qemuAutostartData *data = opaque;
261
virDomainObjLock(vm);
263
if (qemuDomainObjBeginJobWithDriver(data->driver, vm) < 0) {
264
err = virGetLastError();
265
VIR_ERROR(_("Failed to start job on VM '%s': %s"),
267
err ? err->message : _("unknown error"));
270
!virDomainObjIsActive(vm) &&
271
qemudDomainObjStart(data->conn, data->driver, vm, false) < 0) {
272
err = virGetLastError();
273
VIR_ERROR(_("Failed to autostart VM '%s': %s"),
275
err ? err->message : _("unknown error"));
278
if (qemuDomainObjEndJob(vm) == 0)
283
virDomainObjUnlock(vm);
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
293
virConnectPtr conn = virConnectOpen(driver->privileged ?
296
/* Ignoring NULL conn which is mostly harmless here */
297
struct qemuAutostartData data = { driver, conn };
299
qemuDriverLock(driver);
300
virHashForEach(driver->domains.objs, qemuAutostartDomain, &data);
301
qemuDriverUnlock(driver);
304
virConnectClose(conn);
309
* qemudRemoveDomainStatus
311
* remove all state files of a domain from statedir
313
* Returns 0 on success
316
qemudRemoveDomainStatus(struct qemud_driver *driver,
322
if (virAsprintf(&file, "%s/%s.xml", driver->stateDir, vm->def->name) < 0) {
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)));
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)));
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
348
qemuHandleMonitorEOF(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
351
struct qemud_driver *driver = qemu_driver;
352
virDomainEventPtr event = NULL;
353
qemuDomainObjPrivatePtr priv;
355
VIR_DEBUG("Received EOF on %p '%s'", vm, vm->def->name);
357
virDomainObjLock(vm);
359
if (!virDomainObjIsActive(vm)) {
360
VIR_DEBUG("Domain %p is not active, ignoring EOF", vm);
361
virDomainObjUnlock(vm);
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);
372
event = virDomainEventNewFromObj(vm,
373
VIR_DOMAIN_EVENT_STOPPED,
375
VIR_DOMAIN_EVENT_STOPPED_FAILED :
376
VIR_DOMAIN_EVENT_STOPPED_SHUTDOWN);
378
qemudShutdownVMDaemon(driver, vm, 0);
379
qemuDomainStopAudit(vm, hasError ? "failed" : "shutdown");
382
virDomainRemoveInactive(&driver->domains, vm);
384
virDomainObjUnlock(vm);
387
qemuDriverLock(driver);
388
qemuDomainEventQueue(driver, event);
389
qemuDriverUnlock(driver);
394
static virDomainDiskDefPtr
395
findDomainDiskByPath(virDomainObjPtr vm,
400
for (i = 0; i < vm->def->ndisks; i++) {
401
virDomainDiskDefPtr disk;
403
disk = vm->def->disks[i];
404
if (disk->src != NULL && STREQ(disk->src, path))
408
qemuReportError(VIR_ERR_INTERNAL_ERROR,
409
_("no disk found with path %s"),
414
static virDomainDiskDefPtr
415
findDomainDiskByAlias(virDomainObjPtr vm,
420
if (STRPREFIX(alias, QEMU_DRIVE_HOST_PREFIX))
421
alias += strlen(QEMU_DRIVE_HOST_PREFIX);
423
for (i = 0; i < vm->def->ndisks; i++) {
424
virDomainDiskDefPtr disk;
426
disk = vm->def->disks[i];
427
if (disk->info.alias != NULL && STREQ(disk->info.alias, alias))
431
qemuReportError(VIR_ERR_INTERNAL_ERROR,
432
_("no disk found with alias %s"),
438
getVolumeQcowPassphrase(virConnectPtr conn,
439
virDomainDiskDefPtr disk,
448
virStorageEncryptionPtr enc;
450
if (!disk->encryption) {
451
qemuReportError(VIR_ERR_INTERNAL_ERROR,
452
_("disk %s does not have any encryption information"),
456
enc = disk->encryption;
459
qemuReportError(VIR_ERR_INTERNAL_ERROR,
460
"%s", _("cannot find secrets without a connection"));
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"));
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);
481
secret = conn->secretDriver->lookupByUUID(conn,
482
enc->secrets[0]->uuid);
485
data = conn->secretDriver->getValue(secret, &size,
486
VIR_SECRET_GET_VALUE_INTERNAL_CALL);
487
virUnrefSecret(secret);
491
if (memchr(data, '\0', size) != NULL) {
492
memset(data, 0, size);
494
qemuReportError(VIR_ERR_XML_ERROR,
495
_("format='qcow' passphrase for %s must not contain a "
496
"'\\0'"), disk->src);
500
if (VIR_ALLOC_N(passphrase, size + 1) < 0) {
501
memset(data, 0, size);
506
memcpy(passphrase, data, size);
507
passphrase[size] = '\0';
509
memset(data, 0, size);
512
*secretRet = passphrase;
522
findVolumeQcowPassphrase(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
529
virDomainDiskDefPtr disk;
532
virDomainObjLock(vm);
533
disk = findDomainDiskByPath(vm, path);
538
ret = getVolumeQcowPassphrase(conn, disk, secretRet, secretLen);
541
virDomainObjUnlock(vm);
547
qemuHandleDomainReset(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
550
struct qemud_driver *driver = qemu_driver;
551
virDomainEventPtr event;
553
virDomainObjLock(vm);
554
event = virDomainEventRebootNewFromObj(vm);
555
virDomainObjUnlock(vm);
558
qemuDriverLock(driver);
559
qemuDomainEventQueue(driver, event);
560
qemuDriverUnlock(driver);
568
qemuHandleDomainShutdown(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
571
virDomainObjLock(vm);
572
((qemuDomainObjPrivatePtr) vm->privateData)->gotShutdown = true;
573
virDomainObjUnlock(vm);
580
qemuHandleDomainStop(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
583
struct qemud_driver *driver = qemu_driver;
584
virDomainEventPtr event = NULL;
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);
590
vm->state = VIR_DOMAIN_PAUSED;
591
event = virDomainEventNewFromObj(vm,
592
VIR_DOMAIN_EVENT_SUSPENDED,
593
VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
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);
598
virDomainObjUnlock(vm);
601
qemuDriverLock(driver);
603
qemuDomainEventQueue(driver, event);
604
qemuDriverUnlock(driver);
612
qemuHandleDomainRTCChange(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
616
struct qemud_driver *driver = qemu_driver;
617
virDomainEventPtr event;
619
virDomainObjLock(vm);
620
event = virDomainEventRTCChangeNewFromObj(vm, offset);
622
if (vm->def->clock.offset == VIR_DOMAIN_CLOCK_OFFSET_VARIABLE)
623
vm->def->clock.data.adjustment = offset;
625
if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
626
VIR_WARN0("unable to save domain status with RTC change");
628
virDomainObjUnlock(vm);
631
qemuDriverLock(driver);
632
qemuDomainEventQueue(driver, event);
633
qemuDriverUnlock(driver);
641
qemuHandleDomainWatchdog(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
645
struct qemud_driver *driver = qemu_driver;
646
virDomainEventPtr watchdogEvent = NULL;
647
virDomainEventPtr lifecycleEvent = NULL;
649
virDomainObjLock(vm);
650
watchdogEvent = virDomainEventWatchdogNewFromObj(vm, action);
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);
656
vm->state = VIR_DOMAIN_PAUSED;
657
lifecycleEvent = virDomainEventNewFromObj(vm,
658
VIR_DOMAIN_EVENT_SUSPENDED,
659
VIR_DOMAIN_EVENT_SUSPENDED_WATCHDOG);
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);
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;
670
ignore_value(virThreadPoolSendJob(driver->workerPool, wdEvent));
675
virDomainObjUnlock(vm);
677
if (watchdogEvent || lifecycleEvent) {
678
qemuDriverLock(driver);
680
qemuDomainEventQueue(driver, watchdogEvent);
682
qemuDomainEventQueue(driver, lifecycleEvent);
683
qemuDriverUnlock(driver);
691
qemuHandleDomainIOError(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
693
const char *diskAlias,
697
struct qemud_driver *driver = qemu_driver;
698
virDomainEventPtr ioErrorEvent = NULL;
699
virDomainEventPtr ioErrorEvent2 = NULL;
700
virDomainEventPtr lifecycleEvent = NULL;
702
const char *devAlias;
703
virDomainDiskDefPtr disk;
705
virDomainObjLock(vm);
706
disk = findDomainDiskByAlias(vm, diskAlias);
710
devAlias = disk->info.alias;
716
ioErrorEvent = virDomainEventIOErrorNewFromObj(vm, srcPath, devAlias, action);
717
ioErrorEvent2 = virDomainEventIOErrorReasonNewFromObj(vm, srcPath, devAlias, action, reason);
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);
723
vm->state = VIR_DOMAIN_PAUSED;
724
lifecycleEvent = virDomainEventNewFromObj(vm,
725
VIR_DOMAIN_EVENT_SUSPENDED,
726
VIR_DOMAIN_EVENT_SUSPENDED_IOERROR);
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);
731
virDomainObjUnlock(vm);
733
if (ioErrorEvent || ioErrorEvent2 || lifecycleEvent) {
734
qemuDriverLock(driver);
736
qemuDomainEventQueue(driver, ioErrorEvent);
738
qemuDomainEventQueue(driver, ioErrorEvent2);
740
qemuDomainEventQueue(driver, lifecycleEvent);
741
qemuDriverUnlock(driver);
749
qemuHandleDomainGraphics(qemuMonitorPtr mon ATTRIBUTE_UNUSED,
753
const char *localNode,
754
const char *localService,
756
const char *remoteNode,
757
const char *remoteService,
758
const char *authScheme,
759
const char *x509dname,
760
const char *saslUsername)
762
struct qemud_driver *driver = qemu_driver;
763
virDomainEventPtr event;
764
virDomainEventGraphicsAddressPtr localAddr = NULL;
765
virDomainEventGraphicsAddressPtr remoteAddr = NULL;
766
virDomainEventGraphicsSubjectPtr subject = NULL;
769
virDomainObjLock(vm);
771
if (VIR_ALLOC(localAddr) < 0)
773
localAddr->family = localFamily;
774
if (!(localAddr->service = strdup(localService)) ||
775
!(localAddr->node = strdup(localNode)))
778
if (VIR_ALLOC(remoteAddr) < 0)
780
remoteAddr->family = remoteFamily;
781
if (!(remoteAddr->service = strdup(remoteService)) ||
782
!(remoteAddr->node = strdup(remoteNode)))
785
if (VIR_ALLOC(subject) < 0)
788
if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0)
790
if (!(subject->identities[subject->nidentity].type = strdup("x509dname")) ||
791
!(subject->identities[subject->nidentity].name = strdup(x509dname)))
793
subject->nidentity++;
796
if (VIR_REALLOC_N(subject->identities, subject->nidentity+1) < 0)
798
if (!(subject->identities[subject->nidentity].type = strdup("saslUsername")) ||
799
!(subject->identities[subject->nidentity].name = strdup(saslUsername)))
801
subject->nidentity++;
804
event = virDomainEventGraphicsNewFromObj(vm, phase, localAddr, remoteAddr, authScheme, subject);
805
virDomainObjUnlock(vm);
808
qemuDriverLock(driver);
809
qemuDomainEventQueue(driver, event);
810
qemuDriverUnlock(driver);
818
VIR_FREE(localAddr->service);
819
VIR_FREE(localAddr->node);
823
VIR_FREE(remoteAddr->service);
824
VIR_FREE(remoteAddr->node);
825
VIR_FREE(remoteAddr);
828
for (i = 0 ; i < subject->nidentity ; i++) {
829
VIR_FREE(subject->identities[i].type);
830
VIR_FREE(subject->identities[i].name);
832
VIR_FREE(subject->identities);
840
static void qemuHandleMonitorDestroy(qemuMonitorPtr mon,
843
qemuDomainObjPrivatePtr priv = vm->privateData;
844
if (priv->mon == mon)
846
virDomainObjUnref(vm);
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,
863
qemuConnectMonitor(struct qemud_driver *driver, virDomainObjPtr vm)
865
qemuDomainObjPrivatePtr priv = vm->privateData;
868
if (virSecurityManagerSetSocketLabel(driver->securityManager, vm) < 0) {
869
VIR_ERROR(_("Failed to set security context for monitor for %s"),
874
/* Hold an extra reference because we can't allow 'vm' to be
875
* deleted while the monitor is active */
878
priv->mon = qemuMonitorOpen(vm,
883
if (priv->mon == NULL)
884
virDomainObjUnref(vm);
886
if (virSecurityManagerClearSocketLabel(driver->securityManager, vm) < 0) {
887
VIR_ERROR(_("Failed to clear security context for monitor for %s"),
892
if (priv->mon == NULL) {
893
VIR_INFO("Failed to connect monitor for %s", vm->def->name);
898
qemuDomainObjEnterMonitorWithDriver(driver, vm);
899
ret = qemuMonitorSetCapabilities(priv->mon);
900
qemuDomainObjExitMonitorWithDriver(driver, vm);
907
struct virReconnectDomainData {
909
struct qemud_driver *driver;
912
* Open an existing VM's monitor, re-detect VCPU threads
913
* and re-reserve the security labels in use
916
qemuReconnectDomain(void *payload, const char *name ATTRIBUTE_UNUSED, void *opaque)
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;
925
virDomainObjLock(obj);
927
VIR_DEBUG("Reconnect monitor to %p '%s'", obj, obj->def->name);
929
priv = obj->privateData;
931
/* Hold an extra reference because we can't allow 'vm' to be
932
* deleted if qemuConnectMonitor() failed */
933
virDomainObjRef(obj);
935
/* XXX check PID liveliness & EXE path */
936
if (qemuConnectMonitor(driver, obj) < 0)
939
if (qemuUpdateActivePciHostdevs(driver, obj->def) < 0) {
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,
948
&qemuCmdFlags) >= 0 &&
949
(qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE)) {
950
priv->persistentAddrs = 1;
952
if (!(priv->pciaddrs = qemuDomainPCIAddressSetCreate(obj->def)) ||
953
qemuAssignDevicePCISlots(obj->def, priv->pciaddrs) < 0)
957
if (virSecurityManagerReserveLabel(driver->securityManager, obj) < 0)
960
if (qemudVMFiltersInstantiate(conn, obj->def))
963
if (obj->def->id >= driver->nextvmid)
964
driver->nextvmid = obj->def->id + 1;
966
if (virDomainObjUnref(obj) > 0)
967
virDomainObjUnlock(obj);
971
if (!virDomainObjIsActive(obj)) {
972
if (virDomainObjUnref(obj) > 0)
973
virDomainObjUnlock(obj);
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);
985
virDomainObjUnlock(obj);
990
* qemudReconnectDomains
992
* Try to re-open the resources for live VMs that we care
996
qemuReconnectDomains(virConnectPtr conn, struct qemud_driver *driver)
998
struct virReconnectDomainData data = {conn, driver};
999
virHashForEach(driver->domains.objs, qemuReconnectDomain, &data);
1004
qemuSecurityInit(struct qemud_driver *driver)
1006
virSecurityManagerPtr mgr = virSecurityManagerNew(driver->securityDriverName,
1007
driver->allowDiskFormatProbing);
1011
if (driver->privileged) {
1012
virSecurityManagerPtr dac = virSecurityManagerNewDAC(driver->user,
1014
driver->allowDiskFormatProbing,
1015
driver->dynamicOwnership);
1019
if (!(driver->securityManager = virSecurityManagerNewStack(mgr,
1023
driver->securityManager = mgr;
1029
VIR_ERROR0(_("Failed to initialize security drivers"));
1030
virSecurityManagerFree(mgr);
1036
qemuCreateCapabilities(virCapsPtr oldcaps,
1037
struct qemud_driver *driver)
1041
/* Basic host arch / guest machine capabilities */
1042
if (!(caps = qemuCapsInit(oldcaps))) {
1043
virReportOOMError();
1047
if (driver->allowDiskFormatProbing) {
1048
caps->defaultDiskDriverName = NULL;
1049
caps->defaultDiskDriverType = NULL;
1051
caps->defaultDiskDriverName = "qemu";
1052
caps->defaultDiskDriverType = "raw";
1055
qemuDomainSetPrivateDataHooks(caps);
1056
qemuDomainSetNamespaceHooks(caps);
1058
if (virGetHostUUID(caps->host.host_uuid)) {
1059
qemuReportError(VIR_ERR_INTERNAL_ERROR,
1060
"%s", _("cannot get the host uuid"));
1064
/* Security driver data */
1065
const char *doi, *model;
1067
doi = virSecurityManagerGetDOI(driver->securityManager);
1068
model = virSecurityManagerGetModel(driver->securityManager);
1069
if (STRNEQ(model, "none")) {
1070
if (!(caps->host.secModel.model = strdup(model)))
1072
if (!(caps->host.secModel.doi = strdup(doi)))
1076
VIR_DEBUG("Initialized caps for security driver \"%s\" with "
1077
"DOI \"%s\"", model, doi);
1082
virReportOOMError();
1084
virCapabilitiesFree(caps);
1088
static void qemuDomainSnapshotLoad(void *payload,
1089
const char *name ATTRIBUTE_UNUSED,
1092
virDomainObjPtr vm = (virDomainObjPtr)payload;
1093
char *baseDir = (char *)data;
1094
char *snapDir = NULL;
1096
struct dirent *entry;
1100
virDomainSnapshotDefPtr def = NULL;
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"),
1110
VIR_INFO("Scanning for snapshots for domain %s in %s", vm->def->name,
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)));
1121
while ((entry = readdir(dir))) {
1122
if (entry->d_name[0] == '.')
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);
1129
if (virAsprintf(&fullpath, "%s/%s", snapDir, entry->d_name) < 0) {
1130
VIR_ERROR0(_("Failed to allocate memory for path"));
1134
ret = virFileReadAll(fullpath, 1024*1024*1, &xmlStr);
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)));
1143
def = virDomainSnapshotDefParseString(xmlStr, 0);
1145
/* Nothing we can do here, skip this one */
1146
VIR_ERROR(_("Failed to parse snapshot XML from file '%s'"), fullpath);
1152
virDomainSnapshotAssignDef(&vm->snapshots, def);
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.
1167
virResetLastError();
1173
virDomainObjUnlock(vm);
1179
* Initialization function for the QEmu daemon
1182
qemudStartup(int privileged) {
1184
char *driverConf = NULL;
1186
virConnectPtr conn = NULL;
1188
if (VIR_ALLOC(qemu_driver) < 0)
1191
if (virMutexInit(&qemu_driver->lock) < 0) {
1192
VIR_ERROR0(_("cannot initialize mutex"));
1193
VIR_FREE(qemu_driver);
1196
qemuDriverLock(qemu_driver);
1197
qemu_driver->privileged = privileged;
1199
/* Don't have a dom0 so start from 1 */
1200
qemu_driver->nextvmid = 1;
1202
if (virDomainObjListInit(&qemu_driver->domains) < 0)
1205
/* Init callback list */
1206
if (VIR_ALLOC(qemu_driver->domainEventCallbacks) < 0)
1208
if (!(qemu_driver->domainEventQueue = virDomainEventQueueNew()))
1211
if ((qemu_driver->domainEventTimer =
1212
virEventAddTimeout(-1, qemuDomainEventFlush, qemu_driver, NULL)) < 0)
1215
/* Allocate bitmap for vnc port reservation */
1216
if ((qemu_driver->reservedVNCPorts =
1217
virBitmapAlloc(QEMU_VNC_PORT_MAX - QEMU_VNC_PORT_MIN)) == NULL)
1220
/* read the host sysinfo */
1222
qemu_driver->hostsysinfo = virSysinfoRead();
1225
if (virAsprintf(&qemu_driver->logDir,
1226
"%s/log/libvirt/qemu", LOCALSTATEDIR) == -1)
1229
if ((base = strdup (SYSCONFDIR "/libvirt")) == NULL)
1232
if (virAsprintf(&qemu_driver->stateDir,
1233
"%s/run/libvirt/qemu", LOCALSTATEDIR) == -1)
1236
if (virAsprintf(&qemu_driver->libDir,
1237
"%s/lib/libvirt/qemu", LOCALSTATEDIR) == -1)
1240
if (virAsprintf(&qemu_driver->cacheDir,
1241
"%s/cache/libvirt/qemu", LOCALSTATEDIR) == -1)
1243
if (virAsprintf(&qemu_driver->saveDir,
1244
"%s/lib/libvirt/qemu/save", LOCALSTATEDIR) == -1)
1246
if (virAsprintf(&qemu_driver->snapshotDir,
1247
"%s/lib/libvirt/qemu/snapshot", LOCALSTATEDIR) == -1)
1249
if (virAsprintf(&qemu_driver->autoDumpPath,
1250
"%s/lib/libvirt/qemu/dump", LOCALSTATEDIR) == -1)
1253
uid_t uid = geteuid();
1254
char *userdir = virGetUserDirectory(uid);
1258
if (virAsprintf(&qemu_driver->logDir,
1259
"%s/.libvirt/qemu/log", userdir) == -1) {
1264
if (virAsprintf(&base, "%s/.libvirt", userdir) == -1) {
1270
if (virAsprintf(&qemu_driver->stateDir, "%s/qemu/run", base) == -1)
1272
if (virAsprintf(&qemu_driver->libDir, "%s/qemu/lib", base) == -1)
1274
if (virAsprintf(&qemu_driver->cacheDir, "%s/qemu/cache", base) == -1)
1276
if (virAsprintf(&qemu_driver->saveDir, "%s/qemu/save", base) == -1)
1278
if (virAsprintf(&qemu_driver->snapshotDir, "%s/qemu/snapshot", base) == -1)
1280
if (virAsprintf(&qemu_driver->autoDumpPath, "%s/qemu/dump", base) == -1)
1284
if (virFileMakePath(qemu_driver->stateDir) != 0) {
1286
VIR_ERROR(_("Failed to create state dir '%s': %s"),
1287
qemu_driver->stateDir, virStrerror(errno, ebuf, sizeof ebuf));
1290
if (virFileMakePath(qemu_driver->libDir) != 0) {
1292
VIR_ERROR(_("Failed to create lib dir '%s': %s"),
1293
qemu_driver->libDir, virStrerror(errno, ebuf, sizeof ebuf));
1296
if (virFileMakePath(qemu_driver->cacheDir) != 0) {
1298
VIR_ERROR(_("Failed to create cache dir '%s': %s"),
1299
qemu_driver->cacheDir, virStrerror(errno, ebuf, sizeof ebuf));
1302
if (virFileMakePath(qemu_driver->saveDir) != 0) {
1304
VIR_ERROR(_("Failed to create save dir '%s': %s"),
1305
qemu_driver->saveDir, virStrerror(errno, ebuf, sizeof ebuf));
1308
if (virFileMakePath(qemu_driver->snapshotDir) != 0) {
1310
VIR_ERROR(_("Failed to create save dir '%s': %s"),
1311
qemu_driver->snapshotDir, virStrerror(errno, ebuf, sizeof ebuf));
1314
if (virFileMakePath(qemu_driver->autoDumpPath) != 0) {
1316
VIR_ERROR(_("Failed to create dump dir '%s': %s"),
1317
qemu_driver->autoDumpPath, virStrerror(errno, ebuf, sizeof ebuf));
1321
/* Configuration paths are either ~/.libvirt/qemu/... (session) or
1322
* /etc/libvirt/qemu/... (system).
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)
1331
rc = virCgroupForDriver("qemu", &qemu_driver->cgroup, privileged, 1);
1334
VIR_INFO("Unable to create cgroup for driver: %s, disabling cgroups",
1335
virStrerror(-rc, buf, sizeof(buf)));
1338
if (qemudLoadDriverConfig(qemu_driver, driverConf) < 0) {
1341
VIR_FREE(driverConf);
1343
if (qemuSecurityInit(qemu_driver) < 0)
1346
if ((qemu_driver->caps = qemuCreateCapabilities(NULL,
1347
qemu_driver)) == NULL)
1350
if ((qemu_driver->activePciHostdevs = pciDeviceListNew()) == NULL)
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);
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);
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);
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);
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.
1384
* NB the check for '/', since user may config "" to disable hugepages
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)
1393
if ((rc = virFileMakePath(mempath)) != 0) {
1394
virReportSystemError(rc,
1395
_("unable to create hugepage path %s"), mempath);
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);
1408
qemu_driver->hugepage_path = mempath;
1411
/* Get all the running persistent or transient configs first */
1412
if (virDomainLoadAllConfigs(qemu_driver->caps,
1413
&qemu_driver->domains,
1414
qemu_driver->stateDir,
1419
conn = virConnectOpen(qemu_driver->privileged ?
1423
qemuReconnectDomains(conn, qemu_driver);
1425
/* Then inactive persistent configs */
1426
if (virDomainLoadAllConfigs(qemu_driver->caps,
1427
&qemu_driver->domains,
1428
qemu_driver->configDir,
1429
qemu_driver->autostartDir,
1434
virHashForEach(qemu_driver->domains.objs, qemuDomainSnapshotLoad,
1435
qemu_driver->snapshotDir);
1437
qemuDriverUnlock(qemu_driver);
1439
qemudAutostartConfigs(qemu_driver);
1441
qemu_driver->workerPool = virThreadPoolNew(0, 1, processWatchdogEvent, qemu_driver);
1442
if (!qemu_driver->workerPool)
1446
virConnectClose(conn);
1451
virReportOOMError();
1454
qemuDriverUnlock(qemu_driver);
1456
virConnectClose(conn);
1458
VIR_FREE(driverConf);
1463
static void qemudNotifyLoadDomain(virDomainObjPtr vm, int newVM, void *opaque)
1465
struct qemud_driver *driver = opaque;
1468
virDomainEventPtr event =
1469
virDomainEventNewFromObj(vm,
1470
VIR_DOMAIN_EVENT_DEFINED,
1471
VIR_DOMAIN_EVENT_DEFINED_ADDED);
1473
qemuDomainEventQueue(driver, event);
1480
* Function to restart the QEmu daemon, it will recheck the configuration
1481
* files and update its state and the networking
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);
1496
qemudAutostartConfigs(qemu_driver);
1504
* Checks if the QEmu daemon is active, i.e. has an active domain or
1507
* Returns 1 if active, 0 otherwise
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);
1526
* Shutdown the QEmu daemon, it will stop all active domains and networks
1529
qemudShutdown(void) {
1535
qemuDriverLock(qemu_driver);
1536
pciDeviceListFree(qemu_driver->activePciHostdevs);
1537
virCapabilitiesFree(qemu_driver->caps);
1539
virDomainObjListDeinit(&qemu_driver->domains);
1540
virBitmapFree(qemu_driver->reservedVNCPorts);
1542
virSysinfoDefFree(qemu_driver->hostsysinfo);
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);
1565
virSecurityManagerFree(qemu_driver->securityManager);
1567
ebtablesContextFree(qemu_driver->ebtables);
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);
1575
/* Free domain callback list */
1576
virDomainEventCallbackListFree(qemu_driver->domainEventCallbacks);
1577
virDomainEventQueueFree(qemu_driver->domainEventQueue);
1579
if (qemu_driver->domainEventTimer != -1)
1580
virEventRemoveTimeout(qemu_driver->domainEventTimer);
1582
if (qemu_driver->brctl)
1583
brShutdown(qemu_driver->brctl);
1585
virCgroupFree(&qemu_driver->cgroup);
1587
qemuDriverUnlock(qemu_driver);
1588
virMutexDestroy(&qemu_driver->lock);
1589
virThreadPoolFree(qemu_driver->workerPool);
1590
VIR_FREE(qemu_driver);
1595
typedef int qemuLogHandleOutput(virDomainObjPtr vm,
1600
* Returns -1 for error, 0 on success
1603
qemudReadLogOutput(virDomainObjPtr vm,
1607
qemuLogHandleOutput func,
1611
int retries = (timeout*10);
1616
ssize_t func_ret, ret;
1619
func_ret = func(vm, buf, fd);
1621
if (kill(vm->pid, 0) == -1 && errno == ESRCH)
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);
1628
virReportSystemError(errno,
1629
_("Failure while reading %s log output"),
1636
if (got == buflen-1) {
1637
qemuReportError(VIR_ERR_INTERNAL_ERROR,
1638
_("Out of space while reading %s log output: %s"),
1644
qemuReportError(VIR_ERR_INTERNAL_ERROR,
1645
_("Process exited while reading %s log output: %s"),
1657
qemuReportError(VIR_ERR_INTERNAL_ERROR,
1658
_("Timed out while reading %s log output: %s"),
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
1668
* char device redirected to /dev/pts/3
1670
* Returns -1 for error, 0 success, 1 continue reading
1673
qemudExtractTTYPath(const char *haystack,
1677
static const char needle[] = "char device redirected to";
1681
/* First look for our magic string */
1682
if (!(tmp = strstr(haystack + *offset, needle))) {
1685
tmp += sizeof(needle);
1689
* And look for first whitespace character and nul terminate
1690
* to mark end of the pty path
1693
if (c_isspace(*tmp)) {
1694
*path = strndup(dev, tmp-dev);
1695
if (*path == NULL) {
1696
virReportOOMError();
1700
/* ... now further update offset till we get EOL */
1701
*offset = tmp - haystack;
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
1717
qemudFindCharDevicePTYsMonitor(virDomainObjPtr vm,
1718
virHashTablePtr paths)
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) { \
1728
if (snprintf(id, sizeof(id), idprefix "%i", i) >= sizeof(id)) \
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); \
1740
/* 'info chardev' had no pty path for this chardev, */\
1741
/* but the log output had, so we're fine */ \
1746
VIR_FREE(chr->source.data.file.path); \
1747
chr->source.data.file.path = strdup(path); \
1749
if (chr->source.data.file.path == NULL) { \
1750
virReportOOMError(); \
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");
1767
qemudFindCharDevicePTYs(virDomainObjPtr vm,
1769
int fd ATTRIBUTE_UNUSED)
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.... */
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)
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)
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)
1811
static void qemudFreePtyPath(void *payload, const char *name ATTRIBUTE_UNUSED)
1817
qemuReadLogFD(int logfd, char *buf, int maxlen, int off)
1820
char *tmpbuf = buf + off;
1822
ret = saferead(logfd, tmpbuf, maxlen - off - 1);
1831
qemudWaitForMonitor(struct qemud_driver* driver,
1832
virDomainObjPtr vm, off_t pos)
1834
char buf[4096] = ""; /* Plenty of space to get startup greeting */
1837
virHashTablePtr paths = NULL;
1839
if ((logfd = qemudLogReadFD(driver->logDir, vm->def->name, pos)) < 0)
1842
if (qemudReadLogOutput(vm, logfd, buf, sizeof(buf),
1843
qemudFindCharDevicePTYs,
1847
VIR_DEBUG("Connect monitor to %p '%s'", vm, vm->def->name);
1848
if (qemuConnectMonitor(driver, vm) < 0) {
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();
1862
qemuDomainObjEnterMonitorWithDriver(driver, vm);
1863
qemuDomainObjPrivatePtr priv = vm->privateData;
1864
ret = qemuMonitorGetPtyPaths(priv->mon, paths);
1865
qemuDomainObjExitMonitorWithDriver(driver, vm);
1867
VIR_DEBUG("qemuMonitorGetPtyPaths returned %i", ret);
1869
ret = qemudFindCharDevicePTYsMonitor(vm, paths);
1874
virHashFree(paths, qemudFreePtyPath);
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"),
1888
if (VIR_CLOSE(logfd) < 0) {
1890
VIR_WARN("Unable to close logfile: %s",
1891
virStrerror(errno, ebuf, sizeof ebuf));
1898
qemuDetectVcpuPIDs(struct qemud_driver *driver,
1899
virDomainObjPtr vm) {
1900
pid_t *cpupids = NULL;
1902
qemuDomainObjPrivatePtr priv = vm->privateData;
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();
1910
priv->vcpupids[0] = vm->pid;
1914
/* What follows is now all KVM specific */
1916
qemuDomainObjEnterMonitorWithDriver(driver, vm);
1917
if ((ncpupids = qemuMonitorGetCPUInfo(priv->mon, &cpupids)) < 0) {
1918
qemuDomainObjExitMonitorWithDriver(driver, vm);
1921
qemuDomainObjExitMonitorWithDriver(driver, vm);
1923
/* Treat failure to get VCPU<->PID mapping as non-fatal */
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);
1936
priv->nvcpupids = ncpupids;
1937
priv->vcpupids = cpupids;
1942
* To be run between fork/exec of QEMU only
1945
qemudInitCpuAffinity(virDomainObjPtr vm)
1947
int i, hostcpus, maxcpu = QEMUD_CPUMASK_LEN;
1948
virNodeInfo nodeinfo;
1949
unsigned char *cpumap;
1952
DEBUG0("Setting CPU affinity");
1954
if (nodeGetInfo(NULL, &nodeinfo) < 0)
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)
1963
cpumaplen = VIR_CPU_MAPLEN(maxcpu);
1964
if (VIR_ALLOC_N(cpumap, cpumaplen) < 0) {
1965
virReportOOMError();
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);
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);
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
1988
if (virProcessInfoSetAffinity(0, /* Self */
1989
cpumap, cpumaplen, maxcpu) < 0) {
2000
qemuInitPasswords(virConnectPtr conn,
2001
struct qemud_driver *driver,
2003
unsigned long long qemuCmdFlags) {
2005
qemuDomainObjPrivatePtr priv = vm->privateData;
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);
2024
if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
2027
for (i = 0 ; i < vm->def->ndisks ; i++) {
2031
if (!vm->def->disks[i]->encryption ||
2032
!vm->def->disks[i]->src)
2035
if (getVolumeQcowPassphrase(conn,
2037
&secret, &secretLen) < 0)
2040
qemuDomainObjEnterMonitorWithDriver(driver, vm);
2041
ret = qemuMonitorSetDrivePassphrase(priv->mon,
2042
vm->def->disks[i]->info.alias,
2045
qemuDomainObjExitMonitorWithDriver(driver, vm);
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
2066
#define QEMU_PCI_PRODUCT_DISK_VIRTIO 0x1001
2068
#define QEMU_PCI_PRODUCT_BALLOON_VIRTIO 0x1002
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
2076
#define QEMU_PCI_PRODUCT_VGA_CIRRUS 0x00b8
2077
#define QEMU_PCI_PRODUCT_VGA_VMWARE 0x0405
2078
#define QEMU_PCI_PRODUCT_VGA_STDVGA 0x1111
2080
#define QEMU_PCI_PRODUCT_AUDIO_AC97 0x2415
2081
#define QEMU_PCI_PRODUCT_AUDIO_ES1370 0x5000
2083
#define QEMU_PCI_PRODUCT_CONTROLLER_PIIX 0x7010
2084
#define QEMU_PCI_PRODUCT_CONTROLLER_LSI 0x0012
2086
#define QEMU_PCI_PRODUCT_WATCHDOG_I63000ESB 0x25ab
2089
qemuAssignNextPCIAddress(virDomainDeviceInfo *info,
2092
qemuMonitorPCIAddress *addrs,
2098
VIR_DEBUG("Look for %x:%x out of %d", vendor, product, naddrs);
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);
2113
/* Blank it out so this device isn't matched again */
2114
addrs[i].vendor = 0;
2115
addrs[i].product = 0;
2117
if (info->type == VIR_DOMAIN_DEVICE_ADDRESS_TYPE_NONE)
2118
info->type = VIR_DOMAIN_DEVICE_ADDRESS_TYPE_PCI;
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;
2131
qemuGetPCIDiskVendorProduct(virDomainDiskDefPtr def,
2136
case VIR_DOMAIN_DISK_BUS_VIRTIO:
2137
*vendor = QEMU_PCI_VENDOR_REDHAT;
2138
*product = QEMU_PCI_PRODUCT_DISK_VIRTIO;
2149
qemuGetPCINetVendorProduct(virDomainNetDefPtr def,
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;
2172
VIR_INFO("Unexpected NIC model %s, cannot get PCI address",
2180
qemuGetPCIControllerVendorProduct(virDomainControllerDefPtr def,
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;
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 */
2195
case VIR_DOMAIN_CONTROLLER_TYPE_IDE:
2196
*vendor = QEMU_PCI_VENDOR_INTEL;
2197
*product = QEMU_PCI_PRODUCT_CONTROLLER_PIIX;
2201
VIR_INFO("Unexpected controller type %s, cannot get PCI address",
2202
virDomainControllerTypeToString(def->type));
2210
qemuGetPCIVideoVendorProduct(virDomainVideoDefPtr def,
2214
switch (def->type) {
2215
case VIR_DOMAIN_VIDEO_TYPE_CIRRUS:
2216
*vendor = QEMU_PCI_VENDOR_CIRRUS;
2217
*product = QEMU_PCI_PRODUCT_VGA_CIRRUS;
2220
case VIR_DOMAIN_VIDEO_TYPE_VGA:
2221
*vendor = QEMU_PCI_VENDOR_QEMU;
2222
*product = QEMU_PCI_PRODUCT_VGA_STDVGA;
2225
case VIR_DOMAIN_VIDEO_TYPE_VMVGA:
2226
*vendor = QEMU_PCI_VENDOR_VMWARE;
2227
*product = QEMU_PCI_PRODUCT_VGA_VMWARE;
2237
qemuGetPCISoundVendorProduct(virDomainSoundDefPtr def,
2241
switch (def->model) {
2242
case VIR_DOMAIN_SOUND_MODEL_ES1370:
2243
*vendor = QEMU_PCI_VENDOR_ENSONIQ;
2244
*product = QEMU_PCI_PRODUCT_AUDIO_ES1370;
2247
case VIR_DOMAIN_SOUND_MODEL_AC97:
2248
*vendor = QEMU_PCI_VENDOR_INTEL;
2249
*product = QEMU_PCI_PRODUCT_AUDIO_AC97;
2260
qemuGetPCIWatchdogVendorProduct(virDomainWatchdogDefPtr def,
2264
switch (def->model) {
2265
case VIR_DOMAIN_WATCHDOG_MODEL_I6300ESB:
2266
*vendor = QEMU_PCI_VENDOR_INTEL;
2267
*product = QEMU_PCI_PRODUCT_WATCHDOG_I63000ESB;
2279
qemuGetPCIMemballoonVendorProduct(virDomainMemballoonDefPtr def,
2283
switch (def->model) {
2284
case VIR_DOMAIN_MEMBALLOON_MODEL_VIRTIO:
2285
*vendor = QEMU_PCI_VENDOR_REDHAT;
2286
*product = QEMU_PCI_PRODUCT_BALLOON_VIRTIO;
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
2302
* XXXX this might not be a valid assumption if we assign
2303
* some static addrs on CLI. Have to check that...
2306
qemuDetectPCIAddresses(virDomainObjPtr vm,
2307
qemuMonitorPCIAddress *addrs,
2310
unsigned int vendor = 0, product = 0;
2313
/* XXX should all these vendor/product IDs be kept in the
2314
* actual device data structure instead ?
2317
for (i = 0 ; i < vm->def->ndisks ; i++) {
2318
if (qemuGetPCIDiskVendorProduct(vm->def->disks[i], &vendor, &product) < 0)
2321
if (qemuAssignNextPCIAddress(&(vm->def->disks[i]->info),
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);
2331
for (i = 0 ; i < vm->def->nnets ; i++) {
2332
if (qemuGetPCINetVendorProduct(vm->def->nets[i], &vendor, &product) < 0)
2335
if (qemuAssignNextPCIAddress(&(vm->def->nets[i]->info),
2337
addrs, naddrs) < 0) {
2338
qemuReportError(VIR_ERR_INTERNAL_ERROR,
2339
_("cannot find PCI address for %s NIC"),
2340
vm->def->nets[i]->model);
2345
for (i = 0 ; i < vm->def->ncontrollers ; i++) {
2346
if (qemuGetPCIControllerVendorProduct(vm->def->controllers[i], &vendor, &product) < 0)
2349
if (qemuAssignNextPCIAddress(&(vm->def->controllers[i]->info),
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));
2359
for (i = 0 ; i < vm->def->nvideos ; i++) {
2360
if (qemuGetPCIVideoVendorProduct(vm->def->videos[i], &vendor, &product) < 0)
2363
if (qemuAssignNextPCIAddress(&(vm->def->videos[i]->info),
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));
2373
for (i = 0 ; i < vm->def->nsounds ; i++) {
2374
if (qemuGetPCISoundVendorProduct(vm->def->sounds[i], &vendor, &product) < 0)
2377
if (qemuAssignNextPCIAddress(&(vm->def->sounds[i]->info),
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));
2388
if (vm->def->watchdog &&
2389
qemuGetPCIWatchdogVendorProduct(vm->def->watchdog, &vendor, &product) == 0) {
2390
if (qemuAssignNextPCIAddress(&(vm->def->watchdog->info),
2392
addrs, naddrs) < 0) {
2393
qemuReportError(VIR_ERR_INTERNAL_ERROR,
2394
_("cannot find PCI address for watchdog %s"),
2395
virDomainWatchdogModelTypeToString(vm->def->watchdog->model));
2400
if (vm->def->memballoon &&
2401
qemuGetPCIMemballoonVendorProduct(vm->def->memballoon, &vendor, &product) == 0) {
2402
if (qemuAssignNextPCIAddress(&(vm->def->memballoon->info),
2404
addrs, naddrs) < 0) {
2405
qemuReportError(VIR_ERR_INTERNAL_ERROR,
2406
_("cannot find PCI address for balloon %s"),
2407
virDomainMemballoonModelTypeToString(vm->def->memballoon->model));
2412
/* XXX console (virtio) */
2415
/* ... and now things we don't have in our xml */
2417
/* XXX USB controller ? */
2419
/* XXX what about other PCI devices (ie bridges) */
2425
qemuInitPCIAddresses(struct qemud_driver *driver,
2428
qemuDomainObjPrivatePtr priv = vm->privateData;
2431
qemuMonitorPCIAddress *addrs = NULL;
2433
qemuDomainObjEnterMonitorWithDriver(driver, vm);
2434
naddrs = qemuMonitorGetAllPCIAddresses(priv->mon,
2436
qemuDomainObjExitMonitorWithDriver(driver, vm);
2438
ret = qemuDetectPCIAddresses(vm, addrs, naddrs);
2446
static int qemudNextFreePort(struct qemud_driver *driver,
2450
for (i = startPort ; i < QEMU_VNC_PORT_MAX; i++) {
2453
struct sockaddr_in addr;
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);
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);
2470
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*)&reuse, sizeof(reuse)) < 0) {
2471
VIR_FORCE_CLOSE(fd);
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);
2486
VIR_FORCE_CLOSE(fd);
2488
if (errno == EADDRINUSE) {
2489
/* In use, try next */
2492
/* Some other bad failure, get out.. */
2500
qemuReturnPort(struct qemud_driver *driver,
2503
if (port < QEMU_VNC_PORT_MIN)
2506
if (virBitmapClearBit(driver->reservedVNCPorts,
2507
port - QEMU_VNC_PORT_MIN) < 0)
2508
VIR_DEBUG("Could not mark port %d as unused", port);
2513
qemuAssignPCIAddresses(virDomainDefPtr def)
2516
unsigned long long qemuCmdFlags = 0;
2517
qemuDomainPCIAddressSetPtr addrs = NULL;
2519
if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
2524
if (qemuCmdFlags & QEMUD_CMD_FLAG_DEVICE) {
2525
if (!(addrs = qemuDomainPCIAddressSetCreate(def)))
2528
if (qemuAssignDevicePCISlots(def, addrs) < 0)
2535
qemuDomainPCIAddressSetFree(addrs);
2542
qemuPrepareChardevDevice(virDomainDefPtr def ATTRIBUTE_UNUSED,
2543
virDomainChrDefPtr dev,
2544
void *opaque ATTRIBUTE_UNUSED)
2547
if (dev->source.type != VIR_DOMAIN_CHR_TYPE_FILE)
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);
2558
VIR_FORCE_CLOSE(fd);
2564
struct qemudHookData {
2567
struct qemud_driver *driver;
2570
static int qemudSecurityHook(void *data) {
2571
struct qemudHookData *h = data;
2573
/* This must take place before exec(), so that all QEMU
2574
* memory allocation is on the correct NUMA node
2576
if (qemuAddToCgroup(h->driver, h->vm->def) < 0)
2579
/* This must be done after cgroup placement to avoid resetting CPU
2581
if (qemudInitCpuAffinity(h->vm) < 0)
2584
if (virSecurityManagerSetProcessLabel(h->driver->securityManager, h->vm) < 0)
2591
qemuPrepareMonitorChr(struct qemud_driver *driver,
2592
virDomainChrSourceDefPtr monConfig,
2595
monConfig->type = VIR_DOMAIN_CHR_TYPE_UNIX;
2596
monConfig->data.nix.listen = true;
2598
if (virAsprintf(&monConfig->data.nix.path, "%s/%s.monitor",
2599
driver->libDir, vm) < 0) {
2600
virReportOOMError();
2607
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
2609
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
2613
#define START_POSTFIX ": starting up\n"
2614
#define SHUTDOWN_POSTFIX ": shutting down\n"
2616
static int qemudStartVMDaemon(virConnectPtr conn,
2617
struct qemud_driver *driver,
2619
const char *migrateFrom,
2622
const char *stdin_path,
2623
enum virVMOperationType vmop) {
2625
unsigned long long qemuCmdFlags;
2628
char *pidfile = NULL;
2631
qemuDomainObjPrivatePtr priv = vm->privateData;
2632
virCommandPtr cmd = NULL;
2634
struct qemudHookData hookData;
2635
hookData.conn = conn;
2637
hookData.driver = driver;
2639
DEBUG0("Beginning VM startup process");
2641
if (virDomainObjIsActive(vm)) {
2642
qemuReportError(VIR_ERR_OPERATION_INVALID,
2643
"%s", _("VM is already active"));
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
2651
DEBUG0("Setting current domain def as transient");
2652
if (virDomainObjSetDefTransient(driver->caps, vm, true) < 0)
2655
vm->def->id = driver->nextvmid++;
2657
/* Must be run before security labelling */
2658
DEBUG0("Preparing host devices");
2659
if (qemuPrepareHostDevices(driver, vm->def) < 0)
2662
DEBUG0("Preparing chr devices");
2663
if (virDomainChrDefForeach(vm->def,
2665
qemuPrepareChardevDevice,
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);
2676
qemuDomainSecurityLabelAudit(vm, true);
2678
DEBUG0("Generating setting domain security labels (if required)");
2679
if (virSecurityManagerSetAllLabel(driver->securityManager,
2680
vm, stdin_path) < 0)
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
2687
struct stat stdin_sb;
2689
DEBUG0("setting security label on pipe used for migration");
2691
if (fstat(stdin_fd, &stdin_sb) < 0) {
2692
virReportSystemError(errno,
2693
_("cannot stat fd %d"), stdin_fd);
2696
if (S_ISFIFO(stdin_sb.st_mode) &&
2697
virSecurityManagerSetFDLabel(driver->securityManager, vm, stdin_fd) < 0)
2701
/* Ensure no historical cgroup for this VM is lying around bogus
2703
DEBUG0("Ensuring no historical cgroup is lying around");
2704
qemuRemoveCgroup(driver, vm, 1);
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);
2712
qemuReportError(VIR_ERR_INTERNAL_ERROR,
2713
"%s", _("Unable to find an unused VNC port"));
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);
2722
qemuReportError(VIR_ERR_INTERNAL_ERROR,
2723
"%s", _("Unable to find an unused SPICE port"));
2727
if (driver->spiceTLS) {
2728
tlsPort = qemudNextFreePort(driver, port + 1);
2730
qemuReportError(VIR_ERR_INTERNAL_ERROR,
2731
"%s", _("Unable to find an unused SPICE TLS port"));
2732
qemuReturnPort(driver, port);
2737
vm->def->graphics[0]->data.spice.port = port;
2738
vm->def->graphics[0]->data.spice.tlsPort = tlsPort;
2742
if (virFileMakePath(driver->logDir) != 0) {
2743
virReportSystemError(errno,
2744
_("cannot create log directory %s"),
2749
DEBUG0("Creating domain log file");
2750
if ((logfile = qemudLogFD(driver, vm->def->name, false)) < 0)
2753
DEBUG0("Determining emulator version");
2754
if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
2759
DEBUG0("Setting up domain cgroup (if required)");
2760
if (qemuSetupCgroup(driver, vm) < 0)
2763
if (VIR_ALLOC(priv->monConfig) < 0) {
2764
virReportOOMError();
2768
DEBUG0("Preparing monitor state");
2769
if (qemuPrepareMonitorChr(driver, priv->monConfig, vm->def->name) < 0)
2773
if (qemuCmdFlags & QEMUD_CMD_FLAG_MONITOR_JSON)
2779
priv->monitor_warned = 0;
2780
priv->gotShutdown = false;
2782
if ((ret = virFileDeletePid(driver->stateDir, vm->def->name)) != 0) {
2783
virReportSystemError(ret,
2784
_("Cannot remove stale PID file for %s"),
2789
if (!(pidfile = virFilePid(driver->stateDir, vm->def->name))) {
2790
virReportSystemError(errno,
2791
"%s", _("Failed to build pidfile path."));
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
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;
2809
if (!(priv->pciaddrs = qemuDomainPCIAddressSetCreate(vm->def)))
2813
/* Assign any remaining addresses */
2814
if (qemuAssignDevicePCISlots(vm->def, priv->pciaddrs) < 0)
2817
priv->persistentAddrs = 1;
2819
priv->persistentAddrs = 0;
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)))
2829
if (qemuDomainSnapshotSetCurrentInactive(vm, driver->snapshotDir) < 0)
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);
2837
hookret = virHookCall(VIR_HOOK_DRIVER_QEMU, vm->def->name,
2838
VIR_HOOK_QEMU_OP_START, VIR_HOOK_SUBOP_BEGIN, NULL, xml);
2842
* If the script raised an error abort the launch
2848
if ((timestamp = virTimestamp()) == NULL) {
2849
virReportOOMError();
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));
2858
VIR_FREE(timestamp);
2861
virCommandWriteArgLog(cmd, logfile);
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));
2867
VIR_DEBUG("Clear emulator capabilities: %d",
2868
driver->clearEmulatorCapabilities);
2869
if (driver->clearEmulatorCapabilities)
2870
virCommandClearCaps(cmd);
2872
virCommandSetPreExecHook(cmd, qemudSecurityHook, &hookData);
2874
virCommandSetOutputFD(cmd, &logfile);
2875
virCommandSetErrorFD(cmd, &logfile);
2876
virCommandNonblockingFDs(cmd);
2877
virCommandSetPidFile(cmd, pidfile);
2878
virCommandDaemonize(cmd);
2880
ret = virCommandRun(cmd, NULL);
2883
/* wait for qemu process to to show up */
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);
2891
} else if (ret == -2) {
2893
* XXX this is bogus. It isn't safe to set vm->pid = child
2894
* because the child no longer exists.
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).
2901
* Pretend like things succeeded, and let 'WaitForMonitor' report
2902
* the log contents for us.
2910
start_paused = true;
2911
vm->state = start_paused ? VIR_DOMAIN_PAUSED : VIR_DOMAIN_RUNNING;
2913
if (ret == -1) /* The VM failed to start; tear filters before taps */
2914
virDomainConfVMNWFilterTeardown(vm);
2916
if (ret == -1) /* The VM failed to start */
2919
DEBUG0("Waiting for monitor to show up");
2920
if (qemudWaitForMonitor(driver, vm, pos) < 0)
2923
DEBUG0("Detecting VCPU PIDs");
2924
if (qemuDetectVcpuPIDs(driver, vm) < 0)
2927
DEBUG0("Setting any required VM passwords");
2928
if (qemuInitPasswords(conn, driver, vm, qemuCmdFlags) < 0)
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)
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);
2945
qemuDomainObjExitMonitorWithDriver(driver, vm);
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"));
2959
DEBUG0("Writing domain status to disk");
2960
if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
2963
virCommandFree(cmd);
2964
VIR_FORCE_CLOSE(logfile);
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);
2979
static void qemudShutdownVMDaemon(struct qemud_driver *driver,
2984
qemuDomainObjPrivatePtr priv = vm->privateData;
2985
virErrorPtr orig_err;
2986
virDomainDefPtr def;
2992
VIR_DEBUG("Shutting down VM '%s' pid=%d migrated=%d",
2993
vm->def->name, vm->pid, migrated);
2995
if (!virDomainObjIsActive(vm)) {
2996
VIR_DEBUG("VM '%s' not active", vm->def->name);
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));
3006
if ((timestamp = virTimestamp()) == NULL) {
3007
virReportOOMError();
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));
3016
VIR_FREE(timestamp);
3019
if (VIR_CLOSE(logfile) < 0)
3020
VIR_WARN("Unable to close logfile: %s",
3021
virStrerror(errno, ebuf, sizeof ebuf));
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();
3028
virDomainConfVMNWFilterTeardown(vm);
3030
if (driver->macFilter) {
3032
for (i = 0 ; i < def->nnets ; i++) {
3033
virDomainNetDefPtr net = def->nets[i];
3034
if (net->ifname == NULL)
3036
if ((errno = networkDisallowMacOnPort(driver, net->ifname,
3038
virReportSystemError(errno,
3039
_("failed to remove ebtables rule to allow MAC address on '%s'"),
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);
3053
qemuMonitorClose(priv->mon);
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;
3062
/* shut it off for sure */
3063
virKillProcess(vm->pid, SIGKILL);
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);
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);
3075
/* Reset Security Labels */
3076
virSecurityManagerRestoreAllLabel(driver->securityManager,
3078
virSecurityManagerReleaseLabel(driver->securityManager, vm);
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);
3087
virDomainDefClearDeviceAliases(vm->def);
3088
if (!priv->persistentAddrs) {
3089
virDomainDefClearPCIAddresses(vm->def);
3090
qemuDomainPCIAddressSetFree(priv->pciaddrs);
3091
priv->pciaddrs = NULL;
3094
qemuDomainReAttachHostDevices(driver, 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);
3109
if ((ret = qemuRemoveCgroup(driver, vm, 0)) < 0) {
3110
if (ret == -EBUSY && (retries++ < 5)) {
3114
VIR_WARN("Failed to remove cgroup for %s",
3118
qemudRemoveDomainStatus(driver, vm);
3120
/* Remove VNC port from port reservation bitmap, but only if it was
3121
reserved by the driver (autoport=yes)
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);
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);
3137
vm->state = VIR_DOMAIN_SHUTOFF;
3138
VIR_FREE(priv->vcpupids);
3139
priv->nvcpupids = 0;
3142
virDomainDefFree(vm->def);
3143
vm->def = vm->newDef;
3149
virSetError(orig_err);
3150
virFreeError(orig_err);
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;
3161
conn->uri = xmlParseURI(qemu_driver->privileged ?
3165
virReportOOMError();
3166
return VIR_DRV_OPEN_ERROR;
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;
3174
/* Allow remote driver to deal with URIs with hostname server */
3175
if (conn->uri->server != NULL)
3176
return VIR_DRV_OPEN_DECLINED;
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;
3184
if (conn->uri->path == NULL) {
3185
qemuReportError(VIR_ERR_INTERNAL_ERROR,
3186
_("no QEMU URI path given, try %s"),
3187
qemu_driver->privileged
3189
: "qemu:///session");
3190
return VIR_DRV_OPEN_ERROR;
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"),
3199
return VIR_DRV_OPEN_ERROR;
3202
if (STRNEQ (conn->uri->path, "/session")) {
3203
qemuReportError(VIR_ERR_INTERNAL_ERROR,
3204
_("unexpected QEMU URI path '%s', try qemu:///session"),
3206
return VIR_DRV_OPEN_ERROR;
3210
conn->privateData = qemu_driver;
3212
return VIR_DRV_OPEN_SUCCESS;
3215
static int qemudClose(virConnectPtr conn) {
3216
struct qemud_driver *driver = conn->privateData;
3218
/* Get rid of callbacks registered for this conn */
3219
qemuDriverLock(driver);
3220
virDomainEventCallbackListRemoveConn(conn, driver->domainEventCallbacks);
3221
qemuDriverUnlock(driver);
3223
conn->privateData = NULL;
3228
/* Which features are supported by this driver? */
3230
qemudSupportsFeature (virConnectPtr conn ATTRIBUTE_UNUSED, int feature)
3233
case VIR_DRV_FEATURE_MIGRATION_V2:
3234
case VIR_DRV_FEATURE_MIGRATION_P2P:
3241
static const char *qemudGetType(virConnectPtr conn ATTRIBUTE_UNUSED) {
3246
static int qemuIsSecure(virConnectPtr conn ATTRIBUTE_UNUSED)
3248
/* Trivially secure, since always inside the daemon */
3252
static int qemuIsEncrypted(virConnectPtr conn ATTRIBUTE_UNUSED)
3254
/* Not encrypted, but remote driver takes care of that */
3259
static int kvmGetMaxVCPUs(void) {
3264
fd = open(KVM_DEVICE, O_RDONLY);
3266
virReportSystemError(errno, _("Unable to open %s"), KVM_DEVICE);
3270
r = ioctl(fd, KVM_CHECK_EXTENSION, KVM_CAP_NR_VCPUS);
3274
VIR_FORCE_CLOSE(fd);
3280
qemuGetSysinfo(virConnectPtr conn, unsigned int flags)
3282
struct qemud_driver *driver = conn->privateData;
3284
virCheckFlags(0, NULL);
3286
if (!driver->hostsysinfo) {
3287
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
3288
_("Host SMBIOS information is not available"));
3292
return virSysinfoFormat(driver->hostsysinfo, "");
3295
static int qemudGetMaxVCPUs(virConnectPtr conn ATTRIBUTE_UNUSED, const char *type) {
3299
if (STRCASEEQ(type, "qemu"))
3302
if (STRCASEEQ(type, "kvm"))
3303
return kvmGetMaxVCPUs();
3305
if (STRCASEEQ(type, "kqemu"))
3308
qemuReportError(VIR_ERR_INVALID_ARG,
3309
_("unknown type '%s'"), type);
3314
static char *qemudGetCapabilities(virConnectPtr conn) {
3315
struct qemud_driver *driver = conn->privateData;
3316
virCapsPtr caps = NULL;
3319
qemuDriverLock(driver);
3321
if ((caps = qemuCreateCapabilities(qemu_driver->caps,
3322
qemu_driver)) == NULL) {
3323
virCapabilitiesFree(caps);
3327
virCapabilitiesFree(qemu_driver->caps);
3328
qemu_driver->caps = caps;
3330
if ((xml = virCapabilitiesFormatXML(driver->caps)) == NULL)
3331
virReportOOMError();
3334
qemuDriverUnlock(driver);
3341
qemudGetProcessInfo(unsigned long long *cpuTime, int *lastCpu, int pid,
3346
unsigned long long usertime, systime;
3351
ret = virAsprintf(&proc, "/proc/%d/task/%d/stat", pid, tid);
3353
ret = virAsprintf(&proc, "/proc/%d/stat", pid);
3357
if (!(pidinfo = fopen(proc, "r"))) {
3358
/* VM probably shut down, so fake 0 */
3368
/* See 'man proc' for information about what all these fields are. We're
3369
* only interested in a very few of them */
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");
3385
* We want nanoseconds
3386
* _SC_CLK_TCK is jiffies per second
3387
* So calulate thus....
3390
*cpuTime = 1000ull * 1000ull * 1000ull * (usertime + systime) / (unsigned long long)sysconf(_SC_CLK_TCK);
3395
VIR_DEBUG("Got status for %d/%d user=%llu sys=%llu cpu=%d",
3396
pid, tid, usertime, systime, cpu);
3398
VIR_FORCE_FCLOSE(pidinfo);
3404
static virDomainPtr qemudDomainLookupByID(virConnectPtr conn,
3406
struct qemud_driver *driver = conn->privateData;
3408
virDomainPtr dom = NULL;
3410
qemuDriverLock(driver);
3411
vm = virDomainFindByID(&driver->domains, id);
3412
qemuDriverUnlock(driver);
3415
qemuReportError(VIR_ERR_NO_DOMAIN,
3416
_("no domain with matching id %d"), id);
3420
dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3421
if (dom) dom->id = vm->def->id;
3425
virDomainObjUnlock(vm);
3429
static virDomainPtr qemudDomainLookupByUUID(virConnectPtr conn,
3430
const unsigned char *uuid) {
3431
struct qemud_driver *driver = conn->privateData;
3433
virDomainPtr dom = NULL;
3435
qemuDriverLock(driver);
3436
vm = virDomainFindByUUID(&driver->domains, uuid);
3437
qemuDriverUnlock(driver);
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);
3447
dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3448
if (dom) dom->id = vm->def->id;
3452
virDomainObjUnlock(vm);
3456
static virDomainPtr qemudDomainLookupByName(virConnectPtr conn,
3458
struct qemud_driver *driver = conn->privateData;
3460
virDomainPtr dom = NULL;
3462
qemuDriverLock(driver);
3463
vm = virDomainFindByName(&driver->domains, name);
3464
qemuDriverUnlock(driver);
3467
qemuReportError(VIR_ERR_NO_DOMAIN,
3468
_("no domain with matching name '%s'"), name);
3472
dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3473
if (dom) dom->id = vm->def->id;
3477
virDomainObjUnlock(vm);
3482
static int qemuDomainIsActive(virDomainPtr dom)
3484
struct qemud_driver *driver = dom->conn->privateData;
3485
virDomainObjPtr obj;
3488
qemuDriverLock(driver);
3489
obj = virDomainFindByUUID(&driver->domains, dom->uuid);
3490
qemuDriverUnlock(driver);
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);
3498
ret = virDomainObjIsActive(obj);
3502
virDomainObjUnlock(obj);
3506
static int qemuDomainIsPersistent(virDomainPtr dom)
3508
struct qemud_driver *driver = dom->conn->privateData;
3509
virDomainObjPtr obj;
3512
qemuDriverLock(driver);
3513
obj = virDomainFindByUUID(&driver->domains, dom->uuid);
3514
qemuDriverUnlock(driver);
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);
3522
ret = obj->persistent;
3526
virDomainObjUnlock(obj);
3530
static int qemuDomainIsUpdated(virDomainPtr dom)
3532
struct qemud_driver *driver = dom->conn->privateData;
3533
virDomainObjPtr obj;
3536
qemuDriverLock(driver);
3537
obj = virDomainFindByUUID(&driver->domains, dom->uuid);
3538
qemuDriverUnlock(driver);
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);
3550
virDomainObjUnlock(obj);
3554
static int qemudGetVersion(virConnectPtr conn, unsigned long *version) {
3555
struct qemud_driver *driver = conn->privateData;
3558
qemuDriverLock(driver);
3559
if (qemuCapsExtractVersion(driver->caps, &driver->qemuVersion) < 0)
3562
*version = driver->qemuVersion;
3566
qemuDriverUnlock(driver);
3570
static int qemudListDomains(virConnectPtr conn, int *ids, int nids) {
3571
struct qemud_driver *driver = conn->privateData;
3574
qemuDriverLock(driver);
3575
n = virDomainObjListGetActiveIDs(&driver->domains, ids, nids);
3576
qemuDriverUnlock(driver);
3581
static int qemudNumDomains(virConnectPtr conn) {
3582
struct qemud_driver *driver = conn->privateData;
3585
qemuDriverLock(driver);
3586
n = virDomainObjListNumOfDomains(&driver->domains, 1);
3587
qemuDriverUnlock(driver);
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;
3600
virCheckFlags(VIR_DOMAIN_START_PAUSED, NULL);
3602
qemuDriverLock(driver);
3603
if (!(def = virDomainDefParseString(driver->caps, xml,
3604
VIR_DOMAIN_XML_INACTIVE)))
3607
if (virSecurityManagerVerify(driver->securityManager, def) < 0)
3610
if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
3613
if (qemudCanonicalizeMachine(driver, def) < 0)
3616
if (qemuAssignPCIAddresses(def) < 0)
3619
if (!(vm = virDomainAssignDef(driver->caps,
3626
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3627
goto cleanup; /* XXXX free the 'vm' we created ? */
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,
3640
event = virDomainEventNewFromObj(vm,
3641
VIR_DOMAIN_EVENT_STARTED,
3642
VIR_DOMAIN_EVENT_STARTED_BOOTED);
3643
qemuDomainStartAudit(vm, "booted", true);
3645
dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
3646
if (dom) dom->id = vm->def->id;
3649
qemuDomainObjEndJob(vm) == 0)
3653
virDomainDefFree(def);
3655
virDomainObjUnlock(vm);
3657
qemuDomainEventQueue(driver, event);
3658
qemuDriverUnlock(driver);
3663
static int qemudDomainSuspend(virDomainPtr dom) {
3664
struct qemud_driver *driver = dom->conn->privateData;
3667
virDomainEventPtr event = NULL;
3668
qemuDomainObjPrivatePtr priv;
3670
qemuDriverLock(driver);
3671
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
3680
if (!virDomainObjIsActive(vm)) {
3681
qemuReportError(VIR_ERR_OPERATION_INVALID,
3682
"%s", _("domain is not running"));
3686
priv = vm->privateData;
3688
if (priv->jobActive == QEMU_JOB_MIGRATION_OUT) {
3689
if (vm->state != VIR_DOMAIN_PAUSED) {
3690
VIR_DEBUG("Requesting domain pause on %s",
3692
priv->jobSignals |= QEMU_JOB_SIGNAL_SUSPEND;
3697
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3700
if (!virDomainObjIsActive(vm)) {
3701
qemuReportError(VIR_ERR_OPERATION_INVALID,
3702
"%s", _("domain is not running"));
3705
if (vm->state != VIR_DOMAIN_PAUSED) {
3706
if (doStopCPUs(driver, vm) < 0) {
3709
event = virDomainEventNewFromObj(vm,
3710
VIR_DOMAIN_EVENT_SUSPENDED,
3711
VIR_DOMAIN_EVENT_SUSPENDED_PAUSED);
3713
if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
3719
if (qemuDomainObjEndJob(vm) == 0)
3724
virDomainObjUnlock(vm);
3727
qemuDomainEventQueue(driver, event);
3728
qemuDriverUnlock(driver);
3733
static int qemudDomainResume(virDomainPtr dom) {
3734
struct qemud_driver *driver = dom->conn->privateData;
3737
virDomainEventPtr event = NULL;
3739
qemuDriverLock(driver);
3740
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
3750
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3753
if (!virDomainObjIsActive(vm)) {
3754
qemuReportError(VIR_ERR_OPERATION_INVALID,
3755
"%s", _("domain is not running"));
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"));
3765
event = virDomainEventNewFromObj(vm,
3766
VIR_DOMAIN_EVENT_RESUMED,
3767
VIR_DOMAIN_EVENT_RESUMED_UNPAUSED);
3769
if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
3774
if (qemuDomainObjEndJob(vm) == 0)
3779
virDomainObjUnlock(vm);
3781
qemuDomainEventQueue(driver, event);
3782
qemuDriverUnlock(driver);
3787
static int qemudDomainShutdown(virDomainPtr dom) {
3788
struct qemud_driver *driver = dom->conn->privateData;
3792
qemuDriverLock(driver);
3793
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3794
qemuDriverUnlock(driver);
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);
3804
if (qemuDomainObjBeginJob(vm) < 0)
3807
if (!virDomainObjIsActive(vm)) {
3808
qemuReportError(VIR_ERR_OPERATION_INVALID,
3809
"%s", _("domain is not running"));
3813
qemuDomainObjPrivatePtr priv = vm->privateData;
3814
qemuDomainObjEnterMonitor(vm);
3815
ret = qemuMonitorSystemPowerdown(priv->mon);
3816
qemuDomainObjExitMonitor(vm);
3819
if (qemuDomainObjEndJob(vm) == 0)
3824
virDomainObjUnlock(vm);
3829
static int qemudDomainDestroy(virDomainPtr dom) {
3830
struct qemud_driver *driver = dom->conn->privateData;
3833
virDomainEventPtr event = NULL;
3835
qemuDriverLock(driver);
3836
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
3845
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
3848
if (!virDomainObjIsActive(vm)) {
3849
qemuReportError(VIR_ERR_OPERATION_INVALID,
3850
"%s", _("domain is not running"));
3854
qemudShutdownVMDaemon(driver, vm, 0);
3855
event = virDomainEventNewFromObj(vm,
3856
VIR_DOMAIN_EVENT_STOPPED,
3857
VIR_DOMAIN_EVENT_STOPPED_DESTROYED);
3858
qemuDomainStopAudit(vm, "destroyed");
3860
if (!vm->persistent) {
3861
if (qemuDomainObjEndJob(vm) > 0)
3862
virDomainRemoveInactive(&driver->domains,
3870
qemuDomainObjEndJob(vm) == 0)
3875
virDomainObjUnlock(vm);
3877
qemuDomainEventQueue(driver, event);
3878
qemuDriverUnlock(driver);
3883
static char *qemudDomainGetOSType(virDomainPtr dom) {
3884
struct qemud_driver *driver = dom->conn->privateData;
3888
qemuDriverLock(driver);
3889
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3890
qemuDriverUnlock(driver);
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);
3899
if (!(type = strdup(vm->def->os.type)))
3900
virReportOOMError();
3904
virDomainObjUnlock(vm);
3908
/* Returns max memory in kb, 0 if error */
3909
static unsigned long qemudDomainGetMaxMemory(virDomainPtr dom) {
3910
struct qemud_driver *driver = dom->conn->privateData;
3912
unsigned long ret = 0;
3914
qemuDriverLock(driver);
3915
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3916
qemuDriverUnlock(driver);
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);
3926
ret = vm->def->mem.max_balloon;
3930
virDomainObjUnlock(vm);
3934
static int qemudDomainSetMemory(virDomainPtr dom, unsigned long newmem) {
3935
struct qemud_driver *driver = dom->conn->privateData;
3936
qemuDomainObjPrivatePtr priv;
3940
qemuDriverLock(driver);
3941
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
3942
qemuDriverUnlock(driver);
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);
3951
if (newmem > vm->def->mem.max_balloon) {
3952
qemuReportError(VIR_ERR_INVALID_ARG,
3953
"%s", _("cannot set memory higher than max memory"));
3957
if (qemuDomainObjBeginJob(vm) < 0)
3960
if (!virDomainObjIsActive(vm)) {
3961
qemuReportError(VIR_ERR_OPERATION_INVALID,
3962
"%s", _("domain is not running"));
3966
priv = vm->privateData;
3967
qemuDomainObjEnterMonitor(vm);
3968
r = qemuMonitorSetBalloon(priv->mon, newmem);
3969
qemuDomainObjExitMonitor(vm);
3973
/* Lack of balloon support is a fatal error */
3975
qemuReportError(VIR_ERR_OPERATION_INVALID,
3976
"%s", _("cannot set memory of an active domain"));
3982
if (qemuDomainObjEndJob(vm) == 0)
3987
virDomainObjUnlock(vm);
3991
static int qemudDomainGetInfo(virDomainPtr dom,
3992
virDomainInfoPtr info) {
3993
struct qemud_driver *driver = dom->conn->privateData;
3997
unsigned long balloon;
3999
qemuDriverLock(driver);
4000
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
4001
qemuDriverUnlock(driver);
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);
4010
info->state = vm->state;
4012
if (!virDomainObjIsActive(vm)) {
4015
if (qemudGetProcessInfo(&(info->cpuTime), NULL, vm->pid, 0) < 0) {
4016
qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
4017
_("cannot read cputime for domain"));
4022
info->maxMem = vm->def->mem.max_balloon;
4024
if (virDomainObjIsActive(vm)) {
4025
qemuDomainObjPrivatePtr priv = vm->privateData;
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)
4033
if (!virDomainObjIsActive(vm))
4036
qemuDomainObjEnterMonitor(vm);
4037
err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
4038
qemuDomainObjExitMonitor(vm);
4040
if (qemuDomainObjEndJob(vm) == 0) {
4048
/* Balloon not supported, so maxmem is always the allocation */
4049
info->memory = vm->def->mem.max_balloon;
4051
info->memory = balloon;
4053
info->memory = vm->def->mem.cur_balloon;
4056
info->memory = vm->def->mem.cur_balloon;
4059
info->nrVirtCpu = vm->def->vcpus;
4064
virDomainObjUnlock(vm);
4069
/** qemuDomainMigrateOffline:
4070
* Pause domain for non-live migration.
4073
qemuDomainMigrateOffline(struct qemud_driver *driver,
4078
ret = doStopCPUs(driver, vm);
4080
virDomainEventPtr event;
4082
event = virDomainEventNewFromObj(vm,
4083
VIR_DOMAIN_EVENT_SUSPENDED,
4084
VIR_DOMAIN_EVENT_SUSPENDED_MIGRATED);
4086
qemuDomainEventQueue(driver, event);
4094
qemuDomainWaitForMigrationComplete(struct qemud_driver *driver, virDomainObjPtr vm)
4098
unsigned long long memProcessed;
4099
unsigned long long memRemaining;
4100
unsigned long long memTotal;
4101
qemuDomainObjPrivatePtr priv = vm->privateData;
4103
priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
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 };
4112
switch (priv->jobActive) {
4113
case QEMU_JOB_MIGRATION_OUT:
4114
job = _("migration job");
4117
job = _("domain save job");
4120
job = _("domain core dump job");
4127
if (!virDomainObjIsActive(vm)) {
4128
qemuReportError(VIR_ERR_INTERNAL_ERROR, _("%s: %s"),
4129
job, _("guest unexpectedly quit"));
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);
4140
VIR_WARN0("Unable to cancel job");
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;
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);
4157
VIR_WARN0("Unable to set migration downtime");
4160
/* Repeat check because the job signals might have caused
4163
if (!virDomainObjIsActive(vm)) {
4164
qemuReportError(VIR_ERR_INTERNAL_ERROR, _("%s: %s"),
4165
job, _("guest unexpectedly quit"));
4169
qemuDomainObjEnterMonitorWithDriver(driver, vm);
4170
rc = qemuMonitorGetMigrationStatus(priv->mon,
4175
qemuDomainObjExitMonitorWithDriver(driver, vm);
4178
priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
4182
if (gettimeofday(&now, NULL) < 0) {
4183
priv->jobInfo.type = VIR_DOMAIN_JOB_FAILED;
4184
virReportSystemError(errno, "%s",
4185
_("cannot get time of day"));
4188
priv->jobInfo.timeElapsed = timeval_to_ms(now) - priv->jobStart;
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"));
4197
case QEMU_MONITOR_MIGRATION_STATUS_ACTIVE:
4198
priv->jobInfo.dataTotal = memTotal;
4199
priv->jobInfo.dataRemaining = memRemaining;
4200
priv->jobInfo.dataProcessed = memProcessed;
4202
priv->jobInfo.memTotal = memTotal;
4203
priv->jobInfo.memRemaining = memRemaining;
4204
priv->jobInfo.memProcessed = memProcessed;
4207
case QEMU_MONITOR_MIGRATION_STATUS_COMPLETED:
4208
priv->jobInfo.type = VIR_DOMAIN_JOB_COMPLETED;
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"));
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"));
4225
virDomainObjUnlock(vm);
4226
qemuDriverUnlock(driver);
4228
nanosleep(&ts, NULL);
4230
qemuDriverLock(driver);
4231
virDomainObjLock(vm);
4239
#define QEMUD_SAVE_MAGIC "LibvirtQemudSave"
4240
#define QEMUD_SAVE_VERSION 2
4242
enum qemud_save_formats {
4243
QEMUD_SAVE_FORMAT_RAW = 0,
4244
QEMUD_SAVE_FORMAT_GZIP = 1,
4245
QEMUD_SAVE_FORMAT_BZIP2 = 2,
4247
* Deprecated by xz and never used as part of a release
4248
* QEMUD_SAVE_FORMAT_LZMA
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. */
4256
QEMUD_SAVE_FORMAT_LAST
4259
VIR_ENUM_DECL(qemudSaveCompression)
4260
VIR_ENUM_IMPL(qemudSaveCompression, QEMUD_SAVE_FORMAT_LAST,
4267
struct qemud_save_header {
4268
char magic[sizeof(QEMUD_SAVE_MAGIC)-1];
4276
struct fileOpHookData {
4280
struct qemud_save_header *header;
4283
/* return -errno on failure, or 0 on success */
4284
static int qemudDomainSaveFileOpHook(int fd, void *data) {
4285
struct fileOpHookData *hdata = data;
4288
if (safewrite(fd, hdata->header, sizeof(*hdata->header)) != sizeof(*hdata->header)) {
4290
qemuReportError(VIR_ERR_OPERATION_FAILED,
4291
_("failed to write header to domain save file '%s'"),
4296
if (safewrite(fd, hdata->xml, hdata->header->xml_len) != hdata->header->xml_len) {
4298
qemuReportError(VIR_ERR_OPERATION_FAILED,
4299
_("failed to write xml to '%s'"), hdata->path);
4306
/* This internal function expects the driver lock to already be held on
4307
* entry and the vm must be active.
4309
static int qemudDomainSaveFlag(struct qemud_driver *driver, virDomainPtr dom,
4310
virDomainObjPtr vm, const char *path,
4314
struct qemud_save_header header;
4315
struct fileOpHookData hdata;
4316
int bypassSecurityDriver = 0;
4319
virDomainEventPtr event = NULL;
4320
qemuDomainObjPrivatePtr priv;
4323
unsigned long long offset;
4324
virCgroupPtr cgroup = NULL;
4326
memset(&header, 0, sizeof(header));
4327
memcpy(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic));
4328
header.version = QEMUD_SAVE_VERSION;
4330
header.compressed = compressed;
4332
priv = vm->privateData;
4334
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
4337
priv->jobActive = QEMU_JOB_SAVE;
4339
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
4340
priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
4343
if (vm->state == VIR_DOMAIN_RUNNING) {
4344
header.was_running = 1;
4345
if (doStopCPUs(driver, vm) < 0)
4348
if (!virDomainObjIsActive(vm)) {
4349
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4350
_("guest unexpectedly quit"));
4355
/* Get XML for the domain */
4356
xml = virDomainDefFormat(vm->def, VIR_DOMAIN_XML_SECURE);
4358
qemuReportError(VIR_ERR_OPERATION_FAILED,
4359
"%s", _("failed to get domain xml"));
4362
header.xml_len = strlen(xml) + 1;
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 */
4374
is_reg = S_ISREG(sb.st_mode);
4377
offset = sizeof(header) + header.xml_len;
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.
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);
4389
if (VIR_REALLOC_N(xml, header.xml_len + pad) < 0) {
4390
virReportOOMError();
4393
memset(xml + header.xml_len, 0, pad);
4395
header.xml_len += pad;
4398
/* Setup hook data needed by virFileOperation hook function */
4402
hdata.header = &header;
4404
/* Write header to file, followed by XML */
4406
/* First try creating the file as root */
4408
int fd = open(path, O_WRONLY | O_TRUNC);
4410
virReportSystemError(errno, _("unable to open %s"), path);
4413
if (qemudDomainSaveFileOpHook(fd, &hdata) < 0) {
4414
VIR_FORCE_CLOSE(fd);
4417
if (VIR_CLOSE(fd) < 0) {
4418
virReportSystemError(errno, _("unable to close %s"), path);
4422
if ((rc = virFileOperation(path, O_CREAT|O_TRUNC|O_WRONLY,
4425
qemudDomainSaveFileOpHook, &hdata,
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 */
4434
if (((rc != -EACCES) && (rc != -EPERM)) ||
4435
driver->user == getuid()) {
4436
virReportSystemError(-rc, _("Failed to create domain save file '%s'"),
4441
/* On Linux we can also verify the FS-type of the directory. */
4442
switch (virStorageFileIsSharedFS(path)) {
4444
/* it was on a network share, so we'll continue
4450
virReportSystemError(errno,
4451
_("Failed to create domain save file "
4452
"'%s': couldn't determine fs type"),
4459
/* local file - log the error returned by virFileOperation */
4460
virReportSystemError(-rc,
4461
_("Failed to create domain save file '%s'"),
4468
/* Retry creating the file as driver->user */
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'"),
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 */
4484
bypassSecurityDriver = 1;
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"),
4497
rc = virCgroupAllowDevicePath(cgroup, path);
4499
virReportSystemError(-rc,
4500
_("Unable to allow device %s for %s"),
4501
path, vm->def->name);
4506
if ((!bypassSecurityDriver) &&
4507
virSecurityManagerSetSavedStateLabel(driver->securityManager,
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);
4519
const char *prog = qemudSaveCompressionTypeToString(header.compressed);
4520
const char *args[] = {
4525
qemuDomainObjEnterMonitorWithDriver(driver, vm);
4526
rc = qemuMonitorMigrateToFile(priv->mon,
4527
QEMU_MONITOR_MIGRATE_BACKGROUND,
4528
args, path, offset);
4529
qemuDomainObjExitMonitorWithDriver(driver, vm);
4535
rc = qemuDomainWaitForMigrationComplete(driver, vm);
4540
if ((!bypassSecurityDriver) &&
4541
virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4543
VIR_WARN("failed to restore save state label on %s", path);
4545
if (cgroup != NULL) {
4546
rc = virCgroupDenyDevicePath(cgroup, path);
4548
VIR_WARN("Unable to deny device %s for %s %d",
4549
path, vm->def->name, rc);
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,
4570
if (header.was_running && virDomainObjIsActive(vm)) {
4571
rc = doStartCPUs(driver, vm, dom->conn);
4573
VIR_WARN0("Unable to resume guest CPUs after save failure");
4576
if (cgroup != NULL) {
4577
rc = virCgroupDenyDevicePath(cgroup, path);
4579
VIR_WARN("Unable to deny device %s for %s: %d",
4580
path, vm->def->name, rc);
4583
if ((!bypassSecurityDriver) &&
4584
virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4586
VIR_WARN("failed to restore save state label on %s", path);
4589
if (qemuDomainObjEndJob(vm) == 0)
4595
if (ret != 0 && is_reg)
4598
qemuDomainEventQueue(driver, event);
4599
virCgroupFree(&cgroup);
4603
/* Returns true if a compression program is available in PATH */
4604
static bool qemudCompressProgramAvailable(enum qemud_save_formats compress)
4609
if (compress == QEMUD_SAVE_FORMAT_RAW)
4611
prog = qemudSaveCompressionTypeToString(compress);
4612
c = virFindFileInPath(prog);
4619
static int qemudDomainSave(virDomainPtr dom, const char *path)
4621
struct qemud_driver *driver = dom->conn->privateData;
4624
virDomainObjPtr vm = NULL;
4626
qemuDriverLock(driver);
4628
if (driver->saveImageFormat == NULL)
4629
compressed = QEMUD_SAVE_FORMAT_RAW;
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"));
4638
if (!qemudCompressProgramAvailable(compressed)) {
4639
qemuReportError(VIR_ERR_OPERATION_FAILED,
4640
"%s", _("Compression program for image format "
4641
"in configuration file isn't available"));
4646
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
4655
if (!virDomainObjIsActive(vm)) {
4656
qemuReportError(VIR_ERR_OPERATION_INVALID,
4657
"%s", _("domain is not running"));
4661
ret = qemudDomainSaveFlag(driver, dom, vm, path, compressed);
4665
virDomainObjUnlock(vm);
4666
qemuDriverUnlock(driver);
4672
qemuDomainManagedSavePath(struct qemud_driver *driver, virDomainObjPtr vm) {
4675
if (virAsprintf(&ret, "%s/%s.save", driver->saveDir, vm->def->name) < 0) {
4676
virReportOOMError();
4684
qemuDomainManagedSave(virDomainPtr dom, unsigned int flags)
4686
struct qemud_driver *driver = dom->conn->privateData;
4687
virDomainObjPtr vm = NULL;
4692
virCheckFlags(0, -1);
4694
qemuDriverLock(driver);
4695
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
4704
if (!virDomainObjIsActive(vm)) {
4705
qemuReportError(VIR_ERR_OPERATION_INVALID,
4706
"%s", _("domain is not running"));
4710
name = qemuDomainManagedSavePath(driver, vm);
4714
VIR_DEBUG("Saving state to %s", name);
4716
compressed = QEMUD_SAVE_FORMAT_RAW;
4717
ret = qemudDomainSaveFlag(driver, dom, vm, name, compressed);
4721
virDomainObjUnlock(vm);
4722
qemuDriverUnlock(driver);
4729
qemuDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
4731
struct qemud_driver *driver = dom->conn->privateData;
4732
virDomainObjPtr vm = NULL;
4736
virCheckFlags(0, -1);
4738
qemuDriverLock(driver);
4739
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
4748
name = qemuDomainManagedSavePath(driver, vm);
4752
ret = virFileExists(name);
4757
virDomainObjUnlock(vm);
4758
qemuDriverUnlock(driver);
4763
qemuDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
4765
struct qemud_driver *driver = dom->conn->privateData;
4766
virDomainObjPtr vm = NULL;
4770
virCheckFlags(0, -1);
4772
qemuDriverLock(driver);
4773
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
4782
name = qemuDomainManagedSavePath(driver, vm);
4791
virDomainObjUnlock(vm);
4792
qemuDriverUnlock(driver);
4796
static int doCoreDump(struct qemud_driver *driver,
4799
enum qemud_save_formats compress)
4803
qemuDomainObjPrivatePtr priv;
4805
priv = vm->privateData;
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);
4814
if (VIR_CLOSE(fd) < 0) {
4815
virReportSystemError(errno,
4816
_("unable to save file %s"),
4821
if (virSecurityManagerSetSavedStateLabel(driver->securityManager,
4825
qemuDomainObjEnterMonitorWithDriver(driver, vm);
4826
if (compress == QEMUD_SAVE_FORMAT_RAW) {
4827
const char *args[] = {
4831
ret = qemuMonitorMigrateToFile(priv->mon,
4832
QEMU_MONITOR_MIGRATE_BACKGROUND,
4835
const char *prog = qemudSaveCompressionTypeToString(compress);
4836
const char *args[] = {
4841
ret = qemuMonitorMigrateToFile(priv->mon,
4842
QEMU_MONITOR_MIGRATE_BACKGROUND,
4845
qemuDomainObjExitMonitorWithDriver(driver, vm);
4849
ret = qemuDomainWaitForMigrationComplete(driver, vm);
4854
if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
4864
static enum qemud_save_formats
4865
getCompressionType(struct qemud_driver *driver)
4867
int compress = QEMUD_SAVE_FORMAT_RAW;
4870
* We reuse "save" flag for "dump" here. Then, we can support the same
4871
* format in "save" and "dump".
4873
if (driver->dumpImageFormat) {
4874
compress = qemudSaveCompressionTypeFromString(driver->dumpImageFormat);
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;
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, "
4886
return QEMUD_SAVE_FORMAT_RAW;
4892
static int qemudDomainCoreDump(virDomainPtr dom,
4894
int flags ATTRIBUTE_UNUSED) {
4895
struct qemud_driver *driver = dom->conn->privateData;
4897
int resume = 0, paused = 0;
4899
virDomainEventPtr event = NULL;
4900
qemuDomainObjPrivatePtr priv;
4902
qemuDriverLock(driver);
4903
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
4912
priv = vm->privateData;
4914
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
4917
if (!virDomainObjIsActive(vm)) {
4918
qemuReportError(VIR_ERR_OPERATION_INVALID,
4919
"%s", _("domain is not running"));
4923
priv->jobActive = QEMU_JOB_DUMP;
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);
4929
/* Pause domain for non-live dump */
4930
if (!(flags & VIR_DUMP_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
4931
if (doStopCPUs(driver, vm) < 0)
4935
if (!virDomainObjIsActive(vm)) {
4936
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
4937
_("guest unexpectedly quit"));
4942
ret = doCoreDump(driver, vm, path, getCompressionType(driver));
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);
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"));
4968
if (qemuDomainObjEndJob(vm) == 0)
4970
else if ((ret == 0) && (flags & VIR_DUMP_CRASH) && !vm->persistent) {
4971
virDomainRemoveInactive(&driver->domains,
4978
virDomainObjUnlock(vm);
4980
qemuDomainEventQueue(driver, event);
4981
qemuDriverUnlock(driver);
4985
static void processWatchdogEvent(void *data, void *opaque)
4988
struct watchdogEvent *wdEvent = data;
4989
struct qemud_driver *driver = opaque;
4991
switch (wdEvent->action) {
4992
case VIR_DOMAIN_WATCHDOG_ACTION_DUMP:
4996
if (virAsprintf(&dumpfile, "%s/%s-%u",
4997
driver->autoDumpPath,
4998
wdEvent->vm->def->name,
4999
(unsigned int)time(NULL)) < 0) {
5000
virReportOOMError();
5004
qemuDriverLock(driver);
5005
virDomainObjLock(wdEvent->vm);
5007
if (qemuDomainObjBeginJobWithDriver(driver, wdEvent->vm) < 0)
5010
if (!virDomainObjIsActive(wdEvent->vm)) {
5011
qemuReportError(VIR_ERR_OPERATION_INVALID,
5012
"%s", _("domain is not running"));
5016
ret = doCoreDump(driver,
5019
getCompressionType(driver));
5021
qemuReportError(VIR_ERR_OPERATION_FAILED,
5022
"%s", _("Dump failed"));
5024
ret = doStartCPUs(driver, wdEvent->vm, NULL);
5027
qemuReportError(VIR_ERR_OPERATION_FAILED,
5028
"%s", _("Resuming after dump failed"));
5030
if (qemuDomainObjEndJob(wdEvent->vm) > 0)
5031
virDomainObjUnlock(wdEvent->vm);
5033
qemuDriverUnlock(driver);
5043
static int qemudDomainHotplugVcpus(virDomainObjPtr vm, unsigned int nvcpus)
5045
qemuDomainObjPrivatePtr priv = vm->privateData;
5049
qemuDomainObjEnterMonitor(vm);
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);
5066
for (i = vm->def->vcpus - 1 ; i >= nvcpus ; i--) {
5067
/* Offline old CPU */
5068
rc = qemuMonitorSetCPU(priv->mon, i, 0);
5081
qemuDomainObjExitMonitor(vm);
5085
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5086
_("cannot change vcpu count of this domain"));
5092
qemudDomainSetVcpusFlags(virDomainPtr dom, unsigned int nvcpus,
5095
struct qemud_driver *driver = dom->conn->privateData;
5097
virDomainDefPtr persistentDef;
5102
virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
5103
VIR_DOMAIN_VCPU_CONFIG |
5104
VIR_DOMAIN_VCPU_MAXIMUM, -1);
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);
5115
if (!nvcpus || (unsigned short) nvcpus != nvcpus) {
5116
qemuReportError(VIR_ERR_INVALID_ARG,
5117
_("argument out of range: %d"), nvcpus);
5121
qemuDriverLock(driver);
5122
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5123
qemuDriverUnlock(driver);
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);
5133
if (qemuDomainObjBeginJob(vm) < 0)
5136
if (!virDomainObjIsActive(vm) && (flags & VIR_DOMAIN_VCPU_LIVE)) {
5137
qemuReportError(VIR_ERR_OPERATION_INVALID,
5138
"%s", _("domain is not running"));
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"));
5148
if (!(type = virDomainVirtTypeToString(vm->def->virtType))) {
5149
qemuReportError(VIR_ERR_INTERNAL_ERROR,
5150
_("unknown virt type in domain definition '%d'"),
5155
if ((max = qemudGetMaxVCPUs(NULL, type)) < 0) {
5156
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
5157
_("could not determine max vcpus for the domain"));
5161
if (!(flags & VIR_DOMAIN_VCPU_MAXIMUM) && vm->def->maxvcpus < max) {
5162
max = vm->def->maxvcpus;
5166
qemuReportError(VIR_ERR_INVALID_ARG,
5167
_("requested vcpus is greater than max allowable"
5168
" vcpus for the domain: %d > %d"), nvcpus, max);
5172
if (!(persistentDef = virDomainObjGetPersistentDef(driver->caps, vm)))
5176
case VIR_DOMAIN_VCPU_MAXIMUM | VIR_DOMAIN_VCPU_CONFIG:
5177
persistentDef->maxvcpus = nvcpus;
5178
if (nvcpus < persistentDef->vcpus)
5179
persistentDef->vcpus = nvcpus;
5183
case VIR_DOMAIN_VCPU_CONFIG:
5184
persistentDef->vcpus = nvcpus;
5188
case VIR_DOMAIN_VCPU_LIVE:
5189
ret = qemudDomainHotplugVcpus(vm, nvcpus);
5192
case VIR_DOMAIN_VCPU_LIVE | VIR_DOMAIN_VCPU_CONFIG:
5193
ret = qemudDomainHotplugVcpus(vm, nvcpus);
5195
persistentDef->vcpus = nvcpus;
5200
/* Save the persistent config to disk */
5201
if (flags & VIR_DOMAIN_VCPU_CONFIG)
5202
ret = virDomainSaveConfig(driver->configDir, persistentDef);
5205
if (qemuDomainObjEndJob(vm) == 0)
5210
virDomainObjUnlock(vm);
5215
qemudDomainSetVcpus(virDomainPtr dom, unsigned int nvcpus)
5217
return qemudDomainSetVcpusFlags(dom, nvcpus, VIR_DOMAIN_VCPU_LIVE);
5222
qemudDomainPinVcpu(virDomainPtr dom,
5224
unsigned char *cpumap,
5226
struct qemud_driver *driver = dom->conn->privateData;
5228
int maxcpu, hostcpus;
5229
virNodeInfo nodeinfo;
5231
qemuDomainObjPrivatePtr priv;
5233
qemuDriverLock(driver);
5234
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5235
qemuDriverUnlock(driver);
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);
5245
if (!virDomainObjIsActive(vm)) {
5246
qemuReportError(VIR_ERR_OPERATION_INVALID,
5247
"%s",_("cannot pin vcpus on an inactive domain"));
5251
priv = vm->privateData;
5253
if (vcpu > (priv->nvcpupids-1)) {
5254
qemuReportError(VIR_ERR_INVALID_ARG,
5255
_("vcpu number out of range %d > %d"),
5256
vcpu, priv->nvcpupids);
5260
if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
5263
hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
5264
maxcpu = maplen * 8;
5265
if (maxcpu > hostcpus)
5268
if (priv->vcpupids != NULL) {
5269
if (virProcessInfoSetAffinity(priv->vcpupids[vcpu],
5270
cpumap, maplen, maxcpu) < 0)
5273
qemuReportError(VIR_ERR_NO_SUPPORT,
5274
"%s", _("cpu affinity is not supported"));
5281
virDomainObjUnlock(vm);
5286
qemudDomainGetVcpus(virDomainPtr dom,
5287
virVcpuInfoPtr info,
5289
unsigned char *cpumaps,
5291
struct qemud_driver *driver = dom->conn->privateData;
5293
virNodeInfo nodeinfo;
5294
int i, v, maxcpu, hostcpus;
5296
qemuDomainObjPrivatePtr priv;
5298
qemuDriverLock(driver);
5299
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5300
qemuDriverUnlock(driver);
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);
5310
if (!virDomainObjIsActive(vm)) {
5311
qemuReportError(VIR_ERR_OPERATION_INVALID,
5313
_("cannot list vcpu pinning for an inactive domain"));
5317
priv = vm->privateData;
5319
if (nodeGetInfo(dom->conn, &nodeinfo) < 0)
5322
hostcpus = VIR_NODEINFO_MAXCPUS(nodeinfo);
5323
maxcpu = maplen * 8;
5324
if (maxcpu > hostcpus)
5327
/* Clamp to actual number of vcpus */
5328
if (maxinfo > priv->nvcpupids)
5329
maxinfo = priv->nvcpupids;
5333
memset(info, 0, sizeof(*info) * maxinfo);
5334
for (i = 0 ; i < maxinfo ; i++) {
5336
info[i].state = VIR_VCPU_RUNNING;
5338
if (priv->vcpupids != NULL &&
5339
qemudGetProcessInfo(&(info[i].cpuTime),
5342
priv->vcpupids[i]) < 0) {
5343
virReportSystemError(errno, "%s",
5344
_("cannot get vCPU placement & pCPU time"));
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);
5356
if (virProcessInfoGetAffinity(priv->vcpupids[v],
5357
cpumap, maplen, maxcpu) < 0)
5361
qemuReportError(VIR_ERR_NO_SUPPORT,
5362
"%s", _("cpu affinity is not available"));
5371
virDomainObjUnlock(vm);
5377
qemudDomainGetVcpusFlags(virDomainPtr dom, unsigned int flags)
5379
struct qemud_driver *driver = dom->conn->privateData;
5381
virDomainDefPtr def;
5384
virCheckFlags(VIR_DOMAIN_VCPU_LIVE |
5385
VIR_DOMAIN_VCPU_CONFIG |
5386
VIR_DOMAIN_VCPU_MAXIMUM, -1);
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);
5395
qemuDriverLock(driver);
5396
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5397
qemuDriverUnlock(driver);
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);
5407
if (flags & VIR_DOMAIN_VCPU_LIVE) {
5408
if (!virDomainObjIsActive(vm)) {
5409
qemuReportError(VIR_ERR_OPERATION_INVALID, "%s",
5410
_("domain not active"));
5415
def = vm->newDef ? vm->newDef : vm->def;
5418
ret = (flags & VIR_DOMAIN_VCPU_MAXIMUM) ? def->maxvcpus : def->vcpus;
5422
virDomainObjUnlock(vm);
5427
qemudDomainGetMaxVcpus(virDomainPtr dom)
5429
return qemudDomainGetVcpusFlags(dom, (VIR_DOMAIN_VCPU_LIVE |
5430
VIR_DOMAIN_VCPU_MAXIMUM));
5433
static int qemudDomainGetSecurityLabel(virDomainPtr dom, virSecurityLabelPtr seclabel)
5435
struct qemud_driver *driver = (struct qemud_driver *)dom->conn->privateData;
5439
qemuDriverLock(driver);
5440
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
5442
memset(seclabel, 0, sizeof(*seclabel));
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);
5452
if (!virDomainVirtTypeToString(vm->def->virtType)) {
5453
qemuReportError(VIR_ERR_INTERNAL_ERROR,
5454
_("unknown virt type in domain definition '%d'"),
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.
5464
* Comment from Dan Berrange:
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().
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"));
5486
virDomainObjUnlock(vm);
5487
qemuDriverUnlock(driver);
5491
static int qemudNodeGetSecurityModel(virConnectPtr conn,
5492
virSecurityModelPtr secmodel)
5494
struct qemud_driver *driver = (struct qemud_driver *)conn->privateData;
5498
qemuDriverLock(driver);
5499
memset(secmodel, 0, sizeof(*secmodel));
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)
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);
5514
strcpy(secmodel->model, p);
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);
5524
strcpy(secmodel->doi, p);
5527
qemuDriverUnlock(driver);
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
5538
qemudOpenAsUID(const char *path, uid_t uid, gid_t gid, pid_t *child_pid)
5545
if (pipe(pipefd) < 0) {
5546
virReportSystemError(errno,
5547
_("failed to create pipe to read '%s'"),
5549
pipefd[0] = pipefd[1] = -1;
5550
goto parent_cleanup;
5553
int forkRet = virFork(child_pid);
5555
if (*child_pid < 0) {
5556
virReportSystemError(errno,
5557
_("failed to fork child to read '%s'"),
5559
goto parent_cleanup;
5562
if (*child_pid > 0) {
5566
/* parent doesn't need the write side of the pipe */
5567
VIR_FORCE_CLOSE(pipefd[1]);
5570
virReportSystemError(errno,
5571
_("failed in parent after forking child to read '%s'"),
5573
goto parent_cleanup;
5575
/* caller gets the read side of the pipe */
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)) {
5596
/* setuid to the qemu user, then open the file, read it,
5597
and stuff it into the pipe for the parent process to
5601
size_t bufsize = 1024 * 1024;
5604
/* child doesn't need the read side of the pipe */
5605
VIR_FORCE_CLOSE(pipefd[0]);
5609
virReportSystemError(errno,
5610
_("failed in child after forking to read '%s'"),
5615
if (virSetUIDGID(uid, gid) < 0) {
5620
if ((fd = open(path, O_RDONLY)) < 0) {
5622
virReportSystemError(errno,
5623
_("cannot open '%s' as uid %d"),
5628
if (VIR_ALLOC_N(buf, bufsize) < 0) {
5630
virReportOOMError();
5634
/* read from fd and write to pipefd[1] until EOF */
5636
if ((bytesread = saferead(fd, buf, bufsize)) < 0) {
5638
virReportSystemError(errno,
5639
_("child failed reading from '%s'"),
5643
if (safewrite(pipefd[1], buf, bytesread) != bytesread) {
5645
virReportSystemError(errno, "%s",
5646
_("child failed writing to pipe"));
5649
} while (bytesread > 0);
5654
VIR_FORCE_CLOSE(fd);
5655
VIR_FORCE_CLOSE(pipefd[1]);
5659
static int qemudDomainSaveImageClose(int fd, pid_t read_pid, int *status)
5663
if (VIR_CLOSE(fd) < 0) {
5664
virReportSystemError(errno, "%s",
5665
_("cannot close file"));
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) {
5674
} else if (status) {
5681
static int ATTRIBUTE_NONNULL(3) ATTRIBUTE_NONNULL(4) ATTRIBUTE_NONNULL(5)
5682
qemudDomainSaveImageOpen(struct qemud_driver *driver,
5684
virDomainDefPtr *ret_def,
5685
struct qemud_save_header *ret_header,
5686
pid_t *ret_read_pid)
5689
pid_t read_pid = -1;
5690
struct qemud_save_header header;
5692
virDomainDefPtr def = NULL;
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"));
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 */
5712
if (saferead(fd, &header, sizeof(header)) != sizeof(header)) {
5713
qemuReportError(VIR_ERR_OPERATION_FAILED,
5714
"%s", _("failed to read qemu header"));
5718
if (memcmp(header.magic, QEMUD_SAVE_MAGIC, sizeof(header.magic)) != 0) {
5719
qemuReportError(VIR_ERR_OPERATION_FAILED,
5720
"%s", _("image magic is incorrect"));
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);
5731
if (header.xml_len <= 0) {
5732
qemuReportError(VIR_ERR_OPERATION_FAILED,
5733
_("invalid XML length: %d"), header.xml_len);
5737
if (VIR_ALLOC_N(xml, header.xml_len) < 0) {
5738
virReportOOMError();
5742
if (saferead(fd, xml, header.xml_len) != header.xml_len) {
5743
qemuReportError(VIR_ERR_OPERATION_FAILED,
5744
"%s", _("failed to read XML"));
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"));
5759
*ret_header = header;
5760
*ret_read_pid = read_pid;
5765
virDomainDefFree(def);
5767
qemudDomainSaveImageClose(fd, read_pid, NULL);
5772
static int ATTRIBUTE_NONNULL(6)
5773
qemudDomainSaveImageStartVM(virConnectPtr conn,
5774
struct qemud_driver *driver,
5778
const struct qemud_save_header *header,
5782
virDomainEventPtr event;
5783
int intermediatefd = -1;
5784
pid_t intermediate_pid = -1;
5789
if (header->version == 2) {
5790
const char *intermediate_argv[3] = { NULL, "-dc", NULL };
5791
const char *prog = qemudSaveCompressionTypeToString(header->compressed);
5793
qemuReportError(VIR_ERR_OPERATION_FAILED,
5794
_("Invalid compressed save format %d"),
5795
header->compressed);
5799
if (header->compressed != QEMUD_SAVE_FORMAT_RAW) {
5800
intermediate_argv[0] = prog;
5801
intermediatefd = fd;
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]);
5813
/* Set the migration source and start it up. */
5814
ret = qemudStartVMDaemon(conn, driver, vm, "stdio", true, fd, path,
5817
if (intermediate_pid != -1) {
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.
5822
VIR_FORCE_CLOSE(intermediatefd);
5823
VIR_FORCE_CLOSE(fd);
5824
kill(intermediate_pid, SIGTERM);
5827
/* Wait for intermediate process to exit */
5828
while (waitpid(intermediate_pid, &childstat, 0) == -1 &&
5833
VIR_FORCE_CLOSE(intermediatefd);
5835
wait_ret = qemudDomainSaveImageClose(fd, read_pid, &status);
5837
if (read_pid != -1) {
5838
if (wait_ret == -1) {
5839
virReportSystemError(errno,
5840
_("failed to wait for process reading '%s'"),
5843
} else if (!WIFEXITED(status)) {
5844
qemuReportError(VIR_ERR_OPERATION_FAILED,
5845
_("child process exited abnormally reading '%s'"),
5849
int exit_status = WEXITSTATUS(status);
5850
if (exit_status != 0) {
5851
virReportSystemError(exit_status,
5852
_("child process returned error reading '%s'"),
5860
qemuDomainStartAudit(vm, "restored", false);
5864
event = virDomainEventNewFromObj(vm,
5865
VIR_DOMAIN_EVENT_STARTED,
5866
VIR_DOMAIN_EVENT_STARTED_RESTORED);
5867
qemuDomainStartAudit(vm, "restored", true);
5869
qemuDomainEventQueue(driver, event);
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"));
5880
if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
5881
VIR_WARN("Failed to save status on vm %s", vm->def->name);
5889
if (virSecurityManagerRestoreSavedStateLabel(driver->securityManager,
5891
VIR_WARN("failed to restore save state label on %s", path);
5896
static int qemudDomainRestore(virConnectPtr conn,
5898
struct qemud_driver *driver = conn->privateData;
5899
virDomainDefPtr def = NULL;
5900
virDomainObjPtr vm = NULL;
5902
pid_t read_pid = -1;
5904
struct qemud_save_header header;
5906
qemuDriverLock(driver);
5908
fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
5912
if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
5915
if (!(vm = virDomainAssignDef(driver->caps,
5918
/* virDomainAssignDef already set the error */
5923
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
5926
ret = qemudDomainSaveImageStartVM(conn, driver, vm, fd,
5927
read_pid, &header, path);
5929
if (qemuDomainObjEndJob(vm) == 0)
5931
else if (ret < 0 && !vm->persistent) {
5932
virDomainRemoveInactive(&driver->domains, vm);
5937
virDomainDefFree(def);
5938
qemudDomainSaveImageClose(fd, read_pid, NULL);
5940
virDomainObjUnlock(vm);
5941
qemuDriverUnlock(driver);
5945
static int qemudDomainObjRestore(virConnectPtr conn,
5946
struct qemud_driver *driver,
5950
virDomainDefPtr def = NULL;
5952
pid_t read_pid = -1;
5954
struct qemud_save_header header;
5956
fd = qemudDomainSaveImageOpen(driver, path, &def, &header, &read_pid);
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);
5974
virDomainObjAssignDef(vm, def, true);
5977
ret = qemudDomainSaveImageStartVM(conn, driver, vm, fd,
5978
read_pid, &header, path);
5981
virDomainDefFree(def);
5982
qemudDomainSaveImageClose(fd, read_pid, NULL);
5987
static char *qemudVMDumpXML(struct qemud_driver *driver,
5992
virCPUDefPtr cpu = NULL;
5993
virDomainDefPtr def;
5994
virCPUDefPtr def_cpu;
5996
if ((flags & VIR_DOMAIN_XML_INACTIVE) && vm->newDef)
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"));
6010
if (!(cpu = virCPUDefCopy(def_cpu))
6011
|| cpuUpdate(cpu, driver->caps->host.cpu))
6016
ret = virDomainDefFormat(def, flags);
6025
static char *qemudDomainDumpXML(virDomainPtr dom,
6027
struct qemud_driver *driver = dom->conn->privateData;
6030
unsigned long balloon;
6033
qemuDriverLock(driver);
6034
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
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)
6055
qemuDomainObjEnterMonitorWithDriver(driver, vm);
6056
err = qemuMonitorGetBalloonInfo(priv->mon, &balloon);
6057
qemuDomainObjExitMonitorWithDriver(driver, vm);
6058
if (qemuDomainObjEndJob(vm) == 0) {
6065
vm->def->mem.cur_balloon = balloon;
6066
/* err == 0 indicates no balloon support, so ignore it */
6070
ret = qemudVMDumpXML(driver, vm, flags);
6074
virDomainObjUnlock(vm);
6075
qemuDriverUnlock(driver);
6080
static char *qemuDomainXMLFromNative(virConnectPtr conn,
6083
unsigned int flags ATTRIBUTE_UNUSED) {
6084
struct qemud_driver *driver = conn->privateData;
6085
virDomainDefPtr def = NULL;
6088
if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
6089
qemuReportError(VIR_ERR_INVALID_ARG,
6090
_("unsupported config type %s"), format);
6094
qemuDriverLock(driver);
6095
def = qemuParseCommandLineString(driver->caps, config);
6096
qemuDriverUnlock(driver);
6100
xml = virDomainDefFormat(def, VIR_DOMAIN_XML_INACTIVE);
6103
virDomainDefFree(def);
6107
static char *qemuDomainXMLToNative(virConnectPtr conn,
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;
6119
qemuDriverLock(driver);
6121
if (STRNEQ(format, QEMU_CONFIG_FORMAT_ARGV)) {
6122
qemuReportError(VIR_ERR_INVALID_ARG,
6123
_("unsupported config type %s"), format);
6127
def = virDomainDefParseString(driver->caps, xmlData, 0);
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
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);
6143
memset(net, 0, sizeof *net);
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;
6154
memset(net, 0, sizeof *net);
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;
6161
net->bootIndex = bootIndex;
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;
6169
if (qemuCapsExtractVersionInfo(def->emulator, def->os.arch,
6174
if (qemuPrepareMonitorChr(driver, &monConfig, def->name) < 0)
6177
if (!(cmd = qemuBuildCommandLine(conn, driver, def,
6178
&monConfig, false, qemuCmdFlags,
6179
NULL, -1, NULL, VIR_VM_OP_NO_OP)))
6182
ret = virCommandToString(cmd);
6185
qemuDriverUnlock(driver);
6187
virCommandFree(cmd);
6188
virDomainDefFree(def);
6193
static int qemudListDefinedDomains(virConnectPtr conn,
6194
char **const names, int nnames) {
6195
struct qemud_driver *driver = conn->privateData;
6198
qemuDriverLock(driver);
6199
n = virDomainObjListGetInactiveNames(&driver->domains, names, nnames);
6200
qemuDriverUnlock(driver);
6204
static int qemudNumDefinedDomains(virConnectPtr conn) {
6205
struct qemud_driver *driver = conn->privateData;
6208
qemuDriverLock(driver);
6209
n = virDomainObjListNumOfDomains(&driver->domains, 0);
6210
qemuDriverUnlock(driver);
6216
static int qemudDomainObjStart(virConnectPtr conn,
6217
struct qemud_driver *driver,
6225
* If there is a managed saved state restore it instead of starting
6226
* from scratch. In any case the old state is removed.
6228
managed_save = qemuDomainManagedSavePath(driver, vm);
6229
if ((managed_save) && (virFileExists(managed_save))) {
6230
ret = qemudDomainObjRestore(conn, driver, vm, managed_save);
6232
if (unlink(managed_save) < 0) {
6233
VIR_WARN("Failed to remove the managed state %s", managed_save);
6240
ret = qemudStartVMDaemon(conn, driver, vm, NULL, start_paused, -1, NULL,
6242
qemuDomainStartAudit(vm, "booted", ret >= 0);
6244
virDomainEventPtr event =
6245
virDomainEventNewFromObj(vm,
6246
VIR_DOMAIN_EVENT_STARTED,
6247
VIR_DOMAIN_EVENT_STARTED_BOOTED);
6249
qemuDomainEventQueue(driver, event);
6253
VIR_FREE(managed_save);
6258
qemudDomainStartWithFlags(virDomainPtr dom, unsigned int flags)
6260
struct qemud_driver *driver = dom->conn->privateData;
6264
virCheckFlags(VIR_DOMAIN_START_PAUSED, -1);
6266
qemuDriverLock(driver);
6267
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
6277
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6280
if (virDomainObjIsActive(vm)) {
6281
qemuReportError(VIR_ERR_OPERATION_INVALID,
6282
"%s", _("domain is already running"));
6286
ret = qemudDomainObjStart(dom->conn, driver, vm,
6287
(flags & VIR_DOMAIN_START_PAUSED) != 0);
6290
if (qemuDomainObjEndJob(vm) == 0)
6295
virDomainObjUnlock(vm);
6296
qemuDriverUnlock(driver);
6301
qemudDomainStart(virDomainPtr dom)
6303
return qemudDomainStartWithFlags(dom, 0);
6307
qemudCanonicalizeMachineFromInfo(virDomainDefPtr def,
6308
virCapsGuestDomainInfoPtr info,
6315
for (i = 0; i < info->nmachines; i++) {
6316
virCapsGuestMachinePtr machine = info->machines[i];
6318
if (!machine->canonical)
6321
if (STRNEQ(def->os.machine, machine->name))
6324
if (!(*canonical = strdup(machine->canonical))) {
6325
virReportOOMError();
6336
qemudCanonicalizeMachineDirect(virDomainDefPtr def, char **canonical)
6338
virCapsGuestMachinePtr *machines = NULL;
6339
int i, nmachines = 0;
6341
if (qemuCapsProbeMachineTypes(def->emulator, &machines, &nmachines) < 0)
6344
for (i = 0; i < nmachines; i++) {
6345
if (!machines[i]->canonical)
6348
if (STRNEQ(def->os.machine, machines[i]->name))
6351
*canonical = machines[i]->canonical;
6352
machines[i]->canonical = NULL;
6356
virCapabilitiesFreeMachines(machines, nmachines);
6362
qemudCanonicalizeMachine(struct qemud_driver *driver, virDomainDefPtr def)
6364
char *canonical = NULL;
6367
for (i = 0; i < driver->caps->nguests; i++) {
6368
virCapsGuestPtr guest = driver->caps->guests[i];
6369
virCapsGuestDomainInfoPtr info;
6372
for (j = 0; j < guest->arch.ndomains; j++) {
6373
info = &guest->arch.domains[j]->info;
6375
if (!info->emulator || !STREQ(info->emulator, def->emulator))
6378
if (!info->nmachines)
6379
info = &guest->arch.defaultInfo;
6381
if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
6386
info = &guest->arch.defaultInfo;
6388
if (info->emulator && STREQ(info->emulator, def->emulator)) {
6389
if (qemudCanonicalizeMachineFromInfo(def, info, &canonical) < 0)
6395
if (qemudCanonicalizeMachineDirect(def, &canonical) < 0)
6400
VIR_FREE(def->os.machine);
6401
def->os.machine = canonical;
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;
6414
qemuDriverLock(driver);
6415
if (!(def = virDomainDefParseString(driver->caps, xml,
6416
VIR_DOMAIN_XML_INACTIVE)))
6419
if (virSecurityManagerVerify(driver->securityManager, def) < 0)
6422
if ((dupVM = virDomainObjIsDuplicate(&driver->domains, def, 0)) < 0)
6425
if (qemudCanonicalizeMachine(driver, def) < 0)
6428
if (qemuAssignPCIAddresses(def) < 0)
6431
if (!(vm = virDomainAssignDef(driver->caps,
6439
if (virDomainSaveConfig(driver->configDir,
6440
vm->newDef ? vm->newDef : vm->def) < 0) {
6441
virDomainRemoveInactive(&driver->domains,
6447
event = virDomainEventNewFromObj(vm,
6448
VIR_DOMAIN_EVENT_DEFINED,
6450
VIR_DOMAIN_EVENT_DEFINED_ADDED :
6451
VIR_DOMAIN_EVENT_DEFINED_UPDATED);
6453
dom = virGetDomain(conn, vm->def->name, vm->def->uuid);
6454
if (dom) dom->id = vm->def->id;
6457
virDomainDefFree(def);
6459
virDomainObjUnlock(vm);
6461
qemuDomainEventQueue(driver, event);
6462
qemuDriverUnlock(driver);
6466
static int qemudDomainUndefine(virDomainPtr dom) {
6467
struct qemud_driver *driver = dom->conn->privateData;
6469
virDomainEventPtr event = NULL;
6472
qemuDriverLock(driver);
6473
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
6483
if (virDomainObjIsActive(vm)) {
6484
qemuReportError(VIR_ERR_OPERATION_INVALID,
6485
"%s", _("cannot delete active domain"));
6489
if (!vm->persistent) {
6490
qemuReportError(VIR_ERR_OPERATION_INVALID,
6491
"%s", _("cannot undefine transient domain"));
6495
if (virDomainDeleteConfig(driver->configDir, driver->autostartDir, vm) < 0)
6498
event = virDomainEventNewFromObj(vm,
6499
VIR_DOMAIN_EVENT_UNDEFINED,
6500
VIR_DOMAIN_EVENT_UNDEFINED_REMOVED);
6502
virDomainRemoveInactive(&driver->domains,
6509
virDomainObjUnlock(vm);
6511
qemuDomainEventQueue(driver, event);
6512
qemuDriverUnlock(driver);
6517
static int qemudDomainAttachDevice(virDomainPtr dom,
6520
struct qemud_driver *driver = dom->conn->privateData;
6522
virDomainDeviceDefPtr dev = NULL;
6523
unsigned long long qemuCmdFlags;
6524
virCgroupPtr cgroup = NULL;
6527
qemuDriverLock(driver);
6528
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
6537
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6540
if (!virDomainObjIsActive(vm)) {
6541
qemuReportError(VIR_ERR_OPERATION_INVALID,
6542
"%s", _("cannot attach device on inactive domain"));
6546
dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
6547
VIR_DOMAIN_XML_INACTIVE);
6551
if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
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"),
6564
if (qemuSetupDiskCgroup(driver, cgroup, dev->data.disk) < 0)
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,
6576
dev->data.disk = NULL;
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);
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);
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);
6594
dev->data.disk = NULL;
6596
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6597
_("disk bus '%s' cannot be hotplugged."),
6598
virDomainDiskBusTypeToString(dev->data.disk->bus));
6604
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6605
_("disk device type '%s' cannot be hotplugged"),
6606
virDomainDiskDeviceTypeToString(dev->data.disk->device));
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));
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);
6619
dev->data.controller = NULL;
6621
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6622
_("disk controller bus '%s' cannot be hotplugged."),
6623
virDomainControllerTypeToString(dev->data.controller->type));
6626
} else if (dev->type == VIR_DOMAIN_DEVICE_NET) {
6627
ret = qemuDomainAttachNetDevice(dom->conn, driver, vm,
6628
dev->data.net, qemuCmdFlags);
6630
dev->data.net = NULL;
6631
} else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
6632
ret = qemuDomainAttachHostDevice(driver, vm,
6633
dev->data.hostdev, qemuCmdFlags);
6635
dev->data.hostdev = NULL;
6637
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6638
_("device type '%s' cannot be attached"),
6639
virDomainDeviceTypeToString(dev->type));
6643
if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
6647
if (qemuDomainObjEndJob(vm) == 0)
6652
virCgroupFree(&cgroup);
6654
virDomainDeviceDefFree(dev);
6656
virDomainObjUnlock(vm);
6657
qemuDriverUnlock(driver);
6661
static int qemudDomainAttachDeviceFlags(virDomainPtr dom,
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"));
6670
return qemudDomainAttachDevice(dom, xml);
6674
static int qemuDomainUpdateDeviceFlags(virDomainPtr dom,
6678
struct qemud_driver *driver = dom->conn->privateData;
6680
virDomainDeviceDefPtr dev = NULL;
6681
unsigned long long qemuCmdFlags;
6682
virCgroupPtr cgroup = NULL;
6684
bool force = (flags & VIR_DOMAIN_DEVICE_MODIFY_FORCE) != 0;
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);
6691
if (flags & VIR_DOMAIN_DEVICE_MODIFY_CONFIG) {
6692
qemuReportError(VIR_ERR_OPERATION_INVALID,
6693
"%s", _("cannot modify the persistent configuration of a domain"));
6697
qemuDriverLock(driver);
6698
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
6707
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6710
if (!virDomainObjIsActive(vm)) {
6711
qemuReportError(VIR_ERR_OPERATION_INVALID,
6712
"%s", _("cannot attach device on inactive domain"));
6716
dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
6717
VIR_DOMAIN_XML_INACTIVE);
6721
if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
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"),
6735
if (qemuSetupDiskCgroup(driver, cgroup, dev->data.disk) < 0)
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,
6747
dev->data.disk = NULL;
6752
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6753
_("disk bus '%s' cannot be updated."),
6754
virDomainDiskBusTypeToString(dev->data.disk->bus));
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));
6765
case VIR_DOMAIN_DEVICE_GRAPHICS:
6766
ret = qemuDomainChangeGraphics(driver, vm, dev->data.graphics);
6770
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6771
_("disk device type '%s' cannot be updated"),
6772
virDomainDiskDeviceTypeToString(dev->data.disk->device));
6776
if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
6780
if (qemuDomainObjEndJob(vm) == 0)
6785
virCgroupFree(&cgroup);
6787
virDomainDeviceDefFree(dev);
6789
virDomainObjUnlock(vm);
6790
qemuDriverUnlock(driver);
6795
static int qemudDomainDetachDevice(virDomainPtr dom,
6797
struct qemud_driver *driver = dom->conn->privateData;
6799
unsigned long long qemuCmdFlags;
6800
virDomainDeviceDefPtr dev = NULL;
6803
qemuDriverLock(driver);
6804
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
6813
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
6816
if (!virDomainObjIsActive(vm)) {
6817
qemuReportError(VIR_ERR_OPERATION_INVALID,
6818
"%s", _("cannot detach device on inactive domain"));
6822
dev = virDomainDeviceDefParse(driver->caps, vm->def, xml,
6823
VIR_DOMAIN_XML_INACTIVE);
6827
if (qemuCapsExtractVersionInfo(vm->def->emulator, vm->def->os.arch,
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);
6837
else if (dev->data.disk->bus == VIR_DOMAIN_DISK_BUS_SCSI) {
6838
ret = qemuDomainDetachSCSIDiskDevice(driver, vm, dev,
6842
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED, "%s",
6843
_("This type of disk cannot be hot unplugged"));
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,
6852
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6853
_("disk controller bus '%s' cannot be hotunplugged."),
6854
virDomainControllerTypeToString(dev->data.controller->type));
6857
} else if (dev->type == VIR_DOMAIN_DEVICE_HOSTDEV) {
6858
ret = qemuDomainDetachHostDevice(driver, vm, dev, qemuCmdFlags);
6860
qemuReportError(VIR_ERR_CONFIG_UNSUPPORTED,
6861
"%s", _("This type of device cannot be hot unplugged"));
6864
if (!ret && virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0)
6868
if (qemuDomainObjEndJob(vm) == 0)
6872
virDomainDeviceDefFree(dev);
6874
virDomainObjUnlock(vm);
6875
qemuDriverUnlock(driver);
6879
static int qemudDomainDetachDeviceFlags(virDomainPtr dom,
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"));
6888
return qemudDomainDetachDevice(dom, xml);
6891
static int qemudDomainGetAutostart(virDomainPtr dom,
6893
struct qemud_driver *driver = dom->conn->privateData;
6897
qemuDriverLock(driver);
6898
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
6899
qemuDriverUnlock(driver);
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);
6909
*autostart = vm->autostart;
6914
virDomainObjUnlock(vm);
6918
static int qemudDomainSetAutostart(virDomainPtr dom,
6920
struct qemud_driver *driver = dom->conn->privateData;
6922
char *configFile = NULL, *autostartLink = NULL;
6925
qemuDriverLock(driver);
6926
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
6936
if (!vm->persistent) {
6937
qemuReportError(VIR_ERR_OPERATION_INVALID,
6938
"%s", _("cannot set autostart for transient domain"));
6942
autostart = (autostart != 0);
6944
if (vm->autostart != autostart) {
6945
if ((configFile = virDomainConfigFile(driver->configDir, vm->def->name)) == NULL)
6947
if ((autostartLink = virDomainConfigFile(driver->autostartDir, vm->def->name)) == NULL)
6953
if ((err = virFileMakePath(driver->autostartDir))) {
6954
virReportSystemError(err,
6955
_("cannot create autostart directory %s"),
6956
driver->autostartDir);
6960
if (symlink(configFile, autostartLink) < 0) {
6961
virReportSystemError(errno,
6962
_("Failed to create symlink '%s to '%s'"),
6963
autostartLink, configFile);
6967
if (unlink(autostartLink) < 0 && errno != ENOENT && errno != ENOTDIR) {
6968
virReportSystemError(errno,
6969
_("Failed to delete symlink '%s'"),
6975
vm->autostart = autostart;
6980
VIR_FREE(configFile);
6981
VIR_FREE(autostartLink);
6983
virDomainObjUnlock(vm);
6984
qemuDriverUnlock(driver);
6989
static char *qemuGetSchedulerType(virDomainPtr dom,
6992
struct qemud_driver *driver = dom->conn->privateData;
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"));
7005
ret = strdup("posix");
7007
virReportOOMError();
7010
qemuDriverUnlock(driver);
7015
static int qemuDomainSetMemoryParameters(virDomainPtr dom,
7016
virMemoryParameterPtr params,
7018
unsigned int flags ATTRIBUTE_UNUSED)
7020
struct qemud_driver *driver = dom->conn->privateData;
7022
virCgroupPtr group = NULL;
7023
virDomainObjPtr vm = NULL;
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"));
7033
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7036
qemuReportError(VIR_ERR_INTERNAL_ERROR,
7037
_("No such domain %s"), dom->uuid);
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);
7048
for (i = 0; i < nparams; i++) {
7049
virMemoryParameterPtr param = ¶ms[i];
7051
if (STREQ(param->field, VIR_DOMAIN_MEMORY_HARD_LIMIT)) {
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'"));
7060
rc = virCgroupSetMemoryHardLimit(group, params[i].value.ul);
7062
virReportSystemError(-rc, "%s",
7063
_("unable to set memory hard_limit tunable"));
7066
} else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SOFT_LIMIT)) {
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'"));
7075
rc = virCgroupSetMemorySoftLimit(group, params[i].value.ul);
7077
virReportSystemError(-rc, "%s",
7078
_("unable to set memory soft_limit tunable"));
7081
} else if (STREQ(param->field, VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT)) {
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'"));
7090
rc = virCgroupSetSwapHardLimit(group, params[i].value.ul);
7092
virReportSystemError(-rc, "%s",
7093
_("unable to set swap_hard_limit tunable"));
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);
7101
qemuReportError(VIR_ERR_INVALID_ARG,
7102
_("Parameter `%s' not supported"), param->field);
7108
virCgroupFree(&group);
7110
virDomainObjUnlock(vm);
7111
qemuDriverUnlock(driver);
7115
static int qemuDomainGetMemoryParameters(virDomainPtr dom,
7116
virMemoryParameterPtr params,
7118
unsigned int flags ATTRIBUTE_UNUSED)
7120
struct qemud_driver *driver = dom->conn->privateData;
7122
virCgroupPtr group = NULL;
7123
virDomainObjPtr vm = NULL;
7124
unsigned long long val;
7128
qemuDriverLock(driver);
7130
if (!qemuCgroupControllerActive(driver, VIR_CGROUP_CONTROLLER_MEMORY)) {
7131
qemuReportError(VIR_ERR_OPERATION_INVALID,
7132
"%s", _("cgroup memory controller is not mounted"));
7136
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7139
qemuReportError(VIR_ERR_INTERNAL_ERROR,
7140
_("No such domain %s"), dom->uuid);
7144
if ((*nparams) == 0) {
7145
/* Current number of memory parameters supported by cgroups */
7146
*nparams = QEMU_NB_MEM_PARAM;
7151
if ((*nparams) != QEMU_NB_MEM_PARAM) {
7152
qemuReportError(VIR_ERR_INVALID_ARG,
7153
"%s", _("Invalid parameter count"));
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);
7163
for (i = 0; i < *nparams; i++) {
7164
virMemoryParameterPtr param = ¶ms[i];
7166
param->value.ul = 0;
7167
param->type = VIR_DOMAIN_MEMORY_PARAM_ULLONG;
7170
case 0: /* fill memory hard limit here */
7171
rc = virCgroupGetMemoryHardLimit(group, &val);
7173
virReportSystemError(-rc, "%s",
7174
_("unable to get memory hard limit"));
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"));
7182
param->value.ul = val;
7185
case 1: /* fill memory soft limit here */
7186
rc = virCgroupGetMemorySoftLimit(group, &val);
7188
virReportSystemError(-rc, "%s",
7189
_("unable to get memory soft limit"));
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"));
7197
param->value.ul = val;
7200
case 2: /* fill swap hard limit here */
7201
rc = virCgroupGetSwapHardLimit(group, &val);
7203
virReportSystemError(-rc, "%s",
7204
_("unable to get swap hard limit"));
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"));
7212
param->value.ul = val;
7217
/* should not hit here */
7225
virCgroupFree(&group);
7227
virDomainObjUnlock(vm);
7228
qemuDriverUnlock(driver);
7232
static int qemuSetSchedulerParameters(virDomainPtr dom,
7233
virSchedParameterPtr params,
7236
struct qemud_driver *driver = dom->conn->privateData;
7238
virCgroupPtr group = NULL;
7239
virDomainObjPtr vm = NULL;
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"));
7249
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7252
qemuReportError(VIR_ERR_INTERNAL_ERROR,
7253
_("No such domain %s"), dom->uuid);
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);
7263
for (i = 0; i < nparams; i++) {
7264
virSchedParameterPtr param = ¶ms[i];
7266
if (STREQ(param->field, "cpu_shares")) {
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'"));
7274
rc = virCgroupSetCpuShares(group, params[i].value.ul);
7276
virReportSystemError(-rc, "%s",
7277
_("unable to set cpu shares tunable"));
7281
qemuReportError(VIR_ERR_INVALID_ARG,
7282
_("Invalid parameter `%s'"), param->field);
7289
virCgroupFree(&group);
7291
virDomainObjUnlock(vm);
7292
qemuDriverUnlock(driver);
7296
static int qemuGetSchedulerParameters(virDomainPtr dom,
7297
virSchedParameterPtr params,
7300
struct qemud_driver *driver = dom->conn->privateData;
7301
virCgroupPtr group = NULL;
7302
virDomainObjPtr vm = NULL;
7303
unsigned long long val;
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"));
7314
if ((*nparams) != 1) {
7315
qemuReportError(VIR_ERR_INVALID_ARG,
7316
"%s", _("Invalid parameter count"));
7320
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7323
qemuReportError(VIR_ERR_INTERNAL_ERROR,
7324
_("No such domain %s"), dom->uuid);
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);
7334
rc = virCgroupGetCpuShares(group, &val);
7336
virReportSystemError(-rc, "%s",
7337
_("unable to get cpu shares tunable"));
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"));
7351
virCgroupFree(&group);
7353
virDomainObjUnlock(vm);
7354
qemuDriverUnlock(driver);
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.
7364
qemudDomainBlockStats (virDomainPtr dom,
7366
struct _virDomainBlockStats *stats)
7368
struct qemud_driver *driver = dom->conn->privateData;
7371
virDomainDiskDefPtr disk = NULL;
7373
qemuDriverLock(driver);
7374
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7375
qemuDriverUnlock(driver);
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);
7384
if (qemuDomainObjBeginJob(vm) < 0)
7387
if (!virDomainObjIsActive (vm)) {
7388
qemuReportError(VIR_ERR_OPERATION_INVALID,
7389
"%s", _("domain is not running"));
7393
for (i = 0 ; i < vm->def->ndisks ; i++) {
7394
if (STREQ(path, vm->def->disks[i]->dst)) {
7395
disk = vm->def->disks[i];
7401
qemuReportError(VIR_ERR_INVALID_ARG,
7402
_("invalid path: %s"), path);
7406
if (!disk->info.alias) {
7407
qemuReportError(VIR_ERR_INTERNAL_ERROR,
7408
_("missing disk device alias name for %s"), disk->dst);
7412
qemuDomainObjPrivatePtr priv = vm->privateData;
7413
qemuDomainObjEnterMonitor(vm);
7414
ret = qemuMonitorGetBlockStatsInfo(priv->mon,
7421
qemuDomainObjExitMonitor(vm);
7424
if (qemuDomainObjEndJob(vm) == 0)
7429
virDomainObjUnlock(vm);
7435
qemudDomainInterfaceStats (virDomainPtr dom,
7437
struct _virDomainInterfaceStats *stats)
7439
struct qemud_driver *driver = dom->conn->privateData;
7444
qemuDriverLock(driver);
7445
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7446
qemuDriverUnlock(driver);
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);
7456
if (!virDomainObjIsActive(vm)) {
7457
qemuReportError(VIR_ERR_OPERATION_INVALID,
7458
"%s", _("domain is not running"));
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)) {
7472
ret = linuxDomainInterfaceStats(path, stats);
7474
qemuReportError(VIR_ERR_INVALID_ARG,
7475
_("invalid path, '%s' is not a known interface"), path);
7479
virDomainObjUnlock(vm);
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__);
7494
qemudDomainMemoryStats (virDomainPtr dom,
7495
struct _virDomainMemoryStat *stats,
7496
unsigned int nr_stats)
7498
struct qemud_driver *driver = dom->conn->privateData;
7500
unsigned int ret = -1;
7502
qemuDriverLock(driver);
7503
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7504
qemuDriverUnlock(driver);
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);
7514
if (qemuDomainObjBeginJob(vm) < 0)
7517
if (virDomainObjIsActive(vm)) {
7518
qemuDomainObjPrivatePtr priv = vm->privateData;
7519
qemuDomainObjEnterMonitor(vm);
7520
ret = qemuMonitorGetMemoryStats(priv->mon, stats, nr_stats);
7521
qemuDomainObjExitMonitor(vm);
7523
qemuReportError(VIR_ERR_OPERATION_INVALID,
7524
"%s", _("domain is not running"));
7527
if (qemuDomainObjEndJob(vm) == 0)
7532
virDomainObjUnlock(vm);
7537
qemudDomainBlockPeek (virDomainPtr dom,
7539
unsigned long long offset, size_t size,
7541
unsigned int flags ATTRIBUTE_UNUSED)
7543
struct qemud_driver *driver = dom->conn->privateData;
7545
int fd = -1, ret = -1, i;
7547
qemuDriverLock(driver);
7548
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7549
qemuDriverUnlock(driver);
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);
7559
if (!path || path[0] == '\0') {
7560
qemuReportError(VIR_ERR_INVALID_ARG,
7561
"%s", _("NULL or empty path"));
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)) {
7576
/* The path is correct, now try to open it and get its size. */
7577
fd = open (path, O_RDONLY);
7579
virReportSystemError(errno,
7580
_("%s: failed to open"), path);
7584
/* Seek and read. */
7585
/* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
7586
* be 64 bits on all platforms.
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);
7597
qemuReportError(VIR_ERR_INVALID_ARG,
7598
"%s", _("invalid path"));
7602
VIR_FORCE_CLOSE(fd);
7604
virDomainObjUnlock(vm);
7609
qemudDomainMemoryPeek (virDomainPtr dom,
7610
unsigned long long offset, size_t size,
7614
struct qemud_driver *driver = dom->conn->privateData;
7617
int fd = -1, ret = -1;
7619
qemuDriverLock(driver);
7620
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7621
qemuDriverUnlock(driver);
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);
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"));
7637
if (qemuDomainObjBeginJob(vm) < 0)
7640
if (!virDomainObjIsActive(vm)) {
7641
qemuReportError(VIR_ERR_OPERATION_INVALID,
7642
"%s", _("domain is not running"));
7646
if (virAsprintf(&tmp, "%s/qemu.mem.XXXXXX", driver->cacheDir) < 0) {
7647
virReportOOMError();
7651
/* Create a temporary filename. */
7652
if ((fd = mkstemp (tmp)) == -1) {
7653
virReportSystemError(errno,
7654
_("mkstemp(\"%s\") failed"), tmp);
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);
7666
if (qemuMonitorSavePhysicalMemory(priv->mon, offset, size, tmp) < 0) {
7667
qemuDomainObjExitMonitor(vm);
7671
qemuDomainObjExitMonitor(vm);
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);
7684
if (qemuDomainObjEndJob(vm) == 0)
7689
VIR_FORCE_CLOSE(fd);
7692
virDomainObjUnlock(vm);
7697
static int qemuDomainGetBlockInfo(virDomainPtr dom,
7699
virDomainBlockInfoPtr info,
7700
unsigned int flags) {
7701
struct qemud_driver *driver = dom->conn->privateData;
7706
virStorageFileMetadata meta;
7707
virDomainDiskDefPtr disk = NULL;
7712
virCheckFlags(0, -1);
7714
qemuDriverLock(driver);
7715
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
7716
qemuDriverUnlock(driver);
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);
7725
if (!path || path[0] == '\0') {
7726
qemuReportError(VIR_ERR_INVALID_ARG,
7727
"%s", _("NULL or empty path"));
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];
7741
qemuReportError(VIR_ERR_INVALID_ARG,
7742
_("invalid path %s not assigned to domain"), path);
7746
/* The path is correct, now try to open it and get its size. */
7747
fd = open (path, O_RDONLY);
7749
virReportSystemError(errno,
7750
_("failed to open path '%s'"), path);
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);
7763
if (driver->allowDiskFormatProbing) {
7764
if ((format = virStorageFileProbeFormat(disk->src)) < 0)
7767
qemuReportError(VIR_ERR_INTERNAL_ERROR,
7768
_("no disk format for %s and probing is disabled"),
7774
if (virStorageFileGetMetadataFromFD(path, fd,
7779
/* Get info for normal formats */
7780
if (fstat(fd, &sb) < 0) {
7781
virReportSystemError(errno,
7782
_("cannot stat file '%s'"), path);
7786
if (S_ISREG(sb.st_mode)) {
7788
info->physical = (unsigned long long)sb.st_blocks *
7789
(unsigned long long)DEV_BSIZE;
7791
info->physical = sb.st_size;
7793
/* Regular files may be sparse, so logical size (capacity) is not same
7794
* as actual physical above
7796
info->capacity = sb.st_size;
7798
/* NB. Because we configure with AC_SYS_LARGEFILE, off_t should
7799
* be 64 bits on all platforms.
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);
7807
info->physical = end;
7808
info->capacity = end;
7811
/* If the file we probed has a capacity set, then override
7812
* what we calculated from file/block extents */
7814
info->capacity = meta.capacity;
7816
/* Set default value .. */
7817
info->allocation = info->physical;
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)
7828
if (!virDomainObjIsActive(vm))
7831
qemuDomainObjEnterMonitor(vm);
7832
ret = qemuMonitorGetBlockExtent(priv->mon,
7835
qemuDomainObjExitMonitor(vm);
7838
if (qemuDomainObjEndJob(vm) == 0)
7845
VIR_FORCE_CLOSE(fd);
7847
virDomainObjUnlock(vm);
7853
qemuDomainEventRegister(virConnectPtr conn,
7854
virConnectDomainEventCallback callback,
7856
virFreeCallback freecb)
7858
struct qemud_driver *driver = conn->privateData;
7861
qemuDriverLock(driver);
7862
ret = virDomainEventCallbackListAdd(conn, driver->domainEventCallbacks,
7863
callback, opaque, freecb);
7864
qemuDriverUnlock(driver);
7871
qemuDomainEventDeregister(virConnectPtr conn,
7872
virConnectDomainEventCallback callback)
7874
struct qemud_driver *driver = conn->privateData;
7877
qemuDriverLock(driver);
7878
if (driver->domainEventDispatching)
7879
ret = virDomainEventCallbackListMarkDelete(conn, driver->domainEventCallbacks,
7882
ret = virDomainEventCallbackListRemove(conn, driver->domainEventCallbacks,
7884
qemuDriverUnlock(driver);
7891
qemuDomainEventRegisterAny(virConnectPtr conn,
7894
virConnectDomainEventGenericCallback callback,
7896
virFreeCallback freecb)
7898
struct qemud_driver *driver = conn->privateData;
7901
qemuDriverLock(driver);
7902
ret = virDomainEventCallbackListAddID(conn,
7903
driver->domainEventCallbacks,
7905
callback, opaque, freecb);
7906
qemuDriverUnlock(driver);
7913
qemuDomainEventDeregisterAny(virConnectPtr conn,
7916
struct qemud_driver *driver = conn->privateData;
7919
qemuDriverLock(driver);
7920
if (driver->domainEventDispatching)
7921
ret = virDomainEventCallbackListMarkDeleteID(conn, driver->domainEventCallbacks,
7924
ret = virDomainEventCallbackListRemoveID(conn, driver->domainEventCallbacks,
7926
qemuDriverUnlock(driver);
7932
static void qemuDomainEventDispatchFunc(virConnectPtr conn,
7933
virDomainEventPtr event,
7934
virConnectDomainEventGenericCallback cb,
7938
struct qemud_driver *driver = opaque;
7940
/* Drop the lock whle dispatching, for sake of re-entrancy */
7941
qemuDriverUnlock(driver);
7942
virDomainEventDispatchDefaultFunc(conn, event, cb, cbopaque, NULL);
7943
qemuDriverLock(driver);
7946
static void qemuDomainEventFlush(int timer ATTRIBUTE_UNUSED, void *opaque)
7948
struct qemud_driver *driver = opaque;
7949
virDomainEventQueue tempQueue;
7951
qemuDriverLock(driver);
7953
driver->domainEventDispatching = 1;
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;
7961
virEventUpdateTimeout(driver->domainEventTimer, -1);
7962
virDomainEventQueueDispatch(&tempQueue,
7963
driver->domainEventCallbacks,
7964
qemuDomainEventDispatchFunc,
7967
/* Purge any deleted callbacks */
7968
virDomainEventCallbackListPurgeMarked(driver->domainEventCallbacks);
7970
driver->domainEventDispatching = 0;
7971
qemuDriverUnlock(driver);
7975
/* driver must be locked before calling */
7976
static void qemuDomainEventQueue(struct qemud_driver *driver,
7977
virDomainEventPtr event)
7979
if (virDomainEventQueuePush(driver->domainEventQueue,
7981
virDomainEventFree(event);
7982
if (qemu_driver->domainEventQueue->count == 1)
7983
virEventUpdateTimeout(driver->domainEventTimer, 0);
7986
/* Migration support. */
7988
static bool ATTRIBUTE_NONNULL(1)
7989
qemuDomainIsMigratable(virDomainDefPtr def)
7991
if (def->nhostdevs > 0) {
7992
qemuReportError(VIR_ERR_OPERATION_INVALID,
7993
"%s", _("Domain with assigned host devices cannot be migrated"));
8000
/* Prepare is the first step, and it runs on the destination host.
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.
8006
qemudDomainMigratePrepareTunnel(virConnectPtr dconn,
8008
unsigned long flags,
8010
unsigned long resource ATTRIBUTE_UNUSED,
8011
const char *dom_xml)
8013
struct qemud_driver *driver = dconn->privateData;
8014
virDomainDefPtr def = NULL;
8015
virDomainObjPtr vm = NULL;
8017
virDomainEventPtr event = NULL;
8020
char *unixfile = NULL;
8021
unsigned long long qemuCmdFlags;
8022
qemuDomainObjPrivatePtr priv = NULL;
8025
if (gettimeofday(&now, NULL) < 0) {
8026
virReportSystemError(errno, "%s",
8027
_("cannot get time of day"));
8031
qemuDriverLock(driver);
8033
qemuReportError(VIR_ERR_INTERNAL_ERROR,
8034
"%s", _("no domain XML passed"));
8037
if (!(flags & VIR_MIGRATE_TUNNELLED)) {
8038
qemuReportError(VIR_ERR_INTERNAL_ERROR,
8039
"%s", _("PrepareTunnel called but no TUNNELLED flag set"));
8043
qemuReportError(VIR_ERR_INTERNAL_ERROR,
8044
"%s", _("tunnelled migration requested but NULL stream passed"));
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"));
8057
if (!qemuDomainIsMigratable(def))
8060
/* Target domain name, maybe renamed. */
8062
VIR_FREE(def->name);
8063
def->name = strdup(dname);
8064
if (def->name == NULL)
8068
if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
8071
if (!(vm = virDomainAssignDef(driver->caps,
8074
/* virDomainAssignDef already set the error */
8078
priv = vm->privateData;
8080
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
8082
priv->jobActive = QEMU_JOB_MIGRATION_OUT;
8084
/* Domain starts inactive, even if the domain XML had an id field. */
8087
if (virAsprintf(&unixfile, "%s/qemu.tunnelmigrate.dest.%s",
8088
driver->libDir, vm->def->name) < 0) {
8089
virReportOOMError();
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"),
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);
8107
qemuReportError(VIR_ERR_OPERATION_FAILED,
8108
"%s", _("Destination qemu is too old to support tunnelled migration"));
8111
if (internalret < 0) {
8112
virReportOOMError();
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
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.
8126
if (!vm->persistent) {
8127
virDomainRemoveInactive(&driver->domains, vm);
8133
if (virFDStreamConnectUNIX(st,
8136
qemuDomainStartAudit(vm, "migrated", false);
8137
qemudShutdownVMDaemon(driver, vm, 0);
8138
if (!vm->persistent) {
8139
if (qemuDomainObjEndJob(vm) > 0)
8140
virDomainRemoveInactive(&driver->domains, vm);
8143
virReportSystemError(errno,
8144
_("cannot open unix socket '%s' for tunnelled migration"),
8149
qemuDomainStartAudit(vm, "migrated", true);
8151
event = virDomainEventNewFromObj(vm,
8152
VIR_DOMAIN_EVENT_STARTED,
8153
VIR_DOMAIN_EVENT_STARTED_MIGRATED);
8158
qemuDomainObjEndJob(vm) == 0)
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
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);
8174
virDomainDefFree(def);
8179
virDomainObjUnlock(vm);
8181
qemuDomainEventQueue(driver, event);
8182
qemuDriverUnlock(driver);
8186
/* Prepare is the first step, and it runs on the destination host.
8188
* This starts an empty VM listening on a TCP port.
8190
static int ATTRIBUTE_NONNULL (5)
8191
qemudDomainMigratePrepare2 (virConnectPtr dconn,
8192
char **cookie ATTRIBUTE_UNUSED,
8193
int *cookielen ATTRIBUTE_UNUSED,
8196
unsigned long flags,
8198
unsigned long resource ATTRIBUTE_UNUSED,
8199
const char *dom_xml)
8201
static int port = 0;
8202
struct qemud_driver *driver = dconn->privateData;
8203
virDomainDefPtr def = NULL;
8204
virDomainObjPtr vm = NULL;
8206
char *hostname = NULL;
8207
char migrateFrom [64];
8209
virDomainEventPtr event = NULL;
8212
qemuDomainObjPrivatePtr priv = NULL;
8215
if (gettimeofday(&now, NULL) < 0) {
8216
virReportSystemError(errno, "%s",
8217
_("cannot get time of day"));
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);
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
8237
qemuReportError(VIR_ERR_INTERNAL_ERROR,
8238
"%s", _("Tunnelled migration requested but invalid RPC method called"));
8243
qemuReportError(VIR_ERR_INTERNAL_ERROR,
8244
"%s", _("no domain XML passed"));
8248
/* The URI passed in may be NULL or a string "tcp://somehostname:port".
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".
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).
8258
if (uri_in == NULL) {
8259
this_port = QEMUD_MIGRATION_FIRST_PORT + port++;
8260
if (port == QEMUD_MIGRATION_NUM_PORTS) port = 0;
8263
if ((hostname = virGetHostname(NULL)) == NULL)
8266
if (STRPREFIX(hostname, "localhost")) {
8267
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8268
_("hostname on destination resolved to localhost, but migration requires an FQDN"));
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.
8278
internalret = virAsprintf(uri_out, "tcp:%s:%d", hostname, this_port);
8279
if (internalret < 0) {
8280
virReportOOMError();
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.
8288
if (!STRPREFIX (uri_in, "tcp:")) {
8289
qemuReportError (VIR_ERR_INVALID_ARG,
8290
"%s", _("only tcp URIs are supported for KVM/QEMU migrations"));
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)
8303
if (virAsprintf(uri_out, "%s:%d", uri_in, this_port) < 0) {
8304
virReportOOMError();
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'"));
8320
VIR_DEBUG("Generated uri_out=%s", *uri_out);
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"));
8330
if (!qemuDomainIsMigratable(def))
8333
/* Target domain name, maybe renamed. */
8335
VIR_FREE(def->name);
8336
def->name = strdup(dname);
8337
if (def->name == NULL)
8341
if (virDomainObjIsDuplicate(&driver->domains, def, 1) < 0)
8344
if (!(vm = virDomainAssignDef(driver->caps,
8347
/* virDomainAssignDef already set the error */
8351
priv = vm->privateData;
8353
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
8355
priv->jobActive = QEMU_JOB_MIGRATION_OUT;
8357
/* Domain starts inactive, even if the domain XML had an id field. */
8360
/* Start the QEMU daemon, with the same command-line arguments plus
8361
* -incoming tcp:0.0.0.0:port
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.
8370
if (!vm->persistent) {
8371
if (qemuDomainObjEndJob(vm) > 0)
8372
virDomainRemoveInactive(&driver->domains, vm);
8378
qemuDomainStartAudit(vm, "migrated", true);
8379
event = virDomainEventNewFromObj(vm,
8380
VIR_DOMAIN_EVENT_STARTED,
8381
VIR_DOMAIN_EVENT_STARTED_MIGRATED);
8386
qemuDomainObjEndJob(vm) == 0)
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
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);
8403
virDomainDefFree(def);
8407
virDomainObjUnlock(vm);
8409
qemuDomainEventQueue(driver, event);
8410
qemuDriverUnlock(driver);
8416
/* Perform migration using QEMU's native TCP migrate support,
8417
* not encrypted obviously
8419
static int doNativeMigrate(struct qemud_driver *driver,
8423
const char *dname ATTRIBUTE_UNUSED,
8424
unsigned long resource)
8427
xmlURIPtr uribits = NULL;
8428
qemuDomainObjPrivatePtr priv = vm->privateData;
8429
unsigned int background_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
8431
/* Issue the migrate command. */
8432
if (STRPREFIX(uri, "tcp:") && !STRPREFIX(uri, "tcp://")) {
8433
/* HACK: source host generates bogus URIs, so fix them up */
8435
if (virAsprintf(&tmpuri, "tcp://%s", uri + strlen("tcp:")) < 0) {
8436
virReportOOMError();
8439
uribits = xmlParseURI(tmpuri);
8442
uribits = xmlParseURI(uri);
8445
qemuReportError(VIR_ERR_INTERNAL_ERROR,
8446
_("cannot parse URI %s"), uri);
8450
qemuDomainObjEnterMonitorWithDriver(driver, vm);
8452
qemuMonitorSetMigrationSpeed(priv->mon, resource) < 0) {
8453
qemuDomainObjExitMonitorWithDriver(driver, vm);
8457
if (flags & VIR_MIGRATE_NON_SHARED_DISK)
8458
background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_DISK;
8460
if (flags & VIR_MIGRATE_NON_SHARED_INC)
8461
background_flags |= QEMU_MONITOR_MIGRATE_NON_SHARED_INC;
8463
if (qemuMonitorMigrateToHost(priv->mon, background_flags, uribits->server,
8464
uribits->port) < 0) {
8465
qemuDomainObjExitMonitorWithDriver(driver, vm);
8468
qemuDomainObjExitMonitorWithDriver(driver, vm);
8470
if (qemuDomainWaitForMigrationComplete(driver, vm) < 0)
8476
xmlFreeURI(uribits);
8481
#define TUNNEL_SEND_BUF_SIZE 65536
8483
static int doTunnelSendAll(virStreamPtr st,
8487
int nbytes = TUNNEL_SEND_BUF_SIZE;
8489
if (VIR_ALLOC_N(buffer, TUNNEL_SEND_BUF_SIZE) < 0) {
8490
virReportOOMError();
8495
/* XXX should honour the 'resource' parameter here */
8497
nbytes = saferead(sock, buffer, nbytes);
8499
virReportSystemError(errno, "%s",
8500
_("tunnelled migration failed to read from qemu"));
8505
else if (nbytes == 0)
8506
/* EOF; get out of here */
8509
if (virStreamSend(st, buffer, nbytes) < 0) {
8510
qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
8511
_("Failed to write migration data to remote libvirtd"));
8519
if (virStreamFinish(st) < 0)
8520
/* virStreamFinish set the error for us */
8526
static int doTunnelMigrate(virDomainPtr dom,
8527
struct qemud_driver *driver,
8528
virConnectPtr dconn,
8530
const char *dom_xml,
8532
unsigned long flags,
8534
unsigned long resource)
8536
qemuDomainObjPrivatePtr priv = vm->privateData;
8537
int client_sock = -1;
8539
struct sockaddr_un sa_qemu, sa_client;
8541
virDomainPtr ddomain = NULL;
8543
virStreamPtr st = NULL;
8544
char *unixfile = NULL;
8546
unsigned long long qemuCmdFlags;
8548
unsigned long long transferred, remaining, total;
8549
unsigned int background_flags = QEMU_MONITOR_MIGRATE_BACKGROUND;
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.
8556
* 1. setup local support infrastructure (eg sockets)
8557
* 2. setup destination fully
8558
* 3. start migration on source
8562
/* Stage 1. setup local support infrastructure */
8564
if (virAsprintf(&unixfile, "%s/qemu.tunnelmigrate.src.%s",
8565
driver->libDir, vm->def->name) < 0) {
8566
virReportOOMError();
8570
qemu_sock = socket(AF_UNIX, SOCK_STREAM, 0);
8571
if (qemu_sock < 0) {
8572
virReportSystemError(errno, "%s",
8573
_("cannot open tunnelled migration socket"));
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"),
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"),
8592
if (listen(qemu_sock, 1) < 0) {
8593
virReportSystemError(errno,
8594
_("Cannot listen on unix socket '%s' for tunnelled migration"),
8599
if (chown(unixfile, qemu_driver->user, qemu_driver->group) < 0) {
8600
virReportSystemError(errno,
8601
_("Cannot change unix socket '%s' owner"),
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'"),
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"));
8623
/* Stage 2. setup destination fully
8625
* Once stage 2 has completed successfully, we *must* call finish
8626
* to cleanup the target whether we succeed or fail
8628
st = virStreamNew(dconn, 0);
8630
/* virStreamNew only fails on OOM, and it reports the error itself */
8633
qemuDomainObjEnterRemoteWithDriver(driver, vm);
8634
internalret = dconn->driver->domainMigratePrepareTunnel(dconn, st,
8637
qemuDomainObjExitRemoteWithDriver(driver, vm);
8639
if (internalret < 0)
8640
/* domainMigratePrepareTunnel sets the error for us */
8643
/* the domain may have shutdown or crashed while we had the locks dropped
8644
* in qemuDomainObjEnterRemoteWithDriver, so check again
8646
if (!virDomainObjIsActive(vm)) {
8647
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8648
_("guest unexpectedly quit"));
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,
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);
8668
qemuDomainObjExitMonitorWithDriver(driver, vm);
8669
if (internalret < 0) {
8670
qemuReportError(VIR_ERR_OPERATION_FAILED,
8671
"%s", _("tunnelled migration monitor command failed"));
8675
if (!virDomainObjIsActive(vm)) {
8676
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8677
_("guest unexpectedly quit"));
8681
/* From this point onwards we *must* call cancel to abort the
8682
* migration on source if anything goes wrong */
8684
/* it is also possible that the migrate didn't fail initially, but
8685
* rather failed later on. Check the output of "info migrate"
8687
qemuDomainObjEnterMonitorWithDriver(driver, vm);
8688
if (qemuMonitorGetMigrationStatus(priv->mon,
8693
qemuDomainObjExitMonitorWithDriver(driver, vm);
8696
qemuDomainObjExitMonitorWithDriver(driver, vm);
8698
if (status == QEMU_MONITOR_MIGRATION_STATUS_ERROR) {
8699
qemuReportError(VIR_ERR_OPERATION_FAILED,
8700
"%s",_("migrate failed"));
8704
addrlen = sizeof(sa_client);
8705
while ((client_sock = accept(qemu_sock, (struct sockaddr *)&sa_client, &addrlen)) < 0) {
8706
if (errno == EAGAIN || errno == EINTR)
8708
virReportSystemError(errno, "%s",
8709
_("tunnelled migration failed to accept from qemu"));
8713
retval = doTunnelSendAll(st, client_sock);
8716
if (retval != 0 && virDomainObjIsActive(vm)) {
8717
qemuDomainObjEnterMonitorWithDriver(driver, vm);
8718
qemuMonitorMigrateCancel(priv->mon);
8719
qemuDomainObjExitMonitorWithDriver(driver, vm);
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);
8730
VIR_FORCE_CLOSE(client_sock);
8731
VIR_FORCE_CLOSE(qemu_sock);
8734
virUnrefDomain(ddomain);
8742
/* don't call virStreamFree(), because that resets any pending errors */
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,
8755
const char *dom_xml,
8756
const char *uri ATTRIBUTE_UNUSED,
8757
unsigned long flags,
8759
unsigned long resource)
8761
virDomainPtr ddomain = NULL;
8763
char *uri_out = NULL;
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,
8776
qemuDomainObjExitRemoteWithDriver(driver, vm);
8778
/* domainMigratePrepare2 sets the error for us */
8781
/* the domain may have shutdown or crashed while we had the locks dropped
8782
* in qemuDomainObjEnterRemoteWithDriver, so check again
8784
if (!virDomainObjIsActive(vm)) {
8785
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8786
_("guest unexpectedly quit"));
8790
if (uri_out == NULL) {
8791
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
8792
_("domainMigratePrepare2 did not set uri"));
8796
if (doNativeMigrate(driver, vm, uri_out, flags, dname, resource) < 0)
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);
8809
virUnrefDomain(ddomain);
8816
static int doPeer2PeerMigrate(virDomainPtr dom,
8817
struct qemud_driver *driver,
8820
unsigned long flags,
8822
unsigned long resource)
8825
virConnectPtr dconn = NULL;
8829
/* the order of operations is important here; we make sure the
8830
* destination side is completely setup before we touch the source
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);
8842
qemuDomainObjEnterRemoteWithDriver(driver, vm);
8843
p2p = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
8844
VIR_DRV_FEATURE_MIGRATION_P2P);
8845
qemuDomainObjExitRemoteWithDriver(driver, vm);
8847
qemuReportError(VIR_ERR_OPERATION_FAILED, "%s",
8848
_("Destination libvirt does not support peer-to-peer migration protocol"));
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"));
8859
dom_xml = qemudVMDumpXML(driver, vm,
8860
VIR_DOMAIN_XML_SECURE |
8861
VIR_DOMAIN_XML_UPDATE_CPU);
8863
qemuReportError(VIR_ERR_OPERATION_FAILED,
8864
"%s", _("failed to get domain xml"));
8868
if (flags & VIR_MIGRATE_TUNNELLED)
8869
ret = doTunnelMigrate(dom, driver, dconn, vm, dom_xml, uri, flags, dname, resource);
8871
ret = doNonTunnelMigrate(dom, driver, dconn, vm, dom_xml, uri, flags, dname, resource);
8875
/* don't call virConnectClose(), because that resets any pending errors */
8876
qemuDomainObjEnterRemoteWithDriver(driver, vm);
8877
virUnrefConnect(dconn);
8878
qemuDomainObjExitRemoteWithDriver(driver, vm);
8884
/* Perform is the second step, and it runs on the source host. */
8886
qemudDomainMigratePerform (virDomainPtr dom,
8887
const char *cookie ATTRIBUTE_UNUSED,
8888
int cookielen ATTRIBUTE_UNUSED,
8890
unsigned long flags,
8892
unsigned long resource)
8894
struct qemud_driver *driver = dom->conn->privateData;
8896
virDomainEventPtr event = NULL;
8899
qemuDomainObjPrivatePtr priv;
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);
8910
qemuDriverLock(driver);
8911
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
8919
priv = vm->privateData;
8921
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
8923
priv->jobActive = QEMU_JOB_MIGRATION_OUT;
8925
if (!virDomainObjIsActive(vm)) {
8926
qemuReportError(VIR_ERR_OPERATION_INVALID,
8927
"%s", _("domain is not running"));
8931
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
8932
priv->jobInfo.type = VIR_DOMAIN_JOB_UNBOUNDED;
8934
resume = vm->state == VIR_DOMAIN_RUNNING;
8935
if (!(flags & VIR_MIGRATE_LIVE) && vm->state == VIR_DOMAIN_RUNNING) {
8936
if (qemuDomainMigrateOffline(driver, vm) < 0)
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 */
8945
if (doNativeMigrate(driver, vm, uri, flags, dname, resource) < 0)
8949
/* Clean up the source domain. */
8950
qemudShutdownVMDaemon(driver, vm, 1);
8951
qemuDomainStopAudit(vm, "migrated");
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);
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
8973
VIR_ERROR(_("Failed to resume guest %s after failure"),
8977
event = virDomainEventNewFromObj(vm,
8978
VIR_DOMAIN_EVENT_RESUMED,
8979
VIR_DOMAIN_EVENT_RESUMED_MIGRATED);
8982
qemuDomainObjEndJob(vm) == 0)
8987
virDomainObjUnlock(vm);
8989
qemuDomainEventQueue(driver, event);
8990
qemuDriverUnlock(driver);
8996
qemudVPAssociatePortProfiles(virDomainDefPtr def) {
8998
int last_good_net = -1;
8999
virDomainNetDefPtr net;
9001
for (i = 0; i < def->nnets; i++) {
9003
if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
9004
if (vpAssociatePortProfileId(net->ifname,
9006
net->data.direct.linkdev,
9007
&net->data.direct.virtPortProfile,
9009
VIR_VM_OP_MIGRATE_IN_FINISH) != 0)
9018
for (i = 0; i < last_good_net; i++) {
9020
if (net->type == VIR_DOMAIN_NET_TYPE_DIRECT) {
9021
vpDisassociatePortProfileId(net->ifname,
9023
net->data.direct.linkdev,
9024
&net->data.direct.virtPortProfile,
9025
VIR_VM_OP_MIGRATE_IN_FINISH);
9029
#else /* !WITH_MACVTAP */
9031
qemudVPAssociatePortProfiles(virDomainDefPtr def ATTRIBUTE_UNUSED) { }
9032
#endif /* WITH_MACVTAP */
9034
/* Finish is the third and final step, and it runs on the destination host. */
9036
qemudDomainMigrateFinish2 (virConnectPtr dconn,
9038
const char *cookie ATTRIBUTE_UNUSED,
9039
int cookielen ATTRIBUTE_UNUSED,
9040
const char *uri ATTRIBUTE_UNUSED,
9041
unsigned long flags,
9044
struct qemud_driver *driver = dconn->privateData;
9046
virDomainPtr dom = NULL;
9047
virDomainEventPtr event = NULL;
9048
virErrorPtr orig_err;
9050
qemuDomainObjPrivatePtr priv = NULL;
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);
9061
/* Migration failed. Save the current error so nothing squashes it */
9062
orig_err = virSaveLastError();
9064
qemuDriverLock(driver);
9065
vm = virDomainFindByName(&driver->domains, dname);
9067
qemuReportError(VIR_ERR_NO_DOMAIN,
9068
_("no domain with matching name '%s'"), dname);
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);
9078
priv->jobActive = QEMU_JOB_NONE;
9079
memset(&priv->jobInfo, 0, sizeof(priv->jobInfo));
9081
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
9084
/* Did the migration go as planned? If yes, return the domain
9085
* object, but if no, clean up the empty qemu process.
9088
if (!virDomainObjIsActive(vm)) {
9089
qemuReportError(VIR_ERR_INTERNAL_ERROR, "%s",
9090
_("guest unexpectedly quit"));
9094
qemudVPAssociatePortProfiles(vm->def);
9096
if (flags & VIR_MIGRATE_PERSIST_DEST) {
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.
9115
event = virDomainEventNewFromObj(vm,
9116
VIR_DOMAIN_EVENT_DEFINED,
9118
VIR_DOMAIN_EVENT_DEFINED_ADDED :
9119
VIR_DOMAIN_EVENT_DEFINED_UPDATED);
9121
qemuDomainEventQueue(driver, event);
9125
dom = virGetDomain (dconn, vm->def->name, vm->def->uuid);
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
9132
if (doStartCPUs(driver, vm, dconn) < 0) {
9133
if (virGetLastError() == NULL)
9134
qemuReportError(VIR_ERR_INTERNAL_ERROR,
9135
"%s", _("resume operation failed"));
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);
9149
if (virDomainSaveStatus(driver->caps, driver->stateDir, vm) < 0) {
9150
VIR_WARN("Failed to save status on vm %s", vm->def->name);
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);
9168
qemuDomainObjEndJob(vm) == 0)
9173
virSetError(orig_err);
9174
virFreeError(orig_err);
9177
virDomainObjUnlock(vm);
9179
qemuDomainEventQueue(driver, event);
9180
qemuDriverUnlock(driver);
9185
qemudNodeDeviceGetPciInfo (virNodeDevicePtr dev,
9191
virNodeDeviceDefPtr def = NULL;
9192
virNodeDevCapsDefPtr cap;
9196
xml = virNodeDeviceGetXMLDesc(dev, 0);
9200
def = virNodeDeviceDefParseString(xml, EXISTING_DEVICE);
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;
9218
qemuReportError(VIR_ERR_INVALID_ARG,
9219
_("device %s is not a PCI device"), dev->name);
9225
virNodeDeviceDefFree(def);
9231
qemudNodeDeviceDettach (virNodeDevicePtr dev)
9233
struct qemud_driver *driver = dev->conn->privateData;
9235
unsigned domain, bus, slot, function;
9238
if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
9241
pci = pciGetDevice(domain, bus, slot, function);
9245
qemuDriverLock(driver);
9246
if (pciDettachDevice(pci, driver->activePciHostdevs) < 0)
9251
qemuDriverUnlock(driver);
9257
qemudNodeDeviceReAttach (virNodeDevicePtr dev)
9259
struct qemud_driver *driver = dev->conn->privateData;
9261
unsigned domain, bus, slot, function;
9264
if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
9267
pci = pciGetDevice(domain, bus, slot, function);
9271
qemuDriverLock(driver);
9272
if (pciReAttachDevice(pci, driver->activePciHostdevs) < 0)
9277
qemuDriverUnlock(driver);
9283
qemudNodeDeviceReset (virNodeDevicePtr dev)
9285
struct qemud_driver *driver = dev->conn->privateData;
9287
unsigned domain, bus, slot, function;
9290
if (qemudNodeDeviceGetPciInfo(dev, &domain, &bus, &slot, &function) < 0)
9293
pci = pciGetDevice(domain, bus, slot, function);
9297
qemuDriverLock(driver);
9299
if (pciResetDevice(pci, driver->activePciHostdevs, NULL) < 0)
9304
qemuDriverUnlock(driver);
9310
qemuCPUCompare(virConnectPtr conn,
9311
const char *xmlDesc,
9312
unsigned int flags ATTRIBUTE_UNUSED)
9314
struct qemud_driver *driver = conn->privateData;
9315
int ret = VIR_CPU_COMPARE_ERROR;
9317
qemuDriverLock(driver);
9319
if (!driver->caps || !driver->caps->host.cpu) {
9320
qemuReportError(VIR_ERR_NO_SUPPORT,
9321
"%s", _("cannot get host CPU capabilities"));
9324
ret = cpuCompareXML(driver->caps->host.cpu, xmlDesc);
9326
qemuDriverUnlock(driver);
9333
qemuCPUBaseline(virConnectPtr conn ATTRIBUTE_UNUSED,
9334
const char **xmlCPUs,
9336
unsigned int flags ATTRIBUTE_UNUSED)
9340
cpu = cpuBaselineXML(xmlCPUs, ncpus, NULL, 0);
9346
static int qemuDomainGetJobInfo(virDomainPtr dom,
9347
virDomainJobInfoPtr info) {
9348
struct qemud_driver *driver = dom->conn->privateData;
9351
qemuDomainObjPrivatePtr priv;
9353
qemuDriverLock(driver);
9354
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9355
qemuDriverUnlock(driver);
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);
9364
priv = vm->privateData;
9366
if (virDomainObjIsActive(vm)) {
9367
if (priv->jobActive) {
9370
memcpy(info, &priv->jobInfo, sizeof(*info));
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
9377
if (gettimeofday(&now, NULL) < 0) {
9378
virReportSystemError(errno, "%s",
9379
_("cannot get time of day"));
9382
info->timeElapsed = timeval_to_ms(now) - priv->jobStart;
9384
memset(info, 0, sizeof(*info));
9385
info->type = VIR_DOMAIN_JOB_NONE;
9388
qemuReportError(VIR_ERR_OPERATION_INVALID,
9389
"%s", _("domain is not running"));
9397
virDomainObjUnlock(vm);
9402
static int qemuDomainAbortJob(virDomainPtr dom) {
9403
struct qemud_driver *driver = dom->conn->privateData;
9406
qemuDomainObjPrivatePtr priv;
9408
qemuDriverLock(driver);
9409
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
9410
qemuDriverUnlock(driver);
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);
9419
priv = vm->privateData;
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;
9426
qemuReportError(VIR_ERR_OPERATION_INVALID,
9427
"%s", _("no job is active on the domain"));
9431
qemuReportError(VIR_ERR_OPERATION_INVALID,
9432
"%s", _("domain is not running"));
9440
virDomainObjUnlock(vm);
9446
qemuDomainMigrateSetMaxDowntime(virDomainPtr dom,
9447
unsigned long long downtime,
9450
struct qemud_driver *driver = dom->conn->privateData;
9452
qemuDomainObjPrivatePtr priv;
9455
virCheckFlags(0, -1);
9457
qemuDriverLock(driver);
9458
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
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);
9468
if (!virDomainObjIsActive(vm)) {
9469
qemuReportError(VIR_ERR_OPERATION_INVALID,
9470
"%s", _("domain is not running"));
9474
priv = vm->privateData;
9476
if (priv->jobActive != QEMU_JOB_MIGRATION_OUT) {
9477
qemuReportError(VIR_ERR_OPERATION_INVALID,
9478
"%s", _("domain is not being migrated"));
9482
VIR_DEBUG("Requesting migration downtime change to %llums", downtime);
9483
priv->jobSignals |= QEMU_JOB_SIGNAL_MIGRATE_DOWNTIME;
9484
priv->jobSignalsData.migrateDowntime = downtime;
9489
virDomainObjUnlock(vm);
9490
qemuDriverUnlock(driver);
9494
static char *qemuFindQemuImgBinary(void)
9498
ret = virFindFileInPath("kvm-img");
9500
ret = virFindFileInPath("qemu-img");
9502
qemuReportError(VIR_ERR_INTERNAL_ERROR,
9503
"%s", _("unable to find kvm-img or qemu-img"));
9508
static int qemuDomainSnapshotWriteMetadata(virDomainObjPtr vm,
9509
virDomainSnapshotObjPtr snapshot,
9513
char *newxml = NULL;
9515
char *snapDir = NULL;
9516
char *snapFile = NULL;
9518
char uuidstr[VIR_UUID_STRING_BUFLEN];
9520
virUUIDFormat(vm->def->uuid, uuidstr);
9521
newxml = virDomainSnapshotDefFormat(uuidstr, snapshot->def, 1);
9522
if (newxml == NULL) {
9523
virReportOOMError();
9527
if (virAsprintf(&snapDir, "%s/%s", snapshotDir, vm->def->name) < 0) {
9528
virReportOOMError();
9531
err = virFileMakePath(snapDir);
9533
virReportSystemError(err, _("cannot create snapshot directory '%s'"),
9538
if (virAsprintf(&snapFile, "%s/%s.xml", snapDir, snapshot->def->name) < 0) {
9539
virReportOOMError();
9542
fd = open(snapFile, O_CREAT|O_TRUNC|O_WRONLY, S_IRUSR|S_IWUSR);
9544
qemuReportError(VIR_ERR_OPERATION_FAILED,
9545
_("failed to create snapshot file '%s'"), snapFile);
9548
if (safewrite(fd, newxml, strlen(newxml)) != strlen(newxml)) {
9549
virReportSystemError(errno, _("Failed to write snapshot data to %s"),
9560
VIR_FORCE_CLOSE(fd);
9564
static int qemuDomainSnapshotSetCurrentActive(virDomainObjPtr vm,
9567
if (vm->current_snapshot) {
9568
vm->current_snapshot->def->active = 1;
9570
return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
9577
static int qemuDomainSnapshotSetCurrentInactive(virDomainObjPtr vm,
9580
if (vm->current_snapshot) {
9581
vm->current_snapshot->def->active = 0;
9583
return qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
9591
static int qemuDomainSnapshotIsAllowed(virDomainObjPtr vm)
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
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);
9613
static virDomainSnapshotPtr qemuDomainSnapshotCreateXML(virDomainPtr domain,
9614
const char *xmlDesc,
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 };
9626
virCheckFlags(0, NULL);
9628
qemuDriverLock(driver);
9629
virUUIDFormat(domain->uuid, uuidstr);
9630
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
9632
qemuReportError(VIR_ERR_NO_DOMAIN,
9633
_("no domain with matching uuid '%s'"), uuidstr);
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.
9644
if (!qemuDomainSnapshotIsAllowed(vm))
9647
if (!(def = virDomainSnapshotDefParseString(xmlDesc, 1)))
9650
if (!(snap = virDomainSnapshotAssignDef(&vm->snapshots, def)))
9653
/* actually do the snapshot */
9654
if (!virDomainObjIsActive(vm)) {
9655
qemuimgarg[0] = qemuFindQemuImgBinary();
9656
if (qemuimgarg[0] == NULL)
9657
/* qemuFindQemuImgBinary set the error */
9660
qemuimgarg[3] = snap->def->name;
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
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);
9676
qemuimgarg[4] = vm->def->disks[i]->src;
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);
9689
qemuDomainObjPrivatePtr priv;
9692
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
9694
priv = vm->privateData;
9695
qemuDomainObjEnterMonitorWithDriver(driver, vm);
9696
ret = qemuMonitorCreateSnapshot(priv->mon, def->name);
9697
qemuDomainObjExitMonitorWithDriver(driver, vm);
9698
if (qemuDomainObjEndJob(vm) == 0) {
9706
snap->def->state = vm->state;
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
9713
if (vm->current_snapshot) {
9714
def->parent = strdup(vm->current_snapshot->def->name);
9715
if (def->parent == NULL) {
9716
virReportOOMError();
9721
/* Now we set the new current_snapshot for the domain */
9722
vm->current_snapshot = snap;
9724
if (qemuDomainSnapshotWriteMetadata(vm, vm->current_snapshot,
9725
driver->snapshotDir) < 0)
9726
/* qemuDomainSnapshotWriteMetadata set the error */
9729
snapshot = virGetDomainSnapshot(domain, snap->def->name);
9732
VIR_FREE(qemuimgarg[0]);
9734
virDomainObjUnlock(vm);
9735
qemuDriverUnlock(driver);
9739
static int qemuDomainSnapshotListNames(virDomainPtr domain, char **names,
9743
struct qemud_driver *driver = domain->conn->privateData;
9744
virDomainObjPtr vm = NULL;
9747
virCheckFlags(0, -1);
9749
qemuDriverLock(driver);
9750
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
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);
9759
n = virDomainSnapshotObjListGetNames(&vm->snapshots, names, nameslen);
9763
virDomainObjUnlock(vm);
9764
qemuDriverUnlock(driver);
9768
static int qemuDomainSnapshotNum(virDomainPtr domain,
9771
struct qemud_driver *driver = domain->conn->privateData;
9772
virDomainObjPtr vm = NULL;
9775
virCheckFlags(0, -1);
9777
qemuDriverLock(driver);
9778
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
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);
9787
n = virDomainSnapshotObjListNum(&vm->snapshots);
9791
virDomainObjUnlock(vm);
9792
qemuDriverUnlock(driver);
9796
static virDomainSnapshotPtr qemuDomainSnapshotLookupByName(virDomainPtr domain,
9800
struct qemud_driver *driver = domain->conn->privateData;
9802
virDomainSnapshotObjPtr snap = NULL;
9803
virDomainSnapshotPtr snapshot = NULL;
9805
virCheckFlags(0, NULL);
9807
qemuDriverLock(driver);
9808
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
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);
9817
snap = virDomainSnapshotFindByName(&vm->snapshots, name);
9819
qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
9820
_("no snapshot with matching name '%s'"), name);
9824
snapshot = virGetDomainSnapshot(domain, snap->def->name);
9828
virDomainObjUnlock(vm);
9829
qemuDriverUnlock(driver);
9833
static int qemuDomainHasCurrentSnapshot(virDomainPtr domain,
9836
struct qemud_driver *driver = domain->conn->privateData;
9840
virCheckFlags(0, -1);
9842
qemuDriverLock(driver);
9843
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
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);
9852
ret = (vm->current_snapshot != NULL);
9856
virDomainObjUnlock(vm);
9857
qemuDriverUnlock(driver);
9861
static virDomainSnapshotPtr qemuDomainSnapshotCurrent(virDomainPtr domain,
9864
struct qemud_driver *driver = domain->conn->privateData;
9866
virDomainSnapshotPtr snapshot = NULL;
9868
virCheckFlags(0, NULL);
9870
qemuDriverLock(driver);
9871
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
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);
9880
if (!vm->current_snapshot) {
9881
qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT, "%s",
9882
_("the domain does not have a current snapshot"));
9886
snapshot = virGetDomainSnapshot(domain, vm->current_snapshot->def->name);
9890
virDomainObjUnlock(vm);
9891
qemuDriverUnlock(driver);
9895
static char *qemuDomainSnapshotDumpXML(virDomainSnapshotPtr snapshot,
9898
struct qemud_driver *driver = snapshot->domain->conn->privateData;
9899
virDomainObjPtr vm = NULL;
9901
virDomainSnapshotObjPtr snap = NULL;
9902
char uuidstr[VIR_UUID_STRING_BUFLEN];
9904
virCheckFlags(0, NULL);
9906
qemuDriverLock(driver);
9907
virUUIDFormat(snapshot->domain->uuid, uuidstr);
9908
vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
9910
qemuReportError(VIR_ERR_NO_DOMAIN,
9911
_("no domain with matching uuid '%s'"), uuidstr);
9915
snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
9917
qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
9918
_("no domain snapshot with matching name '%s'"),
9923
xml = virDomainSnapshotDefFormat(uuidstr, snap->def, 0);
9927
virDomainObjUnlock(vm);
9928
qemuDriverUnlock(driver);
9932
static int qemuDomainRevertToSnapshot(virDomainSnapshotPtr snapshot,
9935
struct qemud_driver *driver = snapshot->domain->conn->privateData;
9936
virDomainObjPtr vm = NULL;
9938
virDomainSnapshotObjPtr snap = NULL;
9939
char uuidstr[VIR_UUID_STRING_BUFLEN];
9940
virDomainEventPtr event = NULL;
9941
qemuDomainObjPrivatePtr priv;
9944
virCheckFlags(0, -1);
9946
qemuDriverLock(driver);
9947
virUUIDFormat(snapshot->domain->uuid, uuidstr);
9948
vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
9950
qemuReportError(VIR_ERR_NO_DOMAIN,
9951
_("no domain with matching uuid '%s'"), uuidstr);
9955
snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
9957
qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
9958
_("no domain snapshot with matching name '%s'"),
9963
vm->current_snapshot = snap;
9965
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
9968
if (snap->def->state == VIR_DOMAIN_RUNNING
9969
|| snap->def->state == VIR_DOMAIN_PAUSED) {
9971
if (virDomainObjIsActive(vm)) {
9972
priv = vm->privateData;
9973
qemuDomainObjEnterMonitorWithDriver(driver, vm);
9974
rc = qemuMonitorLoadSnapshot(priv->mon, snap->def->name);
9975
qemuDomainObjExitMonitorWithDriver(driver, vm);
9980
if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
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)
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
9996
rc = doStopCPUs(driver, vm);
10001
event = virDomainEventNewFromObj(vm,
10002
VIR_DOMAIN_EVENT_STARTED,
10003
VIR_DOMAIN_EVENT_STARTED_FROM_SNAPSHOT);
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.
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);
10030
if (qemuDomainSnapshotSetCurrentActive(vm, driver->snapshotDir) < 0)
10034
vm->state = snap->def->state;
10039
if (vm && qemuDomainObjEndJob(vm) == 0)
10044
qemuDomainEventQueue(driver, event);
10046
virDomainObjUnlock(vm);
10047
qemuDriverUnlock(driver);
10052
static int qemuDomainSnapshotDiscard(struct qemud_driver *driver,
10053
virDomainObjPtr vm,
10054
virDomainSnapshotObjPtr snap)
10056
const char *qemuimgarg[] = { NULL, "snapshot", "-d", NULL, NULL, NULL };
10057
char *snapFile = NULL;
10060
qemuDomainObjPrivatePtr priv;
10061
virDomainSnapshotObjPtr parentsnap;
10063
if (!virDomainObjIsActive(vm)) {
10064
qemuimgarg[0] = qemuFindQemuImgBinary();
10065
if (qemuimgarg[0] == NULL)
10066
/* qemuFindQemuImgBinary set the error */
10069
qemuimgarg[3] = snap->def->name;
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
10082
qemuimgarg[4] = vm->def->disks[i]->src;
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
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);
10101
if (snap == vm->current_snapshot) {
10102
if (snap->def->parent) {
10103
parentsnap = virDomainSnapshotFindByName(&vm->snapshots,
10104
snap->def->parent);
10106
qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
10107
_("no domain snapshot parent with matching name '%s'"),
10108
snap->def->parent);
10112
/* Now we set the new current_snapshot for the domain */
10113
vm->current_snapshot = parentsnap;
10116
vm->current_snapshot = NULL;
10119
if (virAsprintf(&snapFile, "%s/%s/%s.xml", driver->snapshotDir,
10120
vm->def->name, snap->def->name) < 0) {
10121
virReportOOMError();
10126
virDomainSnapshotObjListRemove(&vm->snapshots, snap);
10131
VIR_FREE(snapFile);
10132
VIR_FREE(qemuimgarg[0]);
10137
struct snap_remove {
10138
struct qemud_driver *driver;
10139
virDomainObjPtr vm;
10144
static void qemuDomainSnapshotDiscardChildren(void *payload,
10145
const char *name ATTRIBUTE_UNUSED,
10148
virDomainSnapshotObjPtr snap = payload;
10149
struct snap_remove *curr = data;
10150
struct snap_remove this;
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;
10157
virHashForEach(curr->vm->snapshots.objs,
10158
qemuDomainSnapshotDiscardChildren, &this);
10161
curr->err = this.err;
10163
this.err = qemuDomainSnapshotDiscard(curr->driver, curr->vm, snap);
10167
struct snap_reparent {
10168
struct qemud_driver *driver;
10169
virDomainSnapshotObjPtr snap;
10170
virDomainObjPtr vm;
10175
qemuDomainSnapshotReparentChildren(void *payload,
10176
const char *name ATTRIBUTE_UNUSED,
10179
virDomainSnapshotObjPtr snap = payload;
10180
struct snap_reparent *rep = data;
10182
if (rep->err < 0) {
10186
if (snap->def->parent && STREQ(snap->def->parent, rep->snap->def->name)) {
10187
VIR_FREE(snap->def->parent);
10189
if (rep->snap->def->parent != NULL) {
10190
snap->def->parent = strdup(rep->snap->def->parent);
10192
if (snap->def->parent == NULL) {
10193
virReportOOMError();
10199
rep->err = qemuDomainSnapshotWriteMetadata(rep->vm, snap,
10200
rep->driver->snapshotDir);
10204
static int qemuDomainSnapshotDelete(virDomainSnapshotPtr snapshot,
10205
unsigned int flags)
10207
struct qemud_driver *driver = snapshot->domain->conn->privateData;
10208
virDomainObjPtr vm = NULL;
10210
virDomainSnapshotObjPtr snap = NULL;
10211
char uuidstr[VIR_UUID_STRING_BUFLEN];
10212
struct snap_remove rem;
10213
struct snap_reparent rep;
10215
virCheckFlags(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN, -1);
10217
qemuDriverLock(driver);
10218
virUUIDFormat(snapshot->domain->uuid, uuidstr);
10219
vm = virDomainFindByUUID(&driver->domains, snapshot->domain->uuid);
10221
qemuReportError(VIR_ERR_NO_DOMAIN,
10222
_("no domain with matching uuid '%s'"), uuidstr);
10226
snap = virDomainSnapshotFindByName(&vm->snapshots, snapshot->name);
10228
qemuReportError(VIR_ERR_NO_DOMAIN_SNAPSHOT,
10229
_("no domain snapshot with matching name '%s'"),
10234
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
10237
if (flags & VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN) {
10238
rem.driver = driver;
10240
rem.parent = snap->def->name;
10242
virHashForEach(vm->snapshots.objs, qemuDomainSnapshotDiscardChildren,
10247
rep.driver = driver;
10251
virHashForEach(vm->snapshots.objs, qemuDomainSnapshotReparentChildren,
10257
ret = qemuDomainSnapshotDiscard(driver, vm, snap);
10260
if (qemuDomainObjEndJob(vm) == 0)
10265
virDomainObjUnlock(vm);
10266
qemuDriverUnlock(driver);
10270
static int qemuDomainMonitorCommand(virDomainPtr domain, const char *cmd,
10271
char **result, unsigned int flags)
10273
struct qemud_driver *driver = domain->conn->privateData;
10274
virDomainObjPtr vm = NULL;
10276
qemuDomainObjPrivatePtr priv;
10279
virCheckFlags(VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP, -1);
10281
qemuDriverLock(driver);
10282
vm = virDomainFindByUUID(&driver->domains, domain->uuid);
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);
10291
if (!virDomainObjIsActive(vm)) {
10292
qemuReportError(VIR_ERR_OPERATION_INVALID,
10293
"%s", _("domain is not running"));
10297
priv = vm->privateData;
10299
if (!priv->monitor_warned) {
10300
VIR_INFO("Qemu monitor command '%s' executed; libvirt results may be unpredictable!",
10302
priv->monitor_warned = 1;
10305
hmp = !!(flags & VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP);
10307
if (qemuDomainObjBeginJobWithDriver(driver, vm) < 0)
10309
qemuDomainObjEnterMonitorWithDriver(driver, vm);
10310
ret = qemuMonitorArbitraryCommand(priv->mon, cmd, result, hmp);
10311
qemuDomainObjExitMonitorWithDriver(driver, vm);
10312
if (qemuDomainObjEndJob(vm) == 0) {
10319
virDomainObjUnlock(vm);
10320
qemuDriverUnlock(driver);
10326
qemuDomainOpenConsole(virDomainPtr dom,
10327
const char *devname,
10329
unsigned int flags)
10331
struct qemud_driver *driver = dom->conn->privateData;
10332
virDomainObjPtr vm = NULL;
10333
char uuidstr[VIR_UUID_STRING_BUFLEN];
10336
virDomainChrDefPtr chr = NULL;
10338
virCheckFlags(0, -1);
10340
qemuDriverLock(driver);
10341
virUUIDFormat(dom->uuid, uuidstr);
10342
vm = virDomainFindByUUID(&driver->domains, dom->uuid);
10344
qemuReportError(VIR_ERR_NO_DOMAIN,
10345
_("no domain with matching uuid '%s'"), uuidstr);
10349
if (!virDomainObjIsActive(vm)) {
10350
qemuReportError(VIR_ERR_OPERATION_INVALID,
10351
"%s", _("domain is not running"));
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];
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];
10368
if (vm->def->console)
10369
chr = vm->def->console;
10370
else if (vm->def->nserials)
10371
chr = vm->def->serials[0];
10375
qemuReportError(VIR_ERR_INTERNAL_ERROR,
10376
_("cannot find character device %s"),
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"),
10388
if (virFDStreamOpenFile(st, chr->source.data.file.path, O_RDWR) < 0)
10394
virDomainObjUnlock(vm);
10395
qemuDriverUnlock(driver);
10400
static virDriver qemuDriver = {
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 */
10510
static virStateDriver qemuStateDriver = {
10512
.initialize = qemudStartup,
10513
.cleanup = qemudShutdown,
10514
.reload = qemudReload,
10515
.active = qemudActive,
10519
qemudVMFilterRebuild(virConnectPtr conn ATTRIBUTE_UNUSED,
10520
virHashIterator iter, void *data)
10522
virHashForEach(qemu_driver->domains.objs, iter, data);
10528
qemudVMFiltersInstantiate(virConnectPtr conn,
10529
virDomainDefPtr def)
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)) {
10552
qemudVMDriverLock(void) {
10553
qemuDriverLock(qemu_driver);
10558
qemudVMDriverUnlock(void) {
10559
qemuDriverUnlock(qemu_driver);
10563
static virNWFilterCallbackDriver qemuCallbackDriver = {
10565
.vmFilterRebuild = qemudVMFilterRebuild,
10566
.vmDriverLock = qemudVMDriverLock,
10567
.vmDriverUnlock = qemudVMDriverUnlock,
10570
int qemuRegister(void) {
10571
virRegisterDriver(&qemuDriver);
10572
virRegisterStateDriver(&qemuStateDriver);
10573
virNWFilterRegisterCallbackDriver(&qemuCallbackDriver);