Commit Graph

1506 Commits

Author SHA1 Message Date
Roman Bogorodskiy
f3d08aa0ba Fix units in virNetDevBridgeSetSTPDelay on BSD
virNetDevBridgeSetSTPDelay accepts delay in milliseconds,
but BSD implementation was expecting seconds. Therefore,
it was working correctly only with delay == 0.
2013-06-25 13:13:46 +01:00
james robson
861d40565e Configure native vlan modes on Open vSwitch ports
This patch adds functionality to allow libvirt to configure the
'native-tagged' and 'native-untagged' modes on openvswitch networks.

Signed-off-by: Laine Stump <laine@redhat.com>
2013-06-25 00:22:36 -04:00
Jiri Denemark
d0d5acb511 Introduce virTypedParamsCopy internal API 2013-06-25 00:38:25 +02:00
Jiri Denemark
fefb0d5464 Introduce VIR_TYPED_PARAMS_DEBUG macro for dumping typed params
All APIs that take typed parameters are only using params address in
their entry point debug messages. With the new VIR_TYPED_PARAMS_DEBUG
macro, all functions can easily log all individual typed parameters
passed to them.
2013-06-25 00:38:24 +02:00
Jiri Denemark
8a7f1166e1 Introduce virTypedParamsReplaceString internal API 2013-06-25 00:38:24 +02:00
Jiri Denemark
637a7c865a Introduce virTypedParamsCheck internal API
This API is useful for checking whether only a specific subset of
supported typed parameters were passed.
2013-06-25 00:38:24 +02:00
Jiri Denemark
40369ea674 util: Emit proper error code in virTypedParamsValidate
When unsupported parameter is passed to virTypedParamsValidate,
VIR_ERR_ARGUMENT_UNSUPPORTED should be returned rather than
VIR_ERR_INVALID_ARG, which is more appropriate for supported parameters
used incorrectly.
2013-06-25 00:38:24 +02:00
Jiri Denemark
c40ed4168a Rename virTypedParameterArrayValidate as virTypedParamsValidate 2013-06-25 00:38:24 +02:00
Laine Stump
9b4a666608 pci: make virPCIDeviceDetach consistent in behavior
virPCIDeviceDetach would previously sometimes consume the input device
object (to put it on the inactive list) and sometimes not. Avoiding
memory leaks required checking beforehand to see if the device was
already on the list, and freeing the device object in the caller only
if there wasn't already an identical object on the inactive list.

This patch makes it consistent - virPCIDeviceDetach will *never*
consume the input virPCIDevice object; if it needs to put one on the
inactive list, it will create a copy and put *that* on the list. This
way the caller knows that it is always their responsibility to free
the device object they created.
2013-06-24 17:35:13 -04:00
Laine Stump
f962e8b603 pci: eliminate memory leak in virPCIDeviceReattach
virPCIDeviceReattach was making the assumption that the dev object
given to it was one and the same with the dev object on the
inactiveDevs list. If that had been the case, it would not need to
free the dev object it removed from the inactive list, because the
caller of virPCIDeviceReattach always frees the dev object that it
passes in. Since the dev object passed in is *never* the same object
that's on the list (it is a different object with the same name and
attributes, created just for the purpose of searching for the actual
object), simply doing a "ListSteal" to remove the object from the list
results in one leaked object; we need to actually free the object
after removing it from the list.
2013-06-24 17:35:01 -04:00
Laine Stump
50a8d85035 pci: new utility functions
* virPCIDeviceFindByIDs - find a device on a list w/o creating an object
    This makes searching for an existing device on a list lighter weight.

* virPCIDeviceCopy - make a copy of an existing virPCIDevice object.

* virPCIDeviceGetDriverPathAndName - construct new strings containing
    1) the name of the driver bound to this device.
    2) the full path to the sysfs config for that driver.
    (This code was lifted from virPCIDeviceUnbindFromStub, and replaced
    there with a call to this new function).
2013-06-24 17:33:38 -04:00
Laine Stump
53e52b4ac3 pci: change stubDriver from const char* to char*
Previously stubDriver was always set from a string literal, so it was
okay to use a const char * that wasn't freed when the virPCIDevice was
freed. This will not be the case in the near future, so it is now a
char* that is allocated in virPCIDeviceSetStubDriver() and freed
during virPCIDeviceFree().
2013-06-24 17:33:29 -04:00
Laine Stump
d80d0d5d40 syntax: virPCIDeviceFree is also a NOP for NULL args
add it to the syntax-check list and fix the one offending caller.
2013-06-24 17:33:23 -04:00
Daniel P. Berrange
5de708c1b9 Set process ID in system identity
When creating a virIdentityPtr for the system identity, include
the current process ID as an attribute.
2013-06-24 15:39:56 +01:00
Daniel P. Berrange
a93cd08fd5 Define basic internal API for access control
This patch introduces the virAccessManagerPtr class as the
interface between virtualization drivers and the access
control drivers. The viraccessperm.h file defines the
various permissions that will be used for each type of object
libvirt manages

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-06-24 15:24:36 +01:00
Ján Tomko
7a99eb912f Get rid of useless VIR_STORAGE_FILE_FEATURE_NONE
It's not used anywhere except for the switch in
virStorageBackendCreateQemuImgOpts, where leaving it in causes
a dead code coverity warning and omitting it breaks compilation
because of unhandled enum value.

Introduced by 6298f74.
2013-06-24 08:44:46 +02:00
Ján Tomko
695593fe00 netdev: accept NULL in virNetDevSetupControl
Commit b9c6b073 dropped the version of virNetDevSetupControl
that didn't check for NULL arguments, but we call it like that
in virNetDevBridgeDelete.
2013-06-21 20:22:07 +02:00
Ján Tomko
a1ee8e18c9 util: add support for qcow2v3 image detection
Detect qcow2 images with version 3 in the image header as
VIR_STORAGE_FILE_QCOW2.

