Commit Graph

1302 Commits

Author SHA1 Message Date
Eric Blake
b0bfbd82d1 qemu: make blkiodevice weights easier to read
The merge code had too many indirections to easily analyze.

* src/qemu/qemu_driver.c (qemuDomainMergeDeviceWeights): Pick
better variable names.
2012-02-08 15:41:11 -07:00
Jiri Denemark
c4caab538e qemu: Always use iohelper for domain save
This is probably not strictly needed as save operation is not live but
we may have other reasons to avoid blocking qemu's main loop.
2012-02-08 14:08:54 +01:00
Jiri Denemark
c8683f231d qemu: Always use iohelper for dumping domain core
Qemu uses non-blocking I/O which doesn't play nice with regular file
descriptors. We need to pass a pipe to qemu instead, which can easily be
done using iohelper.
2012-02-08 11:26:20 +01:00
Jiri Denemark
afe6e58aed util: Generalize virFileDirectFd
virFileDirectFd was used for accessing files opened with O_DIRECT using
libvirt_iohelper. We will want to use the helper for accessing files
regardless on O_DIRECT and thus virFileDirectFd was generalized and
renamed to virFileWrapperFd.
2012-02-08 11:26:20 +01:00
Laine Stump
90e4d681bc util: refactor virFileOpenAs
virFileOpenAs previously would only try opening a file as the current
user, or as a different user, but wouldn't try both methods in a
single call. This made it cumbersome to use as a replacement for
open(2). Additionally, it had a lot of historical baggage that led to
it being difficult to understand.

This patch refactors virFileOpenAs in the following ways:

* reorganize the code so that everything dealing with both the parent
  and child sides of the "fork+setuid+setgid+open" method are in a
  separate function. This makes the public function easier to understand.

* Allow a single call to virFileOpenAs() to first attempt the open as
  the current user, and if that fails to automatically re-try after
  doing fork+setuid (if deemed appropriate, i.e. errno indicates it
  would now be successful, and the file is on a networkFS). This makes
  it possible (in many, but possibly not all, cases) to drop-in
  virFileOpenAs() as a replacement for open(2).

  (NB: currently qemuOpenFile() calls virFileOpenAs() twice, once
  without forking, then again with forking. That unfortunately can't
  be changed without at least some discussion of the ramifications,
  because the requested file permissions are different in each case,
  which is something that a single call to virFileOpenAs() can't deal
  with.)

* Add a flag so that any fchown() of the file to a different uid:gid
  is explicitly requested when the function is called, rather than it
  being implied by the presence of the O_CREAT flag. This just makes
  for less subtle surprises to consumers. (Commit
  b1643dc15c added the check for O_CREAT
  before forcing ownership. This patch just makes that restriction
  more explicit.)

* If either the uid or gid is specified as "-1", virFileOpenAs will
  interpret this to mean "the current [gu]id".

All current consumers of virFileOpenAs should retain their present
behavior (after a few minor changes to their setup code and
arguments).
2012-02-03 16:47:39 -05:00
Laine Stump
72f8a7f197 qemu: new GRACEFUL flag for virDomainDestroy w/ QEMU support
When libvirt's virDomainDestroy API is shutting down the qemu process,
it first sends SIGTERM, then waits for 1.6 seconds and, if it sees the
process still there, sends a SIGKILL.

There have been reports that this behavior can lead to data loss
because the guest running in qemu doesn't have time to flush its disk
cache buffers before it's unceremoniously whacked.

This patch maintains that default behavior, but provides a new flag
VIR_DOMAIN_DESTROY_GRACEFUL to alter the behavior. If this flag is set
in the call to virDomainDestroyFlags, SIGKILL will never be sent to
the qemu process; instead, if the timeout is reached and the qemu
process still exists, virDomainDestroy will return an error.

Once this patch is in, the recommended method for applications to call
virDomainDestroyFlags will be with VIR_DOMAIN_DESTROY_GRACEFUL
included. If that fails, then the application can decide if and when
to call virDomainDestroyFlags again without
VIR_DOMAIN_DESTROY_GRACEFUL (to force the issue with SIGKILL).

(Note that this does not address the issue of existing applications
that have not yet been modified to use VIR_DOMAIN_DESTROY_GRACEFUL.
That is a separate patch.)
2012-02-03 14:21:17 -05:00
Martin Kletzander
3d93706d0d Added RSS reporting
Added RSS information gathering into qemuMemoryStats into qemu driver
and the reporting into virsh dommemstat.
2012-02-03 20:54:58 +08:00
Martin Kletzander
350d6ccb91 Added RSS information gathering into qemudGetProcessInfo
One more parameter added into the function parsing /proc/<pid>/stat
and the call of the function is fixed as well.
2012-02-03 20:33:57 +08:00
Daniel P. Berrange
b170eb99f5 Add two new security label types
Curently security labels can be of type 'dynamic' or 'static'.
If no security label is given, then 'dynamic' is assumed. The
current code takes advantage of this default, and avoids even
saving <seclabel> elements with type='dynamic' to disk. This
means if you temporarily change security driver, the guests
can all still start.

With the introduction of sVirt to LXC though, there needs to be
a new default of 'none' to allow unconfined LXC containers.

This patch introduces two new security label types

 - default:  the host configuration decides whether to run the
             guest with type 'none' or 'dynamic' at guest start
 - none:     the guest will run unconfined by security policy

The 'none' label type will obviously be undesirable for some
deployments, so a new qemu.conf option allows a host admin to
mandate confined guests. It is also possible to turn off default
confinement

  security_default_confined = 1|0  (default == 1)
  security_require_confined = 1|0  (default == 0)

* src/conf/domain_conf.c, src/conf/domain_conf.h: Add new
  seclabel types
* src/security/security_manager.c, src/security/security_manager.h:
  Set default sec label types
* src/security/security_selinux.c: Handle 'none' seclabel type
* src/qemu/qemu.conf, src/qemu/qemu_conf.c, src/qemu/qemu_conf.h,
  src/qemu/libvirtd_qemu.aug: New security config options
* src/qemu/qemu_driver.c: Tell security driver about default
  config
2012-02-02 17:44:37 -07:00
Eric Blake
9f902a2ed5 block rebase: initial qemu implementation
This is a trivial implementation, which works with the current
released qemu 1.0 with backports of preliminary block pull but
no partial rebase.  Future patches will update the monitor handling
to support an optional parameter for partial rebase; but as qemu
1.1 is unreleased, it can be in later patches, designed to be
backported on top of the supported API.

* src/qemu/qemu_driver.c (qemuDomainBlockJobImpl): Add parameter,
and adjust callers.  Drop redundant check.
(qemuDomainBlockPull): Move guts...
(qemuDomainBlockRebase): ...to new function.
2012-02-01 15:31:44 -07:00
Peter Krempa
21d13ddc5d qemu: Add support for virDomainGetMetadata and virDomainSetMetadata
This patch adds support for the new api into the qemu driver to support
modification and retrieval of domain description and title. This patch
does not add support for modifying the <metadata> element.
2012-02-01 15:19:28 -07:00
Jiri Denemark
e17e3ed6aa qemu: Implement virDomainGetDiskErrors 2012-02-01 10:54:15 +01:00
Michal Privoznik
50e9b38930 qemu: Clenup qemuDomainSetInterfaceParameters
which contained some useless lines, copied code, NULL
dereference.
2012-02-01 08:56:54 +01:00
Michal Privoznik
bb311b3458 qemu: Don't jump to endjob if no job was even started
In qemuDomainShutdownFlags if we try to use guest agent,
which has error or is not configured, we jump go endjob
label even if we haven't started any job yet. This may
lead to the daemon crash:
1) virsh shutdown --mode agent on a domain without agent configured
2) wait until domain quits
3) virsh edit
2012-02-01 08:42:47 +01:00
Laine Stump
159f4d0b30 conf: put all guest-related HostdevDef data in one object
To help consolidate the commonality between virDomainHostdevDef and
virDomainNetDef into as few members as possible (and because I
think it makes sense), this patch moves the rombar and bootIndex
members into the "info" member that is common to both (and to all the
other structs that use them).

It's a bit problematic that this gives rombar and bootIndex to many
device types that don't use them, but this is already the case for the
master and mastertype members of virDomainDeviceInfo, and is properly
commented as such in the definition.

Note that this opens the door to supporting rombar for other devices
that are attached to the guest PCI bus - virtio-blk-pci,
virtio-net-pci, various other network adapters - which which have that
capability in qemu, but previously had no support in libvirt.
2012-01-30 12:25:20 -05:00
Daniel P. Berrange
4ce98dadcc Rename virXXXXMacAddr to virMacAddrXXX
Rename virFormatMacAddr, virGenerateMacAddr and virParseMacAddr
to virMacAddrFormat, virMacAddrGenerate and virMacAddrParse
respectively
2012-01-27 17:53:44 +00:00
Michal Privoznik
109593ecb0 snapshots: Introduce VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE flag
With this flag, virDomainSnapshotCreate will use fs-freeze and
fs-thaw guest agent commands to quiesce guest's disks.
2012-01-25 10:59:41 +01:00
Daniel P. Berrange
fb52a39928 Wire up QEMU agent to reboot/shutdown APIs
This makes use of the QEMU guest agent to implement the
virDomainShutdownFlags and virDomainReboot APIs. With
no flags specified, it will prefer to use the agent, but
fallback to ACPI. Explicit choice can be made by using
a suitable flag

* src/qemu/qemu_driver.c: Wire up use of agent
2012-01-24 12:19:51 +01:00
Eric Blake
9e48c22534 util: use new virTypedParameter helpers
Reusing common code makes things smaller; it also buys us some
additional safety, such as now rejecting duplicate parameters
during a set operation.

* src/qemu/qemu_driver.c (qemuDomainSetBlkioParameters)
(qemuDomainSetMemoryParameters, qemuDomainSetNumaParameters)
(qemuSetSchedulerParametersFlags)
(qemuDomainSetInterfaceParameters, qemuDomainSetBlockIoTune)
(qemuDomainGetBlkioParameters, qemuDomainGetMemoryParameters)
(qemuDomainGetNumaParameters, qemuGetSchedulerParametersFlags)
(qemuDomainBlockStatsFlags, qemuDomainGetInterfaceParameters)
(qemuDomainGetBlockIoTune): Use new helpers.
* src/esx/esx_driver.c (esxDomainSetSchedulerParametersFlags)
(esxDomainSetMemoryParameters)
(esxDomainGetSchedulerParametersFlags)
(esxDomainGetMemoryParameters): Likewise.
* src/libxl/libxl_driver.c
(libxlDomainSetSchedulerParametersFlags)
(libxlDomainGetSchedulerParametersFlags): Likewise.
* src/lxc/lxc_driver.c (lxcDomainSetMemoryParameters)
(lxcSetSchedulerParametersFlags, lxcDomainSetBlkioParameters)
(lxcDomainGetMemoryParameters, lxcGetSchedulerParametersFlags)
(lxcDomainGetBlkioParameters): Likewise.
* src/test/test_driver.c (testDomainSetSchedulerParamsFlags)
(testDomainGetSchedulerParamsFlags): Likewise.
* src/xen/xen_hypervisor.c (xenHypervisorSetSchedulerParameters)
(xenHypervisorGetSchedulerParameters): Likewise.
2012-01-19 13:20:30 -07:00
Osier Yang
7aeb9794d2 qemu: Prohibit reattaching node device if it is in use
It doesn't make sense to reattach a device to host while it's
still in use, e.g, by a domain.
2012-01-17 17:15:22 -07:00
Osier Yang
6be610bfaa qemu: Introduce inactive PCI device list
pciTrySecondaryBusReset checks if there is active device on the
same bus, however, qemu driver doesn't maintain an effective
list for the inactive devices, and it passes meaningless argument
for parameter "inactiveDevs". e.g. (qemuPrepareHostdevPCIDevices)

if (!(pcidevs = qemuGetPciHostDeviceList(hostdevs, nhostdevs)))
    return -1;

..skipped...

if (pciResetDevice(dev, driver->activePciHostdevs, pcidevs) < 0)
    goto reattachdevs;

NB, the "pcidevs" used above are extracted from domain def, and
thus one won't be able to attach a device of which bus has other
device even detached from host (nodedev-detach). To see more
details of the problem:

RHBZ: https://bugzilla.redhat.com/show_bug.cgi?id=773667

This patch is to resolve the problem by introducing an inactive
PCI device list (just like qemu_driver->activePciHostdevs), and
the whole logic is:

  * Add the device to inactive list during nodedev-dettach
  * Remove the device from inactive list during nodedev-reattach
  * Remove the device from inactive list during attach-device
    (for non-managed device)
  * Add the device to inactive list after detach-device, only
    if the device is not managed

With the above, we have a sufficient inactive PCI device list, and thus
we can use it for pciResetDevice. e.g.(qemuPrepareHostdevPCIDevices)

if (pciResetDevice(dev, driver->activePciHostdevs,
                   driver->inactivePciHostdevs) < 0)
    goto reattachdevs;
2012-01-17 17:05:32 -07:00
Daniel P. Berrange
99be754ada Change security driver APIs to use virDomainDefPtr instead of virDomainObjPtr
When sVirt is integrated with the LXC driver, it will be neccessary
to invoke the security driver APIs using only a virDomainDefPtr
since the lxc_container.c code has no virDomainObjPtr available.
Aside from two functions which want obj->pid, every bit of the
security driver code only touches obj->def. So we don't need to
pass a virDomainObjPtr into the security drivers, a virDomainDefPtr
is sufficient. Two functions also gain a 'pid_t pid' argument.

* src/qemu/qemu_driver.c, src/qemu/qemu_hotplug.c,
  src/qemu/qemu_migration.c, src/qemu/qemu_process.c,
  src/security/security_apparmor.c,
  src/security/security_dac.c,
  src/security/security_driver.h,
  src/security/security_manager.c,
  src/security/security_manager.h,
  src/security/security_nop.c,
  src/security/security_selinux.c,
  src/security/security_stack.c: Change all security APIs to use a
  virDomainDefPtr instead of virDomainObjPtr
2012-01-11 09:52:18 +00:00
Eric Blake
4e9953a426 snapshot: allow reuse of existing files in disk snapshot
When disk snapshots were first implemented, libvirt blindly refused
to allow an external snapshot destination that already exists, since
qemu will blindly overwrite the contents of that file during the
snapshot_blkdev monitor command, and we don't like a default of
data loss by default.  But VDSM has a scenario where NFS permissions
are intentionally set so that the destination file can only be
created by the management machine, and not the machine where the
guest is running, so that libvirt will necessarily see the destination
file already existing; adding a flag will allow VDSM to force the file
reuse without libvirt complaining of possible data loss.

https://bugzilla.redhat.com/show_bug.cgi?id=767104

* include/libvirt/libvirt.h.in (virDomainSnapshotCreateFlags): Add
VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT.
* src/libvirt.c (virDomainSnapshotCreateXML): Document it.  Add
note about partial failure.
* tools/virsh.c (cmdSnapshotCreate, cmdSnapshotCreateAs): Add new
flag.
* tools/virsh.pod (snapshot-create, snapshot-create-as): Document
it.
* src/qemu/qemu_driver.c (qemuDomainSnapshotDiskPrepare)
(qemuDomainSnapshotCreateXML): Implement the new flag.
2012-01-10 11:53:23 -07:00
Alex Jia
d8d9b0e058 qemu: fix a typo on qemuDomainSetBlkioParameters
It should be a copy-paste error, the result is programming will result in an
infinite loop again due to without iterating 'j' variable.

* src/qemu/qemu_driver.c: fix a typo on qemuDomainSetBlkioParameters.

RHBZ: https://bugzilla.redhat.com/show_bug.cgi?id=770520

Signed-off-by: Alex Jia <ajia@redhat.com>
2012-01-10 11:41:27 +01:00
Laine Stump
177db08775 qemu: add new disk device='lun' for bus='virtio' & type='block'
In the past, generic SCSI commands issued from a guest to a virtio
disk were always passed through to the underlying disk by qemu, and
the kernel would also pass them on.

As a result of CVE-2011-4127 (see:
http://seclists.org/oss-sec/2011/q4/536), qemu now honors its
scsi=on|off device option for virtio-blk-pci (which enables/disables
passthrough of generic SCSI commands), and the kernel will only allow
the commands for physical devices (not for partitions or logical
volumes). The default behavior of qemu is still to allow sending
generic SCSI commands to physical disks that are presented to a guest
as virtio-blk-pci devices, but libvirt prefers to disable those
commands in the standard virtio block devices, enabling it only when
specifically requested (hopefully indicating that the requester
understands what they're asking for). For this purpose, a new libvirt
disk device type (device='lun') has been created.

device='lun' is identical to the default device='disk', except that:

1) It is only allowed if bus='virtio', type='block', and the qemu
   version is "new enough" to support it ("new enough" == qemu 0.11 or
   better), otherwise the domain will fail to start and a
   CONFIG_UNSUPPORTED error will be logged).

2) The option "scsi=on" will be added to the -device arg to allow
   SG_IO commands (if device !='lun', "scsi=off" will be added to the
   -device arg so that SG_IO commands are specifically forbidden).

Guests which continue to use disk device='disk' (the default) will no
longer be able to use SG_IO commands on the disk; those that have
their disk device changed to device='lun' will still be able to use SG_IO
commands.

