Commit Graph

1463 Commits

Author SHA1 Message Date
Peter Krempa
f569b87f51 snapshot: qemu: Add support for external checkpoints
This patch adds support to take external system checkpoints.

The functionality is layered on top of the previous disk-only snapshot
code. When the checkpoint is requested the domain memory is saved to the
memory image file using migration to file. (The user may specify to
take the memory image while the guest is live with the
VIR_DOMAIN_SNAPSHOT_CREATE_LIVE flag.)

The memory save image shares format with the image created by
virDomainSave() API.
2012-11-04 16:53:32 +01:00
Peter Krempa
b5fd404471 snapshot: qemu: Rename qemuDomainSnapshotCreateActive
Before now, libvirt supported only internal snapshots for active guests.
This patch renames this function to qemuDomainSnapshotCreateActiveInternal
to prepare the grounds for external active snapshots.
2012-11-03 15:06:09 +01:00
Peter Krempa
2771f8b74c qemu: Split out domain memory saving code to allow reuse
The code that saves domain memory by migration to file can be reused
while doing external checkpoints of a machine. This patch extracts the
common code and places it in a separate function.
2012-11-03 11:49:41 +01:00
Peter Krempa
ec69ca14f9 qemu: Clean up snapshot retrieval to use the new helper
Two other places were left with the old code to look up snapshots.
Change them to use the snapshot lookup helper.
2012-11-03 11:26:39 +01:00
Peter Krempa
d0fc6dc831 qemu: Fix possible race when pausing guest
When pausing the guest while migration is running (to speed up
convergence) the virDomainSuspend API checks if the migration job is
active before entering the job. This could cause a possible race if the
virDomainSuspend is called while the job is active but ends before the
Suspend API enters the job (this would require that the migration is
aborted). This would cause a incorrect event to be emitted.
2012-11-02 20:18:46 +01:00
Eric Blake
de76cae971 snapshot: merge pre-snapshot checks
Both system checkpoint snapshots and disk snapshots were iterating
over all disks, doing a final sanity check before doing any work.
But since future patches will allow offline snapshots to be either
external or internal, it makes sense to share the pass over all
disks, and then relax restrictions in that pass as new modes are
implemented.  Future patches can then handle external disks when
the domain is offline, then handle offline --disk-snapshot, and
finally, combine with migration to file to gain a complete external
system checkpoint snapshot of an active domain without using 'savevm'.

* src/qemu/qemu_driver.c (qemuDomainSnapshotDiskPrepare)
(qemuDomainSnapshotIsAllowed): Merge...
(qemuDomainSnapshotPrepare): ...into one function.
(qemuDomainSnapshotCreateXML): Update caller.
2012-11-02 10:19:03 -06:00
Eric Blake
e260e401a5 snapshot: populate new XML info for qemu snapshots
Now that the XML supports listing internal snapshots, it is worth
always populating the <memory> and <disks> element to match.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Always
parse disk info and set memory info.
2012-11-02 10:11:50 -06:00
Daniel P. Berrange
1c04f99970 Remove spurious whitespace between function name & open brackets
The libvirt coding standard is to use 'function(...args...)'
instead of 'function (...args...)'. A non-trivial number of
places did not follow this rule and are fixed in this patch.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-11-02 13:36:49 +00:00
Guannan Ren
1851a0c864 qemu: use default machine type if missing it in qemu command line
BZ:https://bugzilla.redhat.com/show_bug.cgi?id=871273
when using virsh qemu-attach to attach an existing qemu process,
if it misses the -M option in qemu command line, libvirtd crashed
because the NULL value of def->os.machine in later use.

Example:
/usr/libexec/qemu-kvm -name foo \
                      -cdrom /var/lib/libvirt/images/boot.img \
                      -monitor unix:/tmp/demo,server,nowait \

error: End of file while reading data: Input/output error
error: Failed to reconnect to the hypervisor

This patch tries to set default machine type if the value of
def->os.machine is still NULL after qemu command line parsing.
2012-11-02 12:55:29 +08:00
Eric Blake
4dbd6e9654 build: prefer mkostemp for multi-thread safety
https://bugzilla.redhat.com/show_bug.cgi?id=871756

Commit cd1e8d1 assumed that systems new enough to have journald
also have mkostemp; but this is not true for uclibc.

For that matter, use of mkstemp[s] is unsafe in a multi-threaded
program.  We should prefer mkostemp[s] in the first place.

* bootstrap.conf (gnulib_modules): Add mkostemp, mkostemps; drop
mkstemp and mkstemps.
* cfg.mk (sc_prohibit_mkstemp): New syntax check.
* tools/virsh.c (vshEditWriteToTempFile): Adjust caller.
* src/qemu/qemu_driver.c (qemuDomainScreenshot)
(qemudDomainMemoryPeek): Likewise.
* src/secret/secret_driver.c (replaceFile): Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainScreenshot): Likewise.
2012-10-31 10:06:10 -06:00
Martin Kletzander
10c5212b10 qemu: Fix EmulatorPinInfo without emulatorpin
https://bugzilla.redhat.com/show_bug.cgi?id=871312

Recent fixes made almost all the right steps to make emulator pinned
to the cpuset of the whole domain in case <emulatorpin> isn't
specified, but qemudDomainGetEmulatorPinInfo still reports all the
CPUs even when cpuset is specified.  This patch fixes that.
2012-10-31 16:27:02 +01:00
Michal Privoznik
34e8f63a32 qemu: Report errors from iohelper
Currently, we use iohelper when saving/restoring a domain.
However, if there's some kind of error (like I/O) it is not
propagated to libvirt. Since it is not qemu who is doing
the actual write() it will not get error. The iohelper does.
Therefore we should check for iohelper errors as it makes
libvirt more user friendly.
2012-10-29 17:04:26 +01:00
Cole Robinson
9a2975786b qemu: Fix domxml-to-native network model conversion
https://bugzilla.redhat.com/show_bug.cgi?id=636832
2012-10-27 12:20:49 -04:00
Eric Blake
5a3501be9e blockjob: relabel entire existing chain
When using block copy to pivot over to a new chain, the backing files
for the new chain might still need labeling (particularly if the user
passes --reuse-ext with a relative backing file name).  Relabeling a
file that is already labeled won't hurt, so this just labels the entire
chain at the point of the pivot.  Doing the relabel of the chain uses
the fact that we already safely probed the file type of an external
file at the start of the block copy.

* src/qemu/qemu_driver.c (qemuDomainBlockPivot): Relabel chain before
asking qemu to pivot.
2012-10-27 07:43:39 -06:00
Eric Blake
35c7701c64 blockjob: allow mirroring under SELinux and cgroup
Use the recent addition of qemuDomainPrepareDiskChainElement to
obtain locking manager lease, permit a block device through cgroups,
and set the SELinux label; then audit the fact that we hand a new
file over to qemu.  Alas, releasing the lease and label at the end
of the mirroring is a trickier prospect (we would have to trace the
backing chain of both source and destination, and be sure not to
revoke rights to any part of the chain that is shared), so for now,
virDomainBlockJobAbort still leaves things with additional access
granted (as block-pull and block-commit have the same problem of
not clamping access after completion, a future cleanup would cover
all three commands).

* src/qemu/qemu_driver.c (qemuDomainBlockCopy): Set up labeling.
2012-10-27 07:43:39 -06:00
Eric Blake
8ee5073c1e blockjob: allow for existing files in block-copy
Support the REUSE_EXT flag, in part by copying sanity checks from
snapshot code.  This code introduces a case of probing an external
file for its type; such an action would be a security risk if the
existing file is supposed to be raw but the contents resemble some
other format; however, since the virDomainBlockRebase API has a
flag to force treating the file as raw rather than probe, we can
assume that probing is safe in all other instances.  Besides, if
we don't probe or force raw, then qemu will.

* src/qemu/qemu_driver.c (qemuDomainBlockRebase): Allow REUSE_EXT
flag.
(qemuDomainBlockCopy): Wire up flag, and add some sanity checks.
2012-10-27 07:43:39 -06:00
Eric Blake
c1eb38053d blockjob: implement block copy for qemu
Minimal patch to wire up all the pieces in the previous patches
to actually enable a block copy job.  By minimal, I mean that
qemu creates the file (that is, no REUSE_EXT flag support yet),
SELinux must be disabled, a lock manager is not informed, and the
audit logs aren't updated.  But those will be added as
improvements in future patches.

This patch is designed so that if we ever add a future API
virDomainBlockCopy with more bells and whistles (such as letting
the user specify a destination image format different than the
source), where virDomainBlockRebase is a wrapper around the
simpler portions of the new functionality, then the new API can
just reuse the new qemuDomainBlockCopy function and already
support _SHALLOW and _REUSE_EXT flags.  Also note that libvirt.c
already filtered the new flags if _COPY is not present, so that
we are not impacting the case of BlockRebase being a wrapper
around BlockPull.

* src/qemu/qemu_driver.c (qemuDomainBlockCopy): New function.
(qemuDomainBlockRebase): Call it when appropriate.
2012-10-27 07:43:39 -06:00
Eric Blake
400ac797ef blockjob: make block pivot safer
Since libvirt drops locks between issuing a monitor command and
getting a response, it is possible for libvirtd to be restarted
before getting a response on a block-job-complete command; worse, it
is also possible for the guest to shut itself down during the window
while libvirtd is down, ending the qemu process.  A management app
needs to know if the pivot happened (and the destination file
contains guest contents not in the source) or failed (and the source
file contains guest contents not in the destination), but since
the job is finished, 'query-block-jobs' no longer tracks the
status of the job, and if the qemu process itself has disappeared,
even 'query-block' cannot be checked to ask qemu its current state.

At the time of this patch, the design for persistent bitmap has not
been clarified, so a followup patch will be needed once qemu
actually figures out how to expose it, and we figure out how to use
it.  In the meantime, we have a solution that avoids the worst of
the problem.  [This problem was first analyzed with the RHEL 6.3
__com.redhat_drive-reopen command; which partly explains why
upstream qemu 1.3 ditched the drive-reopen idea and went with
block-job-complete plus persistent bitmap instead.]

If we surround 'drive-reopen' with a pause/resume pair, then we can
guarantee that the guest cannot modify either source or destination
files in the window of libvirtd uncertainty, and the management app
is guaranteed that either libvirt knows the outcome and reported it
correctly; or that on libvirtd restart, the guest will still be
paused and that the qemu process cannot have disappeared due to
guest shutdown; and use that as a clue that the management app must
implement recovery protocol, with both source and destination files
still being in sync and with 'query-block' still being an option as
part of that recovery.  My testing shows that the pause window will
typically be only a fraction of a second.

* src/qemu/qemu_driver.c (qemuDomainBlockPivot): Pause around
drive-reopen.
(qemuDomainBlockJobImpl): Update caller.
2012-10-27 07:43:38 -06:00
Eric Blake
eaba79d22e blockjob: support pivot operation on cancel
This is the bare minimum to end a copy job (of course, until a
later patch adds the ability to start a copy job, this patch
doesn't do much in isolation; I've just split the patches to
ease the review).

This patch intentionally avoids SELinux, lock manager, and audit
actions.  Also, if libvirtd restarts at the exact moment that a
'block-job-complete' is in flight, the proposed proper way to
detect the outcome of that would be with a persistent bitmap and
some additional query commands when libvirtd restarts.  This
patch is enough to test the common case of success when used
correctly, while saving the subtleties of proper cleanup for
worst-case errors for later.

When a mirror job is started, cancelling the job safely reverts back
to the source disk, regardless of whether the destination is in
phase 1 (streaming, in which case the destination is worthless) or
phase 2 (mirroring, in which case the destination is synced up to
the source at the time of the cancel).  Our existing code does just
fine in either phase, other than some bookkeeping cleanup; this
implements live block copy.

Ideas for future enhancements via new flags:

Depending on when persistent bitmap support is added, it may be
worth adding a VIR_DOMAIN_REBASE_COPY_ATOMIC flag that fails up
front if we detect an older qemu with risky pivot operation.

Interesting side note: while snapshot-create --disk-only creates a
copy of the disk at a point in time by moving the domain on to a
new file (the copy is the file now in the just-extended backing
chain), blockjob --abort of a copy job creates a copy of the disk
while keeping the domain on the original file.  There may be
potential improvements to the snapshot code to exploit block copy
over multiple disks all at one point in time.  And, if
'block-job-cancel' were made part of 'transaction', you could
copy multiple disks at the same point in time without pausing
the domain.  This also implies we may want to add a --quiesce flag
to virDomainBlockJobAbort, so that when breaking a mirror (whether
by cancel or pivot), the side of the mirror that we are abandoning
is at least in a stable state with regards to guest I/O.

* src/qemu/qemu_driver.c (qemuDomainBlockJobAbort): Accept new flag.
(qemuDomainBlockPivot): New helper function.
(qemuDomainBlockJobImpl): Implement it.
2012-10-27 07:43:38 -06:00
Eric Blake
edecd45c78 blockjob: return appropriate event and info
Handle the new type of block copy event and info.  Of course,
this patch does nothing until a later patch actually allows the
creation/abort of a block copy job.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_BLOCK_JOB_READY): New
block job status.
* src/libvirt.c (virDomainBlockRebase): Document the event.
* src/qemu/qemu_monitor_json.c (eventHandlers): New event.
(qemuMonitorJSONHandleBlockJobReady): New function.
(qemuMonitorJSONGetBlockJobInfoOne): Translate new job type.
(qemuMonitorJSONHandleBlockJobImpl): Handle new event and job type.
* src/qemu/qemu_process.c (qemuProcessHandleBlockJob): Recognize
the event to minimize snooping.
* src/qemu/qemu_driver.c (qemuDomainBlockJobImpl): Snoop a successful
info query to save effort on a pivot request.
2012-10-27 07:43:38 -06:00
Eric Blake
b3822ed04a blockjob: react to active block copy
For now, disk migration via block copy job is not implemented in
libvirt.  But when we do implement it, we have to deal with the
fact that qemu does not yet provide an easy way to re-start a qemu
process with mirroring still intact.  Paolo has proposed an idea
for a persistent dirty bitmap that might make this possible, but
until that design is complete, it's hard to say what changes
libvirt would need.  Even something like 'virDomainSave' becomes
hairy, if you realize the implications that 'virDomainRestore'
would be stuck with recreating the same mirror layout.

But if we step back and look at the bigger picture, we realize that
the initial client of live storage migration via disk mirroring is
oVirt, which always uses transient domains, and that if a transient
domain is destroyed while a mirror exists, oVirt can easily restart
the storage migration by creating a new domain that visits just the
source storage, with no loss in data.

We can make life a lot easier by being cowards for now, forbidding
certain operations on a domain.  This patch guarantees that we
never get in a state where we would have to restart a domain with
a mirroring block copy, by preventing saves, snapshots, migration,
hot unplug of a disk in use, and conversion to a persistent domain
(thankfully, it is still relatively easy to 'virsh undefine' a
running domain to temporarily make it transient, run tests on
'virsh blockcopy', then 'virsh define' to restore the persistence).
Later, if the qemu design is enhanced, we can relax our code.

The change to qemudDomainDefine looks a bit odd for undoing an
assignment, rather than probing up front to avoid the assignment,
but this is because of how virDomainAssignDef combines both a
lookup and assignment into a single function call.

* src/conf/domain_conf.h (virDomainHasDiskMirror): New prototype.
* src/conf/domain_conf.c (virDomainHasDiskMirror): New function.
* src/libvirt_private.syms (domain_conf.h): Export it.
* src/qemu/qemu_driver.c (qemuDomainSaveInternal)
(qemuDomainSnapshotCreateXML, qemuDomainRevertToSnapshot)
(qemuDomainBlockJobImpl, qemudDomainDefine): Prevent dangerous
actions while block copy is already in action.
* src/qemu/qemu_hotplug.c (qemuDomainDetachDiskDevice): Likewise.
* src/qemu/qemu_migration.c (qemuMigrationIsAllowed): Likewise.
2012-10-27 07:43:38 -06:00
Laine Stump
def31e4c58 qemu: fix attach/detach of netdevs with matching mac addrs
This resolves:

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

which describes inconsistencies in dealing with duplicate mac
addresses on network devices in a domain.

(at any rate, it resolves *almost* everything, and prints out an
informative error message for the one problem that isn't solved, but
has a workaround.)

A synopsis of the problems:

1) you can't do a persistent attach-interface of a device with a mac
address that matches an existing device.

2) you *can* do a live attach-interface of such a device.

3) you *can* directly edit a domain and put in two devices with
matching mac addresses.

4) When running virsh detach-device (live or config), only MAC address
is checked when matching the device to remove, so the first device
with the desired mac address will be removed. This isn't always the
one that's wanted.

5) when running virsh detach-interface (live or config), the only two
items that can be specified to match against are mac address and model
type (virtio, etc) - if multiple netdevs match both of those
attributes, it again just finds the first one added and assumes that
is the only match.

Since it is completely valid to have multiple network devices with the
same MAC address (although it can cause problems in many cases, there
*are* valid use cases), what is needed is:

1) remove the restriction that prohibits doing a persistent add of a
netdev with a duplicate mac address.

2) enhance the backend of virDomainDetachDeviceFlags to check for
something that *is* guaranteed unique (but still work with just mac
address, as long as it yields only a single results.

This patch does three things:

1) removes the check for duplicate mac address during a persistent
netdev attach.

2) unifies the searching for both live and config detach of netdevices
in the subordinate functions of qemuDomainModifyDeviceFlags() to use the
new function virDomainNetFindIdx (which matches mac address and PCI
address if available, checking for duplicates if only mac address was
specified). This function returns -2 if multiple matches are found,
allowing the callers to print out an appropriate message.

Steps 1 & 2 are enough to fully fix the problem when using virsh
attach-device and detach-device (which require an XML description of
the device rather than a bunch of commandline args)

3) modifies the virsh detach-interface command to check for multiple
matches of mac address and show an error message suggesting use of the
detach-device command in cases where there are multiple matching mac
addresses.

Later we should decide how we want to input a PCI address on the virsh
commandline, and enhance detach-interface to take a --address option,
eliminating the need to use detach-device

* src/conf/domain_conf.c
* src/conf/domain_conf.h
* src/libvirt_private.syms
  * added new virDomainNetFindIdx function
  * removed now unused virDomainNetIndexByMac and
    virDomainNetRemoveByMac