These images have a feature bitfield, with just one feature supported
so far: lazy_refcounts.

The header length changed too, moving the location of the backing
format name.
2013-06-21 13:25:29 +02:00
Roman Bogorodskiy
ce2400676d BSD: implement bridge add/remove port and set STP 2013-06-21 10:23:28 +02:00
Roman Bogorodskiy
b9c6b073e6 BSD: implement virNetDevBridgeCreate() and virNetDevBridgeDelete()
Implementation uses SIOCIFCREATE2 and SIOCIFDESTROY ioctls.
Also, drop static virNetDevSetupControl() as we have
public one avialable now.
2013-06-21 10:23:28 +02:00
Ján Tomko
d0d0413e48 util: switch virBufferTrim to void
We don't care whether the trim was succesful or not anywhere
except the tests.

Switch it to void and set the buffer error on wrong usage.
2013-06-19 09:21:09 +02:00
Doug Goldstein
b5c5f236bb Move virGetUserEnt() to where its needed
In the first if case, virGetUserEnt() isn't necessary so don't bother
calling it before determining we need it.
2013-06-16 14:33:44 -05:00
Roman Bogorodskiy
847e1cd1f8 BSD: implement virNetDevTapCreate() and virNetDevTapDelete()
Implementation uses SIOCIFCREATE2 and SIOCIFDESTROY ioctls.
2013-06-14 16:44:31 +02:00
Roman Bogorodskiy
9614d70b0c Make virNetDevSetupControl() public.
This method is useful not only in virnetdev.c.
2013-06-14 16:14:58 +02:00
Roman Bogorodskiy
0f81bdb2f7 portability: use net/if.h instead of linux/if.h 2013-06-14 15:43:24 +02:00
Ján Tomko
f753dd62f9 udev: fix crash in libudev logging
Call virLogVMessage instead of virLogMessage, since libudev
called us with a va_list object, not a list of arguments.

Honor message priority and strip the trailing newline.

https://bugzilla.redhat.com/show_bug.cgi?id=969152
2013-06-14 13:17:27 +02:00
Michal Privoznik
7793d2a83e virSocketAddrIsWildcard: Use IN6_IS_ADDR_UNSPECIFIED correctly
The IN6_IS_ADDR_UNSPECIFIED macro expects pointer to sin6_addr element
instead of s6_addr element.
2013-06-10 14:48:08 +02:00
Martin Kletzander
78cbff0ff2 storage: fix description of versionOffset 2013-06-10 11:44:31 +02:00
Richard Weinberger
68eea85021 Fix ordering of file open in virProcessGetNamespaces
virProcessGetNamespaces() opens files in /proc/XXX/ns/ which will
later be passed to setns(). We have to make sure that the file
descriptors in the array are in the correct order. In particular
the 'user' namespace must be first otherwise setns() may fail
for other namespaces.

The order has been taken from util-linux's sys-utils/nsenter.c

Also we must ignore EINVAL in setns() which occurs if the
namespace associated with the fd, matches the calling process'
current namespace.

Signed-off-by: Richard Weinberger <richard@nod.at>
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-06-07 17:59:54 +01:00
Michal Privoznik
688994364f virsocket: Introduce virSocketAddrIsWildcard
This internal API checks, if passed address is a wildcard address.
2013-06-07 15:21:57 +02:00
Ján Tomko
85f9178160 Remove redundant two-state integers 2013-06-06 17:22:53 +02:00
Ján Tomko
e557766c3b Replace two-state local integers with bool
Found with 'git grep "= 1"'.
2013-06-06 17:22:53 +02:00
Eric Blake
e90a3598c7 build: fix build without posix_fallocate
Such as on FreeBSD.  Broken in commit aa2a4cff7.

* src/util/virstoragefile.c (virStorageFileResize): Add missing ';',
mark conditionally unused variables.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-06-05 20:38:31 -06:00
Eric Blake
1add9c78da maint: don't use config.h in .h files
Enforce the rule that .h files don't need to (redundantly)
include <config.h>.

* cfg.mk (sc_prohibit_config_h_in_headers): New rule.
(_virsh_includes): Delete; instead, inline a smaller number of
exclusions...
(exclude_file_name_regexp--sc_require_config_h)
(exclude_file_name_regexp--sc_require_config_h_first): ...here.
* daemon/libvirtd.h (includes): Fix offenders.
* src/driver.h (includes): Likewise.
* src/gnutls_1_0_compat.h (includes): Likewise.
* src/libxl/libxl_conf.h (includes): Likewise.
* src/libxl/libxl_driver.h (includes): Likewise.
* src/lxc/lxc_conf.h (includes): Likewise.
* src/lxc/lxc_driver.h (includes): Likewise.
* src/lxc/lxc_fuse.h (includes): Likewise.
* src/network/bridge_driver.h (includes): Likewise.
* src/phyp/phyp_driver.h (includes): Likewise.
* src/qemu/qemu_conf.h (includes): Likewise.
* src/util/virnetlink.h (includes): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-06-05 05:53:25 -06:00
Osier Yang
aa2a4cff7c storage: Support preallocate the new capacity for vol-resize
The document for "vol-resize" says the new capacity will be sparse
unless "--allocate" is specified, however, the "--allocate" flag
is never implemented. This implements the "--allocate" flag for
fs backend's raw type volume, based on posix_fallocate and the
syscall SYS_fallocate.
2013-06-05 18:35:55 +08:00
Martin Kletzander
dc0c791569 usb: don't spoil decimal addresses
For USB devices, dev->name gets formated as %.3o:%.3o even though the
numbers are decimal.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=967712
2013-06-03 13:56:08 +02:00
Daniel P. Berrange
a261996255 Introduce virFilePrintf() as a portable fprintf()
We can't use GNULIB's fprintf-posix due to licensing
incompatibilities. We do already have a portable
formatting via virAsprintf() which we got from GNULIB
though. We can use to create a virFilePrintf() function.