*docs/formatdomain.html.in - document the new device attribute value.
*docs/schemas/domaincommon.rng - allow it in the RNG
*tests/* - update the args of several existing tests to add scsi=off, and
 add one new test that will test scsi=on.
*src/conf/domain_conf.c - update domain XML parser and formatter

*src/qemu/qemu_(command|driver|hotplug).c - treat
 VIR_DOMAIN_DISK_DEVICE_LUN *almost* identically to
 VIR_DOMAIN_DISK_DEVICE_DISK, except as indicated above.

Note that no support for this new device value was added to any
hypervisor drivers other than qemu, because it's unclear what it might
mean (if anything) to those drivers.
2012-01-09 10:55:53 -05:00
Laine Stump
1734cdb995 config: report error when script given for inappropriate interface type
This fixes https://bugzilla.redhat.com/show_bug.cgi?id=638633

Although scripts are not used by interfaces of type other than
"ethernet" in qemu, due to the fact that the parser stores the script
name in a union that is only valid when type is ethernet or bridge,
there is no way for anyone except the parser itself to catch the
problem of specifying an interface script for an inappropriate
interface type (by the time the parsed data gets back to the code that
called the parser, all evidence that a script was specified is
forgotten).

Since the parser itself should be agnostic to which type of interface
allows scripts (an example of why: a script specified for an interface
of type bridge is valid for xen domains, but not for qemu domains),
the solution here is to move the script out of the union(s) in the
DomainNetDef, always populate it when specified (regardless of
interface type), and let the driver decide whether or not it is
appropriate.

Currently the qemu, xen, libxml, and uml drivers recognize the script
parameter and do something with it (the uml driver only to report that
it isn't supported). Those drivers have been updated to log a
CONFIG_UNSUPPORTED error when a script is specified for an interface
type that's inappropriate for that particular hypervisor.

(NB: There was earlier discussion of solving this problem by adding a
VALIDATE flag to all libvirt APIs that accept XML, which would cause
the XML to be validated against the RNG files. One statement during
that discussion was that the RNG shouldn't contain hypervisor-specific
things, though, and a proper solution to this problem would require
that (again, because a script for an interface of type "bridge" is
accepted by xen, but not by qemu).
2012-01-08 10:52:24 -05:00
Eric Blake
13a776ca0d qemu: one more client to live/config helper
Commit ae523427 missed one pair of functions that could use
the helper routine.

* src/qemu/qemu_driver.c (qemuSetSchedulerParametersFlags)
(qemuGetSchedulerParametersFlags): Simplify.
2012-01-07 05:08:01 -07:00
Hu Tao
6b780f744b qemu: fix a bug in numatune
When setting numa nodeset for a domain which has no nodeset set
before, libvirtd crashes by dereferencing the pointer to the old
nodemask which is null in that case.
2012-01-05 13:04:02 -07:00
Eric Blake
820a2159e9 qemu: fix use-after-free regression
Commit baade4d fixed a memory leak on failure, but in the process,
introduced a use-after-free on success, which can be triggered with:

1. set bandwidth with --live
2. query bandwidth
3. set bandwidth with --live

* src/qemu/qemu_driver.c (qemuDomainSetInterfaceParameters): Don't
free newBandwidth on success.
Reported by Hu Tao.
2012-01-05 10:21:34 -07:00
Eric Blake
851fc8139f qemu: fix block stat naming
Typo has existed since API introduction in commit ee0d8c3.

* src/qemu/qemu_driver.c (qemuDomainBlockStatsFlags): Use correct
name.
2012-01-02 20:43:07 -07:00
Eric Blake
269ce467fc domiftune: clean up previous patches
Most severe here is a latent (but currently untriggered) memory leak
if any hypervisor ever adds a string interface property; the
remainder are mainly cosmetic.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_BANDWIDTH_*): Move
macros closer to interface that uses them, and document type.
* src/libvirt.c (virDomainSetInterfaceParameters)
(virDomainGetInterfaceParameters): Formatting tweaks.
* daemon/remote.c (remoteDispatchDomainGetInterfaceParameters):
Avoid memory leak.
* src/libvirt_public.syms (LIBVIRT_0.9.9): Sort lines.
* src/libvirt_private.syms (domain_conf.h): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSetInterfaceParameters): Fix
comments, break long lines.
2012-01-02 14:35:12 -07:00
Alex Jia
baade4cd2b qemu: Fix bandwidth memory leak on failure
Detected by Coverity. Leaks introduced in commit e8d6b29.

Signed-off-by: Alex Jia <ajia@redhat.com>
2011-12-31 16:42:23 -07:00
Eric Blake
8267aea5a6 qemu: fix blkio memory leak on failure
Leak detected by Coverity, and introduced in commit 93ab585.
Reported by Alex Jia.

* src/qemu/qemu_driver.c (qemuDomainSetBlkioParameters): Free
devices array on error.
2011-12-31 16:32:35 -07:00
Hu Tao
e8d6b293d8 domiftune: Add virDomain{S,G}etInterfaceParameters support to qemu driver
* src/qemu/qemu_driver.c: implement the qemu driver support
2011-12-29 18:28:47 +08:00
Eric Blake
1a3f6608aa qemu: fix inf-loop in blkio parameters
https://bugzilla.redhat.com/show_bug.cgi?id=770520

We had two nested loops both trying to use 'i' as the iteration
variable, which can result in an infinite loop when the inner
loop interferes with the outer loop.  Introduced in commit 93ab585.

* src/qemu/qemu_driver.c (qemuDomainSetBlkioParameters): Don't
reuse iteration variable across two loops.
2011-12-28 06:57:42 -07:00
Michal Privoznik
8a34f822e6 qemu: Keep list of USB devices attached to domains
In order to avoid situation where a USB device is
in use by two domains, we must keep a list of already
attached devices like we do for PCI.
2011-12-24 18:12:04 +01:00
Osier Yang
33eca17f6a qemu: Release the lock on domobj if fails on finding the disk path 2011-12-21 10:22:08 +08:00
Hu Tao
6758a01b18 Implement virDomain{G, S}etNumaParameters for the qemu driver 2011-12-20 11:01:27 -07:00
Daniel P. Berrange
707781fe12 Only add the timer when a callback is registered
The lifetime of the virDomainEventState object is tied to
the lifetime of the driver, which in stateless drivers is
tied to the lifetime of the virConnectPtr.

If we add & remove a timer when allocating/freeing the
virDomainEventState object, we can get a situation where
the timer still triggers once after virDomainEventState
has been freed. The timeout callback can't keep a ref
on the event state though, since that would be a circular
reference.

The trick is to only register the timer when a callback
is registered with the event state & remove the timer
when the callback is unregistered.

The demo for the bug is to run

  while true ; do date ; ../tools/virsh -q -c test:///default 'shutdown test; undefine test; dominfo test' ; done

prior to this fix, it will frequently hang and / or
crash, or corrupt memory
2011-12-19 11:08:25 +00:00
Daniel P. Berrange
34ad13536e Hide use of timers for domain event dispatch
Currently all drivers using domain events need to provide a callback
for handling a timer to dispatch events in a clean stack. There is
no technical reason for dispatch to go via driver specific code. It
could trivially be dispatched directly from the domain event code,
thus removing tedious boilerplate code from all drivers

Also fix the libxl & xen drivers to pass 'true' when creating the
virDomainEventState, since they run inside the daemon & thus always
expect events to be present.

* src/conf/domain_event.c, src/conf/domain_event.h: Internalize
  dispatch of events from timer callback
* src/libxl/libxl_driver.c, src/lxc/lxc_driver.c,
  src/qemu/qemu_domain.c, src/qemu/qemu_driver.c,
  src/remote/remote_driver.c, src/test/test_driver.c,
  src/uml/uml_driver.c, src/vbox/vbox_tmpl.c,
  src/xen/xen_driver.c: Remove all timer dispatch functions
2011-12-19 11:08:24 +00:00
Daniel P. Berrange
7b87a30f15 Convert drivers to thread safe APIs for adding callbacks
* src/libxl/libxl_driver.c, src/lxc/lxc_driver.c,
  src/qemu/qemu_driver.c, src/remote/remote_driver.c,
  src/test/test_driver.c, src/uml/uml_driver.c,
  src/vbox/vbox_tmpl.c, src/xen/xen_driver.c: Convert
  to threadsafe APIs
2011-12-19 11:08:10 +00:00
Daniel P. Berrange
d09f6ba5fe Return count of callbacks when registering callbacks
When registering a callback for a particular event some callers
need to know how many callbacks already exist for that event.
While it is possible to ask for a count, this is not free from
race conditions when threaded. Thus the API for registering
callbacks should return the count of callbacks. Also rename
virDomainEventStateDeregisterAny to virDomainEventStateDeregisterID

* src/conf/domain_event.c, src/conf/domain_event.h,
  src/libvirt_private.syms: Return count of callbacks when
  registering callbacks
* src/libxl/libxl_driver.c, src/libxl/libxl_driver.c,
  src/qemu/qemu_driver.c, src/remote/remote_driver.c,
  src/remote/remote_driver.c, src/uml/uml_driver.c,
  src/vbox/vbox_tmpl.c, src/xen/xen_driver.c: Update
  for change in APIs
2011-12-19 11:08:10 +00:00
Eric Blake
d99fe011a2 qemu: detect truncated file as invalid save image
If managed save fails at the right point in time, then the save
image can end up with 0 bytes in length (no valid header), and
our attempts in commit 55d88def to detect and skip invalid save
files missed this case.

* src/qemu/qemu_driver.c (qemuDomainSaveImageOpen): Also unlink
empty file as corrupt.  Reported by Dennis Householder.
2011-12-16 08:29:31 -07:00
Lei Li
ae52342754 Provide a helper method virDomainLiveConfigHelperMethod
This chunk of code below repeated in several functions, factor it into
a helper method virDomainLiveConfigHelperMethod to eliminate duplicated code
based on Eric and Adam's suggestion. I have tested it for all the
relevant APIs changed.

Signed-off-by: Eric Blake <eblake@redhat.com>
Signed-off-by: Lei Li <lilei@linux.vnet.ibm.com>
2011-12-13 15:10:42 -07:00
Jiri Denemark
5547d2b81c qemu: Disable EOF processing during qemuDomainDestroy
When destroying a domain qemuDomainDestroy kills its qemu process and
starts a new job, which means it unlocks the domain object and locks it
again after some time. Although the object is usually unlocked for a
pretty short time, chances are another thread processing an EOF event on
qemu monitor is able to lock the object first and does all the cleanup
by itself. This leads to wrong shutoff reason and lifecycle event detail
and virDomainDestroy API incorrectly reporting failure to destroy an
inactive domain.

Reported by Charlie Smurthwaite.
2011-12-12 16:31:19 +01:00
Michael Ellerman
9f406c5838 qemu: Prepare to cater for more general address assignment
Currently qemuDomainAssignPCIAddresses() is called to assign addresses
to PCI devices.

We need to do something similar for devices with spapr-vio addresses.
So create one place where address assignment will be done, that is
qemuDomainAssignAddresses().

Signed-off-by: Michael Ellerman <michael@ellerman.id.au>
2011-12-09 15:01:52 -07:00
Lei Li
ac6b368d8a Fix a logic error for setting block I/O
Fix a logic error, the initial value of ret = -1, if just set --config,
it will goto endjob directly without doing its really job here.

Signed-off-by: Lei Li <lilei@linux.vnet.ibm.com>
2011-12-01 08:01:16 -07:00
Hu Tao
25a5f07c69 qemu: filter blkio 0-device-weight at two other places
filter 0-device-weight when:

  - getting blkio parameters with --config
  - starting up a domain

When testing with blkio, I found these issues:

  (dom is down)
  virsh blkiotune dom --device-weights /dev/sda,300,/dev/sdb,500
  virsh blkiotune dom --device-weights /dev/sda,300,/dev/sdb,0
  virsh blkiotune dom
  weight         : 800
  device_weight  : /dev/sda,200,/dev/sdb,0

  # issue 1: shows 0 device weight of /dev/sdb that may confuse user

  (continued)
  virsh start dom

  # issue 2: If /dev/sdb doesn't exist, libvirt refuses to bring the
  # dom up because it wants to set the device weight to 0 of a
  # non-existing device. Since 0 means no weight-limit, we really don't
  # have to set it.
2011-11-30 12:34:30 -07:00
Eric Blake
22cf6d46f4 qemu: amend existing table of device weights
Prior to this patch, for a running dom, the commands:

$ virsh blkiotune dom --device-weights /dev/sda,502,/dev/sdb,498
$ virsh blkiotune dom --device-weights /dev/sda,503
$ virsh blkiotune dom
weight         : 500
device_weight  : /dev/sda,503

claim that /dev/sdb no longer has a non-default weight, but
directly querying cgroups says otherwise:

$ cat /cgroup/blkio/libvirt/qemu/dom/blkio.weight_device
8:0     503
8:16    498

After this patch, an explicit 0 is required to remove a device path
from the XML, and omitting a device path that was previously
specified leaves that device path untouched in the XML, to match
cgroups behavior.

* src/qemu/qemu_driver.c (parseBlkioWeightDeviceStr): Rename...
(qemuDomainParseDeviceWeightStr): ...and use correct type.
(qemuDomainSetBlkioParameters): After parsing string, modify
rather than replacing existing table.
* tools/virsh.pod (blkiotune): Tweak wording.
2011-11-30 12:18:18 -07:00
Lei Li
eca96694a7 Implement virDomain{Set, Get}BlockIoTune for the qemu driver
Implement the block I/O throttle setting and getting support to qemu
driver.

Signed-off-by: Lei Li <lilei@linux.vnet.ibm.com>
Signed-off-by: Zhi Yong Wu <wuzhy@linux.vnet.ibm.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-11-30 11:36:10 -07:00
Daniel P. Berrange
a8bb75a3e6 Remove time APIs from src/util/util.h
The virTimestamp and virTimeMs functions in src/util/util.h
duplicate functionality from virtime.h, in a non-async signal
safe manner. Remove them, and convert all code over to the new
APIs.

* src/util/util.c, src/util/util.h: Delete virTimeMs and virTimestamp
* src/lxc/lxc_driver.c, src/qemu/qemu_domain.c,
  src/qemu/qemu_driver.c, src/qemu/qemu_migration.c,
  src/qemu/qemu_process.c, src/util/event_poll.c: Convert to use
  virtime APIs
2011-11-30 11:43:50 +00:00
Hu Tao
93ab58595d blkiotune: add qemu support for blkiotune.device_weight
Implement setting/getting per-device blkio weights in qemu,
using the cgroups blkio.weight_device tunable.
2011-11-29 12:26:21 -07:00
Eric Blake
659ded58ed qemu: fix blkiotune --live --config
Without this,  'virsh blkiotune --live --config --weight=n'
only affected live.

* src/qemu/qemu_driver.c (qemuDomainSetBlkioParameters): Allow
setting both configurations at once.
2011-11-29 10:54:29 -07:00
Eric Blake
51727c1dc0 qemu, lxc: drop redundant checks
After the previous patch, there are now some redundant checks.

* src/qemu/qemu_driver.c (qemudDomainGetVcpuPinInfo)
(qemuGetSchedulerParametersFlags): Drop checks now guaranteed by
libvirt.c.
* src/lxc/lxc_driver.c (lxcGetSchedulerParametersFlags):
Likewise.
2011-11-29 10:54:29 -07:00
Osier Yang
d1a6c77aca block_resize: Implement qemu driver method
It requires the domain is running, otherwise fails. Resize to a lower
size is supported, but should be used with extreme caution.

In order to prohibit the "size" overflowing after multiplied by
1024. We do checking in the codes. For QMP mode, the default units
is Bytes, the passed size needs to be multiplied by 1024, however,
for HMP mode, the default units is "Megabytes", the passed "size"
needs to be divided by 1024 then.
2011-11-29 21:45:18 +08:00
Srivatsa S. Bhat
4ddb37c395 Implement the core API to suspend/resume the host
Add the core functions that implement the functionality of the API.
Suspend is done by using an asynchronous mechanism so that we can return
the status to the caller before the host gets suspended. This asynchronous
operation is achieved by suspending the host in a separate thread of
execution. However, returning the status to the caller is only best-effort,
but not guaranteed.

To resume the host, an RTC alarm is set up (based on how long we want to
suspend) before suspending the host. When this alarm fires, the host
gets woken up.

Suspend-to-RAM operation on a host running Linux can take upto more than 20
seconds, depending on the load of the system. (Freezing of tasks, an operation
preceding any suspend operation, is given up after a 20 second timeout).
And Suspend-to-Disk can take even more time, considering the time required
for compaction, creating the memory image and writing it to disk etc.
So, we do not allow the user to specify a suspend duration of less than 60
seconds, to be on the safer side, since we don't want to prematurely declare
failure when we only had to wait for some more time.
2011-11-29 17:29:17 +08:00
Jiri Denemark
2c4cdb736c Fix version numbers for isAlive and setKeepAlive driver APIs 2011-11-24 14:44:59 +01:00
Jiri Denemark
e401b0cd02 Implement virConnectIsAlive in all drivers 2011-11-24 12:00:10 +01:00
Eric Blake
db2f680775 qemu: fix a const-correctness issue
Generally, functions which return malloc'd strings should be typed
as 'char *', not 'const char *', to make it obvious that the caller
is responsible to free things.  free(const char *) fails to compile,
and although we have a cast embedded in VIR_FREE to work around poor
code that frees const char *, it's better to not rely on that hack.

* src/qemu/qemu_driver.c (qemuDiskPathToAlias): Change return type.
(qemuDomainBlockJobImpl): Update caller.
2011-11-23 07:29:45 -07:00
Eric Blake
c725e2dc5a blockstats: support lookup by path in blockstats
Commit 89b6284f made it possible to pass either a source name or
the target device to most API demanding a disk designation, but
forgot to update the documentation.  It also failed to update
virDomainBlockStats to take both forms. This patch fixes both the
documentation and the remaining function.

Xen continues to use just device shorthand (that is, I did not
implement path lookup there, since xen does not track a domain_conf
to quickly tie a path back to the device shorthand).

* src/libvirt.c (virDomainBlockStats, virDomainBlockStatsFlags)
(virDomainGetBlockInfo, virDomainBlockPeek)
(virDomainBlockJobAbort, virDomainGetBlockJobInfo)
(virDomainBlockJobSetSpeed, virDomainBlockPull): Document
acceptable disk naming conventions.
* src/qemu/qemu_driver.c (qemuDomainBlockStats)
(qemuDomainBlockStatsFlags): Allow lookup by source name.
* src/test/test_driver.c (testDomainBlockStats): Likewise.
2011-11-23 06:10:30 -07:00
Daniel P. Berrange
896104c9f0 Rename and split the macvtap.c file
Rename the macvtap.c file to virnetdevmacvlan.c to reflect its
functionality. Move the port profile association code out into
virnetdevvportprofile.c. Make the APIs available unconditionally
to callers

* src/util/macvtap.h: rename to src/util/virnetdevmacvlan.h,
* src/util/macvtap.c: rename to src/util/virnetdevmacvlan.c
* src/util/virnetdevvportprofile.c, src/util/virnetdevvportprofile.h:
  Pull in vport association code
* src/Makefile.am, src/conf/domain_conf.h, src/qemu/qemu_conf.c,
  src/qemu/qemu_conf.h, src/qemu/qemu_driver.c: Update include
  paths & remove conditional compilation
2011-11-18 16:10:01 +00:00
Daniel P. Berrange
43925db7ca Rename Macvtap management APIs
In preparation for code re-organization, rename the Macvtap
management APIs to have the following patterns

  virNetDevMacVLanXXXXX     - macvlan/macvtap interface management
  virNetDevVPortProfileXXXX - virtual port profile management

* src/util/macvtap.c, src/util/macvtap.h: Rename APIs
* src/conf/domain_conf.c, src/network/bridge_driver.c,
  src/qemu/qemu_command.c, src/qemu/qemu_command.h,
  src/qemu/qemu_driver.c, src/qemu/qemu_hotplug.c,
  src/qemu/qemu_migration.c, src/qemu/qemu_process.c,
  src/qemu/qemu_process.h: Update for renamed APIs
2011-11-18 16:10:01 +00:00
Eric Blake
342c09578a API: add trivial qemu support for VIR_TYPED_PARAM_STRING
Qemu will be the first driver to make use of a typed string in the
next round of additions.  Separate out the trivial addition.

* src/qemu/qemu_driver.c (qemudSupportsFeature): Advertise feature.
(qemuDomainGetBlkioParameters, qemuDomainGetMemoryParameters)
(qemuGetSchedulerParametersFlags, qemudDomainBlockStatsFlags):
Allow typed strings flag where trivially supported.
2011-11-11 17:27:04 -07:00
Daniel P. Berrange
6cfeb9a766 Remove 'brControl' object
The bridge management APIs in src/util/bridge.c require a brControl
object to be passed around. This holds the file descriptor for the
control socket. This extra object complicates use of the API for
only a minor efficiency gain, which is in turn entirely offset by
the need to fork/exec the brctl command for STP configuration.

This patch removes the 'brControl' object entirely, instead opening
the control socket & closing it again within the scope of each method.

The parameter names for the APIs are also made to consistently use
'brname' for bridge device name, and 'ifname' for an interface
device name. Finally annotations are added for non-NULL parameters
and return check validation

* src/util/bridge.c, src/util/bridge.h: Remove brControl object
  and update API parameter names & annotations.
* src/lxc/lxc_driver.c, src/network/bridge_driver.c,
  src/uml/uml_conf.h, src/uml/uml_conf.c, src/uml/uml_driver.c,
  src/qemu/qemu_command.c, src/qemu/qemu_conf.h,
  src/qemu/qemu_driver.c: Remove reference to 'brControl' object
2011-11-09 16:33:14 +00:00
Osier Yang
5ab243b64f qemu: Fix improper error message for disk detaching
s/virDomainDeviceTypeToString/virDomainDiskDeviceTypeToString/

Report by Xu He Jie <xuhj@linux.vnet.ibm.
2011-11-09 13:59:31 +08:00
Daniel P. Berrange
0873b688c6 Allow multiple consoles per virtual guest
While Xen only has a single paravirt console, UML, and
QEMU both support multiple paravirt consoles. The LXC
driver can also be trivially made to support multiple
consoles. This patch extends the XML to allow multiple
<console> elements in the XML. It also makes the UML
and QEMU drivers support this config.

* src/conf/domain_conf.c, src/conf/domain_conf.h: Allow
  multiple <console> devices
* src/lxc/lxc_driver.c, src/xen/xen_driver.c,
  src/xenxs/xen_sxpr.c, src/xenxs/xen_xm.c: Update for
  internal API changes
* src/security/security_selinux.c, src/security/virt-aa-helper.c:
  Only label consoles that aren't a copy of the serial device
* src/qemu/qemu_command.c, src/qemu/qemu_driver.c,
  src/qemu/qemu_process.c, src/uml/uml_conf.c,
  src/uml/uml_driver.c: Support multiple console devices
* tests/qemuxml2xmltest.c, tests/qemuxml2argvtest.c: Extra
  tests for multiple virtio consoles. Set QEMU_CAPS_CHARDEV
  for all console /channel tests
* tests/qemuxml2argvdata/qemuxml2argv-channel-virtio-auto.args,
  tests/qemuxml2argvdata/qemuxml2argv-channel-virtio.args
  tests/qemuxml2argvdata/qemuxml2argv-console-virtio.args: Update
  for correct chardev syntax
* tests/qemuxml2argvdata/qemuxml2argv-console-virtio-many.args,
  tests/qemuxml2argvdata/qemuxml2argv-console-virtio-many.xml: New
  test file
2011-11-03 12:01:05 +00:00
Eric Blake
319992d4b6 API: document scheduler parameter names
Document the parameter names that will be used by
virDomain{Get,Set}SchedulerParameters{,Flags}, rather than
hard-coding those names in each driver, to match what is
done with memory, blkio, and blockstats parameters.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_SCHEDULER_CPU_SHARES)
(VIR_DOMAIN_SCHEDULER_VCPU_PERIOD)
(VIR_DOMAIN_SCHEDULER_VCPU_QUOTA, VIR_DOMAIN_SCHEDULER_WEIGHT)
(VIR_DOMAIN_SCHEDULER_CAP, VIR_DOMAIN_SCHEDULER_RESERVATION)
(VIR_DOMAIN_SCHEDULER_LIMIT, VIR_DOMAIN_SCHEDULER_SHARES): New
field name macros.
* src/qemu/qemu_driver.c (qemuSetSchedulerParametersFlags)
(qemuGetSchedulerParametersFlags): Use new defines.
* src/test/test_driver.c (testDomainGetSchedulerParamsFlags)
(testDomainSetSchedulerParamsFlags): Likewise.
* src/xen/xen_hypervisor.c (xenHypervisorGetSchedulerParameters)
(xenHypervisorSetSchedulerParameters): Likewise.
* src/xen/xend_internal.c (xenDaemonGetSchedulerParameters)
(xenDaemonSetSchedulerParameters): Likewise.
* src/lxc/lxc_driver.c (lxcSetSchedulerParametersFlags)
(lxcGetSchedulerParametersFlags): Likewise.
* src/esx/esx_driver.c (esxDomainGetSchedulerParametersFlags)
(esxDomainSetSchedulerParametersFlags): Likewise.
* src/libxl/libxl_driver.c (libxlDomainGetSchedulerParametersFlags)
(libxlDomainSetSchedulerParametersFlags): Likewise.
2011-11-02 13:52:56 -06:00
Daniel P. Berrange
f4786c1885 Add missing param initialization in qemuDomainBlockStatsFlags
* src/qemu/qemu_driver.c: Fix use of uninitialized 'params'
2011-11-02 14:55:03 +00:00
Eric Blake
97656536e7 qemu: allow getting < max typed parameters
Since all virTypedParameter APIs allow us to return the number
of slots we actually populated, we should allow the user to
call with nparams too small (without overrunning their array)
or too large (ignoring the tail of the array that we can't fill),
rather than requiring that they get things exactly right.

Making this change will make it easier for a future patch to
introduce VIR_TYPED_PARAM_STRING, with filtering in libvirt.c
rather than in every single driver, since users already have
to be prepared for *nparams to be smaller on exit than on entry.

* src/qemu/qemu_driver.c (qemuDomainGetBlkioParameters)
(qemuDomainGetMemoryParameters): Allow variable nparams on entry.
(qemuGetSchedulerParametersFlags): Drop redundant check.
(qemudDomainBlockStats, qemudDomainBlockStatsFlags): Rename...
(qemuDomainBlockStats, qemuDomainBlockStatsFlags): ...to this.
Don't return unavailable stats.
2011-11-01 13:20:48 -06:00
Sage Weil
243f185742 qemu: pass virConnectPtr into Domain{Attach,Detach}*
The qemu RBD driver needs access to the conn in order to get the secret
needed for connecting to the ceph cluster.

Signed-off-by: Sage Weil <sage@newdream.net>
2011-10-31 13:13:29 -06:00
Daniel P. Berrange
f877fed36f Wire up QEMU implementation for virDomainOpenGraphics
The QEMU monitor command 'add_client' can be used to connect to
a VNC or SPICE graphics display. This allows for implementation
of the virDomainOpenGraphics API

* src/qemu/qemu_driver.c: Implement virDomainOpenGraphics
* src/qemu/qemu_monitor.c, src/qemu/qemu_monitor.h,
  src/qemu/qemu_monitor_json.c, src/qemu/qemu_monitor_json.h,
  src/qemu/qemu_monitor_text.c, src/qemu/qemu_monitor_text.h:
  Add binding for 'add_client' command
2011-10-28 10:23:53 +01:00
Eric Blake
6889f33e8b qemu: simplify use of HAVE_YAJL
Rather than making all clients of monitor commands that are JSON-only
check whether yajl support was compiled in, it is simpler to just
avoid setting the capability bit up front if we can't use the capability.

* src/qemu/qemu_capabilities.c (qemuCapsComputeCmdFlags): Only set
capability bit if we also have yajl library to use it.
* src/qemu/qemu_driver.c (qemuDomainReboot): Drop #ifdefs.
* src/qemu/qemu_process.c (qemuProcessStart): Likewise.
* tests/qemuhelptest.c (testHelpStrParsing): Pass test even
without yajl.
* tests/qemuxml2argvtest.c (mymain): Simplify use of json flag.
* tests/qemuxml2argvdata/qemuxml2argv-disk-drive-error-*.args:
Update expected results to match.
2011-10-26 11:55:39 -06:00
Michal Privoznik
b8fbe5d5ba qemu: Move device alias assigning before command line construction
This patch is rather cosmetic as it only moves device alias
assignation from command line construction just before that.
However, it is needed in connotation of previous and next patch.
2011-10-25 09:27:10 +02:00
Eric Blake
9a220665e7 snapshot: simplify indentation of sysinfo
The improvements to virBuffer, along with a paradigm shift to pass
the original buffer through rather than creating a second buffer,
allow us to shave off quite a few lines of code.

* src/util/sysinfo.h (virSysinfoFormat): Alter signature.
* src/util/sysinfo.c (virSysinfoFormat, virSysinfoBIOSFormat)
(virSysinfoSystemFormat, virSysinfoProcessorFormat)
(virSysinfoMemoryFormat): Change indentation parameter.
* src/conf/domain_conf.c (virDomainSysinfoDefFormat): Adjust
caller.
* src/qemu/qemu_driver.c (qemuGetSysinfo): Likewise.
2011-10-20 16:02:16 -06:00
tangchen
755a09b579 qemu: allow json in domxml-to-native
There is a little difference between the output of domxml-to-native and the actual commandline.
No matter qemu is in control or readline mode, domxml-to-native always converts it to readline mode.

That is because the parameter "monitor_json" for qemuBuildCommandLine() is always set to false
in qemuDomainXMLToNative().

Signed-off-by: tangchen <tangchen@cn.fujitsu.com>
2011-10-20 14:30:48 -06:00
Eric Blake
dad15a2e02 snapshot: detect when qemu lacks disk-snapshot support
Noticed when testing new libvirt against old qemu that lacked the
snapshot_blkdev HMP command.  Libvirt was mistakenly treating the
command as successful, and re-writing the domain XML to use the
just-created 0-byte file, rendering the domain broken on restart.

* src/qemu/qemu_monitor_text.c (qemuMonitorTextDiskSnapshot):
Notice another possible error message.
* src/qemu/qemu_driver.c
(qemuDomainSnapshotCreateSingleDiskActive): Don't keep 0-byte file
on failure.
2011-10-18 16:03:42 -06:00
Jiri Denemark
5d784bd6d7 Clarify semantics of virDomainMigrate2
Explicitly disallow conflicts between domain name from dxml and dname.
2011-10-14 22:04:31 +02:00
Jiri Denemark
bf7676af30 qemu: Make sure BeginJob is always followed by EndJob
Otherwise we can end up with a dangling job that can only be cleared by
restarting libvirtd.
2011-10-13 22:05:35 +02:00
Michal Privoznik
9bc9999b6e qemu: Check for domain being active on successful job acquire
As this is needed. Although some functions check for domain
being active before obtaining job, we need to check it after,
because obtaining job unlocks domain object, during which
a state of domain can be changed.
2011-10-13 10:01:07 +02:00
Michal Privoznik
2050b61dec qemu: Implement VIR_DUMP_RESET
This patch extends qemudDomainCoreDump so it supports new VIR_DUMP_RESET
flag. If this flag is set, domain is reset on successful dump. However,
this is needed to be done after we start CPUs.
2011-10-13 09:32:27 +02:00
Eric Blake
5cf56c4b23 snapshot: implement LIST_LEAVES flag in qemu
With the recent refactoring of qemu snapshot relationships, it
is now trivial to filter on leaves.

* src/conf/domain_conf.c (virDomainSnapshotObjListCount)
(virDomainSnapshotObjListCopyNames): Handle new flag.
* src/qemu/qemu_driver.c (qemuDomainSnapshotListNames)
(qemuDomainSnapshotNum, qemuDomainSnapshotListChildrenNames)
(qemuDomainSnapshotNumChildren): Pass new flag through.
2011-10-12 16:09:20 -06:00
Eric Blake
ebec21eee0 snapshot: drop dead parameters
The previous optimizations lead to some follow-on cleanups.

* src/conf/domain_conf.c (virDomainSnapshotForEachChild)
(virDomainSnapshotForEachDescendant): Drop dead parameter.
(virDomainSnapshotActOnDescendant)
(virDomainSnapshotObjListNumFrom)
(virDomainSnapshotObjListGetNamesFrom): Update callers.
* src/qemu/qemu_driver.c (qemuDomainSnapshotNumChildren)
(qemuDomainSnapshotListChildrenNames, qemuDomainSnapshotDelete):
Likewise.
* src/conf/domain_conf.h: Update prototypes.
2011-10-11 17:34:19 -06:00
Eric Blake
9279bdf757 snapshot: track qemu snapshot relations
Maintain the parent/child relationships of all qemu snapshots.

* src/qemu/qemu_driver.c (qemuDomainSnapshotLoad): Populate
relationships after loading.
(qemuDomainSnapshotCreateXML): Set relations on creation; tweak
redefinition to reuse existing object.
(qemuDomainSnapshotReparentChildren, qemuDomainSnapshotDelete):
Clear relations on delete.
2011-10-11 17:15:15 -06:00
Eric Blake
5907403716 snapshot: implement snapshot children listing in qemu
Not too hard to wire up.  The trickiest part is realizing that
listing children of a snapshot cannot use SNAPSHOT_LIST_ROOTS,
and that we overloaded that bit to also mean SNAPSHOT_LIST_DESCENDANTS;
we use that bit to decide which iteration to use, but don't want
the existing counting/listing functions to see that bit.

* src/conf/domain_conf.h (virDomainSnapshotObjListNumFrom)
(virDomainSnapshotObjListGetNamesFrom): New prototypes.
* src/conf/domain_conf.c (virDomainSnapshotObjListNumFrom)
(virDomainSnapshotObjListGetNamesFrom): New functions.
* src/libvirt_private.syms (domain_conf.h): Export them.
* src/qemu/qemu_driver.c (qemuDomainSnapshotNumChildren)
(qemuDomainSnapshotListChildrenNames): New functions.
2011-10-10 17:31:06 -06:00
Michal Privoznik
cd016a46c7 qemuDomainAttach: Initialize pidfile variable
If parsing qemu command line fails (e.g. because of non-existing
process number supplied), we jump to cleanup label where we free
pidfile. Therefore it needs to be initialized. Otherwise we free
random pointer.
2011-10-09 10:42:42 +02:00
Eric Blake
29879b550b snapshot: enforce REVERT_FORCE on qemu
Implements the documentation for snapshot revert vs. force.

Part of the patch tightens existing behavior (previously, reverting
to an old snapshot without <domain> was blindly attempted, now it
requires force), while part of it relaxes behavior (previously, it
was not possible to revert an active domain to an ABI-incompatible
active snapshot, now force allows this transition).

* src/qemu/qemu_driver.c (qemuDomainRevertToSnapshot): Check for
risky situations, and allow force to get past them.
2011-10-05 11:33:39 -06:00
Jiri Denemark
fcd2bd55d7 qemu: Don't fail virDomainGetInfo if we can't update balloon info
Qemu driver tries to update balloon data in virDomainGetInfo and if it
can't do so because there is another monitor job running, it just
reports what's known in domain def. However, if there was no job running
but getting the data from qemu fails, we would fail the whole API. This
doesn't make sense. Let's make the failure nonfatal.
2011-10-05 16:41:48 +02:00
Michal Privoznik
a111b9e24f qemu: Check for outstanding async job too
Currently, qemuDomainGetXMLDesc and qemudDomainGetInfo check for
outstanding synchronous job before (eventual) monitor entering.
However, there can be already async job set, e.g. migration.
2011-09-30 08:36:43 +02:00
Xu He Jie
c0e4d4329c qemu: Implement 'reset' for qemu driver
Signed-off-by: Xu He Jie <xuhj@linux.vnet.ibm.com>
2011-09-29 06:55:17 -06:00
Michal Privoznik
b1b5b51ae8 qemu: Check for ejected media during startup and migration
If the daemon is restarted so we reconnect to monitor, cdrom media
can be ejected. In that case we don't want to show it in domain xml,
or require it on migration destination.

To check for disk status use 'info block' monitor command.
2011-09-28 19:49:11 +02:00
Eric Blake
4ee8092dde snapshot: implement getparent in qemu
First hypervisor implementation of the new API.
Allows 'virsh snapshot-list --tree' to be more efficient.

* src/qemu/qemu_driver.c (qemuDomainSnapshotGetParent): New
function.
2011-09-28 09:54:57 -06:00
Jiri Denemark
bd83b2a371 qemu: Preserve fakeReboot flag in domain status
Thus, when libvirtd is restarted, it will know if a domain is supposed
to be killed or reset when it shuts down.
2011-09-28 15:27:22 +02:00
Eric Blake
e485dcc9cb snapshot: remove snapshot metadata on transient exit
Commit 282fe1f0 documented that transient domains will auto-delete
any snapshot metadata when the last reference to the domain is
removed, and that management apps are in charge of grabbing any
snapshot metadata prior to that point.  However, this was not
actually implemented for qemu until now.

* src/qemu/qemu_driver.c (qemudDomainCreate)
(qemuDomainDestroyFlags, qemuDomainSaveInternal)
(qemudDomainCoreDump, qemuDomainRestoreFlags, qemudDomainDefine)
(qemuDomainUndefineFlags, qemuDomainMigrateConfirm3)
(qemuDomainRevertToSnapshot): Clean up snapshot metadata.
* src/qemu/qemu_migration.c (qemuMigrationPrepareAny)
(qemuMigrationPerformJob, qemuMigrationPerformPhase)
(qemuMigrationFinish): Likewise.
* src/qemu/qemu_process.c (qemuProcessHandleMonitorEOF)
(qemuProcessReconnect, qemuProcessReconnectHelper)
(qemuProcessAutoDestroyDom): Likewise.
2011-09-22 14:02:03 +08:00
Eric Blake
bcf974b94b snapshot: prepare to remove transient snapshot metadata
This patch is mostly code motion - moving some functions out
of qemu_driver and into qemu_domain so they can be reused by
multiple qemu_* files (since qemu_driver.h must not grow).
It also adds a new helper function, qemuDomainRemoveInactive,
which will be used in the next patch.

* src/qemu/qemu_domain.h (qemuFindQemuImgBinary)
(qemuDomainSnapshotWriteMetadata, qemuDomainSnapshotForEachQcow2)
(qemuDomainSnapshotDiscard, qemuDomainSnapshotDiscardAll)
(qemuDomainRemoveInactive): New prototypes.
(struct qemu_snap_remove): New struct.
* src/qemu/qemu_domain.c (qemuDomainRemoveInactive)
(qemuDomainSnapshotDiscardAllMetadata): New functions.
(qemuFindQemuImgBinary, qemuDomainSnapshotWriteMetadata)
(qemuDomainSnapshotForEachQcow2, qemuDomainSnapshotDiscard)
(qemuDomainSnapshotDiscardAll): Move here...
* src/qemu/qemu_driver.c (qemuFindQemuImgBinary)
(qemuDomainSnapshotWriteMetadata, qemuDomainSnapshotForEachQcow2)
(qemuDomainSnapshotDiscard, qemuDomainSnapshotDiscardAll): ...from
here.
(qemuDomainUndefineFlags): Update caller.
* src/conf/domain_conf.c (virDomainRemoveInactive): Doc fixes.
2011-09-22 13:52:17 +08:00
Eric Blake
e6966fa79a snapshot: fix logic bug in qemu undefine
Commit 19f8c98 introduced VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA,
with the intent that omitting the flag makes undefine fail, and
including the flag deletes metadata.  But it used the wrong logic.
Also, hoist the transient domain sooner, so that we don't
accidentally remove metadata of a transient domain.

* src/qemu/qemu_driver.c (qemuDomainUndefineFlags): Check correct
flag value.
2011-09-22 13:43:21 +08:00
Jiri Denemark
f84aedad09 qemu: Fix shutdown regression with buggy qemu
The commit that prevents disk corruption on domain shutdown
(96fc478417) causes regression with QEMU
0.14.* and 0.15.* because of a regression bug in QEMU that was fixed
only recently in QEMU git. The affected versions of QEMU do not quit on
SIGTERM if started with -no-shutdown, which we use to implement fake
reboot. Since -no-shutdown tells QEMU not to quit automatically on guest
shutdown, domains started using the affected QEMU cannot be shutdown
properly and stay in a paused state.

This patch disables fake reboot feature on such QEMU by not using
-no-shutdown, which makes shutdown work as expected. However,
virDomainReboot will not work in this case and it will report "Requested
operation is not valid: Reboot is not supported with this QEMU binary".
2011-09-21 16:53:06 +02:00
Peter Krempa
2ad83bf448 virsh: doc: Fix supported driver types for attach-disk command
Virsh man page lists driver types to be used with attach-device
command, but does not specify that those are usable only with the XEN
Hypervisor.

This patch adds statement, that those options specified are applicable
only on the Xen hypervisor and adds option usable with qemu emulator.

This patch also changes type of error returned by QEMU driver if the
user specifies incompatible driver type from VIR_ERR_INTERNAL_ERROR to
VIR_ERR_CONFIG_UNSUPPORTED.
2011-09-19 16:54:13 -06:00
Eric Blake
43c2641c18 snapshot: allow disk snapshots of qcow2 disks
For all types of disks other than qcow2, we were requesting that
SELinux labeling visit the new file as if it were qcow2, which
means labeling would try to find the backing files of an empty file.
And for a pre-existing qcow2 disk, we were passing NULL, which meant
that labelling tried to probe the file type (and if probing is
disabled, per the default qemu.conf, this made snapshots fail).
What we really want is to make SELinux labeling visit the new
file as raw; it will later be converted to qcow2 if qemu successfully
made the snapshot.

* src/qemu/qemu_driver.c
(qemuDomainSnapshotCreateSingleDiskActive): Force SELinux labeling
to avoid probe of new file.
2011-09-17 06:16:08 -06:00
Eric Blake
2895905a0b snapshot: affect persistent xml after disk snapshot
For external snapshots to be useful on persistent domains, we must
alter the persistent definition alongside the running definition.
Thanks to the possibility of disk hotplug as well as of edits that
only affect the persistent xml, we can't assume that vm->def and
vm->newDef have the same disk at the same index, so we can only
update the persistent copy if the device destination matches up.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateDiskActive)
(qemuDomainSnapshotCreateSingleDiskActive): Also affect newDef, if
present.
2011-09-17 05:57:23 -06:00
Jiri Denemark
96fc478417 qemu: Prevent disk corruption on domain shutdown
Ever since we introduced fake reboot, we call qemuProcessKill as a
reaction to SHUTDOWN event. Unfortunately, qemu doesn't guarantee it
flushed all internal buffers before sending SHUTDOWN, in which case
killing the process forcibly may result in (virtual) disk corruption.

By sending just SIGTERM without SIGKILL we give qemu time to to flush
all buffers and exit. Once qemu exits, we will see an EOF on monitor
connection and tear down the domain. In case qemu ignores SIGTERM or
just hangs there, the process stays running but that's not any different
from a possible hang anytime during the shutdown process so I think it's
just fine.

Also qemu (since 0.14 until it's fixed) has a bug in SIGTERM processing
which causes it not to exit but instead send new SHUTDOWN event and keep
waiting. I think the best we can do is to ignore duplicate SHUTDOWN
events to avoid a SHUTDOWN-SIGTERM loop and leave the domain in paused
state.
2011-09-16 17:21:10 +02:00
Peter Krempa
79cf07af7c Avoid using "devname" as an identifier.
/usr/lib/stdlib.h in Mac OS X and probably also in BSD's
exports this symbol :(
2011-09-16 20:49:04 +08:00
Jim Fehlig
1c90642f85 Fix build after commit 829bce17
Pushing under build-breaker rule.
2011-09-14 17:57:55 -06:00
Jim Fehlig
8fc40c511c Save migration speed in qemuDomainMigrateSetMaxSpeed
Now that migration speed is stored in qemuDomainObjPrivate structure,
save the new value when invoking qemuDomainMigrateSetMaxSpeed().

Allow setting migration speed on inactive domain too.
2011-09-14 16:42:10 -06:00
Jim Fehlig
829bce174c Impl virDomainMigrateGetMaxSpeed in qemu driver 2011-09-14 16:42:10 -06:00
Guannan Ren
011eeb4130 snapshot: fix double free of qemuImgBinary
Regression introduced in commit 3881a470, due to an improper rebase
of a cleanup written beforehand but only applied after a rebased of
a refactoring that created a new function in commit 25fb3ef.

Also avoids passing NULL to printf %s.

* src/qemu/qemu_driver.c: In qemuDomainSnapshotForEachQcow2()
it free up the memory of qemu_driver->qemuImgBinary in the
cleanup tag which leads to the garbage value of qemuImgBinary
in qemu_driver struct and libvirtd crash when running
"virsh snapshot-create" command a second time.

Signed-off-by: Eric Blake <eblake@redhat.com>
2011-09-13 09:11:11 -06:00
Eric Blake
6977fd95bf blockinfo: fix qemu regression in handling disk name
Regression introduced in commit 89b6284fd, due to an incorrect
conversion to the new means of converting disk names back to
the correct object.

* src/qemu/qemu_driver.c (qemuDomainGetBlockInfo): Avoid NULL deref.
2011-09-08 10:52:43 +01:00
Peter Krempa
e0a07bb1f2 link-state: qemu: Add net intf modification to virUpdateDeviceFlags
This patch enables modifying network device configuration using the
virUpdateDeviceFlags API method. Matching of devices is accomplished
using MAC addresses.

While updating live configuration of a running domain, the user is
allowed only to change link state of the interface. Additional
modifications may be added later. For now the code checks for
unsupported changes and thereafter changes the link state, if
applicable.

When updating persistent configuration of guest's network interface the
whole configuration (except for the MAC address) may be modified and
is stored for the next startup.

* src/qemu/qemu_driver.c   - Add dispatching of virUpdateDevice for
                             network devices update (live/config)
* src/qemu/qemu_hotplug.c  - add setting of initial link state on live
                             device addition
                           - add function to change network device
                             configuration. By now it supports only
                             changing of link state
* src/qemu/qemu_hotplug.h  - Headers to above functions
* src/qemu/qemu_process.c  - set link states before virtual machine
                             start. Qemu does not support setting of
                             this on the command line.
2011-09-06 16:23:47 +08:00
Osier Yang
ee0d8c3b5c latency: Implemente internal API for qemu driver 2011-09-06 12:02:51 +08:00
Osier Yang
2f58ba8996 latency: Update monitor functions for new latency fields
The mainly changes are:

1) Update qemuMonitorGetBlockStatsInfo and it's children (Text/JSON)
   functions to return the value of new latency fields.
2) Add new function qemuMonitorGetBlockStatsParamsNumber, which is
   to count how many parameters the underlying QEMU supports.
3) Update virDomainBlockStats in src/qemu/qemu_driver.c to be
   compatible with the changes by 1).
2011-09-06 12:02:51 +08:00
Michal Privoznik
d38897a5d4 qemu: Deal with stucked qemu on daemon startup
If libvirt daemon gets restarted and there is (at least) one
unresponsive qemu, the startup procedure hangs up. This patch creates
one thread per vm in which we try to reconnect to monitor. Therefore,
blocking in one thread will not affect other APIs.
2011-09-05 18:14:08 +02:00
Michal Privoznik
597fe3cee6 daemon: Create priority workers pool
This patch annotates APIs with low or high priority.
In low set MUST be all APIs which might eventually access monitor
(and thus block indefinitely). Other APIs may be marked as high
priority. However, some must be (e.g. domainDestroy).

For high priority calls (HPC), there are some high priority workers
(HPW) created in the pool. HPW can execute only HPC, although normal
worker can process any call regardless priority. Therefore, only those
APIs which are guaranteed to end in reasonable small amount of time
can be marked as HPC.

The size of this HPC pool is static, because HPC are expected to end
quickly, therefore jobs assigned to this pool will be served quickly.
It can be configured in libvirtd.conf via prio_workers variable.
Default is set to 5.

To mark API with low or high priority, append priority:{low|high} to
it's comment in src/remote/remote_protocol.x. This is similar to
autogen|skipgen. If not marked, the generator assumes low as default.
2011-09-05 18:14:08 +02:00
Eric Blake
6337989089 snapshot: use SELinux and lock manager with external snapshots
With this, it is now possible to create external snapshots even
when SELinux is enforcing, and to protect the new file with a
lock manager.

* src/qemu/qemu_driver.c
(qemuDomainSnapshotCreateSingleDiskActive): Create and register
new file with proper permissions and locks.
(qemuDomainSnapshotCreateDiskActive): Update caller.
2011-09-05 07:03:05 -06:00
Eric Blake
9c21b44131 snapshot: wire up live qemu disk snapshots
Lots of earlier patches led up to this point - the qemu snapshot_blkdev
monitor command can now be controlled by libvirt!  Well, insofar as
SELinux doesn't prevent qemu from open(O_CREAT) on the files.  There's
still some followup work before things work with SELinux enforcing,
but this patch is big enough to post now.

There's still room for other improvements, too (for example, taking a
disk snapshot of an inactive domain, by using qemu-img for both internal
and external snapshots; wiring up delete and revert control, including
additional flags from my RFC; supporting active QED disk snapshots;
supporting per-storage-volume snapshots such as LVM or btrfs snapshots;
etc.).  But this patch is the one that proves the new XML works!

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Wire in
active disk snapshots.
(qemuDomainSnapshotDiskPrepare)
(qemuDomainSnapshotCreateDiskActive)
(qemuDomainSnapshotCreateSingleDiskActive): New functions.
2011-09-05 07:03:05 -06:00
Eric Blake
7807e05d43 snapshot: reject unimplemented disk snapshot features
My RFC for snapshot support [1] proposes several rules for when it is
safe to delete or revert to an external snapshot, predicated on
the existence of new API flags.  These will be incrementally added
in future patches, but until then, blindly mishandling a disk
snapshot risks corrupting internal state, so it is better to
outright reject the attempts until the other pieces are in place,
thus incrementally relaxing the restrictions added in this patch.

[1] https://www.redhat.com/archives/libvir-list/2011-August/msg00361.html

* src/qemu/qemu_driver.c (qemuDomainSnapshotCountExternal): New
function.
(qemuDomainUndefineFlags, qemuDomainSnapshotDelete): Use it to add
safety valve.
(qemuDomainRevertToSnapshot, qemuDomainSnapshotCreateXML): Add safety
valve.
2011-09-05 07:03:04 -06:00
Eric Blake
e03a62b456 snapshot: add flag for requesting disk snapshot
Prior to this patch, <domainsnapshot>/<disks> was ignored.  This
changes it to be an error unless an explicit disk snapshot is
requested (a future patch may relax things if it turns out to
be useful to have a <disks> specification alongside a system
checkpoint).

* include/libvirt/libvirt.h.in
(VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY): New flag.
* src/libvirt.c (virDomainSnapshotCreateXML): Document it.
* src/esx/esx_driver.c (esxDomainSnapshotCreateXML): Disk
snapshots not supported yet.
* src/vbox/vbox_tmpl.c (vboxDomainSnapshotCreateXML): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Likewise.
2011-09-05 07:03:04 -06:00
Eric Blake
89b6284fd9 snapshot: also support disks by path
I got confused when 'virsh domblkinfo dom disk' required the
path to a disk (which can be ambiguous, since a single file
can back multiple disks), rather than the unambiguous target
device name that I was using in disk snapshots.  So, in true
developer fashion, I went for the best of both worlds - all
interfaces that operate on a disk (aka block) now accept
either the target name or the unambiguous path to the backing
file used by the disk.

* src/conf/domain_conf.h (virDomainDiskIndexByName): Add
parameter.
(virDomainDiskPathByName): New prototype.
* src/libvirt_private.syms (domain_conf.h): Export it.
* src/conf/domain_conf.c (virDomainDiskIndexByName): Also allow
searching by path, and decide whether ambiguity is okay.
(virDomainDiskPathByName): New function.
(virDomainDiskRemoveByName, virDomainSnapshotAlignDisks): Update
callers.
* src/qemu/qemu_driver.c (qemudDomainBlockPeek)
(qemuDomainAttachDeviceConfig, qemuDomainUpdateDeviceConfig)
(qemuDomainGetBlockInfo, qemuDiskPathToAlias): Likewise.
* src/qemu/qemu_process.c (qemuProcessFindDomainDiskByPath):
Likewise.
* src/libxl/libxl_driver.c (libxlDomainAttachDeviceDiskLive)
(libxlDomainDetachDeviceDiskLive, libxlDomainAttachDeviceConfig)
(libxlDomainUpdateDeviceConfig): Likewise.
* src/uml/uml_driver.c (umlDomainBlockPeek): Likewise.
* src/xen/xend_internal.c (xenDaemonDomainBlockPeek): Likewise.
* docs/formatsnapshot.html.in: Update documentation.
* tools/virsh.pod (domblkstat, domblkinfo): Likewise.
* docs/schemas/domaincommon.rng (diskTarget): Tighten pattern on
disk targets.
* docs/schemas/domainsnapshot.rng (disksnapshot): Update to match.
* tests/domainsnapshotxml2xmlin/disk_snapshot.xml: Update test.
2011-09-05 07:03:04 -06:00
Eric Blake
6f66423e17 snapshot: allow halting after snapshot
Since a snapshot is fully recoverable, it is useful to have a
snapshot as a means of hibernating a guest, then reverting to
the snapshot to wake the guest up.  This mode of usage is
similar to 'virsh save/virsh restore', except that virsh
save uses an external file while virsh snapshot keeps the
vm state internal to a qcow2 file.  However, it only works on
persistent domains.

In the usage pattern of snapshot/revert for hibernating a guest,
there is no need to keep the guest running between the two points
in time, especially since that would generate runtime state that
would just be discarded.  Add a flag to make it possible to
stop the domain after the snapshot has completed.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_SNAPSHOT_CREATE_HALT):
New flag.
* src/libvirt.c (virDomainSnapshotCreateXML): Document it.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML)
(qemuDomainSnapshotCreateActive): Implement it.
2011-09-05 07:03:04 -06:00
Eric Blake
3d77d0a644 snapshot: introduce new deletion flag
Reverting to a state prior to an external snapshot risks
corrupting any other branches in the snapshot hierarchy that
were using the snapshot as a read-only backing file.  So
disk snapshot code will default to preventing reverting to
a snapshot that has any children, meaning that deleting just
the children of a snapshot becomes a useful operation in
preparing that snapshot for being a future reversion target.
The code for the new flag is simple - it's one less deletion,
plus a tweak to keep the current snapshot correct.

* include/libvirt/libvirt.h.in
(VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN_ONLY): New flag.
* src/libvirt.c (virDomainSnapshotDelete): Document it, and
enforce mutual exclusion.
* src/qemu/qemu_driver.c (qemuDomainSnapshotDelete): Implement
it.
2011-09-05 07:03:04 -06:00
Eric Blake
973fcd8fd3 snapshot: store qemu domain details in xml
When reverting to a snapshot, the inactive domain configuration
has to be rolled back to what it was at the time of the snapshot.
Additionally, if the VM is active and the snapshot was active,
this now adds a failure if the two configurations are ABI
incompatible, rather than risking qemu confusion.

A future patch will add a VIR_DOMAIN_SNAPSHOT_FORCE flag, which
will be required for two risky code paths - reverting to an
older snapshot that lacked full domain information, and reverting
from running to a live snapshot that requires starting a new qemu
process.  Any reverting that stops a running vm is also a form
of data loss (discarding the current running state to go back in
time), but as that is what reversion usually implies, it is
probably not worth requiring a force flag.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Copy out
domain.
(qemuDomainSnapshotCreateXML, qemuDomainRevertToSnapshot): Perform
ABI compatibility checks.
2011-09-03 08:27:07 -06:00
Eric Blake
f609cb85ca snapshot: allow full domain xml in snapshot
Just like VM saved state images (virsh save), snapshots MUST
track the inactive domain xml to detect any ABI incompatibilities.

The indentation is not perfect, but functionality comes before form.

Later patches will actually supply a full domain; for now, this
wires up the storage to support one, but doesn't ever generate one
in dumpxml output.

Happily, libvirt.c was already rejecting use of VIR_DOMAIN_XML_SECURE
from read-only connections, even though before this patch, there was
no information to be secured by the use of that flag.

And while we're at it, mark the libvirt snapshot metadata files
as internal-use only.

* src/libvirt.c (virDomainSnapshotGetXMLDesc): Document flag.
* src/conf/domain_conf.h (_virDomainSnapshotDef): Add member.
(virDomainSnapshotDefParseString, virDomainSnapshotDefFormat):
Update signature.
* src/conf/domain_conf.c (virDomainSnapshotDefFree): Clean up.
(virDomainSnapshotDefParseString): Optionally parse domain.
(virDomainSnapshotDefFormat): Output full domain.
* src/esx/esx_driver.c (esxDomainSnapshotCreateXML)
(esxDomainSnapshotGetXMLDesc): Update callers.
* src/vbox/vbox_tmpl.c (vboxDomainSnapshotCreateXML)
(vboxDomainSnapshotGetXMLDesc): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML)
(qemuDomainSnapshotLoad, qemuDomainSnapshotGetXMLDesc)
(qemuDomainSnapshotWriteMetadata): Likewise.
* docs/formatsnapshot.html.in: Rework doc example.
Based on a patch by Philipp Hahn.
2011-09-03 08:09:35 -06:00
Eric Blake
19f8c980ef snapshot: support new undefine flags in qemu
A nice benefit of deleting all snapshots at undefine time is that
you don't have to do any reparenting or subtree identification - since
everything goes, this is an O(n) process, whereas using multiple
virDomainSnapshotDelete calls would be O(n^2) or worse.  But it is
only doable for snapshot metadata, where we are in control of the
data being deleted; for the actual snapshots, there's too much
likelihood of something going wrong, and requiring even more API
calls to figure out what failed in the meantime, so callers are
better off deleting the snapshot data themselves one snapshot at
a time where they can deal with failures as they happen.

* src/qemu/qemu_driver.c (qemuDomainUndefineFlags): Honor new flags.
2011-09-02 21:57:34 -06:00
Eric Blake
3881a47088 snapshot: cache qemu-img location
As more clients start to want to know this information, doing
a PATH stat walk and malloc for every client adds up.

We are only caching the location, not the capabilities, so even
if qemu-img is updated in the meantime, it will still probably
live in the same location.  So there is no need to worry about
clearing this particular cache.

* src/qemu/qemu_conf.h (qemud_driver): Add member.
* src/qemu/qemu_driver.c (qemudShutdown): Cleanup.
(qemuFindQemuImgBinary): Add an argument, and cache result.
(qemuDomainSnapshotForEachQcow2, qemuDomainSnapshotDiscard)
(qemuDomainSnapshotCreateInactive, qemuDomainSnapshotRevertInactive)
(qemuDomainSnapshotCreateXML, qemuDomainRevertToSnapshot): Update
callers.
2011-09-02 21:57:33 -06:00
Eric Blake
8055e5af82 snapshot: refactor some qemu code
Prepare for code sharing.  No semantic change.

* src/qemu/qemu_driver.c (qemuFindQemuImgBinary)
(qemuDomainSnapshotWriteMetadata)
(qemuDomainSnapshotDiscard)
(qemuDomainSnapshotForEachQcow2): Float up.
(qemuDomainSnapshotDiscardDescendant): Likewise, and rename...
(qemuDomainSnapshotDiscardAll): ...for generic use.
(qemuDomainSnapshotDelete): Update caller.
2011-09-02 21:57:33 -06:00
Eric Blake
282fe1f08c snapshot: prevent stranding snapshot data on domain destruction
Just as leaving managed save metadata behind can cause problems
when creating a new domain that happens to collide with the name
of the just-deleted domain, the same is true of leaving any
snapshot metadata behind.  For safety sake, extend the semantic
change of commit b26a9fa9 to also cover snapshot metadata as a
reason to reject undefining an inactive domain.  A future patch
will make sure that shutdown of a transient domain automatically
deletes snapshot metadata (whether by destroy, shutdown, or
guest-initiated action).  Management apps of transient domains
should take care to capture xml of snapshots, if it is necessary
to recreate the snapshot metadata on a later transient domain
with the same name and uuid.

This also documents a new flag that hypervisors can choose to
support as a shortcut for taking care of the metadata as part of
the undefine process; however, nontrivial driver support for these
flags will be deferred to future patches.

Note that ESX and VBox can never be transient; therefore, they
do not have to worry about automatic cleanup after shutdown
(the persistent domain still remains); likewise they never
store snapshot metadata, so the undefine flag is trivial.
The nontrivial work remaining is thus in the qemu driver.

* include/libvirt/libvirt.h.in
(VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA): New flag.
* src/libvirt.c (virDomainUndefine, virDomainUndefineFlags):
Document new limitations and flag.
* src/esx/esx_driver.c (esxDomainUndefineFlags): Trivial
implementation.
* src/vbox/vbox_tmpl.c (vboxDomainUndefineFlags): Likewise.
* src/qemu/qemu_driver.c (qemuDomainUndefineFlags): Enforce
the limitations.
2011-09-02 21:57:33 -06:00
Eric Blake
bd18b9670f snapshot: add qemu snapshot redefine support
Redefining a qemu snapshot requires a bit of a tweak to the common
snapshot parsing code, but the end result is quite nice.

Be careful that redefinitions do not introduce circular parent
chains.  Also, we don't want to allow conversion between online
and offline existing snapshots.  We could probably do some more
validation for snapshots that don't already exist to make sure
they are even feasible, by parsing qemu-img output, but that
can come later.

* src/conf/domain_conf.h (virDomainSnapshotParseFlags): New
internal flags.
* src/conf/domain_conf.c (virDomainSnapshotDefParseString): Alter
signature to take internal flags.
* src/esx/esx_driver.c (esxDomainSnapshotCreateXML): Update caller.
* src/vbox/vbox_tmpl.c (vboxDomainSnapshotCreateXML): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Support
new public flags.
2011-09-02 21:57:33 -06:00
Eric Blake
ece197e9d4 snapshot: add qemu snapshot creation without metadata
Supporting NO_METADATA on snapshot creation is interesting - we must
still return a valid opaque snapshot object, but the user can't get
anything out of it (unless we add a virDomainSnapshotGetName()),
since it is no longer registered with the domain.

Also, virsh now tries to query for secure xml, in anticipation of
when we store <domain> xml inside <domainsnapshot>; for now, we
can trivially support it, since we have nothing secure.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Support
new flag.
(qemuDomainSnapshotGetXMLDesc): Trivially support VIR_DOMAIN_XML_SECURE.
2011-09-02 21:57:32 -06:00
Eric Blake
6b3801b042 snapshot: identify qemu snapshot roots
Filtering for roots is pretty easy to do.

* src/conf/domain_conf.h (virDomainSnapshotObjListGetNames)
(virDomainSnapshotObjListNum): Update prototype.
* src/conf/domain_conf.c (virDomainSnapshotObjListCopyNames)
(virDomainSnapshotObjListGetNames, virDomainSnapshotObjListCount)
(virDomainSnapshotObjListNum): Support filtering.
* src/qemu/qemu_driver.c (qemuDomainSnapshotNum)
(qemuDomainSnapshotListNames): Update callers.
2011-09-02 17:35:02 -06:00
Eric Blake
9f5e53e211 snapshot: identify which snapshots have metadata
To make it easier to know when undefine will fail because of existing
snapshot metadata, we need to know how many snapshots have metadata.

Also, it is handy to filter the list of snapshots to just those that
have no parents; document that flag now, but implement it in later patches.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_SNAPSHOT_LIST_ROOTS)
(VIR_DOMAIN_SNAPSHOT_LIST_METADATA): New flags.
* src/libvirt.c (virDomainSnapshotNum)
(virDomainSnapshotListNames): Document them.
* src/esx/esx_driver.c (esxDomainSnapshotNum)
(esxDomainSnapshotListNames): Implement trivial flag.
* src/vbox/vbox_tmpl.c (vboxDomainSnapshotNum)
(vboxDomainSnapshotListNames): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotNum)
(qemuDomainSnapshotListNames): Likewise.
2011-09-02 16:58:36 -06:00
Eric Blake
7afa6b4129 snapshot: let qemu discard only snapshot metadata
Adding this was trivial compared to the previous patch for fixing
qemu snapshot deletion in the first place.

* src/qemu/qemu_driver.c (qemuDomainSnapshotDiscard): Add
parameter.
(qemuDomainSnapshotDiscardDescendant, qemuDomainSnapshotDelete):
Update callers.
2011-09-02 16:56:48 -06:00
Eric Blake
67555b2434 snapshot: simplify acting on just children
Similar to the last patch in isolating the filtering from the
client actions, so that clients don't have to reinvent the
filtering.

* src/conf/domain_conf.h (virDomainSnapshotForEachChild): New
prototype.
* src/libvirt_private.syms (domain_conf.h): Export it.
* src/conf/domain_conf.c (virDomainSnapshotActOnChild)
(virDomainSnapshotForEachChild): New functions.
(virDomainSnapshotCountChildren): Delete.
(virDomainSnapshotHasChildren): Simplify.
* src/qemu/qemu_driver.c (qemuDomainSnapshotReparentChildren)
(qemuDomainSnapshotDelete): Likewise.
2011-09-02 16:09:18 -06:00
Eric Blake
90ea06b88a snapshot: track current domain across deletion of children
Deleting a snapshot and all its descendants had problems with
tracking the current snapshot.  The deletion does not necessarily
proceed in depth-first order, so a parent could be deleted
before a child, wreaking havoc on passing the notion of the
current snapshot to the parent.  Furthermore, even if traversal
were depth-first, doing multiple file writes to pass current up
the chain one snapshot at a time is wasteful, comparing to a
single update to the current snapshot at the end of the algorithm.

* src/qemu/qemu_driver.c (snap_remove): Add field.
(qemuDomainSnapshotDiscard): Add parameter.
(qemuDomainSnapshotDiscardDescendant): Adjust accordingly.
(qemuDomainSnapshotDelete): Properly reset current.
2011-09-02 16:07:41 -06:00
Eric Blake
cb231b4bee snapshot: avoid crash when deleting qemu snapshots
This one's nasty.  Ever since we fixed virHashForEach to prevent
nested hash iterations for safety reasons (commit fba550f6),
virDomainSnapshotDelete with VIR_DOMAIN_SNAPSHOT_DELETE_CHILDREN
has been broken for qemu: it deletes children, while leaving
grandchildren intact but pointing to a no-longer-present parent.
But even before then, the code would often appear to succeed to
clean up grandchildren, but risked memory corruption if you have
a large and deep hierarchy of snapshots.

For acting on just children, a single virHashForEach is sufficient.
But for acting on an entire subtree, it requires iteration; and
since we declared recursion as invalid, we have to switch to a
while loop.  Doing this correctly requires quite a bit of overhaul,
so I added a new helper function to isolate the algorithm from the
actions, so that callers do not have to reinvent the iteration.

Note that this _still_ does not handle CHILDREN correctly if one
of the children is the current snapshot; that will be next.

* src/conf/domain_conf.h (_virDomainSnapshotDef): Add mark.
(virDomainSnapshotForEachDescendant): New prototype.
* src/libvirt_private.syms (domain_conf.h): Export it.
* src/conf/domain_conf.c (virDomainSnapshotMarkDescendant)
(virDomainSnapshotActOnDescendant)
(virDomainSnapshotForEachDescendant): New functions.
* src/qemu/qemu_driver.c (qemuDomainSnapshotDiscardChildren):
Replace...
(qemuDomainSnapshotDiscardDescenent): ...with callback that
doesn't nest hash traversal.
(qemuDomainSnapshotDelete): Use new function.
2011-09-02 16:04:32 -06:00
Eric Blake
7dc44eb059 snapshot: fine-tune qemu snapshot revert states
For a system checkpoint of a running or paused domain, it's fairly
easy to honor new flags for altering which state to use after the
revert.  For an inactive snapshot, the revert has to be done while
there is no qemu process, so do back-to-back transitions; this also
lets us revert to inactive snapshots even for transient domains.

* src/qemu/qemu_driver.c (qemuDomainRevertToSnapshot): Support new
flags.
2011-09-02 12:33:37 -06:00
Eric Blake
25fb3ef1e1 snapshot: properly revert qemu to offline snapshots
Commit 5e47785 broke reverts to offline system checkpoint snapshots
with older qemu, since there is no longer any code path to use
qemu -loadvm on next boot.  Meanwhile, reverts to offline system
checkpoints have been broken for newer qemu, both before and
after that commit, since -loadvm no longer works to revert to
disk state without accompanying vm state.  Fix both of these by
using qemu-img to revert disk state.

Meanwhile, consolidate the (now 3) clients of a qemu-img iteration
over all disks of a VM into one function, so that any future
algorithmic fixes to the FIXMEs in that function after partial
loop iterations are dealt with at once.  That does mean that this
patch doesn't handle partial reverts very well, but we're not
making the situation any worse in this patch.

* src/qemu/qemu_driver.c (qemuDomainRevertToSnapshot): Use
qemu-img rather than 'qemu -loadvm' to revert to offline snapshot.
(qemuDomainSnapshotRevertInactive): New helper.
(qemuDomainSnapshotCreateInactive): Factor guts...
(qemuDomainSnapshotForEachQcow2): ...into new helper.
(qemuDomainSnapshotDiscard): Use it.
2011-09-02 12:30:11 -06:00
Eric Blake
88fe7a4ba5 snapshot: improve reverting to qemu paused snapshots
If you take a checkpoint snapshot of a running domain, then pause
qemu, then restore the snapshot, the result should be a running
domain, but the code was leaving things paused.  Furthermore, if
you take a checkpoint of a paused domain, then run, then restore,
there was a brief but non-deterministic window of time where the
domain was running rather than paused.  Fix both of these
discrepancies by always pausing before restoring.

Also, check that the VM is active every time lock is dropped
between two monitor calls.

Finally, straighten out the events that get emitted on each
transition.

* src/qemu/qemu_driver.c (qemuDomainRevertToSnapshot): Always
pause before reversion, and improve events.
2011-09-02 12:05:08 -06:00
Eric Blake
7381aaff33 snapshot: fine-tune qemu saved images starting paused
Implement the new running/paused overrides for saved state management.

Unfortunately, for virDomainSaveImageDefineXML, the saved state
updates are write-only - I don't know of any way to expose a way
to query the current run/pause setting of an existing save image
file to the user without adding a new API or modifying the domain
xml of virDomainSaveImageGetXMLDesc to include a new element to
reflect the state bit encoded into the save image.  However, I
don't think this is a show-stopper, since the API is designed to
leave the state bit alone unless an explicit flag is used to
change it.

* src/qemu/qemu_driver.c (qemuDomainSaveInternal)
(qemuDomainSaveImageOpen): Adjust signature.
(qemuDomainSaveFlags, qemuDomainManagedSave)
(qemuDomainRestoreFlags, qemuDomainSaveImageGetXMLDesc)
(qemuDomainSaveImageDefineXML, qemuDomainObjRestore): Adjust
callers.
2011-09-02 10:00:06 -06:00
Eric Blake
c1ff5dc63d snapshot: better events when starting paused
There are two classes of management apps that track events - one
that only cares about on/off (and only needs to track EVENT_STARTED
and EVENT_STOPPED), and one that cares about paused/running (also
tracks EVENT_SUSPENDED/EVENT_RESUMED).  To keep both classes happy,
any transition that can go from inactive to paused must emit two
back-to-back events - one for started and one for suspended (since
later resuming of the domain will only send RESUMED, but the first
class isn't tracking that).

This also fixes a bug where virDomainCreateWithFlags with the
VIR_DOMAIN_START_PAUSED flag failed to start paused when restoring
from a managed save image.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_EVENT_SUSPENDED_RESTORED)
(VIR_DOMAIN_EVENT_SUSPENDED_FROM_SNAPSHOT)
(VIR_DOMAIN_EVENT_RESUMED_FROM_SNAPSHOT): New sub-events.
* src/qemu/qemu_driver.c (qemuDomainRevertToSnapshot): Use them.
(qemuDomainSaveImageStartVM): Likewise, and add parameter.
(qemudDomainCreate, qemuDomainObjStart): Send suspended event when
starting paused.
(qemuDomainObjRestore): Add parameter.
(qemuDomainObjStart, qemuDomainRestoreFlags): Update callers.
* examples/domain-events/events-c/event-test.c
(eventDetailToString): Map new detail strings.
2011-09-02 10:00:06 -06:00
Marc-André Lureau
162efa1a7c Add "redirdev" redirection device
- create a new "redirdev" element for this purpose
2011-09-02 23:39:03 +08:00
Eric Blake
c554f6e18b snapshot: fix corner case on OOM during creation
Commit 6766ff10 introduced a corner case bug with snapshot creation:
if a snapshot is created, but then we hit OOM while trying to
create the return value of the function, then we have polluted the
internal directory with the snapshot metadata with no way to clean
it up from the running libvirtd.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Don't
write metadata file on OOM condition.
2011-09-02 08:50:01 -06:00
Eric Blake
55d88def95 qemu: detect incomplete save files
Several users have reported problems with 'virsh start' failing because
it was encountering a managed save situation where the managed save file
was incomplete.  Be more robust to this by using two different magic
numbers, so that newer libvirt can gracefully handle an incomplete file
differently than a complete one, while older libvirt will at least fail
up front rather than trying to load only to have qemu fail at the end.

Managed save is a convenience - it exists to preserve as much state
as possible; if the state was not preserved, it is reasonable to just
log that fact, then proceed with a fresh boot.  On the other hand,
user saves are under user control, so we must fail, but by making
the failure message distinct, the user can better decide how to handle
the situation of an incomplete save file.

* src/qemu/qemu_driver.c (QEMUD_SAVE_PARTIAL): New define.
(qemuDomainSaveInternal): Use it to mark incomplete images.
(qemuDomainSaveImageOpen, qemuDomainObjRestore): Add parameter
that controls what to do with partial images.
(qemuDomainRestoreFlags, qemuDomainSaveImageGetXMLDesc)
(qemuDomainSaveImageDefineXML, qemuDomainObjStart): Update callers.
Based on an initial idea by Osier Yang.
2011-09-01 22:08:13 -06:00
Eric Blake
449ae9c2f1 qemu: refactor file opening
In a SELinux or root-squashing NFS environment, libvirt has to go
through some hoops to create a new file that qemu can then open()
by name.  Snapshots are a case where we want to guarantee an empty
file that qemu can open; also, reopening a save file to convert it
from being marked partial to complete requires a reopen to avoid
O_DIRECT headaches.  Refactor some existing code to make it easier
to reuse in later patches.

* src/qemu/qemu_migration.h (qemuMigrationToFile): Drop parameter.
* src/qemu/qemu_migration.c (qemuMigrationToFile): Let cgroup do
the stat, rather than asking caller to do it and pass info down.
* src/qemu/qemu_driver.c (qemuOpenFile): New function, pulled from...
(qemuDomainSaveInternal): ...here.
(doCoreDump, qemuDomainSaveImageOpen): Use it here as well.
2011-09-01 22:08:13 -06:00
Adam Litke
d4b9e06256 BlockPull: Set initial bandwidth limit if specified
The libvirt BlockPull API supports the use of an initial bandwidth limit but the
qemu block_stream API does not.  To get the desired behavior we use the two APIs
strung together: first BlockPull, then BlockJobSetSpeed.  We can do this at the
driver level to avoid duplicated code in each monitor path.

Signed-off-by: Adam Litke <agl@us.ibm.com>
2011-09-01 20:11:50 -06:00
Osier Yang
6f2581edd7 qemu: Fix a regression of domain save
* src/qemu/qemu_driver.c - qemuDomainSaveInternal: Return directly
will keep the domain object locked, introduced by 173015bec6.
2011-09-01 17:38:20 +08:00
Eric Blake
173015bec6 snapshot: forbid snapshot on autodestroy domain
There is no reason to forbid pausing an autodestroy domain
(not to mention that 'virsh start --paused --autodestroy'
succeeds in creating a paused autodestroy domain).

Meanwhile, qemu was failing to enforce the API documentation that
autodestroy domains cannot be saved.  And while the original
documentation only mentioned save/restore, snapshots are another
form of saving that are close enough in semantics as to make no
sense on one-shot domains.

* src/qemu/qemu_driver.c (qemudDomainSuspend): Drop bogus check.
(qemuDomainSaveInternal, qemuDomainSnapshotCreateXML): Forbid
saves of autodestroy domains.
* src/libvirt.c (virDomainCreateWithFlags, virDomainCreateXML):
Document snapshot interaction.
2011-08-30 11:03:54 -06:00
Eric Blake
27c8526053 start: allow discarding managed save
There have been several instances of people having problems with
a broken managed save file, and not aware that they could use
'virsh managedsave-remove dom' to fix things.  Making it possible
to do this as part of starting a domain makes the same functionality
easier to find, and one less API call.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_START_FORCE_BOOT): New
flag.
* src/libvirt.c (virDomainCreateWithFlags): Document it.
* src/qemu/qemu_driver.c (qemuDomainObjStart): Alter signature.
(qemuAutostartDomain, qemuDomainStartWithFlags): Update callers.
* tools/virsh.c (cmdStart): Expose it in virsh.
* tools/virsh.pod (start): Document it.
2011-08-30 09:26:47 -06:00
Daniel P. Berrange
ce93f64b1e Fix keymap used to talk with QEMU
The QEMU 'sendkey' command expects keys to be encoded in the same
way as the RFB extended keycode set. Specifically it wants extended
keys to have the high bit of the first byte set, while the Linux
XT KBD driver codeset uses the low bit of the second byte. To deal
with this we introduce a new keymap 'RFB' and use that in the QEMU
driver

* include/libvirt/libvirt.h.in: Add VIR_KEYCODE_SET_RFB
* src/qemu/qemu_driver.c: Use RFB keycode set instead of XT KBD
* src/util/virkeycode-mapgen.py: Auto-generate the RFB keycode
  set from the XT KBD set
* src/util/virkeycode.c: Add RFB keycode entry to table. Add a
  verify check on cardinality of the codeOffset table
2011-08-26 14:18:57 +01:00
Eric Blake
6766ff10dd snapshot: track current snapshot across restarts
Audit all changes to the qemu vm->current_snapshot, and make them
update the saved xml file for both the previous and the new
snapshot, so that there is always at most one snapshot with
<active>1</active> in the xml, and that snapshot is used as the
current snapshot even across libvirtd restarts.

This patch does not fix the case of virDomainSnapshotDelete(,CHILDREN)
where one of the children is the current snapshot; that will be later.

* src/conf/domain_conf.h (_virDomainSnapshotDef): Alter member
type and name.
* src/conf/domain_conf.c (virDomainSnapshotDefParseString)
(virDomainSnapshotDefFormat): Update clients.
* docs/schemas/domainsnapshot.rng: Tighten rng.
* src/qemu/qemu_driver.c (qemuDomainSnapshotLoad): Reload current
snapshot.
(qemuDomainSnapshotCreateXML, qemuDomainRevertToSnapshot)
(qemuDomainSnapshotDiscard): Track current snapshot.
2011-08-25 15:11:03 -06:00
Eric Blake
5e47785b85 snapshot: only pass snapshot to qemu command line when reverting
Changing the current vm, and writing that change to the file
system, all before a new qemu starts, is risky; it's hard to
roll back if starting the new qemu fails for some reason.
Instead of abusing vm->current_snapshot and making the command
line generator decide whether the current snapshot warrants
using -loadvm, it is better to just directly pass a snapshot all
the way through the call chain if it is to be loaded.

This frees up the last use of snapshot->def->active for qemu's
use, so the next patch can repurpose that field for tracking
which snapshot is current.

* src/qemu/qemu_command.c (qemuBuildCommandLine): Don't use active
field of snapshot.
* src/qemu/qemu_process.c (qemuProcessStart): Add a parameter.
* src/qemu/qemu_process.h (qemuProcessStart): Update prototype.
* src/qemu/qemu_migration.c (qemuMigrationPrepareAny): Update
callers.
* src/qemu/qemu_driver.c (qemudDomainCreate)
(qemuDomainSaveImageStartVM, qemuDomainObjStart)
(qemuDomainRevertToSnapshot): Likewise.
(qemuDomainSnapshotSetCurrentActive)
(qemuDomainSnapshotSetCurrentInactive): Delete unused functions.
2011-08-25 15:07:57 -06:00
Eric Blake
861dc84bb5 snapshot: don't leak resources on qemu snapshot failure
https://bugzilla.redhat.com/show_bug.cgi?id=727709
mentions that if qemu fails to create the snapshot (such as what
happens on Fedora 15 qemu, which has qmp but where savevm is only
in hmp, and where libvirt is old enough to not try the hmp fallback),
then 'virsh snapshot-list dom' will show a garbage snapshot entry,
and the libvirt internal directory for storing snapshot metadata
will have a bogus file.

This fixes the fallout bug of polluting the snapshot-list with
garbage on failure (the root cause of the F15 bug of not having
fallback to hmp has already been fixed in newer libvirt releases).

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Allocate
memory before making snapshot, and cleanup on failure.  Don't
dereference NULL if transient domain exited during snapshot creation.
2011-08-25 14:01:36 -06:00
Eric Blake
3a52b864dd maint: fix comment typos
* src/qemu/qemu_driver.c (qemuDomainSaveInternal): Fix typo.
* src/conf/domain_event.c (virDomainEventDispatchMatchCallback):
Likewise.
* daemon/libvirtd.c (daemonRunStateInit): Likewise.
* src/lxc/lxc_container.c (lxcContainerChildMountSort): Likewise.
* src/util/virterror.c (virCopyError, virRaiseErrorFull): Likewise.
* src/xenxs/xen_sxpr.c (xenParseSxprSound): Likewise.
2011-08-23 11:31:28 -06:00
Osier Yang
4340b3ba40 qemu: Cleanup improper VIR_ERR_NO_SUPPORT use
* src/qemu/qemu_command.c: s/VIR_ERR_NO_SUPPORT/VIR_ERR_CONFIG_UNSUPPORTED/

* src/qemu/qemu_driver.c: s/VIR_ERR_NO_SUPPORT/VIR_ERR_OPERATION_INVALID/

* src/qemu/qemu_process.c: s/VIR_ERR_NO_SUPPORT/VIR_ERR_OPERATION_INVALID/
2011-08-23 16:23:10 +08:00
Osier Yang
aaa93ab6fa qemu: Allow to undefine a running domain 2011-08-19 21:49:37 +08:00
Eric Blake
398ce48d5c qemu: silence clang false positive
Our logic throws off analyzer tools:

ptr var = NULL;
if (flags == 0) flags = live ? _LIVE : _CONFIG;
if (flags & _LIVE) do stuff
if (flags & _CONFIG) var = non-null;
if (flags & _LIVE) do more stuff
else if (flags & _CONFIG) use var

the tools keep thinking that var can still be NULL in the last
if clause, adding the hint shuts them up.

* src/qemu/qemu_driver.c (qemuDomainSetBlkioParameters): Add a
static analysis hint.
2011-08-11 13:04:25 -06:00
Eric Blake
0de75e855b managedsave: prohibit use on transient domains
Transient domains reject attempts to set autostart, and using
virDomainCreate to restart a domain only works on persistent
domains.  Therefore, managed save makes no sense on transient
domains, and should be rejected up front rather than creating
an otherwise unrecoverable managed save file.

Besides, transient domains imply that a lot more management is
being done by the upper layer; this includes the assumption
that the upper layer is okay managing the saved state file
created by virDomainSave, and does not need to use managed save.

* src/libvirt.c: Document that transient domains are incompatible
with managed save.
* src/qemu/qemu_driver.c (qemuDomainManagedSave): Enforce it.
* src/libxl/libxl_driver.c (libxlDomainManagedSave): Likewise.
2011-08-10 21:50:02 -06:00
Eric Blake
cdbb27e3bb qemu: minor formatting cleanup
I noticed some inconsistent use of 'else'.

* src/qemu/qemu_driver.c (qemuCPUCompare)
(qemuDomainSnapshotCreateXML, qemuDomainRevertToSnapshot)
(qemuDomainSnapshotDiscard): Match coding conventions.
2011-08-10 09:21:56 -06:00
Philipp Hahn
839a5295ef Fix memory leak while scanning snapshots
If a snapshot with the name already exists, virDomainSnapshotAssignDef()
just returns NULL, in which case the snapshot definition is leaked.
Currently this leak is not a big problem, since qemuDomainSnapshotLoad()
is only called once during initial startup of libvirtd.

Signed-off-by: Philipp Hahn <hahn@univention.de>
2011-08-09 10:13:33 -06:00
Eric Blake
f768b4c3e9 qemu: silence coverity false positives
Coverity gets confused by our logic.  Add some hints to silence
false positives.

* src/qemu/qemu_driver.c (qemudDomainGetVcpuPinInfo): Add hint.
(qemuDomainGetMemoryParameters): Likewise.
2011-08-02 16:45:23 -06:00
Eric Blake
0c1813f4c9 qemu: plug child process leak on domain core dump
Detected by Coverity.  Leak introduced by typo in commit 58e668d2.

* src/qemu/qemu_driver.c (doCoreDump): Use correct function.
2011-08-02 15:10:50 -06:00
Eric Blake
00ef048f62 fdstream: drop delete argument
Revert 6a1f5f568f.  Now that libvirt_iohelper takes fds by
inheritance rather than by open() (commit 1eb66479), there is
no longer a race where the parent can unlink() a file prior to
the iohelper open()ing the same file.  From there, it makes
more sense to have the callers both create and unlink, rather
than the caller create and the stream unlink, since the latter
was only needed when iohelper had to do the unlink.

* src/fdstream.h (virFDStreamOpenFile, virFDStreamCreateFile):
Callers are responsible for deletion.
* src/fdstream.c (virFDStreamOpenFileInternal): Don't leak created
file on failure.
(virFDStreamOpenFile, virFDStreamCreateFile): Drop parameter.
* src/lxc/lxc_driver.c (lxcDomainOpenConsole): Update callers.
* src/qemu/qemu_driver.c (qemuDomainScreenshot)
(qemuDomainOpenConsole): Likewise.
* src/storage/storage_driver.c (storageVolumeDownload)
(storageVolumeUpload): Likewise.
* src/uml/uml_driver.c (umlDomainOpenConsole): Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainScreenshot): Likewise.
* src/xen/xen_driver.c (xenUnifiedDomainOpenConsole): Likewise.
2011-08-02 14:53:43 -06:00
Eric Blake
440d6b6a0b screenshot: don't unlink bogus file
The previous qemu patch could end up calling unlink(tmp) before
tmp was the name of a valid file (unlinking a fileXXXXXX template
instead), or calling unlink(tmp) twice on success (once here,
and once at the end of the stream).  Meanwhile, vbox also suffered
from the same leaked tmp file bug.

* src/qemu/qemu_driver.c (qemuDomainScreenshot): Don't unlink on
success, or on invalid name.
* src/vbox/vbox_tmpl.c (vboxDomainScreenshot): Don't leak temp file.
2011-08-02 13:10:35 -06:00
Michal Privoznik
d68b97c8a6 qemu: Unlink temporary file on failure
Although virFDStreamOpenFile will unlink it once opened, when we hit
error path, we must unlink it by hand.
2011-08-02 10:21:08 -06:00
Eric Blake
193cd0f3c8 qemu: fix crash when mixing sync and async monitor jobs
Currently, we attempt to run sync job and async job at the same time. It
means that the monitor commands for two jobs can be run in any order.

In the function qemuDomainObjEnterMonitorInternal():
    if (priv->job.active == QEMU_JOB_NONE && priv->job.asyncJob) {
        if (qemuDomainObjBeginNestedJob(driver, obj) < 0)
We check whether the caller is an async job by priv->job.active and
priv->job.asynJob. But when an async job is running, and a sync job is
also running at the time of the check, then priv->job.active is not
QEMU_JOB_NONE. So we cannot check whether the caller is an async job
in the function qemuDomainObjEnterMonitorInternal(), and must instead
put the burden on the caller to tell us when an async command wants
to do a nested job.

Once the burden is on the caller, then only async monitor enters need
to worry about whether the VM is still running; for sync monitor enter,
the internal return is always 0, so lots of ignore_value can be dropped.

* src/qemu/THREADS.txt: Reflect new rules.
* src/qemu/qemu_domain.h (qemuDomainObjEnterMonitorAsync): New
prototype.
* src/qemu/qemu_process.h (qemuProcessStartCPUs)
(qemuProcessStopCPUs): Add parameter.
* src/qemu/qemu_migration.h (qemuMigrationToFile): Likewise.
(qemuMigrationWaitForCompletion): Make static.
* src/qemu/qemu_domain.c (qemuDomainObjEnterMonitorInternal): Add
parameter.
(qemuDomainObjEnterMonitorAsync): New function.
(qemuDomainObjEnterMonitor, qemuDomainObjEnterMonitorWithDriver):
Update callers.
* src/qemu/qemu_driver.c (qemuDomainSaveInternal)
(qemudDomainCoreDump, doCoreDump, processWatchdogEvent)
(qemudDomainSuspend, qemudDomainResume, qemuDomainSaveImageStartVM)
(qemuDomainSnapshotCreateActive, qemuDomainRevertToSnapshot):
Likewise.
* src/qemu/qemu_process.c (qemuProcessStopCPUs)
(qemuProcessFakeReboot, qemuProcessRecoverMigration)
(qemuProcessRecoverJob, qemuProcessStart): Likewise.
* src/qemu/qemu_migration.c (qemuMigrationToFile)
(qemuMigrationWaitForCompletion, qemuMigrationUpdateJobStatus)
(qemuMigrationJobStart, qemuDomainMigrateGraphicsRelocate)
(doNativeMigrate, doTunnelMigrate, qemuMigrationPerformJob)
(qemuMigrationPerformPhase, qemuMigrationFinish)
(qemuMigrationConfirm): Likewise.
* src/qemu/qemu_hotplug.c: Drop unneeded ignore_value.
2011-08-01 09:41:57 -06:00
Alex Jia
c03f7f1358 qemu: fix return value issue
whether or not previous return value is -1, the following codes will be
executed for a inactive guest in src/qemu/qemu_driver.c:
ret = virDomainSaveConfig(driver->configDir, persistentDef);
and if everything is okay, 'ret' is assigned to 0, the previous 'ret'
will be overwritten, this patch will fix this issue.

* src/qemu/qemu_driver.c: avoid return value is overwritten when give a argument
  in out of blkio weight range for a inactive guest.

* how to reproduce?
  % virsh blkiotune ${guestname} --weight 10
  % echo $?

  Note: guest must be inactive, argument 10 in out of blkio weight range,
  and can get a error information by checking libvirtd.log, however,
  virsh hasn't raised any error information, and return value is 0.

  https://bugzilla.redhat.com/show_bug.cgi?id=726304

Signed-off-by: Alex Jia <ajia@redhat.com>
2011-08-01 09:40:13 -06:00
Alex Jia
868453db1e qemu: fix return value issue in qemuDomainSetMemoryParameters
whether or not previous return value is -1, the following codes will be
executed for a inactive guest in qemuDomainSetMemoryParameters:
ret = virDomainSaveConfig(driver->configDir, persistentDef);
and if everything is okay, 'ret' is assigned to 0, the previous 'ret'
will be overwritten, this patch will fix this issue.

* src/qemu/qemu_driver.c: avoid return value is overwritten when set
  min_guarante value to a inactive guest.

* how to reproduce?
  % virsh memtune ${guestname} --min_guarante 1024
  % echo $?

  Note: guest must be inactive, in fact, 'min_guarante' hasn't been implemented
  in memory tunable, and I can get the error when check actual libvirtd.log,
  however, virsh hasn't raised any error information, and return value is 0.

Signed-off-by: Alex Jia <ajia@redhat.com>
2011-08-01 09:21:33 -06:00
Osier Yang
f362a99a53 qemu: Fix a regression of domjobabort
Introduced by f9a837da73, the condition is not changed after
the else clause is removed. So now it quit with "domain is not
running" when the domain is running. However, when the domain is
not running, it reports "no job is active".

How to reproduce:

1)
% virsh start $domain
% virsh domjobabort $domain
error: Requested operation is not valid: domain is not running

2)
% virsh destroy $domain
% virsh domjobabort $domain
error: Requested operation is not valid: no job is active on the domain

3)
% virsh save $domain /tmp/$domain.save

Before above commands finished, try to abort job in another terminal

% virsh domabortjob $domain
error: Requested operation is not valid: domain is not running
2011-08-01 19:41:07 +08:00
Eric Blake
f0a5eaf35f save: let qemu driver manipulate save files
The goal here is that save-image-dumpxml fed back to
save-image-define should not change the save file; anywhere that
this is not the case is probably a bug in domain_conf.c.

* src/qemu/qemu_driver.c (qemuDomainSaveImageGetXMLDesc)
(qemuDomainSaveImageDefineXML): New functions.
(qemuDomainSaveImageOpen): Add parameter.
(qemuDomainRestoreFlags, qemuDomainObjRestore): Adjust clients.
2011-07-28 15:39:14 -06:00
Eric Blake
0ea479f8f6 save: support qemu modifying xml on domain save/restore
With this, it is possible to update the path to a disk backing
image on either the save or restore action, without having to
binary edit the XML embedded in the state file.

This also modifies virDomainSave to output a smaller xml (only
the inactive xml, which is all the more virDomainRestore parses),
while still guaranteeing padding for most typical abi-compatible
xml replacements, necessary so that the next patch for
virDomainSaveImageDefineXML will not cause unnecessary
modifications to the save image file.

* src/qemu/qemu_driver.c (qemuDomainSaveInternal): Add parameter,
only use inactive state, and guarantee padding.
(qemuDomainSaveImageOpen): Add parameter.
(qemuDomainSaveFlags, qemuDomainManagedSave)
(qemuDomainRestoreFlags, qemuDomainObjRestore): Update callers.
2011-07-28 15:31:08 -06:00
Michal Privoznik
09d7eba99d qemu: Fix memory leak on metadata fetching
As written in virStorageFileGetMetadataFromFD decription, caller
must free metadata after use. Qemu driver miss this and therefore
leak metadata which can grow to huge mem leak if somebody query
for blockInfo a lot.
2011-07-28 16:01:39 +02:00
Osier Yang
01e1ea1219 qemu: Improve docs for virsh dump format
The error in getCompressionType will never be reported, change
the errors codes into warning (VIR_WARN("%s", _(foo)); doesn't break
syntax-check rule), and also improve the docs in qemu.conf to tell
user the truth.
2011-07-28 09:37:52 +08:00
Jiri Denemark
f9a837da73 qemu: Remove special case for virDomainAbortJob
This doesn't abort migration job in any phase, yet.
2011-07-27 08:45:17 -06:00
Jiri Denemark
ad6cc26c8d qemu: Remove special case for virDomainSuspend 2011-07-27 08:45:17 -06:00
Jiri Denemark
63d15036cc qemu: Remove special case for virDomainMigrateSetMaxDowntime
Call qemu monitor command directly within a special job that is only
allowed during outgoing migration.
2011-07-27 08:45:16 -06:00
Jiri Denemark
d1bd3f57bc qemu: Remove special case for virDomainMigrateSetMaxSpeed
Call qemu monitor command directly within a special job that is only
allowed during outgoing migration.
2011-07-27 08:45:16 -06:00
Jiri Denemark
90feb02dd0 qemu: Remove special case for virDomainBlockStats
Like other query commands, this can now be called directly during
migration.
2011-07-27 08:45:16 -06:00
Jiri Denemark
fb3cada0a0 qemu: Remove special case for virDomainGetBlockInfo
Like other query commands, this can now be called directly during
migration.
2011-07-27 08:45:16 -06:00
Jiri Denemark
d58e91a812 qemu: Migration job on source daemon
Make MIGRATION_OUT use the new helper methods.

This also introduces new protection to migration v3 process: the
migration job is held from Begin to Confirm to avoid changes to a domain
during migration (esp. between Begin and Perform phases). This change is
automatically applied to p2p and tunneled migrations. For normal
migration, this requires support from a client. In other words, if an
old (pre 0.9.4) client starts normal migration of a domain, the domain
will not be protected against changes between Begin and Perform steps.
2011-07-27 08:45:10 -06:00
Wen Congyang
652e55b7a5 set cpu bandwidth for the vm
The cpu bandwidth is applied at the vcpu group level. We should apply it
at the vm group level too, because the vm may do heavy I/O, and it will affect
the other vm.

We apply cpu bandwidth at the vcpu and the vm group level, so we must ensure
that max(child_quota) <= parent_quota when we modify cpu bandwidth.
2011-07-26 22:12:57 +08:00
Eric Blake
59d042871c vcpu: teach getVcpusFlags about current
Now that virDomainSetVcpusFlags knows about VIR_DOMAIN_AFFECT_CURRENT,
so should virDomainGetVcpusFlags.

Unfortunately, the virsh counterpart 'virsh vcpucount' has already
commandeered --current for a different meaning, so teaching virsh
to expose this in the next patch will require a bit of care.

* src/libvirt.c (virDomainGetVcpusFlags): Allow
VIR_DOMAIN_AFFECT_CURRENT.
* src/libxl/libxl_driver.c (libxlDomainGetVcpusFlags): Likewise.
* src/qemu/qemu_driver.c (qemudDomainGetVcpusFlags): Likewise.
* src/test/test_driver.c (testDomainGetVcpusFlags): Likewise.
* src/xen/xen_driver.c (xenUnifiedDomainGetVcpusFlags): Likewise.
2011-07-25 15:45:10 -06:00
Wen Congyang
2a667c34cb rename cfs_* to vcpu_*
In the XML file we now have

  <cputune>
    <shares>1024</shares>
    <period>90000</period>
    <quota>0</quota>
  </cputune>

But the schedinfo parameter are being named

 cpu_shares: 1024
 cfs_period: 90000
 cfs_quota: 0

The period/quota is per-vcpu value, so these new tunables should be named
'vcpu_period' and 'vcpu_quota'.
2011-07-25 22:48:23 +08:00
Adam Litke
b976165ca4 Implement virDomainBlockPull for the qemu driver
The virDomainBlockPull* family of commands are enabled by the
following HMP/QMP commands: 'block_stream', 'block_job_cancel',
 'info block-jobs' / 'query-block-jobs', and 'block_job_set_speed'.

* src/qemu/qemu_driver.c src/qemu/qemu_monitor_text.[ch]: implement disk
  streaming by using the proper qemu monitor commands.
* src/qemu/qemu_monitor_json.[ch]: implement commands using the qmp monitor
2011-07-22 13:39:37 +08:00
Eric Blake
a9f9545e12 save: support bypass-cache flag in qemu.conf
When auto-dumping a domain on crash events, or autostarting a domain
with managed save state, let the user configure whether to imply
the bypass cache flag.

* src/qemu/qemu.conf (auto_dump_bypass_cache, auto_start_bypass_cache):
Document new variables.
* src/qemu/libvirtd_qemu.aug (vnc_entry): Let augeas parse them.
* src/qemu/qemu_conf.h (qemud_driver): Store new preferences.
* src/qemu/qemu_conf.c (qemudLoadDriverConfig): Parse them.
* src/qemu/qemu_driver.c (processWatchdogEvent, qemuAutostartDomain):
Honor them.
2011-07-21 16:24:09 -06:00
Eric Blake
58e668d2ea save: support BYPASS_CACHE during qemu save/restore
Wire together the previous patches to support file system cache
bypass during API save/restore requests in qemu.

* src/qemu/qemu_driver.c (qemuDomainSaveInternal, doCoreDump)
(qemudDomainObjStart, qemuDomainSaveImageOpen, qemuDomainObjRestore)
(qemuDomainObjStart): Add parameter.
(qemuDomainSaveFlags, qemuDomainManagedSave, qemudDomainCoreDump)
(processWatchdogEvent, qemudDomainStartWithFlags, qemuAutostartDomain)
(qemuDomainRestoreFlags): Update callers.
2011-07-21 16:24:08 -06:00
Eric Blake
b1083a4c53 save: wire up trivial save/restore flags implementations
For all hypervisors that support save and restore, the new API
now performs the same functions as the old.

VBox is excluded from this list, because its existing domainsave
is broken (there is no corresponding domainrestore, and there
is no control over the filename used in the save).  A later
patch should change vbox to use its implementation for
managedsave, and teach start to use managedsave results.

* src/libxl/libxl_driver.c (libxlDomainSave): Move guts...
(libxlDomainSaveFlags): ...to new function.
(libxlDomainRestore): Move guts...
(libxlDomainRestoreFlags): ...to new function.
* src/test/test_driver.c (testDomainSave, testDomainSaveFlags)
(testDomainRestore, testDomainRestoreFlags): Likewise.
* src/xen/xen_driver.c (xenUnifiedDomainSave)
(xenUnifiedDomainSaveFlags, xenUnifiedDomainRestore)
(xenUnifiedDomainRestoreFlags): Likewise.
* src/qemu/qemu_driver.c (qemudDomainSave, qemudDomainRestore):
Rename and move guts.
(qemuDomainSave, qemuDomainSaveFlags, qemuDomainRestore)
(qemuDomainRestoreFlags): ...here.
(qemudDomainSaveFlag): Rename...
(qemuDomainSaveInternal): ...to this, and update callers.
2011-07-21 16:24:05 -06:00
Laine Stump
e9949a586a qemu: use virDomainNetGetActual*() in qemuDomainXMLToNative
This is the one function outside of domain_conf.c that plays around
with (even modifying) the internals of the virDomainNetDef, and thus
can't be fixed up simply by replacing direct accesses to the fields of
the struct with the GetActual*() access functions.

In this case, we need to check if the defined type is "network", and
if it is *then* check the actual type; if the actual type is "bridge",
then we can at least put the bridgename in a place where it can be
used; otherwise (if type isn't "bridge"), we behave exactly as we used
to - just null out *everything*.
2011-07-21 14:47:11 -04:00
Michal Privoznik
427eaf13e2 destroy: Implement internal API for qemu driver 2011-07-21 20:41:27 +02:00
Eric Blake
8e22e08935 build: rename files.h to virfile.h
In preparation for a future patch adding new virFile APIs.

* src/util/files.h, src/util/files.c: Move...
* src/util/virfile.h, src/util/virfile.c: ...here, and rename
functions to virFile prefix.  Macro names are intentionally
left alone.
* *.c: All '#include "files.h"' uses changed.
* src/Makefile.am (UTIL_SOURCES): Reflect rename.
* cfg.mk (exclude_file_name_regexp--sc_prohibit_close): Likewise.
* src/libvirt_private.syms: Likewise.
* docs/hacking.html.in: Likewise.
* HACKING: Regenerate.
2011-07-21 10:34:51 -06:00
Daniel P. Berrange
5e7d638ca0 Fix uninitialized variable in QEMU CPU bandwidth code
* src/qemu/qemu_driver.c: Fix uninitialized variable
2011-07-21 13:28:08 +01:00
Wen Congyang
d6fa4967bc fix make syntax-check error 2011-07-21 17:42:44 +08:00
Wen Congyang
67a173c54f qemu: Implement cfs_period and cfs_quota's modification
This patch implements cfs_period and cfs_quota's modification.
We can use the command 'virsh schedinfo' to query or modify cfs_period and
cfs_quota.
If you query period or quota from config file, the value 0 means it does not set
in the config file.
If you set period or quota to config file, the value 0 means that delete current
setting from config file.
If you modify period or quota while vm is running, the value 0 means that use
current value.
2011-07-21 17:11:12 +08:00
Lai Jiangshan
e40725779c qemu: send-key: Implement the driver methods
qemu driver just accept xt_kbd codeset's keycode, so the lib virtkey
is used for translating keycodes from other codesets
2011-07-21 15:58:31 +08:00
Osier Yang
ae8e08aa28 undefine: Implement internal API for qemu driver
* src/qemu/qemu_driver.c: New call back for qemu_driver,
New function qemudDomainUndefineFlags, and changes on
qemudDomainUndefine.
2011-07-20 11:04:15 +08:00
Eric Blake
33ba6e6881 libvirt: do not mix internal flags into public API
There were two API in driver.c that were silently masking flags
bits prior to calling out to the drivers, and several others
that were explicitly masking flags bits.  This is not
forward-compatible - if we ever have that many flags in the
future, then talking to an old server that masks out the
flags would be indistinguishable from talking to a new server
that can honor the flag.  In general, libvirt.c should forward
_all_ flags on to drivers, and only the drivers should reject
unknown flags.

In the case of virDrvSecretGetValue, the solution is to separate
the internal driver callback function to have two parameters
instead of one, with only one parameter affected by the public
API.  In the case of virDomainGetXMLDesc, it turns out that
no one was ever mixing VIR_DOMAIN_XML_INTERNAL_STATUS with
the dumpxml path in the first place; that internal flag was
only used in saving and restoring state files, which happened
to be in functions internal to a single file, so there is no
mixing of the internal flag with a public flags argument.
Additionally, virDomainMemoryStats passed a flags argument
over RPC, but not to the driver.

* src/driver.h (VIR_DOMAIN_XML_FLAGS_MASK)
(VIR_SECRET_GET_VALUE_FLAGS_MASK): Delete.
(virDrvSecretGetValue): Separate out internal flags.
(virDrvDomainMemoryStats): Provide missing flags argument.
* src/driver.c (verify): Drop unused check.
* src/conf/domain_conf.h (virDomainObjParseFile): Delete
declaration.
(virDomainXMLInternalFlags): Move...
* src/conf/domain_conf.c: ...here.  Delete redundant include.
(virDomainObjParseFile): Make static.
* src/libvirt.c (virDomainGetXMLDesc, virSecretGetValue): Update
clients.
(virDomainMemoryPeek, virInterfaceGetXMLDesc)
(virDomainMemoryStats, virDomainBlockPeek, virNetworkGetXMLDesc)
(virStoragePoolGetXMLDesc, virStorageVolGetXMLDesc)
(virNodeNumOfDevices, virNodeListDevices, virNWFilterGetXMLDesc):
Don't mask unknown flags.
* src/interface/netcf_driver.c (interfaceGetXMLDesc): Reject
unknown flags.
* src/secret/secret_driver.c (secretGetValue): Update clients.
* src/remote/remote_driver.c (remoteSecretGetValue)
(remoteDomainMemoryStats): Likewise.
* src/qemu/qemu_process.c (qemuProcessGetVolumeQcowPassphrase):
Likewise.
* src/qemu/qemu_driver.c (qemudDomainMemoryStats): Likewise.
* daemon/remote.c (remoteDispatchDomainMemoryStats): Likewise.
2011-07-18 13:50:51 -06:00
Osier Yang
fab4f0c699 qemu: Fix a regression of attaching device
The regression is introduced by Commit da1eba6b, the new
codes with this commit doesn't reset "ret" to "-1" when
it fails on parsing the device XML (live device attachment)

This patch changes the codes to reset the "ret" and "-1",
and also changes the codes so that it don't modify "ret"
for condition checking.

How to reproduce:

% cat test.xml
<disk type='oops' device='disk'>
  <driver name='qemu' type='raw'/>
  <source file='/var/lib/libvirt/images/test.img'/>
  <target dev='vda' bus='virtio'/>
</disk>

% virsh attach-device $domain test.xml
Device attached successfully

The device attachment failed actually with error "unknown disk type 'oops'",
however, it reports success.
2011-07-16 11:27:34 +08:00
Eric Blake
8d733f4ef1 flags: fix qemu migration regression
Commit f548480b broke migration v3 on qemu, because the driver
passed flags on through to qemu_migration even though
qemu_migration wasn't using those flags.

* src/qemu/qemu_migration.h (QEMU_MIGRATION_FLAGS): New define.
* src/qemu/qemu_driver.c: Simplify all migration callbacks.
* src/qemu/qemu_migration.c (qemuMigrationConfirm): Fix regression.
2011-07-15 12:34:00 -06:00
Eric Blake
461e0f1a2d flags: use common dumpxml flags check
The previous patches only cleaned up ATTRIBUTE_UNUSED flags cases;
auditing the drivers found other places where flags was being used
but not validated.  In particular, domainGetXMLDesc had issues with
clients accepting a different set of flags than the common
virDomainDefFormat helper function.

* src/conf/domain_conf.c (virDomainDefFormat): Add common flag check.
* src/uml/uml_driver.c (umlDomainAttachDeviceFlags)
(umlDomainDetachDeviceFlags): Reject unknown
flags.
* src/vbox/vbox_tmpl.c (vboxDomainGetXMLDesc)
(vboxDomainAttachDeviceFlags)
(vboxDomainDetachDeviceFlags): Likewise.
* src/qemu/qemu_driver.c (qemudDomainMemoryPeek): Likewise.
(qemuDomainGetXMLDesc): Document common flag handling.
* src/libxl/libxl_driver.c (libxlDomainGetXMLDesc): Likewise.
* src/lxc/lxc_driver.c (lxcDomainGetXMLDesc): Likewise.
* src/openvz/openvz_driver.c (openvzDomainGetXMLDesc): Likewise.
* src/phyp/phyp_driver.c (phypDomainGetXMLDesc): Likewise.
* src/test/test_driver.c (testDomainGetXMLDesc): Likewise.
* src/vmware/vmware_driver.c (vmwareDomainGetXMLDesc): Likewise.
* src/xenapi/xenapi_driver.c (xenapiDomainGetXMLDesc): Likewise.
2011-07-15 12:22:20 -06:00
Taku Izumi
c147b93739 setvcpus: extend qemuDomainSetVcpusFlags() to support current flag
This patch extends qemudDomainSetVcpusFlags() function to support
VIR_DOMAIN_AFFECT_CURRENT flag.

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-07-15 08:19:24 -06:00
Eric Blake
f548480b7f qemu: reject unknown flags
* src/qemu/qemu_driver.c (qemudOpen, qemuDomainScreenshot)
(qemuDomainXMLFromNative, qemuDomainXMLToNative)
(qemudDomainBlockPeek, qemuCPUCompare, qemuCPUBaseline): Reject
unknown flags.
* src/qemu/qemu_migration.c (qemuMigrationConfirm): Likewise.
(_qemuMigrationCookie, qemuMigrationCookieXMLParse)
(qemuMigrationCookieXMLParseStr, qemuMigrationBakeCookie)
(qemuMigrationEatCookie): Make flags unsigned.
* src/qemu/qemu_domain.h: (qemuDomainDefFormatXML)
(qemuDomainFormatXML): Prefer unsigned flags.
* src/qemu/qemu_domain.c (qemuDomainDefFormatXML)
(qemuDomainFormatXML): Likewise.
(qemuDomainOpenLogHelper, qemuDomainCreateLog): Rename variable.
2011-07-13 14:44:09 -06:00
Peter Krempa
36caaddde6 qemu: build failed due to unused variables
While compiling on F15 build crashed (probably because of new GCC).
2011-07-13 11:22:28 -06:00
Jiri Denemark
ff340a84b8 qemu: Save job type in domain status XML
If libvirtd is restarted when a job is running, the new libvirtd process
needs to know about that to be able to recover and rollback the
operation.
2011-07-13 01:53:32 +02:00
Jiri Denemark
361842881e qemu: Allow all query commands to be run during long jobs
Query commands are safe to be called during long running jobs (such as
migration). This patch makes them all work without the need to
special-case every single one of them.

The patch introduces new job.asyncCond condition and associated
job.asyncJob which are dedicated to asynchronous (from qemu monitor
point of view) jobs that can take arbitrarily long time to finish while
qemu monitor is still usable for other commands.

The existing job.active (and job.cond condition) is used all other
synchronous jobs (including the commands run during async job).

Locking schema is changed to use these two conditions. While asyncJob is
active, only allowed set of synchronous jobs is allowed (the set can be
different according to a particular asyncJob) so any method that
communicates to qemu monitor needs to check if it is allowed to be
executed during current asyncJob (if any). Once the check passes, the
method needs to normally acquire job.cond to ensure no other command is
running. Since domain object lock is released during that time, asyncJob
could have been started in the meantime so the method needs to recheck
the first condition. Then, normal jobs set job.active and asynchronous
jobs set job.asyncJob and optionally change the list of allowed job
groups.

Since asynchronous jobs only set job.asyncJob, other allowed commands
can still be run when domain object is unlocked (when communicating to
remote libvirtd or sleeping). To protect its own internal synchronous
commands, the asynchronous job needs to start a special nested job
before entering qemu monitor. The nested job doesn't check asyncJob, it
only acquires job.cond and sets job.active to block other jobs.
2011-07-13 01:53:21 +02:00
Jiri Denemark
90a422f071 qemu: Separate job related data into a new object 2011-07-12 21:17:28 +02:00
Daniel P. Berrange
b43070ebfc Move qemu_audit.h helpers into shared code
The LXC and UML drivers can both make use of auditing. Move
the qemu_audit.{c,h} files to src/conf/domain_audit.{c,h}

* src/conf/domain_audit.c: Rename from src/qemu/qemu_audit.c
* src/conf/domain_audit.h: Rename from src/qemu/qemu_audit.h
* src/Makefile.am: Remove qemu_audit.{c,h}, add domain_audit.{c,h}
* src/qemu/qemu_audit.h, src/qemu/qemu_cgroup.c,
  src/qemu/qemu_command.c, src/qemu/qemu_driver.c,
  src/qemu/qemu_hotplug.c, src/qemu/qemu_migration.c,
  src/qemu/qemu_process.c: Update for changed audit API names
2011-07-12 17:05:25 +01:00
Daniel P. Berrange
109efd7941 Implement code to attach to external QEMU instances.
Given a PID, the QEMU driver reads /proc/$PID/cmdline and
/proc/$PID/environ to get the configuration. This is fed
into the ARGV->XML convertor to build an XML configuration
for the process.

/proc/$PID/exe is resolved to identify the full command
binary path

After checking for name/uuid uniqueness, an attempt is
made to connect to the monitor socket. If successful
then 'info status' and 'info kvm' are issued to determine
whether the CPUs are running and if KVM is enabled.

* src/qemu/qemu_driver.c: Implement virDomainQemuAttach
* src/qemu/qemu_process.h, src/qemu/qemu_process.c: Add
  qemuProcessAttach to connect to the monitor of an
  existing QEMU process
2011-07-12 15:39:04 +01:00
Daniel P. Berrange
ebbae359ff Change extract pidfile & monitor config from QEMU command line
When converting QEMU argv into a virDomainDefPtr, also extract
the pidfile, monitor character device config and the monitor
mode.

* src/qemu/qemu_command.c, src/qemu/qemu_command.h: Extract
  pidfile & monitor config from QEMU argv
* src/qemu/qemu_driver.c, tests/qemuargv2xmltest.c: Add extra
  params when calling qemuParseCommandLineString
2011-07-12 15:39:04 +01:00
Eric Blake
f532bfa297 qemu: avoid fd leak on core dump failure
* src/qemu/qemu_driver.c (doCoreDump): Guarantee fd is closed.
2011-07-12 07:24:43 -06:00
Matthias Bolte
aa14709a47 Add domain type checking
The drivers were accepting domain configs without checking if those
were actually meant for them. For example the LXC driver happily
accepts configs with type QEMU.

Add a check for the expected domain types to the virDomainDefParse*
functions.
2011-07-11 19:38:51 +02:00
Michal Privoznik
724819a10a qemu: Don't chown files on NFS share if dynamic_ownership is off
When dynamic ownership is disabled we don't want to chown any files,
not just local.
2011-07-08 10:05:59 +02:00
Eric Blake
1740c38116 drivers: prefer unsigned int for flags
Now that the public APIs always use unsigned flags, the internal
driver callbacks might as well do likewise.

* src/driver.h (vrDrvOpen, virDrvDomainCoreDump)
(virDrvDomainGetXMLDesc, virDrvNetworkGetXMLDesc)
(virDrvNWFilterGetXMLDesc): Update type.
* src/remote/remote_protocol.x (remote_open_args)
(remote_domain_core_dump_args, remote_domain_get_xml_desc_args)
(remote_network_get_xml_desc_args)
(remote_nwfilter_get_xml_desc_args): Likewise.
* src/test/test_driver.c: Update clients.
* src/remote/remote_driver.c: Likewise.
* src/xen/xen_hypervisor.c: Likewise.
* src/xen/xen_hypervisor.h: Likewise.
* src/xen/xen_driver.c: Likewise.
* src/xen/xend_internal.c: Likewise.
* src/xen/xend_internal.h: Likewise.
* src/xen/xm_internal.c: Likewise.
* src/xen/xm_internal.h: Likewise.
* src/xen/xs_internal.c: Likewise.
* src/xen/xs_internal.h: Likewise.
* src/xen/xen_inotify.c: Likewise.
* src/xen/xen_inotify.h: Likewise.
* src/phyp/phyp_driver.c: Likewise.
* src/openvz/openvz_driver.c: Likewise.
* src/vmware/vmware_driver.c: Likewise.
* src/vbox/vbox_driver.c: Likewise.
* src/vbox/vbox_tmpl.c: Likewise.
* src/xenapi/xenapi_driver.c: Likewise.
* src/esx/esx_driver.c: Likewise.
* src/esx/esx_interface_driver.c: Likewise.
* src/esx/esx_network_driver.c: Likewise.
* src/esx/esx_storage_driver.c: Likewise.
* src/esx/esx_device_monitor.c: Likewise.
* src/esx/esx_secret_driver.c: Likewise.
* src/esx/esx_nwfilter_driver.c: Likewise.
* src/interface/netcf_driver.c: Likewise.
* src/nwfilter/nwfilter_driver.c: Likewise.
* src/libxl/libxl_driver.c: Likewise.
* src/qemu/qemu_driver.c: Likewise.
* src/lxc/lxc_driver.c: Likewise.
* src/uml/uml_driver.c: Likewise.
* src/network/bridge_driver.c: Likewise.
* src/secret/secret_driver.c: Likewise.
* src/storage/storage_driver.c: Likewise.
* src/node_device/node_device_hal.c: Likewise.
* src/node_device/node_device_udev.c: Likewise.
* src/remote_protocol-structs: Likewise.
2011-07-07 14:15:37 -06:00
Matthias Bolte
e123e1ee6b Fix return value semantic of virFileMakePath
Some callers expected virFileMakePath to set errno, some expected
it to return an errno value. Unify this to return 0 on success and
-1 on error. Set errno to report detailed error information.

Also optimize virFileMakePath if stat fails with an errno different
from ENOENT.
2011-07-06 09:27:06 +02:00
Guannan Ren
416814e66a pci: initialize state values on reattach
add a new API pciDeviceReAttachInit() in pci.c to initialize state values for nodedev reattach

Initialize three state value of device driver to 1. This is just for a new call to
qemudNodeDeviceReAttach()
2011-07-05 11:42:38 -06:00
Laine Stump
834ce603f9 qemu: check flags in qemuDomainGetXMLDesc
Although most functions with flags check to verify no application is
passing in flag bits that are currently undefined, for some reason
this function wasn't.
2011-07-05 12:33:21 -04:00
Matthias Bolte
4a03db81cd qemu: Fix virFileMakePath error handling in snapshot creation
virFileMakePath returns an errno value on error, that will never
be negative. An virFileMakePath error would have been ignored here,
instead of being reported correctly.
2011-07-05 10:49:36 +02:00
Daniel P. Berrange
e44bec2e34 Fix potential crash when saving guests
The qemudDomainSaveFlag method will call EndJob on the 'vm'
object it is passed in. This can result in the 'vm' object
being free'd if the last reference is removed. Thus no caller
of 'qemudDomainSaveFlag' must *ever* reference 'vm' again
upon return.

Unfortunately qemudDomainSave and qemuDomainManagedSave
both call 'virDomainObjUnlock', which can result in a
crash. This is non-deterministic since it involves a race
with the monitor I/O thread.

Fix this by making qemudDomainSaveFlag responsible for
calling virDomainObjUnlock instead.

* src/qemu/qemu_driver.c: Fix potential use after free
  when saving guests
2011-06-30 18:04:02 +01:00
Wen Congyang
cd13dbb147 lock qemu_driver early in qemuGetSchedulerParametersFlags()
If we pass VIR_DOMAIN_AFFECT_LIVE | VIR_DOMAIN_AFFECT_CONFIG to
qemuGetSchedulerParametersFlags() or *nparams is less than 1,
we will unlock qemu_driver without locking it. It's very dangerous.

We should lock qemu_driver after calling virCheckFlags().
2011-06-30 13:27:00 +08:00
Wen Congyang
fb2a2e2611 save domain status after modifing vcpupin
We should save domain status after modifing vcpupin. If not,
we will get wrong vcpupin information after rebooting libvirtd.
2011-06-30 13:26:56 +08:00
Michal Privoznik
c72aecc5fc screenshot: Set access rights to temporary file
Although we create a temporary file, it is owned by root:root and have
rights 0600. In case qemu does not run under root, it is unable to write
to that file and thus we transfer 0B sized file.
2011-06-29 12:05:34 +02:00
Jiri Denemark
ad7b327690 qemu: Fix update device for CURRENT + FORCE flags
When CURRENT and FORCE flags were used together, UpdateDeviceFlags did
nothing because it failed to transform CURRENT into either LIVE or
CONFIG.
2011-06-28 14:21:50 +02:00
Eric Blake
28e45afc3f build: rename Vcpupin to VcpuPin
We already have a public virDomainPinVcpu, which implies that
Pin and Vcpu are treated as separate words.  Unreleased commit
e261987c introduced virDomainGetVcpupinInfo as the first public
API that used Vcpupin, although we had prior internal uses of
that spelling.  For consistency, change the spelling to be two
words everywhere, regardless of whether pin comes first or last.

* daemon/remote.c: Treat vcpu and pin as separate words.
* include/libvirt/libvirt.h.in: Likewise.
* src/conf/domain_conf.c: Likewise.
* src/conf/domain_conf.h: Likewise.
* src/driver.h: Likewise.
* src/libvirt.c: Likewise.
* src/libvirt_private.syms: Likewise.
* src/libvirt_public.syms: Likewise.
* src/libxl/libxl_driver.c: Likewise.
* src/qemu/qemu_driver.c: Likewise.
* src/remote/remote_driver.c: Likewise.
* src/xen/xend_internal.c: Likewise.
* tools/virsh.c: Likewise.
* src/remote/remote_protocol.x: Likewise.
* src/remote_protocol-structs: Likewise.
Suggested by Matthias Bolte.
2011-06-27 09:55:11 -06:00
Eric Blake
2bebf93846 build: avoid uninitialized variable
Caught by gcc -O2, during autobuild.sh.

* src/qemu/qemu_driver.c (qemudDomainGetVcpupinInfo): Initialize vm.
2011-06-24 20:55:32 -06:00
Taku Izumi
96414c4ed1 vcpupin: implement the code to support new API for the qemu driver
This patch implements the code to address the new API (virDomainGetVcpupinInfo)
in the qemu driver.

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-06-24 17:00:22 -06:00
Eric Blake
3c2f0a17e2 Revert "Implement virDomainBlockPull for the qemu driver"
This reverts commit 784ee08d22.
2011-06-24 08:41:25 -06:00
Daniel P. Berrange
3ba937da42 Allow automatic kill of guests when a connection is closed
If an application is using libvirt + KVM as a piece of its
internal infrastructure to perform a specific task, it can
be desirable to guarentee the VM dies when the virConnectPtr
disconnects from libvirtd. This ensures the app can't leak
any VMs it was using. Adding VIR_DOMAIN_START_AUTOKILL as
a flag when starting guests enables this to be done.

* include/libvirt/libvirt.h.in: All VIR_DOMAIN_START_AUTOKILL
* src/qemu/qemu_driver.c: Support automatic killing of guests
  upon connection close
* tools/virsh.c: Add --autokill flag to 'start' and 'create'
  commands
2011-06-24 12:15:10 +01:00
Daniel P. Berrange
558b7fd03d Add infrastructure to automatically destroy guests when a connection closes
Sometimes it is useful to be able to automatically destroy a guest when
a connection is closed. For example, kill an incoming migration if
the client managing the migration dies. This introduces a map between
guest 'uuid' strings and virConnectPtr objects. When a connection is
closed, any associated guests are killed off.

* src/qemu/qemu_conf.h: Add autokill hash table to qemu driver
* src/qemu/qemu_process.c, src/qemu/qemu_process.h: Add APIs
  for performing autokill of guests associated with a connection
* src/qemu/qemu_driver.c: Initialize autodestroy map
2011-06-24 12:15:10 +01:00
Daniel P. Berrange
42f43592be Support reboots with the QEMU driver
For controlled shutdown we issue a 'system_powerdown' command
to the QEMU monitor. This triggers an ACPI event which (most)
guest OS wire up to a controlled shutdown. There is no equiv
ACPI event to trigger a controlled reboot. This patch attempts
to fake a reboot.

 - In qemuDomainObjPrivatePtr we have a bool fakeReboot
   flag.
 - The virDomainReboot method sets this flag and then
   triggers a normal 'system_powerdown'.
 - The QEMU process is started with '-no-shutdown'
   so that the guest CPUs pause when it powers off the
   guest
 - When we receive the 'POWEROFF' event from QEMU JSON
   monitor if fakeReboot is not set we invoke the
   qemuProcessKill command and shutdown continues
   normally
 - If fakeReboot was set, we spawn a background thread
   which issues 'system_reset' to perform a warm reboot
   of the guest hardware. Then it issues 'cont' to
   start the CPUs again

* src/qemu/qemu_command.c: Add -no-shutdown flag if
  we have JSON support
* src/qemu/qemu_domain.h: Add 'fakeReboot' flag to
  qemuDomainObjPrivate struct
* src/qemu/qemu_driver.c: Fake reboot using the
  system_powerdown command if JSON support is available
* src/qemu/qemu_monitor.c, src/qemu/qemu_monitor.h,
  src/qemu/qemu_monitor_json.c, src/qemu/qemu_monitor_json.h,
  src/qemu/qemu_monitor_text.c, src/qemu/qemu_monitor_text.h: Add
  binding for system_reset command
* src/qemu/qemu_process.c: Reset the guest & start CPUs if
  fakeReboot is set
2011-06-24 12:13:47 +01:00
Eric Blake
ab228c81f2 build: avoid compiler failure
GCC complained about a C99 for-loop declaration outside of C99 mode
when compiling on RHEL 5.

* src/qemu/qemu_driver.c (qemudDomainPinVcpuFlags): Avoid C99 for
loop, since gcc 4.1.2 hates it.
2011-06-23 21:57:58 -06:00
Cole Robinson
6094ad7bd7 Promote virEvent*Handle/Timeout to public API
Since we virEventRegisterDefaultImpl is now a public API, callers need
a way to invoke the default registered Handle and Timeout functions. We
already have general functions for these internally, so promote
them to the public API.

v2:
    Actually add APIs to libvirt.h
2011-06-21 10:08:47 -04:00
Taku Izumi
7ea9778c8a vcpupin: add vcpupin resetting feature to qemu driver
Pinning to all physical cpus means resetting, hence it is preferable to
delete vcpupin setting of XML.

This patch changes qemu driver to delete vcpupin setting by invoking
virDomainVcpupinDel API when pinning the specified virtual cpu to
all host physical cpus.

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-06-20 18:14:54 +08:00
Hu Tao
8485e5a256 Update qemuDomainSetBlkioParameters to use flags 2011-06-20 15:52:11 +08:00
Hu Tao
100c39ca03 update qemuDomainGetBlkioParameters to use flags 2011-06-20 15:52:11 +08:00
Jiri Denemark
559fcf8a24 qemu: Implement virDomainGetControlInfo 2011-06-16 18:47:12 +02:00
Adam Litke
784ee08d22 Implement virDomainBlockPull for the qemu driver
The virDomainBlockPull* family of commands are enabled by the
'block_stream' and 'info block_stream' qemu monitor commands.

* src/qemu/qemu_driver.c src/qemu/qemu_monitor_text.[ch]: implement disk
  streaming by using the stream and info stream text monitor commands
* src/qemu/qemu_monitor_json.[ch]: implement commands using the qmp monitor

Signed-off-by: Adam Litke <agl@us.ibm.com>
Acked-by: Daniel P. Berrange <berrange@redhat.com>
2011-06-14 22:02:06 -06:00
Minoru Usui
af35cece3b virNodeGetMemoryStats: Implement linux support
Signed-off-by: Minoru Usui <usui@mxm.nes.nec.co.jp>
2011-06-14 16:54:01 -06:00
Minoru Usui
ce76e85350 virNodeGetCPUStats: Implement linux support
Signed-off-by: Minoru Usui <usui@mxm.nes.nec.co.jp>
2011-06-14 15:57:26 -06:00
Hu Tao
fbd7820b2c Deprecate several CURRENT/LIVE/CONFIG enums
This patch deprecates following enums:

VIR_DOMAIN_MEM_CURRENT
VIR_DOMAIN_MEM_LIVE
VIR_DOMAIN_MEM_CONFIG

VIR_DOMAIN_VCPU_LIVE
VIR_DOMAIN_VCPU_CONFIG

VIR_DOMAIN_DEVICE_MODIFY_CURRENT
VIR_DOMAIN_DEVICE_MODIFY_LIVE
VIR_DOMAIN_DEVICE_MODIFY_CONFIG

And modify internal codes to use virDomainModificationImpact.
2011-06-13 14:17:16 -06:00
Taku Izumi
6690150ddd vcpupin: implement the code to address the new API in the qemu driver
This patch implements the new API (virDomainPinVcpuFlags) in the qemu
driver.
2011-06-13 23:42:09 +08:00
Jiri Denemark
a231016b69 Use virTimeMs when appropriate 2011-06-13 11:24:58 +02:00
Cole Robinson
1ba75cf9aa qemu: Convert virExec usage to virCommand
v2:
    Have virCommand cleanup intermediate process for us

v3:
    Preserve original FD closing behavior

Signed-off-by: Cole Robinson <crobinso@redhat.com>
2011-06-07 11:11:02 -04:00
Eric Blake
33d90bafe7 API: consolidate common unreleased enums
This commit is safe precisely because there has been no release
for any of the enum values being deleted (they were added post-0.9.1).

After the 0.9.2 release, we can then take advantage of
virDomainModificationImpact in more places.

* include/libvirt/libvirt.h.in (virDomainModificationImpact): New
enum.
(virDomainSchedParameterFlags, virMemoryParamFlags): Delete, since
these were never released, and the new enum works fine here.
* src/libvirt.c	(virDomainGetMemoryParameters)
(virDomainSetMemoryParameters)
(virDomainGetSchedulerParametersFlags)
(virDomainSetSchedulerParametersFlags): Update documentation.
* src/qemu/qemu_driver.c (qemuDomainSetMemoryParameters)
(qemuDomainGetMemoryParameters, qemuSetSchedulerParametersFlags)
(qemuSetSchedulerParameters, qemuGetSchedulerParametersFlags)
(qemuGetSchedulerParameters): Adjust clients.
* tools/virsh.c (cmdSchedinfo, cmdMemtune): Likewise.
Based on ideas by Daniel Veillard and Hu Tao.
2011-06-04 09:58:53 +02:00
Daniel P. Berrange
2027e184c5 Fix regressions BlockStats/Info APIs in QEMU driver
The change 18c2a59206 caused
some regressions in behaviour of virDomainBlockStats
and virDomainBlockInfo in the QEMU driver.

The virDomainBlockInfo API stopped working for inactive
guests if querying a block device.

The virDomainBlockStats API did not promptly report
an error if the guest was not running in some cases.

* src/qemu/qemu_driver.c: Fix inactive guest handling
  in BlockStats/Info APIs
2011-06-03 14:55:11 +01:00
Daniel P. Berrange
30ffe7bceb Allow leases to be hotpluged with QEMU guests
* src/conf/domain_conf.c, src/conf/domain_conf.h: APIs for
  inserting/finding/removing virDomainLeaseDefPtr instances
* src/qemu/qemu_driver.c: Wire up hotplug/unplug for leases
* src/qemu/qemu_hotplug.h, src/qemu/qemu_hotplug.c: Support
  for hotplug and unplug of leases
2011-06-02 10:54:01 +01:00
Daniel P. Berrange
7474560bef Support passing QEMU lock state to dest during migration
Some lock managers associate state with leases, allowing a process
to temporarily release its leases, and re-acquire them later, safe
in the knowledge that no other process has acquired + released the
leases in between.

This is already used between suspend/resume operations, and must
also be used across migration. This passes the lockstate in the
migration cookie. If the lock manager uses lockstate, then it
becomes compulsory to use the migration v3 protocol to get the
cookie support.

* src/qemu/qemu_driver.c: Validate that migration v2 protocol is
  not used if lock manager needs state transfer
* src/qemu/qemu_migration.c: Transfer lock state in migration
  cookie XML
2011-06-02 10:54:01 +01:00
Daniel P. Berrange
12317957ec Integrate the QEMU driver with the lock manager infrastructure
The QEMU integrates with the lock manager instructure in a number
of key places

 * During startup, a lock is acquired in between the fork & exec
 * During startup, the libvirtd process acquires a lock before
   setting file labelling
 * During shutdown, the libvirtd process acquires a lock
   before restoring file labelling
 * During hotplug, unplug & media change the libvirtd process
   holds a lock while setting/restoring labels

The main content lock is only ever held by the QEMU child process,
or libvirtd during VM shutdown. The rest of the operations only
require libvirtd to hold the metadata locks, relying on the active
QEMU still holding the content lock.

* src/qemu/qemu_conf.c, src/qemu/qemu_conf.h,
  src/qemu/libvirtd_qemu.aug, src/qemu/test_libvirtd_qemu.aug:
  Add config parameter for configuring lock managers
* src/qemu/qemu_driver.c: Add calls to the lock manager
2011-06-02 10:54:01 +01:00
Eric Blake
8432170f6f qemu: introduce qemuGetSchedulerParametersFlags
* src/qemu/qemu_driver.c (qemuGetSchedulerParameters): Move
guts...
(qemuGetSchedulerParametersFlags): ...to new callback, and honor
flags more accurately.
2011-05-29 18:40:06 +08:00
Eric Blake
163e5f04ef maint: prefer newer API names internally
Rather mechanical in nature.

* src/driver.h: Use newer virTypedParameter API names.
* src/libvirt.c: Likewise.
* daemon/remote.c: Likewise.
* src/esx/esx_driver.c: Likewise.
* src/libxl/libxl_driver.c: Likewise.
* src/lxc/lxc_driver.c: Likewise.
* src/qemu/qemu_driver.c: Likewise.
* src/remote/remote_driver.c: Likewise.
* src/test/test_driver.c: Likewise.
* src/xen/xen_driver.c: Likewise.
* src/xen/xen_hypervisor.c: Likewise.
* src/xen/xen_hypervisor.h: Likewise.
* src/xen/xend_internal.c: Likewise.
* tools/virsh.c: Likewise.
2011-05-29 18:26:31 +08:00
Hu Tao
4b997daaf5 qemu: implement the new flags for setting memory parameters
* src/qemu/qemu_driver.c: update qemuDomainSetMemoryParameters to
  look at the flag parameter and depending on it save the config
  or the live amount
2011-05-27 15:49:07 +08:00
Hu Tao
7639d1ef31 qemu: implement the new flags for getting memory parameters
* src/qemu/qemu_driver.c: update qemuDomainGetMemoryParameters to
  look at the flag parameter and depending on it read the config
  or the live amount
2011-05-27 15:48:55 +08:00
KAMEZAWA Hiroyuki
9c26d6f09e qemu : support persistent add/delete network interface
This patch allows to modify interfaces of domain(qemu)
* src/conf/domain_conf.c src/conf/domain_conf.h src/libvirt_private.syms:
  (virDomainNetInsert)     : Insert a network device to domain definition.
  (virDomainNetIndexByMac) : Returns an index of net device in array.
  (virDomainNetRemoveByMac): Remove a NIC of passed MAC address.
* src/qemu/qemu_driver.c
  (qemuDomainAttachDeviceConfig): add codes for NIC.
  (qemuDomainDetachDeviceConfig): add codes for NIC.
2011-05-27 15:01:47 +08:00
Federico Simoncelli
18c2a59206 qemu: allow blkstat/blkinfo calls during migration
Originally most of libvirt domain-specific calls were blocking
during a migration.
A new mechanism to allow specific calls (blkstat/blkinfo) to be
executed in such condition has been implemented.
In the long term it'd be desirable to get a more general
solution to mark further APIs as migration safe, without needing
special case code.

 * src/qemu/qemu_migration.c: add some additional job signal
   flags for doing blkstat/blkinfo during a migration
 * src/qemu/qemu_domain.c: add a condition variable that can be
   used to efficiently wait for the migration code to clear the
   signal flag
 * src/qemu/qemu_driver.c: execute blkstat/blkinfo using the
   job signal flags during migration
2011-05-26 11:05:04 -06:00
Markus Groß
23e5393c40 Fix modifying disk devices in qemu driver
When modifying the disk devices of a live domain and the domain
configuration, the function qemuDomainAttachDeviceConfig
first sets dev->data->disk to NULL. Later qemuDomainAttachDeviceLive
accesses dev->data.disk and causes a segfault.
* src/qemu/qemu_driver.c: fix qemuDomainModifyDeviceFlags() accordingly
2011-05-26 22:32:51 +08:00
Daniel P. Berrange
2593f9692d Fix the signature of virDomainMigrateFinish3 for error reporting
The current virDomainMigrateFinish3 method signature attempts to
distinguish two types of errors, by allowing return with ret== 0,
but ddomain == NULL, to indicate a failure to start the guest.
This is flawed, because when ret == 0, there is no way for the
virErrorPtr details to be sent back to the client.

Change the signature of virDomainMigrateFinish3 so it simply
returns a virDomainPtr, in the same way as virDomainMigrateFinish2
The disk locking code will protect against the only possible
failure mode this doesn't account for (loosing conenctivity to
libvirtd after Finish3 starts the CPUs, but before the client
sees the reply for Finish3).

* src/driver.h, src/libvirt.c, src/libvirt_internal.h: Change
  virDomainMigrateFinish3 to return a virDomainPtr instead of int
* src/remote/remote_driver.c, src/remote/remote_protocol.x,
  daemon/remote.c, src/qemu/qemu_driver.c, src/qemu/qemu_migration.c:
  Update for API change
2011-05-25 11:47:48 -04:00
Daniel P. Berrange
5e31df9335 Fix preservation of errors across migration steps
When doing migration, if an error occurs in Perform, it must not
be overwritten during Finish/Confirm steps. If an error occurs
in Finish, it must not be overwritten in Confirm.

Previous commit a9d12c2444 added
code to qemudDomainMigrateFinish2 to preserve the error. This
is not the right place, because it is not applicable in non-p2p
migration. The src/libvirt.c virDomainMigrateV2/3 methods need
code to preserve errors for non-p2p migration, while the
doPeer2PeerMigrate2 and doPeer2PeerMigrate3 methods contain
code to preverse errors for p2p migration.

Remove the bogus error preservation from qemudDomainMigrateFinish2
and qemudDomainMigrateFinish3.

Fix virDomainMigrateV3 and doPeer2PeerMigrate3 so that they
preserve any error hit during the Finish3 step, before invoking
Confirm3.

Finally if qemuMigrationFinish fails to resume the CPUs, it must
preserve the error before tearing down the VM, so that VM cleanup
doesn't overwrite it.

* src/libvirt.c: Preserve error before invoking Confirm3
* src/qemu/qemu_driver.c: Remove bogus error preservation
  code in qemudDomainMigrateFinish2/qemudDomainMigrateFinish3
* src/qemu/qemu_migration.c: Preserve error before invoking Confirm3
  and after resume fails in qemuMigrationFinish.
2011-05-25 11:47:48 -04:00
Daniel P. Berrange
1853bd9d6e Fix error propagation in finish method for v3 migration
Even when failing to start CPUs, the finish method was returning
a success result. Fix this so that the QEMU process is killed
off when finish fails under v3 protocol. Also rename the
killOnFinish boolean to 'v3proto' to make it clearer that this
is a tunable based on the migration protocol version

* src/qemu/qemu_driver.c: Update for API change
* src/qemu/qemu_migration.c, src/qemu/qemu_migration.h: Kill
  VM in qemuMigrationFinish if failing to start CPUs
2011-05-25 11:47:48 -04:00
Daniel P. Berrange
f9f2d4e147 Add a second URI parameter to virDomainMigratePerform3 method
The virDomainMigratePerform3 currently has a single URI parameter
whose meaning varies. It is either

 - A QEMU migration URI (normal migration)
 - A libvirtd connection URI (peer2peer migration)

Unfortunately when using peer2peer migration, without also
using tunnelled migration, it is possible that both URIs are
required.

This adds a second URI parameter to the virDomainMigratePerform3
method, to cope with this scenario. Each parameter how has a fixed
meaning.

NB, there is no way to actually take advantage of this yet,
since virDomainMigrate/virDomainMigrateToURI do not have any
way to provide the 2 separate URIs

* daemon/remote.c, src/remote/remote_driver.c,
  src/remote/remote_protocol.x, src/remote_protocol-structs: Add
  the second URI parameter to perform3 message
* src/driver.h, src/libvirt.c, src/libvirt_internal.h: Add
  the second URI parameter to Perform3 method
* src/libvirt_internal.h, src/qemu/qemu_migration.c,
  src/qemu/qemu_migration.h: Update to handle URIs correctly
2011-05-25 11:47:48 -04:00
Daniel P. Berrange
7ad4b6b9cc Extend v3 migration protocol to allow app supplied XML for target
This extends the v3 migration protocol such that the
virDomainMigrateBegin3 and virDomainMigratePerform3
methods accept an application supplied XML config for
the target VM.

If the 'xmlin' parameter is NULL, then Begin3 uses the
current guest XML as normal. A driver implementing the
Begin3 method should either reject all non-NULL 'xmlin'
parameters, or strictly validate that the app supplied
XML does not change guest ABI.

The Perform3 method also needed the xmlin parameter to
cope with the Peer2Peer migration sequence.

NB it is not yet possible to use this capability since
neither of the public virDomainMigrate/virDomainMigrateToURI
methods have a way to pass in XML.

* daemon/remote.c, src/remote/remote_driver.c,
  src/remote/remote_protocol.x, src/remote_protocol-structs:
  Add 'remote_string xmlin' parameter to begin3/perform3
  RPC messages
* src/libvirt.c, src/driver.h, src/libvirt_internal.h: Add
  'const char *xmlin' parameter to Begin3/Perform3 methods
* src/qemu/qemu_driver.c, src/qemu/qemu_migration.c,
  src/qemu/qemu_migration.h: Pass xmlin parameter around
  migration methods
2011-05-25 11:47:47 -04:00
Michal Privoznik
764c282cdf qemu: Don't change ownership of file when appending to it
Saving domain to previously created file changes also its ownership.
This is certainly not what users want if some conditions are met:
it is a regular, local file and dynamic_ownership is off.
2011-05-24 17:41:34 +02:00
Daniel P. Berrange
65e1acad80 Fix peer2peer migration with transient VMs
The qemuMigrationConfirm method shouldn't deal with final VM
cleanup, since it can be called from the peer2peer migration,
which expects to still use the 'vm' object afterwards.

Push the cleanup code out of qemuMigrationConfirm, into its
caller, qemuDomainMigrateConfirm3

* src/qemu/qemu_driver.c: Add VM cleanup code to
  qemuDomainMigrateConfirm3
* src/qemu/qemu_migration.c, src/qemu/qemu_migration.h: Remove
  job handling cleanup from qemuMigrationConfirm
2011-05-24 05:41:23 -04:00
Richard W.M. Jones
bb12a63909 qemudDomainMemoryPeek: change ownership/selinux label on temporary file.
Otherwise qemu is unable to write to it, with the error:

libvir: QEMU error : internal error unable to execute QEMU command 'memsave': Could not open '/var/cache/libvirt/qemu/qemu.mem.RRNvLv'
2011-05-20 16:12:36 +01:00
Daniel P. Berrange
6b937b2430 Don't generate cookies with v2 migration protocol.
The v2 migration protocol had a limit on cookie length that was
too small to be useful for QEMU. Avoid generating cookies with
v2 protocol, so that old libvirtd can still reliably migrate a
guest to new libvirtd uses v2 protocol.

* src/qemu/qemu_driver.c: Avoid migration cookies with v2
  migration
2011-05-19 07:13:07 -04:00
Matthias Bolte
191e1ec65c Clarify that virDomainGet(Memory|Blkio)Parameters doesn't support subsets
Improve invalid argument checks in the size query case. The drivers already
relied on this unchecked behavior.

Relax the implementation of virDomainGet(Memory|Blkio)MemoryParameters
in the drivers and allow to pass more memory than necessary for all
parameters.
2011-05-18 18:20:47 +02:00
Matthias Bolte
e430c0d0c6 Clarify the semantic of virDomainGetSchedulerParameters arguments
params and nparams are essential and cannot be NULL. Check this in
libvirt.c and remove redundant checks from the drivers (e.g. xend).

Instead of enforcing that nparams must point to exact same value as
returned by virDomainGetSchedulerType relax this to a lower bound
check. This is what some drivers (e.g. xen hypervisor and esx)
already did. Other drivers (e.g. xend) didn't check nparams at all
and assumed that there is enough space in params.

Unify the behavior in all drivers to a lower bound check and update
nparams to the number of valid values in params on success.
2011-05-18 18:20:47 +02:00
Hu Tao
a9189e2c41 qemu: introduce qemuSetSchedulerParametersFlags
Support for virDomainSetSchedulerParametersFlags of qemu driver.
2011-05-17 10:17:53 -06:00
Daniel P. Berrange
2d5caf7a25 Implement migration v3 protocol in QEMU driver
Implement the v3 migration protocol, which has two extra
steps, 'begin' on the source host and 'confirm' on the
source host. All other methods also gain both input and
output cookies to allow bi-directional data passing at
all stages.

The QEMU peer2peer migration method gains another impl
to provide the v3 migration. This finally allows migration
cookies to work with tunnelled migration, which is required
for Spice seamless migration & the lock manager transfer

* src/qemu/qemu_driver.c: Wire up migrate v3 APIs
* src/qemu/qemu_migration.c, src/qemu/qemu_migration.h: Add
  begin & confirm methods, and peer2peer impl of v3
2011-05-16 15:18:22 +01:00
Daniel P. Berrange
8654175c5b Introduce migration cookies to QEMU driver
The migration protocol has support for a 'cookie' parameter which
is an opaque array of bytes as far as libvirt is concerned. Drivers
may use this for passing around arbitrary extra data they might
need during migration. The QEMU driver needs to do a few things:

 - Pass hostname/uuid to allow strict protection against localhost
   migration attempts
 - Pass SPICE/VNC server port from the target back to the source to
   allow seamless relocation of client sessions
 - Pass lock driver state from source to destination

This patch introduces the basic glue for handling cookies
but only includes the host/guest UUID & name.

* src/libvirt_private.syms: Export virXMLParseStrHelper
* src/qemu/qemu_migration.c, src/qemu/qemu_migration.h: Parsing
  and formatting of migration cookies
* src/qemu/qemu_driver.c: Pass in cookie parameters where possible
* src/remote/remote_protocol.h, src/remote/remote_protocol.x: Change
  cookie max length to 16384 bytes
2011-05-16 15:18:20 +01:00
Daniel P. Berrange
9b1ae97fdc Add many version number annotations to drivers
Add many version number annotations to the internal driver
tables, to allow hvsupport.html to display more accurate
information
2011-05-16 14:20:48 +01:00
Daniel P. Berrange
879d409e9e Convert all driver struct intializers to C99 style
Change all the driver struct initializers to use the
C99 style, leaving out unused fields. This will make
it possible to add new APIs without changing every
driver. eg change:

    qemudDomainResume, /* domainResume */
    qemudDomainShutdown, /* domainShutdown */
    NULL, /* domainReboot */
    qemudDomainDestroy, /* domainDestroy */