* src/qemu/qemu_driver.c
  * remove check for duplicate max from qemuDomainAttachDeviceConfig
  * use virDomainNetFindIdx/virDomainNetRemove instead
    of virDomainNetRemoveByMac in qemuDomainDetachDeviceConfig
  * use virDomainNetFindIdx instead of virDomainIndexByMac
    in qemuDomainUpdateDeviceConfig

* src/qemu/qemu_hotplug.c
  * use virDomainNetFindIdx instead of a homespun loop in
    qemuDomainDetachNetDevice.

* tools/virsh-domain.c: modified detach-interface command as described
    above
2012-10-26 20:47:54 -04:00
Eric Blake
4fbf322fe9 cpustat: fix regression when cpus are offline
It turns out that the cpuacct results properly account for offline
cpus, and always returns results for every possible cpu, not just
the online ones.  So there is no need to check the map of online
cpus in the first place, merely only a need to know the maximum
possible cpu.  Meanwhile, virNodeGetCPUBitmap had a subtle change
from returning the maximum id to instead returning the width of
the bitmap (one larger than the maximum id) in commit 2f4c5338,
which made this code encounter some off-by-one logic leading to
bad error messages when a cpu was offline:

$ virsh cpu-stats dom
error: Failed to virDomainGetCPUStats()

error: An error occurred, but the cause is unknown

Cleaning this up unraveled a chain of other unused variables.

* src/qemu/qemu_driver.c (qemuDomainGetPercpuStats): Drop
pointless check for cpumap changes, and use correct number of
cpus.  Simplify signature.
(qemuDomainGetCPUStats): Adjust caller.
* src/nodeinfo.h (nodeGetCPUCount): New prototype.
(nodeGetCPUBitmap): Drop unused parameter.
* src/nodeinfo.c (nodeGetCPUBitmap): Likewise.
(nodeGetCPUMap): Adjust caller.
(nodeGetCPUCount): New function.
* src/libvirt_private.syms (nodeinfo.h): Export it.
2012-10-26 15:34:52 -06:00
Viktor Mihajlovski
e3ba67037b virNodeGetCPUMap: Implement driver support
Driver support added for:
- test: pretending 8 host CPUS, 3 being online
- qemu, lxc, openvz, uml: using nodeGetCPUMap

Signed-off-by: Viktor Mihajlovski <mihajlov@linux.vnet.ibm.com>
2012-10-25 11:20:15 -06:00
Eric Blake
2f4c5338a6 nodeinfo: improve probing node cpu bitmap
Callers should not need to know what the name of the file to
be read in the Linux-specific version of nodeGetCPUmap;
furthermore, qemu cares about online cpus, not present cpus,
when determining which cpus to skip.

While at it, I fixed the fact that we were computing the maximum
online cpu id by doing a slow iteration, when what we really want
to know is the max available cpu.

* src/nodeinfo.h (nodeGetCPUmap): Rename...
(nodeGetCPUBitmap): ...and simplify signature.
* src/nodeinfo.c (linuxParseCPUmax): New function.
(linuxParseCPUmap): Simplify and alter signature.
(nodeGetCPUBitmap): Change implementation.
* src/libvirt_private.syms (nodeinfo.h): Reflect rename.
* src/qemu/qemu_driver.c (qemuDomainGetPercpuStats): Update
caller.
2012-10-25 11:20:08 -06:00
Osier Yang
a6bd7c22ea qemu: Prohibit chaning affinity of domain process if placement is 'auto'
On one hand, numad probably will manage the affinity of domain process
dynamically in future. On the other hand, even numad won't manage it,
it still could confusion. Let's make things simpler enough to avoid
the lair for now.
2012-10-24 22:26:11 +08:00
Eric Blake
33eaebe48e snapshot: sanity check when reusing file for snapshot
The snapshot code when reusing an existing file had hard-to-read
logic, as well as a missing sanity check: REUSE_EXT should require
the destination to already be present.

* src/qemu/qemu_driver.c (qemuDomainSnapshotDiskPrepare): Require
destination on REUSE_EXT, rename variable for legibility.
2012-10-22 15:10:16 -06:00
Eric Blake
d9d77bfa80 storage: let format probing work on root-squash NFS
Yet another instance of where using plain open() mishandles files
that live on root-squash NFS, and where improving the API can
improve the chance of a successful probe.

* src/util/storage_file.h (virStorageFileProbeFormat): Alter
signature.
* src/util/storage_file.c (virStorageFileProbeFormat): Use better
method for opening file.
* src/qemu/qemu_driver.c (qemuDomainGetBlockInfo): Update caller.
* src/storage/storage_backend_fs.c (virStorageBackendProbeTarget):
Likewise.
2012-10-22 09:04:57 -06:00
Ján Tomko
b6ab7a067f migrate: v2: use VIR_DOMAIN_XML_MIGRATABLE when available
In v2 migration protocol, XML is obtained by calling domainGetXMLDesc.
This includes the default USB controller in XML, which breaks migration
to older libvirt (before 0.9.2).

Commit 409b5f5495
    qemu: Emit compatible XML when migrating a domain
only fixed this for v3 migration.

This patch uses the new VIR_DOMAIN_XML_MIGRATABLE flag (detected by
VIR_DRV_FEATURE_XML_MIGRATABLE) to obtain XML without the default controller,
enabling backward v2 migration.
2012-10-22 10:48:50 +02:00
Eric Blake
a172dfbe2e blockjob: avoid segv on early error
Gcc with optimization warns:
../../src/qemu/qemu_driver.c: In function 'qemuDomainBlockCommit':
../../src/qemu/qemu_driver.c:12813:46: error: 'disk' may be used uninitialized in this function [-Werror=maybe-uninitialized]
../../src/qemu/qemu_driver.c:12698:25: note: 'disk' was declared here
cc1: all warnings being treated as errors

so obviously I had only been testing with optimization off.

* src/qemu/qemu_driver.c (qemuDomainBlockCommit): Guard cleanup.
2012-10-19 21:17:00 -06:00
Eric Blake
2e43cb8e90 blockjob: properly label disks for qemu block-commit
I finally have all the pieces in place to perform a block-commit with
SELinux enforcing.  There's still missing cleanup work when the commit
completes, but doing that requires tracking both the backing chain and
the base and top files within that chain in domain XML across libvirtd
restarts.  Furthermore, from a security standpoint, once you have
granted access, you must assume any damage that can be done will be
done; later revoking access is nice to minimize the window of damage,
but less important as it does not affect the fact that damage can be
done in the first place.  Therefore, deferring the revoke efforts until
we have better XML tracking of what chain operations are in effect,
including across a libvirtd restart, is reasonable.

* src/qemu/qemu_driver.c (qemuDomainBlockCommit): Label disks as
needed.
(qemuDomainPrepareDiskChainElement): Cast away const.
2012-10-19 17:56:39 -06:00
Eric Blake
35a2f5bc52 blockjob: refactor qemu disk chain permission grants
Previously, snapshot code did its own permission granting (lock
manager, cgroup device controller, and security manager labeling)
inline.  But now that we are adding block-commit and block-copy
which also have to change permissions, it's better to reuse
common code for the task.  While snapshot should fall back to
no access if read-write access failed, block-commit will want to
fall back to read-only access.  The common code doesn't know
whether failure to grant read-write access should revert to no
access (snapshot, block-copy) or read-only access (block-commit).
This code can also be used to revoke access to unused files after
block-pull.

It might be nice to clean things up in a future patch by adding
new functions to the lock manager, cgroup manager, and security
manager that takes a single file name and applies context of a
disk to that file, rather than the current semantics of applying
context to the entire chain already associated to a disk.  That
way, we could avoid the games this patch plays of temporarily
swapping out the disk->src and related fields of the disk.  But
that would involve more code changes, so this patch really is
the smallest hack for doing the necessary work; besides, this
patch is more or less code motion (the hack was already employed
by the snapshot creation code, we are just making it reusable).

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateSingleDiskActive)
(qemuDomainSnapshotUndoSingleDiskActive): Refactor labeling hacks...
(qemuDomainPrepareDiskChainElement): ...into new function.
2012-10-19 17:49:06 -06:00
Eric Blake
0a220e2225 blockjob: implement shallow commit flag in qemu
Now that we can crawl the chain of backing files, we can do
argument validation and implement the 'shallow' flag.  In
testing this, I discovered that it can be handy to pass the
shallow flag and an explicit base, as a means of validating
that the base is indeed the file we expected.

* src/qemu/qemu_driver.c (qemuDomainBlockCommit): Crawl through
chain to implement shallow flag.
* src/libvirt.c (virDomainBlockCommit): Relax API.
2012-10-19 17:35:11 -06:00
Eric Blake
2cbc1fd892 blockjob: wire up online qemu block-commit
This is the bare minimum to kick off a block commit.  In particular,
flags support is missing (shallow requires us to crawl the backing
chain to determine the file name to pass to the qemu monitor command;
delete requires us to track what needs to be deleted at the time
the completion event fires).  Also, we are relying on qemu to do
error checking (such as validating 'top' and 'base' as being members
of the backing chain), including the fact that the current qemu code
does not support committing the active layer (although it is still
planned to add that before qemu 1.3).  Since the active layer won't
change, we have it easy and do not have to alter the domain XML.
Additionally, this will fail if SELinux is enforcing, because we fail
to grant qemu proper read/write access to the files it will modify.

* src/qemu/qemu_driver.c (qemuDomainBlockCommit): New function.
(qemuDriver): Register it.
2012-10-19 17:35:11 -06:00
Eric Blake
67aea3fb78 blockjob: remove unused parameters after previous patch
Minor cleanup made possible by previous simplifications.

* src/qemu/qemu_cgroup.h (qemuSetupDiskCgroup)
(qemuTeardownDiskCgroup): Alter signature.
* src/qemu/qemu_cgroup.c (qemuSetupDiskCgroup)
(qemuTeardownDiskCgroup, qemuSetupCgroup): Update all uses.
* src/qemu/qemu_hotplug.c (qemuDomainDetachPciDiskDevice)
(qemuDomainDetachDiskDevice): Likewise.
* src/qemu/qemu_driver.c (qemuDomainAttachDeviceDiskLive)
(qemuDomainChangeDiskMediaLive)
(qemuDomainSnapshotCreateSingleDiskActive)
(qemuDomainSnapshotUndoSingleDiskActive): Likewise.
2012-10-19 17:35:11 -06:00
Eric Blake
4d34c92947 storage: cache backing chain while qemu domain is live
Technically, we should not be re-probing any file that qemu might
be currently writing to.  As such, we should cache the backing
file chain prior to starting qemu.  This patch adds the cache,
but does not use it until the next patch.

Ultimately, we want to also store the chain in domain XML, so that
it is remembered across libvirtd restarts, and so that the only
kosher way to modify the backing chain of an offline domain will be
through libvirt API calls, but we aren't there yet.  So for now, we
merely invalidate the cache any time we do a live operation that
alters the chain (block-pull, block-commit, external disk snapshot),
as well as tear down the cache when the domain is not running.

* src/conf/domain_conf.h (_virDomainDiskDef): New field.
* src/conf/domain_conf.c (virDomainDiskDefFree): Clean new field.
* src/qemu/qemu_domain.h (qemuDomainDetermineDiskChain): New
prototype.
* src/qemu/qemu_domain.c (qemuDomainDetermineDiskChain): New
function.
* src/qemu/qemu_driver.c (qemuDomainAttachDeviceDiskLive)
(qemuDomainChangeDiskMediaLive): Pre-populate chain.
(qemuDomainSnapshotCreateSingleDiskActive): Uncache chain before
snapshot.
* src/qemu/qemu_process.c (qemuProcessHandleBlockJob): Update
chain after block pull.
2012-10-19 17:35:10 -06:00
Eric Blake
1fc9593271 storage: don't require caller to pre-allocate metadata struct
Requiring pre-allocation was an unusual idiom.  It allowed iteration
over the backing chain to use fewer mallocs, but made one-shot
clients harder to read.  Also, this makes it easier for a future
patch to move away from opening fds on every iteration over the chain.

* src/util/storage_file.h (virStorageFileGetMetadataFromFD): Alter
signature.
* src/util/storage_file.c (virStorageFileGetMetadataFromFD): Allocate
return value.
 (virStorageFileGetMetadata): Update clients.
* src/conf/domain_conf.c (virDomainDiskDefForeachPath): Likewise.
* src/qemu/qemu_driver.c (qemuDomainGetBlockInfo): Likewise.
* src/storage/storage_backend_fs.c (virStorageBackendProbeTarget):
Likewise.
2012-10-19 17:35:10 -06:00
Eric Blake
1246640b3d storage: use enum for snapshot driver type
This is the last use of raw strings for disk formats throughout
the src/conf directory.

* src/conf/snapshot_conf.h (_virDomainSnapshotDiskDef): Store enum
rather than string for disk type.
* src/conf/snapshot_conf.c (virDomainSnapshotDiskDefClear)
(virDomainSnapshotDiskDefParseXML, virDomainSnapshotDefFormat):
Adjust users.
* src/qemu/qemu_driver.c (qemuDomainSnapshotDiskPrepare)
(qemuDomainSnapshotCreateSingleDiskActive): Likewise.
2012-10-19 17:35:10 -06:00
Eric Blake
e5e8d5d082 storage: use enum for disk driver type
Actually use the enum in the domain conf structure.

* src/conf/domain_conf.h (_virDomainDiskDef): Store enum rather
than string for disk type.
* src/conf/domain_conf.c (virDomainDiskDefFree)
(virDomainDiskDefParseXML, virDomainDiskDefFormat)
(virDomainDiskDefForeachPath): Adjust users.
* src/xenxs/xen_sxpr.c (xenParseSxprDisks, xenFormatSxprDisk):
Likewise.
* src/xenxs/xen_xm.c (xenParseXM, xenFormatXMDisk): Likewise.
* src/vbox/vbox_tmpl.c (vboxAttachDrives): Likewise.
* src/libxl/libxl_conf.c (libxlMakeDisk): Likewise.
2012-10-19 17:35:09 -06:00
Eric Blake
09e7fb5e1f storage: use enum for default driver type
Express the default disk type as an enum, for easier handling.

* src/conf/capabilities.h (_virCaps): Store enum rather than
string for disk type.
* src/conf/domain_conf.c (virDomainDiskDefParseXML): Adjust
clients.
* src/qemu/qemu_driver.c (qemuCreateCapabilities): Likewise.
2012-10-19 17:35:09 -06:00
Eric Blake
f772b3d91f storage: list more file types
When an image has no backing file, using VIR_STORAGE_FILE_AUTO
for its type is a bit confusing.  Additionally, a future patch
would like to reserve a default value for the case of no file
type specified in the XML, but different from the current use
of -1 to imply probing, since probing is not always safe.

Also, a couple of file types were missing compared to supported
code: libxl supports 'vhd', and qemu supports 'fat' for directories
passed through as a file system.

* src/util/storage_file.h (virStorageFileFormat): Add
VIR_STORAGE_FILE_NONE, VIR_STORAGE_FILE_FAT, VIR_STORAGE_FILE_VHD.
* src/util/storage_file.c (virStorageFileMatchesVersion): Match
documentation when version probing not supported.
(cowGetBackingStore, qcowXGetBackingStore, qcow1GetBackingStore)
(qcow2GetBackingStoreFormat, qedGetBackingStore)
(virStorageFileGetMetadataFromBuf)
(virStorageFileGetMetadataFromFD): Take NONE into account.
* src/conf/domain_conf.c (virDomainDiskDefForeachPath): Likewise.
* src/qemu/qemu_driver.c (qemuDomainGetBlockInfo): Likewise.
* src/conf/storage_conf.c (virStorageVolumeFormatFromString): New
function.
(poolTypeInfo): Use it.
2012-10-19 17:35:09 -06:00
Jiri Denemark
f1c7010040 qemu: Always format CPU topology
When libvirt cannot find a suitable CPU model for host CPU (easily
reproducible by running libvirt in a guest), it would not provide CPU
topology in capabilities XML either. Even though CPU topology is known
and can be queried by virNodeGetInfo. With this patch, CPU topology will
always be provided in capabilities XML regardless on the presence of CPU
model.
2012-10-18 14:57:08 +02:00
Martin Kletzander
ba63d8f7d8 qemu: Pin the emulator when only cpuset is specified
According to our recent changes (clarifications), we should be pinning
qemu's emulator processes using the <vcpu> 'cpuset' attribute in case
there is no <emulatorpin> specified.  This however doesn't work
entirely as expected and this patch should resolve all the remaining
issues.
2012-10-17 17:37:10 +02:00
Laine Stump
6bde0a1a37 qemu: reorganize qemuDomainChangeNet and qemuDomainChangeNetBridge
This patch resolves:

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

to the extent that it can be resolved with current qemu functionality.
It attempts to detect as many situations as possible when the simple
operation of disconnecting an existing tap device from one bridge and
attaching it to another will satisfy the change requested in
virDomainUpdateDeviceFlags() for a network device. Before this patch,
that situation could only be detected if the pre-change interface
*and* the post-change interface definition were both "type='bridge'".
After this patch, it can also be detected if the before or after
interfaces are any combination of type='bridge' and type='network'
(the networks can be <forward mode='nat|route|bridge'>, as long as
they use a Linux host bridge and not macvtap connections).

This extra effort is especially useful since the recent discovery that
a netdev_del+netdev_add combo (to reconnect the network device with
completely different hostside configuration) doesn't work properly
with current qemu (1.2) unless it is accompanied by the matching
device_del+device_add - see this mailing list message for details:

  http://lists.nongnu.org/archive/html/qemu-devel/2012-10/msg02355.html

(A slight modification of the patch referenced there has been prepared
to apply on top of this patch, but won't be pushed until qemu can be
made to work with it.)

* qemuDomainChangeNet needs access to the virDomainDeviceDef that
holds the new netdef (so that it can clear out the virDomainDeviceDef
if it ends up using the NetDef to replace the original), so the
virDomainNetDefPtr arg is replaced with a virDomainDeviceDefPtr.

* qemuDomainChangeNet previously checked for *some* changes to the
interface config, but this check was by no means complete. It was also
a bit disorganized.

This refactoring of the code is (I believe) complete in its check of
all NetDef attributes that might be changed, and either returns a
failure (for changes that are simply impossible), or sets one of three
flags:

  needLinkStateChange - if the device link state needs to go up/down
  needBridgeChange    - if everything else is the same, but it needs
                        to be connected to a difference linux host
                        bridge
  needReconnect       - if the entire host side of the device needs
                        to be torn down and reconstructed (currently
                        non-working, as mentioned above)

