Commit Graph

2630 Commits

Author SHA1 Message Date
Christian Loehle
e7aa45055c document virCommandRunRegex function
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-11-24 08:23:29 +01:00
Andrea Bolognani
a6a5ac9650 process: Log when limiting the amount of locked memory
This can be useful for debugging.
2015-11-20 10:25:14 +01:00
Joao Martins
b52779b30c util: add virDiskNameParse to handle disk and partition idx
Introduce a new helper function "virDiskNameParse" which extends
virDiskNameToIndex but handling both disk index and partition index.
Also rework virDiskNameToIndex to be based on virDiskNameParse.
A test is also added for this function testing both valid and
invalid disk names.

Signed-off-by: Joao Martins <joao.m.martins@oracle.com>
2015-11-18 13:48:38 -07:00
Richard Weinberger
867f34a683 virSetUIDGID: Don't leak supplementary groups
The LXC driver uses virSetUIDGID() to become UID/GID 0.
It passes an empty groups list to virSetUIDGID()
to get rid of all supplementary groups from the host side.
But virSetUIDGID() calls setgroups() only if the supplied list
is larger than 0.
This leads to a container root with unrelated supplementary groups.
In most cases this issue is unoticed as libvirtd runs as UID/GID 0
without any supplementary groups.

Signed-off-by: Richard Weinberger <richard@nod.at>
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2015-11-18 11:41:12 +00:00
Stefan Berger
5ed7afa9de tpm: adapt sysfs cancel path for new TPM driver
This patch addresses BZ 1244895.

Adapt the sysfs TPM command cancel path for the TPM driver that
does not use a miscdevice anymore since Linux 4.0. Support old
and new paths and check their availability.

Add a mockup for the test cases to avoid the testing for
availability of the cancel path.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2015-11-17 20:52:13 -05:00
Chen Hanxiao
e340013ea8 util: remove unnecessary needSize
Use toadd->use directly.

Signed-off-by: Chen Hanxiao <chenhanxiao@gmail.com>
2015-11-16 11:03:04 +01:00
John Ferlan
edc88e2084 virnetdev: Use virNetDevSetupControl in virNetDevSendEthtoolIoctl
Use virNetDevSetupControl instead of open coding using socket(AF_LOCAL...)
and clearing virIfreq.

By using virNetDevSetupControl, the socket is then opened using
AF_PACKET which requires being privileged (effectively root) in
order to complete successfully.  Since that's now a requirement,
then the ioctl(SIOCETHTOOL) should not fail with EPERM, thus it
is removed from the filtered listed of failure codes.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-11-06 11:20:17 -05:00
John Ferlan
d0a3a1ff92 virnetdev: Check for root in virNetDevGetFeatures
Since the SIOCETHTOOL ioctl only works for privileged daemons, if called
when not root, then virNetDevGetFeatures will VIR_DEBUG a message and
return 0 as if the functions were not available for the architecture.
This effectively returns an empty bitmap indicating no features available.

Introduced by commit id 'c9027d8f4'

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-11-06 11:19:07 -05:00
John Ferlan
9efab5da16 virnetdev: Fix function comments for virNetDevGetFeatures
In commit id 'c9027d8f4' when updating the posted patch to generate
a bitmap instead of an array of named feature bits, adjustment of
the args was missed
2015-11-06 10:53:57 -05:00
John Ferlan
301bd80194 virnetdev: Document reasons for ignoring some SIOCETHTOOL errno values
Recently reverted commit id '6f2a0198' showed a need to add extra
comments when dealing with filtering of potential "non-issues".

Scanning through upstream patch postings indicates early on the
reasons for the filtering of specific ioctl failures were provided;
however, when converted from causing an error to VIR_DEBUG's the
reasons were missing. A future read/change of the code incorrectly
assumed they could or should be removed.
2015-11-06 10:50:55 -05:00
Daniel P. Berrange
a3f63b853c Revert "utils: Remove the logging of errors from virNetDevSendEthtoolIoctl"
This reverts commit 6f2a0198e9.

This commit removed error reporting from virNetDevSendEthtoolIoctl
pushing responsibility onto the callers. This is wrong, however,
since virNetDevSendEthtoolIoctl calls virNetDevSetupControl
which can still report errors. So as a result virNetDevSendEthtoolIoctl
may or may not report errors depending on which bit of it fails, and as
a result callers now overwrite some errors.

It also introduced a regression causing unprivileged libvirtd to
spew error messages to the console due to inability to query the
NIC features, an error which was previously ignored.

virNetDevSetupControlFull:148 : Cannot open network interface control socket: Operation not permitted
virNetDevFeatureAvailable:3062 : Cannot get device wlp3s0 flags: Operation not permitted
virNetDevSetupControlFull:148 : Cannot open network interface control socket: Operation not permitted
virNetDevFeatureAvailable:3062 : Cannot get device wlp3s0 flags: Operation not permitted
virNetDevSetupControlFull:148 : Cannot open network interface control socket: Operation not permitted
virNetDevFeatureAvailable:3062 : Cannot get device wlp3s0 flags: Operation not permitted
virNetDevSetupControlFull:148 : Cannot open network interface control socket: Operation not permitted
virNetDevFeatureAvailable:3062 : Cannot get device wlp3s0 flags: Operation not permitted

Looking back at the original posting I see no explanation of why
thsi refactoring was needed, so reverting the clearly broken
error reporting logic looks like the best option.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2015-11-06 09:34:52 -05:00
John Ferlan
01db247941 network: Remove extraneous ATTRIBUTE_NONNULL for virNetDevWaitDadFinish
Commit id '0f7436ca' added virNetDevWaitDadFinish using ATTRIBUTE_NONNULL
for both arguments, although one is a non-null argument. A Coverity build
balks at that.
2015-11-04 17:47:42 -05:00
John Ferlan
4ee1b16a54 virnetdev: Check correct return value for virNetDevFeatureAvailable
Rather than "if (virNetDevFeatureAvailable(ifname, &cmd))" change the
success criteria to "if (virNetDevFeatureAvailable(ifname, &cmd) == 1)".

The called helper returns -1 on failure, 0 on not found, and 1 on found.
Thus a failure was setting bits.

Introduced by commit ac3ed20 which changed the helper's return
values without adjusting its callers

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-11-04 14:28:06 -05:00
Jiri Denemark
e4ee043636 Remove new lines from log messages
VIR_DEBUG and VIR_WARN will automatically add a new line to the message,
having "\n" at the end or at the beginning of the message results in
empty lines.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-11-04 13:09:35 +01:00
Laine Stump
ac339206bf util: set max wait for IPv6 DAD to 20 seconds
This was originally set to 5 seconds, but times of 5.5 to 7 seconds
were experienced. Since it's an arbitrary number intended to prevent
an infinite hang, having it a bit too high won't hurt anything, and 20
seconds looks to be adequate (i.e. I think/hope we don't need to make
it tunable in libvirtd.conf)
2015-10-29 15:49:38 -04:00
Luyao Huang
d41a64a194 util: set error if DAD is not finished
If DAD not finished in 5 seconds, user will get an
unknown error like this:

 # virsh net-start ipv6
 error: Failed to start network ipv6
 error: An error occurred, but the cause is unknown

Call virReportError to set an error.

Signed-off-by: Luyao Huang <lhuang@redhat.com>
2015-10-29 14:19:56 -04:00
Roman Bogorodskiy
2589ca3019 Fix virNetDevWaitDadFinish stub
Build on non-Linux fails because the virNetDevWaitDadFinish() stub
has unused parameters. Fix by adding appropriate ATTRIBUTE_UNUSED
for these parameters.

Pushing under build-breaker rule.
2015-10-29 07:20:16 +03:00
Maxim Perevedentsev
0f7436ca54 network: wait for DAD to finish for bridge IPv6 addresses
commit db488c79 assumed that dnsmasq would complete IPv6 DAD before
daemonizing, but in reality it doesn't wait, which creates problems
when libvirt's bridge driver sets the matching "dummy tap device" to
IFF_DOWN prior to DAD completing.