to

    .domainResume = qemudDomainResume,
    .domainShutdown = qemudDomainShutdown,
    .domainDestroy = qemudDomainDestroy,

And get rid of any existing C99 style initializersr which
set NULL, eg change

     .listPools          = vboxStorageListPools,
     .numOfDefinedPools  = NULL,
     .listDefinedPools   = NULL,
     .findPoolSources    = NULL,
     .poolLookupByName   = vboxStoragePoolLookupByName,

to

     .listPools          = vboxStorageListPools,
     .poolLookupByName   = vboxStoragePoolLookupByName,
2011-05-16 14:20:43 +01:00
Daniel P. Berrange
360df0199e Tweak driver naming for consistency with public API
Fix some driver names:

  s/virDrvCPUCompare/virDrvCompareCPU/
  s/virDrvCPUBaseline/virDrvBaselineCPU/
  s/virDrvQemuDomainMonitorCommand/virDrvDomainQemuMonitorCommand/
  s/virDrvSecretNumOfSecrets/virDrvNumOfSecrets/
  s/virDrvSecretListSecrets/virDrvListSecrets/

And some driver struct field names:

  s/getFreeMemory/nodeGetFreeMemory/
2011-05-16 14:20:35 +01:00
Jiri Denemark
b046c55d40 Implement domain state reason
Only in drivers which use virDomainObj, drivers that query hypervisor
for domain status need to be updated separately in case their hypervisor
supports this functionality.