Note that this function will refuse to make any change that requires
the *guest* side of the device to be detached (e.g. changing the PCI
address or mac address). Those would be disruptive enough to the guest
that it's reasonable to require an explicit detach/attach sequence
from the management application.

* As mentioned above, qemuDomainChangeNet also does its best to
understand when a simple change in attached bridge for the existing
tap device will work vs. the need to completely tear down/reconstruct
the host side of the device (including tap device).

This patch *does not* implement the "reconnect" code anyway - there is
a placeholder that turns that into an error. Rather, the purpose of
this patch is to replicate existing behavior with code that is ready
to have that functionality plugged in in a later patch.

* The expanded uses for qemuDomainChangeNetBridge meant that it needed
to be enhanced as well - it no longer replaces the original brname
string in olddev with the new brname; instead, it relies on the
caller to replace the *entire* olddev with newdev (since we've gone
to great lengths to assure they are functionally identical other
than the name of the bridge, this is now not only safe, but more
correct). Additionally, qemuDomainNetChangeBridge can now set the
bridge for type='network' interfaces as well as plain type='bridge'
interfaces. (Note that I had to make this change simultaneous to the
reorganization of qemuDomainChangeNet because the two are too
closely intertwined to separate).
2012-10-15 04:36:39 -04:00
Guido Günther
a2b80edbc6 Fix tab vs space
that broke "make syntax-check"

found by http://honk.sigxcpu.org:8001/job/libvirt-syntax-check/157/

Pushed under the build breaker rule.
2012-10-15 09:18:18 +02:00
Osier Yang
0df1a79089 qemu: Initialize cpuset for hotplugged vcpu as def->cpuset
The onlined vcpu pinning policy should inherit def->cpuset if
it's not specified explicitly, and the affinity should be set
in this case. Oppositely, the offlined vcpu pinning policy should
be free()'ed.
2012-10-15 12:16:02 +08:00
Osier Yang
a9bfe887f9 qemu: Create or remove cgroup when doing vcpu hotpluging
Various APIs use cgroup to either set or get the statistics of
host or guest. Hotplug or hot unplug new vcpus without creating
or removing the cgroup for the vcpus could cause problems for
those APIs. E.g.

% virsh vcpucount dom
maximum      config        10
maximum      live          10
current      config         1
current      live           1

% virsh setvcpu dom 2

% virsh schedinfo dom --set vcpu_quota=1000
Scheduler      : posix
error: Unable to find vcpu cgroup for rhel6.2(vcpu: 1): No such file or
directory

This patch fixes the problem by creating cgroups for each of the
onlined vcpus, and destroying cgroups for each of the offlined
vcpus.
2012-10-15 12:15:32 +08:00
Jiri Denemark
bd1282d624 qemu: Make save/restore with USB devices usable
Save/restore with passed through USB devices currently only works if the
USB device can be found at the same USB address where it used to be
before saving a domain. This makes sense in case a user explicitly
configure the USB address in domain XML. However, if the device was
found automatically by vendor/product identification, we should try to
search for that device when restoring the domain and use any device we
find as long as there is only one available. In other words, the USB
device can now be removed and plugged again or the host can be rebooted
between saving and restoring the domain.
2012-10-11 15:11:42 +02:00
Jiri Denemark
28f8dfdccc Add MIGRATABLE flag for virDomainGetXMLDesc
Using VIR_DOMAIN_XML_MIGRATABLE flag, one can request domain's XML
configuration that is suitable for migration or save/restore. Such XML
may contain extra run-time stuff internal to libvirt and some default
configuration may be removed for better compatibility of the XML with
older libvirt releases.

This flag may serve as an easy way to get the XML that can be passed
(after desired modifications) to APIs that accept custom XMLs, such as
virDomainMigrate{,ToURI}2 or virDomainSaveFlags.
2012-10-11 15:11:42 +02:00
Jiri Denemark
d236f3fc38 locking: Pass hypervisor driver name when acquiring locks
This is required in case a lock manager needs to contact libvirtd in
case of an unexpected event.
2012-10-11 14:41:42 +02:00
Daniel P. Berrange
4da9b2c163 Change qemuSetSchedularParameters to use AFFECT_CURRENT
When adding variants of parameter setting APIs which accepted
flags, the existing APIs were all adapted internally to pass
VIR_DOMAIN_AFFECT_CURRENT to the new API. The QEMU impl
qemuSetSchedularParameters was an exception, which instead
used VIR_DOMAIN_AFFECT_LIVE. Change this to match other
compatibility scenarios, so that calling

   virDomainSetSchedularParameters(dom, params, nparams);

Has the same semantics as

   virDomainSetSchedularParametersFlags(dom, params, nparams, 0);

And

   virDomainSetSchedularParametersFlags(dom, params, nparams, VIR_DOMAIN_AFFECT_CURRENT);

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-10-10 14:20:37 +01:00
Jiri Denemark
0caccb58f0 qemu: Kill processes used for QMP caps probing
Since libvirt switched to QMP capabilities probing recently, it starts
QEMU process used for this probing with -daemonize, which means
virCommandAbort can no longer reach these processes. As a result of
that, restarting libvirtd will leave several new QEMU processes behind.
Let's use QEMU's -pidfile and use it to kill the process when QMP caps
probing is done.
2012-10-02 13:39:58 +02:00
Peter Krempa
e0316b5ebd qemu: Use proper agent entering function when freezing filesystems
When doing snapshots, the filesystem freeze function used the agent
entering function that expects the qemud_driver unlocked. This might
cause a deadlock of the qemu driver if the agent does not respond.

The only call path of this function has the qemud_driver locked, so this
patch changes the entering functions to those expecting the driver
locked.
2012-10-02 11:40:32 +02:00
Daniel P. Berrange
43e23c73af Add support for detecting capablities using QMP commands
Start a QEMU process using

   $QEMU -S -no-user-config -nodefaults \
         -nographic -M none -qmp unix:/some/path,server,nowait

and talk QMP over stdio to discover what capabilities the
binary supports. This works for QEMU 1.2.0 or later and
for older QEMU automatically fallback to the old approach
of parsing -help and related command line args.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-28 16:50:51 +01:00
Daniel P. Berrange
bd66c243b3 Remove probing of machine types when canonicalizing XML
When XML for a new guest is received, the machine type is
immediately canonicalized into the version specific name.
This involves probing QEMU for supported machine types.
Replace this probing with a lookup of the machine types
in the (hopefully cached) qemuCapsPtr object

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-27 10:24:52 +01:00
Daniel P. Berrange
15ee6614f7 Remove probing of flags when launching QEMU guests
Remove all use of the existing APIs for querying QEMU
capability flags. Instead obtain a qemuCapsPtr object
from the global cache. This avoids the execution of
'qemu -help' (and related commands) when launching new
guests.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-27 10:24:52 +01:00
Daniel P. Berrange
494e2f5cc2 Switch over to use cache for building QEMU capabilities
When building up a virCapsPtr instance, the QEMU driver
was copying the list of machine types across from the
previous virCapsPtr instance, if the QEMU binary had not
changed. Replace this ad-hoc caching of data with use
of the new qemuCapsCache global cache.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-27 10:24:52 +01:00
Daniel P. Berrange
8fd3823117 Move most of qemuProcessKill into virProcessKillPainfully
In the cgroups APIs we have a virCgroupKillPainfully function
which does the loop sending SIGTERM, then SIGKILL and waiting
for the process to exit. There is similar functionality for
simple processes in qemuProcessKill, but it is tangled with
the QEMU code. Untangle it to provide a virProcessKillPainfuly
function

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-27 10:11:44 +01:00
Daniel P. Berrange
f1b4021b38 Don't ignore return value of qemuProcessKill
When calling qemuProcessKill from the virDomainDestroy impl
in QEMU, do not ignore the return value. This ensures that
if QEMU fails to respond to SIGKILL, the caller will know
about the failure.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-27 10:11:44 +01:00
Daniel P. Berrange
7307c3c00c Simplify some redundant locking while unref'ing objects
There is no need to hold the mutex when unref'ing
virObject instances

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-26 10:09:58 +01:00
Peter Krempa
35fe4e7e2e qemu: Avoid holding the driver lock in trivial snapshot API's
In most of the snapshot API's there's no need to hold the driver lock
the whole time.

This patch adds helper functions that get the domain object in functions
that don't require the driver lock and simplifies call paths from
snapshot-related API's.
2012-09-25 17:05:41 +02:00
Tang Chen
9ce64e6aae Remove redundant lines in src/qemu/qemu_driver.c
maxcpu and hostcpus are defined and calculated in qemudDomainPinVcpuFlags()
and qemudDomainPinEmulator(), but never used. So remove them including nodeinfo.

Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
2012-09-21 12:49:47 -06:00
Tang Chen
1437ea6f48 Remove a redundant line in src/qemu/qemu_driver.c
Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
2012-09-21 12:16:25 +08:00
Eric Blake
4ecb723b9e maint: fix up copyright notice inconsistencies
https://www.gnu.org/licenses/gpl-howto.html recommends that
the 'If not, see <url>.' phrase be a separate sentence.

* tests/securityselinuxhelper.c: Remove doubled line.
* tests/securityselinuxtest.c: Likewise.
* globally: s/;  If/.  If/
2012-09-20 16:30:55 -06:00
Eric Blake
d239085e95 qemu: drop unused arguments for dump-guest-memory
Upstream qemu has raised a concern about whether dumping guest
memory by reading guest paging tables is a security hole:
https://lists.gnu.org/archive/html/qemu-devel/2012-09/msg02607.html

While auditing libvirt to see if we would be impacted, I noticed
that we had some dead code.  It is simpler to nuke the dead code
and limit our monitor code to just the subset we make use of.

* src/qemu/qemu_monitor.h (QEMU_MONITOR_DUMP): Drop poorly named
and mostly-unused enum.
* src/qemu/qemu_monitor.c (qemuMonitorDumpToFd): Drop arguments.
* src/qemu/qemu_monitor_json.h (qemuMonitorJSONDump): Likewise.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONDump): Likewise.
* src/qemu/qemu_driver.c (qemuDumpToFd): Update caller.
2012-09-17 20:44:29 -06:00
Hu Tao
fe2a0b027b use virBitmap to store nodeinfo. 2012-09-17 14:59:37 -04:00
Hu Tao
75b198b3e7 use virBitmap to store numa nodemask info. 2012-09-17 14:59:37 -04:00
Hu Tao
f1a43a8e41 use virBitmap to store cpu affinity info 2012-09-17 14:59:37 -04:00
Hu Tao
f970d8481e use virBitmap to store cpupin info 2012-09-17 14:59:36 -04:00
Hu Tao
0831a5bade bitmap: new member variable and function renaming
Add a new member variable map_len to store map len of bitmap.
and rename size to max_bit accordingly.

rename virBitmapAlloc to virBitmapNew.
2012-09-17 14:59:36 -04:00
Osier Yang
8268a24548 node_memory: Support get/set memory parameters for drivers
Including QEMU, LXC, UML, XEN drivers.
2012-09-17 13:55:22 +08:00
Guannan Ren
ac89a611d4 snapshot: fix rollback failure in transaction mode
BZ:https://bugzilla.redhat.com/show_bug.cgi?id=843372
when qemu supports the 'transaction' monitor command,
and libvirt's --reuse-ext flag was not specified, libvirt created
a stub file with zero size in first place. After the failure of
QEMU transaction command performing qcow2 snapshots on more than
one drives, the stub file is left behind with non-empty
by the QEMU transaction command.
In order to unlink the file, the patch removes the file size checking.

Steps to reproduce the issue:
Steps:
 1, Create a qemu instance with two drive images of qcow2 type (root user)
    /usr/libexec/qemu-kvm -m 1024 -smp 1 -name "rhel6u1" \
      -drive file=/var/lib/libvirt/images/firstqcow2,if=none,id=drive-virtio-disk0,format=qcow2,cache=none
      -device virtio-blk-pci,scsi=off,bus=pci.0,addr=0x5,drive=drive-virtio-disk0,id=virtio-disk0,bootindex=1 \
      -drive file=/var/lib/libvirt/images/secondqcow2,if=none,id=drive-virtio-disk1,format=qcow2,cache=none \
      -device virtio-blk-pci,scsi=off,bus=pci.0,addr=0x7,drive=drive-virtio-disk1,id=virtio-disk1 -qmp stdio

 2, Initialize qemu qmp
    {"execute":"qmp_capabilities"}

 3, Remove the second drive image file
    rm -f /var/lib/libvirt/images/secondqcow2

 4, Run 'transaction' command with snapshot qemu commands in.
    {"execute":"transaction","arguments":
      {"actions":
        [{"type":"blockdev-snapshot-sync","data":
          {"device":"drive-virtio-disk0","snapshot-file":"/var/lib/libvirt/images/firstqcow2-snapshot.img","format":"qcow2"}
         },
         {"type":"blockdev-snapshot-sync","data":
          {"device":"drive-virtio-disk1","snapshot-file":"/var/lib/libvirt/images/secondqcow2-snapshot.img","format":"qcow2"}
         }]
      },
   "id":"libvirt-6"}

 5, Got the error as follows:
    {"id": "libvirt-6",
      "error": {"class": "OpenFileFailed", "desc": "Could not open '/var/lib/libvirt/images/secondqcow2-snapshot.img'",
                "data": {"filename": "/var/lib/libvirt/images/secondqcow2-snapshot.img"}
               }
    }

 6, List first newly-created snapshot file:
    -rw-r--r--. 1 root root     262144 Sep 13 11:43 firstqcow2-snapshot.img
2012-09-14 11:18:19 +08:00
Daniel P. Berrange
9b5c540096 Fix data types used for list sizes in QEMU capabilities
The QEMU capabilities APIs used a misc of 'int' and
'unsigned int' for variables relating to array sizes.
Change all these to use 'size_t'

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-13 12:30:23 +01:00
Daniel P. Berrange
beac09fd68 Turn QEMU capabilities object into a full virObjectPtr
The current qemu capabilities are stored in a virBitmapPtr
object, whose type is exposed to callers. We want to store
more data besides just the flags, so we need to move to a
struct type. This object will also need to be reference
counted, since we'll be maintaining a cache of data per
binary. This change introduces a 'qemuCapsPtr' virObject
class. Most of the change is just renaming types and
variables in all the callers

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-09-13 12:24:12 +01:00
Eric Blake
2387aa26c1 maint: fix missing spaces in message
I got an off-list report about a bad diagnostic:
Target network card mac 52:54:00:49:07:ccdoes not match source 52:54:00:49:07:b8

True to form, I've added a syntax check rule to prevent it
from recurring, and found several other offenders.

* cfg.mk (sc_require_whitespace_in_translation): New rule.
* src/conf/domain_conf.c (virDomainNetDefCheckABIStability): Add
space.
* src/esx/esx_util.c (esxUtil_ParseUri): Likewise.
* src/qemu/qemu_command.c (qemuCollectPCIAddress): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSetMetadata)
(qemuDomainGetMetadata): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainChangeNetBridge): Likewise.
* src/rpc/virnettlscontext.c
(virNetTLSContextCheckCertDNWhitelist): Likewise.
* src/vmware/vmware_driver.c (vmwareDomainResume): Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainGetXMLDesc, vboxAttachDrives):
Avoid false negatives.
* tools/virsh-domain.c (info_save_image_dumpxml): Reword.
Based on a report by Luwen Su.
2012-09-12 11:55:29 -06:00
Peter Krempa
972e914f59 qemu: Add range checking for scheduler tunables when changed by API
The quota and period tunables for cpu scheduler accept only a certain
range of values. When changing the live configuration invalid values get
rejected. This check is not performed when changing persistent config.

This patch adds a separate range check, that improves error messages
when changing live config and adds the check for persistent config.
This check is done only when using the API. It is still possible to
specify invalid values in the XML.
2012-09-07 07:52:48 +02:00
Peter Krempa
3e250b3669 qemu: clean up qemuSetSchedulerParametersFlags()
This patch tries to clean the code up a little bit and shorten very long
lines.

The apparent semantic change from moving the condition before calling
the setter function is a non-issue here as the setter function is a
no-op when called with both arguments zero.
2012-09-07 07:52:48 +02:00
Martin Kletzander
b8216ec917 qemu: Add support for S3/S4 state configuration
This patch adds support for running qemu guests with the required
parameters to forcefully enable or disable BIOS advertising of S3 and
S4 states.  The support for this is added to capabilities and there is
also a qemu command parameter parsing implemented.
2012-09-03 09:32:39 +02:00
Guannan Ren
fccab89def cgroup: fix libvirtd crash caused by messed memory
The variable max_id is initialized again in the step of
getting cpu mapping variable map2. But in the next for loop
we still expect original value of max_id, the bug will
crash libvirtd when using on NUMA machine with big number
of cpus.
2012-08-31 16:45:02 +08:00
Guannan Ren
657fef1401 cgroup: fix a typo on extracting data from vcpu cgroup 2012-08-31 16:40:10 +08:00
Peter Krempa
077e7bf51f vcpupin: Fix returning of arrays from virDomainVcpuPinAdd
virDomainVcpuPinAdd does a realloc on vcpupin_list if the new vcpu pin
definition doesn't fit into the array. The list is an array of pointers
but the function definition didn't support returning the changed pointer
to the caller if it was realloced. This caused segfaults if realloc
would change the base pointer.
2012-08-30 16:45:38 +02:00
Peter Krempa
46514ff752 qemu: Clean up security driver initialisation and config file
Commit d0c0e79ac6 left behind some dead
code (hasDAC can't be efectively set to true, because
virSecurityManagerNew fails to load the "dac" driver).

This patch also enhances the condition for adding the default
auto-detected security manager if the manager array is allocated but
empty.

Also the configuration file for qemu driver still contains reference to
the DAC driver that can't be enabled manualy.
2012-08-30 16:45:38 +02:00
Osier Yang
20b780aec9 qemu: Sort the numa params only when it affects the live config
As the next boot doesn't have to worry about the previous numa
params setting (there is no).
2012-08-30 12:29:56 +08:00
Daniel P. Berrange
d0c0e79ac6 Fix configuration of QEMU security drivers
If no 'security_driver' config option was set, then the code
just loaded the 'dac' security driver. This is a regression
on previous behaviour, where we would probe for a possible
security driver. ie default to SELinux if available.

This changes things so that it 'security_driver' is not set,
we once again do probing. For simplicity we also always
create the stack driver, even if there is only one driver
active.

The desired semantics are:

 - security_driver not set
     -> probe for selinux/apparmour/nop
     -> auto-add DAC driver
 - security_driver set to a string
     -> add that one driver
     -> auto-add DAC driver
 - security_driver set to a list
     -> add all drivers in list
     -> auto-add DAC driver