But really gnulib could just provide a 'fprintf'
module, that depended on just its 'asprintf' module.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-31 10:51:33 -06:00
Eric Blake
327d4db83e build: drop unused variable
Compilation for mingw failed:

../../src/util/virutil.c: In function 'virGetWin32DirectoryRoot':
../../src/util/virutil.c:1094:9: error: unused variable 'ret' [-Werror=unused-variable]

* src/util/virutil.c (virGetWin32DirectoryRoot): Silence compiler
warning.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-28 17:11:48 -06:00
Eric Blake
146ba114a5 syntax: prefer space after semicolon in for loop
I noticed several unusual spacings in for loops, and decided to
fix them up.  See the next commit for the syntax check that found
all of these.

* examples/domsuspend/suspend.c (main): Fix spacing.
* python/libvirt-override.c: Likewise.
* src/conf/interface_conf.c: Likewise.
* src/security/virt-aa-helper.c: Likewise.
* src/util/virconf.c: Likewise.
* src/util/virhook.c: Likewise.
* src/util/virlog.c: Likewise.
* src/util/virsocketaddr.c: Likewise.
* src/util/virsysinfo.c: Likewise.
* src/util/viruuid.c: Likewise.
* src/vbox/vbox_tmpl.c: Likewise.
* src/xen/xen_hypervisor.c: Likewise.
* tools/virsh-domain-monitor.c (vshDomainStateToString): Drop
default case, to let compiler check us.
* tools/virsh-domain.c (vshDomainVcpuStateToString): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-28 07:56:07 -06:00
yangdongsheng
2da3bc646e util: fix the VIR_STRDUP when src is NULL
When src is NULL, VIR_STRDUP will return 0 directly.
This patch will set dest to NULL before VIR_STRDUP return.

Example:
[root@yds-pc libvirt]# virsh
Welcome to virsh, the virtualization interactive terminal.

Type: 'help' for help with commands
'quit' to quit

virsh # connect
error: Failed to connect to the hypervisor
error: internal error Unable to parse URI �N�*

Signed-off-by: yangdongsheng <yangds.fnst@cn.fujitsu.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-28 05:57:01 -06:00
Michal Privoznik
0fc5d09cbb Adapt to new VIR_STRNDUP behavior
With previous patch, we accept negative value as length of string to
duplicate. So there is no need to pass strlen(src) in case we want to do
duplicate the whole string.
2013-05-24 17:00:39 +02:00
Michal Privoznik
c93571968b virStrndup: Accept negative values as string length
It may shorten the code a bit as the following pattern:

  VIR_STRNDUP(dst, src, cond ? n : strlen(src))

is used on several places among our code. However, we can
move the strlen into virStrndup and thus write just:

  VIR_STRNDUP(dst, src, cond ? n : -1)
2013-05-24 16:59:30 +02:00
Viktor Mihajlovski
eb21408f44 cgroups: Do not enforce nonexistent controllers
Currently, the controllers argument to virCgroupDetect acts both as
a result filter and a required controller specification, which is
a bit overloaded. If both functionalities are needed, it would be
better to have them seperated into a filter and a requirement mask.
The only situation where it is used today is to ensure that only
CPU related controllers are used for the VCPU directories. But here
we clearly do not want to enforce the existence of cpu, cpuacct and
specifically not cpuset at the same time.
This commit changes the semantics of controllers to "filter only".
Should a required mask ever be needed, more work will have to be done.