The reason is also saved into domain state XML so if a domain is not
running (i.e., no state XML exists) the reason will be lost by libvirtd
restart. I think this is an acceptable limitation.
2011-05-16 13:36:08 +02:00
Jiri Denemark
26d94012f6 Implement basic virDomainGetState in all drivers
Reason is currently always set to 0 (i.e., *_UNKNOWN).
2011-05-16 11:33:53 +02:00
Jiri Denemark
6feb1341e5 Internal driver API for virDomainGetState 2011-05-16 10:04:18 +02:00
Cole Robinson
42a3687f29 qemu: Use virDomainEventState helpers
v2:
    Drop libvirt_private.syms changes

v3:
    Adjust for new virDomainEventStateNew argument
2011-05-13 10:48:32 -04:00
Michal Privoznik
9936aecfd1 qemu: Implement the driver methods
* src/qemu/qemu_driver.c: new qemuDomainScreenshot() function
* src/qemu/qemu_monitor.c, src/qemu/qemu_monitor.h,
  src/qemu/qemu_monitor_json.c, src/qemu/qemu_monitor_json.h,
  src/qemu/qemu_monitor_text.c, src/qemu/qemu_monitor_text.h:
  Monitor command
2011-05-13 12:45:42 +02:00
Michal Privoznik
6a1f5f568f virFDStream: Add option for delete file after it's opening
This is needed if we want to transfer a temporary file. If the
transfer is done with iohelper, we might run into a race condition,
where we unlink() file before iohelper is executed.