It is not allowed, or possible to specify 'dac' in the
security_driver config param, since that is always
enabled.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-30 11:36:28 +08:00
Peter Krempa
eb8e9b6027 qemu: Refactor initialisation of security drivers.
The security driver loading code in qemu has a flaw that causes it to
register the DAC security driver twice. This causes problems (machines
unable to start) as the two DAC drivers clash together.

This patch refactors the code to allow loading the DAC driver even if
its specified in configuration (it can't be registered as a common
security driver), and does not add the driver twice.
2012-08-29 16:18:41 +02:00
Osier Yang
6fd1708fad qemu: Set placement when setting numa parameters
To keep the internal data structure consistent.
2012-08-29 09:45:28 +08:00
Michal Privoznik
9eee40cc54 qemu: Fix define logic
With current flow in qemudDomainDefine we might lose data
when updating an existing domain. We parse given XML and
overwrite the configuration.  Then we try to save the new
config. However, this step may fail and we don't perform any
roll back.  In fact, we remove the domain from the list of
domains held up by qemu driver. This is okay as long as the
domain was brand new one.
2012-08-27 19:01:09 +02:00
Michal Privoznik
aa3e8bd4ca Introduce new VIR_ERR_AGENT_UNRESPONSIVE error code
Currently, when guest agent is configured but not responsive
(e.g. due to appropriate service not running in the guest)
we return VIR_ERR_INTERNAL_ERROR. Both are wrong. Therefore
we need to introduce new error code to reflect this case.
2012-08-27 18:00:10 +02:00
Michal Privoznik
661d7fb4fc qemu: Switch to unified func name
With the latest patches libvirt supports qemu agent monitor
passthrough. However, function in qemu driver is called
qemuDrvDomainAgentCommand. s/Drv// as used in all other names.
2012-08-27 11:44:03 +02:00
Eric Blake
1385c9cd74 snapshot: rename an enum
The name 'virDomainDiskSnapshot' didn't fit in with our normal
conventions of using a prefix hinting that it is related to a
virDomainSnapshotPtr.  Also, a future patch will reuse the
enum for declaring where the VM memory is stored.

* src/conf/snapshot_conf.h (virDomainDiskSnapshot): Rename...
(virDomainSnapshotLocation): ...to this.
(_virDomainSnapshotDiskDef): Update clients.
* src/conf/domain_conf.h (_virDomainDiskDef): Likewise.
* src/libvirt_private.syms (domain_conf.h): Likewise.
* src/conf/domain_conf.c (virDomainDiskDefParseXML)
(virDomainDiskDefFormat): Likewise.
* src/conf/snapshot_conf.c: (virDomainSnapshotDiskDefParseXML)
(virDomainSnapshotAlignDisks, virDomainSnapshotDefFormat):
Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotDiskPrepare)
(qemuDomainSnapshotCreateSingleDiskActive)
(qemuDomainSnapshotCreateDiskActive, qemuDomainSnapshotCreateXML):
Likewise.
2012-08-24 09:51:08 -06:00
Eric Blake
3211deba3e snapshot: make virDomainSnapshotObjList opaque
We were failing to react to allocation failure when initializing
a snapshot object list.  Changing things to store a pointer
instead of a complete object adds one more possible point of
allocation failure, but at the same time, will make it easier to
react to failure now, as well as making it easier for a future
patch to split all virDomainSnapshotPtr handling into a separate
file, as I continue to add even more snapshot code.

Luckily, there was only one client outside of domain_conf.c that
was actually peeking inside the object, and a new wrapper function
was easy.

* src/conf/domain_conf.h (_virDomainObj): Use a pointer.
(virDomainSnapshotObjListInit): Rename.
(virDomainSnapshotObjListFree, virDomainSnapshotForEach): New
declarations.
(_virDomainSnapshotObjList): Move definitions...
* src/conf/domain_conf.c: ...here.
(virDomainSnapshotObjListInit, virDomainSnapshotObjListDeinit):
Rename...
(virDomainSnapshotObjListNew, virDomainSnapshotObjListFree): ...to
these.
(virDomainSnapshotForEach): New function.
(virDomainObjDispose, virDomainListPopulate): Adjust callers.
* src/qemu/qemu_domain.c (qemuDomainSnapshotDiscard)
(qemuDomainSnapshotDiscardAllMetadata): Likewise.
* src/qemu/qemu_migration.c (qemuMigrationIsAllowed): Likewise.
* src/qemu/qemu_driver.c (qemuDomainSnapshotLoad)
(qemuDomainUndefineFlags, qemuDomainSnapshotCreateXML)
(qemuDomainSnapshotListNames, qemuDomainSnapshotNum)
(qemuDomainListAllSnapshots)
(qemuDomainSnapshotListChildrenNames)
(qemuDomainSnapshotNumChildren)
(qemuDomainSnapshotListAllChildren)
(qemuDomainSnapshotLookupByName, qemuDomainSnapshotGetParent)
(qemuDomainSnapshotGetXMLDesc, qemuDomainSnapshotIsCurrent)
(qemuDomainSnapshotHasMetadata, qemuDomainRevertToSnapshot)
(qemuDomainSnapshotDelete): Likewise.
* src/libvirt_private.syms (domain_conf.h): Export new function.
2012-08-24 09:51:08 -06:00
Eric Blake
352cbae8b3 qemu-agent: available in 0.10.0
The recent virDomainQemuAgentCommand addition is part of 0.10.0;
also, grouping all libvirt-qemu.so callbacks together makes them
easier to identify.

* src/libvirt_qemu.syms: Fix release symbol.
* src/qemu/qemu_driver.c (qemuDriver): Likewise.
* src/remote/remote_driver.c (remote_driver): Likewise.
* src/driver.h (_virDriver): Group qemu-specific callbacks.
2012-08-23 13:05:52 -06:00
Michal Privoznik
385ee0e982 qemu: forbid suspend if already pmsuspended
If a domain is pmsuspended then virsh suspend will succeed. Beside
obvious flaw, virsh resume will report success and change domain
state to running which is another mistake. Therefore we must forbid
any attempts for suspend and resume when pmsuspended.
2012-08-23 17:48:44 +02:00
MATSUDA Daiki
0e963f4dc6 agent: add qemu driver support
Add qemuDrvDomainAgentCommand() for .qemuDomainArbitraryAgentCommand
to qemu driver.

Signed-off-by: MATSUDA Daiki <matsudadik@intellilink.co.jp>
2012-08-23 19:04:49 +08:00
Wen Congyang
5065942019 qemu: support of emulator_period and emulator_quota's modification
allow the user change/get emulator's period and quota when the vm is running.
2012-08-22 17:01:44 +08:00
Hu Tao
1d4395eb47 limit cpu bandwidth only for vcpus
This patch changes the behaviour of xml element cputune.period
and cputune.quota to limit cpu bandwidth only for vcpus, and no
longer limit cpu bandwidth for the whole guest.

The reasons to do this are:

  - This matches docs of cputune.period and cputune.quota.
  - The other parts excepting vcpus are treated as "emulator",
    and there are separate period/quota settings for emulator
    in the subsequent patches
2012-08-22 16:50:41 +08:00
Hu Tao
3dbf4838e4 qemu: support emulator pinning
Introduce 2 APIs to support emulator threads pin in qemu driver.

    1) qemudDomainPinEmulator: setup emulator threads pin info.
    2) qemudDomainGetEmulatorPinInfo: get all emulator threads pin info.

They are similar to qemudDomainPinVcpuFlags and qemudDomainGetVcpuPinInfo.
And also, remoteDispatchDomainPinEmulatorFlags and remoteDispatchDomainGetEmulatorPinInfo
functions are introduced.

Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
2012-08-22 16:30:44 +08:00
Hu Tao
fe1d32596c Enable cpuset cgroup and synchronous vcpupin info to cgroup.
vcpu threads pin are implemented using sched_setaffinity(), but
not controlled by cgroup. This patch does the following things:

    1) enable cpuset cgroup
    2) reflect all the vcpu threads pin info to cgroup

Signed-off-by: Tang Chen <tangchen@cn.fujitsu.com>
Signed-off-by: Hu Tao <hutao@cn.fujitsu.com>
2012-08-22 15:12:22 +08:00
Hu Tao
fd8fd0f916 refactor virDomainVcpuPinAdd() 2012-08-22 15:03:28 +08:00
Martin Kletzander
29226beefe qemu: configurable remote display port boundaries
The defines QEMU_REMOTE_PORT_MIN and QEMU_REMOTE_PORT_MAX were used to
find free port when starting domains. As this was hard-coded to the
same ports as default VNC servers, there were races with these other
programs. This patch includes the possibility to change the default
starting port as well as the maximum port (mostly for completeness) in
qemu config file.

Support for two new config options in qemu.conf is added:
 - remote_port_min (defaults to QEMU_REMOTE_PORT_MIN and
   must be >= than this value)
 - remote_port_max (defaults to QEMU_REMOTE_PORT_MAX and
   must be <= than this value)
2012-08-21 11:36:32 +02:00
Martin Kletzander
a14b4aea51 qemu: Unify port-wise SPICE and VNC behavior
Port allocations for SPICE and VNC behave almost the same (with
default ports), but there is some mess in the code. This patch clears
these inconsistencies and makes sure the same behavior will be used
when ports for remote displays are changed.

Changes:
 - hard-coded number 5900 removed (handled elsewhere like with VNC)
 - reservedVNCPorts renamed to reservedRemotePorts (it's not just for
   VNC anymore)
 - QEMU_VNC_PORT_{MIN,MAX} renamed to QEMU_REMOTE_PORT_{MIN,MAX}
 - port allocation unified for VNC and SPICE
2012-08-21 11:36:32 +02:00
Marcelo Cerri
2f8a09fbce Update the remote API
This patch updates libvirt's API to allow applications to inspect the
full list of security labels of a domain.

Signed-off-by: Marcelo Cerri <mhcerri@linux.vnet.ibm.com>
2012-08-20 19:14:30 +02:00
Marcelo Cerri
6d6bff3a46 Support for multiple default security drivers in QEMU config
This patch updates the key "security_driver" in QEMU config to suport
both a sigle default driver or a list of default drivers. This ensures
that it will remain compatible with older versions of the config file.

Signed-off-by: Marcelo Cerri <mhcerri@linux.vnet.ibm.com>
2012-08-20 19:14:30 +02:00
Marcelo Cerri
a994ef2d1a Update security layer to handle many security labels
These changes make the security drivers able to find and handle the
correct security label information when more than one label is
available. They also update the DAC driver to be used as an usual
security driver.

Signed-off-by: Marcelo Cerri <mhcerri@linux.vnet.ibm.com>
2012-08-20 19:14:30 +02:00
Marcelo Cerri
6c3cf57d6c Internal refactory of data structures
This patch updates the structures that store information about each
domain and each hypervisor to support multiple security labels and
drivers. It also updates all the remaining code to use the new fields.

Signed-off-by: Marcelo Cerri <mhcerri@linux.vnet.ibm.com>
2012-08-20 19:13:33 +02:00
Osier Yang
75e5bec97b qemu: Set swap_hard_limit before hard_limit
Setting hard_limit larger than previous swap_hard_limit must fail,
it's not that good if one wants to change the swap_hard_limit
and hard_limit together. E.g.

% virsh memtune rhel6
hard_limit     : 1000000
soft_limit     : 1000000
swap_hard_limit: 1000000

% virsh memtune rhel6 --hard-limit 1000020 --soft-limit 1000020 \
--swap-hard-limit 1000020 --live

This patch reorder the limits setting to set the swap_hard_limit
first, hard_limit then, and soft_limit last if it's greater than
current swap_hard_limit. And soft_limit first, hard_limit then,
swap_hard_limit last, if not.
2012-08-17 22:08:21 +08:00
Osier Yang
29d8ed7a61 qemu: Ensure the cpuset is formatted as expected before passing to cgroup
The parameter value for cpuset could be in special format like
"0-10,^7", which is not recognized by cgroup. This patch is to
ensure the cpuset is formatted as expected before passing it to
cgroup. As a side effect, after the patch, it parses the cpuset
early before cgroup setting, to avoid the rollback if cpuset
parsing fails afterwards.
2012-08-16 16:44:56 +08:00
Laine Stump
1d1744285b conf: move virtPortProfile out of unions in virDomainNetDef
virtPortProfile is now used by 4 different types of network devices
(NETWORK, BRIDGE, DIRECT, and HOSTDEV), and it's getting cumbersome to
replicate so much code in 4 different places just because each type
has the virtPortProfile in a slightly different place. This patch puts
a single virtPortProfile in a common place (outside the type-specific
union) in both virDomainNetDef and virDomainActualNetDef, and adjusts
the parse and format code (and the few other places where it is used)
accordingly.

Note that when a <virtualport> element is found, the parse functions
verify that the interface is of a type that supports one, otherwise an
error is generated (CONFIG_UNSUPPORTED in the case of <interface>, and
INTERNAL in the case of <actual>, since the contents of <actual> are
always generated by libvirt itself).
2012-08-14 15:47:28 -04:00
Osier Yang
bb705e2519 Destroy virdomainlist.[ch]
As the consensus in:
https://www.redhat.com/archives/libvir-list/2012-July/msg01692.html,
this patch is to destroy conf/virdomainlist.[ch], folding the
helpers into conf/domain_conf.[ch].

* src/Makefile.am:
  - Various indention fixes incidentally
  - Add macro DATATYPES_SOURCES (datatypes.[ch])
  - Link datatypes.[ch] for libvirt_lxc

* src/conf/domain_conf.c:
  - Move all the stuffs from virdomainlist.c into it
  - Use virUnrefDomain and virUnrefDomainSnapshot instead of
    virDomainFree and virDomainSnapshotFree, which are defined
    in libvirt.c, and we don't want to link to it.
  - Remove "if" before "free" the object, as virObjectUnref
    is in the list "useless_free_options".

* src/conf/domain_conf.h:
  - Move all the stuffs from virdomainlist.h into it
  - s/LIST_FILTER/LIST_DOMAINS_FILTER/

* src/libxl/libxl_driver.c:
  - s/LIST_FILTER/LIST_DOMAINS_FILTER/
  - no (include "virdomainlist.h")

* src/libxl/libxl_driver.c: Likewise

* src/lxc/lxc_driver.c: Likewise

* src/openvz/openvz_driver.c: Likewise

* src/parallels/parallels_driver.c: Likewise

* src/qemu/qemu_driver.c: Likewise

* src/test/test_driver.c: Likewise

* src/uml/uml_driver.c: Likewise

* src/vbox/vbox_tmpl.c: Likewise

* src/vmware/vmware_driver.c: Likewise

* tools/virsh-domain-monitor.c: Likewise

* tools/virsh.c: Likewise
2012-08-14 17:27:49 +08:00
Laine Stump
b8a56f12f5 nwfilter: fix crash during filter define when lxc driver failed startup
The meat of this patch is just moving the calls to
virNWFilterRegisterCallbackDriver from each hypervisor's "register"
function into its "initialize" function. The rest is just code
movement to allow that, and a new virNWFilterUnRegisterCallbackDriver
function to undo what the register function does.

The long explanation:

There is an array in nwfilter called callbackDrvArray that has
pointers to a table of functions for each hypervisor driver that are
called by nwfilter. One of those function pointers is to a function
that will lock the hypervisor driver. Entries are added to the table
by calling each driver's "register" function, which happens quite
early in libvirtd's startup.

Sometime later, each driver's "initialize" function is called. This
function allocates a driver object and stores a pointer to it in a
static variable that was previously initialized to NULL. (and here's
the important part...) If the "initialize" function fails, the driver
object is freed, and that pointer set back to NULL (but the entry in
nwfilter's callbackDrvArray is still there).

When the "lock the driver" function mentioned above is called, it
assumes that the driver was successfully loaded, so it blindly tries
to call virMutexLock on "driver->lock".

BUT, if the initialize never happened, or if it failed, "driver" is
NULL. And it just happens that "lock" is always the first field in
driver so it is also NULL.

Boom.

To fix this, the call to virNWFilterRegisterCallbackDriver for each
driver shouldn't be called until the end of its (*already guaranteed
successful*) "initialize" function, not during its "register" function
(which is currently the case). This implies that there should also be
a virNWFilterUnregisterCallbackDriver() function that is called in a
driver's "shutdown" function (although in practice, that function is
currently never called).
2012-08-09 23:28:00 -04:00
Daniel P. Berrange
31cb030ab6 Turn virDomainObjPtr into a virObjectPtr
Switch virDomainObjPtr to use the virObject APIs for reference
counting. The main change is that virObjectUnref does not return
the reference count, merely a bool indicating whether the object
still has any refs left. Checking the return value is also not
mandatory.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-08-07 11:47:41 +01:00
Osier Yang
ed1e711b99 qemu: Allow to attach/detach controller device persistently
* src/conf/domain_conf.c:
  - Add virDomainControllerFind to find controller device by type
    and index.
  - Add virDomainControllerRemove to remove the controller device
    from maintained controler list.

* src/conf/domain_conf.h:
  - Declare the two new helpers.

* src/libvirt_private.syms:
  - Expose private symbols for the two new helpers.

* src/qemu/qemu_driver.c:
  - Support attach/detach controller device persistently

* src/qemu/qemu_hotplug.c:
  - Use the two helpers to simplify the codes.
2012-08-03 12:19:16 +08:00
Michal Privoznik
e94c0a09ee qemu: Fix typo in qemuDomainModifyDeviceFlags
One of our latest commits fbe87126 introduced this nasty typo:
func(vmdef, ...); where func() dereference vmdef->ncontrollers,
and vmdef was initialized to NULL. This leaves us with unconditional
immediate segfault. It should be vm->def instead.
2012-08-02 16:43:57 +02:00
Peter Krempa
fbe871263c qemu: Add support for "none" USB controller
This patch enables the "none" USB controller for qemu guests and adds
valdiation on hot-plugged devices if the guest has USB disabled.

This patch also adds a set of tests to check parsing of domain XMLs that
use the "none" controller and some forbidden situations concerning it.
2012-08-02 12:13:48 +02:00
Eric Blake
768007aedc maint: don't permit format strings without %
Any time we have a string with no % passed through gettext, a
translator can inject a % to cause a stack overread.  When there
is nothing to format, it's easier to ask for a string that cannot
be used as a formatter, by using a trivial "%s" format instead.

In the past, we have used --disable-nls to catch some of the
offenders, but that doesn't get run very often, and many more
uses have crept in.  Syntax check to the rescue!

