When trying to assign a PCI device to a guest, we have
to check that all bridges upstream of that device support
ACS. That means that we have to find the parent bridge of
the current device, check for ACS, then find the parent bridge
of that device, check for ACS, etc. As it currently stands,
the code to do this iterates through all PCI devices on the
system, looking for a device that has a range of busses that
included the current device's bus.
That check is not restrictive enough, though. Depending on
how we iterated through the list of PCI devices, we could first
find the *topmost* bridge in the system; since it necessarily had
a range of busses including the current device's bus, we
would only ever check the topmost bridge, and not check
any of the intermediate bridges.
Note that this also caused a fairly serious bug in the
secondary bus reset code, where we could erroneously
find and reset the topmost bus instead of the inner bus.
This patch changes pciGetParentDevice() so that it first
checks if a bridge device's secondary bus exactly matches
the bus of the device we are looking for. If it does, we've
found the correct parent bridge and we are done. If it does not,
then we check to see if this bridge device's busses *include* the
bus of the device we care about. If so, we mark this bridge device
as best, and go on. If we later find another bridge device whose
busses include this device, but is more restrictive, then we
free up the previous best and mark the new one as best. This
algorithm ensures that in the normal case we find the direct
parent, but in the case that the parent bridge secondary bus
is not exactly the same as the device, we still find the
correct bridge.
This patch was tested by me on a 4-port NIC with a
bridge without ACS (where assignment failed), a 4-port
NIC with a bridge with ACS (where assignment succeeded),
and a 2-port NIC with no bridges (where assignment
succeeded).
Signed-off-by: Chris Lalancette <clalance@redhat.com>
valgrind was complaining that virUUIDParse was depending on
an uninitialized value. Indeed it was; virSetHostUUIDStr()
didn't initialize the dmiuuid buffer to 0's, meaning that
anything after the string read from /sys was uninitialized.
Clear out the dmiuuid buffer before use, and make sure to
always leave a \0 at the end.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
If detecting the FLR flag of a pci device fails, then we
could run into the situation of trying to close a file
descriptor twice, once in pciInitDevice() and once in pciFreeDevice().
Fix that by removing the pciCloseConfig() in pciInitDevice() and
just letting pciFreeDevice() handle it.
Thanks to Chris Wright for pointing out this problem.
While we are at it, fix an error check. While it would actually
work as-is (since success returns 0), it's still more clear to
check for < 0 (as the rest of the code does).
Signed-off-by: Chris Lalancette <clalance@redhat.com>
During function test of the 802.1Qbg implementation in lldpad we came
across a small problem in the handling of the netlink message
corresponding to PORT_PROFILE_RESPONSE_INPROGRESS. This should not
result in returning the default rc=1.
- src/util/macvtap.c: fix getPortProfileStatus() to return 0 in that
case and also fix an indentation problem
Some buggy PCI devices actually support FLR, but
forget to advertise that fact in their PCI config space.
However, Virtual Functions on SR-IOV devices are
*required* to support FLR by the spec, so force has_flr
on if this is a virtual function.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
When doing a PCI secondary bus reset, we must be sure that there are no
active devices on the same bus segment. The active device tracking is
designed to only track host devices that are active in use by guests.
This ignores host devices that are actively in use by the host. So the
current logic will reset host devices.
Switch this logic around and allow sbus reset when we are assigning all
devices behind a bridge to the same guest at guest startup or as a result
of a single attach-device command.
* src/util/pci.h: change signature of pciResetDevice to add an
inactive devices list
* src/qemu/qemu_driver.c src/xen/xen_driver.c: use (or not) the new
functionality of pciResetDevice() depending on the place of use
* src/util/pci.c: implement the interface and logic changes
The first conditional is always true which means the iterator will
never find another device on the same bus.
if (dev->domain != check->domain ||
dev->bus != check->bus ||
----> (check->slot == check->slot &&
check->function == check->function)) <-----
The goal of that check is to verify that the device is either:
in a different pci domain
on a different bus
is the same identical device
This means libvirt may issue a secondary bus reset when there are
devices
on that bus that actively in use by the host or another guest.
* src/util/pci.c: fix a bogus test in pciSharesBusWithActive()
A Linux software bridge will assume the MAC address of the enslaved
interface with the numerically lowest MAC addr. When the bridge
changes MAC address there is a period of network blackout, so a
change should be avoided. The kernel gives TAP devices a completely
random MAC address. Occassionally the random TAP device MAC is lower
than that of the physical interface (eth0, eth1etc) that is enslaved,
causing the bridge to change its MAC.
This change sets an explicit MAC address for all TAP devices created
using the configured MAC from the XML, but with the high byte set
to 0xFE. This should ensure TAP device MACs are higher than any
physical interface MAC.
* src/qemu/qemu_conf.c, src/uml/uml_conf.c: Pass in a MAC addr
for the TAP device with high byte set to 0xFE
* src/util/bridge.c, src/util/bridge.h: Set a MAC when creating
the TAP device to override random MAC
virDirCreate also previously returned 0 on success and errno on
failure. This makes it fit the recommended convention of returning 0
on success, -errno (ie a negative number) on failure.
virFileOperation previously returned 0 on success, or the value of
errno on failure. Although there are other functions in libvirt that
use this convention, the preferred (and more common) convention is to
return 0 on success and -errno (or simply -1 in some cases) on
failure. This way the check for failure is always (ret < 0).
* src/util/util.c - change virFileOperation and virFileOperationNoFork to
return -errno on failure.
* src/storage/storage_backend.c, src/qemu/qemu_driver.c
- change the hook functions passed to virFileOperation to return
-errno on failure.
Require the disk image to be passed into virStorageFileGetMetadata.
If this is set to VIR_STORAGE_FILE_AUTO, then the format will be
resolved using probing. This makes it easier to control when
probing will be used
* src/qemu/qemu_driver.c, src/qemu/qemu_security_dac.c,
src/security/security_selinux.c, src/security/virt-aa-helper.c:
Set VIR_STORAGE_FILE_AUTO when calling virStorageFileGetMetadata.
* src/storage/storage_backend_fs.c: Probe for disk format before
calling virStorageFileGetMetadata.
* src/util/storage_file.h, src/util/storage_file.c: Remove format
from virStorageFileMeta struct & require it to be passed into
method.
The virStorageFileGetMetadataFromFD did two jobs in one. First
it probed for storage type, then it extracted metadata for the
type. It is desirable to be able to separate these jobs, allowing
probing without querying metadata, and querying metadata without
probing.
To prepare for this, split out probing code into a new pair of
methods
virStorageFileProbeFormatFromFD
virStorageFileProbeFormat
* src/util/storage_file.c, src/util/storage_file.h,
src/libvirt_private.syms: Introduce virStorageFileProbeFormat
and virStorageFileProbeFormatFromFD
Instead of including a field in FileTypeInfo struct for the
disk format, rely on the array index matching the format.
Use verify() to assert the correct number of elements in the
array.
* src/util/storage_file.c: remove type field from FileTypeInfo
When QEMU opens a backing store for a QCow2 file, it will
normally auto-probe for the format of the backing store,
rather than assuming it has the same format as the referencing
file. There is a QCow2 extension that allows an explicit format
for the backing store to be embedded in the referencing file.
This closes the auto-probing security hole in QEMU.
This backing store format can be useful for libvirt users
of virStorageFileGetMetadata, so extract this data and report
it.
QEMU does not require disk image backing store files to be in
the same format the file linkee. It will auto-probe the disk
format for the backing store when opening it. If the backing
store was intended to be a raw file this could be a security
hole, because a guest may have written data into its disk that
then makes the backing store look like a qcow2 file. If it can
trick QEMU into thinking the raw file is a qcow2 file, it can
access arbitrary files on the host by adding further backing
store links.
To address this, callers of virStorageFileGetMeta need to be
told of the backing store format. If no format is declared,
they can make a decision whether to allow format probing or
not.
IPtables will seek to preserve the source port unchanged when
doing masquerading, if possible. NFS has a pseudo-security
option where it checks for the source port <= 1023 before
allowing a mount request. If an admin has used this to make the
host OS trusted for mounts, the default iptables behaviour will
potentially allow NAT'd guests access too. This needs to be
stopped.
With this change, the iptables -t nat -L -n -v rules for the
default network will be
Chain POSTROUTING (policy ACCEPT 95 packets, 9163 bytes)
pkts bytes target prot opt in out source destination
14 840 MASQUERADE tcp -- * * 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535
75 5752 MASQUERADE udp -- * * 192.168.122.0/24 !192.168.122.0/24 masq ports: 1024-65535
0 0 MASQUERADE all -- * * 192.168.122.0/24 !192.168.122.0/24
* src/network/bridge_driver.c: Add masquerade rules for TCP
and UDP protocols
* src/util/iptables.c, src/util/iptables.c: Add source port
mappings for TCP & UDP protocols when masquerading.
Any error message raised after the process has forked needs
to be followed by virDispatchError, otherwise we have no chance of
ever seeing it. This was selectively done for hook functions in the past,
but really applies to all post-fork errors.
As pointed out by Eric Blake, using dirent->d_type breaks
compilation on MinGW. This patch addresses this by using
'#if defined' as same as doing for virCgroupForDriver.
ENOENT happens normally when a subsystem is enabled with any other
subsystems and the directory of the target group has already removed
in a prior loop. In that case, the function should just return without
leaving an error message.
NB this is the same behavior as before introducing virCgroupRemoveRecursively.
In the current libvirt PCI code, there is no checking whether
a PCI device is in use by a guest when doing node device
detach or reattach. This causes problems when a device is
assigned to a guest, and the administrator starts issuing
nodedevice commands. Make it so that we check the list
of active devices when trying to detach/reattach, and only
allow the operation if the device is not assigned to a guest.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
virStorageFileIsSharedFS would previously only work if the entire path
in question was stat'able by the uid of the libvirtd process. This
patch changes it to crawl backwards up the path retrying the statfs
call until it gets to a partial path that *can* be stat'ed.
This is necessary to use the function to learn the fstype for files
stored as a different user (and readable only by that user) on a
root-squashed remote filesystem.
When configuring serial, parallel, console or channel devices
with a file, dev or pipe backend type, it is necessary to label
the file path in the security drivers. For char devices of type
file, it is neccessary to pre-create (touch) the file if it does
not already exist since QEMU won't be allowed todo so itself.
dev/pipe configs already require the admin to pre-create before
starting the guest.
* src/qemu/qemu_security_dac.c: set file ownership for character
devices
* src/security/security_selinux.c: Set file labeling for character
devices
* src/qemu/qemu_driver.c: Add character devices to cgroup ACL
Through conversation with Kumar L Srikanth-B22348, I found
that the function of getting memory usage (e.g., virsh dominfo)
doesn't work for lxc with ns subsystem of cgroup enabled.
This is because of features of ns and memory subsystems.
Ns creates child cgroup on every process fork and as a result
processes in a container are not assigned in a cgroup for
domain (e.g., libvirt/lxc/test1/). For example, libvirt_lxc
and init (or somewhat specified in XML) are assigned into
libvirt/lxc/test1/8839/ and libvirt/lxc/test1/8839/8849/,
respectively. On the other hand, memory subsystem accounts
memory usage within a group of processes by default, i.e.,
it does not take any child (and descendant) groups into
account. With the two features, virsh dominfo which just
checks memory usage of a cgroup for domain always returns
zero because the cgroup has no process.
Setting memory.use_hierarchy of a group allows to account
(and limit) memory usage of every descendant groups of the group.
By setting it of a cgroup for domain, we can get proper memory
usage of lxc with ns subsystem enabled. (To be exact, the
setting is required only when memory and ns subsystems are
enabled at the same time, e.g., mount -t cgroup none /cgroup.)
As same as normal directories, a cgroup cannot be removed if it
contains sub groups. This patch changes virCgroupRemove to remove
all descendant groups (subdirectories) of a target group before
removing the target group.
The handling is required when we run lxc with ns subsystem of cgroup.
Ns subsystem automatically creates child cgroups on every process
forks, but unfortunately the groups are not removed on process exits,
so we have to remove them by ourselves.
With this patch, such child (and descendant) groups are surely removed
at lxc shutdown, i.e., lxcVmCleanup which calls virCgroupRemove.
If there is no driver for a URI we report
"no hypervisor driver available"
This is bad because not all virt drivers are hypervisors (ie container
based virt).
If there is no driver support for an API we report
"this function is not supported by the hypervisor"
This is bad for the same reason, and additionally because it is
also used for the network, interface & storage drivers.
* src/util/virterror.c: Improve error messages
If VM startup fails early enough (can't find a referenced USB device),
libvirtd will crash trying to clear the VNC port bit, since port = 0,
which overflows us out of the bitmap bounds.
Fix this by being more defensive in the bitmap operations, and only
clearing a previously set VNC port.
Signed-off-by: Cole Robinson <crobinso@redhat.com>
This patch works around a recent extension of the netlink driver I had made use of when building the netlink messages. Unfortunately older kernels don't accept IFLA_IFNAME + name of interface as a replacement for the interface's index, so this patch now gets the interface index ifindex if it's not provided (ifindex <= 0).
* src/util/threads.c (includes) [WIN32]: On mingw, favor native
threading over pthreads-win32 library.
* src/util/thread.h [WIN32] Likewise.
Suggested by Daniel P. Berrange.
A look at the QEMU source revealed the missing bits of info about
the VPC file format, so we can enable this now
* src/util/storage_file.c: Enable VPC format, providing version
and disk size offset fields
This patch that adds support for configuring 802.1Qbg and 802.1Qbh
switches. The 802.1Qbh part has been successfully tested with real
hardware. The 802.1Qbg part has only been tested with a (dummy)
server that 'behaves' similarly to how we expect lldpad to 'behave'.
The following changes were made during the development of this patch:
- Merging Scott's v13-pre1 patch
- Fixing endptr related bug while using virStrToLong_ui() pointed out
by Jim Meyering
- Addressing Jim Meyering's comments to v11
- requiring mac address to the vpDisassociateProfileId() function to
pass it further to the 802.1Qbg disassociate part (802.1Qbh untouched)
- determining pid of lldpad daemon by reading it from /var/run/libvirt.pid
(hardcode as is hardcode alson in lldpad sources)
- merging netlink send code for kernel target and user space target
(lldpad) using one function nlComm() to send the messages
- adding a select() after the sending and before the reading of the
netlink response in case lldpad doesn't respond and so we don't hang
- when reading the port status, in case of 802.1Qbg, no status may be
received while things are 'in progress' and only at the end a status
will be there.
- when reading the port status, use the given instanceId and vf to pick
the right IFLA_VF_PORT among those nested under IFLA_VF_PORTS.
- never sending nor parsing IFLA_PORT_SELF type of messages in the
802.1Qbg case
- iterating over the elements in a IFLA_VF_PORTS to pick the right
IFLA_VF_PORT by either IFLA_PORT_PROFILE and given profileId
(802.1Qbh) or IFLA_PORT_INSTANCE_UUID and given instanceId (802.1Qbg)
and reading the current status in IFLA_PORT_RESPONSE.
- recycling a previous patch that adds functionality to interface.c to
- get the vlan identifier on an interface
- get the flags of an interface and some convenience function to
check whether an interface is 'up' or not (not currently used here)
- adding function to determine the root physical interface of an
interface. For example if a macvtap is linked to eth0.100, it will
find eth0. Also adding a function that finds the vlan on the 'way to
the root physical interface'
- conveying the root physical interface name and index in case of 802.1Qbg
- conveying mac address of macvlan device and vlan identifier in
IFLA_VFINFO_LIST[ IFLA_VF_INFO[ IFLA_VF_MAC(mac), IFLA_VF_VLAN(vlan) ] ]
to (future) lldpad via netlink
- To enable build with --without-macvtap rename the
[dis|]associatePortProfileId functions, prepend 'vp' before their
name and make them non-static functions.
- Renaming variable multicast to nltarget_kernel and inverting
the logic
- Addressing Jim Meyering's comments; this also touches existing
code for example for correcting indentation of break statements or
simplification of switch statements.
- Renamed occurrencvirVirtualPortProfileDef to virVirtualPortProfileParamses
- 802.1Qbg part prepared for sending a RTM_SETLINK and getting
processing status back plus a subsequent RTM_GETLINK to
get IFLA_PORT_RESPONSE.
Note: This interface for 802.1Qbg may still change
- [David Allan] move getPhysfn inside IFLA_VF_PORT_MAX to avoid
compiler
warning when latest if_link.h isn't available
- move from Stefan's 802.1Qb{g|h} XML v8 to v9
- move hostuuid and vf index calcs to inside doPortProfileOp8021Qbh
- remove debug fprintfs
- use virGetHostUUID (thanks Stefan!)
- fix compile issue when latest if_link.h isn't available
- change poll timeout to 10s, at 1/8 intervals
- if polling times out, log msg and return -ETIMEDOUT
- Add Stefan's code for getPortProfileStatus
- Poll for up to 2 secs for port-profile status, at 1/8 sec intervals:
- if status indicates error, abort openMacvtapTap
- if status indicates success, exit polling
- if status is "in-progress" after 2 secs of polling, exit
polling loop silently, without error
My patch finishes out the 802.1Qbh parts, which Stefan had mostly complete.
I've tested using the recent kernel updates for VF_PORT netlink msgs and
enic for Cisco's 10G Ethernet NIC. I tested many VMs, each with several
direct interfaces, each configured with a port-profile per the XML. VM-to-VM,
and VM-to-external work as expected. VM-to-VM on same host (using same NIC)
works same as VM-to-VM where VMs are on diff hosts. I'm able to change
settings on the port-profile while the VM is running to change the virtual
port behaviour. For example, adjusting a QoS setting like rate limit. All
VMs with interfaces using that port-profile immediatly see the effect of the
change to the port-profile.
I don't have a SR-IOV device to test so source dev is a non-SR-IOV device,
but most of the code paths include support for specifing the source dev and
VF index. We'll need to complete this by discovering the PF given the VF
linkdev. Once we have the PF, we'll also have the VF index. All this info-
mation is available from sysfs.
Fedora bug https://bugzilla.redhat.com/show_bug.cgi?id=598272
Some files under /sys/bus/usb/devices/ have the format 'usbX', where
X is the USB bus number. Use STRPREFIX to correctly parse the bus numbers.
We've been running into a lot of situations where
virGetHostname() is returning "localhost", where a plain
gethostname() would have returned the correct thing. This
is because virGetHostname() is *always* trying to canonicalize
the name returned from gethostname(), even when it doesn't
have to.
This patch changes virGetHostname so that if the value returned
from gethostname() is already FQDN or localhost, it returns
that string directly. If the value returned from gethostname()
is a shortened hostname, then we try to canonicalize it. If
that succeeds, we returned the canonicalized hostname. If
that fails, and/or returns "localhost", then we just return
the original string we got from gethostname() and hope for
the best.
Note that after this patch it is up to clients to check whether
"localhost" is an allowed return value. The only place
where it's currently not is in qemu migration.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
This patch parses the following two XML descriptions, one for
802.1Qbg and one for 802.1Qbh, and stores the data internally.
The actual triggering of the switch setup protocol has not been
implemented here but the relevant code to do that should go into
the functions associatePortProfileId() and disassociatePortProfileId().
<interface type='direct'>
<source dev='eth0.100' mode='vepa'/>
<model type='virtio'/>
<virtualport type='802.1Qbg'>
<parameters managerid='12' typeid='0x123456' typeidversion='1'
instanceid='fa9b7fff-b0a0-4893-8e0e-beef4ff18f8f'/>
</virtualport>
<filterref filter='clean-traffic'/>
</interface>
<interface type='direct'>
<source dev='eth0.100' mode='vepa'/>
<model type='virtio'/>
<virtualport type='802.1Qbh'>
<parameters profileid='my_profile'/>
</virtualport>
</interface>
I'd suggest to use this patch as a base for triggering the setup
protocol with the 802.1Qb{g|h} switch.
Several rounds of changes were made to this patch. The
following is a list of these changes.
- Renamed structure virVirtualPortProfileDef to virVirtualPortProfileParams
as per Daniel Berrange's request
- Addressing Daniel Berrange's comments:
- removing macvtap.h's dependency on domain_conf.h by
moving the virVirtualPortProfileDef structure into macvtap.h
and not passing virtDomainNetDefPtr to any functions in
macvtap.c
- Addressed most of Chris Wright's comments:
- indicating error in case virtualport XML node cannot be parsed
properly
- parsing hex and decimal numbers using virStrToLong_ui() with
parameter '0' for base
- tgifname (target interface name) variable wasn't necessary
to pass to openMacvtapTap function anymore
- assigning the virtual port data structure to the virDomainNetDef
only if it was previously parsed
- make sure that the error code returned by openMacvtapTap() is a negative n
in case the associatePortProfileId() function failed.
- renaming vsi in the XML to virtualport
- replace all occurrences of vsi in the source as well
- removing mode and MAC address parameters from the functions that
will communicate with the hareware diretctly or indirectly
- moving the associate and disassociate functions to the end of the
file for subsequent patches to easier make them generally available
for export
- passing the macvtap interface name rather than the link device since
this otherwise gives funny side effects when using netlink messages
where IFLA_IFNAME and IFLA_ADDRESS are specified and the link dev
all of a sudden gets the MAC address of the macvtap interface.
- Removing rc = -1 error indications in the case of 802.1Qbg|h setup in case
we wanted to use hook scripts for the setup and so the setup doesn't fail
here.
- if instance ID UUID is not supplied it will automatically be generated
- adapted schema to make instance ID UUID optional
- added test case
- parser and XML generator have been separated into their own
functions so they can be re-used elsewhere (passthrough case
for example)
- Adapted XML parser and generator support the above shown type
(802.1Qbg, 802.1Qbh).
- Adapted schema to above XML
- Adapted test XML to above XML
- Passing through the VM's UUID which seems to be necessary for
802.1Qbh -- sorry no host UUID
- adding virtual function ID to association function, in case it's
necessary to use (for SR-IOV)
Spurious / in a pool target path makes life difficult for apps using the
GetVolByPath, and doing other path based comparisons with pools. This
has caused a few issues for virt-manager users:
https://bugzilla.redhat.com/show_bug.cgi?id=494005https://bugzilla.redhat.com/show_bug.cgi?id=593565
Add a new util API which removes spurious /, virFileSanitizePath. Sanitize
target paths when parsing pool XML, and for paths passed to GetVolByPath.
v2: Leading // must be preserved, properly sanitize path=/, sanitize
away /./ -> /
v3: Properly handle starting ./ and ending /.
v4: Drop all '.' handling, just sanitize / for now.
Allow for a host UUID in the capabilities XML. Local drivers
will initialize this from the SMBIOS data. If a sanity check
shows SMBIOS uuid is invalid, allow an override from the
libvirtd.conf configuration file
* daemon/libvirtd.c, daemon/libvirtd.conf: Support a host_uuid
configuration option
* docs/schemas/capability.rng: Add optional host uuid field
* src/conf/capabilities.c, src/conf/capabilities.h: Include
host UUID in XML
* src/libvirt_private.syms: Export new uuid.h functions
* src/lxc/lxc_conf.c, src/qemu/qemu_driver.c,
src/uml/uml_conf.c: Set host UUID in capabilities
* src/util/uuid.c, src/util/uuid.h: Support for host UUIDs
* src/node_device/node_device_udev.c: Use the host UUID functions
* tests/confdata/libvirtd.conf, tests/confdata/libvirtd.out: Add
new host_uuid config option to test
V2:
- Move bitmap impl to src/util/bitmap.[ch]
- Use CHAR_BIT instead of explicit '8'
- Use size_t instead of unsigned int
- Fix calculation of bitmap size in virBitmapAlloc
- Ensure bit is within range of map in the set, clear, and get
operations
- Use bool in virBitmapGetBit
- Add virBitmapFree to free-like funcs in cfg.mk
V3:
- Check for overflow in virBitmapAlloc
- Fix copy and paste bug in virBitmapAlloc
- Use size_t in prototypes
- Add ATTRIBUTE_NONNULL in prototypes where appropriate
and remove NULL check from impl
V4:
- Add ATTRIBUTE_RETURN_CHECK in prototypes where appropriate.
Do not require each caller of virStorageFileGetMetadata and
virStorageFileGetMetadataFromFD to first clear the storage of the
"meta" buffer. Instead, initialize that storage in
virStorageFileGetMetadataFromFD.
* src/util/storage_file.c (virStorageFileGetMetadataFromFD): Clear
"meta" here, not before each of the following callers.
* src/qemu/qemu_driver.c (qemuSetupDiskCgroup): Don't clear "meta" here.
(qemuTeardownDiskCgroup): Likewise.
* src/qemu/qemu_security_dac.c (qemuSecurityDACSetSecurityImageLabel):
Likewise.
* src/security/security_selinux.c (SELinuxSetSecurityImageLabel):
Likewise.
* src/security/virt-aa-helper.c (get_files): Likewise.
Approximately 60 messages were marked. Since these diagnostics are
intended solely for developers and maintainers, encouraging translation
is deemed to be counterproductive:
http://thread.gmane.org/gmane.comp.emulators.libvirt/25050/focus=25052
Run this command:
git grep -l VIR_WARN|xargs perl -pi -e \
's/(VIR_WARN0?)\s*\(_\((".*?")\)/$1($2/'
virFileResolveLink was returning a positive value on error,
thus confusing callers that assumed failure was < 0. The
confusion is further evidenced by callers that would have
ended up calling virReportSystemError with a negative value
instead of a valid errno.
Fixes Red Hat BZ #591363.
* src/util/util.c (virFileResolveLink): Live up to documentation.
* src/qemu/qemu_security_dac.c
(qemuSecurityDACRestoreSecurityFileLabel): Adjust callers.
* src/security/security_selinux.c
(SELinuxRestoreSecurityFileLabel): Likewise.
* src/storage/storage_backend_disk.c
(virStorageBackendDiskDeleteVol): Likewise.
* configure.ac: Check for <linux/magic.h>.
* src/util/storage_file.c: Include <linux/magic.h> only if present.
Linux kernels prior to 2.6.19 lacked it.
[__linux__] (NFS_SUPER_MAGIC): Define if not already defined.
When QEMU runs with its disk on NFS, and as a non-root user, the
disk is chownd to that non-root user. When migration completes
the last step is shutting down the QEMU on the source host. THis
normally resets user/group/security label. This is bad when the
VM was just migrated because the file is still in use on the dest
host. It is thus neccessary to skip the reset step for any files
found to be on a shared filesystem
* src/libvirt_private.syms: Export virStorageFileIsSharedFS
* src/util/storage_file.c, src/util/storage_file.h: Add a new
method virStorageFileIsSharedFS() to determine if a file is
on a shared filesystem (NFS, GFS, OCFS2, etc)
* src/qemu/qemu_driver.c: Tell security driver not to reset
disk labels on migration completion
* src/qemu/qemu_security_dac.c, src/qemu/qemu_security_stacked.c,
src/security/security_selinux.c, src/security/security_driver.h,
src/security/security_apparmor.c: Add ability to skip disk
restore step for files on shared filesystems.
Gnulib can guarantee that pthread.h exists, but for now, it is a dummy
header with no support for most pthread_* functions. Modify our
use of pthread to use function checks, rather than header checks,
to determine how much pthread support is present.
* bootstrap.conf (gnulib_modules): Add pthread.
* configure.ac: Drop all pthread.h checks. Optimize function
checks. Add check for pthread functions.
* src/Makefile.am (libvirt_lxc_LDADD): Ensure proper link.
* src/remote/remote_driver.c (remoteIOEventLoop): Depend on
pthread_sigmask, now that gnulib guarantees pthread.h.
* src/util/util.c (virFork): Likewise.
* src/util/threads.c (threads-pthread.c): Depend on
pthread_mutexattr_init, as a witness of full pthread support.
* src/util/threads.h (threads-pthread.h): Likewise.
Detected by clang. POSIX requires that the second argument to
va_start be the name of the last variable; and in some implementations,
passing *path instead of path would dereference bogus memory instead
of pulling arguments off the stack.
* src/util/util.c (virBuildPathInternal): Use correct argument to
va_start.
Add an empty body for virCondWaitUntil and move virPipeReadUntilEOF
out of the '#ifndef WIN32' block, because it compiles fine with MinGW
in combination with gnulib.
Necessary on cygwin, where uid_t and gid_t are 4-byte long rather
than int, causing gcc -Wformat warnings.
* src/util/util.c (virFileOperationNoFork, virDirCreateNoFork)
(virFileOperation, virDirCreate, virGetUserEnt): Cast uid_t and
gid_t before passing to printf.
* .gitignore: Ignore Windows executables.
It implements an idea to save dhcp hosts' macaddr vs. ipaddr mappings to
static file and make dnsmasq loading it with "--dhcp-hostsfile" option,
originally suggested by Dan, and can address the problem that too
many "--dhcp-host" args hitting ARG_MAX limit
* src/util/dnsmasq.h src/util/dnsmasq.c: adds the 2 new files
Based on a warning from coverity. The safe* functions
guarantee complete transactions on success, but don't guarantee
freedom from failure.
* src/util/util.h (saferead, safewrite, safezero): Add
ATTRIBUTE_RETURN_CHECK.
* src/remote/remote_driver.c (remoteIO, remoteIOEventLoop): Ignore
some failures.
(remoteIOReadBuffer): Adjust error messages on read failure.
* daemon/event.c (virEventHandleWakeup): Ignore read failure.
* This patch implements a memory allocator to obtain memory for
structures whose last member is a variable length array. C99 refers
to these variable length objects as structs containing flexible
array members.
* Fixed macro parentheses per Eric Blake
Changes from v1 to v2:
- changed function name prefixes to 'iface' from previous 'Iface'
- Further to make make syntax-check pass:
- indentation fix in interface.h
- added entry to POTFILES.in
I am consolidating network interface related functions used in nwfilter
and macvtap code in utils/interface.c. All function names are prefixed
with 'Iface'. The following functions are now available through
interface.h:
int ifaceCtrl(const char *name, bool up);
int ifaceUp(const char *name);
int ifaceDown(const char *name);
int ifaceCheck(bool reportError, const char *ifname,
const unsigned char *macaddr, int ifindex);
int ifaceGetIndex(bool reportError, const char *ifname, int *ifindex);
I added 'int ifindex' as parameter to ifaceCheck to the original
function and modified the code accordingly.
The network filter / snapshot / hooks code introduced some
non-portable pices that broke the win32 build
* configure.ac: Check for net/ethernet.h required by nwfile config
parsing code
* src/conf/nwfilter_conf.c: Define ethernet protocol constants
if net/ethernet.h is missing
* src/util/hooks.c: Disable hooks build on Win32 since it lacks
fork/exec/pipe
* src/util/threads-win32.c: Fix unchecked return value
* tools/virsh.c: Disable SIGPIPE on Win32 since it doesn't exist.
Fix non-portable strftime() formats
git grep found 12 of the former but 100 of the latter in src/.
* src/remote/remote_driver.c (initialise_gnutls): Rename...
(initialize_gnutls): ...to this.
(doRemoteOpen): Adjust caller.
* src/xen/xen_driver.c (xenUnifiedOpen): Adjust output string.
* src/util/network.c: Adjust comments.
Suggested by Matthias Bolte.
This also fixes a problem with MinGW's GCC on Windows. GCC complains
about the L modifier being unknown.
Parsing in pciIterDevices is stricter now and doesn't accept trailing
characters after the actual <domain>:<bus>:<slot>.<function> sequence
anymore.
Parsing in pciWaitForDeviceCleanup is also stricter now and expects
the <start>-<end> : <domain>:<bus>:<slot>.<function> sequence to be
terminated by \n.
Change domain from unsigned long long to unsigned int in
pciWaitForDeviceCleanup, because everywhere else domain is handled as
unsigned int too.
The switch from %lli to %lld in virCgroupGetValueI64 is intended,
as virCgroupGetValueU64 uses base 10 too, and virCgroupSetValueI64
uses %lld to format the number to string.
Parsing is stricter now and doesn't accept trailing characters
after the actual value anymore.
virParseVersionString uses virStrToLong_ui instead of sscanf.
This also fixes a bug in the UML driver, that always returned 0
as version number.
Introduce STRSKIP to check if a string has a certain prefix and
to skip this prefix.
This patch changes the network filtering code to use libvirt's existing
IPv4 and IPv6 address parsers/printers rather than my self-written ones.
I am introducing a new function in network.c that counts the number of
bits in a netmask and ensures that the given address is indeed a netmask,
return -1 on error or values of 0-32 for IPv4 addresses and 0-128 for
IPv6 addresses. I then based the function checking for valid netmask
on invoking this function.
This exports 3 basic routines:
- virHookInitialize() initializing the hook support by looking for
scripts availability
- virHookPresent() used to test if there is a hook for a given driver
- virHookCall() which actually calls a synchronous script hook with
the needed parameters
Note that this doesn't expose any public API except for the locations
and arguments passed to the scripts
* src/Makefile.am: add the 2 new files
* src/util/hooks.h src/util/hooks.c: implements the 3 functions
* src/libvirt_private.syms: export the 3 symbols internally
* po/POTFILES.in: add src/util/hooks.c to translatables modules
used to read the data from virExec stdout/err file descriptors
* src/util/util.c src/util/util.h: not static anymore and export it
* src/libvirt_private.syms: allow access internally
This patch adds the implementation of the public API for the network
filtering (ACL) extensions to libvirt.c .
Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
This patch adds recursive locks necessary due to the processing of
network filter XML that can reference other network filters, including
references that cause looks. Loops in the XML are prevented but their
detection requires recursive locks.
Signed-off-by: Stefan Berger <stefanb@us.ibm.com>
The keys of entries in a VMX file are case insensitive. Both scsi0:1.fileName
and scsi0:1.filename are valid. Therefore, make the conf parser compare names
case insensitive in VMX mode to accept every capitalization variation.
Also add test cases for this.
Even if gnulib can provide stubs, it won't help that much. So just
replace affected util functions (virFileOperation and virDirCreate)
with stubs on Windows. Both functions aren't used on libvirt's
client side, so this is fine for MinGW builds.
Invoking virDomainSetMemory() on lxc driver results in libvirtd
segfault when cgroups has not been configured on the host.
Ensure driver->cgroup is non-null before invoking
virCgroupForDomain(). To prevent similar segfaults in the future,
ensure driver parameter to virCgroupForDomain() is non-null before
dereferencing.
POSIX states that creation of a mutex with default attributes
is unspecified whether the mutex is recursive or non-recursive.
We specifically want non-recursive (deadlock is desirable in
flushing out coding bugs that used our mutex incorrectly).
* src/util/threads-pthread.c (virMutexInit): Specifically request
non-recursive mutex, rather than relying on unspecified default.
to saferead_lim, which interprets it as a size_t.
* src/util/util.c (virFileReadLimFD): Do not malfunction when
maxlen < -1. Return -1,EINVAL in that case. Handle maxlen==0
in the same manner.
Changeset
commit 5073aa994a
Author: Cole Robinson <crobinso@redhat.com>
Date: Mon Jan 11 11:40:46 2010 -0500
Added support for product/vendor based passthrough, but it only
worked at the security driver layer. The main guest XML config
was not updated with the resolved bus/device ID. When the QEMU
argv refactoring removed use of product/vendor, this then broke
launching guests.
THe solution is to move the product/vendor resolution up a layer
into the QEMU driver. So the first thing QEMU does is resolve
the product/vendor to a bus/device and updates the XML config
with this info. The rest of the code, including security drivers
and QEMU argv generated can now rely on bus/device always being
set.
* src/util/hostusb.c, src/util/hostusb.h: Split vendor/product
resolution code out of usbGetDevice and into usbFindDevice.
Add accessors for bus/device ID
* src/security/virt-aa-helper.c, src/security/security_selinux.c,
src/qemu/qemu_security_dac.c: Remove vendor/product from the
usbGetDevice() calls
* src/qemu/qemu_driver.c: Use usbFindDevice to resolve vendor/product
into a bus/device ID
When getting the driver/domain cgroup it is possible to specify
whether it should be auto created. If auto-creation was turned
off, libvirt still mistakenly created its own top level cgroup
* src/util/cgroup.c: Honour autocreate flag for top level cgroup
Various safezero() implementations used either -1, errno or -errno
return values. This patch fixes them all to return -1 and set errno
appropriately.
There was also a bug in size parameter passed to safewrite() which could
result in an attempt to write gigabytes out of a megabyte buffer.
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
This introduces a third option for clock offset synchronization,
that allows an arbitrary / variable adjustment to be set. In
essence the XML contains the time delta in seconds, relative to
UTC.
<clock offset='variable' adjustment='123465'/>
The difference from 'utc' mode, is that management apps should
track adjustments and preserve them at next reboot.
* docs/schemas/domain.rng: Schema for new clock mode
* src/conf/domain_conf.c, src/conf/domain_conf.h: Parse
new clock time delta
* src/libvirt_private.syms, src/util/xml.c, src/util/xml.h: Add
virXPathLongLong() method
It turns out it is also useful to be able to perform other operations
on a file created while running as a different uid (eg, write things
to that file), and possibly to do this to a file that already
exists. This patch adds an optional hook function to the renamed (for
more accuracy of purpose) virFileOperation; the hook will be called
after the file has been opened (possibly created) and gid/mode
checked/set, before closing it.
As with the other operations on the file, if the VIR_FILE_OP_AS_UID
flag is set, this hook function will be called in the context of a
child process forked from the process that called virFileOperation.
The implication here is that, while all data in memory is available to
this hook function, any modification to that data will not be seen by
the caller - the only indication in memory of what happened in the
hook will be the return value (which the hook should set to 0 on
success, or one of the standard errno values on failure).
Another piece of making the function more flexible was to add an
"openflags" argument. This arg should contain exactly the flags to be
passed to open(2), eg O_RDWR | O_EXCL, etc.
In the process of adding the hook to virFileOperation, I also realized
that the bits to fix up file owner/group/mode settings after creation
were being done in the parent process, which could fail, so I moved
them to the child process where they should be.
* src/util/util.[ch]: rename and rework virFileCreate-->virFileOperation,
and redo flags in virDirCreate
* storage/storage_backend.c, storage/storage_backend_fs.c: update the
calls to virFileOperation/virDirCreate to reflect changes in the API,
but don't yet take advantage of the hook.
If the hostname as returned by "gethostname" resolves
to "localhost" (as it does with the broken Fedora-12
installer), then live migration will fail because the
source will try to migrate to itself. Detect this
situation up-front and abort the live migration before
we do any real work.
* src/util/util.h src/util/util.c: add a new virGetHostnameLocalhost
with an optional localhost check, and rewire virGetHostname() to use
it
* src/libvirt_private.syms: expose the new function
* src/qemu/qemu_driver.c: use it in qemudDomainMigratePrepare2()
This patch sets or unsets the IFF_VNET_HDR flag depending on what device
is used in the VM. The manipulation of the flag is done in the open
function and is only fatal if the IFF_VNET_HDR flag could not be cleared
although it has to be (or if an ioctl generally fails). In that case the
macvtap tap is closed again and the macvtap interface torn.
* src/qemu/qemu_conf.c src/qemu/qemu_conf.h: pass qemuCmdFlags to
qemudPhysIfaceConnect()
* src/util/macvtap.c src/util/macvtap.h: add vnet_hdr boolean to
openMacvtapTap(), and private function configMacvtapTap()
* src/qemu/qemu_driver.c: add extra qemuCmdFlags when calling
qemudPhysIfaceConnect()
For __virExec() this is a semantic NOP except for when fork()
fails. __virExec() would previously forget to restore the signal mask
in this case; virFork() corrects this behavior.
virFileCreate() and virDirCreate() gain the code to reset the logging
and properly deal with the signal handling race condition.
This also removes a log message that had a typo ("cannot fork o create
file '%s'") - this error is now logged in a more generic manner in
virFork() (more generic, but really just as informative, since the
fact that it's forking to create a file is immaterial to the fact that
it simply can't fork)
* src/util/util.c: use the generic virFork() in the 3 functions
virFork() contains bookkeeping that must be done any time a process
forks. Currently this includes:
1) Call virLogLock() prior to fork() and virLogUnlock() just after,
to avoid a deadlock if some other thread happens to hold that lock
during the fork.
2) Reset the logging hooks and send all child process log messages to
stderr.
3) Block all signals prior to fork(), then either a) reset the signal
mask for the parent process, or b) clear the signal mask for the
child process.
Note that the signal mask handling in __virExec erroneously fails to
restore the signal mask when fork() fails. virFork() fixes this
problem.
Other than this, it attempts to behave as closely to fork() as
possible (including preserving errno for the caller), with a couple
exceptions:
1) The return value is 0 (success) or -1 (failure), while the pid is
returned via the pid_t* argument. Like fork(), if pid < 0 there is
no child process, otherwise both the child and the parent will
return to the caller, and both should look at the return value,
which will indicate if some of the extra processing outlined above
encountered an error.
2) If virFork() returns with pid < 0 or with a return value < 0
indicating an error condition, the error has already been
reported. You can log an additional message if you like, but it
isn't necessary, and may be awkwardly extraneous.
Note that virFork()'s child process will *never* call _exit() - if a
child process is created, it will return to the caller.
* util.c util.h: add virFork() function, based on what is currently
done in __virExec().
virGetLastError returns NULL if no error has been set, not on
allocation error like virSetError assumed. Use virLastErrorObject
instead. This fixes virSetError when no error is currently stored.
Rework and simplification of teardown of the macvtap device.
Basically all devices with the same MAC address and link device are kept
alive and not attempted to be torn down. If a macvtap device linked to a
physical interface with a certain MAC address 'M' is to be created it
will automatically fail if the interface is 'up'ed and another macvtap
with the same properties (MAC addr 'M', link dev) happens to be 'up'.
This will prevent the VM from starting or the device from being attached
to a running VM. Stale interfaces are assumed to be there for some
reason and not stem from libvirt.
In the VM shutdown path, it's assuming that an interface name is always
available so that if the device type is DIRECT it can be torn down
using its name.
* src/util/macvtap.h src/libvirt_macvtap.syms: change of deleting routine
* src/util/macvtap.c: cleanups and change of deleting routine
* src/qemu/qemu_driver.c: change cleanup on shutdown
* src/qemu/qemu_conf.c: don't delete Macvtap in qemudPhysIfaceConnect()
This part adds the helper code to setup and tear down macvtap devices
using direct communication with the device driver via netlink sockets.
The rather short messages received from the netlink layer are now
written into a dynamically allocated buffer
* src/util/macvtap.h src/util/macvtap.c: provides the new module
* po/POTFILES.in: the module contains translated strings
This part adds support to domain_conf.{c|h} for parsing the new
interface XML of type 'direct'. The parsed mode is now stored as
an int.
* src/conf/domain_conf.c src/conf/domain_conf.h: extend parsing code
* src/util/macvtap.h: empty header to not break compilation
This patch adds build support for libvirt checking for certain contents
of /usr/include/linux/if_link.h to see whether macvtap support is
compilable on that system. One can disable macvtap support in libvirt
via --without-macvtap passed to configure.
* configure.ac src/Makefile.am: new build support
* src/libvirt_macvtap.syms: list of exported symbols
* src/util/macvtap.c: empty module to not break compilation
All callers now pass a NULL virConnectPtr into the USB/PCi device
iterator functions. Therefore the virConnectPtr arg can now be
removed from these functions
* src/util/hostusb.h, src/util/hostusb.c: Remove virConnectPtr
from usbDeviceFileIterate
* src/util/pci.c, src/util/pci.h: Remove virConnectPtr arg from
pciDeviceFileIterate
* src/qemu/qemu_security_dac.c, src/security/security_selinux.c: Update
to drop redundant virConnectPtr arg
* src/util/util.h (virAsprintf): Remove ATTRIBUTE_RETURN_CHECK, since
it is perfectly fine to ignore the return value, now that the pointer
is guaranteed to be set to NULL upon failure.
* src/util/storage_file.c (absolutePathFromBaseFile): Remove now-
unnecessary use of ignore_value.
* src/util/storage_file.c (absolutePathFromBaseFile): While this use
of virAsprintf is slightly cleaner than using stpncpy(stpcpy(...,
it does impose an artificial limitation on the length of the base_file
name. Rather than asserting that it does not exceed INT_MAX, return
NULL when it does.
When configured with --enable-gcc-warnings, it didn't even compile.
* src/util/storage_file.c: Include <assert.h>.
(absolutePathFromBaseFile): Assert that converting size_t to int is valid.
Reverse length/string args to match "%.*s".
Explicitly ignore the return value of virAsprintf.
* src/util/storage_file.c: Include "dirname.h".
(absolutePathFromBaseFile): Rewrite not to leak, and to require
fewer allocations.
* bootstrap (modules): Add dirname-lgpl.
* .gnulib: Update submodule to the latest.
Similar fix as previous one but for fork() usage when creating
a file or directory
* src/util/util.c: virLogLock() and virLogUnlock() around fork()
in virFileCreate() and virDirCreateSimple()
Ad pointed out by Dan Berrange:
So if some thread in libvirtd is currently executing a logging call,
while another thread calls virExec(), that other thread no longer
exists in the child, but its lock is never released. So when the
child then does virLogReset() it deadlocks.
The only way I see to address this, is for the parent process to call
virLogLock(), immediately before fork(), and then virLogUnlock()
afterwards in both parent & child. This will ensure that no other
thread
can be holding the lock across fork().
* src/util/logging.[ch] src/libvirt_private.syms: export virLogLock() and
virLogUnlock()
* src/util/util.c: lock just before forking and unlock just after - in
both parent and child.
* src/util/util.c (virGetUserID, virGetGroupID): In the unlikely event
that sysconf(_SC_GETPW_R_SIZE_MAX) fails, don't use -1 as the size in
the subsequent allocation.
On RHEL-5 the qemu-kvm binary is located in /usr/libexec.
To reduce confusion for people trying to run upstream libvirt
on RHEL-5 machines, make the qemu driver look in /usr/libexec
for the qemu-kvm binary.
To make this work, I modified virFindFileInPath to handle an
absolute path correctly. I also ran into an issue where
NULL was sometimes being passed for the file parameter
to virFindFileInPath; it didn't crash prior to this patch
since it was building paths like /usr/bin/(null). This
is non-standard behavior, though, so I added a NULL
check at the beginning.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
* src/util/util.c (virGetUserEnt): In the unlikely event that
sysconf(_SC_GETPW_R_SIZE_MAX) fails, don't use -1 as the size in
the subsequent allocation.
virFileMakePath is a recursive function that was creates a buffer
PATH_MAX bytes long for each recursion (one recursion for each element
in the path). This changes it to have no buffers on the stack, and to
allocate just one buffer total, no matter how many elements are in the
path. Because the modified algorithm requires a char* to be passed in
rather than const char *, it is now 2 functions - a toplevel API
function that remains identical in function, and a 2nd helper function
called for the recursions, which 1) doesn't allocate anything, and 2)
takes a char* arg, so it can modify the contents.
* src/util/util.c: rewrite virFileMakePath
* src/util/json.c, src/util/json.h: Declare returned strings
to be const
* src/qemu/qemu_monitor.c: Wire up JSON mode for qemuMonitorGetPtyPaths
* src/qemu/qemu_monitor_json.c, src/qemu/qemu_monitor_json.h: Fix
const correctness. Add missing error message in the function
qemuMonitorJSONGetAllPCIAddresses. Add implementation of the
qemuMonitorGetPtyPaths function calling 'query-chardev'.
Certain hypervisors (like qemu/kvm) map the PCI bar(s) on
the host when doing device passthrough. This can lead to a race
condition where the hypervisor is still cleaning up the device while
libvirt is trying to re-attach it to the host device driver. To avoid
this situation, we look through /proc/iomem, and if the hypervisor is
still holding onto the bar (denoted by the string in the matcher variable),
then we can wait around a bit for that to clear up.
v2: Thanks to review by DV, make sure we wait the full timeout per-device
Signed-off-by: Chris Lalancette <clalance@redhat.com>
The patches to add ACS checking to PCI device passthrough
introduced a bug. With the current code, if you try to
passthrough a device on the root bus (i.e. bus 0), then
it denies the passthrough. This is because the code in
pciDeviceIsBehindSwitchLackingACS() to check for a parent
device doesn't take into account the possibility of the
root bus. If we are on the root bus, it means we
legitimately can't find a parent, and it also means that
we don't have to worry about whether ACS is enabled.
Therefore return 0 (indicating we don't lack ACS) from
pciDeviceIsBehindSwitchLackingACS().
Signed-off-by: Chris Lalancette <clalance@redhat.com>
These functions create a new file or directory with the given
uid/gid. If the flag VIR_FILE_CREATE_AS_UID is given, they do this by
forking a new process, calling setuid/setgid in the new process, and
then creating the file. This is better than simply calling open then
fchown, because in the latter case, a root-squashing nfs server would
create the new file as user nobody, then refuse to allow fchown.
If VIR_FILE_CREATE_AS_UID is not specified, the simpler tactic of
creating the file/dir, then chowning is is used. This gives better
results in cases where the parent directory isn't on a root-squashing
NFS server, but doesn't give permission for the specified uid/gid to
create files. (Note that if the fork/setuid method fails to create the
file due to access privileges, the parent process will make a second
attempt using this simpler method.)
If the bit VIR_FILE_CREATE_ALLOW_EXIST is set in the flags, an
existing file/directory will not cause an error; in this case, the
function will simply set the permissions of the file/directory to
those requested. If VIR_FILE_CREATE_ALLOW_EXIST is not specified, an
existing file/directory is considered (and reported as) an error.
Return from both of these functions is 0 on success, or the value of
errno if there was a failure.
* src/util/util.[ch]: add the 2 new util functions
* src/util/logging.c (virLogMessage): Include "ignore-value.h".
Use it to ignore the return value of safewrite.
Use STDERR_FILENO, rather than "2".
* bootstrap (modules): Add ignore-value.
* gnulib: Update to latest, for ignore-value that is now LGPLv2+.
I noticed some debug messages are printed with an empty lines after
them. This patch removes these empty lines from all invocations of the
following macros:
VIR_DEBUG
VIR_DEBUG0
VIR_ERROR
VIR_ERROR0
VIR_INFO
VIR_WARN
VIR_WARN0
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
New pciDeviceIsAssignable() function for checking whether a given PCI
device can be assigned to a guest was added. Currently it only checks
for ACS being enabled on all PCIe switches between root and the PCI
device. In the future, it could be the right place to check whether a
device is unbound or bound to a stub driver.
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
Until recently, some gnulib-generated replacement headers
included *other* headers that were not strictly necessary,
thus masking the need in this file for an explicit <stdlib.h>.
* src/util/util.c: Include <stdlib.h> for declarations of e.g.,
strtol, random_r, getenv, etc.
With the introduction virDispatchError, hook function errors are
never sent through the error callback, so users will never see
these messages.
Fix this by calling virDispatchError after hook failure.
Based off how QEMU does it, look through /sys/bus/usb/devices/* for
matching vendor:product info, and if found, use info from the surrounding
files to build the device's /dev/bus/usb path.
This fixes USB device assignment by vendor:product when running qemu
as non-root (well, it should, but for some reason I couldn't reproduce
the failure people are seeing in [1], but it appears to work properly)
[1] https://bugzilla.redhat.com/show_bug.cgi?id=542450
This allows debug statements and raised errors in hook functions to
actually be logged somewhere (stderr). Users can enable debugging in the
daemon and now see more info in /var/log/libvirt/...
The virRaiseErrorFull() may invoke the error handler callback
functions an application has registered. This is not good
because the connection object may not be available at this
point, and the caller may be holding locks. This creates a
problem if the error handler calls back into libvirt.
The solutuon is to move invocation of the handler into the
final cleanup code in the public API entry points, where it
is guarenteed to have safe state.
* src/libvirt.c: Invoke virDispatchError() in all error paths
* src/util/virterror.c: Remove virSetConnError/virSetGlobalError,
replacing with virDispatchError(). Move invocation of the
error callbacks into virDispatchError() instead of the
virRaiseErrorFull function which is not in a safe context
Only use pseudo-random generator for uuid if using /dev/random fails.
* src/util/uuid.c: The original code. would only print the warning
message if using /dev/random failed, but would still go ahead and call
virUUIDGeneratePseudoRandomBytes in all cases anyway.
Found while trying to cross-compile libvirt on Fedora 12 for Windows.
gnulib redefines 'close' to 'close_used_without_including_unistd_h'
in sys/socket.h if winsock2.h is present and unistd.h has not been
included before sys/socket.h. Reorder some includes to fix this.
* include/libvirt/virterror.h src/util/virterror.c: add new domain
VIR_FROM_CPU for errors
* src/conf/cpu_conf.c src/conf/cpu_conf.h: new parsing module
* src/Makefile.am proxy/Makefile.am: include new files
* src/conf/capabilities.[ch] src/conf/domain_conf.[ch]: reference
new code
* src/libvirt_private.syms: private export of new entry points
The virFileResolveLink utility function relied on the POSIX guarantee
that stat.st_size of a symlink is the length of the value. However,
on some types of file systems, it is invalid, so do not rely on it.
Use gnulib's areadlink module instead.
* bootstrap (modules): Add areadlink.
* src/util/util.c: Include "areadlink.h".
Let areadlink perform the readlink and malloc.
* configure.in (AC_CHECK_FUNCS): Remove readlink. No need,
since it's presence is guaranteed by gnulib.
* src/xen/xm_internal.c (xenXMConfigGetULong): Remove useless and
misleading test (always false) for val->str == NULL before code that
always dereferences val->str. "val" comes from virConfGetValue, and
at that point, val->str is guaranteed to be non-NULL.
(xenXMConfigGetBool): Likewise.
* src/util/conf.c (virConfSetValue): Ensure that vir->str is never NULL,
not even if someone tries to set such a value via virConfSetValue.
We don't use this method of reloading rules anymore, so we can just
kill the code.
This simplifies things a lot because we no longer need to keep a
table of the rules we've added.
* src/util/iptables.c: kill iptablesReloadRules()
Long ago we tried to use Fedora's lokkit utility in order to register
our iptables rules so that 'service iptables restart' would
automatically load our rules.
There was one fatal flaw - if the user had configured iptables without
lokkit, then we would clobber that configuration by running lokkit.
We quickly disabled lokkit support, but never removed it. Let's do
that now.
The 'my virtual network stops working when I restart iptables' still
remains. For all the background on this saga, see:
https://bugzilla.redhat.com/227011
* src/util/iptables.c: remove lokkit support
* configure.in: remove --enable-lokkit
* libvirt.spec.in: remove the dirs used only for saving rules for lokkit
* src/Makefile.am: ditto
* src/libvirt_private.syms, src/network/bridge_driver.c,
src/util/iptables.h: remove references to iptablesSaveRules
Replace free(virBufferContentAndReset()) with virBufferFreeAndReset().
Update documentation and replace all remaining calls to free() with
calls to VIR_FREE(). Also add missing calls to virBufferFreeAndReset()
and virReportOOMError() in OOM error cases.
Fix this warning, there is no need to use an intermediate,
different array pointer.
network.c: In function 'getIPv6Addr':
network.c:50: warning: dereferencing type-punned pointer will break strict-aliasing rules
* src/util/network.c: avoid an intermediary pointer cast
configure: yajl: no
CC libvirt_util_la-json.lo
util/json.c:32:27: error: yajl/yajl_gen.h: No such file or directory
util/json.c:33:29: error: yajl/yajl_parse.h: No such file or directory
* src/util/json.c: remove the includes if yajl not configured in
This introduces simple API for handling JSON data. There is
an internal data structure 'virJSONValuePtr' which stores a
arbitrary nested JSON value (number, string, array, object,
nul, etc). There are APIs for constructing/querying objects
and APIs for parsing/formatting string formatted JSON data.
This uses the YAJL library for parsing/formatting from
http://lloyd.github.com/yajl/
* src/util/json.h, src/util/json.c: Data structures and APIs
for representing JSON data, and parsing/formatting it
* configure.in: Add check for yajl library
* libvirt.spec.in: Add build requires for yajl
* src/Makefile.am: Add json.c/h
* src/libvirt_private.syms: Export JSON symbols to drivers
esxVMX_IndexToDiskName handles indices up to 701. This limit comes
from a mapping gap in virDiskNameToIndex:
sdzy -> 700
sdzz -> 701
sdaaa -> 728
sdaab -> 729
This line in virDiskNameToIndex causes this gap:
idx = (idx + i) * 26;
Fixing it by altering this line to:
idx = (idx + (i < 1 ? 0 : 1)) * 26;
Also add a new version of virIndexToDiskName that handles the inverse
mapping for arbitrary indices.
* src/esx/esx_vmx.[ch]: remove esxVMX_IndexToDiskName
* src/util/util.[ch]: add virIndexToDiskName and fix mapping gap
* tests/esxutilstest.c: update test to verify that the gap is fixed
The cpu_set_t type can only cope with NR_CPUS <= 1024, beyond this
it is neccessary to use alternate CPU_SET maps with a dynamically
allocated CPU map
* src/util/processinfo.c: Support new unlimited size CPU set type
* src/Makefile.am: Add processinfo.h/processinfo.c
* src/util/processinfo.c, src/util/processinfo.h: Module providing
APIs for getting/setting process CPU affinity
* src/qemu/qemu_driver.c: Switch over to new APIs for schedular
affinity
* src/libvirt_private.syms: Export virProcessInfoSetAffinity
and virProcessInfoGetAffinity to internal drivers
In the scenario where the cgroups were mounted but the
particular group did not exist, and the caller had not
requested auto-creation, the code would fail to return
an error condition. This caused the lxc_controller to
think the cgroup existed, and it then later failed when
attempting to use it
* src/util/cgroup.c: Raise an error if the cgroup path does not
exist
* configure.in: add new --with-udev, disabled by default, and requiring
libudev > 145
* src/node_device/node_device_udev.c src/node_device/node_device_udev.h:
the new node device backend
* src/node_device/node_device_linux_sysfs.c: moved node_device_hal_linux.c
to a better file name
* src/conf/node_device_conf.c src/conf/node_device_conf.h: add a couple
of fields in node device definitions, and an API to look them up,
remove a couple of unused fields from previous patch.
* src/node_device/node_device_driver.c src/node_device/node_device_driver.h:
plug the new driver
* po/POTFILES.in src/Makefile.am src/libvirt_private.syms: add the new
files and symbols
* src/util/util.h src/util/util.c: add a new convenience macro
virBuildPath and virBuildPathInternal() function
* src/xen/xen_driver.c: Add support for VIR_MIGRATE_PERSIST_DEST flag
* src/xen/xend_internal.c: Add support for VIR_MIGRATE_UNDEFINE_SOURCE flag
* include/libvirt/virterror.h, src/util/virterror.c: Add new errorcode
VIR_ERR_MIGRATE_PERSIST_FAILED
* src/libvirt.c src/lxc/lxc_conf.c src/lxc/lxc_container.c
src/lxc/lxc_controller.c src/node_device/node_device_hal.c
src/openvz/openvz_conf.c src/qemu/qemu_driver.c
src/qemu/qemu_monitor_text.c src/remote/remote_driver.c
src/storage/storage_backend_disk.c src/storage/storage_driver.c
src/util/logging.c src/xen/sexpr.c src/xen/xend_internal.c
src/xen/xm_internal.c: Steve Grubb <sgrubb@redhat.com> sent a code
review and those are the fixes correcting the problems
Some monitor commands may take a very long time to complete. It is
not desirable to block other incoming API calls forever. With this
change, if an existing API call is holding the job lock, additional
API calls will not wait forever. They will time out after a short
period of time, allowing application to retry later.
* include/libvirt/virterror.h, src/util/virterror.c: Add new
VIR_ERR_OPERATION_TIMEOUT error code
* src/qemu/qemu_driver.c: Change to a timed condition variable
wait for acquiring the monitor job lock
* src/util/threads-pthread.c: pthreads APIs do not set errno, instead
the return value is the positive errno. Set errno based on the return
value in the wrappers
* src/util/pci.c, src/util/pci.h: Make the pciDeviceList struct
opaque to callers of the API. Add accessor methods for managing
devices in the list
* src/qemu/qemu_driver.c: Update to use APIs instead of directly
accessing pciDeviceList fields
As it was basically unimplemented and more confusing than useful
at the moment.
* src/libvirt_private.syms: remove from internal symbols list
* src/qemu/qemu_bridge_filter.c src/util/ebtables.c: remove code and
one use of the unimplemented function
* src/internal.h (ATTRIBUTE_SENTINEL): New, it's a ggc feature and
protected as such
* src/util/buf.c (virBufferStrcat): Use it.
* src/util/ebtables.c (ebtablesAddRemoveRule): Use it.
* src/util/iptables.c (iptableAddRemoveRule: Use it.
* src/util/qparams.h (new_qparam_set, append_qparams): Use it.
* docs/apibuild.py: avoid breaking the API generator with that new
internal keyword macro
* include/libvirt/virterror.h src/util/virterror.c: add a new error
VIR_ERR_CONFIG_UNSUPPORTED for valid but unsupported configuration options
* src/conf/domain_conf.c: Throw an error if guestfwd address isn't IPv4
and cleanup a number of parsing return error values.
* configure.in: look for ebtables binary location if present
* src/Makefile.am: add the new module
* src/util/ebtables.[ch]: new module and internal APIs around
the ebtables binary
* src/libvirt_private.syms: export the symbols only internally
All drivers have copy + pasted inadequate error reporting which wraps
util.c:virGetHostname. Move all error reporting to this function, and improve
what we report.
Changes from v1:
Drop the driver wrappers around virGetHostname. This means we still need
to keep the new conn argument to virGetHostname, but I think it's worth
it.
Nearly all of the methods in src/util/util.h have error codes that
must be checked by the caller to correct detect & report failure.
Add ATTRIBUTE_RETURN_CHECK to ensure compile time validation of
this
* daemon/libvirtd.c: Add explicit check on return value of virAsprintf
* src/conf/domain_conf.c: Add missing check on virParseMacAddr return
value status & report error
* src/network/bridge_driver.c: Add missing OOM check on virAsprintf
and report error
* src/qemu/qemu_conf.c: Add missing check on virParseMacAddr return
value status & report error
* src/security/security_selinux.c: Remove call to virRandomInitialize
that's done in libvirt.c already
* src/storage/storage_backend_logical.c: Add check & log on virRun
return status
* src/util/util.c: Add missing checks on virAsprintf/Run status
* src/util/util.h: Annotate all methods with ATTRIBUTE_RETURN_CHECK
if they return an error status code
* src/vbox/vbox_tmpl.c: Add missing check on virParseMacAddr
* src/xen/xm_internal.c: Add missing checks on virAsprintf
* tests/qemuargv2xmltest.c: Remove bogus call to virRandomInitialize()
__in6_u.__u6_addr16 is the private name for this struct member,
s6_addr16 is the public one
* src/util/network.c: dont use the private field, but the public one.
We can slightly tighten up the regex's used to detect the use of
nonreentrant functions. We can also check src/util/virterror.c
by modifying a comment; I think it's worth it to get the additional
coverage.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
virXPathNodeSet() could return -1 when doing an evaluation failure
due to xmlXPathEval() from libxml2 behaviour.
* src/util/xml.c: make sure we always return 0 unless the returned
XPath type is of the wrong type (meaning the query passed didn't
evaluate to a node set and code must be fixed)
Most of the hash iterators need to modify either payload of
data args. The const annotation prevents this.
* src/util/hash.h, src/util/hash.c: Remove const-ness from
virHashForEach/Iterator
* src/xen/xm_internal.c: Remove bogus casts
A cgroup file returns integer value terminated with '\n' and remaining
it has sometimes harmful effects, for example it leads virStrToLong_ull
to fail.
* src/util/cgroup.c: strip out terminating \n when reading a value
* src/util/buf.c: if virBufferEscapeString was called on a buffer that
had 0 bytes of space, a size of -1 will be passed to snprintf, resulting
in a segmentation fault, this preallocate some space.
The fread_file_lim() function uses fread() but never handles
EINTR results, causing unexpected failures when reading QEMU
help arg info. It was unneccessarily using FILE * instead
of plain UNIX file handles, which prevented use of saferead()
* src/util/util.c: Switch fread_file_lim over to use saferead
instead of fread, remove FILE * use, and rename
When configuring logging settings, keep more information about the
output destination. Add accessors to retrieve the filter and output
settings in the original string form; this to be used to set up
environment for a child process that also logs.
* src/util/logging.[ch]: add virLogGetFilters and virLogGetOutputs
accessors and modify the internals (including virLogDefineOutput())
to save the data needed for the accessors
* src/util/util.[ch]: Add virFileAbsPath() function to ensure an
absolute path for a potentially realtive path.
* src/libvirt_private.syms: add it in libvirt private symbols
The patch implements the missing memory control APIs for lxc, i.e.,
domainGetMaxMemory, domainSetMaxMemory, domainSetMemory, and improves
domainGetInfo to return proper amount of used memory via cgroup.
* src/libvirt_private.syms: Export virCgroupGetMemoryUsage
and add missing virCgroupSetMemory
* src/lxc/lxc_driver.c: Implement missing memory functions
* src/util/cgroup.c, src/util/cgroup.h: Add the function
to get used memory
Finally, we get to the point of all this.
Move virStorageGetMetadataFromFD() to virStorageFileGetMetadataFromFD()
and move to src/util/storage_file.[ch]
There's no functional changes in this patch, just code movement
* src/storage/storage_backend_fs.c: move code from here ...
* src/util/storage_file.[ch]: ... to here
* src/libvirt_private.syms: export virStorageFileGetMetadataFromFD()
Introduce a metadata structure and make virStorageGetMetadataFromFD()
fill it in.
* src/util/storage_file.h: add virStorageFileMetadata
* src/backend/storage_backend_fs.c: virStorageGetMetadataFromFD() now
fills in the virStorageFileMetadata structure
Rename virStorageVolFormatFileSystem to virStorageFileFormat and
move to src/util/storage_file.[ch]
* src/Makefile.am: add src/util/storage_file.[ch]
* src/conf/storage_conf.[ch]: move enum from here ...
* src/util/storage_file.[ch]: .. to here
* src/libvirt_private.syms: update To/FromString exports
* src/storage/storage_backend.c, src/storage/storage_backend_fs.c,
src/vbox/vbox_tmpl.c: update for above changes
* src/util/xml.c: The virXPath... function take extra care to preserve
the XPath context node (ctxt->node) but in the case of virXPathString
and virXPathBoolean they forgot to do this on the error path. This
patch fixes this and move all ctxt->node = relnode instuctions just
after the xmlXPathEval() to make sure this doesn't happen if this code
is modified.
Add the virStrncpy function, which takes a dst string, source string,
the number of bytes to copy and the number of bytes available in the
dest string. If the source string is too large to fit into the
destination string, including the \0 byte, then no data is copied and
the function returns NULL. Otherwise, this function copies n bytes
from source into dst, including the \0, and returns a pointer to the
dst string. This function is intended to replace all unsafe uses
of strncpy in the code base, since strncpy does *not* guarantee that
the buffer terminates with a \0.
Signed-off-by: Chris Lalancette <clalance@redhat.com>
* src/conf/domain_conf.c: Don't assume all virDomainObjPtr have
a non-NULL monitor_chr field in virDomainObjFormat.
* src/lxc/lxc_driver.c: Implement suspend/resume driver APis
* src/util/cgroup.c, src/util/cgroup.h: Support the 'freezer'
cgroup controller
* src/libvirt_private.syms: Export virCgroupSetFreezerState
and virCgroupGetFreezerState