* src/fdstream.c, src/fdstream.h,
  src/util/iohelper.c: Add new option
* src/lxc/lxc_driver.c, src/qemu/qemu_driver.c,
  src/storage/storage_driver.c, src/uml/uml_driver.c,
  src/xen/xen_driver.c: Expand existing function calls
2011-05-13 12:44:49 +02:00
Michal Privoznik
3c38664339 screenshot: Defining the internal API
* src/driver.h: Stub code for new API
* src/esx/esx_driver.c, src/libxl/libxl_driver.c,
  src/lxc/lxc_driver.c, src/openvz/openvz_driver.c,
  src/phyp/phyp_driver.c, src/qemu/qemu_driver.c,
  rc/remote/remote_driver.c, rc/test/test_driver.c,
  src/uml/uml_driver.c, src/vbox/vbox_tmpl.c,
  src/vmware/vmware_driver.c, src/xen/xen_driver.c,
  src/xen/xen_driver.h, src/xen/xen_hypervisor.c,
  src/xen/xen_inotify.c, src/xen/xend_internal.c,
  src/xen/xm_internal.c, src/xen/xs_internal.c,
  src/xenapi/xenapi_driver.c: Add dummy entries in driver
  table for new APIs
2011-05-13 12:35:58 +02:00
Eric Blake
cb84580a25 maint: omit translation for all VIR_INFO
We were 31/73 on whether to translate; since less than 50% translated
and since VIR_INFO is less than VIR_WARN which also doesn't translate,
this makes sense.

* cfg.mk (sc_prohibit_gettext_markup): Add VIR_INFO, since it
falls between WARN and DEBUG.
* daemon/libvirtd.c (qemudDispatchSignalEvent, remoteCheckAccess)
(qemudDispatchServer): Adjust offenders.
* daemon/remote.c (remoteDispatchAuthPolkit): Likewise.
* src/network/bridge_driver.c (networkReloadIptablesRules)
(networkStartNetworkDaemon, networkShutdownNetworkDaemon)
(networkCreate, networkDefine, networkUndefine): Likewise.
* src/qemu/qemu_driver.c (qemudDomainDefine)
(qemudDomainUndefine): Likewise.
* src/storage/storage_driver.c (storagePoolCreate)
(storagePoolDefine, storagePoolUndefine, storagePoolStart)
(storagePoolDestroy, storagePoolDelete, storageVolumeCreateXML)
(storageVolumeCreateXMLFrom, storageVolumeDelete): Likewise.
* src/util/bridge.c (brProbeVnetHdr): Likewise.
* po/POTFILES.in: Drop src/util/bridge.c.
2011-05-11 15:20:33 -06:00
Lai Jiangshan
b65f37a4a1 libvirt,logging: cleanup VIR_XXX0()
These VIR_XXXX0 APIs make us confused, use the non-0-suffix APIs instead.

How do these coversions works? The magic is using the gcc extension of ##.
When __VA_ARGS__ is empty, "##" will swallow the "," in "fmt," to
avoid compile error.

example: origin				after CPP
	high_level_api("%d", a_int)	low_level_api("%d", a_int)
	high_level_api("a  string")	low_level_api("a  string")

About 400 conversions.

8 special conversions:
VIR_XXXX0("") -> VIR_XXXX("msg") (avoid empty format) 2 conversions
VIR_XXXX0(string_literal_with_%) -> VIR_XXXX(%->%%) 0 conversions
VIR_XXXX0(non_string_literal) -> VIR_XXXX("%s", non_string_literal)
  (for security) 6 conversions

Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
2011-05-11 12:41:14 -06:00
Daniel P. Berrange
cbf9f2f2c0 Allow destroying QEMU VM even if a job is active
Introduce a virProcessKill function that can be safely called
even when the job mutex is held. This allows virDomainDestroy
to kill any VM even if it is asleep in a monitor job. The PID
will die and the thread asleep on the monitor will then wake
up releasing the job mutex.

* src/qemu/qemu_driver.c: Kill process before using qemuProcessStop
  to ensure job is released
* src/qemu/qemu_process.c: Add virProcessKill for killing off
  QEMU processes
2011-05-11 09:35:15 +01:00
Matthias Bolte
9817604afc Rename internal DumpXML functions to GetXMLDesc
This matches the public API and helps to get rid of some special
case code in the remote generator.

Rename driver API functions and XDR protocol structs.

No functional change included outside of the remote generator.
2011-05-10 20:32:41 +02:00
Lai Jiangshan
fcf967f2ad qemu,inject-nmi: Implement the driver methods 2011-05-10 11:40:51 -06:00
Lai Jiangshan
b19bd85e15 inject-nmi: Defining the internal API 2011-05-10 11:40:51 -06:00
Daniel P. Berrange
f79cddad55 Make taint warnings also go into the domain logfile
As well as taint warnings going to the main libvirt log,
add taint warnings to the per-domain logfile

  Domain id=3 is tainted: high-privileges
  Domain id=3 is tainted: disk-probing
  Domain id=3 is tainted: shell-scripts
  Domain id=3 is tainted: custom-monitor

* src/qemu/qemu_domain.c, src/qemu/qemu_domain.h: Enhance
  qemuDomainTaint to also log to the domain logfile
* src/qemu/qemu_driver.c: Pass -1 for logFD to taint methods to
  auto-append to logfile
* src/qemu/qemu_process.c: Pass open logFD at startup for taint
  methods
2011-05-06 12:02:02 +01:00
Daniel P. Berrange
718ac9b52f Log taint warnings in QEMU driver
Wire up logging of VM tainting to the QEMU driver

 - If running QEMU as root user/group or without capabilities
   being cleared
 - If passing custom QEMU command line args
 - If issuing custom QEMU monitor commands
 - If using a network interface config with an associated
   shell script
 - If using a disk config relying on format probing

The warnings, per-VM appear in the main libvirtd logs

  11:56:17.571: 10832: warning : qemuDomainObjTaint:712 : Domain id=1 name='l2' uuid=c7a3edbd-edaf-9455-926a-d65c16db1802 is tainted: high-privileges
  11:56:17.571: 10832: warning : qemuDomainObjTaint:712 : Domain id=1 name='l2' uuid=c7a3edbd-edaf-9455-926a-d65c16db1802 is tainted: disk-probing

The taint flags are reset when the VM is stopped.

* src/qemu/qemu_domain.c, src/qemu/qemu_domain.h: Helper APIs
  for logging taint warnings
* src/qemu/qemu_driver.c: Log tainting with custom QEMU monitor
  commands and disk/net hotplug with unsupported configs
* src/qemu/qemu_process.c: Log tainting at startup based on
  unsupported configs
2011-05-06 12:02:02 +01:00
Daniel P. Berrange
7c31e1ef0f Make QEMU migration use cached qemu capabilities data
* src/qemu/qemu_migration.c, src/qemu/qemu_migration.h: Remove
  qemuCaps parameters & use cached data
* src/qemu/qemu_driver.c: Don't create & pass qemuCaps to
  migration methods
2011-05-05 11:33:15 +01:00
Daniel P. Berrange
a623bff450 Make QEMU hotplug use cached qemu capabilities data
* src/qemu/qemu_hotplug.h, src/qemu/qemu_hotplug.c: Remove
  qemuCaps parameters from all methods
* src/qemu/qemu_driver.c: Don't create & pass qemuCaps to
  hotplug methods
2011-05-05 11:33:10 +01:00
Eric Blake
d8f7528157 qemu: silence clang false positives
Clang 2.8 wasn't quite able to follow that persistentDef was
assigned earlier if (flags & VIR_DOMAIN_MEM_CONFIG) is true.
Silence this false positive, to make clang analysis easier to use.

* src/qemu/qemu_driver.c (qemudDomainSetMemoryFlags): Add an
annotation to silence clang's claim of a NULL dereference.
2011-05-03 13:19:48 -06:00
Eric Blake
4d080ee403 qemu: avoid null pointer dereference
This code has had problems historically.  As originally
written, in commit 6bcf2501 (Jun 08), it could call unlink
on a random string, nuking an unrelated file.

Then commit 182a80b9 (Sep 09), the code was rewritten to
allocate tmp, with both a use-after-free bug and a chance to
call unlink(NULL).

Commit e206946 (Mar 11) fixed the use-after-free, but not the
NULL dereference.  Thanks to clang for catching this!

* src/qemu/qemu_driver.c (qemudDomainMemoryPeek): Don't call
unlink on NULL.
2011-05-03 10:59:55 -06:00
Christophe Fergeau
b15a8a1bdf qemu: fix uninitialized variable warning
This commit fixes
qemu/qemu_driver.c: In function 'qemuDomainModifyDeviceFlags':
qemu/qemu_driver.c:4041:8: warning: 'ret' may be used uninitialized in this
function [-Wuninitialized]
qemu/qemu_driver.c:4013:9: note: 'ret' was declared here

The variable is set to -1 so that the error paths are taken when the code
to set it didn't get a chance to run. Without initializing it, we could
return some an undefined value from this function.

While I was at it, I made a trivial whitespace change in the same function
to improve readability.
2011-05-02 09:23:47 -06:00
Matthias Bolte
feecc9f395 qemu: Fix qemuDomainModifyDeviceFlags leaking the caps bitmap 2011-04-30 17:37:34 +02:00
KAMEZAWA Hiroyuki
f37c29c8aa libvirt/qemu - support persistent update of disks
Support update of disks by MODIFY_CONFIG

This patch includes changes for qemu's disk to support
virDomainUpdateDeviceFlags() with VIR_DOMAIN_DEVICE_MODIFY_CONFIG.

This patch adds support for CDROM/foppy disk types.

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>

* src/qemu/qemu_driver.c
(qemuDomainUpdateDeviceConfig): support cdrom/floppy.
2011-04-28 14:59:06 -06:00
KAMEZAWA Hiroyuki
ab9102c232 libvirt/qemu - support persistent attach/detach disks
Support changes of disks by MODIFY_CONFIG for qemu.

This patch includes patches for qemu's disk to support
virDomainAt(De)tachDeviceFlags with VIR_DOMAIN_DEVICE_MODIFY_CONFIG.

Other devices can be added incrementally.

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>

* /src/conf/domain_conf.c
(virDomainDiskIndexByName): returns array index of disk in vmdef.
(virDomainDiskRemoveByName): removes a disk which has the name in vmdef.
* src/qemu/qemu_driver.c
(qemuDomainAttachDeviceConfig): add support for Disks.
(qemuDomainDetachDeviceConfig): add support for Disks.
2011-04-27 21:46:35 -06:00
KAMEZAWA Hiroyuki
da1eba6bc8 libvirt/qemu - support persistent modification of devices
This patch adds functions for modify domain's persistent definition.
To do error recovery in easy way, we use a copy of vmdef and update it.

The whole sequence will be:

  make a copy of domain definition.

  if (flags & MODIFY_CONFIG)
      update copied domain definition
  if (flags & MODIF_LIVE)
      do hotplug.
  if (no error)
      save copied one to the file and update cached definition.
  else
      discard copied definition.

This patch is mixuture of Eric Blake's work and mine.
From: Eric Blake <eblake@redhat.com>
Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>

(virDomainObjCopyPersistentDef): make a copy of persistent vm definition
(qemuDomainAttach/Detach/UpdateDeviceConfig) : callbacks. now empty
(qemuDomainModifyDeviceFlags): add support for MODIFY_CONFIG and MODIFY_CURRENT
2011-04-27 21:33:58 -06:00
Jiri Denemark
1c84237852 qemu: Add flags checking in DomainCoreDump 2011-04-26 13:37:26 +02:00
KAMEZAWA Hiroyuki
9b8543b6ad libvirt/qemu - clean up UpdateDevice for consolidation.
This patch strips reusable part of qemuDomainUpdateDeviceFlags()
and consolidate it to qemuDomainModifyDeviceFlags().
No functional changes.

* src/qemu/qemu_driver.c
(qemuDomainChangeDiskMediaLive) : pulled out code for updating disks.
(qemuDomainUpdateDeviceLive) : core of UpdateDevice, extracted from
UpdateDeviceFlags()
(qemuDomainModifyDeviceFlags): add support for updating device in live domain.
(qemuDomainUpdateDeviceFlags): reworked as a wrapper function of
qemuDomainModifyDeviceFlags()

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-04-21 15:49:57 -06:00
KAMEZAWA Hiroyuki
19ad136f60 libvirt/qemu - clean up At(De)tachDeviceFlags() for consolidation.
clean up At(De)tachDeviceFlags() for consolidation.

qemuDomainAttachDeviceFlags()/qemuDomainDetachFlags()/
qemuDomainUpdateDeviceFlags() has similar logics and copied codes.

This patch series tries to unify them to use shared code when it can.
At first, clean up At(De)tachDeviceFlags() and devide it into functions.

By this, this patch pulls out shared components between functions.
Based on patch series by Eric Blake, I added some modification as
switch-case with QEMU_DEVICE_ATTACH, QEMU_DEVICE_DETACH, QEMU_DEVICE_UPDATE

* src/qemu/qemu_driver.c
(qemuDomainAt(De)tachDeviceFlags) : pulled out to qemuDomainModifyDeviceFlags()
(qemuDomainModifyDeviceFlags) : implements generic code for modifying domain.
(qemuDomainAt(De)tachDeviceFlagsLive) : code for at(de)taching devices to
domain in line. no changes in logic from old code.
(qemuDomainAt(De)tachDeviceDiskLive) : for at(de)taching Disks.
(qemuDomainAt(De)tachDeviceControllerLive) : for at(de)taching Controllers

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-04-21 14:19:21 -06:00
KAMEZAWA Hiroyuki
2160116ff8 libvirt/qemu - Centralize device modification in the more flexible APIs
Centralize device modification in the more flexible APIs, to allow future
honoring of additional flags.  Explicitly reject the
VIR_DOMAIN_DEVICE_MODIFY_FORCE flag on attach/detach.

Based on Eric Blake<eblake@redhat.com>'s work.

* src/qemu/qemu_driver.c
(qemudDomainAttachDevice)(qemudDomainAttachDeviceFlags): Swap bodies,rename...
(qemudDomainDetachDevice, qemudDomainDetachDeviceFlags): Likewise.

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2011-04-21 13:12:04 -06:00
Wen Congyang
b060d2e5d4 enhance processWatchdogEvent()
This patch does the following two things:
1. hold an extra reference while handling watchdog event
   If the domain is not persistent, and qemu quits unexpectedly before
   calling processWatchdogEvent(), vm will be freed and the function
   processWatchdogEvent() will be dangerous.

2. unlock qemu driver and vm before returning from processWatchdogEvent()
   When the function processWatchdogEvent() failed, we only free wdEvent,
   but forget to unlock qemu driver and vm, free dumpfile.
2011-04-18 09:38:45 +08:00
Wen Congyang
847efb32de qemu: avoid qemu_driver being unlocked twice when virThreadPoolNew() failed
We do not lock qemu_driver when calling virThreadPoolNew(). If it failed,
we will unlock qemu_driver. It is dangerous.

We may use this pool during auto starting domains. So we must create it before
calling qemuAutostartDomains(). Otherwise, libvirtd will crash.
2011-04-18 09:38:45 +08:00
Stefan Berger
cf2145d546 Migrate VMs between different-endianess hosts
This patch enables the migration of Qemu VMs between hosts of different endianess. I tested this by migrating a i686 VM between a x86 and ppc64 host.

I am converting the 'int's in the VM's state header to uint32_t assuming this doesn't break compatibility with existing deployments other than Linux.
2011-04-14 14:48:03 -04:00
Daniel P. Berrange
97263cb115 Add missing checks for QEMU domain state in tunables APIs
The methods qemuDomain{Get,Set}{Memory,Blkio,Scheduler}Parameters
all forgot to do a check on virDomainIsActive(), resulting in bogus
error messages from later parts of their impl

* src/qemu/qemu_driver.c: Add missing checks on virDomainIsActive()
2011-04-14 14:32:34 +01:00
Taku Izumi
c1795c5204 maxmem: implement virDomainSetMaxMemory API of the qemu driver
This patch implements the code to support virDomainSetMaxMemory API,
and to support VIR_DOMAIN_MEM_MAXIMUM flag in qemudDomainSetMemoryFlags function.
As a result, we can change the maximum memory size of inactive QEMU guests.

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-04-08 17:40:29 -06:00
Eric Blake
5bc22e129b docs: tweak virsh restore warning
* tools/virsh.pod: Fix grammar, and clarify wording.
* src/qemu/qemu_driver.c (qemudDomainObjStart): Drop redundant
condition.
2011-04-08 07:58:07 -06:00
Taku Izumi
95298e2380 setmem: add VIR_DOMAIN_MEM_CURRENT support to qemu
This patch adds virDomainSetMemoryFlags(,,VIR_DOMAIN_MEM_CURRENT) support
code to qemu driver.

Also, change virDomainObjIsActive to return bool, given its usage.

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-04-07 17:13:56 -06:00
Osier Yang
a73bbfc8be qemu: Remove the managed state file only if restoring succeeded
1) Both "qemuDomainStartWithFlags" and "qemuAutostartDomain" try to
restore the domain from managedsave'ed image if it exists (by
invoking "qemuDomainObjRestore"), but it unlinks the image even
if restoring fails, which causes data loss. (This problem exists
for "virsh managedsave dom; virsh start dom").

The fix for is to unlink the managed state file only if restoring
succeeded.

2) For "virsh save dom; virsh restore dom;", it can cause data
corruption if one reuse the saved state file for restoring. Add
doc to tell user about it.

3) In "qemuDomainObjStart", if "managed_save" is NULL, we shouldn't
fallback to start the domain, skipping it to cleanup as a incidental
fix. Discovered by Eric.
2011-04-07 16:58:26 +08:00
Eric Blake
0d166c6b7c build: detect potentential uninitialized variables
Even with -Wuninitialized (which is part of autobuild.sh
--enable-compile-warnings=error), gcc does NOT catch this
use of an uninitialized variable:

{
  if (cond)
    goto error;
  int a = 1;
error:
  printf("%d", a);
}

which prints 0 (supposing the stack started life wiped) if
cond was true.  Clang will catch it, but we don't use clang
as often.  Using gcc -Wjump-misses-init catches it, but also
gives false positives:

{
  if (cond)
    goto error;
  int a = 1;
  return a;
error:
  return 0;
}

Here, a was never used in the scope of the error block, so
declaring it after goto is technically fine (and clang agrees).
However, given that our HACKING already documents a preference
to C89 decl-before-statement, the false positive warning is
enough of a prod to comply with HACKING.

[Personally, I'd _really_ rather use C99 decl-after-statement
to minimize scope, but until gcc can efficiently and reliably
catch scoping and uninitialized usage bugs, I'll settle with
the compromise of enforcing a coding standard that happens to
reject false positives if it can also detect real bugs.]