The syntax check can catch uses such as
virReportError(code,
               _("split "
                 "string"));
by using a sed script to fold context lines into one pattern
space before checking for a string without %.

This patch is just mechanical insertion of %s; there are probably
several messages touched by this patch where we would be better
off giving the user more information than a fixed string.

* cfg.mk (sc_prohibit_diagnostic_without_format): New rule.
* src/datatypes.c (virUnrefConnect, virGetDomain)
(virUnrefDomain, virGetNetwork, virUnrefNetwork, virGetInterface)
(virUnrefInterface, virGetStoragePool, virUnrefStoragePool)
(virGetStorageVol, virUnrefStorageVol, virGetNodeDevice)
(virGetSecret, virUnrefSecret, virGetNWFilter, virUnrefNWFilter)
(virGetDomainSnapshot, virUnrefDomainSnapshot): Add %s wrapper.
* src/lxc/lxc_driver.c (lxcDomainSetBlkioParameters)
(lxcDomainGetBlkioParameters): Likewise.
* src/conf/domain_conf.c (virSecurityDeviceLabelDefParseXML)
(virDomainDiskDefParseXML, virDomainGraphicsDefParseXML):
Likewise.
* src/conf/network_conf.c (virNetworkDNSHostsDefParseXML)
(virNetworkDefParseXML): Likewise.
* src/conf/nwfilter_conf.c (virNWFilterIsValidChainName):
Likewise.
* src/conf/nwfilter_params.c (virNWFilterVarValueCreateSimple)
(virNWFilterVarAccessParse): Likewise.
* src/libvirt.c (virDomainSave, virDomainSaveFlags)
(virDomainRestore, virDomainRestoreFlags)
(virDomainSaveImageGetXMLDesc, virDomainSaveImageDefineXML)
(virDomainCoreDump, virDomainGetXMLDesc)
(virDomainMigrateVersion1, virDomainMigrateVersion2)
(virDomainMigrateVersion3, virDomainMigrate, virDomainMigrate2)
(virStreamSendAll, virStreamRecvAll)
(virDomainSnapshotGetXMLDesc): Likewise.
* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopReqLeaseDel)
(virNWFilterDHCPSnoopReq): Likewise.
* src/openvz/openvz_driver.c (openvzUpdateDevice): Likewise.
* src/openvz/openvz_util.c (openvzKBPerPages): Likewise.
* src/qemu/qemu_cgroup.c (qemuSetupCgroup): Likewise.
* src/qemu/qemu_command.c (qemuBuildHubDevStr, qemuBuildChrChardevStr)
(qemuBuildCommandLine): Likewise.
* src/qemu/qemu_driver.c (qemuDomainGetPercpuStats): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainAttachNetDevice): Likewise.
* src/rpc/virnetsaslcontext.c (virNetSASLSessionGetIdentity):
Likewise.
* src/rpc/virnetsocket.c (virNetSocketNewConnectUNIX)
(virNetSocketSendFD, virNetSocketRecvFD): Likewise.
* src/storage/storage_backend_disk.c
(virStorageBackendDiskBuildPool): Likewise.
* src/storage/storage_backend_fs.c
(virStorageBackendFileSystemProbe)
(virStorageBackendFileSystemBuild): Likewise.
* src/storage/storage_backend_rbd.c
(virStorageBackendRBDOpenRADOSConn): Likewise.
* src/storage/storage_driver.c (storageVolumeResize): Likewise.
* src/test/test_driver.c (testInterfaceChangeBegin)
(testInterfaceChangeCommit, testInterfaceChangeRollback):
Likewise.
* src/vbox/vbox_tmpl.c (vboxListAllDomains): Likewise.
* src/xenxs/xen_sxpr.c (xenFormatSxprDisk, xenFormatSxpr):
Likewise.
* src/xenxs/xen_xm.c (xenXMConfigGetUUID, xenFormatXMDisk)
(xenFormatXM): Likewise.
2012-07-26 14:32:30 -06:00
Peter Krempa
8e0f7faf56 maint: Clean up coding style and fix error message spelling
This patch cleans up coding style breaks some long lines and fixes error
message spelling on various places in domain_conf.c and in the qemu
driver.
2012-07-23 13:37:56 +02:00
Osier Yang
f9ce7dad60 Desert the FSF address in copyright
Per the FSF address could be changed from time to time, and GNU
recommends the following now: (http://www.gnu.org/licenses/gpl-howto.html)

  You should have received a copy of the GNU General Public License
  along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

This patch removes the explicit FSF address, and uses above instead
(of course, with inserting 'Lesser' before 'General').

Except a bunch of files for security driver, all others are changed
automatically, the copyright for securify files are not complete,
that's why to do it manually:

  src/security/security_selinux.h
  src/security/security_driver.h
  src/security/security_selinux.c
  src/security/security_apparmor.h
  src/security/security_apparmor.c
  src/security/security_driver.c
2012-07-23 10:50:50 +08:00
Daniel P. Berrange
3399875965 Only enforce check for YAJL when starting a VM
The previous check for YAJL would have many undesirable
consequences, the most important being that it caused the
capabilities XML to lose all <guest> elements. There is
no user visible feedback as to what is wrong in this respect,
merely a syslog message. The empty capabilities causes
libvirtd to then throw away all guest XML configs that are
stored.

This changes the code so that the check for YAJL is only
performed at the time we attempt to spawn a QEMU process

error: Failed to start domain vm-vnc
error: unsupported configuration: this qemu binary requires libvirt to be compiled with yajl

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-20 20:31:46 +01:00
Daniel P. Berrange
3b7399b5c9 Replace use of qemuReportError with virReportError
Update the QEMU driver to use virReportError instead of
the qemuReportError custom macro

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-19 14:42:28 +01:00
Peter Krempa
4e532f2e3d qemu: Add missing "%s" before translation macros
This patch cleans up some missing "%s" before translation macros,
for strings which are const without format specifiers
2012-07-19 14:41:55 +01:00
Daniel P. Berrange
95c2c19f06 Don't autostart domains when reloading config
When sending SIGHUP to libvirtd, it will trigger the virStateDriver
reload operation. This is intended to reload the configuration files
for guests. For unknown historical reasons this is also triggering
autostart of all guests. Autostart is generally expected to be
something that happens on OS startup. Starting VMs on SIGHUP will
violate that expectation and potentially cause dangerous scenarios
if the admin has explicitly shutdown a misbehaving VM that has
been marked as autostart

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-19 10:18:26 +01:00
Stefan Berger
387117ad92 Convert 'raw MAC address' usages to use virMacAddr
Introduce new members in the virMacAddr 'class'
- virMacAddrSet: set virMacAddr from a virMacAddr
- virMacAddrSetRaw: setting virMacAddr from raw 6 byte MAC address buffer
- virMacAddrGetRaw: writing virMacAddr into raw 6 byte MAC address buffer
- virMacAddrCmp: comparing two virMacAddr
- virMacAddrCmpRaw: comparing a virMacAddr with a raw 6 byte MAC address buffer

then replace raw MAC addresses by replacing

- 'unsigned char *' with virMacAddrPtr
- 'unsigned char ... [VIR_MAC_BUFLEN]' with virMacAddr

and introduce usage of above functions where necessary.
2012-07-17 08:07:59 -04:00
Jiri Denemark
87c8623161 qemu: Do not fail virConnectCompareCPU if host CPU is not known
When host CPU could not be properly detected, virConnectCompareCPU will
just report that any CPU is incompatible with host CPU instead of
failing.
2012-07-16 13:21:38 +02:00
Daniel P. Berrange
1d9d5103b4 Wire up handling for QMP's BALLOON_EVENT
If QEMU supports the BALLOON_EVENT QMP event, then we can
avoid invoking 'query-balloon' when returning XML or the
domain info.

* src/qemu/qemu_capabilities.c, src/qemu/qemu_capabilities.h:
  Add QEMU_CAPS_BALLOON_EVENT
* src/qemu/qemu_driver.c: Skip query-balloon in
  qemudDomainGetInfo and qemuDomainGetXMLDesc if we have
  QEMU_CAPS_BALLOON_EVENT set
* src/qemu/qemu_monitor.c, src/qemu/qemu_monitor.h: Check
  for BALLOON_EVENT at connect to monitor. Add callback
  for balloon change notifications
* src/qemu/qemu_monitor_json.c, src/qemu/qemu_monitor_json.h:
  Add handling of BALLOON_EVENT and impl 'query-events'
  check

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-07-14 16:02:34 +08:00
Viktor Mihajlovski
f5dd58a608 qemu: Extended qemuDomainAssignAddresses to be callable from everywhere.
This is in preparation of the enablement of s390 guests with virtio devices.

The assignment of device addresses happens in different places, i.e. the
qemu driver and process modules as well as in the unit tests in slightly
different flavors. Currently, these are PPC spapr-vio and PCI
devices, virtio-s390 (not PCI based) will follow.

By optionally passing to qemuDomainAssignAddresses the domain
object and the capabilities it is now possible to call the function
from most of the places (except for hotplug) where address assignment
is done.

Signed-off-by: Viktor Mihajlovski <mihajlov@linux.vnet.ibm.com>
2012-07-11 11:19:05 +02:00
Eric Blake
0867a87721 build: detect all improper uses of _("%s")
The only useful translation of "%s" as a format string is "%s" (I
suppose you could claim "%1$s" is also valid, but why bother).  So
it is not worth translating; fixing this exposes some instances
where we were failing to translate real error messages.  This makes
the fix of commit 097da1ab more generic, as well as ensuring no
future regressions.

* cfg.mk (sc_prohibit_useless_translation): New rule.
* src/lxc/lxc_driver.c (lxcSetVcpuBWLive): Fix offender.
* src/openvz/openvz_conf.c (openvzReadFSConf): Likewise.
* src/qemu/qemu_cgroup.c (qemuSetupCgroupForVcpu): Likewise.
* src/qemu/qemu_driver.c (qemuSetVcpusBWLive): Likewise.
* src/xenapi/xenapi_utils.c (xenapiSessionErrorHandle): Likewise.
2012-07-10 15:49:41 -06:00
Peter Krempa
a4f74cd09a qemu: Mark domains as having managed state image only on managed save
QEMU domains were marked as having managed save image even if they were
saved using the regular save. With this patch, domains are marked so
only when using managed save API.
2012-07-04 11:06:51 +02:00
Osier Yang
968b6c60e9 qemu: Improve error if setmem fails for lacking of balloon support
"cannot set memory of an active domain" is misleading, it sounds
like setting memory of active domain is not supported.
2012-06-25 21:34:22 +08:00
Peter Krempa
33dc8cf018 drivers: Implement virListAllDomains for drivers using virDomainObj
This patch adds support for listing all domains into drivers that use
the common virDomainObj implementation: libxl, lxc, openvz, qemu, test,
uml, vmware.

For drivers that don't support managed save images the guests are
treated as if they had none, so filtering guests that do have such an
image on this driver succeeds and produces 0 results.
2012-06-20 13:35:26 +02:00
Eric Blake
5488612eb0 list: add qemu snapshot list support
The two new functions are very similar to the existing functions;
just a matter of different arguments and a call to a different
helper function.

* src/qemu/qemu_driver.c (qemuDomainSnapshotListNames)
(qemuDomainSnapshotNum, qemuDomainSnapshotListChildrenNames)
(qemuDomainSnapshotNumChildren): Support new flags.
(qemuDomainListAllSnapshots): New functions.
2012-06-19 14:58:45 -06:00
Eric Blake
7e111c6fe6 snapshot: merge domain and snapshot computation
Now that domain listing is a thin wrapper around child listing,
it's easier to have a common entry point.  This restores the
hashForEach optimization lost in the previous patch when there
are no snapshots being filtered out of the entire list.

* src/conf/domain_conf.h (virDomainSnapshotObjListGetNames)
(virDomainSnapshotObjListNum): Add parameter.
(virDomainSnapshotObjListGetNamesFrom)
(virDomainSnapshotObjListNumFrom): Delete.
* src/libvirt_private.syms (domain_conf.h): Drop deleted functions.
* src/conf/domain_conf.c (virDomainSnapshotObjListGetNames):
Merge, and (re)add an optimization.
* src/qemu/qemu_driver.c (qemuDomainUndefineFlags)
(qemuDomainSnapshotListNames, qemuDomainSnapshotNum)
(qemuDomainSnapshotListChildrenNames)
(qemuDomainSnapshotNumChildren): Update callers.
* src/qemu/qemu_migration.c (qemuMigrationIsAllowed): Likewise.
* src/conf/virdomainlist.c (virDomainListPopulate): Likewise.
2012-06-18 15:11:28 -06:00
Eric Blake
06d4a1e429 snapshot: use metaroot node to simplify management
This idea was first suggested by Daniel Veillard here:
https://www.redhat.com/archives/libvir-list/2011-October/msg00353.html

Now that I am about to add more complexity to snapshot listing, it
makes sense to avoid code duplication and special casing for domain
listing (all snapshots) vs. snapshot listing (descendants); adding
a metaroot reduces the number of code lines by having the domain
listing turn into a descendant listing of the metaroot.

Note that this has one minor pessimization - if we are going to list
ALL snapshots without filtering, then virHashForeach is more efficient
than recursing through the child relationships; restoring that minor
optimization will occur in the next patch.

* src/conf/domain_conf.h (_virDomainSnapshotObj)
(_virDomainSnapshotObjList): Repurpose some fields.
(virDomainSnapshotDropParent): Drop unused parameter.
* src/conf/domain_conf.c (virDomainSnapshotObjListGetNames)
(virDomainSnapshotObjListCount): Simplify.
(virDomainSnapshotFindByName, virDomainSnapshotSetRelations)
(virDomainSnapshotDropParent): Match new field semantics.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML)
(qemuDomainSnapshotReparentChildren, qemuDomainSnapshotDelete):
Adjust clients.
2012-06-18 15:11:28 -06:00
Peter Krempa
bc8e15592c conf: Store managed save image existence in virDomainObj
This patch stores existence of the image in the object. At start of the
daemon the state is checked and then updated in key moments in domain
lifecycle.
2012-06-18 21:24:13 +02:00
Wen Congyang
cdef31c562 qemu: allow the client to choose the vmcore's format
This patch updates qemu driver to allow the client to choose the
vmcore's format: memory only or including device state.
2012-06-15 20:36:14 +08:00
Wen Congyang
5136c5799f qemu: fix potential dead lock
If we lock the qemu_driver, we should call qemuDomainObjBeginJobWithDriver()
not qemuDomainObjBeginJob().
2012-06-15 20:25:35 +08:00
Michal Privoznik
69dd77149c qemuProcessStop: Switch to flags
Currently, we are passing only one boolean (migrated) so there is
no real profit in this. But it creates starting position for
next patch.
2012-06-12 09:57:02 +02:00
Eric Blake
e3559a6e66 snapshot: implement new APIs for qemu
The two APIs are rather trivial; based on bits and pieces of other
existing APIs.  It leaves the door open for future extension to
qemu to report snapshots without metadata based on reading qcow2
internal snapshot names.

* src/qemu/qemu_driver.c (qemuDomainSnapshotIsCurrent)
(qemuDomainSnapshotHasMetadata): New functions.
2012-06-11 15:23:02 -06:00
Wen Congyang
0a045f01cf avoid closing uninitialized fd
If the system does not support bypass cache, we will close fd,
but it is uninitialized.
2012-05-30 13:55:49 -06:00
Stefan Berger
67dd486f20 leak_fix.diff
==3240== 23 bytes in 1 blocks are definitely lost in loss record 242 of 744
==3240==    at 0x4C2A4CD: malloc (vg_replace_malloc.c:236)
==3240==    by 0x8077537: __vasprintf_chk (vasprintf_chk.c:82)
==3240==    by 0x509C677: virVasprintf (stdio2.h:199)
==3240==    by 0x509C733: virAsprintf (util.c:1912)
==3240==    by 0x1906583A: qemudStartup (qemu_driver.c:679)
==3240==    by 0x511991D: virStateInitialize (libvirt.c:809)
==3240==    by 0x40CD84: daemonRunStateInit (libvirtd.c:751)
==3240==    by 0x5098745: virThreadHelper (threads-pthread.c:161)
==3240==    by 0x7953D8F: start_thread (pthread_create.c:309)
==3240==    by 0x805FF5C: clone (clone.S:115)
2012-05-29 06:25:59 -04:00
Daniel P. Berrange
517368a377 Remove uid param from directory lookup APIs
Remove the uid param from virGetUserConfigDirectory,
virGetUserCacheDirectory, virGetUserRuntimeDirectory,
and virGetUserDirectory

These functions were universally called with the
results of getuid() or geteuid(). To make it practical
to port to Win32, remove the uid parameter and hardcode
geteuid()

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-05-28 10:55:06 +01:00
Daniel P. Berrange
2cb0899eec Fix potential events deadlock when unref'ing virConnectPtr
When the last reference to a virConnectPtr is released by
libvirtd, it was possible for a deadlock to occur in the
virDomainEventState functions. The virDomainEventStatePtr
holds a reference on virConnectPtr for each registered
callback. When removing a callback, the virUnrefConnect
function is run. If this causes the last reference on the
virConnectPtr to be released, then virReleaseConnect can
be run, which in turns calls qemudClose. This function has
a call to virDomainEventStateDeregisterConn which is intended
to remove all callbacks associated with the virConnectPtr
instance. This will try to grab a lock on virDomainEventState
but this lock is already held. Deadlock ensues

Thread 1 (Thread 0x7fcbb526a840 (LWP 23185)):

Since each callback associated with a virConnectPtr holds a
reference on virConnectPtr, it is impossible for the qemudClose
method to be invoked while any callbacks are still registered.
Thus the call to virDomainEventStateDeregisterConn must in fact
be a no-op. Thus it is possible to just remove all trace of
virDomainEventStateDeregisterConn and avoid the deadlock.

* src/conf/domain_event.c, src/conf/domain_event.h,
  src/libvirt_private.syms: Delete virDomainEventStateDeregisterConn
* src/libxl/libxl_driver.c, src/lxc/lxc_driver.c,
  src/qemu/qemu_driver.c, src/uml/uml_driver.c: Remove
  calls to virDomainEventStateDeregisterConn
2012-05-21 18:50:47 +01:00
Hu Tao
fe0aac0503 Adds support to param 'vcpu_time' in qemu_driver.
This involves setting the cpuacct cgroup to a per-vcpu granularity,
as well as summing the each vcpu accounting into a common array.
Now that we are reading more than one cgroup file, we double-check
that cpus weren't hot-plugged between reads to invalidate our
summing.