This patch waits for DAD completion by periodically polling the kernel
using netlink to check whether there are any IPv6 addresses assigned
to bridge which have a 'tentative' state (if there are any in this
state, then DAD hasn't yet finished). After DAD is finished, execution
continues. To avoid an endless hang in case something was wrong with
the kernel's DAD, we wait a maximum of 5 seconds.
2015-10-28 21:48:04 -04:00
Maxim Perevedentsev
131e7245a8 netlink: add support for multi-part netlink messages.
Such messages do not have NLMSG_ERROR or NLMSG_DONE type
but they are valid responses. We test 'multi-partness'
by looking for NLM_F_MULTI flag.
2015-10-28 21:47:58 -04:00
Pino Toscano
10fe8d0668 util: implement virProcessGetStartTime on GNU/kFreeBSD
Use the virProcessGetStartTime implementation also when only the kernel
is FreeBSD, such as on GNU/kFreeBSD.
2015-10-27 19:08:03 +03:00
Andrea Bolognani
2ab52f4af7 hostdev: Rename virHostdevUpdateDomainActiveDevices()
The new name, virHostdevUpdateActiveDomainDevices(), follows the
same naming conventions used by the rest of the module.

No functional changes.
2015-10-26 13:50:35 +01:00
Luyao Huang
4f9e61f648 util: Produce friendlier error message to user
Commit id '1c24cfe9' added error messages for virNumaSetPagePoolSize;
however, virNumaGetHugePageInfo also uses virNumaGetHugePageInfoPath
in order to build the path, but it never checked upon return if
the built path exists which could lead to an error message as follows:

$ virsh freepages 0 1
error: Failed to open file
    '/sys/devices/system/node/node0/hugepages/hugepages-1kB/free_hugepages':
    No such file or directory

Rather than add the same message for the other two callers, adjust
the virNumaGetHugePageInfoPath in order not only build the path, but
also check if the built path exists.  If the path does not exist,
then generate the error message and return failure.

Signed-off-by: Luyao Huang <lhuang@redhat.com>
2015-10-21 16:19:42 -04:00
Luyao Huang
e802d7efb4 util: Adjust error paths for virNumaSetPagePoolSize
Commit id '1c24cfe9' added new checks and error messaes for failure
scenarios. Let's adjust those error messages to after the call to
virNumaGetHugePageInfoPath in order to provide a more specific error
message depending on node and page_size

After this patch:
 # virsh allocpages --pagesize 2047 --pagecount 1 --cellno 0
 error: operation failed: page size 2047 is not available on node 0

 # virsh allocpages --pagesize 2047 --pagecount 1
 error: operation failed: page size 2047 is not available

Signed-off-by: Luyao Huang <lhuang@redhat.com>
2015-10-21 16:19:42 -04:00
Luyao Huang
deb8c66d44 util: split the virNumaGetHugePageInfoPath into separate function
https://bugzilla.redhat.com/show_bug.cgi?id=1265114

Refactor helper virNumaGetHugePageInfoPath to handle returning a directory
path when passed a page_size of 0 and suffix == NULL into a new helper
virNumaGetHugePageInfoDir which will only be called when a directory
path is expected to be returned. This solves the issue where the helper
was called with page_size == 0 expecting a file path in return, but
instead got a directory path and failed in virFileReadAll with:

    error : virFileReadAll:1358 : Failed to read file
                '/sys/devices/system/node/node0/hugepages/': Is a directory

Since virNumaGetPages API expects to return a directory by passing
page_size == 0 and suffix == NULL, it will now call the new helper.
Callers to virNumaGetHugePageInfoPath expect to return a file path
which could then be used in the call to virFileReadAll.

Signed-off-by: Luyao Huang <lhuang@redhat.com>
2015-10-21 16:19:42 -04:00
Ishmanpreet Kaur Khera
32cee5b2f0 Avoid using !STREQ and !STRNEQ
We have macros for both positive and negative string matching.
Therefore there is no need to use !STREQ or !STRNEQ. At the same
time as we are dropping this, new syntax-check rule is
introduced to make sure we won't introduce it again.

Signed-off-by: Ishmanpreet Kaur Khera <khera.ishman@gmail.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-10-21 15:03:35 +02:00
Dominik Perpeet
9bf1cef737 docs: event impl. registration before hypervisor connection
Event implementations need to be registered before a connection to the
Hypervisor is opened, otherwise event handling can be impaired (e.g.
delayed messages). This fact is referenced in an e-mail [1], but should
also be noted in the documentation of the registration functions.

[1] https://www.redhat.com/archives/libvirt-users/2014-April/msg00011.html
2015-10-15 19:50:58 -04:00
John Ferlan
21eb897241 storage: On error rmdir created directory in virDirCreate[NoFork]
After a successful creation of a directory, if some other call results
in returning a failure, let's remove the directory we created to
prevent another round trip or confusion in the caller. In particular, this
function can be called during a storage backend buildVol, so in order
to ensure that caller doesn't need to distinguish between failed create
or some other failure after create, just remove the directory we created.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-10-13 18:03:55 -04:00
John Ferlan
695562154f storage: On error unlink created file in virFileOpen{As|Forked}
After a successful creation of a file, if some other call results
in returning a failure, let's unlink the file we created to prevent
another round trip or confusion in the caller. In particular, this
function can be called during a storage backend buildVol, so in order
to ensure that caller doesn't need to distinguish between failed create
or some other failure after create, just remove the volume we created.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-10-13 18:03:55 -04:00
Michal Privoznik
4f77c48cba virJSONValueArraySize: return ssize_t
The internal representation of a JSON array counts the items in
size_t. However, for some reason, when asking for the count it's
reported as int. Firstly, we need the function to return a signed
type as it's returning -1 on an error. But, not every system has
integer the same size as size_t. Therefore, lets return ssize_t.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-10-09 15:25:08 +02:00
John Ferlan
cb19cff468 virfile: Fix error path for forked virFileRemove
As it turns out the caller in this case expects a return < 0 for failure
and to get/use "errno" rather than using the negative of returned status.
Again different than the create path.

If someone "deleted" a file from the pool without using virsh vol-delete,
then the unlink/rmdir would return an error (-1) and set errno to ENOENT.
The caller checks errno for ENOENT when determining whether to throw an
error message indicating the failure.  Without the change, the error
message is:

error: Failed to delete vol $vol
error: cannot unlink file '/$pathto/$vol': Success

This patch thus allows the fork path to follow the non-fork path
where unlink/rmdir return -1 and errno.
2015-10-05 08:14:44 -04:00
John Ferlan
c6b32d6801 virfile: Add extra check for direct delete in virFileRemove
Unlike create options, if the file to be removed is already in the
pool, then the uid/gid will come from the pool. If it's the same as the
currently running process, then just do the unlink/rmdir directly
rather than going through the fork processing unnecessarily
2015-10-05 08:14:44 -04:00
Guido Günther
fd00f0e6c7 Use daemon log facility for journald
otherwise messages end up in /var/log/kern.log if journald forwards to
syslog.

Reference: https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=799633
2015-09-25 16:22:39 +02:00
Martin Kletzander
d772a70faa Use VIR_DIV_UP macro where possible
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-09-23 11:45:59 +02:00
John Ferlan
9ced219a68 virfile: Use virProcessWait in virDirCreate
Rather than inlining the code, use the common API.
2015-09-21 08:24:16 -04:00
John Ferlan
b01c68d9bc virfile: Use virProcessWait in virFileUnlink
Rather than inlining the code, use the common API.
2015-09-21 08:24:16 -04:00
John Ferlan
89b9b6d35a virfile: Use virProcessWait in virFileOpenForked
Rather than inlining the code, use the common API
2015-09-21 08:24:16 -04:00
John Ferlan
1b046a6837 virfile: Rename virFileUnlink to virFileRemove
Similar to commit id '35847860', it's possible to attempt to create
a 'netfs' directory in an NFS root-squash environment which will cause
the 'vol-delete' command to fail.  It's also possible error paths from
the 'vol-create' would result in an error to remove a created directory
if the permissions were incorrect (and disallowed root access).

Thus rename the virFileUnlink to be virFileRemove to match the C API
functionality, adjust the code to following using rmdir or unlink
depending on the path type, and then use/call it for the VIR_STORAGE_VOL_DIR
2015-09-21 08:24:16 -04:00
John Ferlan
b421a70811 virfile: Check for existence of dir in virFileDeleteTree
Commit id 'f1f68ca33' added code to remove the directory paths for
auto-generated sockets, but that code could be called before the
paths were created resulting in generating error messages from
virFileDeleteTree indicating that the file doesn't exist.

Rather than "enforce" all callers to make the non-NULL and existence
checks, modify the virFileDeleteTree API to silently ignore NULL on
input and non-existent directory trees.
2015-09-16 11:23:16 -04:00
Andrea Bolognani
17c4d2a17f util: Add space before comment end marker
This allows the Wikipedia link to be recognized correctly by eg.
gnome-terminal's Open Link and Copy Link Address features.
2015-09-14 11:32:44 +02:00
Martin Kletzander
26893ac6e0 util: Add win32 version of virFileUnlink
Commit 35847860f6 Added the virFileUnlink function, but failed to add
a version for mingw build, causing the following error:

  Cannot export virFileUnlink: symbol not defined

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-09-08 11:54:53 +02:00
John Ferlan
c78e1cfcb5 util: Avoid Coverity FORWARD_NULL
Coverity claims it could be possible to call virDBusTypeStackFree with
*stack == NULL and although the two API's that call it don't appear to
allow that - I suppose it's better to be safe than sorry
2015-09-04 15:19:04 -04:00
John Ferlan
53caf99db6 virfile: Avoid Coverity IDENTICAL_BRANCHES error
In virFileNBDDeviceFindUnused if virFileNBDDeviceIsBusy returns 0,
then both branches jumped to cleanup, so just use ignore_value
since the function returns NULL or some memory and the caller
handles the error.
2015-09-04 15:19:04 -04:00
Laine Stump
46cf0cefa0 util: don't use netlink to save/set mac for macvtap+passthrough+802.1Qbh
Before libvirt sets the MAC address of the physdev (the physical
ethernet device) linked to a macvtap passthrough device, it always
saves the previous MAC address to restore when the guest is finished
(following a "leave nothing behind" policy). For a long time it
accomplished the save/restore with a combination of
ioctl(SIOCGIFHWADDR) and ioctl(SIOCSIFHWADDR), but in commit cbfe38c
(first in libvirt 1.2.15) this was changed to use netlink RTM_GETLINK
and RTM_SETLINK commands sent to the Physical Function (PF) of any
device that was detected to be a Virtual Function (VF).

We later found out that this caused problems with any devices using
the Cisco enic driver (e.g. vmfex cards) because the enic driver
hasn't implemented the function that is called to gather the
information in the IFLA_VFINFO_LIST attribute of RTM_GETLINK
(ndo_get_vf_config() for those keeping score), so we would never get
back a useful response.

In an ideal world, all drivers would implement all functions, but it
turns out that in this case we can work around this omission without
any bad side effects - since all macvtap passthrough <interface>
definitions pointing to a physdev that uses the enic driver *must*
have a <virtualport type='802.1Qbh'>, and since no other type of
ethernet devices use 802.1Qbh, libvirt can change its behavior in this
case to use the old-style.  ioctl(SIOC[GS]IFHWADDR).  That's what this
patch does.

Resolves:  https://bugzilla.redhat.com/show_bug.cgi?id=1257004
2015-09-03 11:38:17 -04:00
Laine Stump
3ce08fab84 util: make virNetDev(Replace|Restore)MacAddress public functions
These functions were made static as a part of commit cbfe38c since
they were no longer called from outside virnetdev.c. We once again
need to call them from another file, so this patch makes them once
again public.
2015-09-03 11:38:09 -04:00
John Ferlan
35847860f6 virfile: Introduce virFileUnlink
In an NFS root-squashed environment the 'vol-delete' command will fail to
'unlink' the target volume since it was created under a different uid:gid.

This code continues the concepts introduced in virFileOpenForked and
virDirCreate[NoFork] with respect to running the unlink command under
the uid/gid of the child. Unlike the other two, don't retry on EACCES
(that's why we're here doing this now).
2015-09-02 08:59:53 -04:00
John Ferlan
1fafc1bc1c virfile: Add error for root squash change mode failure
This will only be seen when debugging, but in order to help determine
whether a virFileOpenForceOwnerMode failed during an NFS root-squash
volume/file creation, add an error message from the child.
2015-09-02 08:59:53 -04:00
Laine Stump
97d26e470d util: fallback to ioctl(SIOCBRDELBR) if netlink RTM_DELLINK fails
commit 09778e09 switched from using ioctl(SIOCBRDELBR) for bridge
device deletion to using a netlink RTM_DELLINK message, which is the
more modern way to delete a bridge (and also doesn't require the
bridge to be ~IFF_UP to succeed). However, although older kernels
(e.g. 2.6.32, in RHEL6/CentOS6) support deleting *some* link types
with RTM_NEWLINK, they don't support deleting bridges, and there is no
compile-time way to figure this out.

This patch moves the body of the SIOCBRDELBR version of
virNetDevBridgeDelete() into a static function, calls the new function
from the original, and also calls the new function from the
RTM_DELLINK version if the RTM_DELLINK message generates an EOPNOTSUPP
error. Since RTM_DELLINK is done from the subordinate function
virNetlinkDelLink, which is also called for other purposes (deleting a
macvtap interface), a function pointer called "fallback" has been
added to the arglist of virNetlinkDelLink() - if that arg != NULL, the
provided function will be called when (and only when) RTM_DELLINK
fails with EOPNOTSUPP.

Resolves:  https://bugzilla.redhat.com/show_bug.cgi?id=1252780 (part 2)
2015-08-28 16:39:30 -04:00
Laine Stump
66dcb40937 util: fallback to ioctl(SIOCBRADDBR) if netlink RTM_NEWLINK fails
commit fc7b23db switched from using ioctl(SIOCBRADDBR) for bridge
creation to using a netlink RTM_NEWLINK message with IFLA_INFO_KIND =
"bridge", which is the more modern way to create a bridge. However,
although older kernels (e.g. 2.6.32, in RHEL6/CentOS6) support
creating *some* link types with RTM_NEWLINK, they don't support
creating bridges, and there is no compile-time way to figure this out
(since the "type" isn't an enum, but rather a character string).

This patch moves the body of the SIOCBRADDBR version of
virNetDevBridgeCreate() into a static function, calls the new function
from the original, and also calls the new function from the
RTM_NEWLINK version if the RTM_NEWLINK message generates an EOPNOTSUPP
error.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1252780
2015-08-28 16:19:05 -04:00
Michal Privoznik
ea0486873e util: Allow virProcessSetNamespaces() to have sparse FD list
So far, the virProcessSetNamespaces() takes an array of FDs that
it tries to set namespace on. However, in the very next commit
this array may be sparse, having some -1's in it. Teach the
function to cope with that.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-27 15:05:51 +02:00
Moshe Levi
6f2a0198e9 utils: Remove the logging of errors from virNetDevSendEthtoolIoctl
This patch remove the logging of errors of ioctl api and instead
let the caller to choose what errors to log
2015-08-26 17:11:27 -04:00
Laine Stump
108d591b11 hostdev: skip ACS check when using VFIO for device assignment
The ACS checks are meaningless when using the more modern VFIO driver
for device assignment since VFIO has its own more complete and exact
checks, but I didn't realize that when I added support for VFIO. This
patch eliminates the ACS check when preparing PCI devices for
assignment if VFIO is being used.

This resolves:

  https://bugzilla.redhat.com/show_bug.cgi?id=1256486
2015-08-26 14:07:01 -04:00
Roman Bogorodskiy
46550cde0f util: fix build without cgroup
Commit 89c509a0 added getters for cgroup block device I/O throttling,
however stub versions of these functions have not matching function
prototypes that result in compilation fail on platforms not supporting
cgroup.

Fix build by correcting prototypes of the stubbed functions.

Pushing under build-breaker rule.
2015-08-20 09:42:56 +03:00
Cao jin
d0fbaf16cc virconf: correct code formatting
Signed-off-by: Cao jin <caoj.fnst@cn.fujitsu.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-08-20 01:41:28 +02:00
Cao jin
4cbeb48713 virConfWalk: fix the inconsistent name
Fix inconsistency between function description and actual
parameter name.

Signed-off-by: Cao jin <caoj.fnst@cn.fujitsu.com>
2015-08-20 01:03:42 +02:00
Martin Kletzander
89c509a0c1 util: Add getters for cgroup block device I/O throttling
Since now they were not needed, but I sense they will be in a short
while.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-08-18 16:25:16 -07:00
Martin Kletzander
ea9db906fc util: Add virCgroupGetBlockDevString
This function translates device paths to "major:minor " string, and all
virCgroupSetBlkioDevice* functions are modified to use it.  It's a
cleanup with no functional change.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-08-18 16:16:38 -07:00
Martin Kletzander
1fe69c4656 util: Add virStringGetFirstWithPrefix
That function takes string list and returns first string in that list
that starts with the @prefix parameter with that prefix being skipped as
the caller knows what it starts with (also for easier manipulation in
future).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-08-18 16:16:37 -07:00
Cao jin
d5d710a199 virconf: fix the inconsistent name
Fix inconsistency between function description and actual
parameter name in virConfGetValue/virConfSetValue.

Signed-off-by: Cao jin <caoj.fnst@cn.fujitsu.com>
2015-08-18 19:42:49 +02:00
Eric Blake
0a617b53d4 build: fix mingw build
Ever since commit e44b0269, 64-bit mingw compilation fails with:

../../src/util/virprocess.c: In function 'virProcessGetPids':
../../src/util/virprocess.c:628:50: error: passing argument 4 of 'virStrToLong_i' from incompatible pointer type [-Werror=incompatible-pointer-types]
         if (virStrToLong_i(ent->d_name, NULL, 10, &tmp_pid) < 0)
                                                  ^
In file included from ../../src/util/virprocess.c:59:0:
../../src/util/virstring.h:53:5: note: expected 'int *' but argument is of type 'pid_t * {aka long long int *}'
 int virStrToLong_i(char const *s,
     ^
cc1: all warnings being treated as errors

Although mingw won't be using this function, it does compile the
file, and the fix is relatively simple.

* src/util/virprocess.c (virProcessGetPids): Don't assume pid_t
fits in int.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-08-17 16:03:40 -07:00
Michal Privoznik
1dc2587224 virHashAddEntry: Report error on duplicate key
If this function fails, the error message is reported only in
some cases (e.g. OOM), but in some it's not (e.g. duplicate key).
This fact is painful and we should either not report error at all
or report the error in all possible cases. I vote for the latter.
Unfortunately, since the key may be an arbitrary value (not
necessarily a string) we can't report it in the error message.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-17 23:34:08 +02:00
Michal Privoznik
890676d26b virHashAddOrUpdateEntry: Turn @new_name into void *
In 9190f0b0 we've tried to fix an OOM. And boy, was that fix
successful. But back then, the hash table implementation worked
strictly over string keys, which is not the case anymore. Hash
table have this function keyCopy() which returns void *.
Therefore a local variable that is temporarily holding the
intermediate return value from that function should be void *
too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-17 23:25:01 +02:00
Erik Skultety
834c5720e4 tools: Introduce new client generic module vsh
In order to share as much virsh' logic as possible with upcomming
virt-admin client we need to split virsh logic into virsh specific and
client generic features.

Since majority of virsh methods should be generic enough to be used by
other clients, it's much easier to rename virsh specific data to virshX
than doing this vice versa. It moved generic virsh commands (including info
and opts structures) to generic module vsh.c.

Besides renaming methods and structures, this patch also involves introduction
of a client specific control structure being referenced as private data in the
original control structure, introduction of a new global vsh Initializer,
which currently doesn't do much, but there is a potential for added
functionality in the future.
Lastly it introduced client hooks which are especially necessary during
client connecting phase.
2015-08-14 15:45:44 +02:00
Laine Stump
bfaaa2b681 util: don't overwrite stack when getting ethtool gfeatures
This fixes the crash described here:

 https://www.redhat.com/archives/libvir-list/2015-August/msg00162.html

In short, we were calling ioctl(SIOCETHTOOL) pointing to a too-short
object that was a local on the stack, resulting in the memory past the
end of the object being overwritten. This was because the struct used
by the ETHTOOL_GFEATURES command of SIOCETHTOOL ends with a 0-length
array, but we were telling ethtool that it could use 2 elements on the
array.

The fix is to allocate the necessary memory with VIR_ALLOC_VAR(),
including the extra length needed for a 2 element array at the end.
2015-08-11 15:29:14 -04:00
Michal Privoznik
45090449c4 virNetDevBandwidthUpdateRate: turn class_id into integer
This is no functional change. It's just that later in the series we
will need to pass class_id as an integer.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-11 16:10:32 +02:00
Michal Privoznik
327bc16a05 virNetDevParseMcast: Avoid magic constant
There is no guarantee that an enum start it mapped onto a value
of zero. However, we are guaranteed that enum items are
consecutive integers. Moreover, it's a pity to define an enum to
avoid using magical constants but then using them anyway.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-11 16:10:32 +02:00
Laine Stump
a6f9af8292 network: validate network NAT range
This patch modifies virSocketAddrGetRange() to function properly when
the containing network/prefix of the address range isn't known, for
example in the case of the NAT range of a virtual network (since it is
a range of addresses on the *host*, not within the network itself). We
then take advantage of this new functionality to validate the NAT
range of a virtual network.

Extra test cases are also added to verify that virSocketAddrGetRange()
works properly in both positive and negative cases when the network
pointer is NULL.

This is the *real* fix for:

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

Commits 1e334a and 48e8b9 had earlier been pushed as fixes for that
bug, but I had neglected to read the report carefully, so instead of
fixing validation for the NAT range, I had fixed validation for the
DHCP range. sigh.
2015-08-10 13:06:56 -04:00
Peter Krempa
8dc2725925 qemu: Fix reporting of physical capacity for block devices
Qemu reports physical size 0 for block devices. As 15fa84acbb
changed the behavior of qemuDomainGetBlockInfo to just query the monitor
this created a regression since we didn't report the size correctly any
more.

This patch adds code to refresh the physical size of a block device by
opening it and seeking to the end and uses it both in
qemuDomainGetBlockInfo and also in qemuDomainGetStatsOneBlock that was
broken since it was introduced in this respect.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1250982
2015-08-07 13:28:50 +02:00
Shivaprasad G Bhat
e3810db34f Allow vfio hotplug of a device to the domain which owns the iommu
The commit 7e72de4 didn't consider the hotplug scenarios. The patch addresses
the hotplug case whereby if atleast one of the pci function is owned by a
guest, the hotplug of other functions/devices in the same iommu group to the
same guest goes through successfully.

Signed-off-by: Shivaprasad G Bhat <sbhat@linux.vnet.ibm.com>
2015-08-06 17:55:03 +02:00
Cédric Bosdonnat
e5e8406e9c Fix syntax-check: missing "%s" 2015-07-30 11:10:48 +02:00
Cédric Bosdonnat
0aedcbd37c Load nbd module before running qemu-nbd
So far qemu-nbd is run even if the nbd kernel module isn't loaded. This
leads to errors when the user starts his lxc container while libvirt
could easily load the nbd module automatically.
2015-07-30 09:55:37 +02:00
John Ferlan
136f17efd1 nodeinfo: Check for SYSFS_INFINIBAND_DIR before open
Commit id 'ac3ed2085' causes 'virsh nodedev-list --cap net' to fail
on any system without SYSFS_INFINIBAND_DIR (/sys/class/infiniband).

Rather than assume it's there and fail on the attempt to open the
non-existent directory, check if it's there - if not, return
success and move on. Also fix caller to check < 0 upon return.

As reported by Suren Hajyan <shajyan@redhat.com> from run of unit tests
2015-07-24 09:41:06 -04:00
Roman Bogorodskiy
830344d6e7 netdev: fix build on FreeBSD
Commit ac3ed20 breaks build on FreeBSD with:

  CC       util/libvirt_util_la-virnetdev.lo
util/virnetdev.c:2967:1: error: unused function 'virNetDevRDMAFeature' [-Werror,-Wunused-function]
virNetDevRDMAFeature(const char *ifname,
^

So hide virNetDevRDMAFeature function under the #ifdef 'SIOCETHTOOL'
and 'HAVE_STRUCT_IFREQ' section.

Pushed under the build breaker rule.
2015-07-22 18:37:00 +03:00
Peter Krempa
88f6c007c3 cgroup: Drop resource partition from virSystemdMakeScopeName
The scope name, even according to our docs is
"machine-$DRIVER\x2d$VMNAME.scope" virSystemdMakeScopeName would use the
resource partition name instead of "machine-" if it was specified thus
creating invalid scope paths.

This makes libvirt drop cgroups for a VM that uses custom resource
partition upon reconnecting since the detected scope name would not
match the expected name generated by virSystemdMakeScopeName.

The error is exposed by the following log entry:

debug : virCgroupValidateMachineGroup:302 : Name 'machine-qemu\x2dtestvm.scope' for controller 'cpu' does not match 'testvm', 'testvm.libvirt-qemu' or 'machine-test-qemu\x2dtestvm.scope'

for a "/machine/test" resource and "testvm" vm.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1238570
2015-07-22 07:12:56 +02:00
Moshe Levi
ac3ed2085f nodedev: add RDMA and tx-udp_tnl-segmentation NIC capabilities
Adding functionality to libvirt that will allow
it query the interface for the availability of RDMA and
tx-udp_tnl-segmentation Offloading NIC capabilities

Here is an example of the feature XML definition:

<device>
<name>net_eth4_90_e2_ba_5e_a5_45</name>
  <path>/sys/devices/pci0000:00/0000:00:03.0/0000:08:00.1/net/eth4</path>
  <parent>pci_0000_08_00_1</parent>
  <capability type='net'>
    <interface>eth4</interface>
    <address>90:e2:ba:5e:a5:45</address>
    <link speed='10000' state='up'/>
    <feature name='rx'/>
    <feature name='tx'/>
    <feature name='sg'/>
    <feature name='tso'/>
    <feature name='gso'/>
    <feature name='gro'/>
    <feature name='rxvlan'/>
    <feature name='txvlan'/>
    <feature name='rxhash'/>
    <feature name='rdma'/>
    <feature name='txudptnl'/>
    <capability type='80203'/>
  </capability>
</device>
2015-07-21 07:08:35 -04:00
John Ferlan
51281dcb90 nodeinfo: Add sysfs_prefix to nodeGetPresentCPUBitmap
Add the sysfs_prefix argument to the call to allow for setting the
path for tests to something other than SYSFS_SYSTEM_PATH.
2015-07-13 15:59:32 -04:00
Jiri Denemark
44c42b564d qemu: Don't report false error from MigrateFinish
virDomainMigrateFinish* APIs were unfortunately designed to return the
pointer to the domain on destination and NULL on error. This looks OK in
normal cases but the same API is also called when we know migration
failed and thus we expect Finish to return NULL even if it actually did
all it was supposed to do without any error. The call is defined to
return nonnull domain pointer over RPC, which means returning NULL will
always result in an error being send. If this was not in fact an error,
the API itself wouldn't set anything to the thread local virError, which
makes the RPC layer come up with it's own "Library function returned
error but did not set virError" error.

This is quite confusing and also hard to detect by the caller. This
patch adds a special error code which can be used to check that Finish
successfully aborted migration.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-07-10 11:47:13 +02:00
Jiri Denemark
9d0a2af6c2 Introduce virErrorCopyNew
A helper function for copying error objects.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-07-10 11:47:13 +02:00
Jiri Denemark
a7c22a1f29 Introduce virHashAtomic
This is a self-locking wrapper around virHashTable. Only a limited set
of APIs are implemented now (the ones which are used in the following
patch) as more can be added on demand.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-07-10 11:47:13 +02:00
Peter Krempa
e8c5f61e91 util: bitmap: Don't alloc overly large binary bitmaps
Optimize the virBitmap to array-of-char bitmap conversion by skipping
trailing zero bytes.

This also fixes a regression when requesting iothread information from a
live VM since after commit 825df8c315 the
bitmap returned from virProcessGetAffinity is too big to be formatted
properly via RPC. A user would get the following error:

error: Unable to get domain IOThreads information
error: Unable to encode message payload

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1238589
2015-07-08 11:01:33 +02:00
John Ferlan
2c05841246 util: Avoid Coverity FORWARD_NULL
Avoid a false positive since Coverity find a path in virResizeN which
could return 0 prior to the allocation of memory and thus flags a
possible NULL dereference. Instead allocate the output buffer based
on 'nparams' and only fill it partially if need be - shouldn't be too
much a waste of space. Quicker than multiple VIR_RESIZE_N calls or
two loops of STREQ's sandwiched around a single VIR_ALLOC_N using
'n' matches from a first loop to generate the 'n' addresses to return

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-07-02 06:30:27 -04:00
John Ferlan
c50c664de5 util: Resolve Coverity FORWARD_NULL
Convert virPCIDriverDir to return the buffer allocated (or not) and make the
appropriate check in the caller.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-07-01 12:15:16 -04:00
John Ferlan
e3939e86ba util: Resolve Coverity FORWARD_NULL
Convert virPCIDriverFile to return the buffer allocated (or not) and make the
appropriate check in the caller.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-07-01 12:15:12 -04:00
John Ferlan
d7ddb4c2f0 util: Resolve Coverity FORWARD_NULL
Convert virPCIFile to return the buffer allocated (or not) and make the
appropriate check in the caller.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-07-01 12:15:08 -04:00
Peter Krempa
14062e6fe5 internal: Introduce virCheckNonEmptyStringArgGoto and reuse it
The helper makes sure that strings passed to APIs are non-NULL and
non-empty. This allows to drop some inlined checks where it does not
make sense.
2015-06-26 16:05:10 +02:00
Eric Blake
cb005533ab json: enhance parser test
We already enable the parser option to detect invalid UTF-8, but
didn't test it.  Also, JSON states that behavior of an object
with a duplicated key is undefined; we chose to reject it, but
were not testing it.

With the enhanced tests in place, we can simplify yajl2
initialization by relying on parser defaults being sane.

* src/util/virjson.c (virJSONValueFromString): Simplify.
* tests/jsontest.c (mymain): Test more bad usage.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-25 09:11:15 +02:00
Eric Blake
7e191fd939 json: even stricter trailing garbage detection
Since older yajl ignores trailing garbage, a client can cause
problems by intentionally ending the wrapper array early. Since
we already track nesting, it's not too much harder to reject
invalid nesting pops.

* src/util/virjson. (_virJSONParser): Add field.
(virJSONValueFromString): Set witness.
(virJSONParserHandleEndArray): Use it to catch abuse.
* tests/jsontest.c (mymain): Test it.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-25 09:11:15 +02:00
Eric Blake
7cd991b74c json: reject trailing garbage
Yajl 2 has a nice feature that it can be configured whether to
allow multiple JSON objects parsed from a single stream, defaulting
to off.  And yajl 1.0.12 at least provided a way to tell if all
input bytes were parsed, or if trailing bytes remained after a
valid JSON object was parsed.  But we target RHEL 6 yajl 1.0.7,
which has neither of these.  So fake it by always parsing '[...]'
instead, so that trailing garbage either trips up the array parse,
or is easily detected when unwrapping the result.

* src/util/virjson.c (virJSONValueFromString): With older json,
wrap text to avoid trailing garbage.
* tests/jsontest.c (mymain): Add tests for this.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-25 09:11:15 +02:00
Eric Blake
54dbba5bc3 json: reject javascript comments
We have been allowing javascript style comments in JSON ever
since commit 9428f2c (v0.7.5), but qemu doesn't send them, and
they are not strict JSON.  Reject them for now; if we can later
prove that it is worthwhile, we can reinstate it at that point
(or even make it conditional, by adding a bool parameter to
the libvirt entry point).

* src/util/virjson.c (virJSONValueFromString): Don't enable
comment parsing.
* tests/jsontest.c (mymain): Test it.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-25 09:11:15 +02:00
Eric Blake
f2acaebd40 json: cope with older yajl semantics
Commit ceb496e5 fails on RHEL 6, with yajl 1.0.7, because that
version of yajl returns yajl_status_insufficient_data when the
parser is waiting for the rest of a token (this enum value was
dropped in yajl 2, so we have to wrap it).  It also exposes a
problem where older yajl silently ignores trailing garbage after
a successful parse, so this patch works around that by changing
the testsuite.  Another more invasive patch can add tighter
semantics to json parsing, but this is sufficient for a minimal
clean backport.

While touching this, fix up our error message cleanup. Yajl
documents that error messages produced by yajl_get_error()
MUST be cleaned with yajl_free_error(); this is certainly
true if we were to pass non-NULL allocator callbacks during
yajl_alloc(), but probably harmless in our usage of passing
NULL.  But better safe than sorry.

* src/util/virjson.c (virJSONValueFromString): Allow different
error code.  Use canonical cleanup of error message.
(VIR_YAJL_STATUS_OK): New helper macro.
* tests/jsontest.c (mymain): Wrap text to avoid difference in
trailing garbage handling

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-25 09:11:15 +02:00
Eric Farman
22b8a61756 Convert SCSI logical unit from unsigned int to unsigned long long
The SCSI Architecture Model defines a logical unit address
as 64-bits in length, so change the field accordingly so
that the entire value could be stored.

Signed-off-by: Eric Farman <farman@linux.vnet.ibm.com>
2015-06-22 16:03:33 -04:00
Eric Farman
3b7983ad6d Print SCSI address attributes bus, target, unit as unsigned integer
The address elements are all unsigned integers, so we should
use the appropriate print directive when printing it.

Signed-off-by: Eric Farman <farman@linux.vnet.ibm.com>
2015-06-22 16:03:33 -04:00
Eric Blake
58fd670335 json: make it easier to type-check when getting from object
While working in qemu_monitor_json, I repeatedly found myself
getting a value then checking if it was an object.  Add some
wrappers to make this task easier.

* src/util/virjson.c (virJSONValueObjectGetByType)
(virJSONValueObjectGetObject, virJSONValueObjectGetArray): New
functions.
(virJSONValueObjectGetString, virJSONValueObjectGetNumberInt)
(virJSONValueObjectGetNumberUint)
(virJSONValueObjectGetNumberLong)
(virJSONValueObjectGetNumberUlong)
(virJSONValueObjectGetNumberDouble)
(virJSONValueObjectGetBoolean): Simplify.
(virJSONValueIsNull): Change return type.
* src/util/virjson.h: Reflect changes.
* src/libvirt_private.syms (virjson.h): Export them.
* tests/jsontest.c (testJSONLookup): New test.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-22 10:38:21 -06:00
Eric Blake
ceb496e5f0 json: fully parse input string
I was adding a JSON test, and was shocked to find out our parser
treated the input string of "1" as invalid JSON.  It turns out
that YAJL specifically documents that it buffers input, and that
if the last input read could be a prefix to a longer token, then
you have to explicitly tell the parser that the buffer has ended
before that token will be processed.

It doesn't help that yajl 2 renamed the function from what it was
in yajl 1.

* src/util/virjson.c (virJSONValueFromString): Complete parse, in
case buffer ends in possible token prefix.
* tests/jsontest.c (mymain): Expose the problem.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-06-22 10:38:21 -06:00
Pavel Boldin
5eb03b6ea0 util: add virTypedParamsAddStringList
The `virTypedParamsAddStringList' function provides interface to add a
NULL-terminated array of string values as a multi-value to the params.

Signed-off-by: Pavel Boldin <pboldin@mirantis.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-18 16:46:09 +02:00
Pavel Boldin
952907f540 util: virTypedParams{Filter,GetStringList}
Add multikey API:

 * virTypedParamsFilter that filters all the parameters with specified name.
 * virTypedParamsGetStringList that returns a list with all the values for
   specified name and string type.

Signed-off-by: Pavel Boldin <pboldin@mirantis.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-18 16:46:09 +02:00
Pavel Boldin
e9ef856520 util: multi-value parameters in virTypedParamsAdd*
Allow multi-value parameters to be build using virTypedParamsAdd*
functions by removing check for duplicates.

Signed-off-by: Pavel Boldin <pboldin@mirantis.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-18 16:46:09 +02:00
Pavel Boldin
a5250449de util: multi-value virTypedParameter
The `virTypedParamsValidate' function now can be instructed to allow
multiple entries for some of the keys. For this flag the type with
the `VIR_TYPED_PARAM_MULTIPLE' flag.

Add unit tests for this new behaviour.

Signed-off-by: Pavel Boldin <pboldin@mirantis.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-18 16:46:09 +02:00
Michal Privoznik
a9a27e602c virSysinfo: Introduce SMBIOS type 2 support
https://bugzilla.redhat.com/show_bug.cgi?id=1220527

This type of information defines attributes of a system
baseboard. With one exception: board type is yet not implemented
in qemu so it's not introduced here either.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-18 10:10:26 +02:00
Erik Skultety
4e6ee877d4 virfile: virDirCreate: Insert blank lines to assure slightly better readability 2015-06-16 16:26:20 +02:00
Erik Skultety
e9478d9a8b util: virfile: Fix 'unknown cause' error if NFS mount point creation fails
This happens if user requires creation of a directory with specified
UID/GID permissions. To accomplish this, we use fork approach and
set particular UID/GID permissions in child process. However, child
process doesn't have a valid descriptor to a logfile (this is prohibited
explicitly) and since parent process doesn't handle negative exit codes from
child in any way, 'uknown cause' error is returned to the user.

Commit 92d9114e tweaked the way we handle child errors when using fork
approach to set specific permissions (features originally introduced
by 98f6f381). The same logic should be used to create directories with
specified permissions as well.

https://bugzilla.redhat.com/show_bug.cgi?id=1230137
2015-06-16 16:26:20 +02:00
Erik Skultety
fdcb057a28 util: virDirCreate: Child now exits with positive errno-code
Previous patch of this series proposed a fix to virDirCreate, so that parent
process reports an error if child process failed its task.
However our logic still permits the child to exit with negative errno followed
by a check of the status on the parent side using WEXITSTATUS which, being
POSIX compliant, takes the lower 8 bits of the exit code and returns is to
the caller. However, by taking 8 bits from a negative exit code
(two's complement) the status value we read and append to stream is
'2^8 - abs(original exit code)' which doesn't quite reflect the real cause when
compared to the meaning of errno values.
2015-06-16 16:26:20 +02:00
John Ferlan
ad5fd9b87b util: Fix Coverity RESOURCE_LEAK
Commit id 'e44b0269c9' in advertently checked !dir before calling closedir
2015-06-16 09:15:10 -04:00
Martin Kletzander
653acbfd62 Add admin error domain
Just the addition of VIR_FROM_ADMIN to the enum of error domains.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-06-16 13:46:20 +02:00
Cédric Bosdonnat
e44b0269c9 Add virProcessGetPids to get all tasks of a process
This function gets all the PIDs listed in /proc/PID/task. This will be
needed at least to move all qmeu-nbd tasks to the container cgroup.
2015-06-16 12:38:03 +02:00
Michal Privoznik
c1dff918c9 virsysinfo: s/system/sysdef/
A variable can't be named system, obviously. Well, it can if the
compiler is new enough to distinguish a variable named system and a
function call system(). And some older systems, don't have wise
compiler.

  CC     util/libvirt_util_la-virsysinfo.lo
cc1: warnings being treated as errors
../../src/util/virsysinfo.c: In function 'virSysinfoParseSystem':
../../src/util/virsysinfo.c:649: error: declaration of 'system' shadows a global declaration [-Wshadow]
/usr/include/stdlib.h:717: error: shadowed declaration is here [-Wshadow]
make[3]: *** [util/libvirt_util_la-virsysinfo.lo] Error 1

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-12 17:43:38 +02:00
Michal Privoznik
0b92974c15 virSysinfoDef: Exempt SYSTEM variables
Move all the system_* fields into a separate struct. Not only this
simplifies the code a bit it also helps us to identify whether BIOS
info is present. We don't have to check all the four variables for
being not-NULL, but we can just check the pointer to the struct.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-12 10:42:39 +02:00
Michal Privoznik
3f9cae18fe virSysinfoDef: Exempt BIOS variables
Move all the bios_* fields into a separate struct. Not only this
simplifies the code a bit it also helps us to identify whether BIOS
info is present. We don't have to check all the four variables for
being not-NULL, but we can just check the pointer to the struct.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-12 10:42:34 +02:00
Martin Kletzander
d9a610f90c util: add virJSONValueCopy
Faster version of virJSONValueFromString(virJSONValueToString()).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-06-11 15:39:30 +02:00
Peter Krempa
b0d2e31c5f util: Make virProcessGetAffinity more readable and fix coverity warning
Store the cpu count in an intermediate variable and reuse it rather than
caluclating the index.

Additionally add a coverity silencing comment.
2015-06-11 13:59:28 +02:00
Michal Privoznik
1c24cfe9d8 virNumaSetPagePoolSize: Produce friendlier error message
https://bugzilla.redhat.com/show_bug.cgi?id=1224587

The function takes two important arguments (among many others): @node
and @page_size. From these two a path under /sys is constructed. The
path is then used to read and write the desired size of huge pages
pool. However, if the path does not exists due to either @node or
@page_size having nonexistent value (e.g. there's no such NUMA node or
no page size like -2), an cryptic error message is produced:

  virsh # allocpages --pagesize 2049 --pagecount 8 --cellno -2
  error: Failed to open file '/sys/devices/system/node/node-2/hugepages/hugepages-2049kB/nr_hugepages': No such file or directory

Add two more checks to catch this and therefore produce much more
friendlier error messages.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-06-10 17:27:16 +02:00
Shivaprasad G Bhat
310c98d0c4 network: escape quotes for dsmasq conf contents
dnsmasq conf file contents needs to have quotes escaped for it to
work.  Because of this, the network-create/start for a network with
quotes in the name fails. The patch escapes strings for the entries
that go into the conf file.

Signed-off-by: Shivaprasad G Bhat <sbhat@linux.vnet.ibm.com>
2015-06-09 13:56:00 -04:00
Roman Bogorodskiy
5ceb34eea0 util: process: fix build on FreeBSD
Commit 825df8c3 refactored virProcess{Set,Get}Affinity routines,
however broke BSD implementation because of the incorrect variable
name. Fix build by using a proper variable name.

Pushing as trivial and build break fix.
2015-06-08 11:27:39 +04:00
Peter Krempa
679576cf8c util: Properly return error from virGetUserID and virGetGroupID stubs
The stubs for the two functions that are compiled on platforms that
don't have HAVE_GETPWUID_R and friends defined do not return error but
report an error message. The calling code then assumes that the @uid or
@gid arguments were filled, which is not the case in the stubs.
2015-06-08 09:32:24 +02:00
Lubomir Rintel
81b19ce46a virnetdev: fix moving of 802.11 phys
There was a couple of problems with the style fixes applied to the original
patch:

1.) virFileReadAllQuiet comparison was incorrectly parenthesized when moved
into a condition, causing the len to be set to the result of comparison. This,
together with the removed underflow check would underflow the phy buffer.

2.) The logic was broken. Failure to call "ip" would abort the function, thus
the "iw" branch would never be reached.

This aims to fix the issues and work around possible style complains :)

Signed-off-by: Lubomir Rintel <lkundrak@v3.sk>
2015-06-03 18:05:23 +02:00
Peter Krempa
825df8c315 util: process: Refactor and fix virProcessSetAffinity
Refactor the function to return the bitmap instead of an integer and the
inner workings so that they make more sense.

This patch also fixes possible segfault on old systems that was
introduced by commit:

commit f1a43a8e41
Author: Hu Tao <hutao@cn.fujitsu.com>
Date:   Fri Sep 14 15:46:59 2012 +0800

    use virBitmap to store cpu affinity info
2015-06-03 14:20:25 +02:00
Martin Kletzander
99cc11b924 util: Clear output broadcast address before filling it in
Since commit 55ace7c478, the sockettest
fails without VIR_TEST_DEBUG set.  The problem is found by test number
42 (co-incidence?), which tests range '192.168.122.1' -
'192.168.122.255' in network '192.168.122.0/24'.  That is supposed to
fail because the end address is equal to the broadcast address.

When comparing these two in 'virSocketAddrEqual(end, &broadcast)',
there is a check for sin_addr as well as for sin_port.  That port,
however, is different when we do not enable test debugging.  With the
testing enabled, the port is 0 (correctly initialized), but without that
it has a random number there.  And that's because the structure is not
initialized anywhere.

By zeroing the structure before filling in the info, we make sure we
return only the address and not any information that was not requested.
And the test work once again.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-06-03 12:54:32 +02:00
Peter Krempa
65c61e5030 util: Add macro to overflow check integer assignments
Add a macro that will allow to simplify overflow checks and make them
more universal in case data types change.
2015-06-03 09:42:08 +02:00
Peter Krempa
02a6c73f27 util: bitmap: Add virBitmapToDataBuf that does not allocate the buffer
Since some functions can be optimized by reusing the buffers that they
already have instead of allocating and copying new ones, lets split
virBitmapToData to two functions where one only converts the data and
the second one is a wrapper that allocates the buffer if necessary.
2015-06-03 09:42:07 +02:00
Laine Stump
55ace7c478 util: report all address range errors in virSocketAddrGetRange()
There are now many more reasons that virSocketAddrGetRange() could
fail, so it is much more informative to report the error there instead
of in the caller. (one of the two callers was previously assuming
success, which is almost surely safe based on the parsing that has
already happened to the config by that time, but it still is nicer to
account for an error "just in case")

Part of fix for: https://bugzilla.redhat.com/show_bug.cgi?id=985653
2015-06-02 12:40:07 -04:00
Laine Stump
1e334a0a00 network: validate DHCP ranges are completely within defined network
virSocketAddrGetRange() has been updated to take the network address
and prefix, and now checks that both the start and end of the range
are within that network, thus validating that the entire range of
addresses is in the network. For IPv4, it also checks that ranges to
not start with the "network address" of the subnet, nor end with the
broadcast address of the subnet (this check doesn't apply to IPv6,
since IPv6 doesn't have a broadcast or network address)

Negative tests have been added to the network update and socket tests
to verify that bad ranges properly generate an error.

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=985653
2015-06-02 12:40:07 -04:00
Peter Krempa
f88750b931 util: process: @pid in virProcessSetAffinity's BSD impl is not unused 2015-06-02 08:38:12 +02:00
Zhang Bo
39d0396f39 util: make it more robust to calculate timeout value
When we change system clock to years ago, a certain CPU may use up 100% cputime.
The reason is that in function virEventPollCalculateTimeout(), we assign the
unsigned long long result to an INT variable,
        *timeout = then - now; // timeout is INT, and then/now are long long
        if (*timeout < 0)
            *timeout = 0;
there's a chance that variable @then minus variable @now may be a very large number
that overflows INT value expression, then *timeout will be negative and be assigned to 0.
Next the 'poll' in function virEventPollRunOnce() will get into an 'endless' while loop there.
thus, the cpu that virEventPollRunOnce() thread runs on will go up to 100%.

Although as we discussed before in https://www.redhat.com/archives/libvir-list/2015-May/msg00400.html
it should be prohibited to set-time while other applications are running, but it does
seems to have no harm to make the codes more robust.

Signed-off-by: Wang Yufei <james.wangyufei@huawei.com>
Signed-off-by: Zhang Bo <oscar.zhangbo@huawei.com>
2015-05-27 16:59:18 +02:00
Luyao Huang
e14cdeb44f util: improve the sysinfo element XML format
If the <sysinfo type='smbios'...> ends up not formatting any sub-elements,
then rather than formatting as:

  <sysinfo type='smbios'>
  </sysinfo>

Just format it more cleanly as:

  <sysinfo type='smbios'/>

Signed-off-by: Luyao Huang <lhuang@redhat.com>
2015-05-26 19:57:15 -04:00
Cole Robinson
db1140f117 storage: fs: Only force directory permissions if required
Only set directory permissions at pool build time, if:

- User explicitly requested a mode via the XML
- The directory needs to be created
- We need to do the crazy NFS root-squash workaround

This allows qemu:///session to call build on an existing directory
like /tmp.
2015-05-25 20:52:57 -04:00
Laine Stump
a9c53462fb util: better error message after failure to initialize firewall backend
If the firewalld backend wasn't available and libvirt decides to try
setting up a "direct" backend, it checks for the presence of iptables,
ip6tables, and ebtables. If they are not found, a message like this is logged:

  error : virFirewallValidateBackend:193 : direct firewall backend
          requested, but /usr/sbin/ip6tables is not available:
          No such file or directory

But then at a later time if an attempt is made to use the virFirewall
API, failure will be indicated with:

  error : virFirewallApply:936 : out of memory

This patch changes virFirewallApply to first check if a firewall
backend hadn't been successfully setup, and logs a slightly more
informative message in that case:

  error : virFirewallApply:940 : internal error:
          Failed to initialize a valid firewall backend

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1223876
2015-05-22 10:15:05 -04:00
Laine Stump
474523fa2c netdev: fail when setting up an SRIOV VF if PF is offline
If an SRIOV PF is offline, the kernel won't complain if you set the
mac address and vlan tag for a VF via this PF, and it will even let
you assign the VF to a guest using PCI device assignment or macvtap
passthrough. But in this case (the PF isn't online), the device won't
be usable in the guest.

Silently setting the PF online would solve the connectivity problem,
but as pointed out by Dan Berrange, when an interface is set online
with no associated config, the kernel will by default turn on IPv6
autoconf, which could create unexpected security problems for the
host. For this reason, this patch instead logs an error and fails the
operation.

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=893738

Originally filed against RHEL6, but present in every version of
libvirt until today.
2015-05-22 10:12:39 -04:00
Michal Privoznik
85128e2962 sysinfo: Fix reports on ARM
Due to a kernel commit (b4b8f770e), cpuinfo format has changed on
ARMs. Firstly, 'Processor: ...' may not be reported, it's
replaced by 'model name: ...'. Secondly, the "Processor" string
may occur in CPU name, e.g. 'ARMv7 Processor rev 5 (v7l)'.
Therefore, we must firstly look for 'model name' and then for
'Processor' if not found.
Moreover, lines in the cpuinfo file are shuffled, so we better
not manipulate the pointer to start of internal buffer as we may
lost some info.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-05-21 18:13:18 +02:00
Peter Krempa
a5c2d1988e util: Avoid shadow of 'ulong' in virMemoryMaxValue
Old compilers whine:
src/util/virutil.c: In function 'virMemoryMaxValue':
src/util/virutil.c:2612: error: declaration of 'ulong' shadows a global declaration [-Wshadow]
/usr/include/sys/types.h:151: error: shadowed declaration is here [-Wshadow]

s/ulong/capped/ to work around the problem
2015-05-21 16:52:01 +02:00
Jiri Denemark
6cc5c33eb5 threadpool: Switch to detached threads
Using joinable threads does not help anything, but it can lead to memory
leaks.

When a worker thread exits, it decreases nWorkers or nPrioWorkers and
once both nWorkers and nPrioWorkers are zero (i.e., the last worker is
gone), quit_cond is signaled. When freeing the pool we first tell all
threads to die and then we are waiting for both nWorkers and
nPrioWorkers to become zero. At this point we already know all threads
are gone. So the only reason for calling virThreadJoin of all workers is
to free the memory allocated for joinable threads. If we avoid
allocating this memory, we don't need to take care of freeing it.

Moreover, any memory associated with a worker thread which died before
we asked it to die (e.g., because virCondWait failed in the thread)
would be lost anyway since virThreadPoolFree calls virThreadJoin only
for threads which were running at the time virThreadPoolFree was called.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-05-21 14:35:02 +02:00
Cole Robinson
9ce409561a virfile: virDirCreate: Drop redundant FORCE_PERMS flag
The only two virDirCreate callers already use it
2015-05-19 19:29:39 -04:00
Cole Robinson
c8661a1a7e virfile: virDirCreate: Fix ALLOW_EXIST conditional
I screwed this up in the previous (post 1.2.16) commits
2015-05-19 19:24:42 -04:00
Ján Tomko
3511c12244 reject out of range memory in SetMemory APIs
The APIs take the memory value in KiB and we store it in KiB
internally, but we cannot parse the whole ULONG_MAX range
on 64-bit systems, because virDomainParseScaledValue
needs to fit the value in bytes in an unsigned long long.

https://bugzilla.redhat.com/show_bug.cgi?id=1176739
2015-05-14 17:17:40 +02:00
Michal Privoznik
abac12b585 virSysinfoParseProcessor: Drop useless check for NULL
VIR_STRDUP plays nicely with NULLs. Theres no need to guard its
call with check for non-NULL.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-05-13 10:17:45 +02:00
Peter Krempa
a5e89ae16e util: Make the virDomainListFree helper more universal
Extend it to a universal helper used for clearing lists of any objects.
Note that the argument type is specifically void * to allow implicit
typecasting.

Additionally add a helper that works on non-NULL terminated arrays once
we know the length.
2015-05-11 08:28:53 +02:00
Cole Robinson
28c547ed6d storage: fs: Don't try to chown directory unless user requested
Currently we try to chown any directory passed to virDirCreate,
even if the user didn't request any explicit owner/group via the
pool/vol XML.

This causes issues with qemu:///session: try to build a pool of
a root owned directory like /tmp, and it fails trying to chown the
directory to the session user. Instead it should just leave things
as they are, unless the user requests changing permissions via
the pool XML.

Similarly this is annoying if creating a storage pool via system
libvirtd of an existing directory in user $HOME, it's now owned
by root.

The virDirCreate function is pretty convoluted, since it needs to
fork off in certain specific cases. Try to document that, to make
it clear where exactly we are changing behavior.
2015-05-04 12:56:38 -04:00
Cole Robinson
262b3c05dd storage: fs: Don't attempt directory creation if it already exists
The current code attempts to handle this, but it only catches mkdir
failing with EEXIST. However if say trying to build /tmp for an
unprivileged qemu:///session, mkdir will fail with EPERM.

Rather than catch any errors, just don't attempt mkdir if the directory
already exists.
2015-05-04 12:56:38 -04:00
zhang bo
ab7cd11e0b util: fix memleak in virStorageSourceClear
snapshot and configFile are not freed, free them.

Signed-off-by: Zhang Bo <oscar.zhangbo@huawei.com>
2015-04-27 15:37:13 +02:00
Zhang Bo
6fabe2f227 util: fix memleak in virFindSCSIHostByPCI
free buf in cleanup.

Signed-off-by: Zhang Bo <oscar.zhangbo@huawei.com>
2015-04-27 10:04:38 +02:00
John Ferlan
6f75779ece virhostdev: Fix comments for virHostdevReAttachPCIDevices
Pushed previous patch (commit id 'd45dadae6') too quickly...

The patch just updates the patch from Laine's suggestions.
2015-04-24 13:38:01 -04:00
Huanle Han
d45dadae6c hostdev: fix net config restore error
Fix for such a case:
1. Domain A and B xml contain the same SRIOV net hostdev(<interface
type='hostdev' /> with same pci address).
2. virsh start A (Successfully, and configure the SRIOV net with
custom mac)
3. virsh start B (Fail because of the hostdev used by domain A or other
reason.)
In step 3, 'virHostdevNetConfigRestore' is called for the hostdev
which is still used by domain A. It makes the mac/vlan of the SRIOV net
change.

Code Change in this fix:
1. As the pci used by other domain have been removed from
'pcidevs' in previous loop, we only restore the nic config for
the hostdev still in 'pcidevs'(used by this domain)
2. update the comments to make it more clear

Signed-off-by: Huanle Han <hanxueluo@gmail.com>
2015-04-24 12:28:59 -04:00
Huanle Han
7ec3f8051f hostdev: Create virHostdevIsPCINetDevice
Refactor some code to create a static function virHostdevIsPCINetDevice
which will detect whether the hostdev is a pci net device or not.

Signed-off-by: Huanle Han <hanxueluo@gmail.com>
2015-04-24 12:28:59 -04:00
Pavel Hrdina
7674c0454b build: add pragma directive to fix build on some gcc
Commit 1268820a removed obsolete index() function and replaced it by
strchr.  Few versions of gcc has a bug and reports a warning about
strchr:

../../src/util/virstring.c:1006: error: logical '&&' with non-zero
constant will always evaluate as true [-Wlogical-op]

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-04-24 13:40:41 +02:00
Cédric Bosdonnat
28d599c513 Allow access to vendor and device file for PCI device passthrough
For some devices, the $PCIDIR/vendor and $PCIDIR/device need to be
read. Iterate over them to get them as well in the the generated
apparmor profile.
2015-04-24 10:47:41 +02:00
Eric Blake
1268820a63 build: avoid obsolete index()
Commit 2a530a3e5 is not portable to mingw, which intentionally
avoids declaring the obsolete index().  See also:
https://bugzilla.redhat.com/show_bug.cgi?id=1214605

* src/util/virstring.c (virStringStripControlChars): Use strchr.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-04-23 08:15:55 -06:00
Roman Bogorodskiy
e34cccf783 vircommand: fix polling in virCommandProcessIO
When running on FreeBSD, there's a bug in virCommandProcessIO
polling that is triggered by the commandtest.

A test that triggers EPIPE in commandtest (named "test20") hungs
forever on FreeBSD.

Apparently, this happens because FreeBSD sets POLLHUP flag on revents
when stdin in closed. And as the current implementation only checks for
POLLOUT and POLLERR, it ends up looping forever inside
virCommandProcessIO and not trying to do one more write() that would
trigger EPIPE.

To fix that check for the POLLHUP flag along with POLLOUT and POLLERR.
2015-04-22 17:56:53 +03:00
Peter Krempa
dff92b3f2f util: storage: Improve error message when requesting image above 'start'
When a user would specify a backing chain index that is above the start
point libvirt would report a rather unhelpful error:

invalid argument: could not find backing store 1 in chain for 'sub/link2'

This patch adds an explicit check that the index is below start point in
the backing store and reports the following error if not:

invalid argument: requested backing store index 1 is above 'sub/../qcow2' in chain for 'sub/link2'

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1177062
2015-04-22 14:24:32 +02:00
Peter Krempa
9447f3c5fb util: storage: Add hint to error message that indexed access was used 2015-04-22 14:18:53 +02:00
Peter Krempa
62a61d583c util: storage: Fix possible crash when source path is NULL
Some storage protocols allow to have the @path field in struct
virStorageSource set to NULL. Add NULLSTR() wrappers to handle this
possibility until I finish the storage source error formatter.
2015-04-22 14:18:52 +02:00
Peter Krempa
64a9d2fa2f util: command: Deduplicate code in virCommandNewArgList
virCommandNewArgList can use virCommandNewVAList.
2015-04-22 14:05:50 +02:00
Roman Bogorodskiy
584db1054c util: fix build on non-Linux
Build fails on non-Linux systems with this error:

  CC       util/libvirt_util_la-virnetdev.lo
util/virnetdev.c:364:1: error: unused function 'virNetDevReplaceMacAddress' [-Werror,-Wunused-function]
virNetDevReplaceMacAddress(const char *linkdev,
^
util/virnetdev.c:406:1: error: unused function 'virNetDevRestoreMacAddress' [-Werror,-Wunused-function]
virNetDevRestoreMacAddress(const char *linkdev,
^
2 errors generated.

The virNetDev{Restore,Replace}MacAddress() functions are only used
by VF-related routines that are available on Linux only. So move these
functions under the same #ifdef.
2015-04-22 13:05:06 +04:00
Laine Stump
cb3fe38c74 util: set MAC address for VF via netlink message to PF+VF# when possible
Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1113474

When we set the MAC address of a network device as a part of setting
up macvtap "passthrough" mode (where the domain has an emulated netdev
connected to a host macvtap device that has exclusive use of the
physical device, and sets the device MAC address to match its own,
i.e. "<interface type='direct'> <source mode='passthrough' .../>"), we
use ioctl(SIOCSIFHWADDR) giving it the name of that device. This is
true even if it is an SRIOV Virtual Function (VF).

But, when we are setting the MAC address / vlan ID of a VF in
preparation for "hostdev network" passthrough (this is where we set
the MAC address and vlan id of the VF after detaching the host net
driver and before assigning the device to the domain with PCI
passthrough, i.e. "<interface type='hostdev'>", we do the setting via
a netlink RTM_SETLINK message for that VF's Physical Function (PF),
telling it the VF# we want to change. This sets an "administratively
changed MAC" flag for that VF in the PF's driver, and from that point
on (until the PF driver is reloaded, *not* merely the VF driver) that
VF's MAC address can't be changed using ioctl(SIOCSIFHWADDR) - the
only way to change it is via the PF with RTM_SETLINK.

This means that if a VF is used for hostdev passthrough, it will have
the admin flag set, and future attempts to use that VF for macvtap
passthrough will fail.

The solution to this problem is to check if the device being used for
macvtap passthrough is actually a VF; if so, we use the netlink
RTM_SETLINK message to the PF to set the VF's mac address instead of
ioctl(SIOCSIFHWADDR) directly to the VF; if not, behavior does not
change from previously.

There are three pieces to making this work:

1) virNetDevMacVLan(Create|Delete)WithVPortProfile() now call
   virNetDev(Replace|Restore)NetConfig() rather than
   virNetDev(Replace|Restore)MacAddress() (simply passing -1 for VF#
   and vlanid).

2) virNetDev(Replace|Restore)NetConfig() check to see if the device is
   a VF. If so, they find the PF's name and VF#, allowing them to call
   virNetDev(Replace|Restore)VfConfig().

3) To prevent mixups when detaching a macvtap passthrough device that
   had been attached while running an older version of libvirt,
   virNetDevRestoreVfConfig() is potentially given the preserved name
   of the VF, and if the proper statefile for a VF can't be found in
   the stateDir (${stateDir}/${pfname}_vf${vfid}),
   virNetDevRestoreMacAddress() is called instead (which will look in
   the file named ${stateDir}/${vfname}).

This problem has existed in every version of libvirt that has both
macvtap passthrough and interface type='hostdev'. Fortunately people
seem to use one or the other though, so it hasn't caused any real
world problem reports.
2015-04-21 12:33:20 -04:00
Michal Privoznik
176a95fd50 Introduce virNetDevBandwidthUpdateFilter
This is a simple wrapper around virNetDevBandwidthManipulateFilter() that
will update the desired filter on an interface (usually a network bridge)
with a new MAC address. Although, the MAC address in question usually
refers to some other interface - the one that the filter is constructed
for. Yeah, hard to parse. Thing is, our NATed network has a bridge where
some part of QoS takes place. And vNICs from guests are plugged into
the bridge. However, if a guest decides to change the MAC of its vNIC,
the corresponding qemu process emits an event which we can use to
update the QoS configuration based on the new MAC address.. However,
our QoS hierarchy is currently not notified, therefore it falls apart.
This function (when called in response to the aforementioned event)
will update our QoS hierarchy and duct tape it together again.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-17 10:49:03 +02:00
Michal Privoznik
c6f0be2fcf virnetdevbandwidth.c: Separate tc filter creation to a function
Not only this simplifies the code a bit, it prepares the
environment for upcoming patches. The new
virNetDevBandwidthManipulateFilter() function is capable of both
removing a filter and adding a new one. At the same time! Yeah,
this is not currently used anywhere but look at the next commit
where you'll see it.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-17 10:30:21 +02:00
Michal Privoznik
2397be694d virNetDevBandwidthSet: Add priority to filter
Currently, when constructing traffic shaping rules, the ingress
filter is created without any priority specified on the command
line. This makes kernel to make up one. While this works, it
simplifies things a bit if we provide the filter priority. In
this case, since it's the root filter lets give it the highest
priority of number 1.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-17 10:18:58 +02:00
Lubomir Rintel
3a495948b9 lxc: move wireless PHYs to a network namespace
The 802.11 interfaces can not be moved by themselves, their Phy has to move too.

If there are other interfaces, they have to move too -- hopefully it's not too
confusing. This is a less-invasive alternative to defining a new hostdev type
for PHYs.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-17 09:53:47 +02:00
Pavel Hrdina
358dbf8457 virbuffer: fix build on rhel-6
On rhel-6 is broken gcc that reports this warning:

util/virbuffer.c:500: error: logical '&&' with non-zero constant will
    always evaluate as true [-Wlogical-op]

Move the pragma directive before function virBufferEscapeString because
since commit aeb5262e this function uses 'strchr' too.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-04-16 18:35:41 +02:00
Michael Chapman
3617e3b36d virCondWaitUntil: calculate timespec correctly
ts.tv_nsec was off by a factor of 1000, making timeouts less than a
second in the future often expiring immediately.

Signed-off-by: Michael Chapman <mike@very.puzzling.org>
2015-04-16 15:39:22 +02:00
Michal Privoznik
3535de4626 virNetDevBandwidthPlug: Update function description
The comment is describing arguments passed to the function.
However, there's no @ifmac argument. In 955af4d4 it was replaced
with @ifmac_ptr.  Unfortunately, the comment wasn't updated.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-16 09:07:35 +02:00
Ján Tomko
aeb5262e43 Strip control codes in virBufferEscapeString
These cannot be represented in XML.

We have been stripping them, but only if the string had
characters that needed escaping: <>"'&

Extend the strcspn check to include control codes, and strip
them even if we don't do any escaping.

https://bugzilla.redhat.com/show_bug.cgi?id=1184131
https://bugzilla.redhat.com/show_bug.cgi?id=1066564
2015-04-15 18:41:20 +02:00
Ján Tomko
2a530a3e50 Add functions dealing with control characters in strings
Add virStringHasControlChars that checks if the string has
any control characters other than \t\r\n,
and virStringStripControlChars that removes them in-place.
2015-04-15 18:41:20 +02:00
Michal Privoznik
96a21e975f Cleanup "/sys/class/net" usage
Throughout the code, we have several places need to construct a path
somewhere in /sys/class/net/... They are not consistent and nearly
each code piece invents its own way how to do it. So unify this by:

1) use virNetDevSysfsFile() wherever possible

2) At least use common macro SYSFS_NET_DIR declared in virnetdev.h at
   the rest of places which can't go with 1)

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-15 16:43:28 +02:00
Michal Privoznik
6515f3df94 virPidFileConstructPath: Drop useless VIR_FREE()
If a virAsprintf() within the function fails, we call VIR_FREE()
over @rundir variable and jump onto cleanup label, where it is
freed again.  It doesn't hurt, but not make much sense too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-15 15:01:02 +02:00
Martin Kletzander
fae5b555c8 Change virConnectPtr into virObjectLocklable
It already had a virMutex inside, so this is just a cleanup.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-04-15 13:33:35 +02:00
Jiri Denemark
4864e377c9 sanlock: Use VIR_ERR_RESOURCE_BUSY if sanlock_acquire fails
When acquiring resource via sanlock fails, we would report it as
VIR_ERR_INTERNAL_ERROR, which is not very friendly to applications using
libvirt. Moreover, the lockd driver would report the same failure as
VIR_ERR_RESOURCE_BUSY, which looks better.

Unfortunately, in sanlock driver we don't really know if acquiring the
resource failed because it was already locked or there was another
reason behind. But the end result is the same and I think using
VIR_ERR_RESOURCE_BUSY reason for all acquire failures is still better
than what we have now.

https://bugzilla.redhat.com/show_bug.cgi?id=1165119
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-04-15 09:40:42 +02:00
Eric Blake
58dfc53414 build: provide virNetDevSysfsFile on non-Linux
Commit 49ed6cff is broken on mingw and other non-linux platforms:

  CCLD     libvirt.la
  Cannot export virNetDevSysfsFile: symbol not defined
  collect2: error: ld returned 1 exit status

* src/util/virnetdev.c: Provide virNetDevSysfsFile fallback.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-04-14 13:53:50 -06:00
Eric Blake
e4ab084813 build: include correct header for time()
Found by ./autobuild.sh during a mingw cross-compile:

Commit 8a96e87 was not innocuous - glibc happens to leak the
definition of time() through other headers, so that even without
<sys/select.h>, virrandom.c compiled just fine.  But on mingw,
we were not so lucky; <sys/select.h> was important for its side
effect of dragging in <time.h>, and we now have nothing providing
the declaration of time():

../../src/util/virrandom.c: In function 'virRandomOnceInit':
../../src/util/virrandom.c:65:5: error: implicit declaration of function 'time' [-Werror=implicit-function-declaration]
     unsigned int seed = time(NULL) ^ getpid();
          ^
	  ../../src/util/virrandom.c:65:5: error: nested extern declaration of 'time' [-Werror=nested-externs]

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-04-14 13:24:51 -06:00
Michal Privoznik
49ed6cff99 Introduce virnetdevtest
This is yet another test for check of basic functionality of our
NIC state handling code.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-14 19:33:02 +02:00
John Ferlan
454e52c89d util: Use 'idx' instead of 'index'
Impending syntax checker will disallow 'int index', so change it here.
2015-04-14 11:18:28 -04:00
Huanle Han
a959671da8 hostdev: fix loop index error when resetvfnetconfig
The variable 'last_processed_hostdev_vf' indicates index of the last
successfully configed vf. When resetvfnetconfig because of failure,
hostdevs[last_processed_hostdev_vf] should also be reset.

Signed-off-by: Huanle Han <hanxueluo@gmail.com>
2015-04-14 14:49:15 +02:00
Ján Tomko
9b90899915 Split out storage format 'compat' attribute sanity check
For future reuse in the snapshot XML.
2015-04-13 15:07:45 +02:00
Erik Skultety
b77ce18a28 virBitmap: Place virBitmapIsAllClear check after virBitmapParse calls
This patch adds checks for empty bitmaps right after the calls of
virBitmapParse. These only include spots where set API's are called and
where domain's XML is parsed.
Also, it partially reverts commit 983f5a which added a check for
invalid nodeset "0,^0" into virBitmapParse function. This change broke
the logic, as an empty bitmap should not cause an error.

https://bugzilla.redhat.com/show_bug.cgi?id=1210545
2015-04-13 14:21:02 +02:00
Luyao Huang
2605089c04 util: Update virNetDevGetIPAddress to get IPv6 addresses
Add static virNetDevGetifaddrsAddress to attempt to get the interface
IP address. If getifaddrs is not supported, fall back to
virNetDevGetIPv4AddressIoctl to get the IP address.

This allows IPv6 addresses to be used for <listen type='network>
with device-backed networks.

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

Signed-off-by: Luyao Huang <lhuang@redhat.com>
Signed-off-by: John Ferlan <jferlan@redhat.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-04-10 15:01:17 +02:00
John Ferlan
61fee39967 util: Replace virNetDevGetIPv4Address with virNetDevGetIPAddress
Rename it to virNetDevGetIPv4AddressIoctl and make
virNetDevGetIPAddress a wrapper around it, allowing
other ways of getting the address to be implemented,
and still falling back to the old method.

Signed-off-by: John Ferlan <jferlan@redhat.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-04-10 15:01:17 +02:00
John Ferlan
0456eda317 cgroup: Use virCgroupNewThread
Replace the virCgroupNew{Vcpu|Emulator|IOThread} calls with the common
virCgroupNewThread API

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-04-09 19:27:08 -04:00
John Ferlan
2cd3a980dc cgroup: Introduce virCgroupNewThread
Create a new common API to replace the virCgroupNew{Vcpu|Emulator|IOThread}
API's using an emum to generate the cgroup name

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-04-09 19:27:08 -04:00
Cédric Bosdonnat
cc21badc5c Open /proc/PID/ns/* read-only to avoid getting permission denied
lxc-enter-namespace stopped working on recent kernels (at least 3.19+)
due to /proc/PID/ns/* file descriptors being opened RW. From outside
the namespace these can only be opened RO.
2015-04-09 11:20:32 +02:00
Peter Krempa
fac04598bb util: file: Don't carelessly sanitize URIs
rfc3986 states that the separator in URI path is a single slash.
Multiple slashes may potentially lead to different resources and thus we
should not remove them.
2015-04-09 09:43:36 +02:00
Michal Privoznik
d65acbde35 vircgroup: Introduce virCgroupControllerAvailable
This new internal API checks if given CGroup controller is
available.  It is going to be needed later when we need to make a
decision whether pin domain memory onto NUMA nodes using cpuset
CGroup controller or using numa_set_membind().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-04-08 11:54:24 +02:00
Michael Chapman
fa2607d577 util: fix removal of callbacks in virCloseCallbacksRun
The close callbacks hash are keyed by a UUID-string, but
virCloseCallbacksRun was attempting to remove them by raw UUID. This
patch ensures the callback entries are removed by UUID-string as well.

This bug caused problems when guest migrations were abnormally aborted:

  # timeout --signal KILL 1 \
      virsh migrate example qemu+tls://remote/system \
        --verbose --compressed --live --auto-converge \
        --abort-on-error --unsafe --persistent \
        --undefinesource --copy-storage-all --xml example.xml
  Killed

  # virsh migrate example qemu+tls://remote/system \
      --verbose --compressed --live --auto-converge \
      --abort-on-error --unsafe --persistent \
      --undefinesource --copy-storage-all --xml example.xml
  error: Requested operation is not valid: domain 'example' is not being migrated

Signed-off-by: Michael Chapman <mike@very.puzzling.org>
2015-04-08 09:45:48 +02:00
Shivaprasad G Bhat
fb0ef7a60e hostdev: Report the domain name for used hostdevs during nodedev-detach
The nodedev-detach can report the name of the domain using the device
just the way nodedev-reattach does it.

Signed-off-by: Shivaprasad G Bhat <sbhat@linux.vnet.ibm.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-04-07 14:01:40 +02:00
Martin Kletzander
2a15fef067 Typos: Get rid of dependan(t|cies)
Dependant is flagged as wrong in US dictionary (only valid in UK
dictionary, and even then, it has only the financial sense and not the
inter-relatedness sense that we are more prone to be wanting throughout
code).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-04-02 16:05:32 +02:00
Huanle Han
7adb4bfc80 hostdev: Fix index error in loop after remove an element
'virPCIDeviceList' is actually an array. Removing one element makes the
rest of the element move.

Use while loop, increase index only when not virPCIDeviceListDel(pcidevs, dev)

Signed-off-by: Huanle Han <hanxueluo@gmail.com>
2015-04-02 16:05:32 +02:00
Ján Tomko
8a96e87e67 Clean up headers in src/util/virutil.h
* "verify.h" from gnulib is included in internal.h
* <sys/select.h> is no longer needed
  added by commit da196338 to use fd_set in virExec prototype
2015-04-02 10:27:56 +02:00
Ján Tomko
a0482396d7 Remove unused macros
In the order of appearance:

* MAX_LISTEN - never used
  added by 23ad665c (qemud) and addec57 (lock daemon)

* NEXT_FREE_CLASS_ID - never used, added by 07d1b6b

* virLockError - never used, added by eb8268a4

* OPENVZ_MAX_ARG, CMDBUF_LEN, CMDOP_LEN
  unused since the removal of ADD_ARG_LIT in d8b31306

* QEMU_NB_PER_CPU_STAT_PARAM - unused since 897808e

* QEMU_CMD_PROMPT, QEMU_PASSWD_PROMPT - unused since 1dc10a7

* TEST_MODEL_WORDSIZE - unused since c25c18f7

* TEMPDIR - never used, added by 714bef5

* NSIG - workaround around old headers
  added by commit 60ed1d2
  unused since virExec was moved by commit 02e8691

* DO_TEST_PARSE - never used, added by 9afa006

* DIFF_MSEC, GETTIMEOFDAY - unused since eee6eb6
2015-04-02 10:27:56 +02:00
Michal Privoznik
771e6e5a46 virCgroupController: Check the enum fits into 'int'
Throughout our code, the virCgroupController enum is used in two ways.
First as an index to an array of cgroup controllers:

struct virCgroup {
    char *path;

    struct virCgroupController controllers[VIR_CGROUP_CONTROLLER_LAST];
};

Second way is that when calling virCgroupNew() a bitmask of the enum
items can be passed to selectively detect only some controllers. For
instance:

int
virCgroupNewVcpu(virCgroupPtr domain,
                 int vcpuid,
                 bool create,
                 virCgroupPtr *group)
{
    ...
    controllers = ((1 << VIR_CGROUP_CONTROLLER_CPU) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUACCT) |
                   (1 << VIR_CGROUP_CONTROLLER_CPUSET));

    if (virCgroupNew(-1, name, domain, controllers, group) < 0)
        goto cleanup;
}

Even though it's highly unlikely that so many new controllers will be
invented so that we would overflow when constructing the bitmask, it
doesn't hurt to check at compile time either.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-30 15:20:28 +02:00
Michal Privoznik
149a62bc83 virCgroupNew: Enhance debug message
When creating new internal representation of cgroups, all passed
arguments are logged. Well, except for two: pid and pointer for
return value. Lets log them too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-30 15:20:24 +02:00
Michal Privoznik
0a09bcdc7f virCgroupNewPartition: Fix comment
The function has no argument named @name rather than @path
instead.  The comment is, however, referring to @name while it
should have been referring to @path really.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-30 15:20:20 +02:00
John Ferlan
cf6ab17e45 vircgroup: Fix build issue mingw cross compile
Commit id '2dbfa716' exposed virCgroupDetectMountsFromFile, but did not
add the corresponding entry in the "#else /* !VIR_CGROUP_SUPPORTED */"
section of the module.
2015-03-27 18:09:07 -04:00
John Ferlan
38efd52584 vircgroup: Fix build issue on mingw cross compile
Commit id 'ba1dfc5' added virCgroupSetCpusetMemoryMigrate and
virCgroupGetCpusetMemoryMigrate, but did not add the corresponding
entry points into the "#else /* !VIR_CGROUP_SUPPORTED */" section
2015-03-27 18:09:07 -04:00
Pavel Hrdina
0614976bc9 virnetlink: fix build error
Commint 0473b45cc introduced new function virNetlinkDelLink, but in
it's counterpart for non-linux platform there should be ATTRIBUTE_UNUSED
instead of ATTRIBUTE_UNSUPPORTED.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-03-27 11:06:05 +01:00
Laine Stump
fc7b23db02 util: use netlink to create bridge devices
Just as it is possible to delete a bridge device with the netlink
RTM_DELLINK message, one can be created with the RTM_NEWLINK
message. Because of differences in the format of the message, it's not
as straightforward as with virNetlinkDelLink() to create a single
utility function that can be used to create any type of interface, so
the new netlink version of virNetDevBridgeCreate() does its own
construction of the netlink message and calls virNetlinkCommand()
itself.

This doesn't provide any extra functionality, just provides symmetry
with the previous commit.

NB: We *could* alter the API of virNetDevBridgeCreate() to take a MAC
address, and directly program that mac address into the bridge (by
adding an IFLA_ADDRESS attribute, as is done in
virNetDevMacVLanCreate()) rather than separately creating the "dummy
tap" (e.g. virbr0-nic) to maintain a fixed mac address on the bridge,
but the commit history of virnetdevbridge.c shows that the presence of
this dummy tap is essential in some older versions of the kernel
(between 2.6.39 and 3.1 or 3.2, possibly?) to proper operation of IPv6
DAD, and I don't want to take the chance of breaking something that I
don't have the time/setup to test (my RHEL6 box is at kernel
2.6.32-544, and the next lowest kernel I have is 3.17)
2015-03-26 15:33:05 -04:00
Laine Stump
09778e0908 util: use netlink to delete bridge devices
https://bugzilla.redhat.com/show_bug.cgi?id=1125755

reported that a stray bridge device was left on the system when a
libvirt network failed to start due to an illegal iptables rule caused
by bad config. Apparently the reason this was happening was that
NetworkManager was noticing immediately when the bridge device was
created and automatically setting it IFF_UP. libvirt would then try to
setup the iptables rules, get an error back, and since libvirt had
never IFF_UPed the bridge, it didn't expect that it needed to set it
~IFF_UP before deleting it during the cleanup process. But the
ioctl(SIOCBRDELBR) ioctl will fail to delete a bridge if it is IFF_UP.

Since that bug was reported, NetworkManager has gotten a bit more
polite in this respect, but just in case something similar happens in
the future, this patch switches to using the netlink RTM_DELLINK
message to delete the bridge - unlike SIOCBRDELBR, it will delete the
requested bridge no matter what the setting of IFF_UP.
2015-03-26 15:31:34 -04:00
Laine Stump
e849062a64 util: replace body of virNetDevMacVLanDelete() with virNetlinkDelLink()
These two functions are identical, so no sense in having the
duplication. I resisted the temptation to replace calls to
virNetDevMacVLanDelete() with calls to virNetlinkDelLink() just in
case some mythical future platform has macvtap devices that aren't
managed with netlink (or in case we some day need to do more than just
tell the kernel to delete the device).
2015-03-26 15:30:46 -04:00
Laine Stump
0473b45cc1 util: netlink function to delete any network device
libvirt has always used the netlink RTM_DELLINK message to delete
macvtap/macvlan devices, but it can actually be used to delete other
types of network devices, such as bonds and bridges. This patch makes
virNetDevMacVLanDelete() available as a generic function so it can
intelligibly be called to delete these other types of interfaces.
2015-03-26 15:29:42 -04:00
Peter Krempa
6ff59cbc83 util: buffer: Add support for adding text blocks with indentation
The current auto-indentation buffer code applies indentation only on
complete strings. To allow adding a string containing newlines and
having it properly indented this patch adds virBufferAddStr.
2015-03-25 15:42:52 +01:00
Peter Krempa
ad886fa6c8 util: identity: Harden virIdentitySetCurrent()
Don't unref the old identity unless we set the new one correctly and
unref the new one on failure to set it so that we don't leak any
references or use invalid pointers.
2015-03-25 13:37:41 +01:00
Peter Krempa
8ad871f39e util: NUMA: Change error code in virNumaNodesetIsAvailable()
An invalid nodeset is a configuration problem rather than an internal
error.
2015-03-25 12:24:40 +01:00
Jiri Denemark
d20f5dde29 virThreadPool: Set thread worker name
Every thread created as a worker thread within a pool gets a name
according to virThreadPoolJobFunc name.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-03-25 10:00:53 +01:00
Jiri Denemark
55ebc93a08 virThread: Set thread job
Automatically assign a job to every thread created by virThreadCreate.
The name of the virThreadFunc function passed to virThreadCreate is used
as the job or worker name in case no name is explicitly passed.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-03-25 10:00:53 +01:00
Jiri Denemark
956953884e Add support for tracking thread jobs
Each thread can use a thread local variable to keep the name of a job
which is currently running in the job.

The virThreadJobSetWorker API is supposed to be called once by any
thread which is used as a worker, i.e., it is waiting in a pool, woken
up to do a job, and returned back to the pool.

The virThreadJobSet/virThreadJobClear APIs are to be called at the
beginning/end of each job.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-03-25 10:00:53 +01:00
Martin Kletzander
0e7457e501 Fix common misspellings
Wikipedia's list of common misspellings [1] has a machine-readable
version.  This patch fixes those misspellings mentioned in the list
which don't have multiple right variants (as e.g. "accension", which can
be both "accession" and "ascension"), such misspellings are left
untouched.  The list of changes was manually re-checked for false
positives.

[1] https://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings/For_machines

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-03-23 09:01:30 +01:00
Martin Kletzander
ba1dfc5b6a cgroup: Add accessors for cpuset.memory_migrate
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-03-20 13:40:02 +01:00
Laine Stump
72423df992 util: more verbose error when failing to create macvtap device
Investigation of a problem with creating passthrough macvtap devices
(https://bugzilla.redhat.com/show_bug.cgi?id=1185501) has shown that
this slightly more verbose failure message is useful. In particular,
the mac address can be used to determine the domain. You could also
figure this out by looking at preceding messages in a debug log, but
this gets it in a single place.
2015-03-18 14:49:29 -04:00
Jiri Denemark
2dbfa716e8 tests: Add tests for virCgroupDetectMounts
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-03-18 09:53:24 +01:00
Antoni Segura Puimedon
d490f47ba3 network: Add midonet virtual port type support to qemu
Use the utilities introduced in the previous patches so the qemu
driver is able to create tap devices that are bound (and unbound
on domain destroyal) to Midonet virtual ports.

Signed-off-by: Antoni Segura Puimedon <toni+libvirt@midokura.com>
2015-03-17 13:10:17 -04:00
Antoni Segura Puimedon
a9fbe3b157 docs: schema and docs for the midonet virtualport type
Midonet is an opensource virtual networking that over lays the IP
network between hypervisors. Currently, such networks can be made
with the openvswitch virtualport type.

This patch, defines the schema and documentation that will serve
as basis for the follow up patches that will add support to libvirt
for using Midonet virtual ports for its interfaces. The schema
definition requires that the port profile expresses its interfaceid
as part of the port profile. For that reason, this is part of the
patch too.

Signed-off-by: Antoni Segura Puimedon <toni+libvirt@midokura.com>
2015-03-17 13:09:05 -04:00
Antoni Segura Puimedon
e1f6485694 util: functions to support binding/unbinding midonet virtualports
Adds the port type definitions and methods that will be used to bind
interfaces to the Midonet virtual ports.

virtnetdevmidonet.c adds the way to bind and unbind the ports by
calling into the Midonet Host Agent control command line (installed
with the midolman package).

Signed-off-by: Antoni Segura Puimedon <toni+libvirt@midokura.com>
2015-03-17 12:56:37 -04:00
Peter Krempa
158340e2fb util: storage: Fix check for empty storage device
If the storage device type is parsed as network our parser still allows
it to omit the <source> element. The empty drive check would not trigger
on such device as it expects that every network storage source is valid.

Use VIR_STORAGE_NET_PROTOCOL_NONE as a marker that the storage source is
empty.
2015-03-17 17:11:38 +01:00
Martin Kletzander
3a13e4f178 util: Make sure the comment about virBufferAddBuffer is true
Change it so it really *always* eats the @toadd buffer.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-03-17 12:03:33 +01:00
Eric Blake
a9abc08dff netdev: silence valgrind warning about ioctl use
Valgrind complained:

==3770== Syscall param ioctl(SIOCETHTOOL) points to uninitialised byte(s)
==3770==    at 0x919D407: ioctl (syscall-template.S:81)
==3770==    by 0x530FE7E: rpl_ioctl (ioctl.c:42)
==3770==    by 0x50CB433: virNetDevFeatureAvailable (virnetdev.c:2764)
==3770==    by 0x50CB6A7: virNetDevGetFeatures (virnetdev.c:2830)
==3770==    by 0x1F0E5347: udevProcessNetworkInterface (node_device_udev.c:722)
==3770==    by 0x1F0E689F: udevGetDeviceDetails (node_device_udev.c:1300)
==3770==    by 0x1F0E6E06: udevAddOneDevice (node_device_udev.c:1422)
==3770==    by 0x1F0E6FB8: udevProcessDeviceListEntry (node_device_udev.c:1464)
==3770==    by 0x1F0E70CF: udevEnumerateDevices (node_device_udev.c:1494)
==3770==    by 0x1F0E7BB4: nodeStateInitialize (node_device_udev.c:1806)
==3770==    by 0x51B4303: virStateInitialize (libvirt.c:777)
==3770==    by 0x11DEE7: daemonRunStateInit (libvirtd.c:906)
==3770==  Address 0x228e38d4 is on thread 12's stack
==3770==  in frame #2, created by virNetDevFeatureAvailable (virnetdev.c:2750)

* src/util/virnetdev.c (virNetDevFeatureAvailable): Initialize all
bytes of ifr.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-03-14 20:59:02 -06:00
zhang bo
25df57db73 util: don't fail if no PortData is found while getting migrateData
Introduced by f6a2f97e

Problem Description:
After multiple times of migrating a domain, which has an ovs interface with no portData set,
with non-shared disk, nbd ports got overflowed.

The steps to reproduce the problem:
1 define and start a domain with its network configured as:
    <interface type='bridge'>
          <source bridge='br0'/>
          <virtualport type='openvswitch'>
          </virtualport>
          <model type='virtio'/>
          <driver name='vhost' queues='4'/>
    </interface>
2 do not set the network's portData.
3 migrate(ToURI2) it with flag 91(1011011), which means:
  VIR_MIGRATE_LIVE
  VIR_MIGRATE_PEER2PEER
  VIR_MIGRATE_PERSIST_DEST
  VIR_MIGRATE_UNDEFINE_SOURCE
  VIR_MIGRATE_NON_SHARED_DISK
4 migrate success, but we got an error log in libvirtd.log:
  error : virCommandWait:2423 : internal error: Child process (ovs-vsctl --timeout=5 get Interface
  vnet1 external_ids:PortData) unexpected exit status 1: ovs-vsctl: no key "PortData" in Interface
  record "vnet1" column external_ids
5 migrate it back, migrate it , migrate it back, .......
6 nbd port got overflowed.

The reasons for the problem is :
1 virNetDevOpenvswitchGetMigrateData() takes it as wrong if no portData is available for  the ovs
 interface of a domain. (We think it's not appropriate, as portData is just OPTIONAL)
2 in func qemuMigrationBakeCookie(), it fails in qemuMigrationCookieAddNetwork(), and returns with -1.
 qemuMigrationCookieAddNBD() is not called thereafter, and mig->nbd is still NULL.
3 However, qemuMigrationRun() just *WARN* if qemuMigrationBakeCookie() fails, migration still successes.
 cookie is NULL, it's not baked on the src side.
4 On the destination side, it would alloc a port first and then free the nbd port in COOKIE.
 But the cookie is NULL due to qemuMigrationCookieAddNetwork() failure at src side. thus the nbd port
 is not freed.

In this patch, we add "--if-exists" option to make ovs-vsctl not raise error if there's no portData available.
Further more, because portData may be NULL in the cookie at the dest side, check it before setting portData.

Signed-off-by: Zhou Yimin <zhouyimin@huawei.com>
Signed-off-by: Zhang Bo <oscar.zhangbo@huawei.com>
2015-03-13 22:43:08 -04:00
Ján Tomko
22fd3ac38f Introduce virBitmapIsBitSet
A helper that never returns an error and treats bits out of bitmap range
as false.

Use it everywhere we use ignore_value on virBitmapGetBit, or loop over
the bitmap size.
2015-03-13 15:31:33 +01:00
Pavel Hrdina
48461b169e virnetdev: fix build with old kernel
Commit c9027d8f added a detection of NIC HW features, but some of them
are not available in old kernel.  Very old kernels lack enum
ethtool_flags and even if this enum is present, not all values are
available for all kernels.  To be sure that we have everything in kernel
that we need, we must check for existence of most of that flags, because
only few of them were defined at first.

Also to successfully build libvirt with older kernel we need to include
<linux/types.h> before <linux/ethtool.h> to have __u32 and friends
defined.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-03-12 17:48:02 +01:00
Pavel Hrdina
cf521fc8ba memtune: change the way how we store unlimited value
There was a mess in the way how we store unlimited value for memory
limits and how we handled values provided by user.  Internally there
were two possible ways how to store unlimited value: as 0 value or as
VIR_DOMAIN_MEMORY_PARAM_UNLIMITED.  Because we chose to store memory
limits as unsigned long long, we cannot use -1 to represent unlimited.
It's much easier for us to say that everything greater than
VIR_DOMAIN_MEMORY_PARAM_UNLIMITED means unlimited and leave 0 as valid
value despite that it makes no sense to set limit to 0.

Remove unnecessary function virCompareLimitUlong.  The update of test
is to prevent the 0 to be miss-used as unlimited in future.

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

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-03-06 11:52:24 +01:00
Pavel Hrdina
a73395ae66 virutil: introduce helper functions for memory limits
The first one is to truncate the memory limit to
VIR_DOMAIN_MEMORY_PARAM_UNLIMITED if the value is greater and the second
one is to decide whether the memory limit is set or not, unlimited means
that it's not set.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-03-06 11:52:23 +01:00
Stefan Berger
a06e9ce11d utils: Implement virCommandPassFDGetFDIndex
Implement virCommandPassFDGetFDIndex to determine the index a given
file descriptor will have when passed to the child process.

Signed-off-by: Stefan Berger <stefanb@linux.vnet.ibm.com>
2015-03-05 18:57:06 -05:00
Ján Tomko
41c5baeafb Fix build on mingw
Last commit unconditionally included a linux-specific header.

Do not do that.
2015-03-05 12:04:11 +01:00
James Chapman
c9027d8f44 SRIOV NIC offload feature discovery
Adding functionality to libvirt that will allow it
query the ethtool interface for the availability
of certain NIC HW offload features

Here is an example of the feature XML definition:

<device>
<name>net_eth4_90_e2_ba_5e_a5_45</name>
  <path>/sys/devices/pci0000:00/0000:00:03.0/0000:08:00.1/net/eth4</path>
  <parent>pci_0000_08_00_1</parent>
  <capability type='net'>
    <interface>eth4</interface>
    <address>90:e2:ba:5e:a5:45</address>
    <link speed='10000' state='up'/>
    <feature name='rx'/>
    <feature name='tx'/>
    <feature name='sg'/>
    <feature name='tso'/>
    <feature name='gso'/>
    <feature name='gro'/>
    <feature name='rxvlan'/>
    <feature name='txvlan'/>
    <feature name='rxhash'/>
    <capability type='80203'/>
  </capability>
</device>

Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-03-05 11:31:05 +01:00
Peter Krempa
ef2e6f4089 util: storage: Fix error type in virStorageSourceParseBackingURI
The gluster volume name extraction code was copied from the XML parser
without changing the VIR_ERR_XML_ERROR error code. Use
VIR_ERR_CONFIG_UNSUPPORTED instead.
2015-02-26 11:50:38 +01:00
Peter Krempa
fc56ecd735 util: storagefile: Don't crash on gluster URIs without path
Similar to commit fdb80ed4f6 libvirtd
would crash if a gluster URI without path would be used in the backing
chain of a volume. The crash happens in the gluster specific part of the
parser that extracts the gluster volume name from the path.

Fix the crash by checking that the PATH is NULL.

This patch does not contain a test case as it's not possible to test it
with the current infrastructure as the test suite would attempt to
contact the gluster server in the URI. I'm working on the test suite
addition but that will be post-release material.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1196528
2015-02-26 11:50:38 +01:00
Laine Stump
153b06c6d1 util: check for null ifname inside virNetDevBandwidthSet()
Previously this function relied on having ATTRIBUTE_NONNULL(1) in its
prototype rather than explicitly checking for a null
ifname. Unfortunately, ATTRIBUTE_NONNULL is just a hint to the
optimizer and code analyzers like Coverity, it doesn't actually check
anything at execution time, so the result was possible warnings from
Coverity, along with the possibility of null dereferences when ifname
wasn't available.

This patch removes the ATTRIBUTE_NONNULL from the prototype, and
checks ifname inside the function, logging an error if it's NULL (once
we've determined that the user really is trying to set a bandwidth).
2015-02-25 13:10:34 -05:00
Laine Stump
118b240808 network: only clear bandwidth if it has been set
libvirt was unconditionally calling virNetDevBandwidthClear() for
every interface (and network bridge) of a type that supported
bandwidth, whether it actually had anything set or not. This doesn't
hurt anything (unless ifname == NULL!), but is wasteful.

This patch makes sure that all calls to virNetDevBandwidthClear() are
qualified by checking that the interface really had some bandwidth
setup done, and checks for a null ifname inside
virNetDevBandwidthClear(), silently returning success if it is null
(as well as removing the ATTRIBUTE_NONNULL from that function's
prototype, since we can't guarantee that it is never null,
e.g. sometimes a type='ethernet' interface has no ifname as it is
provided on the fly by qemu).
2015-02-25 13:09:34 -05:00
Ján Tomko
6784acc7b0 Fix error messages in virStorageFileGetMetadataFromFD
Do not use relPath, it has not been filled by virStorageFileMetadataNew.
2015-02-25 12:14:30 +01:00
Michal Privoznik
83c5467ee9 util: Introduce virBufferAddBuffer
This API joins the following two lines:

char *s = virBufferContentAndReset(buf1);
virBufferAdd(buf2, s, -1);

into one:

virBufferAddBuffer(buf2, buf1);

With one exception: there's no re-indentation applied to @buf1.
The idea is, that in general both can have different indentation
(like the test I'm adding proves)

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-02-25 09:23:42 +01:00
Jiri Denemark
bc6e206322 Search for schemas and cpu_map.xml in source tree
Not all files we want to find using virFileFindResource{,Full} are
generated when libvirt is built, some of them (such as RNG schemas) are
distributed with sources. The current API was not able to find source
files if libvirt was built in VPATH.

Both RNG schemas and cpu_map.xml are distributed in source tarball.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-02-19 15:25:04 +01:00
Pavel Hrdina
94cc577807 virprocess: fix MinGW build and RHEL-5 build
Commit b6a2828e introduced new functions to set process scheduler. There
is a small typo in ELSE path for systems where scheduler is not
available.

Also some of the definitions were introduced later in kernel. For
example RHEL-5 is running on kernel 2.6.18, but SCHED_IDLE was introduces
in 2.6.23 [1] and SCHED_BATCH in 2.6.16 [1]. We should not count only on
existence of function sched_setscheduler(), we must also check for
existence of used macros as they might not be defined.

[1] see 'man 7 sched'

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-02-12 18:00:21 +01:00
Martin Kletzander
b6a2828e53 util: Add virProcessSetScheduler() function for scheduler settings
This function uses sched_setscheduler() function so it works with
processes and threads as well (even threads not created by us, which is
what we'll need in the future).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-02-11 17:30:06 +01:00
John Ferlan
92d9114eac virfile: Adjust error path for virFileOpenForked
Rather than have a dummy waitpid loop and return of the failure status
from recvfd, adjust the logic to save the recvfd error & fd and then
in priority order:

- if waitpid failed, use that errno value
- waitpid succeeded, but if the child exited abnormally, report failure
(use EACCES to report as return failure, since either EACCES or EPERM is
what caused us to fall into the fork+setuid path)
- waitpid succeeded, but if the child reported non-zero status, report
failure (use the errno value that the child encoded into exit status)
- waitpid succeeded, but if recvfd failed, report recvfd_errno
- waitpid and recvfd succeeded, use the fd

NOTE: Original logic to retry the open and force owner mode was
"documented" as only being attempted if we had already tried opening
with the fork+setuid, but checked flags vs. VIR_FILE_OPEN_NOFORK which
is counter to how we would get to that point. So that code was removed.
2015-02-11 07:28:58 -05:00
Daniel P. Berrange
95fd6a91c6 qemu: include libvirt & QEMU versions in QEMU log files
It is often helpful to know which version of libvirt and QEMU
was present when a guest was first launched. Ensure this info
is written into the QEMU log file for each guest.
2015-02-06 10:22:07 +00:00
Peter Krempa
fdb80ed4f6 util: storage: Fix parsing of nbd:// URI without path
If a storage file would be backed with a NBD device without path
(nbd://localhost) libvirt would crash when parsing the backing path for
the disk as the URI structure's path element is NULL in such case but
the NBD parser would access it shamelessly.
2015-02-04 08:38:25 +01:00
Pavel Hrdina
47dd6c4335 virutil: fix MinGW build
Commit b38da584 introduced two new functions to get a page size but it
won't work on Windows. We should take care of this.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-02-03 16:37:01 +01:00
Pavel Hrdina
8bda903528 virnetdev: fix some issues found by coverity and mingw builds
Commit e562a61a introduced new function to get/set interface state but
there was misuse of ATTRIBUTE_NONNULL on non-pointer attributes and also
we need to wrap that functions by #ifdef to not break mingw build.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2015-02-03 16:34:35 +01:00
Daniel P. Berrange
b38da58423 Make tests independant of system page size
Some code paths have special logic depending on the page size
reported by sysconf, which in turn affects the test results.
We must mock this so tests always have a consistent page size.
2015-02-02 20:27:43 +00:00
Laine Stump
df2cc650c0 util: make virNetDev(Get|Set)IFFlags() static
e562a61a07 added these two new helper functions and only used them
within virnetdev.c, but declared them in the .h file. If some
currently unsupported interface flags need to be accessed in the
future, it will make more sense to write the appropriate higher level
function rather than require us to artificially define IFF_* on some
mythical platform that doesn't have SIOC[SG]IFFLAGS (and therefore
doesn't have IFF_*) just so we can call virNetDevSetIFFFlags() to
return an error.

To help someone in not going down the wrong road, this patch makes the
two helper functions static, hopefully making it less likely that
someone will want to use them outside of virnetdev.c.
2015-02-02 14:50:19 -05:00
Peter Krempa
a6f277a67b util: json: add helper to iterate JSON object key=value pairs
This helper eases iterating all key=value pairs stored in a JSON
object. Usually we pick only certain known keys from a JSON object, but
this will allow to walk complete objects and have the callback act on
those.
2015-01-31 08:53:21 +01:00
Peter Krempa
58f61d24a4 util: json: Add functions to convert JSON arrays from/to virBitmaps
To be able to easily represent nodesets and other data stored in
virBitmaps in libvirt, this patch introduces a set of helpers that allow
to convert the bitmap to and from JSON value objects.
2015-01-31 08:53:21 +01:00
Peter Krempa
bc2d8e5b06 util: bitmap: Add option to allocate bitmap without reporting error
The virBitmapNew() function reports only OOM errors. Split out the
internals into a "quiet" function and add a wrapper that reports the
error.
2015-01-31 08:53:21 +01:00
Peter Krempa
f0363aa145 util: json: make value object creator universal by supporting adding
To allow constructing of value objects stepwise explode the helper into
separate steps and allow appending into existing value objects.
2015-01-31 08:53:21 +01:00
Tony Krowiak
e562a61a07 util: Functions for getting/setting device options
This patch provides the utility functions needed to synchronize
the rxfilter changes made to a guest domain with the corresponding
macvtap devices on the host:

* Get/set PROMISC flag
* Get/set ALLMULTI, MULTICAST

Signed-off-by: Tony Krowiak <akrowiak@linux.vnet.ibm.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-01-30 13:07:27 +01:00
John Ferlan
29946e3e53 virfile: Need to check for ENOTCONN from recvfd failure
A gnulib change (commit id 'beae0bdc') causes ENOTCONN to be returned
from recvfd which causes us to fall into the throwaway waitpid() call
and return ENOTCONN to the caller, this then gets displayed during
a 'virsh save' when using a root squashed NFS environment that's trying
to save the file as something other than root:root.

This patch will add the additional check for ENOTCONN to force the code
into the waitpid loop looking for the actual status from the _exit()'d
child fork.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-01-29 15:37:09 -05:00
Ján Tomko
9783c20cfb Fix syntax-check
My commit 08d1ae1 broke syntax-check by adding ATTRIBUTE_UNUSED
to the flags parameter.

Rename the parameter to unused_flags to bypass the check.
2015-01-29 14:39:12 +01:00
Ján Tomko
08d1ae16d6 Remove flag checking in MacVLanCreate helper stub
When compiling without WITH_MACVTAP, we can get:
'unsupported flags (0x1) in function
virNetDevMacVLanCreateWithVPortProfile'
on an attempt to start a domain.

Remove the flag check to reach the more helpful error:
Cannot create macvlan devices on this platform

https://bugzilla.redhat.com/show_bug.cgi?id=1186928
2015-01-29 10:06:56 +01:00
Peter Krempa
20448c2a72 util: bitmap: Tolerate NULL bitmaps in virBitmapEqual
After virBitmapEqual is able to compare NULL bitmaps few bits of code
can be cleaned up.
2015-01-29 08:22:41 +01:00
Daniel P. Berrange
b3e4401dc6 systemd: don't report an error if the guest is already terminated
In many cases where we invoke virSystemdTerminateMachine the
process(es) will have already gone away on their own accord.
In these cases we log an error message that the machine does
not exist. We should catch this particular error and simply
ignore it, so we don't pollute the logs.
2015-01-27 13:57:02 +00:00
Ján Tomko
b54f48812d Fix a memory leak in virCgroupGetPercpuStats
Coverity reports that my commit af1c98e introduced
two memory leaks:
the cpumap if ncpus == 0 in virCgroupGetPercpuStats
and the params array in the test of the function.
2015-01-26 16:13:06 +01:00
Ján Tomko
495accb047 Use correct location for qcow1 encryption header
After the 8-byte size header, there are two one-byte headers
and two bytes of padding before the crypt_header field.

Our QCOW1_HDR_CRYPT constant did not skip the padding.
http://git.qemu.org/?p=qemu.git;a=blob;f=block/qcow.c;h=ece22697#l41

https://bugzilla.redhat.com/show_bug.cgi?id=1185165
2015-01-26 16:13:02 +01:00
Daniel P. Berrange
2d8b59c060 systemd: avoid string comparisons on dbus error messages
Add a virDBusErrorIsUnknownMethod helper so that callers
don't need todo string comparisons themselves to detect
standard error names.
2015-01-26 09:14:04 +00:00
Daniel P. Berrange
d13b586a91 systemd: fix build without dbus
The virDBusMethodCall method has a DBusError as one of its
parameters. If the caller wants to pass a non-NULL value
for this, it immediately makes the calling code require
DBus at build time. This has led to breakage of non-DBus
builds several times. It is desirable that only the virdbus.c
file should need WITH_DBUS conditionals, so we must ideally
remove the DBusError parameter from the method.

We can't simply raise a libvirt error, since the whole point
of this parameter is to give the callers a way to check if
the error is one they want to ignore, without having the logs
polluted with an error message. So, we add a virErrorPtr
parameter which the caller can then either ignore or raise
using the new virReportErrorObject method.

This new method is distinct from virSetError in that it
ensures the logging hooks are run.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2015-01-26 09:14:04 +00:00
Peter Krempa
60e4e5783d util: json: Make argument of virJSONValueArraySize const
The function doesn't allow to modify the array in any way, thus the
argument can be const.
2015-01-23 13:18:04 +01:00
Ján Tomko
af1c98e406 Fix virCgroupGetPercpuStats with non-continuous present CPUs
Per-cpu stats are only shown for present CPUs in the cgroups,
but we were only parsing the largest CPU number from
/sys/devices/system/cpu/present and looking for stats even for
non-present CPUs.
This resulted in:
internal error: cpuacct parse error
2015-01-22 17:01:11 +01:00