* acinclude.m4 (LIBVIRT_COMPILE_WARNINGS): Add -Wjump-misses-init.
* src/util/util.c (__virExec): Adjust offenders.
* src/conf/domain_conf.c (virDomainTimerDefParseXML): Likewise.
* src/remote/remote_driver.c (doRemoteOpen): Likewise.
* src/phyp/phyp_driver.c (phypGetLparNAME, phypGetLparProfile)
(phypGetVIOSFreeSCSIAdapter, phypVolumeGetKey)
(phypGetStoragePoolDevice)
(phypVolumeGetPhysicalVolumeByStoragePool)
(phypVolumeGetPath): Likewise.
* src/vbox/vbox_tmpl.c (vboxNetworkUndefineDestroy)
(vboxNetworkCreate, vboxNetworkDumpXML)
(vboxNetworkDefineCreateXML): Likewise.
* src/xenapi/xenapi_driver.c (getCapsObject)
(xenapiDomainDumpXML): Likewise.
* src/xenapi/xenapi_utils.c (createVMRecordFromXml): Likewise.
* src/security/security_selinux.c (SELinuxGenNewContext):
Likewise.
* src/qemu/qemu_command.c (qemuBuildCommandLine): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainChangeEjectableMedia):
Likewise.
* src/qemu/qemu_process.c (qemuProcessWaitForMonitor): Likewise.
* src/qemu/qemu_monitor_text.c (qemuMonitorTextGetPtyPaths):
Likewise.
* src/qemu/qemu_driver.c (qemudDomainShutdown)
(qemudDomainBlockStats, qemudDomainMemoryPeek): Likewise.
* src/storage/storage_backend_iscsi.c
(virStorageBackendCreateIfaceIQN): Likewise.
* src/node_device/node_device_udev.c (udevProcessPCI): Likewise.
2011-04-04 11:26:29 -06:00
Wen Congyang
e206946da7 free tmp after unlinking it
We create a temporary file to save memory, and we will remove it after reading
memory to buffer. But we free the variable that contains the temporary filename
before we remove it. So we should free tmp after unlinking it.
2011-04-01 12:15:21 +08:00
Hu Tao
025e199810 qemu: unlock qemu driver before return from domain save
qemuDriverUnlock() wasn't called on 2 exit paths
* src/qemu/qemu_driver.c: fix qemudDomainSave() to always unlock
  the driver before exiting on error
2011-03-30 10:34:16 +08:00
Naoya Horiguchi
343a27aff8 extend logging to record configuration-related changes
Currently libvirt's default logging is limited and it is difficult to
determine what was happening when a proglem occurred (especially on a
machines where one don't know the detail.)  This patch helps to do that
by making additional logging available for the following events:

  creating/defining/undefining domains
  creating/defining/undefining/starting/stopping networks
  creating/defining/undefining/starting/stopping storage pools
  creating/defining/undefining/starting/stopping storage volumes.

* AUTHORS: add Naoya Horiguchi
* src/network/bridge_driver.c src/qemu/qemu_driver.c
  src/storage/storage_driver.c: provide more VIR_INFO logging
2011-03-30 09:19:47 +08:00
Osier Yang
1cc4d0259c cputune: Support cputune for qemu driver
When domain startup, setting cpu affinity and cpu shares according
to the cputune xml specified in domain xml.

Modify "qemudDomainPinVcpu" to update domain config for vcpupin,
and modify "qemuSetSchedulerParameters" to update domain config
for cpu shares.

v1 - v2:
   * Use "VIR_ALLOC_N" instead of "VIR_ALLOC_VAR"
   * But keep raising error when it fails on adding vcpupin xml
     entry, as I still don't have a better idea yet.
2011-03-29 22:13:46 +08:00
Daniel P. Berrange
e886237af5 Enhance the streams helper to support plain file I/O
The O_NONBLOCK flag doesn't work as desired on plain files
or block devices. Introduce an I/O helper program that does
the blocking I/O operations, communicating over a pipe that
can support O_NONBLOCK

* src/fdstream.c, src/fdstream.h: Add non-blocking I/O
  on plain files/block devices
* src/Makefile.am, src/util/iohelper.c: I/O helper program
* src/qemu/qemu_driver.c, src/lxc/lxc_driver.c,
  src/uml/uml_driver.c, src/xen/xen_driver.c: Update for
  streams API change
2011-03-29 12:17:28 +01:00
Eric Blake
83b77fa589 qemu: fix regression that hangs on save failure
Regression introduced in commit 6034ddd55.

* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Jump to correct
label.
2011-03-28 17:00:32 -06:00
Eric Blake
6034ddd559 qemu: consolidate migration to file code
This points out that core dumps (still) don't work for root-squash
NFS, since the fd is not opened correctly.  This patch should not
introduce any functionality change, it is just a refactoring to
avoid duplicated code.

* src/qemu/qemu_migration.h (qemuMigrationToFile): New prototype.
* src/qemu/qemu_migration.c (qemuMigrationToFile): New function.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag, doCoreDump): Use
it.
2011-03-28 10:26:33 -06:00
Eric Blake
80449b325e qemu: use common API for reading difficult files
Direct access to an open file is so much simpler than passing
everything through a pipe!

* src/qemu/qemu_driver.c (qemudOpenAsUID)
(qemudDomainSaveImageClose): Delete.
(qemudDomainSaveImageOpen): Rename...
(qemuDomainSaveImageOpen): ...and drop read_pid argument.  Use
virFileOpenAs instead of qemudOpenAsUID.
(qemudDomainSaveImageStartVM, qemudDomainRestore)
(qemudDomainObjRestore): Rename...
(qemuDomainSaveImageStartVM, qemuDomainRestore)
(qemDomainObjRestore): ...and simplify accordingly.
(qemudDomainObjStart, qemuDriver): Update callers.
2011-03-28 10:26:33 -06:00
Eric Blake
1a369dfbe8 qemu, storage: improve type safety
* src/storage/storage_backend.c (createRawFileOpHook): Change
signature.
(struct createRawFileOpHookData): Delete unused struct.
(virStorageBackendCreateRaw): Adjust caller.
* src/qemu/qemu_driver.c (struct fileOpHookData): Delete unused
struct.
(qemudDomainSaveFileOpHook): Rename...
(qemuDomainSaveFileOpHook): ...and change signature.
(qemudDomainSaveFlag): Adjust caller.
2011-03-28 10:26:33 -06:00
Eric Blake
1fdd50f999 util: rename virFileOperation to virFileOpenAs
This patch intentionally doesn't change indentation, in order to
make it easier to review the real changes.

* src/util/util.h (VIR_FILE_OP_RETURN_FD, virFileOperationHook):
Delete.
(virFileOperation): Rename...
(virFileOpenAs): ...and reduce parameters.
* src/util/util.c (virFileOperationNoFork, virFileOperation):
Rename and simplify.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Adjust caller.
* src/storage/storage_backend.c (virStorageBackendCreateRaw):
Likewise.
* src/libvirt_private.syms: Reflect rename.
2011-03-28 10:26:33 -06:00
Eric Blake
3eede281eb qemu: simplify domain save fd handling
This makes root-squash NFS saves more efficient.

* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Use new
virFileOperation flag to open fd only once.
2011-03-28 10:26:33 -06:00
Eric Blake
9497506fa0 qemu: allow simple domain save to use fd: protocol
This allows direct saves (no compression, no root-squash NFS) to use
the more efficient fd: migration, which in turn avoids a race where
qemu exec: migration can sometimes fail because qemu does a generic
waitpid() that conflicts with the pclose() used by exec:.  Further
patches will solve compression and root-squash NFS.

* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Use new function
when there is no compression.
2011-03-28 10:26:32 -06:00
Eric Blake
96d567862a qemu: don't restore state label twice
Otherwise, if something like doStopVcpus fails after the first
restore, a second restore is attempted and throws a useless
warning.

* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Avoid second
restore of state label.
2011-03-28 09:10:09 -06:00
Philipp Hahn
24da109573 Add missing { for qemudDomainInterfaceStats
Add missing open curly brace between function declaration of non-linux
variant of qemudDomainInterfaceStats() and its body.

Signed-off-by: Philipp Hahn <hahn@univention.de>
2011-03-25 09:56:06 -06:00
Wen Congyang
9450a7cbef update domain status forcibly even if attach a device failed
Steps to reproduce this bug:
1. virsh attach-disk domain --source diskimage --target sdb --sourcetype file --driver qemu --subdriver qcow2
   error: Failed to attach disk
   error: operation failed: adding scsi-disk,bus=scsi0.0,scsi-id=1,drive=drive-scsi0-0-1,id=scsi0-0-1 device failed: Property 'scsi-disk.drive' can't find value 'drive-scsi0-0-1'
2. service libvirtd restart
   Stopping libvirtd daemon:                                  [  OK  ]
   Starting libvirtd daemon:                                  [  OK  ]
3. virsh attach-disk domain --source diskimage --target sdb --sourcetype file --driver qemu --subdriver raw
   error: Failed to attach disk
   error: operation failed: adding lsi,id=scsi0,bus=pci.0,addr=0x6 device failed: Duplicate ID 'scsi0' for device

The reason is that we create a new scsi controller but we do not update
/var/run/libvirt/qemu/domain.xml.

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-03-24 15:26:28 +08:00
Daniel P. Berrange
83cc3d1d55 Wire up virDomainMigrateSetSpeed into QEMU driver
Enhance the QEMU migration monitoring loop, so that it can get
a signal to change migration speed on the fly

* src/qemu/qemu_domain.h: Add signal for changing speed on the fly
* src/qemu/qemu_driver.c: Wire up virDomainMigrateSetSpeed driver
* src/qemu/qemu_migration.c: Support signal for changing speed
2011-03-22 15:53:08 +00:00
Daniel P. Berrange
cb4aba9b6a Add public API for setting migration speed on the fly
It is possible to set a migration speed limit when starting
migration. This new API allows the speed limit to be changed
on the fly to adjust to changing conditions

* src/driver.h, src/libvirt.c, src/libvirt_public.syms,
  include/libvirt/libvirt.h.in: Add virDomainMigrateSetMaxSpeed
* src/esx/esx_driver.c, src/lxc/lxc_driver.c,
  src/opennebula/one_driver.c, src/openvz/openvz_driver.c,
  src/phyp/phyp_driver.c, src/qemu/qemu_driver.c,
  src/remote/remote_driver.c, src/test/test_driver.c,
  src/uml/uml_driver.c, src/vbox/vbox_tmpl.c,
  src/vmware/vmware_driver.c, src/xen/xen_driver.c,
  src/libxl/libxl_driver.c: Stub new API
2011-03-22 15:53:08 +00:00
Eric Blake
496084175a qemu: respect locking rules
THREADS.txt states that the contents of vm should not be read or
modified while the vm lock is not held, but that the lock must not
be held while performing a monitor command.  This fixes all the
offenders that I could find.

* src/qemu/qemu_process.c (qemuProcessStartCPUs)
(qemuProcessInitPasswords, qemuProcessStart): Don't modify or
refer to vm state outside lock.
* src/qemu/qemu_driver.c (qemudDomainHotplugVcpus): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainChangeGraphicsPasswords):
Likewise.
2011-03-18 13:32:17 -06:00
Wen Congyang
e2aec53b97 qemu: check driver name while attaching disk
This bug was reported by Shi Jin(jinzishuai@gmail.com):
=============
# virsh attach-disk RHEL6RC /var/lib/libvirt/images/test3.img vdb \
        --driver file --subdriver qcow2
Disk attached successfully

# virsh save RHEL6RC /var/lib/libvirt/images/memory.save
Domain RHEL6RC saved to /var/lib/libvirt/images/memory.save

# virsh restore /var/lib/libvirt/images/memory.save
error: Failed to restore domain from /var/lib/libvirt/images/memory.save
error: internal error unsupported driver name 'file'
       for disk '/var/lib/libvirt/images/test3.img'
=============

We check the driver name when we start or restore VM, but we do
not check it while attaching a disk. This adds the same check on disk
driverName used in qemuBuildCommandLine to qemudDomainAttachDevice.

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-03-18 00:36:37 -04:00
Nikunj A. Dadhania
78ba748ef1 virsh: fix memtune's help message for swap_hard_limit
* Correct the documentation for cgroup: the swap_hard_limit indicates
  mem+swap_hard_limit.
* Change cgroup private apis to: virCgroupGet/SetMemSwapHardLimit

Signed-off-by: Nikunj A. Dadhania <nikunj@linux.vnet.ibm.com>
2011-03-17 16:45:06 -06:00
Gui Jianfeng
f84a756eca qemu: implement new BlkioParameters API
Implement domainSetBlkioParameters and domainGetBlkioParameters for QEmu

Signed-off-by: Gui Jianfeng <guijianfeng@cn.fujitsu.com>
2011-03-10 17:53:52 -07:00
Gui Jianfeng
d55aa8694e libvirt: implements virDomain{Get,Set}BlkioParameters
Implements virDomainSetBlkioParameters and virDomainGetBlkioParameters and initialization

Signed-off-by: Gui Jianfeng <guijianfeng@cn.fujitsu.com>
2011-03-10 17:53:33 -07:00
Taku Izumi
cad769001c setmem: implement the code to address the new API in the qemu driver
This patch implements the code to address the new API
in the qemu driver.

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-03-10 15:02:58 -07:00
Taku Izumi
e8340a8b79 setmem: introduce a new libvirt API (virDomainSetMemoryFlags)
This patch introduces a new libvirt API (virDomainSetMemoryFlags) and
a flag (virDomainMemoryModFlags).

Signed-off-by: Taku Izumi <izumi.taku@jp.fujitsu.com>
2011-03-10 15:02:58 -07:00
Jiri Denemark
346236fea9 qemu: Stop guest CPUs before creating a snapshot 2011-03-10 14:36:05 +01:00
Jiri Denemark
89e75b01a0 qemu: Refactor qemuDomainSnapshotCreateXML 2011-03-10 14:36:05 +01:00
Eric Blake
340ab27dd2 audit: also audit cgroup ACL permissions
* src/qemu/qemu_audit.h (qemuAuditCgroupMajor)
(qemuAuditCgroupPath): Add parameter.
* src/qemu/qemu_audit.c (qemuAuditCgroupMajor)
(qemuAuditCgroupPath): Add 'acl=rwm' to cgroup audit entries.
* src/qemu/qemu_cgroup.c: Update clients.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Likewise.
2011-03-09 11:36:59 -07:00
Eric Blake
5564c57528 cgroup: allow fine-tuning of device ACL permissions
Adding audit points showed that we were granting too much privilege
to qemu; it should not need any mknod rights to recreate any
devices.  On the other hand, lxc should have all device privileges.
The solution is adding a flag parameter.

This also lets us restrict write access to read-only disks.

* src/util/cgroup.h (virCgroup*Device*): Adjust prototypes.
* src/util/cgroup.c (virCgroupAllowDevice)
(virCgroupAllowDeviceMajor, virCgroupAllowDevicePath)
(virCgroupDenyDevice, virCgroupDenyDeviceMajor)
(virCgroupDenyDevicePath): Add parameter.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Update clients.
* src/lxc/lxc_controller.c (lxcSetContainerResources): Likewise.
* src/qemu/qemu_cgroup.c: Likewise.
(qemuSetupDiskPathAllow): Also, honor read-only disks.
2011-03-09 11:35:36 -07:00
Eric Blake
48096a0064 audit: rename remaining qemu audit functions
Also add ATTRIBUTE_NONNULL markers.

* src/qemu/qemu_audit.h: The pattern qemuDomainXXXAudit is
inconsistent; prefer qemuAuditXXX instead.
* src/qemu/qemu_audit.c: Reflect the renames.
* src/qemu/qemu_driver.c: Likewise.
* src/qemu/qemu_hotplug.c: Likewise.
* src/qemu/qemu_migration.c: Likewise.
* src/qemu/qemu_process.c: Likewise.
2011-03-09 11:35:20 -07:00
Eric Blake
d04916faae audit: split cgroup audit types to allow more information
Device names can be manipulated, so it is better to also log
the major/minor device number corresponding to the cgroup ACL
changes that libvirt made.  This required some refactoring
of the relatively new qemu cgroup audit code.

Also, qemuSetupChardevCgroup was only auditing on failure, not success.

* src/qemu/qemu_audit.h (qemuDomainCgroupAudit): Delete.
(qemuAuditCgroup, qemuAuditCgroupMajor, qemuAuditCgroupPath): New
prototypes.
* src/qemu/qemu_audit.c (qemuDomainCgroupAudit): Rename...
(qemuAuditCgroup): ...and drop a parameter.
(qemuAuditCgroupMajor, qemuAuditCgroupPath): New functions, to
allow listing device major/minor in audit.
(qemuAuditGetRdev): New helper function.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Adjust callers.
* src/qemu/qemu_cgroup.c (qemuSetupDiskPathAllow)
(qemuSetupHostUsbDeviceCgroup, qemuSetupCgroup)
(qemuTeardownDiskPathDeny): Likewise.
(qemuSetupChardevCgroup): Likewise, fixing missing audit.
2011-03-09 09:08:10 -07:00
Cole Robinson
9189301426 Don't overwrite virRun error messages
virRun gives pretty useful error output, let's not overwrite it unless there
is a good reason. Some places were providing more information about what
the commands were _attempting_ to do, however that's usually less useful from
a debugging POV than what actually happened.
2011-03-09 08:53:12 -05:00
Hu Tao
83d35233a9 Fix a wrong error message thrown to user
* src/qemu/qemu_driver.c: qemuDomainUpdateDeviceFlags() is not disk
  specific as the message suggests
2011-03-09 20:09:25 +08:00
Wen Congyang
0e29f71135 support to detach USB disk
Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-03-07 11:40:12 -07:00
Wen Congyang
8f338032b9 rename qemuDomainDetachSCSIDiskDevice to qemuDomainDetachDiskDevice
The way to detach a USB disk is the same as that to detach a SCSI
disk. Rename this function and we can use it to detach a USB disk.

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-03-07 11:28:15 -07:00
Eric Blake
4f805dcdc4 qemu: avoid double close on domain restore
qemudDomainSaveImageStartVM was evil - it closed the incoming fd
argument on some, but not all, code paths, without informing the
caller about that action.  No wonder that this resulted in
double-closes: https://bugzilla.redhat.com/show_bug.cgi?id=672725

* src/qemu/qemu_driver.c (qemudDomainSaveImageStartVM): Alter
signature, to avoid double-close.
(qemudDomainRestore, qemudDomainObjRestore): Update callers.
2011-03-02 08:58:49 -07:00
Daniel P. Berrange
16ba2aafc4 Allow hash tables to use generic pointers as keys
Relax the restriction that the hash table key must be a string
by allowing an arbitrary hash code generator + comparison func
to be provided

* util/hash.c, util/hash.h: Allow any pointer as a key
* internal.h: Include stdbool.h as standard.
* conf/domain_conf.c, conf/domain_conf.c,
  conf/nwfilter_params.c, nwfilter/nwfilter_gentech_driver.c,
  nwfilter/nwfilter_gentech_driver.h, nwfilter/nwfilter_learnipaddr.c,
  qemu/qemu_command.c, qemu/qemu_driver.c,
  qemu/qemu_process.c, uml/uml_driver.c,
  xen/xm_internal.c: s/char */void */ in hash callbacks
2011-02-25 13:00:54 +00:00
Eric Blake
e25f2c74df audit: audit qemu memory and vcpu adjusments
* src/qemu/qemu_audit.h (qemuDomainMemoryAudit)
(qemuDomainVcpuAudit): New prototypes.
* src/qemu/qemu_audit.c (qemuDomainResourceAudit)
(qemuDomainMemoryAudit, qemuDomainVcpuAudit): New functions.
(qemuDomainStartAudit): Call as appropriate.
* src/qemu/qemu_driver.c (qemudDomainSetMemory)
(qemudDomainHotplugVcpus): Likewise.
2011-02-24 13:32:17 -07:00
Eric Blake
6bb98d419f audit: add qemu hooks for auditing cgroup events
* src/qemu/qemu_audit.h (qemuDomainCgroupAudit): New prototype.
* src/qemu/qemu_audit.c (qemuDomainCgroupAudit): Implement it.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Add audit.
* src/qemu/qemu_cgroup.c (qemuSetupDiskPathAllow)
(qemuSetupChardevCgroup, qemuSetupHostUsbDeviceCgroup)
(qemuSetupCgroup, qemuTeardownDiskPathDeny): Likewise.
2011-02-24 13:32:15 -07:00
Eric Blake
b4d3434fc2 audit: prepare qemu for listing vm in cgroup audits
* src/qemu/qemu_cgroup.h (struct qemuCgroupData): New helper type.
(qemuSetupDiskPathAllow, qemuSetupChardevCgroup)
(qemuTeardownDiskPathDeny): Drop unneeded prototypes.
(qemuSetupDiskCgroup, qemuTeardownDiskCgroup): Adjust prototype.
* src/qemu/qemu_cgroup.c
(qemuSetupDiskPathAllow, qemuSetupChardevCgroup)
(qemuTeardownDiskPathDeny): Mark static and use new type.
(qemuSetupHostUsbDeviceCgroup): Use new type.
(qemuSetupDiskCgroup): Alter signature.
(qemuSetupCgroup): Adjust caller.
* src/qemu/qemu_hotplug.c (qemuDomainAttachHostUsbDevice)
(qemuDomainDetachPciDiskDevice, qemuDomainDetachSCSIDiskDevice):
Likewise.
* src/qemu/qemu_driver.c (qemudDomainAttachDevice)
(qemuDomainUpdateDeviceFlags): Likewise.
2011-02-24 13:31:05 -07:00
Eric Blake
061738764d cgroup: determine when skipping non-devices
* src/util/cgroup.c (virCgroupAllowDevicePath)
(virCgroupDenyDevicePath): Don't fail with EINVAL for
non-devices.
* src/qemu/qemu_driver.c (qemudDomainSaveFlag): Update caller.
* src/qemu/qemu_cgroup.c (qemuSetupDiskPathAllow)
(qemuSetupChardevCgroup, qemuSetupHostUsbDeviceCgroup)
(qemuSetupCgroup, qemuTeardownDiskPathDeny): Likewise.
2011-02-24 13:31:05 -07:00
Daniel P. Berrange
35416720c2 Put <stdbool.h> into internal.h so it is available everywhere
Remove the <stdbool.h> header from all source files / headers
and just put it into internal.h

* src/internal.h: Add <stdbool.h>
2011-02-24 12:04:06 +00:00
Jiri Denemark
9fc4b6a606 qemu: Switch over command line capabilities to virBitmap
This is done for two reasons:
- we are getting very close to 64 flags which is the maximum we can use
  with unsigned long long
- by using LL constants in enum we already violates C99 constraint that
  enum values have to fit into int
2011-02-24 12:10:00 +01:00
Jiri Denemark
23d935bd97 qemu: Rename qemud\?CmdFlags to qemuCaps
The new name complies more with the fact that it contains a set of
qemuCapsFlags.
2011-02-24 12:08:34 +01:00
Eric Blake
009fce98be security: avoid memory leak
Leak introduced in commit d6623003.

* src/qemu/qemu_driver.c (qemuSecurityInit): Avoid leak on failure.
* src/security/security_stack.c (virSecurityStackClose): Avoid
leaking component drivers.
2011-02-22 09:50:34 -07:00
Daniel P. Berrange
766de43533 Move all the QEMU migration code to a new file
The introduction of the v3 migration protocol, along with
support for migration cookies, will significantly expand
the size of the migration code. Move it all to a separate
file to make it more manageable

The functions are not moved 100%. The API entry points
remain in the main QEMU driver, but once the public
virDomainPtr is resolved to the internal virDomainObjPtr,
all following code is moved.

This will allow the new v3 API entry points to call into the
same shared internal migration functions

* src/qemu/qemu_domain.c, src/qemu/qemu_domain.h: Add
  qemuDomainFormatXML helper method
* src/qemu/qemu_driver.c: Remove all migration code
* src/qemu/qemu_migration.c, src/qemu/qemu_migration.h: Add
  all migration code.
2011-02-17 12:56:10 +00:00
Daniel P. Berrange
48c2d6c65b Split all QEMU process mangement code into separate file
Move the qemudStartVMDaemon and qemudShutdownVMDaemon
methods into a separate file, renaming them to
qemuProcessStart, qemuProcessStop. All helper methods
called by these are also moved & renamed to match

* src/Makefile.am: Add qemu_process.c/.h
* src/qemu/qemu_command.c: Add qemuDomainAssignPCIAddresses
* src/qemu/qemu_command.h: Add VNC port min/max
* src/qemu/qemu_domain.c, src/qemu/qemu_domain.h: Add
  domain event queue helpers
* src/qemu/qemu_driver.c, src/qemu/qemu_driver.h: Remove
  all QEMU process startup/shutdown functions
* src/qemu/qemu_process.c, src/qemu/qemu_process.h: Add
  all QEMU process startup/shutdown functions
2011-02-17 12:48:55 +00:00
Osier Yang
cd951ad2ec qemu: Error prompt when saving a shutoff domain
"qemudDomainSaveFlag" goto wrong label "endjob", which will cause
error when security manager trying to restore label (regression).

As it's more reasonable to check if vm is shutoff immediately, and
return right away if it is, remove the checking in "qemudDomainSaveFlag",
and add checking in "qemudDomainSave".

* src/qemu/qemu_driver.c
2011-02-17 11:18:47 +08:00
Eric Blake
abaa65605f qemu: avoid NULL derefs
The processWatchdogEvent fix is real, although it can only trigger
on OOM, since bad things happen if doCoreDump is called with a NULL
pathname argument.  The other fixes silence clang, but aren't a real
bug because virReportErrorHelper tolerates a NULL format string even
though *printf does not.

* src/qemu/qemu_driver.c (processWatchdogEvent): Exit on OOM.
(qemuDomainIsActive, qemuDomainIsPersistent, qemuDomainIsUpdated):
Provide valid message.
2011-02-15 09:55:45 -07:00
Daniel P. Berrange
41f551e25e Fix cleanup on VM state after failed QEMU startup
Commit 9962e406c6 introduced a
problem where if the VM failed to startup, it would not be
correctly cleaned up. Amongst other things the SELinux
security label would not be removed, which prevents the VM
from ever starting again.

The virDomainIsActive() check at the start of qemudShutdownVMDaemon
checks for vm->def->id not being -1. By moving the assignment of the
VM id to the start of qemudStartVMDaemon, we can ensure cleanup will
occur on failure

* src/qemu/qemu_driver.c: Move initialization of 'vm->def->id'
  so that qemudShutdownVMDaemon() will process the shutdown
2011-02-14 16:02:00 +00:00
Matthias Bolte
1682bcf7d8 qemu: Report a more informative error for missing cgroup controllers
Also use VIR_ERR_OPERATION_INVALID instead of VIR_ERR_NO_SUPPORT, as
the operation could succeed when the cgroup controller was mounted.
2011-02-12 13:37:57 +01:00
Wen Congyang
6bf4788e86 qemu: fix attach-interface regression
QEMUD_CMD_FLAG_PCI_MULTIBUS should be set in the function
qemuCapsExtractVersionInfo()

The flag QEMUD_CMD_FLAG_PCI_MULTIBUS is used in the function
qemuBuildDeviceAddressStr(). All callers get qemuCmdFlags
by the function qemuCapsExtractVersionInfo() except that
testCompareXMLToArgvFiles() in qemuxml2argvtest.c.

So we should set QEMUD_CMD_FLAG_PCI_MULTIBUS in the function
qemuCapsExtractVersionInfo() instead of qemuBuildCommandLine()
because the function qemuBuildCommandLine() does not be called
when we attach a pci device.

tests: set QEMUD_CMD_FLAG_PCI_MULTIBUS in testCompareXMLToArgvFiles()

set QEMUD_CMD_FLAG_PCI_MULTIBUS before calling qemuBuildCommandLine()
as the flags is not set by qemuCapsExtractVersionInfo().

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-02-10 15:07:21 -07:00
Daniel P. Berrange
eacb3bb02a Reduce log level when cgroups aren't mounted
Quite a few hosts don't have cgroups mounted and so see warnings
from libvirt logged, which then cause bug reports, etc. Reduce
the log level to INFO so they're not visible by default

* src/qemu/qemu_driver.c: Reduce log level for cgroups
2011-02-10 14:30:02 +00:00
Eric Blake
5ec8fb5662 sysinfo: implement qemu support
* src/qemu/qemu_driver.c (qemuGetSysinfo): New function.
(qemuDriver): Install it.
2011-02-08 19:38:49 -07:00
Eric Blake
dec13a5a15 sysinfo: define internal driver API
* src/driver.h (virDrvGetSysinfo): New typedef.
(_virDriver): New callback member.
* src/esx/esx_driver.c (esxDriver): Add stub for driver.
* src/lxc/lxc_driver.c (lxcDriver): Likewise.
* src/opennebula/one_driver.c (oneDriver): Likewise.
* src/openvz/openvz_driver.c (openvzDriver): Likewise.
* src/phyp/phyp_driver.c (phypDriver): Likewise.
* src/qemu/qemu_driver.c (qemuDriver): Likewise.
* src/remote/remote_driver.c (remote_driver): Likewise.
* src/test/test_driver.c (testDriver): Likewise.
* src/uml/uml_driver.c (umlDriver): Likewise.
* src/vbox/vbox_tmpl.c (Driver): Likewise.
* src/vmware/vmware_driver.c (vmwareDriver): Likewise.
* src/xen/xen_driver.c (xenUnifiedDriver): Likewise.
* src/xenapi/xenapi_driver.c (xenapiDriver): Likewise.
2011-02-08 19:25:30 -07:00
Jiri Denemark
2169472ab6 qemu: Add shortcut for HMP pass through
Currently users who want to use virDomainQemuMonitorCommand() API or
it's virsh equivalent has to use the same protocol as libvirt uses for
communication to qemu. Since the protocol is QMP with current qemu and
HMP much more usable for humans, one ends up typing something like the
following:

    virsh qemu-monitor-command DOM \
'{"execute":"human-monitor-command","arguments":{"command-line":"info kvm"}}'

which is not a very convenient way of debugging qemu.

This patch introduces --hmp option to qemu-monitor-command, which says
that the provided command is in HMP. If libvirt uses QMP to talk with
qemu, the command will automatically be converted into QMP. So the
example above is simplified to just

    virsh qemu-monitor-command --hmp DOM "info kvm"

Also the result is converted from

    {"return":"kvm support: enabled\r\n"}

to just plain HMP:

    kvm support: enabled

If libvirt talks to qemu in HMP, --hmp flag is obviously a noop.
2011-02-03 22:20:30 +01:00
Eric Blake
9962e406c6 qemu: avoid double shutdown
* src/qemu/qemu_driver.c (qemudShutdownVMDaemon): Check that vm is
still active.
Reported by Wen Congyang as follows:

Steps to reproduce this bug:

1. use gdb to debug libvirtd, and set breakpoint in the function
   qemuConnectMonitor()
2. start a vm, and the libvirtd will be stopped in qemuConnectMonitor()
3. kill -STOP $(cat /var/run/libvirt/qemu/<domain>.pid)
4. continue to run libvirtd in gdb, and libvirtd will be blocked in the
   function qemuMonitorSetCapabilities()
5. kill -9 $(cat /var/run/libvirt/qemu/<domain>.pid)

Here is log of the qemu:
=========
LC_ALL=C PATH=/sbin:/usr/sbin:/bin:/usr/bin ...
char device redirected to /dev/pts/3
2011-01-27 09:38:48.101: shutting down
2011-01-27 09:41:26.401: shutting down
=========

The vm is shut down twice. I do not know whether this behavior has
side effect, but I think we should shutdown the vm only once.
2011-02-03 09:00:35 -07:00
Osier Yang
ee3b030050 qemu: More clear error parsing domain def failure of tunneled migration
* src/qemu/qemu_driver.c
2011-01-31 17:12:46 +08:00
Daniel P. Berrange
0095edaa06 Remove bogus log warning lines when launching QEMU
The refactoring of QEMU command startup was comitted with
a couple of VIR_WARN lines left in from debugging.

* src/qemu/qemu_driver.c: Remove log warning lines
2011-01-28 11:49:21 +00:00
Daniel P. Berrange
e85247e7c3 Remove double close of qemu monitor
When qemuMonitorSetCapabilities() fails, there is no need to
call qemuMonitorClose(), because the caller will already see
the error code and tear down the entire VM. The extra call to
qemuMonitorClose resulted in a double-free due to it removing
a ref count prematurely.

* src/qemu/qemu_driver.c: Remove premature close of monitor
2011-01-28 11:49:13 +00:00
Eric Blake
b96b6f4723 qemu: fix error messages
Regression in commit caa805ea let a lot of bad messages slip in.

* cfg.mk (msg_gen_function): Fix function name.
* src/qemu/qemu_cgroup.c (qemuRemoveCgroup): Fix fallout from
'make syntax-check'.
* src/qemu/qemu_driver.c (qemudDomainGetInfo)
(qemuDomainWaitForMigrationComplete, qemudStartVMDaemon)
(qemudDomainSaveFlag, qemudDomainAttachDevice)
(qemuDomainUpdateDeviceFlags): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainAttachHostUsbDevice)
(qemuDomainDetachPciDiskDevice, qemuDomainDetachSCSIDiskDevice):
Likewise.
2011-01-27 20:41:26 -07:00
Wen Congyang
d96431f910 avoid vm to be deleted if qemuConnectMonitor failed
Steps to reproduce this bug:
1. service libvirtd start
2. virsh start <domain>
3. kill -STOP $(cat /var/run/libvirt/qemu/<domain>.pid)
4. service libvirtd restart
5. kill -9 $(cat /var/run/libvirt/qemu/<domain>.pid)

Then libvirtd will core dump or be in deadlock state.

Make sure that json is built into libvirt and the version
of qemu is newer than 0.13.0.

The reason of libvirtd cores dump is that:
We add vm->refs when we alloc the memory, and decrease it
in the function qemuHandleMonitorEOF() in other thread.

We add vm->refs in the function qemuConnectMonitor() and
decrease it when the vm is inactive.

The libvirtd will block in the function qemuMonitorSetCapabilities()
because the vm is stopped by signal SIGSTOP. Now the vm->refs is 2.

Then we kill the vm by signal SIGKILL. The function
qemuMonitorSetCapabilities() failed, and then we will decrease vm->refs
in the function qemuMonitorClose().
In another thread, mon->fd is broken and the function
qemuHandleMonitorEOF() is called.

If qemuHandleMonitorEOF() decreases vm->refs before qemuConnectMonitor()
returns, vm->refs will be decrease to 0 and the memory is freed.

We will call qemudShutdownVMDaemon() as qemuConnectMonitor() failed.
The memory has been freed, so qemudShutdownVMDaemon() is too dangerous.

We will reference NULL pointer in the function virDomainConfVMNWFilterTeardown():
=============
void
virDomainConfVMNWFilterTeardown(virDomainObjPtr vm) {
    int i;

    if (nwfilterDriver != NULL) {
        for (i = 0; i < vm->def->nnets; i++)
            virDomainConfNWFilterTeardown(vm->def->nets[i]);
    }
}
============
vm->def->nnets is not 0 but vm->def->nets is NULL(We don't set vm->def->nnets
to 0 when we free vm).

We should add an extra reference of vm to avoid vm to be deleted if
qemuConnectMonitor() failed.

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-01-27 13:38:29 -07:00
Laine Stump
c9c794b52b Manually kill gzip if restore fails before starting qemu
If a guest image is saved in compressed format, and the restore fails
in some way after the intermediate process used to uncompress the
image has been started, but before qemu has been started to hook up to
the uncompressor, libvirt will endlessly wait for the uncompressor to
finish, but it never will because it's still waiting to have something
hooked up to drain its output.

The solution is to close the pipes on both sides of the uncompressor,
then send a SIGTERM before calling waitpid on it (only if the restore
has failed, of course).
2011-01-26 10:13:43 -05:00
Laine Stump
34a19dda1c Set SELinux context label of pipes used for qemu migration
This patch is a partial resolution to the following bug:

   https://bugzilla.redhat.com/show_bug.cgi?id=667756

(to complete the fix, an updated selinux-policy package is required,
to add the policy that allows libvirt to set the context of a fifo,
which was previously not allowed).

Explanation : When an incoming migration is over a pipe (for example,
if the image was compressed and is being fed through gzip, or was on a
root-squash nfs server, so needed to be opened by a child process
running as a different uid), qemu cannot read it unless the selinux
context label for the pipe has been set properly.

The solution is to check the fd used as the source of the migration
just before passing it to qemu; if it's a fifo (implying that it's a
pipe), we call the newly added virSecurityManagerSetFDLabel() function
to set the context properly.
2011-01-26 09:03:21 -05:00
Osier Yang
dbd63c4d63 qemu: Error prompt when managed save a shutoff domain
The problem was introduced by commit 4303c91, which removed the checking
of domain state, this patch is to fix it.

Otherwise, improper error will be thrown, e.g.

error: Failed to save domain rhel6 state
error: cannot resolve symlink /var/lib/libvirt/qemu/save/rhel6.save: No such
file or directory
2011-01-25 09:51:26 -07:00
Cole Robinson
1d9c0a08d9 qemu: Allow serving VNC over a unix domain socket
QEMU supports serving VNC over a unix domain socket rather than traditional
TCP host/port. This is specified with:

<graphics type='vnc' socket='/foo/bar/baz'/>

This provides better security access control than VNC listening on
127.0.0.1, but will cause issues with tools that rely on the lax security
(virt-manager in fedora runs as regular user by default, and wouldn't be
able to access a socket owned by 'qemu' or 'root').

Also not currently supported by any clients, though I have patches for
virt-manager, and virt-viewer should be simple to update.

v2:
    schema: Make listen vs. socket a <choice>