Signed-off-by: Eric Blake <eblake@redhat.com>
2012-05-18 08:53:49 -06:00
Daniel Walsh
73580c60d1 Pass the virt driver name into security drivers
To allow the security drivers to apply different configuration
information per hypervisor, pass the virtualization driver name
into the security manager constructor.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-05-16 10:05:46 +01:00
Jiri Denemark
63b4243624 qemu: Add support for -no-user-config
Thanks to this new option we are now able to use modern CPU models (such
as Westmere) defined in external configuration file.

The qemu-1.1{,-device} data files for qemuhelptest are filled in with
qemu-1.1-rc2 output for now. I will update those files with real
qemu-1.1 output once it is released.
2012-05-15 20:29:12 +02:00
William Jon McCann
32a9aac2e0 Use XDG Base Directories instead of storing in home directory
As defined in:
http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

This offers a number of advantages:
 * Allows sharing a home directory between different machines, or
sessions (eg. using NFS)
 * Cleanly separates cache, runtime (eg. sockets), or app data from
user settings
 * Supports performing smart or selective migration of settings
between different OS versions
 * Supports reseting settings without breaking things
 * Makes it possible to clear cache data to make room when the disk
is filling up
 * Allows us to write a robust and efficient backup solution
 * Allows an admin flexibility to change where data and settings are stored
 * Dramatically reduces the complexity and incoherence of the
system for administrators
2012-05-14 15:15:58 +01:00
Peter Krempa
3163682b58 qemu: Re-detect virtual cpu threads after cpu hot (un)plug.
After a cpu hotplug the qemu driver did not refresh information about
virtual processors used by qemu and their corresponding threads. This
patch forces a re-detection as is done on start of QEMU.

This ensures that correct information is reported by the
virDomainGetVcpus API and "virsh vcpuinfo".

A failure to obtain the thread<->vcpu mapping is treated non-fatal and
the mapping is not updated in a case of failure as not all versions of
QEMU report this in the info cpus command.
2012-05-11 16:40:05 +02:00
Peter Krempa
e99ad93d02 qemu: Refactor qemuDomainSetVcpusFlags
This patch changes a switch statement into ifs when handling live vs.
configuration modifications getting rid of redundant code in case when
both live and persistent configuration gets changed.
2012-05-11 16:40:05 +02:00
Eric Blake
8be304ecb9 snapshot: allow block devices past cgroup
It turns out that when cgroups are enabled, the use of a block device
for a snapshot target was failing with EPERM due to libvirt failing
to add the block device to the cgroup whitelist.  See also
https://bugzilla.redhat.com/show_bug.cgi?id=810200

* src/qemu/qemu_driver.c
(qemuDomainSnapshotCreateSingleDiskActive)
(qemuDomainSnapshotUndoSingleDiskActive): Account for cgroup.
(qemuDomainSnapshotCreateDiskActive): Update caller.
2012-05-08 15:59:58 -06:00
Jiri Denemark
409b5f5495 qemu: Emit compatible XML when migrating a domain
When we added the default USB controller into domain XML, we efficiently
broke migration to older versions of libvirt that didn't support USB
controllers at all (0.9.4 and earlier) even for domains that don't use
anything that the older libvirt can't provide. We still want to present
the default USB controller in any XML seen by a user/app but we can
safely remove it from the domain XML used during migration. If we are
migrating to a new enough libvirt, it will add the controller XML back,
while older libvirt won't be confused with it although it will still
tell qemu to create the controller.

Similar approach can be used in the future whenever we find out we
always enabled some kind of device without properly advertising it in
domain XML.
2012-05-07 14:26:02 +02:00
Jiri Denemark
cd603008b1 qemu: Don't use virDomainDefFormat* directly
Always use appropriate qemuDomain{,Def}Format wrapper since it may do
some additional magic based on the flags.
2012-05-05 00:37:30 +02:00
Eric Blake
13f9a19326 qemu: reject blockiotune if qemu too old
Commit 4c82f09e added a capability check for qemu per-device io
throttling, but only applied it to domain startup.  As mentioned
in the previous commit (98cec05), the user can still get an 'internal
error' message during a hotplug attempt, when the monitor command
doesn't exist.  It is confusing to allow tuning on inactive domains
only to then be rejected when starting the domain.

* src/qemu/qemu_driver.c (qemuDomainSetBlockIoTune): Reject
offline tuning if online can't match it.
2012-05-04 16:13:56 -06:00
Eric Blake
98cec05288 qemu: don't modify domain on failed blockiotune
If you have a qemu build that lacks the blockio tune monitor command,
then this command:

$ virsh blkdeviotune rhel6u2 hda --total_bytes_sec 1000
error: Unable to change block I/O throttle
error: internal error Unexpected error

fails as expected (well, the error message is lousy), but the next
dumpxml shows that the domain was modified anyway.  Worse, that means
if you save the domain then restore it, the restore will likely fail
due to throttling being unsupported, even though no throttling should
even be active because the monitor command failed in the first place.

* src/qemu/qemu_driver.c (qemuDomainSetBlockIoTune): Check for
error before making modification permanent.
2012-05-04 16:13:53 -06:00
Stefan Berger
c0774482ff qemu: fix resource leak
Error: RESOURCE_LEAK:
/libvirt/src/qemu/qemu_driver.c:6968:
alloc_fn: Calling allocation function "calloc".
/libvirt/src/qemu/qemu_driver.c:6968:
var_assign: Assigning: "nodeset" =  storage returned from "calloc(1UL, 1UL)".
/libvirt/src/qemu/qemu_driver.c:6977:
noescape: Variable "nodeset" is not freed or pointed-to in function "virTypedParameterAssign".
/libvirt/src/qemu/qemu_driver.c:6997:
leaked_storage: Variable "nodeset" going out of scope leaks the storage it points to.
2012-05-04 10:42:09 -04:00
Li Zhang
0d631e9182 Correct indent errors in the function qemuDomainNetsRestart
qemuDomainNetsRestart indents with 3 spaces.

This patch is to correct it.

Signed-off-by: Li Zhang <zhlcindy@linux.vnet.ibm.com>
2012-05-03 17:25:40 +08:00
Josh Durgin
b57e01532a qemu: allow snapshotting of sheepdog and rbd disks
Signed-off-by: Josh Durgin <josh.durgin@dreamhost.com>
2012-05-01 08:54:18 -06:00
Jiri Denemark
9d2ac5453e qemu: Make sure qemu can access its directory in hugetlbfs
When libvirtd is started, we create "libvirt/qemu" directories under
hugetlbfs mount point. Only the "qemu" subdirectory is chowned to qemu
user and "libvirt" remains owned by root. If umask was too restrictive
when libvirtd started, qemu user may lose access to "qemu"
subdirectory. Let's explicitly grant search permissions to "libvirt"
directory for all users.
2012-04-30 08:17:40 +02:00
Eric Blake
2eabac008e blockjob: fix block-stream bandwidth race
With RHEL 6.2, virDomainBlockPull(dom, dev, bandwidth, 0) has a race
with non-zero bandwidth: there is a window between the block_stream
and block_job_set_speed monitor commands where an unlimited amount
of data was let through, defeating the point of a throttle.

This race was first identified in commit a9d3495e, and libvirt was
able to reduce the size of the window for that race.  In the meantime,
the qemu developers decided to fix things properly; per this message:
https://lists.gnu.org/archive/html/qemu-devel/2012-04/msg03793.html
the fix will be in qemu 1.1, and changes block-job-set-speed to use
a different parameter name, as well as adding a new optional parameter
to block-stream, which eliminates the race altogether.

Since our documentation already mentioned that we can refuse a non-zero
bandwidth for some hypervisors, I think the best solution is to do
just that for RHEL 6.2 qemu, so that the race is obvious to the user
(anyone using stock RHEL 6.2 binaries won't have this patch, and anyone
building their own libvirt with this patch for RHEL can also rebuild
qemu to get the modern semantics, so it is no real loss in behavior).

Meanwhile the code must be fixed to honor actual qemu 1.1 naming.
Rename the parameter to 'modern', since the naming difference now
covers more than just 'async' block-job-cancel.  And while at it,
fix an unchecked integer overflow.

* src/qemu/qemu_monitor.h (enum BLOCK_JOB_CMD): Drop unused value,
rename enum to match conventions.
* src/qemu/qemu_monitor.c (qemuMonitorBlockJob): Reflect enum rename.
* src/qemu_qemu_monitor_json.h (qemuMonitorJSONBlockJob): Likewise.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONBlockJob): Likewise,
and support difference between RHEL 6.2 and qemu 1.1 block pull.
* src/qemu/qemu_driver.c (qemuDomainBlockJobImpl): Reject
bandwidth during pull with too-old qemu.
* src/libvirt.c (virDomainBlockPull, virDomainBlockRebase):
Document this.
2012-04-27 13:00:56 -06:00
Jiri Denemark
2d76fea134 qemu: Use common helper when probing qemu capabilities
QEMU binary is called several times when we probe different kinds of
capabilities the binary supports. This patch introduces new common
helper so that all probes use a consistent way of invoking qemu.
2012-04-27 12:09:32 +02:00
Eric Blake
8e532d3403 qemu: improve errors related to offline domains
https://bugzilla.redhat.com/show_bug.cgi?id=816662 pointed out
that attempting 'virsh blockpull' on an offline domain gave a
misleading error message about qemu lacking support for the
operation, even when qemu was specifically updated to support it.
The real problem is that we have several capabilities that are
only determined when starting a domain, and therefore are still
clear when first working with an inactive domain (namely, any
capability set by qemuMonitorJSONCheckCommands).

While this patch was able to hoist an existing check in one of the
three culprits, it had to add redundant checks in the other two
places (because you always have to check for an active domain after
obtaining a VM job lock, but the capability bits were being checked
prior to obtaining the job lock).

Someday it would be nice to patch libvirt to cache the set of
capabilities per qemu binary (as determined by inode and timestamp),
rather than re-probing the binary every time a domain is started,
and to teach the cache how to query the monitor during the one
time the probe is made rather than having to wait until a guest
is started; then, a capability probe would succeed even for offline
guests because it just refers to the cache, and the single check for
an active domain after grabbing the job lock would be sufficient.
But since that will involve a lot more coding, I'm happy to go
with this simpler solution for an immediate solution.

* src/qemu/qemu_driver.c (qemuDomainPMSuspendForDuration)
(qemuDomainSnapshotCreateXML, qemuDomainBlockJobImpl): Check for
offline state before checking an online-only cap.
2012-04-26 16:43:05 -06:00
Eric Blake
6fb8a64d93 qemu: use consistent error when qemu binary is too old
Most of our errors complaining about an inability to support a
particular action due to qemu limitations used CONFIG_UNSUPPORTED,
but we had a few outliers.  Reported by Jiri Denemark.

* src/qemu/qemu_command.c (qemuBuildDriveDevStr): Prefer
CONFIG_UNSUPPORTED.
* src/qemu/qemu_driver.c (qemuDomainReboot)
(qemuDomainBlockJobImpl): Likewise.
* src/qemu/qemu_hotplug.c (qemuDomainAttachPciControllerDevice):
Likewise.
* src/qemu/qemu_monitor.c (qemuMonitorTransaction)
(qemuMonitorBlockJob, qemuMonitorSystemWakeup): Likewise.
2012-04-17 11:09:44 -06:00
Michal Privoznik
63ddc65d63 qemuProcessStart: Switch to flags instead of bunch booleans
Currently, we have 3 boolean arguments we have to pass
to qemuProcessStart(). As libvirt grows it is harder and harder
to remember them and their position. Therefore we should
switch to flags instead.
2012-04-16 17:20:04 +02:00
Michal Privoznik
b1256816ff qemuOpenFile: Don't force chown on NFS
If dynamic_ownership is off and we are creating a file on NFS
we force chown. This will fail as chown/chmod are not supported
on NFS. However, with no dynamic_ownership we are not required
to do any chown.
2012-04-12 13:53:38 +02:00
Eric Blake
a9d3495e67 blockjob: allow for fast-finishing job
In my testing, I was able to provoke an odd block pull failure:

$ virsh blockpull dom vda --bandwidth 10000
error: Requested operation is not valid: No active operation on device: drive-virtio-disk0

merely by using gdb to artifically wait to do the block job set speed
until after the pull had already finished.  But in reality, that should
be a success, since the pull finished before we had a chance to set
speed.  Furthermore, using a double job lock is not only annoying, but
a bug in itself - if you do parallel virDomainBlockRebase, and hit
the race window just right, the first call grabs the VM job to start
a fast block job, then the second call grabs the VM job to start
a long-running job with unspecified speed, then the first call finally
regrabs the VM job and sets the speed, which ends up running the
second job under the speed from the first call.  By consolidating
things into a single job, we avoid opening that race, as well as reduce
the time between starting the job and changing the speed, for less
likelihood of the speed change happening after block job completion
in the first place.

* src/qemu/qemu_monitor.h (BLOCK_JOB_CMD): Add new mode.
* src/qemu/qemu_driver.c (qemuDomainBlockRebase): Move secondary
job call...
(qemuDomainBlockJobImpl): ...here, for fewer locks.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONBlockJob): Change
return value on new internal mode.
2012-04-11 21:45:43 -06:00
Eric Blake
a91ce852b5 blockjob: wire up qemu async virDomainBlockJobAbort
Without the VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC flag, libvirt will internally
poll using qemu's "query-block-jobs" API and will not return until the
operation has been completed.  API users are advised that this operation
is unbounded and further interaction with the domain during this period
may block.  Future patches may refactor things to allow other queries in
parallel with this polling.  For older qemu, we synthesize the cancellation
event, since qemu won't generate it.

The choice of polling duration copies from the code in qemu_migration.c.

Signed-off-by: Adam Litke <agl@us.ibm.com>
Cc: Stefan Hajnoczi <stefanha@gmail.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2012-04-11 21:22:06 -06:00
Eric Blake
2b085f5bc5 blockjob: add qemu capabilities related to block pull jobs
RHEL 6.2 was released with an early version of block jobs, which only
worked on the qed file format, where the commands were spelled with
underscore (contrary to QMP style), and where 'block_job_cancel' was
synchronous and did not trigger an event.

The upcoming qemu 1.1 release has fixed these short-comings [1][2]:
the commands now work on multiple file types, are spelled with dash,
and 'block-job-cancel' is asynchronous and emits an event upon conclusion.

[1]qemu commit 370521a1d6f5537ea7271c119f3fbb7b0fa57063
[2]https://lists.gnu.org/archive/html/qemu-devel/2012-04/msg01248.html

This patch recognizes the new spellings, and fixes virDomainBlockRebase
to give a graceful error when talking to a too-old qemu on a partial
rebase attempt.  Fixes for the new semantics will come later.  This
patch also removes a bogus ATTRIBUTE_NONNULL mistakenly added in
commit 10ec36e2.

* src/qemu/qemu_capabilities.h (QEMU_CAPS_BLOCKJOB_SYNC)
(QEMU_CAPS_BLOCKJOB_ASYNC): New bits.
* src/qemu/qemu_capabilities.c (qemuCaps): Name them.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONCheckCommands): Set
them.
(qemuMonitorJSONBlockJob): Manage both command names.
(qemuMonitorJSONDiskSnapshot): Minor formatting fix.
* src/qemu/qemu_monitor.h (qemuMonitorBlockJob): Alter signature.
* src/qemu/qemu_monitor_json.h (qemuMonitorJSONBlockJob): Likewise.
* src/qemu/qemu_monitor.c (qemuMonitorBlockJob): Pass through
capability bit.
* src/qemu/qemu_driver.c (qemuDomainBlockJobImpl): Update callers.
2012-04-11 20:43:53 -06:00
Peter Krempa
3d3de46a67 qemu: Fix deadlock when qemuDomainOpenConsole cleans up a connection
The new safe console handling introduced a possibility to deadlock the
qemu driver when a new console connection forcibly disconnects a
previous console stream that belongs to an already closed connection.

The virStreamFree function calls subsequently a the virReleaseConnect
function that tries to lock the driver while discarding the connection,
but the driver was already locked in qemuDomainOpenConsole.

Backtrace of the deadlocked thread:
0  0x00007f66e5aa7f14 in __lll_lock_wait () from /lib64/libpthread.so.0
1  0x00007f66e5aa3411 in _L_lock_500 () from /lib64/libpthread.so.0
2  0x00007f66e5aa322a in pthread_mutex_lock () from/lib64/libpthread.so.0
3  0x0000000000462bbd in qemudClose ()
4  0x00007f66e6e178eb in virReleaseConnect () from/usr/lib64/libvirt.so.0
5  0x00007f66e6e19c8c in virUnrefStream () from /usr/lib64/libvirt.so.0
6  0x00007f66e6e3d1de in virStreamFree () from /usr/lib64/libvirt.so.0
7  0x00007f66e6e09a5d in virConsoleHashEntryFree () from/usr/lib64/libvirt.so.0
8  0x00007f66e6db7282 in virHashRemoveEntry () from/usr/lib64/libvirt.so.0
9  0x00007f66e6e09c4e in virConsoleOpen () from /usr/lib64/libvirt.so.0
10 0x00000000004526e9 in qemuDomainOpenConsole ()
11 0x00007f66e6e421f1 in virDomainOpenConsole () from/usr/lib64/libvirt.so.0
12 0x00000000004361e4 in remoteDispatchDomainOpenConsoleHelper ()
13 0x00007f66e6e80375 in virNetServerProgramDispatch () from/usr/lib64/libvirt.so.0
14 0x00007f66e6e7ae11 in virNetServerHandleJob () from/usr/lib64/libvirt.so.0
15 0x00007f66e6da897d in virThreadPoolWorker () from/usr/lib64/libvirt.so.0
16 0x00007f66e6da7ff6 in virThreadHelper () from/usr/lib64/libvirt.so.0
17 0x00007f66e5aa0c5c in start_thread () from /lib64/libpthread.so.0
18 0x00007f66e57e7fcd in clone () from /lib64/libc.so.6

* src/qemu/qemu_driver.c: qemuDomainOpenConsole()
        -- unlock the qemu driver right after acquiring the domain
        object
2012-04-11 10:45:53 +02:00
Eric Blake
1413560966 snapshot: fix memory leak on error
Leak introduced in commit 0436d32.  If we allocate an actions array,
but fail early enough to never consume it with the qemu monitor
transaction call, we leaked memory.