Signed-off-by: Viktor Mihajlovski <mihajlov@linux.vnet.ibm.com>
2013-05-24 12:11:24 +02:00
Michal Privoznik
f48ba88b35 Adapt to VIR_STRDUP and VIR_STRNDUP in src/util/* 2013-05-24 10:10:03 +02:00
Michal Privoznik
eb8e5e8774 Adapt to VIR_STRDUP and VIR_STRNDUP in src/util/vircgroup.c
This commit is separate due to unusual paradigm compared to the
most source files.
2013-05-24 10:10:03 +02:00
Michal Privoznik
b43bb98a31 virCgroupAddTaskStrController: s/-1/-ENOMEM/
Within whole vircgroup.c we 'return -errno', e.g. 'return -ENOMEM'.
However, in this specific function virCgroupAddTaskStrController
we weren't returning -ENOMEM but -1 despite fact that later in
the function we are returning one of errno values indeed.
2013-05-24 10:03:22 +02:00
Michal Privoznik
25a2d944df virNetDevTapCreate: Fail on systems not supporting IFF_MULTI_QUEUE
In my previous patches I enabled the IFF_MULTI_QUEUE flag every
time the user requested multiqueue TAP device. However, this
works only at runtime. During build time the flag may be
undeclared.
2013-05-22 18:32:27 +02:00
Michal Privoznik
1f24f68225 qemu: Adapt qemuBuildInterfaceCommandLine to to multiqueue net
In order to learn libvirt multiqueue several things must be done:

1) The '/dev/net/tun' device needs to be opened multiple times with
IFF_MULTI_QUEUE flag passed to ioctl(fd, TUNSETIFF, &ifr);

2) Similarly, '/dev/vhost-net' must be opened as many times as in 1)
in order to keep 1:1 ratio recommended by qemu and kernel folks.

3) The command line construction code needs to switch from 'fd=X' to
'fds=X:Y:...:Z' and from 'vhostfd=X' to 'vhostfds=X:Y:...:Z'.

4) The monitor handling code needs to learn to pass multiple FDs.
2013-05-22 17:24:27 +02:00
Eric Blake
83e4c77547 cgroup: be robust against cgroup movement races
https://bugzilla.redhat.com/show_bug.cgi?id=965169 documents a
problem starting domains when cgroups are enabled; I was able
to reliably reproduce the race about 5% of the time when I added
hooks to domain startup by 3 seconds (as that seemed to be about
the length of time that qemu created and then closed a temporary
thread, probably related to aio handling of initially opening
a disk image).  The problem has existed since we introduced
virCgroupMoveTask in commit 9102829 (v0.10.0).

There are some inherent TOCTTOU races when moving tasks between
kernel cgroups, precisely because threads can be created or
completed in the window between when we read a thread id from the
source and when we write to the destination.  As the goal of
virCgroupMoveTask is merely to move ALL tasks into the new
cgroup, it is sufficient to iterate until no more threads are
being created in the old group, and ignoring any threads that
die before we can move them.

It would be nicer to start the threads in the right cgroup to
begin with, but by default, all child threads are created in
the same cgroup as their parent, and we don't want vcpu child
threads in the emulator cgroup, so I don't see any good way
of avoiding the move.  It would also be nice if the kernel were
to implement something like rename() as a way to atomically move
a group of threads from one cgroup to another, instead of forcing
a window where we have to read and parse the source, then format
and write back into the destination.

* src/util/vircgroup.c (virCgroupAddTaskStrController): Ignore
ESRCH, because a thread ended between read and write attempts.
(virCgroupMoveTask): Loop until all threads have moved.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-21 11:33:56 -06:00
Osier Yang
3fcc1df2f8 src/utils: Remove the whitespace before ";" 2013-05-21 23:41:45 +08:00
Daniel P. Berrange
ec04914c47 Add missing c-ctype.h to virfile.c
The virfile.c file uses c_isalpha on Win32 platforms, so must
include c-ctype.h

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-17 17:09:29 +01:00
Guannan Ren
6459af6a43 qemu: report useful error failling to destroy domain gracefully
Resolves:https://bugzilla.redhat.com/show_bug.cgi?id=927620

 #kill -STOP `pidof qemu-kvm`
 #virsh destroy $guest --graceful
 error: Failed to destroy domain testVM
 error: An error occurred, but the cause is unknown

With --graceful, SIGTERM always is emitted to kill driver
process, but it won't success till burning out waiting time
in case of process being stopped.
But domain destroy without --graceful can work, SIGKILL will
be emitted to the stopped process after 10 secs which always
kills a process even one that is currently stopped.
So report an error after burning out waiting time in this case.
2013-05-17 22:22:46 +08:00
Daniel P. Berrange
c2cf5f1c2a Fix failure to detect missing cgroup partitions
Change bbe97ae968 caused the
QEMU driver to ignore ENOENT errors from cgroups, in order
to cope with missing /proc/cgroups. This is not good though
because many other things can cause ENOENT and should not
be ignored. The callers expect to see ENXIO when cgroups
are not present, so adjust the code to report that errno
when /proc/cgroups is missing

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-17 10:25:15 +01:00
Osier Yang
28d3ad952f utils: Add a helper to get the device name that sg device mapped to
E.g.

% sg_map
/dev/sg0  /dev/sda
/dev/sg1  /dev/sr0

What the helper gets for /dev/sg0 is /dev/sda, it will be used by
later patch.
2013-05-16 23:50:00 +08:00
Jiri Denemark
c431f06587 util: Fix build without devmapper
stdlib.h header file needed for getenv was only transitively included
through libdevmapper.h.
2013-05-16 12:15:38 +02:00
Martin Kletzander
84d9142495 Fix invalid argument reference in virnetdev.h
Commit ccff335f added ATTRIBUTE_NONNULL for an attribute which is not
a pointer and made files including virnetdev.h not compilable, so fix
that.
2013-05-14 18:27:51 +02:00
Eric Blake
547a7c778a json: support removing a value from an object
In an upcoming patch, I need the way to safely transfer a nested
virJSON object out of its parent container for independent use,
even after the parent is freed.

* src/util/virjson.h (virJSONValueObjectRemoveKey): New function.
(_virJSONObject, _virJSONArray): Use correct type.
* src/util/virjson.c (virJSONValueObjectRemoveKey): Implement it.
* src/libvirt_private.syms (virjson.h): Export it.
* tests/jsontest.c (mymain): Test it.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-13 15:15:54 -06:00
Gene Czarcinski
ccff335f83 Support for static routes on a virtual bridge
network: static route support for <network>

This patch adds the <route> subelement of <network> to define a static
route.  the address and prefix (or netmask) attribute identify the
destination network, and the gateway attribute specifies the next hop
address (which must be directly reachable from the containing
<network>) which is to receive the packets destined for
"address/(prefix|netmask)".

These attributes are translated into an "ip route add" command that is
executed when the network is started. The command used is of the
following form:

  ip route add <address>/<prefix> via <gateway> \
               dev <virbr-bridge> proto static metric <metric>

Tests are done to validate that the input data are correct.  For
example, for a static route ip definition, the address must be a
network address and not a host address.  Additional checks are added
to ensure that the specified gateway is directly reachable via this
network (i.e. that the gateway IP address is in the same subnet as one
of the IP's defined for the network).

prefix='0' is supported for both family='ipv4' address='0.0.0.0'
netmask='0.0.0.0' or prefix='0', and for family='ipv6' address='::',
prefix=0', although care should be taken to not override a desired
system default route.

Anytime an attempt is made to define a static route which *exactly*
duplicates an existing static route (for example, address=::,
prefix=0, metric=1), the following error message will be sent to
syslog:

    RTNETLINK answers: File exists

This can be overridden by decreasing the metric value for the route
that should be preferred, or increasing the metric for the route that
shouldn't be preferred (and is thus in place only in anticipation that
the preferred route may be removed in the future).  Caution should be
used when manipulating route metrics, especially for a default route.

Note: The use of the command-line interface should be replaced by
direct use of libnl so that error conditions can be handled better.  But,
that is being left as an exercise for another day.

Signed-off-by: Gene Czarcinski <gene@czarc.net>
Signed-off-by: Laine Stump <laine@laine.org>
2013-05-13 16:14:40 -04:00
Daniel P. Berrange
3407e3b3a2 Don't overwrite useful message when creating macvlan fails
Currently we report a bogus error message when macvlan
creation fails:

error: Failed to start domain migtest
error: operation failed: Unable to create macvlan device

With this removed, we see the real error:

error: Failed to start domain migtest
error: Unable to get index for interface p31p1: No such device

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 17:32:55 +01:00
Daniel P. Berrange
8845d8dfa3 Remove & ban use of select() for waiting for I/O
Use of the select() system call is inherantly dangerous since
applications will hit a buffer overrun if any FD number exceeds
the size of the select set size (typically 1024). Replace the
two uses of select() with poll() and use cfg.mk to ban any
future use of select().

NB: This changes the phyp driver so that it uses an infinite
timeout, instead of busy-waiting for 1ms at a time.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 17:32:43 +01:00
Jim Fehlig
bbe97ae968 Fix starting domains when kernel has no cgroups support
Found that I was unable to start existing domains after updating
to a kernel with no cgroups support

  # zgrep CGROUP /proc/config.gz
  # CONFIG_CGROUPS is not set
  # virsh start test
  error: Failed to start domain test
  error: Unable to initialize /machine cgroup: Cannot allocate memory

virCgroupPartitionNeedsEscaping() correctly returns errno (ENOENT) when
attempting to open /proc/cgroups on such a system, but it was being
dropped in virCgroupSetPartitionSuffix().

Change virCgroupSetPartitionSuffix() to propagate errors returned by
its callees.  Also check for ENOENT in qemuInitCgroup() when determining
if cgroups support is available.
2013-05-13 09:27:46 -06:00
Daniel P. Berrange
0ced83dcfb Escaping leading '.' in cgroup names
Escaping a leading '.' with '_' in the cgroup names

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 14:28:46 +01:00
Daniel P. Berrange
8aabd597b3 Add a helper API for setting up a NBD device with qemu-nbd
Add a virFileNBDDeviceAssociate method, which given a filename
will setup a NBD device, using qemu-nbd as the server.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 13:15:19 +01:00
Daniel P. Berrange
1eeff53d7d Fix error handling of readdir() in virFileLoopDeviceOpen
To correctly handle errors from readdir() you must set 'errno'
to zero before invoking it & check its value afterwards to
distinguish error from EOF.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-13 13:15:19 +01:00
Han Cheng
7486584c9f utils: util functions for scsi hostdev
This patch adds util functions for scsi hostdev.

Signed-off-by: Han Cheng <hanc.fnst@cn.fujitsu.com>
Signed-off-by: Osier Yang <jyang@redhat.com>
2013-05-13 18:40:50 +08:00
Osier Yang
b7ab719528 util: Honor the passed sysfs_prefix
The helper works for default sysfs_prefix, but for user specified
prefix, it doesn't work. (Detected when writing test cases. A later
patch will add the test cases for fc_host).
2013-05-13 17:19:54 +08:00
Osier Yang
1a59ae919d util: Update the comment for virGetFCHostNameByWWN
The returned result is something like "host5" acutally.
2013-05-13 17:18:52 +08:00
Osier Yang
c56c273be6 util: Change virIsCapable* to return bool
Function name with "aIsB" generally means its return value is
in Bi-state (true/false).
2013-05-13 17:17:26 +08:00
Osier Yang
b595588fef util: Don't miss the slash in constructed path
In case of the caller can pass a "prefix" (or "sysfs_prefix")
without the trailing slash, and Unix-Like system always eats
up the redundant "slash" in the filepath, let's add it explicitly.
2013-05-13 17:14:51 +08:00
Osier Yang
e106c0112a util: Fix regression introduced by commit 4360a09844
Which refactored the old code, and introduced new helper
virIsCapableVport, but the path for checking with access() is not
correctly constructed.
2013-05-13 17:12:55 +08:00
Osier Yang
b76284afb1 util: Fix regression of wwn reading
Introduced by commit 244ce462e2, which refactored the helper for wwn
reading, however, it forgot to change the old "strndup" and "sizeof(buf)",
"sizeof(buf)" operates on the fixed length array ("buf") in the old code,
but now "buf" is a pointer.

Before the fix:

% virsh nodedev-dumpxml scsi_host5
<device>
  <name>scsi_host5</name>
  <parent>pci_0000_04_00_1</parent>
  <capability type='scsi_host'>
    <host>5</host>
    <capability type='fc_host'>
      <wwnn>2001001b</wwnn>
      <wwpn>2101001b</wwpn>
      <fabric_wwn>2001000d</fabric_wwn>
    </capability>
  </capability>
</device>

With the fix:

% virsh nodedev-dumpxml scsi_host5
<device>
  <name>scsi_host5</name>
  <parent>pci_0000_04_00_1</parent>
  <capability type='scsi_host'>
    <host>5</host>
    <capability type='fc_host'>
      <wwnn>0x2001001b32a9da4e</wwnn>
      <wwpn>0x2101001b32a9da4e</wwpn>
      <fabric_wwn>0x2001000dec9877c1</fabric_wwn>
    </capability>
  </capability>
</device>
2013-05-13 17:10:59 +08:00
Eric Blake
d34ef01779 build: fix use of mmap
Commit bfe7721d introduced a regression, but only on platforms
like FreeBSD that lack posix_fallocate and where mmap serves as
a nice fallback for safezero.

util/virfile.c: In function 'safezero':
util/virfile.c:837: error: 'PROT_READ' undeclared (first use in this function)

* src/util/virutil.c (includes): Move use of <sys/mman.h>...
* src/util/virfile.c (includes): ...to the file that uses mmap.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-10 20:52:57 -06:00
Daniel P. Berrange
69c6a58a1d Add a virGetLastErrorMessage() function
Apps using libvirt will often have code like

   if (virXXXX() < 0) {
      virErrorPtr err = virGetLastError();
      fprintf(stderr, "Something failed: %s\n",
              err && err->message ? err->message :
              "unknown error");
      return -1;
   }

Checking for a NULL error object or message leads to very
verbose code. A virGetLastErrorMessage() helper from libvirt
can simplify this to

   if (virXXXX() < 0) {
      fprintf(stderr, "Something failed: %s\n",
              virGetLastErrorMessage());
      return -1;
   }

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-10 19:57:18 +01:00
Roman Bogorodskiy
95934171fb portability: fix virNetDevSetMAC and virNetDevExists on BSD
- provide virNetDevSetMAC() implementation based on SIOCSIFLLADDR
  ioctl.
- adjust virNetDevExists() to check for ENXIO error because
  FreeBSD throws it when device doesn't exist

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-10 11:13:21 -06:00
Laine Stump
bfe7721d50 util: move virFile* functions from virutil.c to virfile.c
These all existed before virfile.c was created, and for some reason
weren't moved.

This is mostly straightfoward, although the syntax rule prohibiting
write() had to be changed to have an exception for virfile.c instead
of virutil.c.

This movement pointed out that there is a function called
virBuildPath(), and another almost identical function called
virFileBuildPath(). They really should be a single function, which
I'll take care of as soon as I figure out what the arglist should look
like.
2013-05-10 13:09:30 -04:00
Laine Stump
a2c1bedbd8 util: fix virFileOpenAs return value and resulting error logs
This resolves:

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

The first problem was that virFileOpenAs was returning fd (-1) in one
of the error cases rather than ret (-errno), so the caller thought
that the error was EPERM rather than ENOENT.

The second problem was that some log messages in the general purpose
qemuOpenFile() function would always say "Failed to create" even if
the caller hadn't included O_CREAT (i.e. they were trying to open an
existing file).

This fixes virFileOpenAs to jump down to the error return (which
returns ret instead of fd) in the previously mentioned incorrect
failure case of virFileOpenAs(), removes all error logging from
virFileOpenAs() (since the callers report it), and modifies
qemuOpenFile to appropriately use "open" or "create" in its log
messages.

NB: I seriously considered removing logging from all callers of
virFileOpenAs(), but there is at least one case where the caller
doesn't want virFileOpenAs() to log any errors, because it's just
going to try again (qemuOpenFile()). We can't simply make a silent
variation of virFileOpenAs() though, because qemuOpenFile() can't make
the decision about whether or not it wants to retry until after
virFileOpenAs() has already returned an error code.

Likewise, I also considered changing virFileOpenAs() to return -1 with
errno set on return, and may still do that, but only as a separate
patch, as it obscures the intent of this patch too much.
2013-05-10 13:09:25 -04:00
Daniel P. Berrange
4a044d0256 Separate internal node suspend APIs from public API
The individual hypervisor drivers were directly referencing
APIs in virnodesuspend.c in their virDriverPtr struct. Separate
these methods, so there is always a wrapper in the hypervisor
driver. This allows the unused virConnectPtr args to be removed
from the virnodesuspend.c file. Again this will ensure that
ACL checks will only be performed on invocations that are
directly associated with public API usage.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:47:47 +01:00
Daniel P. Berrange
ead630319d Separate virGetHostname() API contract from driver APIs
Currently the virGetHostname() API has a bogus virConnectPtr
parameter. This is because virtualization drivers directly
reference this API in their virDriverPtr tables, tieing its
API design to the public virConnectGetHostname API design.

This also causes problems for access control checks since
these must only be done for invocations from the public
API, not internal invocation.

Remove the bogus virConnectPtr parameter, and make each
hypervisor driver provide a dedicated function for the
driver API impl. This will allow access control checks
to be easily inserted later.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:47:47 +01:00
Daniel P. Berrange
979e9c56a7 Include process start time when doing polkit checks
Since PIDs can be reused, polkit prefers to be given
a (PID,start time) pair. If given a PID on its own,
it will attempt to lookup the start time in /proc/pid/stat,
though this is subject to races.

It is safer if the client app resolves the PID start
time itself, because as long as the app has the client
socket open, the client PID won't be reused.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:47:45 +01:00
Daniel P. Berrange
b1d753fe40 Rename "security context" to "selinux context"
There are various methods named "virXXXXSecurityContext",
which are specific to SELinux. Rename them all to
"virXXXXSELinuxContext". They will still raise errors at
runtime if SELinux is not compiled in

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-05-08 10:21:01 +01:00
Eric Blake
6b74a9f5d9 string: make VIR_STRDUP easier to use
While reviewing proposed VIR_STRDUP conversions, I've already noticed
several places that do:

if (str && VIR_STRDUP(dest, str) < 0)

which can be simplified by allowing str to be NULL (something that
strdup() doesn't allow).  Meanwhile, code that wants to ensure a
non-NULL dest regardless of the source can check for <= 0.

Also, make it part of the VIR_STRDUP contract that macro arguments
are evaluated exactly once.

* src/util/virstring.h (VIR_STRDUP, VIR_STRDUP_QUIET, VIR_STRNDUP)
(VIR_STRNDUP_QUIET): Improve contract.
* src/util/virstring.c (virStrdup, virStrndup): Change return
conventions.
* docs/hacking.html.in: Document this.
* HACKING: Regenerate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-07 13:21:31 -06:00
Eric Blake
ddcfc5492a alloc: make VIR_APPEND_ELEMENT safer
VIR_APPEND_ELEMENT(array, size, elem) was not safe if the expression
for 'size' had side effects.  While no one in the current code base
was trying to pass side effects, we might as well be robust and
explicitly document our intentions.

* src/util/viralloc.c (virInsertElementsN): Add special case.
* src/util/viralloc.h (VIR_APPEND_ELEMENT): Use it.
(VIR_ALLOC, VIR_ALLOC_N, VIR_REALLOC_N, VIR_EXPAND_N)
(VIR_RESIZE_N, VIR_SHRINK_N, VIR_INSERT_ELEMENT)
(VIR_DELETE_ELEMENT, VIR_ALLOC_VAR, VIR_FREE): Document
which macros are safe in the presence of side effects.
* docs/hacking.html.in: Document this.
* HACKING: Regenerate.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-07 13:21:31 -06:00
Ján Tomko
dcea5a492f get rid of virBufferAsprintf where possible
Use virBufferAddLit or virBufferAddChar instead.
2013-05-07 17:38:58 +02:00
Michal Privoznik
c3abb5c459 virstring: Introduce VIR_STRDUP and VIR_STRNDUP
The code adaptation is not done right now, but in subsequent patches.
Hence I am not implementing syntax-check rule as it would break
compilation. Developers are strongly advised to use these new macros.
They are similar to VIR_ALLOC() logic: VIR_STRDUP(dst, src) returns zero
on success, -1 otherwise. In case you don't want to report OOM error,
use the _QUIET variant of a macro.
2013-05-05 12:08:54 +02:00
Eric Blake
22d12905e6 build: avoid non-portable cast of pthread_t
POSIX says pthread_t is opaque.  We can't guarantee if it is scaler
or a pointer, nor what size it is; and BSD differs from Linux.
We've also had reports of gcc complaining on attempts to cast it,
if we use a cast to the wrong type (for example, pointers have to be
cast to void* or intptr_t before being narrowed; while casting a
function return of scalar pthread_t to void* triggers a different
warning).

Give up on casts, and use unions to get at decent bits instead.  And
rather than futz around with figuring which 32 bits of a potentially
64-bit pointer are most likely to be unique, convert the rest of
the code base to use 64-bit values when using a debug id.

Based on a report by Guido Günther against kFreeBSD, but with a
fix that doesn't regress commit 4d970fd29 for FreeBSD.

* src/util/virthreadpthread.c (virThreadSelfID, virThreadID): Use
union to get at a decent bit representation of thread_t bits.
* src/util/virthread.h (virThreadSelfID, virThreadID): Alter
signature.
* src/util/virthreadwin32.c (virThreadSelfID, virThreadID):
Likewise.
* src/qemu/qemu_domain.h (qemuDomainJobObj): Alter type of owner.
* src/qemu/qemu_domain.c (qemuDomainObjTransferJob)
(qemuDomainObjSetJobPhase, qemuDomainObjReleaseAsyncJob)
(qemuDomainObjBeginNestedJob, qemuDomainObjBeginJobInternal): Fix
clients.
* src/util/virlog.c (virLogFormatString): Likewise.
* src/util/vireventpoll.c (virEventPollInterruptLocked):
Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-03 06:30:22 -06:00
Eric Blake
05f79a3894 build: fix mingw build of virprocess.c
Commit 776d49f4 added a static function that is only called
conditionally; leading to this compile error on mingw:

  CC       libvirt_util_la-virprocess.lo
../../src/util/virprocess.c:624:26: error: 'struct rlimit' declared inside parameter list [-Werror]
../../src/util/virprocess.c:624:26: error: its scope is only this definition or declaration, which is probably not what you want [-Werror]
../../src/util/virprocess.c:622:1: error: 'virProcessPrLimit' defined but not used [-Werror=unused-function]

* src/util/virprocess.c (virProcessPrLimit): Only declare
virProcessPrLimit when used.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 15:46:19 -06:00
Eric Blake
348ac06133 build: fix FreeBSD build
Commit 7c9a2d88 cleaned up too many headers; FreeBSD builds
failed due to:

util/virutil.c:556: warning: implicit declaration of function 'canonicalize_file_name'

(Not sure which Linux header leaked this declaration, but gnulib
only guarantees it in stdlib.h)

libvirt.c:956: warning: implicit declaration of function 'virGetUserConfigDirectory'

(Here, a build on Linux was picking up virutil.h indirectly via
one of the conditional driver headers, where that driver was not
being built on my FreeBSD setup)

* src/util/virutil.c (includes): Need <stdlib.h> for
canonicalize_file_name.
* src/libvirt.c (includes): Use "virutil.h" unconditionally,
rather than relying on conditional indirect inclusion.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 15:41:21 -06:00
Eric Blake
25ae3d3015 build: avoid useless virAsprintf
virAsprintf(&foo, "%s", bar) is wasteful compared to
foo = strdup(bar) (or eventually, VIR_STRDUP(foo, bar),
but one thing at a time...).

Noticed while reviewing Laine's attempt to clean up broken
qemu:///session.

* cfg.mk (sc_prohibit_asprintf): Enhance rule.
* src/esx/esx_storage_backend_vmfs.c
(esxStorageBackendVMFSVolumeLookupByKey): Fix offender.
* src/network/bridge_driver.c (networkStateInitialize): Likewise.
* src/nwfilter/nwfilter_dhcpsnoop.c (virNWFilterSnoopDHCPOpen):
Likewise.
* src/storage/storage_backend_sheepdog.c
(virStorageBackendSheepdogRefreshVol): Likewise.
* src/util/vircgroup.c (virCgroupAddTaskStrController): Likewise.
* src/util/virdnsmasq.c (addnhostsAdd): Likewise.
* src/xen/block_stats.c (xenLinuxDomainDeviceID): Likewise.
* src/xen/xen_driver.c (xenUnifiedConnectOpen): Likewise.
* tools/virsh.c (vshGetTypedParamValue): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-05-02 13:35:26 -06:00
Michal Privoznik
7c9a2d88cd virutil: Move string related functions to virstring.c
The source code base needs to be adapted as well. Some files
include virutil.h just for the string related functions (here,
the include is substituted to match the new file), some include
virutil.h without any need (here, the include is removed), and
some require both.
2013-05-02 16:56:55 +02:00
Guido Günther
ca75c44310 virInitctlRequest: unbreak make syntax check
introduced by dcf97846d5

To trigger this cppi needs to be installed.
2013-05-02 10:20:33 +02:00
Guido Günther
a1365d7351 virInitctlRequest: unbreak make syntax check
introduced by dcf97846d5
2013-05-02 09:22:41 +02:00
Guido Günther
dcf97846d5 virInitctlRequest: Don't hardcode 384 bytes size
When MAXHOSTNAMELEN is set we have to take it's value into account.
Otherwise the build fails on kFreeBSD (FreeBSD kernel and GNU userland)
2013-05-02 08:18:42 +02:00
Laine Stump
e482693b24 pci: autolearn name of stub driver, remove from arglist
virPCIDeviceReattach and virPCIDeviceUnbindFromStub (called by
virPCIDeviceReattach) had previously required the name of the stub
driver as input. This is unnecessary, because the name of the driver
the device is currently bound to can be found by looking at the link:

  /sys/bus/pci/dddd:bb:ss.ff/driver

Instead of requiring that the name of the expected stub driver name
and only unbinding if that one name is matched, we no longer take a
driver name in the arglist for either of these
functions. virPCIDeviceUnbindFromStub just compares the name of the
currently bound driver to a list of "well known" stubs (right now
contains "pci-stub" and "vfio-pci" for qemu, and "pciback" for xen),
and only performs the unbind if it's one of those devices.

This allows virsh nodedevice-reattach to work properly across a
libvirtd restart, and fixes a couple of cases where we were
erroneously still hard-coding "pci-stub" as the drive name.

For some unknown reason, virPCIDeviceReattach had been calling
modprobe on the stub driver prior to unbinding the device. This was
problematic because we no longer know the name of the stub driver in
that function. However, it is pointless to probe for the stub driver
at that time anyway - because the device is bound to the stub driver,
we are guaranteed that it is already loaded, and so that call to
modprobe has been removed.
2013-05-02 02:09:29 -04:00
Eric Blake
7fecc8e36f build: fix cygwin build in virnetdev
On cygwin, compilation failed because SIOCSIFHWADDR is undefined.

* src/util/virnetdev.c (virNetDevSetMAC): Cygwin can query but not
set mac address.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-30 15:16:22 -06:00
Roman Bogorodskiy
5295e35f58 portability: handle ifreq differences in virnetdev
FreeBSD (and maybe other BSDs) have different member
names in struct ifreq when compared to Linux, such as:

 - uses ifr_data instead of ifr_newname for setting
   interface names
 - uses ifr_index instead of ifr_ifindex for interface
   index

Also, add a check for SIOCGIFHWADDR for virNetDevValidateConfig().

Use AF_LOCAL if AF_PACKET is not available.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-30 09:42:22 -06:00
Eric Blake
b376dea91f build: mark conditionally unused variables
These fixes solve a compilation failure on FreeBSD:

util/virnetdevtap.c: In function 'virNetDevTapGetName':
util/virnetdevtap.c:56: warning: unused parameter 'tapfd' [-Wunused-parameter]
util/virnetdevtap.c:56: warning: unused parameter 'ifname' [-Wunused-parameter]

* src/util/virnetdevtap.c (virNetDevTapGetName): Add attributes
when TUNGETIFF is not present.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-04-30 08:21:26 -06:00
Paolo Bonzini
740d98a17d virnetdevtap: add virNetDevTapGetName
This will be used on a tap file descriptor returned by the bridge helper
to populate the <target> element, because the helper does not provide
the interface name.

Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
2013-04-26 15:37:15 -06:00
Laine Stump
776d49f492 util: new virCommandSetMax(MemLock|Processes|Files)
This patch adds two sets of functions:

1) lower level virProcessSet*() functions that will immediately set
the RLIMIT_MEMLOCK. RLIMIT_NPROC, or RLIMIT_NOFILE of either the
current process (using setrlimit()) or any other process (using
prlimit()). "current process" is indicated by passing a 0 for pid.

2) functions for virCommand* that will setup a virCommand object to
set those limits at a later time just after it has forked a new
process, but before it execs the new program.

configure.ac has prlimit and setrlimit added to the list of functions
to check for, and the low level functions log an "unsupported" error)
on platforms that don't support those functions.
2013-04-26 10:23:46 -04:00
Daniel P. Berrange
f3662737b1 Do proper escaping of cgroup resource partitions
If a user cgroup name begins with "cgroup.", "_" or with any of
the controllers from /proc/cgroups followed by a dot, then they
need to be prefixed with a single underscore. eg if there is
an object "cpu.service", then this would end up as "_cpu.service"
in the cgroup filesystem tree, however, "waldo.service" would
stay "waldo.service", at least as long as nobody comes up with
a cgroup controller called "waldo".

Since we require a '.XXXX' suffix on all partitions, there is
no scope for clashing with the kernel 'tasks' and 'release_agent'
files.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-26 13:52:02 +01:00
Daniel P. Berrange
9ddfe7eea6 Ensure all cgroup partitions have a suffix of ".partition"
If the partition named passed in the XML does not already have
a suffix, ensure it gets a '.partition' added to each component.
The exceptions are /machine, /user and /system which do not need
to have a suffix, since they are fixed partitions at the top
level.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-04-26 13:52:02 +01:00