2011-01-21 16:03:04 -05:00
Cole Robinson
cb4c2694f1 qemu: Set domain def transient at beginning of startup process
This will allow us to record transient runtime state in vm->def, like
default VNC parameters. Accomplish this by adding an extra 'live' parameter
to SetDefTransient, with similar semantics to the 'live' flag for
AssignDef.
2011-01-21 16:03:03 -05:00
Daniel P. Berrange
f0bbf96047 Fix error reporting when machine type probe fails
Avoid overwriting the real error message with a generic
OOM failure message, when machine type probe fails

* src/qemu/qemu_driver.c: Don't overwrite error
2011-01-21 16:08:28 +00:00
Wen Congyang
bda57661b8 qemu: Fix a possible deadlock in p2p migration
The function virUnrefConnect() may call virReleaseConnect() to release
the dest connection, and the function virReleaseConnect() will call
conn->driver->close().

So the function virUnrefConnect() should be surrounded by
qemuDomainObjEnterRemoteWithDriver() and
qemuDomainObjExitRemoteWithDriver() to prevent possible deadlock between
two communicating libvirt daemons.

See commit f0c8e1cb37 for further details.

Signed-off-by: Wen Congyang <wency@cn.fujitsu.com>
2011-01-21 08:21:12 -07:00
Jiri Denemark
15e7865893 qemu: Avoid sending STOPPED event twice
In some circumstances, libvirtd would issue two STOPPED events after it
stopped a domain. This was because an EOF event can arrive after a qemu
process is killed but before qemuMonitorClose() is called.

qemuHandleMonitorEOF() should ignore EOF when the domain is not running.

I wasn't able to reproduce this bug directly, only after adding an
artificial sleep() into qemudShutdownVMDaemon().
2011-01-19 15:01:52 +01:00
Matthias Bolte
e065e1ea04 Use VIR_ERR_OPERATION_INVALID when appropriated
VIR_ERR_OPERATION_INVALID means that the operation is not valid
for the current state of the involved object.
2011-01-18 23:14:37 +01:00
Matthias Bolte
8c6d61162f Fix misuse of VIR_ERR_INVALID_* error code
VIR_ERR_INVALID_* is meant for invalid pointers only.
2011-01-18 23:14:37 +01:00
Eric Blake
1859939a74 qemu: use -incoming fd:n to avoid qemu holding fd indefinitely
https://bugzilla.redhat.com/show_bug.cgi?id=620363

When using -incoming stdio or -incoming exec:, qemu keeps the
stdin fd open long after the migration is complete.  Not to
mention that exec:cat is horribly inefficient, by doubling the
I/O and going through a popen interface in qemu.

The new -incoming fd: of qemu 0.12.0 closes the fd after using
it, and allows us to bypass an intermediary cat process for
less I/O.

* src/qemu/qemu_command.h (qemuBuildCommandLine): Add parameter.
* src/qemu/qemu_command.c (qemuBuildCommandLine): Support
migration via fd: when possible.  Consolidate migration handling
into one spot, now that it is more complex.
* src/qemu/qemu_driver.c (qemudStartVMDaemon): Update caller.
* tests/qemuxml2argvtest.c (mymain): Likewise.
* tests/qemuxml2argvdata/qemuxml2argv-restore-v2-fd.args: New file.
* tests/qemuxml2argvdata/qemuxml2argv-restore-v2-fd.xml: Likewise.
2011-01-17 09:24:41 -07:00
Jiri Denemark
3d44035824 qemu: Support per-device boot ordering
Support for this is included in qemu and seabios from upstream git.
2011-01-17 17:08:13 +01:00
Nikunj A. Dadhania
d94a14f89d memtune: Let virsh know the unlimited value for memory tunables
Display or set unlimited values for memory parameters. Unlimited is
represented by INT64_MAX in memory cgroup.

Signed-off-by: Nikunj A. Dadhania <nikunj@linux.vnet.ibm.com>
Reported-by: Justin Clift <jclift@redhat.com>
2011-01-14 17:17:27 -07:00
Marc-André Lureau
9d73efdbe3 Use the new set_password monitor command to set password.
We try to use that command first when setting a VNC/SPICE password. If
that doesn't work we fallback to the legacy VNC only password

Allow an expiry time to be set, if that doesn't work, throw an error
if they try to use SPICE.

Change since v1:
- moved qemuInitGraphicsPasswords to qemu_hotplug, renamed
  to qemuDomainChangeGraphicsPasswords.
- updated what looks like a typo (that appears to work anyway) in
  initial patch from Daniel:
    - ret = qemuInitGraphicsPasswords(driver, vm,
    -                                 VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
    -                                 &vm->def->graphics[0]->data.vnc.auth,
    -                                 driver->vncPassword);
    + ret = qemuInitGraphicsPasswords(driver, vm,
    +                                 VIR_DOMAIN_GRAPHICS_TYPE_SPICE,
    +                                 &vm->def->graphics[0]->data.spice.auth,
    +                                 driver->spicePassword);

Based on patch by Daniel P. Berrange <berrange@redhat.com>.
2011-01-14 12:36:00 -07:00
Eric Blake
30b9e608c6 qemu: move monitor device out of domain_conf common code
* src/conf/domain_conf.h (virDomainChrDeviceType): Drop monitor.
* src/conf/domain_conf.c (virDomainChrDevice)
(virDomainChrDefParseTargetXML, virDomainChrDefFormat): Drop
monitor support.
* src/qemu/qemu_command.h (qemuBuildCommandLine): Alter signature.
* src/qemu/qemu_monitor.h (qemuMonitorOpen): Likewise.
* src/qemu/qemu_domain.h (_qemuDomainObjPrivate): Change type of
monConfig.
* src/qemu/qemu_domain.c (qemuDomainObjPrivateFree)
(qemuDomainObjPrivateXMLFormat, qemuDomainObjPrivateXMLParse):
Adjust to type change.
* src/qemu/qemu_command.c (qemuBuildCommandLine): Likewise.
* src/qemu/qemu_driver.c (qemuPrepareMonitorChr)
(qemudStartVMDaemon, qemuDomainXMLToNative, qemuConnectMonitor)
(qemudShutdownVMDaemon): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainAttachNetDevice): Likewise.
* src/qemu/qemu_monitor.c (qemuMonitorOpen): Likewise.
* tests/qemuxml2argvtest.c (testCompareXMLToArgvFiles): Likewise.
2011-01-14 09:54:26 -07:00
Eric Blake
98334e7c3a domain_conf: split source data out from ChrDef
This opens up the possibility of reusing the smaller ChrSourceDef
for both qemu monitor and a passthrough smartcard device.

* src/conf/domain_conf.h (_virDomainChrDef): Factor host
details...
(_virDomainChrSourceDef): ...into new struct.
(virDomainChrSourceDefFree): New prototype.
* src/conf/domain_conf.c (virDomainChrDefFree)
(virDomainChrDefParseXML, virDomainChrDefFormat): Split...
(virDomainChrSourceDefClear, virDomainChrSourceDefFree)
(virDomainChrSourceDefParseXML, virDomainChrSourceDefFormat):
...into new functions.
(virDomainChrDefParseTargetXML): Update clients to reflect type
split.
* src/vmx/vmx.c (virVMXParseSerial, virVMXParseParallel)
(virVMXFormatSerial, virVMXFormatParallel): Likewise.
* src/xen/xen_driver.c (xenUnifiedDomainOpenConsole): Likewise.
* src/xen/xend_internal.c (xenDaemonParseSxprChar)
(xenDaemonFormatSxprChr): Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainDumpXML, vboxAttachSerial)
(vboxAttachParallel): Likewise.
* src/security/security_dac.c (virSecurityDACSetChardevLabel)
(virSecurityDACSetChardevCallback)
(virSecurityDACRestoreChardevLabel)
(virSecurityDACRestoreChardevCallback): Likewise.
* src/security/security_selinux.c (SELinuxSetSecurityChardevLabel)
(SELinuxSetSecurityChardevCallback)
(SELinuxRestoreSecurityChardevLabel)
(SELinuxSetSecurityChardevCallback): Likewise.
* src/security/virt-aa-helper.c (get_files): Likewise.
* src/lxc/lxc_driver.c (lxcVmStart, lxcDomainOpenConsole):
Likewise.
* src/uml/uml_conf.c (umlBuildCommandLineChr): Likewise.
* src/uml/uml_driver.c (umlIdentifyOneChrPTY, umlIdentifyChrPTY)
(umlDomainOpenConsole): Likewise.
* src/qemu/qemu_command.c (qemuBuildChrChardevStr)
(qemuBuildChrArgStr, qemuBuildCommandLine)
(qemuParseCommandLineChr): Likewise.
* src/qemu/qemu_domain.c (qemuDomainObjPrivateXMLFormat)
(qemuDomainObjPrivateXMLParse): Likewise.
* src/qemu/qemu_cgroup.c (qemuSetupChardevCgroup): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainAttachNetDevice): Likewise.
* src/qemu/qemu_driver.c (qemudFindCharDevicePTYsMonitor)
(qemudFindCharDevicePTYs, qemuPrepareChardevDevice)
(qemuPrepareMonitorChr, qemudShutdownVMDaemon)
(qemuDomainOpenConsole): Likewise.
* src/qemu/qemu_command.h (qemuBuildChrChardevStr)
(qemuBuildChrArgStr): Delete, now that they are static.
* src/libvirt_private.syms (domain_conf.h): New exports.
* cfg.mk (useless_free_options): Update list.
* tests/qemuxml2argvtest.c (testCompareXMLToArgvFiles): Update
tests.
2011-01-14 09:54:26 -07:00
Daniel P. Berrange
d6623003c6 Refactor the security drivers to simplify usage
The current security driver usage requires horrible code like

    if (driver->securityDriver &&
        driver->securityDriver->domainSetSecurityHostdevLabel &&
        driver->securityDriver->domainSetSecurityHostdevLabel(driver->securityDriver,
                                                              vm, hostdev) < 0)

This pair of checks for NULL clutters up the code, making the driver
calls 2 lines longer than they really need to be. The goal of the
patchset is to change the calling convention to simply

  if (virSecurityManagerSetHostdevLabel(driver->securityDriver,
                                        vm, hostdev) < 0)

The first check for 'driver->securityDriver' being NULL is removed
by introducing a 'no op' security driver that will always be present
if no real driver is enabled. This guarentees driver->securityDriver
!= NULL.

The second check for 'driver->securityDriver->domainSetSecurityHostdevLabel'
being non-NULL is hidden in a new abstraction called virSecurityManager.
This separates the driver callbacks, from main internal API. The addition
of a virSecurityManager object, that is separate from the virSecurityDriver
struct also allows for security drivers to carry state / configuration
information directly. Thus the DAC/Stack drivers from src/qemu which
used to pull config from 'struct qemud_driver' can now be moved into
the 'src/security' directory and store their config directly.

* src/qemu/qemu_conf.h, src/qemu/qemu_driver.c: Update to
  use new virSecurityManager APIs
* src/qemu/qemu_security_dac.c,  src/qemu/qemu_security_dac.h
  src/qemu/qemu_security_stacked.c, src/qemu/qemu_security_stacked.h:
  Move into src/security directory
* src/security/security_stack.c, src/security/security_stack.h,
  src/security/security_dac.c, src/security/security_dac.h: Generic
  versions of previous QEMU specific drivers
* src/security/security_apparmor.c, src/security/security_apparmor.h,
  src/security/security_driver.c, src/security/security_driver.h,
  src/security/security_selinux.c, src/security/security_selinux.h:
  Update to take virSecurityManagerPtr object as the first param
  in all callbacks
* src/security/security_nop.c, src/security/security_nop.h: Stub
  implementation of all security driver APIs.
* src/security/security_manager.h, src/security/security_manager.c:
  New internal API for invoking security drivers
* src/libvirt.c: Add missing debug for security APIs
2011-01-10 18:10:52 +00:00
Stefan Berger
0922ff2fea qemu driver: fix positioning to end of log file
While doing some testing with Qemu and creating huge logfiles I encountered the case where the VM could not start anymore due to the lseek() to the end of the Qemu VM's log file failing. The patch below fixes the problem by replacing the previously used 'int' with 'off_t'.

To reproduce this error, you could do the following:

dd if=/dev/zero of=/var/log/libvirt/qemu/<name of VM>.log bs=1024 count=$((1024*2048))

and you should get an error like this:

error: Failed to start domain <name of VM>
error: Unable to seek to -2147482651 in /var/log/libvirt/qemu/<name of VM>.log: Success
2011-01-04 12:46:10 -05:00
Laine Stump
f42cf7cb79 Replace setuid/setgid/initgroups with virSetUIDGID()
This patch fixes https://bugzilla.redhat.com/show_bug.cgi?id=664406

If qemu is run as a different uid, it has been unable to access mode
0660 files that are owned by a different user, but with a group that
the qemu is a member of (aside from the one group listed in the passwd
file), because initgroups() is not being called prior to the
exec. initgroups will change the group membership of the process (and
its children) to match the new uid.

To make this happen, the setregid()/setreuid() code in
qemuSecurityDACSetProcessLabel has been replaced with a call to
virSetUIDGID(), which does both of those, plus calls initgroups.

Similar, but not identical, code in qemudOpenAsUID() has been replaced
with virSetUIDGID(). This not only consolidates the functionality to a
single location, but also potentially fixes some as-yet unreported
bugs.
2010-12-23 16:48:37 -05:00
Matthias Bolte
2412babedb qemu: Reparent children when deleting a snapshot
Shorten qemuDomainSnapshotWriteSnapshotMetadata function name
and make it take a snapshot pointer instead of dealing with
the current snapshot. Update other functions accordingly.

Add a qemuDomainSnapshotReparentChildren hash iterator to
reparent the children of a snapshot that is being deleted. Use
qemuDomainSnapshotWriteMetadata to write updated metadata
to disk.

This fixes a problem where outdated parent information breaks
the snapshot tree and hinders the deletion of child snapshots.

Reported by Philipp Hahn.
2010-12-23 16:42:08 +01:00
Jiri Denemark
e6cf98ceb5 qemu: Return SPICE ports on domain shutdown
Commit ed0d9f6c0c added support for
automatic port allocation for SPICE but forgot to mark such ports as
unused when they are not used anymore.
2010-12-22 17:24:10 +01:00
Eric Blake
450e84050b qemu: use virAsprintf instead of PATH_MAX
* src/qemu/qemu_driver.c (qemudLogFD, qemudLogReadFD)
(qemudStartup, qemudGetProcessInfo): Use heap instead of stack.
2010-12-20 10:33:43 -07:00
Daniel P. Berrange
acabd9d0ff Move QEMU hotplug helper code out of the QEMU driver
The QEMU driver file is far too large. Move all the hotplug
helper code out into a separate file. No functional change.

* src/qemu/qemu_hotplug.c, src/qemu/qemu_hotplug.h,
  src/Makefile.am: Add hotplug helper file
* src/qemu/qemu_driver.c: Delete hotplug code
2010-12-17 13:58:54 +00:00
Daniel P. Berrange
679d628c43 Move QEMU domain lock / job helper code to separate file
To allow the APIs to be used from separate files, move the domain
lock / job helper code into qemu_domain.c

* src/qemu/qemu_domain.c, src/qemu/qemu_domain.h: Add domain lock
  / job code
* src/qemu/qemu_driver.c: Remove domain lock / job code
2010-12-17 13:58:54 +00:00
Daniel P. Berrange
22f4cb855c Move QEMU driver lock helpers to a separate file
To allow their use from other source files, move qemuDriverLock
and qemuDriverUnlock to qemu_conf.h and make them non-static

* src/qemu/qemu_conf.c, src/qemu/qemu_conf.h: Add qemuDriverLock
  qemuDriverUnlock
* src/qemu/qemu_driver.c: Remove qemuDriverLock and qemuDriverUnlock
2010-12-17 13:50:47 +00:00
Daniel P. Berrange
01abc8a1b8 Move QEMU hostdev helper code out of the QEMU driver
The QEMU driver file is far too large. Move all the hostdev
helper code out into a separate file. No functional change.

* src/qemu/qemu_hostdev.c, src/qemu/qemu_hostdev.h,
  src/Makefile.am: Add hostdev helper file
* src/qemu/qemu_driver.c: Delete hostdev code
2010-12-17 13:50:21 +00:00
Daniel P. Berrange
52271cfc28 Move QEMU cgroup helper code out of the QEMU driver
The QEMU driver file is far too large. Move all the cgroup
helper code out into a separate file. No functional change.

* src/qemu/qemu_cgroup.c, src/qemu/qemu_cgroup.h,
  src/Makefile.am: Add cgroup helper file
* src/qemu/qemu_driver.c: Delete cgroup code
2010-12-17 13:48:30 +00:00
Daniel P. Berrange
1aecb6348c Move QEMU audit helper code out of the QEMU driver
The QEMU driver file is far too large. Move all the audit
helper code out into a separate file. No functional change.

* src/qemu/qemu_audit.c, src/qemu/qemu_audit.h,
  src/Makefile.am: Add audit helper file
* src/qemu/qemu_driver.c: Delete audit code
2010-12-17 13:46:15 +00:00
Daniel P. Berrange
df4aabafbe Move QEMU private data & namespace code into separate file
Move the code for handling the QEMU virDomainObjPtr private
data, and custom XML namespace into a separate file

* src/qemu/qemu_domain.c, src/qemu/qemu_domain.h: New file
  for private data & namespace code
* src/qemu/qemu_driver.c, src/qemu/qemu_driver.h: Remove
  private data & namespace code
* src/qemu/qemu_driver.h, src/qemu/qemu_command.h: Update
  includes
* src/Makefile.am: Add src/qemu/qemu_domain.c
2010-12-17 13:44:54 +00:00
Daniel P. Berrange
0f2e4b9c68 Move QEMU command line management into a separate file
The qemu_conf.c code is doing three jobs, driver config file
loading, QEMU capabilities management and QEMU command line
management. Move the command line code into its own file

* src/qemu/qemu_command.c, src/qemu/qemu_command.h: New
  command line management code
* src/qemu/qemu_conf.c, src/qemu/qemu_conf.h: Delete command
  line code
* src/qemu/qemu_conf.h, src/qemu_conf.c: Adapt for API renames
* src/Makefile.am: add src/qemu/qemu_command.c
* src/qemu/qemu_monitor_json.c, src/qemu/qemu_monitor_text.c: Add
  import of qemu_command.h
2010-12-17 13:43:20 +00:00
Daniel P. Berrange
d8ae147d8e Move QEMU capabilities management into a separate file
The qemu_conf.c code is doing three jobs, driver config file
loading, QEMU capabilities management and QEMU command line
management. Move the capabilities code into its own file

* src/qemu/qemu_capabilities.c, src/qemu/qemu_capabilities.h: New
  capabilities management code
* src/qemu/qemu_conf.c, src/qemu/qemu_conf.h: Delete capabilities
  code
* src/qemu/qemu_conf.h: Adapt for API renames
* src/Makefile.am: add src/qemu/qemu_capabilities.c
2010-12-17 13:39:18 +00:00
Hu Tao
226f40542e Add a new function doStartCPUs 2010-12-14 08:43:53 -07:00
Hu Tao
fa139130fb Add a new function doStopCPUs 2010-12-14 08:40:26 -07:00
Hu Tao
54c6833392 Add a macro timeval_to_ms to compute micro seconds from timeval 2010-12-14 08:38:41 -07:00
Osier Yang
5faf88fe98 qemu: Introduce two new job types
Currently, all of domain "save/dump/managed save/migration"
use the same function "qemudDomainWaitForMigrationComplete"
to wait the job finished, but the error messages are all
about "migration", e.g. when a domain saving job is canceled
by user, "migration was cancled by client" will be throwed as
an error message, which will be confused for user.

As a solution, intoduce two new job types(QEMU_JOB_SAVE,
QEMU_JOB_DUMP), and set "priv->jobActive" to "QEMU_JOB_SAVE"
before saving, to "QEMU_JOB_DUMP" before dumping, so that we
could get the real job type in
"qemudDomainWaitForMigrationComplete", and give more clear
message further.

And as It's not important to figure out what's the exact job
is in the DEBUG and WARN log, also we don't need translated
string in logs, simply repace "migration" with "job" in some
statements.

* src/qemu/qemu_driver.c
2010-12-13 10:20:29 -07:00
Hu Tao
e19cdbfcf1 Add a watchdog action `dump'
`dump' watchdog action lets libvirtd to dump the guest when receives a
watchdog event (which probably means a guest crash)

Currently only qemu is supported.
2010-12-09 11:59:27 -07:00
Hu Tao
b4560bf2ef Add a new function doCoreDump
This patch prepares for the next patch.
2010-12-09 11:43:58 -07:00
Jiri Denemark
c778fe9678 qemu: Distinguish between domain shutdown and crash
When we get an EOF event on monitor connection, it may be a result of
either crash or graceful shutdown. QEMU which supports async events
(i.e., we are talking to it using JSON monitor) emits SHUTDOWN event on
graceful shutdown. In case we don't get this event by the time monitor
connection is closed, we assume the associated domain crashed.
2010-12-09 11:50:48 +01:00
Ryan Harper
aefaeb3d48 qemu: call drive_del in DetachPciDiskDevice
Currently libvirt doesn't confirm whether the guest has responded to the
disk removal request.  In some cases this can leave the guest with
continued access to the device while the mgmt layer believes that it has
been removed.  With a recent qemu monitor command[1] we can
deterministically revoke a guests access to the disk (on the QEMU side)
to ensure no futher access is permitted.

This patch adds support for the drive_del() command and introduces it
in the disk removal paths.  If the guest is running in a QEMU without this
command we currently explicitly check for unknown command/CommandNotFound
and log the issue.

If QEMU supports the command we issue the drive_del command after we attempt
to remove the device.  The guest may respond and remove the block device
before we get to attempt to call drive_del.  In that case, we explicitly check
for 'Device not found' from the monitor indicating that the target drive
was auto-deleted upon guest responds to the device removal notification.

1. http://thread.gmane.org/gmane.comp.emulators.qemu/84745

Signed-off-by: Ryan Harper <ryanh@us.ibm.com>
2010-12-08 14:43:45 -07:00
Ryan Harper
0cdc982995 qemu: call drive_unplug in DetachPciDiskDevice
Currently libvirt doesn't confirm whether the guest has responded to the
disk removal request.  In some cases this can leave the guest with
continued access to the device while the mgmt layer believes that it has
been removed.  With a recent qemu monitor command[1] we can
deterministically revoke a guests access to the disk (on the QEMU side)
to ensure no futher access is permitted.

This patch adds support for the drive_unplug() command and introduces it
in the disk removal paths.  There is some discussion to be had about how
to handle the case where the guest is running in a QEMU without this
command (and the fact that we currently don't have a way of detecting
what monitor commands are available).

Changes since v2:
 - use VIR_ERROR to report when unplug command not found
Changes since v1:
 - return > 0 when command isn't present, < 0 on command failure
 - detect when drive_unplug command isn't present and log error
   instead of failing entire command

Signed-off-by: Ryan Harper <ryanh@us.ibm.com>
2010-12-08 11:03:02 -07:00
Osier Yang
981f7c8c9b qemu: Only build devstr when needs (attach PCI controller)
- qemudDomainAttachPciControllerDevice: Don't build "devstr"
  if "-device" of qemu is not available, as "devstr" will only
  be used by "qemuMonitorAddDevice", which depends on "-device"
  argument of qemu is supported.

- "qemudDomainSaveImageOpen": Fix indent problem.

* src/qemu/qemu_driver.c
2010-12-08 08:58:51 -07:00
Jiri Denemark
584c13f356 qemu: Fix a possible deadlock in p2p migration
Two more calls to remote libvirtd have to be surrounded by
qemuDomainObjEnterRemoteWithDriver() and
qemuDomainObjExitRemoteWithDriver() to prevent possible deadlock between
two communicating libvirt daemons.

See commit f0c8e1cb37 for further details.
2010-12-06 10:09:50 +01:00
Matthias Bolte
ccf2d0847b qemu: Don't try to set input FD to -1 2010-12-05 00:45:43 +01:00
Eric Blake
6a7e7c4f62 qemu: convert to virCommand
* src/qemu/qemu_conf.c (qemudExtractVersionInfo): Check for file
before executing it here, rather than in callers.
(qemudBuildCommandLine): Rewrite with virCommand.
* src/qemu/qemu_conf.h (qemudBuildCommandLine): Update signature.
* src/qemu/qemu_driver.c (qemuAssignPCIAddresses)
(qemudStartVMDaemon, qemuDomainXMLToNative): Adjust callers.
2010-12-02 16:00:47 -07:00
Osier Yang
401979a454 qemu: Use macro for max and min vnc port instead of number
* src/qemu/qemu_driver.c (though MACROS QEMU_VNC_PORT_MAX, and
QEMU_VNC_PORT_MIN are defined at the beginning, numbers (65535, 5900)
are still used, replace them)
2010-12-01 10:28:23 -07:00
Osier Yang
ead3c43456 qemu: Fix typo in qemuTeardownDiskPathDeny
typo in error message, it should be by copy-a-paste
from "qemuSetupDiskPathAllow".

* src/qemu/qemu_driver.c (qemuTeardownDiskPathDeny)
2010-12-01 18:04:56 +01:00
Eric Blake
428ea3a626 qemu: plug memory leak
* src/qemu/qemu_driver.c (qemudShutdown): Free all strings and the
ebtables structure.
* src/libvirt_private.syms (ebtablesContextFree): Export missing
symbol.
* src/util/ebtables.c (ebtablesContextFree): Allow early exit.
2010-12-01 10:00:10 -07:00
Matthias Bolte
474b1c1487 Fix undefined symbol errors when macvtap support is disabled
Use macvtap specific functions depending on WITH_MACVTAP.

Use #if instead of #ifdef to check for WITH_MACVTAP, because
WITH_MACVTAP is always defined with value 0 or 1.

Also export virVMOperationType{To|From}String unconditional,
because they are used unconditional in the domain config code.
2010-12-01 17:08:08 +01:00
Hu Tao
1b6f13bb70 Fall back to QEMUD_SAVE_FORMAT_RAW if compression method fails.
When dumping a domain, it's reasonable to save dump-file in raw format
if dump format is misconfigured or the corresponding compress program
is not available rather then fail dumping.
2010-11-30 14:22:53 -07:00
Stefan Berger
c2b38277b3 802.1Qbg: use pre-associate state at beginning of inc. migr
This patch introduces the usage of the pre-associate state of the IEEE 802.1Qbg standard on incoming VM migration on the target host. It is in response to bugzilla entry 632750.

https://bugzilla.redhat.com/show_bug.cgi?id=632750

For being able to differentiate the exact reason as to why a macvtap device is being created, either due to a VM creation or an incoming VM migration, I needed to pass that reason as a parameter from wherever qemudStartVMDaemon is being called in order to determine whether to send an ASSOCIATE (VM creation) or a PRE-ASSOCIATE (incoming VM migration) towards lldpad.

I am also fixing a problem with the virsh domainxml-to-native call on the way.

Gerhard successfully tested the patch with a recent blade network 802.1Qbg-compliant switch.

The patch should not have any side-effects on the 802.1Qbh support in libvirt, but Roopa (cc'ed) may want to verify this.
2010-11-30 12:50:54 -05:00
Osier Yang
c1fb916618 implement callback function for qemu driver
* src/qemu/qemu_driver.c (add function qemuDomainIsUpdated)
2010-11-23 15:04:42 -07:00
Osier Yang
37a02efd71 define internal driver API
* src/driver.h (new typedef, new callback member for "_virDriver")
* src/esx/esx_driver.c
* src/lxc/lxc_driver.c
* src/opennebula/one_driver.c
* src/openvz/openvz_driver.c
* src/phyp/phyp_driver.c
* src/qemu/qemu_driver.c
* src/remote/remote_driver.c
* src/test/test_driver.c
* src/uml/uml_driver.c
* src/vbox/vbox_tmpl.c
* src/xen/xen_driver.c
* src/xenapi/xenapi_driver.c
2010-11-23 15:04:41 -07:00
Daniel P. Berrange
7f9cebc0c0 Ensure logfile isn't truncated by shutdown message.
When running non-root, the QEMU log file is usually opened with
truncation, since there is no logrotate for non-root usage.
This means that when libvirt logs the shutdown timestamp, the
log is accidentally truncated

* src/qemu/qemu_driver.c: Never truncate log file with shutdown
  message
2010-11-23 14:10:05 +00:00
Cole Robinson
388fa6257e qemu: setvcpus: Save config changes to disk
Currently changes to the persistent config aren't flushed to disk, meaning
they are lost if the domain is redefined or libvirtd is restarted.
2010-11-23 08:42:46 -05:00
Cole Robinson
39b6265476 qemu: setvcpus: Simplify altering the persistent config
Do this by adding a helper function to get the persistent domain config. This
should be useful for other functions that may eventually want to alter
the persistent domain config (attach/detach device). Also make similar changes
to the test drivers setvcpus command.

A caveat is that the function will return the running config for a transient
domain, rather than error. This simplifies callers, as long as they use
other methods to ensure the guest is persistent.
2010-11-23 08:42:46 -05:00
Cole Robinson
d75202915e qemu: setvcpus: Fix maxvcpus check
Doing 'virsh setvcpus $vm --config 10' doesn't check the value against the
domains maxvcpus value. A larger value for example will prevent the guest
from starting.

Also make a similar change to the test driver.
2010-11-23 08:42:46 -05:00
Cole Robinson
45ec297d6f Make state driver device hotplug/update actually transient
The current semantics of non-persistent hotplug/update are confusing: the
changes will persist as long as the in memory domain definition isn't
overwritten. This means hotplug changes stay around until the domain is
redefined or libvirtd is restarted.

Call virDomainObjSetDefTransient at VM startup, so that we properly discard
hotplug changes when the VM is shutdown.
2010-11-23 08:42:45 -05:00
Eric Blake
0d5f54bb21 maint: use gnulib configmake rather than open-coding things
* bootstrap.conf (gnulib_modules): Add configmake.
* daemon/Makefile.am (libvirtd_CFLAGS): Drop defines provided by
gnulib.
* src/Makefile.am (INCLUDES): Likewise.
* tests/Makefile.am (INCLUDES): Likewise.
* tools/Makefile.am (virsh_CFLAGS): Likewise.
* daemon/libvirtd.c (qemudInitPaths, usage, main): Update
clients.
* src/cpu/cpu_map.c (CPUMAPFILE): Likewise.
* src/driver.c (DEFAULT_DRIVER_DIR): Likewise.
* src/internal.h (_): Likewise.
* src/libvirt.c (virInitialize): Likewise.
* src/lxc/lxc_conf.h (LXC_CONFIG_DIR, LXC_STATE_DIR, LXC_LOG_DIR):
Likewise.
* src/lxc/lxc_conf.c (lxcCapsInit, lxcLoadDriverConfig):
Likewise.
* src/network/bridge_driver.c (NETWORK_PID_DIR)
(NETWORK_STATE_DIR, DNSMASQ_STATE_DIR, networkStartup): Likewise.
* src/nwfilter/nwfilter_driver.c (nwfilterDriverStartup):
Likewise.
* src/qemu/qemu_conf.c (qemudLoadDriverConfig): Likewise.
* src/qemu/qemu_driver.c (qemudStartup): Likewise.
* src/remote/remote_driver.h (LIBVIRTD_PRIV_UNIX_SOCKET)
(LIBVIRTD_PRIV_UNIX_SOCKET_RO, LIBVIRTD_CONFIGURATION_FILE)
(LIBVIRT_PKI_DIR): Likewise.
* src/secret/secret_driver.c (secretDriverStartup): Likewise.
* src/security/security_apparmor.c (VIRT_AA_HELPER): Likewise.
* src/security/virt-aa-helper.c (main): Likewise.
* src/storage/storage_backend_disk.c (PARTHELPER): Likewise.
* src/storage/storage_driver.c (storageDriverStartup): Likewise.
* src/uml/uml_driver.c (TEMPDIR, umlStartup): Likewise.
* src/util/hooks.c (LIBVIRT_HOOK_DIR): Likewise.
* tools/virsh.c (main): Likewise.
* docs/hooks.html.in: Likewise.
2010-11-17 08:58:58 -07:00
Stefan Berger
7b7cb1ecc9 deprecate fclose() and introduce VIR_{FORCE_}FCLOSE()
Similarly to deprecating close(), I am now deprecating fclose() and
introduce VIR_FORCE_FCLOSE() and VIR_FCLOSE(). Also, fdopen() is replaced with
VIR_FDOPEN().

Most of the files are opened in read-only mode, so usage of
VIR_FORCE_CLOSE() seemed appropriate. Others that are opened in write
mode already had the fclose()<  0 check and I converted those to
VIR_FCLOSE()<  0.

I did not find occurrences of possible double-closed files on the way.
2010-11-16 21:13:29 -05:00
Osier Yang
93bc093ac2 qemu: record timestamp in qemu domain log
Currently only support domain start and shutdown, for domain start,
record timestamp before the qemu command line, and for domain shutdown,
just say it's shutting down with timestamp.

* src/qemu/qemu_driver.c (qemudStartVMDaemon, qemudShutdownVMDaemon
  introduced two macros - START_POSTFIX, SHUTDOWN_POSTFIX)
2010-11-16 09:18:32 -07:00
Daniel P. Berrange
bdb28f4426 Support virDomainOpenConsole with QEMU
This provides an implementation of the virDomainOpenConsole
API with the QEMU driver. For the streams code, this reuses
most of the code previously added for the tunnelled migration
streams since it is generic.

* src/qemu/qemu_driver.c: Support virDomainOpenConsole
2010-11-11 16:03:03 +00:00
Daniel P. Berrange
7c08fcc439 Add a generic internal API for handling any FD based stream
To avoid the need for duplicating implementations of virStream
drivers, provide a generic implementation that can handle any
FD based stream. This code is copied from the existing impl
in the QEMU driver, with the locking moved into the stream
impl, and addition of a read callback

The FD stream code will refuse to operate on regular files or
block devices, since those can't report EAGAIN properly when
they would block on I/O

* include/libvirt/virterror.h, include/libvirt/virterror.h: Add
  VIR_FROM_STREAM error domain
* src/qemu/qemu_driver.c: Remove code obsoleted by the new
  generic streams driver.
* src/fdstream.h, src/fdstream.c, src/fdstream.c,
  src/libvirt_private.syms: Generic reusable FD based streams
2010-11-11 16:02:57 +00:00
Daniel P. Berrange
88a9b382c6 Introduce a virDomainOpenConsole API
To enable virsh console (or equivalent) to be used remotely
it is necessary to provide remote access to the /dev/pts/XXX
pseudo-TTY associated with the console/serial/parallel device
in the guest. The virStream API provide a bi-directional I/O
stream capability that can be used for this purpose. This
patch thus introduces a virDomainOpenConsole API that uses
the stream APIs.

* src/libvirt.c, src/libvirt_public.syms,
  include/libvirt/libvirt.h.in, src/driver.h: Define the
  new virDomainOpenConsole API
* src/esx/esx_driver.c, src/lxc/lxc_driver.c,
  src/opennebula/one_driver.c, src/openvz/openvz_driver.c,
  src/phyp/phyp_driver.c, src/qemu/qemu_driver.c,
  src/remote/remote_driver.c, src/test/test_driver.c,
  src/uml/uml_driver.c, src/vbox/vbox_tmpl.c,
  src/xen/xen_driver.c, src/xenapi/xenapi_driver.c: Stub
  API entry point
2010-11-11 16:02:41 +00:00
Cole Robinson
96d52fcf43 qemu: Add flag to force a CDROM eject
QEMU allows forcing a CDROM eject even if the guest has locked the device.
Expose this via a new UpdateDevice flag, VIR_DOMAIN_DEVICE_MODIFY_FORCE.

This has been requested for RHEV:

https://bugzilla.redhat.com/show_bug.cgi?id=626305

v2: Change flag name, bool cleanups
2010-11-10 12:31:20 -05:00
Stefan Berger
60ae1c34ad bye to close(), welcome to VIR_(FORCE_)CLOSE()
Using automated replacement with sed and editing I have now replaced all
occurrences of close() with VIR_(FORCE_)CLOSE() except for one, of
course. Some replacements were straight forward, others I needed to pay
attention. I hope I payed attention in all the right places... Please
have a look. This should have at least solved one more double-close
error.
2010-11-09 15:48:48 -05:00
Daniel P. Berrange
7a696678e5 Define XML syntax for password expiry
This extends the XML syntax for <graphics> to allow a password
expiry time to be set

eg

  <graphics type='vnc' port='5900' autoport='yes' keymap='en-us' passwd='12345' passwdValidTo='2010-04-09T15:51:00'/>

The timestamp is in UTC.

* src/conf/domain_conf.h: Pull passwd out into separate struct
  virDomainGraphicsAuthDef to allow sharing between VNC & SPICE
* src/conf/domain_conf.c: Add parsing/formatting of new passwdValidTo
  argument
* src/opennebula/one_conf.c, src/qemu/qemu_conf.c, src/qemu/qemu_driver.c,
  src/xen/xend_internal.c, src/xen/xm_internal.c: Update for changed
  struct containing VNC password
2010-11-09 11:47:13 +00:00
Daniel P. Berrange
b5c9920955 Add SPICE support for QEMU driver configuration file
In common with VNC, the QEMU driver configuration file is used
specify the host level TLS certificate location and a default
password / listen address

* src/qemu/qemu.conf: Add spice_listen, spice_tls,
  spice_tls_x509_cert_dir & spice_password config params
* src/qemu/qemu_conf.c, src/qemu/qemu_conf.h: Parsing of
  spice config parameters and updating -spice arg generation
  to use them
* tests/qemuxml2argvdata/qemuxml2argv-graphics-spice-rhel6.args,
  tests/qemuxml2argvtest.c: Expand test case to cover driver
  level configuration
2010-11-09 11:47:05 +00:00
Daniel P. Berrange
ed0d9f6c0c Support automatic port number allocation for SPICE
* src/qemu/qemu_driver.c: Allocate the TCP ports for SPICE
  before starting guest
2010-11-09 11:46:56 +00:00
Daniel Veillard
1e4c45999e Read the host sysinfo for the QEmu driver
Read and store the data when initializing the driver.
2010-11-08 15:14:50 +01:00
Matthias Bolte
b5f8691ee2 qemu: Remove redundant slash in save directory path 2010-11-05 20:06:46 +01:00
Daniel P. Berrange
a51ccaf828 Revert commit 06f81c63eb
Commit 06f81c63eb attempted to make
QEMU driver ignore the failure to relabel 'stdin_path' if it was
on NFS. The actual result was that it ignores *all* failures to
label any aspect of the VM, unless stdin_path is non-NULL and
is not on NFS.

* src/qemu/qemu_driver.c: Treat all relabel failures as terminal
2010-11-02 14:37:26 +00:00
Diego Elio Pettenò
5919afe3c6 qemu: add the USB devices to the cgroup whitelist
Make sure that the QEmu process within the cgroup can access the device
file for the USB device that has to be connected to the virtual domain.
2010-11-01 10:19:51 -06:00
KAMEZAWA Hiroyuki
f69ce3feb0 qemu: check compression program availability of virsh save and dump 2010-10-29 10:22:08 -06:00
KAMEZAWA Hiroyuki
95a17abda7 add compression support for "virsh dump"
Add dump_image_format[] to qemu.conf and support compressed dump
at virsh dump. coredump compression is important for saving disk space
in an environment where multiple guests run.

In general, "disk space for dump" is specially allocated and will be
a dead space in the system. It's used only at emergency. So, it's better
to have both of save_image_format and dump_image_format. "save" is done
in scheduled manner with enough calculated disk space for it.

This code reuses some of save_image_format[] and supports the same format.

Changelog:
 - modified libvirtd_qemu.aug
 - modified test_libvirtd_qemu.aug
 - fixed error handling of qemudSaveCompressionTypeFromString()
2010-10-29 10:04:34 -06:00
Lai Jiangshan
41b2cee2a8 qemu_driver: add virCgroupMounted
When we mount any cgroup without "-o devices", we will fail to start vms:

error: Failed to start domain vm1
error: Unable to deny all devices for vm1: No such file or directory

When we mount any cgroup without "-o cpu", we will fail to get schedinfo:
Scheduler      : posix
error: unable to get cpu shares tunable: No such file or directory

We should only use the cgroup controllers which are mounted on host.
So I add virCgroupMounted() for qemuCgroupControllerActive()

Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
2010-10-29 09:46:25 -06:00
Eric Blake
054d43f570 qemu: check for vm after starting a job
https://bugzilla.redhat.com/show_bug.cgi?id=638285 - when migrating
a guest, it was very easy to provoke a race where an application
could query block information on a VM that had just been migrated
away.  Any time qemu code obtains a job lock, it must also check
that the VM was not taken down in the time where it was waiting
for the lock.

* src/qemu/qemu_driver.c (qemudDomainSetMemory)
(qemudDomainGetInfo, qemuDomainGetBlockInfo): Check that vm still
exists after obtaining job lock, before starting monitor action.
2010-10-28 08:56:03 -06:00
Daniel P. Berrange
8dc136b5fc Add disk/net resource auditing to QEMU driver
Add auditing of all initial disk/net assignments to QEMU guests
at startup. Add auditing for all hotplug & unplug events and
disk media changes.

* src/qemu/qemu_driver.c: Add disk/net resource auditing
2010-10-27 17:03:22 +01:00
Daniel P. Berrange
160b5479f2 Add auditing of security label in QEMU driver
Add auditing of the allocated security label in the QEMU driver
VM startup code

* src/qemu/qemu_driver.c: Audit security label
2010-10-27 17:03:22 +01:00
Daniel P. Berrange
62622f841a Add auditing of start/stop events to the QEMU driver
Add audit hooks to report all start and stop events on QEMU
guest domains.

* src/qemu/qemu_driver.c: Audit start/stop events
2010-10-27 17:03:21 +01:00
Daniel P. Berrange
43e7e8f614 Remove all auditing hooks from libvirtd dispatch code
Revert most of commit a8b5f9bd27.
The audit hooks will be re-added directly in the QEMU driver code
in a future commit

* daemon/remote.c: Remove all audit logging hooks
* src/qemu/qemu_driver.c: Remove all audit logging hooks
2010-10-27 17:03:21 +01:00
Matthias Bolte
a1109a7c7c qemu: Exit on first error in qemuDomainGetMemoryParameters
There is no point in trying to fill params beyond the first error,
because when qemuDomainGetMemoryParameters returns -1 then the caller
cannot detect which values in params are valid.
2010-10-20 19:33:11 +02:00
Matthias Bolte
916f95b7aa Rename VIR_DOMAIN_SWAP_HARD_LIMIT to VIR_DOMAIN_MEMORY_SWAP_HARD_LIMIT
To get them under the common VIR_DOMAIN_MEMORY_* prefix.
2010-10-20 19:33:11 +02:00
Miloslav Trmač
a8b5f9bd27 Audit VM start/stop/suspend/resume
Most operations are audited at the libvirtd level; auditing in
src/libvirt.c would result in two audit entries per operation (one in
the client, one in libvirtd).

The only exception is a domain stopping of its own will (e.g. because
the user clicks on "shutdown" inside the interface).  There can often be
no client connected at the time the domain stops, so libvirtd does not
have any virConnectPtr object on which to attach an event watch.  This
patch therefore adds auditing directly inside the qemu driver (other
drivers are not supported).
2010-10-19 17:31:31 +01:00
Eric Blake
28a3605906 vcpu: complete vcpu support in qemu driver
* src/qemu/qemu_driver.c (qemudDomainSetVcpusFlags)
(qemudDomainGetVcpusFlags): Support all feasible flag
combinations.
2010-10-19 10:06:38 -06:00
Eric Blake
4617eedfae vcpu: support maxvcpu in domain_conf
Although this patch adds a distinction between maximum vcpus and
current vcpus in the XML, the values should be identical for all
drivers at this point.  Only in subsequent per-driver patches will
a distinction be made.

In general, virDomainGetInfo should prefer the current vcpus.

* src/conf/domain_conf.h (_virDomainDef): Adjust vcpus to unsigned
short, to match virDomainGetInfo limit.  Add maxvcpus member.
* src/conf/domain_conf.c (virDomainDefParseXML)
(virDomainDefFormat): parse and print out vcpu details.
* src/xen/xend_internal.c (xenDaemonParseSxpr)
(xenDaemonFormatSxpr): Manage both vcpu numbers, and require them
to be equal for now.
* src/xen/xm_internal.c (xenXMDomainConfigParse)
(xenXMDomainConfigFormat): Likewise.
* src/phyp/phyp_driver.c (phypDomainDumpXML): Likewise.
* src/openvz/openvz_conf.c (openvzLoadDomains): Likewise.
* src/openvz/openvz_driver.c (openvzDomainDefineXML)
(openvzDomainCreateXML, openvzDomainSetVcpusInternal): Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainDumpXML, vboxDomainDefineXML):
Likewise.
* src/xenapi/xenapi_driver.c (xenapiDomainDumpXML): Likewise.
* src/xenapi/xenapi_utils.c (createVMRecordFromXml): Likewise.
* src/esx/esx_vmx.c (esxVMX_ParseConfig, esxVMX_FormatConfig):
Likewise.
* src/qemu/qemu_conf.c (qemuBuildSmpArgStr)
(qemuParseCommandLineSmp, qemuParseCommandLine): Likewise.
* src/qemu/qemu_driver.c (qemudDomainHotplugVcpus): Likewise.
* src/opennebula/one_conf.c (xmlOneTemplate): Likewise.
2010-10-19 10:05:51 -06:00
Eric Blake
50c51f13e2 vcpu: make old API trivially wrap to new API
Note - this wrapping is completely mechanical; the old API will
function identically, since the new API validates that the exact
same flags are provided by the old API.  On a per-driver basis,
it may make sense to have the old API pass a different set of flags,
but that should be done in the per-driver patch that implements
the full range of flag support in the new API.