But our semantics of making the transaction command free the caller's
memory is awkward; avoiding the memory leak requires making every
intermediate function in the call chain check for error.  It is much
easier to fix things so that the function that allocates also frees,
while the call chain leaves the caller's data intact.  To do that,
I had to hack our JSON data structure to make it easy to protect a
portion of an arbitrary JSON tree from being freed.

* src/util/json.h (virJSONType): Name the enum.
(_virJSONValue): New field.
* src/util/json.c (virJSONValueFree): Use it to protect a portion
of an array.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONTransaction): Avoid
freeing caller's data.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateDiskActive):
Free actions array on failure.
2012-04-06 08:39:34 -06:00
Michal Privoznik
650da0e99c qemu_ga: Don't overwrite errors on FSThaw
We can tell qemuDomainSnapshotFSThaw if we want it to report errors or
not. However, if we don't want to and an error has been already set by
previous qemuReportError() we must keep copy of that error not just a
pointer to it. Otherwise, it get overwritten if FSThaw reports an error.
2012-04-06 13:42:04 +02:00
Jiri Denemark
66cab01ae1 qemu: Start nested job in qemuDomainCheckEjectableMedia
Originally, qemuDomainCheckEjectableMedia was entering monitor with qemu
driver lock. Commit 2067e31bf9, which I
made to fix that, revealed another issue we had (but didn't notice it
since the driver was locked): we didn't set nested job when
qemuDomainCheckEjectableMedia is called during migration. Thus the
original fix I made was wrong.
2012-04-02 21:44:27 +02:00
Daniel P. Berrange
ec8cae93db Consistent style for usage of sizeof operator
The code is splattered with a mix of

  sizeof foo
  sizeof (foo)
  sizeof(foo)

Standardize on sizeof(foo) and add a syntax check rule to
enforce it

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-30 11:47:24 +01:00
Eric Blake
a14eda311e snapshot: don't pass NULL to QMP command creation
Commit d42a2ff caused a regression in creating a disk-only snapshot
of a qcow2 disk; by passing the wrong variable to the monitor call,
libvirt ended up creating JSON that looked like "format":null instead
of the intended "format":"qcow2".

To make it easier to diagnose this in the future, make JSON creation
error out if "s:arg" is paired with NULL (it is still possible to
use "n:arg" in the rare cases where qemu will accept a null).

* src/qemu/qemu_driver.c
(qemuDomainSnapshotCreateSingleDiskActive): Pass correct value.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONMakeCommandRaw):
Improve error message.
2012-03-27 09:34:07 -06:00
D. Herrendoerfer
bd6b0a052e qemu,util: on restart of libvirt restart vepa callbacks
When libvirtd is restarted, also restart the netlink event
message callbacks for existing VEPA connections and send
a message to lldpad for these existing links, so it learns
the new libvirtd pid.

Signed-off-by: D. Herrendoerfer <d.herrendoerfer@herrendoerfer.name>
2012-03-27 10:48:39 -04:00
Laine Stump
cf57d345b5 build: avoid frame size error when building without -O2
libvirt always adds -Werror-frame-larger-than=4096 to the flags when
it builds. When building on Fedora 17, two functions with multiple
1024 buffers declared inside if {} blocks would generate frame size
errors; apparently the version of gcc on Fedora 16 will merge these
multiple buffers into a single buffer even when optimization is off,
but Fedora 17 won't.

The fix is to declare a single 1024 buffer at the top of the two
offending functions, and reuse the single buffer throughout the
functions.
2012-03-26 17:08:30 -04:00
Martin Kletzander
9943276fd2 Cleanup for a return statement in source files
Return statements with parameter enclosed in parentheses were modified
and parentheses were removed. The whole change was scripted, here is how:

List of files was obtained using this command:
git grep -l -e '\<return\s*([^()]*\(([^()]*)[^()]*\)*)\s*;' |             \
grep -e '\.[ch]$' -e '\.py$'

Found files were modified with this command:
sed -i -e                                                                 \
's_^\(.*\<return\)\s*(\(\([^()]*([^()]*)[^()]*\)*\))\s*\(;.*$\)_\1 \2\4_' \
-e 's_^\(.*\<return\)\s*(\([^()]*\))\s*\(;.*$\)_\1 \2\3_'

Then checked for nonsense.

The whole command looks like this:
git grep -l -e '\<return\s*([^()]*\(([^()]*)[^()]*\)*)\s*;' |             \
grep -e '\.[ch]$' -e '\.py$' | xargs sed -i -e                            \
's_^\(.*\<return\)\s*(\(\([^()]*([^()]*)[^()]*\)*\))\s*\(;.*$\)_\1 \2\4_' \
-e 's_^\(.*\<return\)\s*(\([^()]*\))\s*\(;.*$\)_\1 \2\3_'
2012-03-26 14:45:22 -06:00
Eric Blake
d42a2ffc07 snapshot: improve qemu handling of reused snapshot targets
The oVirt developers have stated that the real reasons they want
to have qemu reuse existing volumes when creating a snapshot are:
1. the management framework is set up so that creation has to be
done from a central node for proper resource tracking, and having
libvirt and/or qemu create things violates the framework, and
2. qemu defaults to creating snapshots with an absolute path to
the backing file, but oVirt wants to manage a backing chain that
uses just relative names, to allow for easier migration of a chain
across storage locations.

When 0.9.10 added VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT (commit
4e9953a4), it only addressed point 1, but libvirt was still using
O_TRUNC which violates point 2.  Meanwhile, the new qemu
'transaction' monitor command includes a new optional mode argument
that will force qemu to reuse the metadata of the file it just
opened (with the burden on the caller to have valid metadata there
in the first place).  So, this tweaks the meaning of the flag to
cover both points as intended for use by oVirt.  It is not strictly
backward-compatible to 0.9.10 behavior, but it can be argued that
the O_TRUNC of 0.9.10 was a bug.

Note that this flag is all-or-nothing, and only selects between
'existing' and the default 'absolute-paths'.  A more flexible
approach that would allow per-disk selections, as well as adding
support for the 'no-backing-file' mode, would be possible by
extending the <domainsnapshot> xml to have a per-disk mode, but
until we have a management application expressing a need for that
additional complexity, it is not worth doing.

* src/libvirt.c (virDomainSnapshotCreateXML): Tweak documentation.
* src/qemu/qemu_monitor.h (qemuMonitorDiskSnapshot): Add
parameters.
* src/qemu/qemu_monitor_json.h (qemuMonitorJSONDiskSnapshot):
Likewise.
* src/qemu/qemu_monitor.c (qemuMonitorDiskSnapshot): Pass them
through.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONDiskSnapshot): Use
new monitor command arguments.
* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateDiskActive)
(qemuDomainSnapshotCreateSingleDiskActive): Adjust callers.
(qemuDomainSnapshotDiskPrepare): Allow qed, modify rules on reuse.
2012-03-23 16:38:20 -06:00
Eric Blake
0436d328f5 snapshot: wire up qemu transaction command
The hardest part about adding transactions is not using the new
monitor command, but undoing the partial changes we made prior
to a failed transaction.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateDiskActive): Use
transaction when available.
(qemuDomainSnapshotUndoSingleDiskActive): New function.
(qemuDomainSnapshotCreateSingleDiskActive): Pass through actions.
(qemuDomainSnapshotCreateXML): Adjust caller.
2012-03-23 16:38:20 -06:00
Eric Blake
64d5e815b7 snapshot: add support for qemu transaction command
QEmu 1.1 is adding a 'transaction' command to the JSON monitor.
Each element of a transaction corresponds to a top-level command,
with the additional guarantee that the transaction flushes all
pending I/O, then guarantees that all actions will be successful
as a group or that failure will roll back the state to what it
was before the monitor command.  The difference between a
top-level command:

{ "execute": "blockdev-snapshot-sync", "arguments":
  { "device": "virtio0", ... } }

and a transaction:

{ "execute": "transaction", "arguments":
  { "actions": [
    { "type": "blockdev-snapshot-sync", "data":
      { "device": "virtio0", ... } } ] } }

is just a couple of changed key names and nesting the shorter
command inside a JSON array to the longer command.  This patch
just adds the framework; the next patch will actually use a
transaction.

* src/qemu/qemu_monitor_json.c (qemuMonitorJSONMakeCommand): Move
guts...
(qemuMonitorJSONMakeCommandRaw): ...into new helper.  Add support
for array element.
(qemuMonitorJSONTransaction): New command.
(qemuMonitorJSONDiskSnapshot): Support use in a transaction.
* src/qemu/qemu_monitor_json.h (qemuMonitorJSONDiskSnapshot): Add
argument.
(qemuMonitorJSONTransaction): New declaration.
* src/qemu/qemu_monitor.h (qemuMonitorTransaction): Likewise.
(qemuMonitorDiskSnapshot): Add argument.
* src/qemu/qemu_monitor.c (qemuMonitorTransaction): New wrapper.
(qemuMonitorDiskSnapshot): Pass argument on.
* src/qemu/qemu_driver.c
(qemuDomainSnapshotCreateSingleDiskActive): Update caller.
2012-03-23 16:38:20 -06:00
Eric Blake
4c4cc1b96d snapshot: rudimentary qemu support for atomic disk snapshot
Taking an external snapshot of just one disk is atomic, without having
to pause and resume the VM.  This also paves the way for later patches
to interact with the new qemu 'transaction' monitor command.

The various scenarios when requesting atomic are:
online, 1 disk, old qemu - safe, allowed by this patch
online, more than 1 disk, old qemu - failure, this patch
offline snapshot - safe, once a future patch implements offline disk snapshot
online, 1 or more disks, new qemu - safe, once future patch uses transaction

Taking an online system checkpoint snapshot is atomic, since it is
done via a single 'savevm' monitor command.  Taking an offline system
checkpoint snapshot is atomic, thanks to the previous patch.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateXML): Support
new flag for single-disk setups.
(qemuDomainSnapshotDiskPrepare): Check for atomic here.
(qemuDomainSnapshotCreateDiskActive): Skip pausing the VM when
atomic supported.
(qemuDomainSnapshotIsAllowed): Use bool instead of int.
2012-03-23 16:38:20 -06:00
Daniel P. Berrange
1f66c18f79 Centralize error reporting for URI parsing/formatting problems
Move error reporting out of the callers, into virURIParse
and virURIFormat, to get consistency.

* include/libvirt/virterror.h, src/util/virterror.c: Add VIR_FROM_URI
* src/util/viruri.c, src/util/viruri.h: Add error reporting
* src/esx/esx_driver.c, src/libvirt.c, src/libxl/libxl_driver.c,
  src/lxc/lxc_driver.c, src/openvz/openvz_driver.c,
  src/qemu/qemu_driver.c, src/qemu/qemu_migration.c,
  src/remote/remote_driver.c, src/uml/uml_driver.c,
  src/vbox/vbox_tmpl.c, src/vmx/vmx.c, src/xen/xen_driver.c,
  src/xen/xend_internal.c, tests/viruritest.c: Remove error
  reporting

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2012-03-23 12:59:21 +00:00
Jiri Denemark
1fdc53c385 qemu: Avoid dangling migration-out job when client dies
When a client which started non-p2p migration dies in a bad time, the
source libvirtd never clears the migration job and almost nothing can be
done with the domain without restarting the daemon. This patch makes use
of connection close callbacks and ensures that migration job is properly
discarded when the client disconnects.
2012-03-21 17:31:09 +01:00
Jiri Denemark
527d867a94 qemu: Make autodestroy utilize connection close callbacks 2012-03-21 17:31:09 +01:00
Jiri Denemark
791273603e qemu: Add connection close callbacks
Add support for registering arbitrary callback to be called for a domain
when a connection gets closed.
2012-03-21 17:31:09 +01:00
Eric Blake
7c736bab06 snapshot: make quiesce a bit safer
If a guest is paused, we were silently ignoring the quiesce flag,
which results in unclean snapshots, contrary to the intent of the
flag.  Since we can't quiesce without guest agent support, we should
instead fail if the guest is not running.

Meanwhile, if we attempt a quiesce command, but the guest agent
doesn't respond, and we time out, we may have left the command
pending on the guest's queue, and when the guest resumes parsing
commands, it will freeze even though our command is no longer
around to issue a thaw.  To be safe, we must _always_ pair every
quiesce call with a counterpart thaw, even if the quiesce call
failed due to a timeout, so that if a guest wakes up and starts
processing a command backlog, it will not get stuck in a frozen
state.

* src/qemu/qemu_driver.c (qemuDomainSnapshotCreateDiskActive):
Always issue thaw after a quiesce, even if quiesce failed.
(qemuDomainSnapshotFSThaw): Add a parameter.
2012-03-19 10:58:18 -06:00
Daniel P. Berrange
f987d17511 Fix handling of blkio deviceWeight empty string
A common coding pattern for changing blkio parameters is

  1. virDomainGetBlkioParameters

  2. change one or more params

  3. virDomainSetBlkioParameters

For this to work, it must be possible to roundtrip through
the methods without error. Unfortunately virDomainGetBlkioParameters
will return "" for the deviceWeight parameter for guests by default,
which virDomainSetBlkioParameters will then reject as invalid.

This fixes the handling of "" to be a no-op, and also improves the
error message to tell you what was invalid
2012-03-16 15:05:05 +00:00
Osier Yang
3165602a55 qemu: Use scsi-block for lun passthrough instead of scsi-disk
And don't allow to hotplug a usb disk with "device == lun". This
is the missed pieces in previous virtio-scsi patchset:

http://www.redhat.com/archives/libvir-list/2012-February/msg01052.html
2012-03-14 23:32:53 +08:00
Jiri Denemark
041109afef qemu: Fix (managed)save and snapshots with host mode CPU
When host-model and host-passthrouh CPU modes were introduced, qemu
driver was properly modify to update guest CPU definition during
migration so that we use the right CPU at the destination. However,
similar treatment is needed for (managed)save and snapshots since they
need to save the exact CPU so that a domain can be properly restored.
To avoid repetition of such situation, all places that need live XML
share the code which generates it.

As a side effect, this patch fixes error reporting from
qemuDomainSnapshotWriteMetadata().
2012-03-13 07:59:36 +01:00
Eric Blake
759095f636 cpustats: report user and sys times
Thanks to cgroups, providing user vs. system time of the overall
guest is easy to add to our existing API.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_CPU_STATS_USERTIME)
(VIR_DOMAIN_CPU_STATS_SYSTEMTIME): New constants.
* src/util/virtypedparam.h (virTypedParameterArrayValidate)
(virTypedParameterAssign): Enforce checking the result.
* src/qemu/qemu_driver.c (qemuDomainGetPercpuStats): Fix offender.
(qemuDomainGetTotalcpuStats): Implement new parameters.
* tools/virsh.c (cmdCPUStats): Tweak output accordingly.
2012-03-12 08:46:56 -06:00
Laine Stump
7a23ba090d qemu: eliminate memory leak in qemuDomainUpdateDeviceConfig
This function was freeing a virDomainNetDef with
VIR_FREE(). virDomainNetDef is a complex structure with many pointers
to other dynamically allocated data; to properly free it
virDomainNetDefFree() must be called instead, otherwise several
strings (and potentially other things) will be leaked.
2012-03-08 16:58:53 -05:00
Laine Stump
edb6fc3a7f qemu: support persistent hotplug of <hostdev> devices
For some reason, although live hotplug of <hostdev> devices is
supported, persistent hotplug is not. This patch adds the proper
VIR_DOMAIN_DEVICE_HOSTDEV cases to the switches in
qemuDomainAttachDeviceConfig and qemuDomainDetachDeviceConfig.
2012-03-08 16:58:40 -05:00
Laine Stump
f985773d06 util: eliminate device object leaks related to virDomain*Remove*()
There are several functions in domain_conf.c that remove a device
object from the domain's list of that object type, but don't free the
object or return it to the caller to free. In many cases this isn't a
problem because the caller already had a pointer to the object and
frees it afterward, but in several cases the removed object was just
left floating around with no references to it.

In particular, the function qemuDomainDetachDeviceConfig() calls
functions to locate and remove net (virDomainNetRemoveByMac), disk
(virDomainDiskRemoveByName()), and lease (virDomainLeaseRemove())
devices, but neither it nor its caller qemuDomainModifyDeviceConfig()
ever obtain a pointer to the device being removed, much less free it.

This patch modifies the following "remove" functions to return a
pointer to the device object being removed from the domain device
arrays, to give the caller the option of freeing the device object
using that pointer if needed. In places where the object was
previously leaked, it is now freed:

  virDomainDiskRemove
  virDomainDiskRemoveByName
  virDomainNetRemove
  virDomainNetRemoveByMac
  virDomainHostdevRemove
  virDomainLeaseRemove
  virDomainLeaseRemoveAt

The functions that had been leaking:

  libxlDomainDetachConfig - leaked a virDomainDiskDef
  qemuDomainDetachDeviceConfig - could leak a virDomainDiskDef,
                            a virDomainNetDef, or a
                            virDomainLeaseDef
  qemuDomainDetachLease   - leaked a virDomainLeaseDef
2012-03-08 16:58:27 -05:00
Michal Privoznik
1e0534a770 qemu: Don't parse device twice in attach/detach
Some members are generated during XML parse (e.g. MAC address of
an interface); However, with current implementation, if we
are plugging a device both to persistent and live config,
we parse given XML twice: first time for live, second for config.
This is wrong then as the second time we are not guaranteed
to generate same values as we did for the first time.
To prevent that we need to create a copy of DeviceDefPtr;
This is done through format/parse process instead of writing
functions for deep copy as it is easier to maintain:
adding new field to any virDomain*DefPtr doesn't require change
of copying function.
2012-03-08 10:20:21 +01:00
Michal Privoznik
b819b3b7cf qemu: Fix startupPolicy for snapshot-revert
Currently, startupPolicy='requisite' was determining cold boot
by migrateFrom != NULL. That means, if domain was started up
with migrateFrom set we didn't require disk source path and allowed
it to be dropped. However, on snapshot-revert domain wasn't migrated
but according to documentation, requisite should drop disk source
as well.
2012-03-08 10:03:08 +01:00
Eric Blake
4888f0fb56 xml: use better types for memory values
Using 'unsigned long' for memory values is risky on 32-bit platforms,
as a PAE guest can have more than 4GiB memory.  Our API is
(unfortunately) locked at 'unsigned long' and a scale of 1024, but
the rest of our system should consistently use 64-bit values,
especially since the previous patch centralized overflow checking.