* src/esx/esx_driver.c (esxDomainSetVcpus, escDomainGetMaxVpcus):
Move guts...
(esxDomainSetVcpusFlags, esxDomainGetVcpusFlags): ...to new
functions.
(esxDriver): Trivially support the new API.
* src/openvz/openvz_driver.c (openvzDomainSetVcpus)
(openvzDomainSetVcpusFlags, openvzDomainGetMaxVcpus)
(openvzDomainGetVcpusFlags, openvzDriver): Likewise.
* src/phyp/phyp_driver.c (phypDomainSetCPU)
(phypDomainSetVcpusFlags, phypGetLparCPUMAX)
(phypDomainGetVcpusFlags, phypDriver): Likewise.
* src/qemu/qemu_driver.c (qemudDomainSetVcpus)
(qemudDomainSetVcpusFlags, qemudDomainGetMaxVcpus)
(qemudDomainGetVcpusFlags, qemuDriver): Likewise.
* src/test/test_driver.c (testSetVcpus, testDomainSetVcpusFlags)
(testDomainGetMaxVcpus, testDomainGetVcpusFlags, testDriver):
Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainSetVcpus)
(vboxDomainSetVcpusFlags, virDomainGetMaxVcpus)
(virDomainGetVcpusFlags, virDriver): Likewise.
* src/xen/xen_driver.c (xenUnifiedDomainSetVcpus)
(xenUnifiedDomainSetVcpusFlags, xenUnifiedDomainGetMaxVcpus)
(xenUnifiedDomainGetVcpusFlags, xenUnifiedDriver): Likewise.
* src/xenapi/xenapi_driver.c (xenapiDomainSetVcpus)
(xenapiDomainSetVcpusFlags, xenapiDomainGetMaxVcpus)
(xenapiDomainGetVcpusFlags, xenapiDriver): Likewise.
(xenapiError): New helper macro.
2010-10-19 10:03:33 -06:00
Eric Blake
dd255d6405 vcpu: define internal driver API
* src/driver.h (virDrvDomainSetVcpusFlags)
(virDrvDomainGetVcpusFlags): New typedefs.
(_virDriver): New callback members.
* src/esx/esx_driver.c (esxDriver): Add stub for driver.
* src/lxc/lxc_driver.c (lxcDriver): Likewise.
* src/opennebula/one_driver.c (oneDriver): Likewise.
* src/openvz/openvz_driver.c (openvzDriver): Likewise.
* src/phyp/phyp_driver.c (phypDriver): Likewise.
* src/qemu/qemu_driver.c (qemuDriver): Likewise.
* src/remote/remote_driver.c (remote_driver): Likewise.
* src/test/test_driver.c (testDriver): Likewise.
* src/uml/uml_driver.c (umlDriver): Likewise.
* src/vbox/vbox_tmpl.c (Driver): Likewise.
* src/xen/xen_driver.c (xenUnifiedDriver): Likewise.
* src/xenapi/xenapi_driver.c (xenapiDriver): Likewise.
2010-10-19 10:00:47 -06:00
Dan Kenigsberg
b2c9a87940 root_squash: virFileOperation may fail with EPERM too
Over root-squashing nfs, when virFileOperation() is called as uid==0,
it may fail with EACCES, but also with EPERM, due to
virFileOperationNoFork()'s failed attemp to chown a writable file.

qemudDomainSaveFlag() should expect this case, too.
2010-10-19 15:26:32 +02:00
Dan Kenigsberg
b7bd75c4c0 Run initgroups() in qemudOpenAsUID()
qemudOpenAsUID is intended to open a file with the credentials of a
specified uid. Current implementation fails if the file is accessible to
one of uid's groups but not owned by uid.

This patch replaces the supplementary group list that the child process
inherited from libvirtd with the default group list of uid.
2010-10-19 15:22:57 +02:00
Laine Stump
d3fec47f81 Fix warning about a non-literal format string in qemu_driver.c 2010-10-15 11:34:38 -04:00
Jiri Denemark
f93924f465 qemu: Prohibit migration of guests with host devices
Explicitly raising a nice error in the case user tries to migrate a
guest with assigned host devices is much better than waiting for a
mysterious error with no clue for the reason.
2010-10-14 09:36:54 +02:00
Stefan Berger
4435f3c477 nwfilter: resolve deadlock between VM ops and filter update
This is from a bug report and conversation on IRC where Soren reported that while a filter update is occurring on one or more VMs (due to a rule having been edited for example), a deadlock can occur when a VM referencing a filter is started.

The problem is caused by the two locking sequences of

qemu driver, qemu domain, filter             # for the VM start operation
filter, qemu_driver, qemu_domain            # for the filter update operation

that obviously don't lock in the same order. The problem is the 2nd lock sequence. Here the qemu_driver lock is being grabbed in qemu_driver:qemudVMFilterRebuild()

The following solution is based on the idea of trying to re-arrange the 2nd sequence of locks as follows:

qemu_driver, filter, qemu_driver, qemu_domain

and making the qemu driver recursively lockable so that a second lock can occur, this would then lead to the following net-locking sequence

qemu_driver, filter, qemu_domain

where the 2nd qemu_driver lock has been ( logically ) eliminated.

The 2nd part of the idea is that the sequence of locks (filter, qemu_domain) and (qemu_domain, filter) becomes interchangeable if all code paths where filter AND qemu_domain are locked have a preceding qemu_domain lock that basically blocks their concurrent execution

So, the following code paths exist towards qemu_driver:qemudVMFilterRebuild where we now want to put a qemu_driver lock in front of the filter lock.

-> nwfilterUndefine()   [ locks the filter ]
    -> virNWFilterTestUnassignDef()
        -> virNWFilterTriggerVMFilterRebuild()
            -> qemudVMFilterRebuild()

-> nwfilterDefine()
    -> virNWFilterPoolAssignDef() [ locks the filter ]
        -> virNWFilterTriggerVMFilterRebuild()
            -> qemudVMFilterRebuild()

-> nwfilterDriverReload()
    -> virNWFilterPoolLoadAllConfigs()
        ->virNWFilterPoolObjLoad()
            -> virNWFilterPoolAssignDef() [ locks the filter ]
                -> virNWFilterTriggerVMFilterRebuild()
                    -> qemudVMFilterRebuild()

-> nwfilterDriverStartup()
    -> virNWFilterPoolLoadAllConfigs()
        ->virNWFilterPoolObjLoad()
            -> virNWFilterPoolAssignDef() [ locks the filter ]
                -> virNWFilterTriggerVMFilterRebuild()
                    -> qemudVMFilterRebuild()

Qemu is not the only driver using the nwfilter driver, but also the UML driver calls into it. Therefore qemuVMFilterRebuild() can be exchanged with umlVMFilterRebuild() along with the driver lock of qemu_driver that can now be a uml_driver. Further, since UML and Qemu domains can be running on the same machine, the triggering of a rebuild of the filter can touch both types of drivers and their domains.

In the patch below I am now extending each nwfilter callback driver with functions for locking and unlocking the (VM) driver (UML, QEMU) and introduce new functions for locking all registered callback drivers and unlocking them. Then I am distributing the lock-all-cbdrivers/unlock-all-cbdrivers call into the above call paths. The last shown callpath starting with nwfilterDriverStart() is problematic since it is initialize before the Qemu and UML drives are and thus a lock in the path would result in a NULL pointer attempted to be locked -- the call to virNWFilterTriggerVMFilterRebuild() is never called, so we never lock either the qemu_driver or the uml_driver in that path. Therefore, only the first 3 paths now receive calls to lock and unlock all callback drivers. Now that the locks are distributed where it matters I can remove the qemu_driver and uml_driver lock from qemudVMFilterRebuild() and umlVMFilterRebuild() and not requiring the recursive locks.

For now I want to put this out as an RFC patch. I have tested it by 'stretching' the critical section after the define/undefine functions each lock the filter so I can (easily) concurrently execute another VM operation (suspend,start). That code is in this patch and if you want you can de-activate it. It seems to work ok and operations are being blocked while the update is being done.
I still also want to verify the other assumption above that locking filter and qemu_domain always has a preceding qemu_driver lock.
2010-10-13 10:33:26 -04:00
Nikunj A. Dadhania
261ad74e52 Adding memtunables to qemuSetupCgroup
QEmu startup will pick up the memory tunables specified in the domain
configuration file
2010-10-12 19:26:09 +02:00
Nikunj A. Dadhania
013fe4b848 Implement domainGetMemoryParamters for QEmu
Driver interface for getting memory parameters, eg. hard_limit,
soft_limit and swap_hard_limit based on cgroup support
2010-10-12 19:26:09 +02:00
Nikunj A. Dadhania
71d0b4275d Implement domainSetMemoryParamters for QEmu
Driver interface for setting memory hard_limit, soft_limit and swap
hard_limit based on cgroup support
2010-10-12 19:26:09 +02:00
Nikunj A. Dadhania
d390fce413 XML parsing for memory tunables
Adding parsing code for memory tunables in the domain xml file
also change the internal define structures used for domain memory
informations
Adds a new specific test
2010-10-12 19:26:09 +02:00
Nikunj A. Dadhania
0cd7823271 Adding virDomainSetMemoryParameters and virDomainGetMemoryParameters API
Public api to set/get memory tunables supported by the hypervisors.

dv:
* some cleanups in libvirt.c
* adding extra checks in libvirt.c new entry points

v4:
* Move exporting public API to this patch
* Add unsigned int flags to the public api for future extensions

v3:
* Add domainGetMemoryParamters and NULL in all the driver interface

v2:
* Initialize domainSetMemoryParameters to NULL in all the driver
  interface structure.
2010-10-12 19:26:09 +02:00
Soren Hansen
efe4e210b8 Rename qemudShrinkDisks to virDomainDiskRemove and move to domain_conf.c
Other drivers will need this same functionality, so move it to up to
conf/domain_conf.c and give it a more general name.

Signed-off-by: Soren Hansen <soren@linux2go.dk>
2010-08-24 20:17:48 +02:00
Eric Blake
4b93002358 build: delete dead comments
* src/qemu/qemu_driver.c (qemudGetProcessInfo): Clean up.
* src/uml/uml_driver.c (umlGetProcessInfo): Likewise.
* src/xen/sexpr.c (_string2sexpr): Likewise.
2010-08-19 16:09:46 -06:00
Chris Lalancette
4303c91cc3 Fix up qemu domain save/managed save locking.
The current version of the qemu managed save implementation
is subject to a race where the domain shuts down between
the time that we start the command and the time that we
actually try to do the save.  Close this race by making
qemuDomainSaveFlags() expect both the driver and the passed-in
vm object to be locked before executing.

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-08-17 16:18:49 -04:00
Jiri Denemark
0a5f3ae0c6 qemu: Fix copy&paste error in warning message
This also makes the message consistent with the message used in error
path of qemudDomainAttachHostPciDevice.
2010-08-16 21:37:13 +02:00
Jiri Denemark
5afec51730 qemu: Release PCI slot when detaching disk and net devices 2010-08-16 21:36:59 +02:00
Jiri Denemark
4f86613ba1 qemu: Re-reserve all PCI addresses on libvirtd restart
When reconnecting to existing VMs, we re-reserved only those PCI
addresses which were explicitly mentioned in domain XML. Since some
addresses are always reserved (e.g., 0:0:0 and 0:0:1), we need to handle
those too.

Also all this should only be done if device flag is supported by qemu.
2010-08-16 21:36:53 +02:00
Stefan Berger
cf6f8b9a97 nwfilter: extend nwfilter reload support
In this patch I am extending and fixing the nwfilter module's reload support to stop all ongoing threads (for learning IP addresses of interfaces) and rebuild the filtering rules of all interfaces of all VMs when libvirt is started. Now libvirtd rebuilds the filters upon the SIGHUP signal and libvirtd restart.

About the patch: The nwfilter functions require a virConnectPtr. Therefore I am opening a connection in qemudStartup, which later on needs to be closed outside where the driver lock is held since otherwise it ends up in a deadlock due to virConnectClose() trying to lock the driver as well.

I have tested this now for a while with several machines running and needing the IP address learner thread(s). The rebuilding of the firewall rules seems to work fine following libvirtd restart or a SIGHUP. Also the termination of libvirtd worked fine.
2010-08-16 12:59:54 -04:00
Chris Lalancette
e80f1a7e3f Move the tunnelled migration unix socket to /var/lib/libvirt/qemu
Since the qemu process is running as qemu:qemu, it can't actually
look at the unix socket in /var/run/libvirt/qemu which is owned by
root and has permission 700.  Move the unix socket to
/var/lib/libvirt/qemu, which is already owned by qemu:qemu.

Thanks to Justin Clift for test this out for me.

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-08-13 08:39:53 -04:00
Chris Lalancette
a2f0b6b81d Fix tunnelled migration with qemu running as qemu:qemu.
The problem is that on the source of the migration, libvirtd
is responsible for creating the unix socket over which the data
will flow.  Since libvirtd is running as root, this file will
be created as root.  When the qemu process running as qemu:qemu
goes to access the unix file to write data to it, it will get
permission denied and fail.  Make sure to change the owner
of the unix file to qemu:qemu.

Thanks to Justin Clift for testing this patch out for me.

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-08-13 08:39:46 -04:00
Daniel Veillard
986c208695 qemu: avoid calling the balloon info command if disabled
Basically a followup of the previous patch about balloon desactivation
if desactivated, to not ask for balloon information to qemu as we will
just get an error back.
 This can make a huge difference in the time needed for domain
information or list when a machine is loaded, and balloon has been
desactivated in the guests.

* src/qemu/qemu_driver.c: do not get the balloon info if the balloon
  suppor is disabled
2010-08-12 18:32:16 +02:00
Jiri Denemark
d1e5676c0d qemu: Hack around asynchronous device_del
device_del command is not synchronous for PCI devices, it merely asks
the guest to release the device and returns. If the host wants to use
that device before the guest actually releases it, we are in big
trouble. To avoid this, we already added a loop which waits up to 10
seconds until the device is actually released before we do anything else
with that device. But we only added this loop for managed PCI devices
before we try reattach them back to the host.

However, we need to wait even for non-managed devices. We don't reattach
them automatically, but we still want to prevent the host from using it.
This was revealed thanks to sVirt: when we relabel sysfs files
corresponding to the PCI device before the guest finished releasing the
device, qemu is no longer allowed to access those files and if it wants
(as a result of guest's request) to write anything to them, it just
exits, which kills the guest.

This is not a proper fix and needs some further work both on libvirt and
qemu side in the future.
2010-08-10 16:59:49 +02:00
Eric Blake
6790805d6e qemu: don't lose error on setting monitor capabilities
Spotted by clang.  Regression introduced in commit e72cc3c11d.

* src/qemu/qemu_driver.c (qemuConnectMonitor): Don't lose error status.
2010-08-02 14:16:10 -06:00
Eric Blake
68e4be71be qemu: kill some dead stores
Spotted by clang.

* src/qemu/qemu_monitor.c (qemuMonitorClose): Kill dead store.
* src/qemu/qemu_driver.c (qemudDomainSaveImageStartVM): Likewise.
2010-07-30 11:33:26 -06:00
Chris Lalancette
56b408231a Fix a potential race in pciInitDevice.
If detecting the FLR flag of a pci device fails, then we
could run into the situation of trying to close a file
descriptor twice, once in pciInitDevice() and once in pciFreeDevice().
Fix that by removing the pciCloseConfig() in pciInitDevice() and
just letting pciFreeDevice() handle it.

Thanks to Chris Wright for pointing out this problem.

While we are at it, fix an error check.  While it would actually
work as-is (since success returns 0), it's still more clear to
check for < 0 (as the rest of the code does).

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-29 10:18:23 -04:00
Cole Robinson
82b6d7600e qemu: virtio console support
Enable specifying a virtio console device with:

<console type='pty'>
  <target type='virtio'/>
</console>
2010-07-28 16:48:00 -04:00
Cole Robinson
50147933a5 domain conf: Rename character prop targetType -> deviceType
There is actually a difference between the character device type (serial,
parallel, channel, ...) and the target type (virtio, guestfwd). Currently
they are awkwardly conflated.

Start to pull them apart by renaming targetType -> deviceType. This is
an entirely mechanical change.

Signed-off-by: Cole Robinson <crobinso@redhat.com>
2010-07-28 16:47:57 -04:00
Chris Lalancette
8bb0cd14e7 Fix up confusing indentation in qemudDomainAttachHostPciDevice.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-28 09:47:47 -04:00
Chris Wright
46bcdb960d pciResetDevice: use inactive devices to determine safe reset
When doing a PCI secondary bus reset, we must be sure that there are no
active devices on the same bus segment.  The active device tracking is
designed to only track host devices that are active in use by guests.
This ignores host devices that are actively in use by the host.  So the
current logic will reset host devices.

Switch this logic around and allow sbus reset when we are assigning all
devices behind a bridge to the same guest at guest startup or as a result
of a single attach-device command.

* src/util/pci.h: change signature of pciResetDevice to add an
  inactive devices list
* src/qemu/qemu_driver.c src/xen/xen_driver.c: use (or not) the new
  functionality of pciResetDevice() depending on the place of use
* src/util/pci.c: implement the interface and logic changes
2010-07-26 18:43:04 +02:00
Chris Wright
042b208370 qemudDomainAttachHostPciDevice refactor to use new helpers
- src/qemu/qemu_driver.c: Eliminate code duplication by using the new
  helpers qemuPrepareHostdevPCIDevices and qemuDomainReAttachHostdevDevices.
  This reduces the number of open coded calls to pciResetDevice.
2010-07-26 18:34:24 +02:00
Chris Wright
f1365b558d Add helpers qemuPrepareHostdevPCIDevice and qemuDomainReAttachHostdevDevices
- src/qemu/qemu_driver.c: These new helpers take hostdev list and count
  directly rather than getting them indirectly from domain definition.
  This will allow reuse for the attach-device case.
2010-07-26 18:23:17 +02:00
Chris Wright
8bd00c0edf qemuGetPciHostDeviceList take hostdev list directly
- src/qemu/qemu_driver.c: Update qemuGetPciHostDeviceList to take a
  hostdev list and count directly, rather than getting this indirectly
  from domain definition. This will allow reuse for the attach-device case.
2010-07-26 18:17:20 +02:00
Chris Lalancette
a71be01f04 Add tests for the new Qemu namespace XML.
Thanks to DV for knocking together the Relax-NG changes
quickly for me.

Changes since v1:
 - Change the domain.rng to correspond to the new schema
 - Don't allocate caps->ns in testQemuCapsInit since it is a static table

Changes since v2:
 - Change domain.rng to add restrictions on allowed environment names

Changes since v3:
 - Remove a bogus comment in the tests

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-23 17:30:45 -04:00
Chris Lalancette
057e855324 Qemu arbitrary monitor commands.
Implement the qemu driver's virDomainQemuMonitorCommand
and hook it into the API entry point.

Changes since v1:
 - Rename the (external) qemuMonitorCommand to qemuDomainMonitorCommand
 - Add virCheckFlags to qemuDomainMonitorCommand

Changes since v2:
 - Drop ATTRIBUTE_UNUSED from the flags

Changes since v3:
 - Add a flag to priv so we only print out monitor command warning once.  Note
   that this has not been plumbed into qemuDomainObjPrivateXMLFormat or
   qemuDomainObjPrivateXMLParse, which means that if you run a monitor command,
   restart libvirtd, and then run another monitor command, you may get an
   an erroneous VIR_INFO.  It's a pretty minor matter, and I didn't think it
   warranted the additional code.
 - Add BeginJob/EndJob calls around EnterMonitor/ExitMonitor

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-23 17:30:24 -04:00
Chris Lalancette
21adf03c2d Qemu Monitor API entry point.
Add the library entry point for the new virDomainQemuMonitorCommand()
entry point.  Because this is not part of the "normal" libvirt API,
it gets its own header file, library file, and will eventually
get its own over-the-wire protocol later in the series.

Changes since v1:
 - Go back to using the virDriver table for qemuDomainMonitorCommand, due to
   linking issues
 - Added versioning information to the libvirt-qemu.so

Changes since v2:
 - None

Changes since v3:
 - Add LGPL header to libvirt-qemu.c
 - Make virLibConnError and virLibDomainError macros instead of function calls

Changes since v4:
 - Move exported symbols to libvirt_qemu.syms

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-23 17:30:14 -04:00
Chris Lalancette
869939a543 Qemu arbitrary command-line arguments.
Implement the qemu hooks for XML namespace data.  This
allows us to specify a qemu XML namespace, and then
specify:

<qemu:commandline>
 <qemu:arg value='arg'/>
 <qemu:env name='name' value='value'/>
</qemu:commandline>

In the domain XML.

Changes since v1:
 - Change the <qemu:arg>arg</qemu:arg> XML to <qemu:arg value='arg'/> XML
 - Fix up some memory leaks in qemuDomainDefNamespaceParse
 - Rename num_extra and extra to num_args and args, respectively
 - Fixed up some error messages
 - Make sure to escape user-provided data in qemuDomainDefNamespaceFormatXML

Changes since v2:
 - Add checking to ensure environment variable names are valid
 - Invert the logic in qemuDomainDefNamespaceFormatXML to return early

Changes since v3:
 - Change strspn() to c_isalpha() check of first letter of environment variable

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-23 17:29:59 -04:00
Laine Stump
2ad04f7853 Change virFileOperation to return -errno (ie < 0) on error.
virFileOperation previously returned 0 on success, or the value of
errno on failure. Although there are other functions in libvirt that
use this convention, the preferred (and more common) convention is to
return 0 on success and -errno (or simply -1 in some cases) on
failure. This way the check for failure is always (ret < 0).

* src/util/util.c - change virFileOperation and virFileOperationNoFork to
                    return -errno on failure.

* src/storage/storage_backend.c, src/qemu/qemu_driver.c
  - change the hook functions passed to virFileOperation to return
    -errno on failure.
2010-07-21 14:32:35 -04:00
Daniel P. Berrange
b2f1863533 Explicitly represent balloon device in XML and handle PCI address
To allow compatibility with older QEMU PCI device slot assignment
it is necessary to explicitly track the balloon device in the
XML. This introduces a new device

   <memballoon model='virtio|xen'/>

It can also have a PCI address, auto-assigned if necessary.

The memballoon will be automatically added to all Xen and QEMU
guests by default.

* docs/schemas/domain.rng: Add <memballoon> element
* src/conf/domain_conf.c, src/conf/domain_conf.h: parsing
  and formatting for memballoon device. Always add a memory
  balloon device to Xen/QEMU if none exists in XML
* src/libvirt_private.syms: Export memballoon model APIs
* src/qemu/qemu_conf.c, src/qemu/qemu_conf.h: Honour the
  PCI device address in memory balloon device
* tests/*: Update to test new functionality
2010-07-21 11:33:11 +01:00
Daniel P. Berrange
021251bd7d Remove inappropriate use of VIR_ERR_NO_SUPPORT
The VIR_ERR_NO_SUPPORT refers to an API which is not implemented.
There is a separate VIR_ERR_CONFIG_UNSUPPORTED for XML config
options that are not available with the current hypervisor.

* src/qemu/qemu_conf.c, src/qemu/qemu_driver.c: Remove
  many VIR_ERR_NO_SUPPORT replace with VIR_ERR_CONFIG_UNSUPPORTED
2010-07-21 11:30:26 +01:00
Chris Lalancette
f0c8e1cb37 Fix a deadlock in bi-directional p2p concurrent migration.
If you try to execute two concurrent migrations p2p
from A->B and B->A, the two libvirtd's will deadlock
trying to perform the migrations.  The reason for this is
that in p2p migration, the libvirtd's are responsible for
making the RPC Prepare, Migrate, and Finish calls.  However,
they are currently holding the driver lock while doing so,
which basically guarantees deadlock in this scenario.

This patch fixes the situation by adding
qemuDomainObjEnterRemoteWithDriver and
qemuDomainObjExitRemoteWithDriver helper methods.  The Enter
take an additional object reference, then drops both the
domain object lock and the driver lock.  The Exit takes
both the driver and domain object lock, then drops the
reference.  Adding calls to these Enter and Exit helpers
around remote calls in the various migration methods
seems to fix the problem for me in testing.

This should make the situation safe. The additional domain
object reference ensures that the domain object won't disappear
while this operation is happening.  The BeginJob that is called
inside of qemudDomainMigratePerform ensures that we can't execute a
second migrate (or shutdown, or save, etc) job while the
migration is active.  Finally, the additional check on the state
of the vm after we reacquire the locks ensures that we can't
be surprised by an external event (domain crash, etc).

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-07-20 09:52:52 -04:00
Daniel P. Berrange
03ca42046a Add ability to set a default driver name/type when parsing disks
Record a default driver name/type in capabilities struct. Use this
when parsing disks if value is not set in XML config.

* src/conf/capabilities.h: Record default driver name/type for disks
* src/conf/domain_conf.c: Fallback to default driver name/type
  when parsing disks
* src/qemu/qemu_driver.c: Set default driver name/type to raw
2010-07-19 18:25:14 +01:00
Daniel P. Berrange
68719c4bdd Disable all disk probing in QEMU driver & add config option to re-enable
Disk format probing is now disabled by default. A new config
option in /etc/qemu/qemu.conf will re-enable it for existing
deployments where this causes trouble
2010-07-19 18:25:13 +01:00
Daniel P. Berrange
f70e080962 Pass security driver object into all security driver callbacks
The implementation of security driver callbacks often needs
to access the security driver object. Currently only a handful
of callbacks include the driver object as a parameter. Later
patches require this is many more places.

* src/qemu/qemu_driver.c: Pass in the security driver object
  to all callbacks
* src/qemu/qemu_security_dac.c, src/qemu/qemu_security_stacked.c,
  src/security/security_apparmor.c, src/security/security_driver.h,
  src/security/security_selinux.c: Add a virSecurityDriverPtr
  param to all security callbacks
2010-07-19 18:25:13 +01:00
Daniel P. Berrange
a885334499 Convert all disk backing store loops to shared helper API
Update the QEMU cgroups code, QEMU DAC security driver, SELinux
and AppArmour security drivers over to use the shared helper API
virDomainDiskDefForeachPath().

* src/qemu/qemu_driver.c, src/qemu/qemu_security_dac.c,
  src/security/security_selinux.c, src/security/virt-aa-helper.c:
  Convert over to use virDomainDiskDefForeachPath()
2010-07-19 18:25:13 +01:00
Daniel P. Berrange
bf80fc68ca Require format to be passed into virStorageFileGetMetadata
Require the disk image to be passed into virStorageFileGetMetadata.
If this is set to VIR_STORAGE_FILE_AUTO, then the format will be
resolved using probing. This makes it easier to control when
probing will be used

* src/qemu/qemu_driver.c, src/qemu/qemu_security_dac.c,
  src/security/security_selinux.c, src/security/virt-aa-helper.c:
  Set VIR_STORAGE_FILE_AUTO when calling virStorageFileGetMetadata.
* src/storage/storage_backend_fs.c: Probe for disk format before
  calling virStorageFileGetMetadata.
* src/util/storage_file.h, src/util/storage_file.c: Remove format
  from virStorageFileMeta struct & require it to be passed into
  method.
2010-07-19 18:25:04 +01:00
Jim Meyering
c1fd7d7b3e qemuConnectMonitor: fix a bug that would have masked SELinux failure
* src/qemu/qemu_driver.c (qemuConnectMonitor): Correct erroneous
parenthesization in two expressions.  Without this fix, failure
to set or clear SELinux security context in the monitor would go
undiagnosed.  Also correct a diagnostic and split some long lines.
2010-07-14 12:42:59 -05:00
Chris Lalancette
ec75b0cf59 Fix crash when detaching devices from qemu domains.
Make sure to *not* call qemuDomainPCIAddressReleaseAddr if
QEMUD_CMD_FLAG_DEVICE is *not* set (for older qemu).  This
prevents a crash when trying to do device detachment from
a qemu guest.

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-06-29 10:40:20 -04:00
Chris Lalancette
53a1db4dfc Check for active PCI devices when doing nodedevice operations.
In the current libvirt PCI code, there is no checking whether
a PCI device is in use by a guest when doing node device
detach or reattach.  This causes problems when a device is
assigned to a guest, and the administrator starts issuing
nodedevice commands.  Make it so that we check the list
of active devices when trying to detach/reattach, and only
allow the operation if the device is not assigned to a guest.

Signed-off-by: Chris Lalancette <clalance@redhat.com>
2010-06-29 10:40:00 -04:00
Laine Stump
11a7060250 Avoid calling virStorageFileIsSharedFS with NULL
This code was just recently added (by me) and didn't account for the
fact that stdin_path is sometimes NULL. If it's NULL, and
SetSecurityAllLabel fails, a segfault would result.
2010-06-28 23:52:04 -04:00
Laine Stump
06f81c63eb Selectively ignore domainSetSecurityAllLabel failure in domain restore
When the saved domain image is on an NFS share, at least some part of
domainSetSecurityAllLabel will fail (for example, selinux labels can't
be modified). To allow domain restore to still work in this case, just
ignore the errors.
2010-06-28 11:56:02 -04:00