* src/conf/domain_conf.h (_virDomainDef): Always use 64-bit values
for memory.  Change hugepage_backed to a bool.
* src/conf/domain_conf.c (virDomainDefParseXML)
(virDomainDefCheckABIStability, virDomainDefFormatInternal): Fix
clients.
* src/vmx/vmx.c (virVMXFormatConfig): Likewise.
* src/xenxs/xen_sxpr.c (xenParseSxpr, xenFormatSxpr): Likewise.
* src/xenxs/xen_xm.c (xenXMConfigGetULongLong): New function.
(xenXMConfigGetULong, xenXMConfigSetInt): Avoid truncation.
(xenParseXM, xenFormatXM): Fix clients.
* src/phyp/phyp_driver.c (phypBuildLpar): Likewise.
* src/openvz/openvz_driver.c (openvzDomainSetMemoryInternal):
Likewise.
* src/vbox/vbox_tmpl.c (vboxDomainDefineXML): Likewise.
* src/qemu/qemu_command.c (qemuBuildCommandLine): Likewise.
* src/qemu/qemu_process.c (qemuProcessStart): Likewise.
* src/qemu/qemu_monitor.h (qemuMonitorGetBalloonInfo): Likewise.
* src/qemu/qemu_monitor_text.h (qemuMonitorTextGetBalloonInfo):
Likewise.
* src/qemu/qemu_monitor_text.c (qemuMonitorTextGetBalloonInfo):
Likewise.
* src/qemu/qemu_monitor_json.h (qemuMonitorJSONGetBalloonInfo):
Likewise.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONGetBalloonInfo):
Likewise.
* src/qemu/qemu_driver.c (qemudDomainGetInfo)
(qemuDomainGetXMLDesc): Likewise.
* src/uml/uml_conf.c (umlBuildCommandLine): Likewise.
2012-03-07 18:24:44 -07:00
Eric Blake
73b9977140 xml: use long long internally, to centralize overflow checks
On 64-bit platforms, unsigned long and unsigned long long are
identical, so we don't have to worry about overflow checks.
On 32-bit platforms, anywhere we narrow unsigned long long back
to unsigned long, we have to worry about overflow; it's easier
to do this in one place by having most of the code use the same
or wider types, and only doing the narrowing at the last minute.
Therefore, the memory set commands remain unsigned long, and
the memory get command now centralizes the overflow check into
libvirt.c, so that drivers don't have to repeat the work.

This also fixes a bug where xen returned the wrong value on
failure (most APIs return -1 on failure, but getMaxMemory
must return 0 on failure).

* src/driver.h (virDrvDomainGetMaxMemory): Use long long.
* src/libvirt.c (virDomainGetMaxMemory): Raise overflow.
* src/test/test_driver.c (testGetMaxMemory): Fix driver.
* src/rpc/gendispatch.pl (name_to_ProcName): Likewise.
* src/xen/xen_hypervisor.c (xenHypervisorGetMaxMemory): Likewise.
* src/xen/xen_driver.c (xenUnifiedDomainGetMaxMemory): Likewise.
* src/xen/xend_internal.c (xenDaemonDomainGetMaxMemory):
Likewise.
* src/xen/xend_internal.h (xenDaemonDomainGetMaxMemory):
Likewise.
* src/xen/xm_internal.c (xenXMDomainGetMaxMemory): Likewise.
* src/xen/xm_internal.h (xenXMDomainGetMaxMemory): Likewise.
* src/xen/xs_internal.c (xenStoreDomainGetMaxMemory): Likewise.
* src/xen/xs_internal.h (xenStoreDomainGetMaxMemory): Likewise.
* src/xenapi/xenapi_driver.c (xenapiDomainGetMaxMemory):
Likewise.
* src/esx/esx_driver.c (esxDomainGetMaxMemory): Likewise.
* src/libxl/libxl_driver.c (libxlDomainGetMaxMemory): Likewise.
* src/qemu/qemu_driver.c (qemudDomainGetMaxMemory): Likewise.
* src/lxc/lxc_driver.c (lxcDomainGetMaxMemory): Likewise.
* src/uml/uml_driver.c (umlDomainGetMaxMemory): Likewise.
2012-03-07 18:24:43 -07:00
Eric Blake
239fb8c46b api: add overflow error
Overflow can be user-induced, so it deserves more than being called
an internal error.  Note that in general, 32-bit platforms have
far more places to trigger this error (anywhere the public API
used 'unsigned long' but the other side of the connection is a
64-bit server); but some are possible on 64-bit platforms (where
the public API computes the product of two numbers).

* include/libvirt/virterror.h (VIR_ERR_OVERFLOW): New error.
* src/util/virterror.c (virErrorMsg): Translate it.
* src/libvirt.c (virDomainSetVcpusFlags, virDomainGetVcpuPinInfo)
(virDomainGetVcpus, virDomainGetCPUStats): Use it.
* daemon/remote.c (HYPER_TO_TYPE): Likewise.
* src/qemu/qemu_driver.c (qemuDomainBlockResize): Likewise.
2012-03-07 18:24:43 -07:00
Eric Blake
462dc569de rpc: allow truncated return for virDomainGetCPUStats
The RPC code assumed that the array returned by the driver would be
fully populated; that is, ncpus on entry resulted in ncpus * return
value on exit.  However, while we don't support holes in the middle
of ncpus, we do want to permit the case of ncpus on entry being
longer than the array returned by the driver (that is, it should be
safe for the caller to pass ncpus=128 on entry, and the driver will
stop populating the array when it hits max_id).

Additionally, a successful return implies that the caller will then
use virTypedParamArrayClear on the entire array; for this to not
free uninitialized memory, the driver must ensure that all skipped
entries are explicitly zeroed (the RPC driver did this, but not
the qemu driver).

There are now three cases:
server 0.9.10 and client 0.9.10 or newer: No impact - there were no
hypervisor drivers that supported cpu stats

server 0.9.11 or newer and client 0.9.10: if the client calls with
ncpus beyond the max, then the rpc call will fail on the client side
and disconnect the client, but the server is no worse for the wear

server 0.9.11 or newer and client 0.9.11: the server can return a
truncated array and the client will do just fine

I reproduced the problem by using a host with 2 CPUs, and doing:
virsh cpu-stats $dom --start 1 --count 2

* daemon/remote.c (remoteDispatchDomainGetCPUStats): Allow driver
to omit tail of array.
* src/remote/remote_driver.c (remoteDomainGetCPUStats):
Accommodate driver that omits tail of array.
* src/libvirt.c (virDomainGetCPUStats): Document this.
* src/qemu/qemu_driver.c (qemuDomainGetPercpuStats): Clear all
unpopulated entries.
2012-03-07 07:14:11 -07:00
KAMEZAWA Hiroyuki
44b0a53a7c qemu driver for virDomainGetCPUstats using cpuacct cgroup.
* For now, only "cpu_time" is supported.
* cpuacct cgroup is used for providing percpu cputime information.

* src/qemu/qemu.conf     - take care of cpuacct cgroup.
* src/qemu/qemu_conf.c   - take care of cpuacct cgroup.
* src/qemu/qemu_driver.c - added an interface
* src/util/cgroup.c/h    - added interface for getting percpu cputime

Signed-off-by: KAMEZAWA Hiroyuki <kamezawa.hiroyu@jp.fujitsu.com>
Signed-off-by: Lai Jiangshan <laijs@cn.fujitsu.com>
2012-03-06 21:54:48 -07:00
Eric Blake
877fd769b9 blockResize: add flag for bytes
Qemu supports sizing by bytes; we shouldn't force the user to
round up if they really wanted an unaligned total size.

* include/libvirt/libvirt.h.in (VIR_DOMAIN_BLOCK_RESIZE_BYTES):
New flag.
* src/libvirt.c (virDomainBlockResize): Document it.
* src/qemu/qemu_monitor_json.c (qemuMonitorJSONBlockResize): Take
size in bytes.
* src/qemu/qemu_monitor_text.c (qemuMonitorTextBlockResize):
Likewise.  Pass bytes, not megabytes, to monitor.
* src/qemu/qemu_driver.c (qemuDomainBlockResize): Implement new
flag.
2012-03-05 10:06:52 -07:00
Osier Yang
1f77472d5b qemu: Fix indention 2012-03-05 18:32:53 +08:00
Eric Blake
3e2c3d8f6d build: use correct type for pid and similar types
No thanks to 64-bit windows, with 64-bit pid_t, we have to avoid
constructs like 'int pid'.  Our API in libvirt-qemu cannot be
changed without breaking ABI; but then again, libvirt-qemu can
only be used on systems that support UNIX sockets, which rules
out Windows (even if qemu could be compiled there) - so for all
points on the call chain that interact with this API decision,
we require a different variable name to make it clear that we
audited the use for safety.

Adding a syntax-check rule only solves half the battle; anywhere
that uses printf on a pid_t still needs to be converted, but that
will be a separate patch.

* cfg.mk (sc_correct_id_types): New syntax check.
* src/libvirt-qemu.c (virDomainQemuAttach): Document why we didn't
use pid_t for pid, and validate for overflow.
* include/libvirt/libvirt-qemu.h (virDomainQemuAttach): Tweak name
for syntax check.
* src/vmware/vmware_conf.c (vmwareExtractPid): Likewise.
* src/driver.h (virDrvDomainQemuAttach): Likewise.
* tools/virsh.c (cmdQemuAttach): Likewise.
* src/remote/qemu_protocol.x (qemu_domain_attach_args): Likewise.
* src/qemu_protocol-structs (qemu_domain_attach_args): Likewise.
* src/util/cgroup.c (virCgroupPidCode, virCgroupKillInternal):
Likewise.
* src/qemu/qemu_command.c(qemuParseProcFileStrings): Likewise.
(qemuParseCommandLinePid): Use pid_t for pid.
* daemon/libvirtd.c (daemonForkIntoBackground): Likewise.
* src/conf/domain_conf.h (_virDomainObj): Likewise.
* src/probes.d (rpc_socket_new): Likewise.
* src/qemu/qemu_command.h (qemuParseCommandLinePid): Likewise.
* src/qemu/qemu_driver.c (qemudGetProcessInfo, qemuDomainAttach):
Likewise.
* src/qemu/qemu_process.c (qemuProcessAttach): Likewise.
* src/qemu/qemu_process.h (qemuProcessAttach): Likewise.
* src/uml/uml_driver.c (umlGetProcessInfo): Likewise.
* src/util/virnetdev.h (virNetDevSetNamespace): Likewise.
* src/util/virnetdev.c (virNetDevSetNamespace): Likewise.
* tests/testutils.c (virtTestCaptureProgramOutput): Likewise.
* src/conf/storage_conf.h (_virStoragePerms): Use mode_t, uid_t,
and gid_t rather than int.
* src/security/security_dac.c (virSecurityDACSetOwnership): Likewise.
* src/conf/storage_conf.c (virStorageDefParsePerms): Avoid
compiler warning.
2012-03-02 06:57:43 -07:00
Eric Blake
10ec36e2e7 qemu: pass block pull backing file to monitor
This actually wires up the new optional parameter to block_stream:
http://wiki.qemu.org/Features/LiveBlockMigration/ImageStreamingAPI

The error checking is still sparse, since libvirt must not use
qemu-img or header probing on a qcow2 file in use by qemu to
check if the backing file name is valid; so for now, libvirt is
relying on qemu to diagnose an incorrect backing name.  Fixing this
will require libvirt to track the entire backing file chain at the
time qemu is started and keeps it updated with snapshot and pull
operations.

* src/qemu/qemu_monitor_json.c (qemuMonitorJSONBlockJob): Add
parameter, and update callers.
* src/qemu/qemu_monitor_json.h (qemuMonitorJSONBlockJob): Update
signature.
* src/qemu/qemu_monitor.h (qemuMonitorBlockJob): Likewise.
* src/qemu/qemu_driver.c (qemuDomainBlockJobImpl): Update caller.
* src/qemu/qemu_monitor.c (qemuMonitorBlockJob): Likewise.
2012-02-29 13:44:20 -07:00
Peter Krempa
4716138229 qemu: Add ability to abort existing console while creating new one
This patch fixes console corruption, that happens if two concurrent
sessions are opened for a single console on a domain. Result of this
corruption was that each of the console streams recieved just a part
of the data written to the pipe so every console rendered unusable.

New helper function for safe console handling is used to establish the
console stream connection. This function ensures that no other libvirt
client is using the console (with the ability to disconnect consoles of
libvirt clients) and that no UUCP style lockfile is placed on the PTY
device.

* src/qemu/qemu_domain.h
        - add data structure to domain's private data dealing with
          console connections
* src/qemu/qemu_domain.c:
        - allocate/free domain's console data structure
* src/qemu/qemu_driver.c
        - use the new helper function for console handling
2012-02-27 15:05:17 +01:00
Michal Privoznik
9bf1bcc59d qemu: Implement virDomainPMWakeup API
using 'system-wakeup' monitor command. It is supported only in JSON,
as we are enabling it if possible. Moreover, this command is available
in qemu-1.1+ which definitely has JSON.
2012-02-27 11:47:02 +01:00
Martin Kletzander
9f748277bb Fixed URI parsing
Function xmlParseURI does not remove square brackets around IPv6
address when parsing. One of the solutions is making wrappers around
functions working with xmlURI*. This assures that uri->server will be
always properly assigned and it doesn't have to be changed when used
on some new place in the code.
For this purpose, functions virParseURI and virSaveURI were
added. These function are wrappers around xmlParseURI and xmlSaveUri
respectively.
Also there is one new syntax check function to prohibit these functions
anywhere else.

File changes:
 - src/util/viruri.h        -- declaration
 - src/util/viruri.c        -- definition
 - src/libvirt_private.syms -- symbol export
 - src/Makefile.am          -- added source and header files
 - cfg.mk                   -- added sc_prohibit_xmlURI
 - all others               -- ID name and include fixes
2012-02-24 16:49:21 -07:00
Eric Blake
d2dc5057fd qemu: nicer error message on failed graceful destroy
https://bugzilla.redhat.com/show_bug.cgi?id=795656 mentions
that a graceful destroy request can time out, meaning that the
error message is user-visible and should be more appropriate
than just internal error.

* src/qemu/qemu_driver.c (qemuDomainDestroyFlags): Swap error type.
2012-02-23 08:47:06 -07:00
Jiri Denemark
d57485f73a qemu: Forbid migration with cache != none
Migrating domains with disks using cache != none is unsafe unless the
disk images are stored on coherent clustered filesystem. Thus we forbid
migrating such domains unless VIR_MIGRATE_UNSAFE flags is used.
2012-02-23 14:34:56 +01:00
Laine Stump
595e26c086 qemu: drop driver lock while trying to terminate qemu process
This patch is based on an earlier patch by Eric Blake which was never
committed:

https://www.redhat.com/archives/libvir-list/2011-November/msg00243.html

Aside from rebasing, this patch only drops the driver lock once (prior
to the first time the function sleeps), then leaves it dropped until
it returns (Eric's patch would drop and re-acquire the lock around
each call to sleep).

At the time Eric sent his patch, the response (from Dan Berrange) was
that, while it wasn't a good thing to be holding the driver lock while
sleeping, we really need to rethink locking wrt the driver object,
switching to a finer-grained approach that locks individual items
within the driver object separately to allow for greater concurrency.

This is a good plan, and at the time it made sense to not apply the
patch because there was no known bug related to the driver lock being
held in this function.

However, we now know that the length of the wait in qemuProcessKill is
sometimes too short to allow the qemu process to fully flush its disk
cache before SIGKILL is sent, so we need to lengthen the timeout (in
order to improve the situation with management applications until they
can be updated to use the new VIR_DOMAIN_DESTROY_GRACEFUL flag added
in commit 72f8a7f197). But, if we
lengthen the timeout, we also lengthen the amount of time that all
other threads in libvirtd are essentially blocked from doing anything
(since just about everything needs to acquire the driver lock, if only
for long enough to get a pointer to a domain).

The solution is to modify qemuProcessKill to drop the driver lock
while sleeping, as proposed in Eric's patch. Then we can increase the
timeout with a clear conscience, and thus at least lower the chances
that someone running with existing management software will suffer the
consequence's of qemu's disk cache not being flushed.

In the meantime, we still should work on Dan's proposal to make
locking within the driver object more fine grained.

(NB: although I couldn't find any instance where qemuProcessKill() was
called with no jobs active for the domain (or some other guarantee
that the current thread had at least one refcount on the domain
object), this patch still follows Eric's method of temporarily adding
a ref prior to unlocking the domain object, because I couldn't
convince myself 100% that this was the case.)
2012-02-15 13:57:10 -05:00
Michal Privoznik
82f47fde6c qemu: Implement DomainPMSuspendForDuration
via user agent. Allow targets mem & hybrid iff system_wakeup
monitor command is available.
2012-02-15 11:45:45 +01:00
Eric Blake
172d34298f qemu: make block io tuning smarter
When blkdeviotune was first committed in 0.9.8, we had the limitation
that setting one value reset all others.  But bytes and iops should
be relatively independent.  Furthermore, setting tuning values on
a live domain followed by dumpxml did not output the new settings.

* src/qemu/qemu_driver.c (qemuDiskPathToAlias): Add parameter, and
update callers.
(qemuDomainSetBlockIoTune): Don't lose previous unrelated
settings.  Make live changes reflect to dumpxml output.
* tools/virsh.pod (blkdeviotune): Update documentation.
2012-02-13 10:34:25 -07:00
Osier Yang
7c90026db9 npiv: Auto-generate WWN if it's not specified
The auto-generated WWN comply with the new addressing schema of WWN:

<quote>
the first nibble is either hex 5 or 6 followed by a 3-byte vendor
identifier and 36 bits for a vendor-specified serial number.
</quote>

We choose hex 5 for the first nibble. And for the 3-bytes vendor ID,
we uses the OUI according to underlying hypervisor type, (invoking
virConnectGetType to get the virt type). e.g. If virConnectGetType
returns "QEMU", we use Qumranet's OUI (00:1A:4A), if returns
ESX|VMWARE, we use VMWARE's OUI (00:05:69). Currently it only
supports qemu|xen|libxl|xenapi|hyperv|esx|vmware drivers. The last
36 bits are auto-generated.
2012-02-10 12:53:25 +08:00
Eric Blake
c8c239a439 qemu: fix persistent setting of blkiodevice weights
virsh blkiotune dom --device-weights /dev/sda,400 --config

wasn't working correctly.

* src/qemu/qemu_driver.c (qemuDomainSetBlkioParameters): Use
correct definition.
2012-02-08 16:53:39 -07:00
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