Commit Graph

1895 Commits

Author SHA1 Message Date
John Ferlan
b2e4ace220 Coverity: Resolve a CHECKED_RETURN message
Recent changes to the module seemed to have caused Coverity to find a new
issue regarding the failure to check the return from a sendmsg. The code
doesn't seem to care about the return status, so just added an ignore_value
to keep Coverity quiet.
2014-03-25 17:13:27 -04:00
Ján Tomko
bada4222e5 Indent top-level labels by one space in src/util/ 2014-03-25 14:58:40 +01:00
Peter Krempa
562112f4f9 util: Sanitize ATTRIBUTE_NONNULL use in viriscsi.h
Some of the function attributes marked as nonnull actually explicitly
handle the arguments for NULL. All changed functions handle missing
"initiatoriqn" argument well and virISCSIScanTargets also handles well
if the return pointers are missing. Remove some of the liberaly used
ATTRIBUTE_NONNULLs as coverity and possibly other compilers that honor
the attribute fail to compile the code.

Flaw introduced in commit 5e1d5dde
2014-03-25 08:26:39 +01:00
Ján Tomko
80fb32c320 Add stubs for virDBusCreateReply{,V}
Fix the build without dbus.
2014-03-21 14:38:19 +01:00
Wang Yufei
bfb29654c8 cgroup: Fix start VMs coincidently failed
When I start multi VMs coincidently and any of the cgroup directories
named machine doesn't exist. There's a chance that VM start failed because
of creating directory failed:
Unable to initialize /machine cgroup: File exists
When the errno returned by mkdir in virCgroupMakeGroup is EEXIST,
we should pass it through and continue to start the VM.
Signed-off-by: Wang Yufei <james.wangyufei@huawei.com>
2014-03-21 13:27:28 +01:00
Daniel P. Berrange
edff187a39 Allow caller to handle DBus error messages
The caller may not want all DBus error conditions to be turned
into libvirt errors, so provide a way for the caller to get
back the full DBusError object. They can then check the errors
and only report those that they consider to be fatal.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-21 11:26:34 +00:00
Daniel P. Berrange
2c64603366 Introduce alternate way to encode/decode arrays in DBus messages
Currently the DBus helper APIs require the values for an array
to be passed inline in the variadic argument list. This change
introduces support for passing arrays using a pointer to a plain
C array of the basic type. This is of particular benefit for
decoding messages when you don't know how many array elements
are being received.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-21 11:26:34 +00:00
Daniel P. Berrange
217ac43e03 Remove bogus call to dbus_set_error_from_message
The dbus_connection_send_with_reply_and_block method will
automatically call dbus_set_error_from_message for us. We
mistakenly thought we had todo it because of a flaw in the
systemd unit test mock impl. The latter should have directly
set the error object, instead of creating an error message
object.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-21 11:26:34 +00:00
Daniel P. Berrange
dc7f3ffc02 Remove bogus unref in virDBusMessageRead
The virDBusMessageRead method should not have side-effects on
the message parameter passed in, so unref'ing it is wrong.
The caller should unref only when they decided they are done
with it.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-21 11:26:34 +00:00
Daniel P. Berrange
bd93dea3f7 Add DBus helper methods for creating reply messages
The test suites often have to create DBus method reply messages
with payloads. Create two helpers for simplifying the process
of creating replies with payloads.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-21 11:26:34 +00:00
Daniel P. Berrange
838d0b04ca Refactor dbus helper methods for method calls
Split the virDBusMethodCall method into a couple of new methods
virDBusCall, virDBusCreateMethod and virDBusCreateMethodV.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-21 11:26:34 +00:00
Zhou Yimin
835a1cdf85 virlog: Modify virLogParseDefaultPriority's comment of return value
virLogParseDefaultPriority's successful return value is the same as
virLogSetDefaultPriority's successful return value. So it should be 0
rather than the parsed log level.

Signed-off-by: Zhou Yimin <zhouyimin@huawei.com>
2014-03-21 11:19:51 +01:00
Ján Tomko
5e1d5dded2 Move functions using iscsiadm to viriscsi.c
Remove the 'StorageBackend' from names of the functions and fix
indentation.
2014-03-20 18:04:50 +01:00
Ján Tomko
7dbbad35f2 Switch virCommandRunRegex to use virStringSplit
Instead of running the command asynchronously and reading the output
via fgets, let virCommand collect the output and split it with
virStringSplit.
2014-03-20 18:04:50 +01:00
Ján Tomko
f2cc42868e Move virStorageBackendRun to vircommand
The only storage-specific parameter is the pool object, which
is only used for passing to the callback function.
2014-03-20 18:04:50 +01:00
Martin Kletzander
daedff47ae Use K&R style for curly braces in src/util/
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-03-20 17:16:18 +01:00
Scott Sullivan
0099a4ae2b is_selinux_enabled() returns -1 on error, account for this.
Per the documentation, is_selinux_enabled() returns -1 on error.
Account for this. Previously when -1 was being returned the condition
would still be true. I was noticing this because on my system that has
selinux disabled I was getting this in the libvirt.log every 5
seconds:

error : virIdentityGetSystem:173 : Unable to lookup SELinux process context: Invalid argument

With this patch applied, I no longer get these messages every 5
seconds. I am submitting this in case its deemed useful for inclusion.
Anyone have any comments on this change? This is a patch off current
master.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-03-20 16:26:55 +01:00
Daniel P. Berrange
ba08c5932e Fix unitialized data in virSocketAddrMask
The virSocketAddrMask method did not initialize all fields
in the sockaddr_in6 struct. In paticular the 'sin6_scope_id'
field could contain random garbage, which would in turn
affect the result of any later virSocketAddrFormat calls.
This led to ip6tables rules in the FORWARD chain which
matched on random garbage sin6_scope_id. Fortunately these
were ACCEPT rules, so the impact was merely that desired
traffic was blocked, rather than undesired traffic allowed.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-20 12:15:00 +00:00
Daniel P. Berrange
7b3f1f8c30 Add ability to register callback for virCommand dry run
To allow for fault injection of the virCommand dry run,
add the ability to register a callback. The callback will
be passed the argv, env and stdin buffer and is expected
to return the exit status and optionally fill stdout and
stderr buffers.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-19 10:47:58 +00:00
Chunyan Liu
1b780c9eae virhostdev.h: remove ATTRIBUTE_NONNULL from oldStateDir
In libxl driver oldStateDir is NULL when calling
virHostdevReAttachDomainHostdevs. This is allowed.
Remove ATTRIBUTE_NONNULL setting from oldStateDir.

Introduced by commit 6225cb3.

Signed-off-by: Chunyan Liu <cyliu@suse.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2014-03-19 10:05:31 +01:00
Daniel P. Berrange
c0c8c1d7bb Remove global log buffer feature entirely
A earlier commit changed the global log buffer so that it only
records messages that are explicitly requested via the log
filters setting. This removes the performance burden, and
improves the signal/noise ratio for messages in the global
buffer. At the same time though, it is somewhat pointless, since
all the recorded log messages are already going to be sent to an
explicit log output like syslog, stderr or the journal. The
global log buffer is thus just duplicating this data on stderr
upon crash.

The log_buffer_size config parameter is left in the augeas
lens to prevent breakage for users on upgrade. It is however
completely ignored hereafter.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:22 +00:00
Daniel P. Berrange
975b2392c3 Switch to filtering based on log source name instead of filename
Currently the log filter strings are used in a string comparison
against the source filename each time log message is emitted.
If no log filters at all are set, there's obviously no string
comparison to be done. If any single log filter is set though,
this imposes a compute burden on every logging call even if logs
from the file in question are disabled. This string comparison
must also be done while the logging mutex is held, which has
implications for concurrency when multiple threads are emitting
log messages.

This changes the log filtering to be done based on the virLogSource
object name. The virLogSource struct is extended to contain
'serial' and 'priority' fields. Any time the global log filter
rules are changed a global serial number is incremented. When a
log message is emitted, the serial in the virLogSource instance
is compared with the global serial number. If out of date, then
the 'priority' field in the virLogSource instance is updated based
on the new filter rules. The 'priority' field is checked to see
whether the log message should be sent to the log outputs.

The comparisons of the 'serial' and 'priority' fields are done
with no locks held. So in the common case each logging call has
an overhead of 2 integer comparisons, with no locks held. Only
if the decision is made to forward the message to the log output,
or if the 'serial' value is out of date do locks need to be
acquired.

Technically the comparisons of the 'serial' and 'priority' fields
should be done with locks held, or using atomic operations. Both
of these options have a notable performance impact, however, and
since all writes a protected by a global mutex, it is believed
that worst case behaviour where the fields are read concurrently
with being written would merely result in an mistaken emission
or dropping of the log message in question. This is an acceptable
tradeoff for the performance benefit of avoiding locking.

As a quick benchmark, a demo program that registers 500 file
descriptors with the event loop (eg equiv of 500 QEMU monitor
commands), creates pending read I/O on every FD, and then runs
virEventRunDefaultImpl() took 4.6 seconds to do 51200 iterations.
After this optimization it only takes 3.3 seconds, with the log
APIs no longer being a relevant factor in the running time.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:22 +00:00
Daniel P. Berrange
2835c1e730 Add virLogSource variables to all source files
Any source file which calls the logging APIs now needs
to have a VIR_LOG_INIT("source.name") declaration at
the start of the file. This provides a static variable
of the virLogSource type.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:22 +00:00
Daniel P. Berrange
098dd79ee2 Turn virLogSource into a struct instead of an enum
As part of the goal to get away from doing string matching on
filenames when deciding whether to emit a log message, turn
the virLogSource enum into a struct which contains a log
"name". There will eventually be one virLogSource instance
statically declared per source file. To minimise churn in this
commit though, a single global instance is used.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:22 +00:00
Daniel P. Berrange
b29275d928 Move dtrace probe macros into separate header file
The dtrace probe macros rely on the logging API. We can't make
the internal.h header include the virlog.h header though since
that'd be a circular include. Instead simply split the dtrace
probes into their own header file, since there's no compelling
reason for them to be in the main internal.h header.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:21 +00:00
Daniel P. Berrange
3887c5d83b Refactor code that skips logging of error messages
The error reporting code will invoke a callback when any error
is raised and the default callback will print to stderr. The
virRaiseErrorFull method also sends all error messages on to the
logging code, which also prints to stderr by default. To avoid
duplicated data on stderr, the logging code has some logic to
skip emission when no log outputs are configured, which checks
whether the virLogSource == VIR_LOG_FROM_ERROR.

Meanwhile the libvirtd daemon can register another callback which
is used to reduce log message priority from error to a lower level.
When this is used we do want messages to end up on stderr, so the
error code will conditionally use either VIR_LOG_FROM_FILE or
VIR_LOG_FROM_ERROR depending on whether such a callback is provided.

This will all complicate later refactoring. By pushing the checks
for whether a log output is present up a level into the error code,
the special cases can be isolated in one place.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:21 +00:00
Daniel P. Berrange
27f2edf96c Reduce performance overhead of the global log buffer
With the vast number of log debug statements in the code, the
logging framework has a measurable performance impact on libvirt
code, particularly in the daemon event loop.

The global log buffer records every single log message triggered
whether anyone cares to see them or not. This makes it impossible
to eliminate the overhead of printf format expansions in any of
the logging code. It is possible to disable the global log buffer
in libvirtd itself, but this doesn't help client side library
code. Also even if disabled by the config file, the existence of
the feature makes other performance improvements in the logging
layer impossible.

Instead of logging every single message to the global buffer, only
log messages that pass the log filters. This if libvirtd is set
to have log_filters="1:libvirt 1:qemu" the global log buffer will
only get filled with those messages instead of everything. This
reduces the performance burden, as well as improving the signal
to noise ratio of the log buffer.

As a quick benchmark, a demo program that registers 500 file
descriptors with the event loop (eg equiv of 500 QEMU monitor
commands), creates pending read I/O on every FD, and then runs
virEventRunDefaultImpl() took 1 minute 40 seconds to do 51200
iterations with nearly all the time shown against the logging
code. After this optimization it only takes 4.6 seconds.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-18 14:29:21 +00:00
Martin Kletzander
cc9c62fef9 Require spaces around equality comparisons
Commit a1cbe4b5 added a check for spaces around assignments and this
patch extends it to checks for spaces around '=='.  One exception is
virAssertCmpInt where comma after '==' is acceptable (since it is a
macro and '==' is its argument).

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-03-18 11:29:44 +01:00
Nehal J Wani
2250a2b5d2 Add parameter to wait for lock in file locking APIs
Our current pidfile acquire APis (virPidFileAcquire) simply return -1 upon
failure to acquire a lock. This patch adds a parameter 'bool waitForLock'
which instructs the APIs if we want to make it block and wait for the lock
or not.
2014-03-17 10:04:47 -06:00
Roman Bogorodskiy
075650ff40 qemu: cleanup tap devices on FreeBSD
We have to explicitly destroy TAP devices on FreeBSD because
they're not freed after being closed, otherwise we end up with
orphaned TAP devices after destroying a domain.
2014-03-14 15:45:51 +01:00
Laine Stump
3f05dc6de8 util: eliminate hardcoded indent in virConnectSysInfo formatting
This same set of functions is used by the qemu, xen, and lxc drivers'
connectSysInfo function.
2014-03-14 00:02:42 -06:00
Jim Fehlig
b322717f6e hostdev: add virObject field to virHostdevManager struct
Commit 6b306d66 converted virHostdevManager to a virObject, but
missed adding a virObject field to the virHostdevManager struct.
Result is memory corruption when taking a reference on an instance
of the object, where atomic inc is done on the stateDir field.
Later use of stateDir crashes libvirtd.
2014-03-13 08:41:43 -06:00
Nehal J Wani
03fc0c626d vircrypto: fix Invalid write in virCryptoHashString()
While running vircryptotest, it was found that valgrind pointed out the
following error:

==27453== Invalid write of size 1
==27453==    at 0x4C7D7C9: virCryptoHashString (vircrypto.c:76)
==27453==    by 0x401C4E: testCryptoHash (vircryptotest.c:41)
==27453==    by 0x402A11: virtTestRun (testutils.c:199)
==27453==    by 0x401AD5: mymain (vircryptotest.c:76)
==27453==    by 0x40318D: virtTestMain (testutils.c:782)
==27453==    by 0x3E6CE1ED1C: (below main) (libc-start.c:226)
==27453==  Address 0x51f0541 is 0 bytes after a block of size 65 alloc'd
==27453==    at 0x4A0577B: calloc (vg_replace_malloc.c:593)
==27453==    by 0x4C69F2E: virAllocN (viralloc.c:189)
==27453==    by 0x4C7D76B: virCryptoHashString (vircrypto.c:69)
==27453==    by 0x401C4E: testCryptoHash (vircryptotest.c:41)
==27453==    by 0x402A11: virtTestRun (testutils.c:199)
==27453==    by 0x401AD5: mymain (vircryptotest.c:76)
==27453==    by 0x40318D: virtTestMain (testutils.c:782)
==27453==    by 0x3E6CE1ED1C: (below main) (libc-start.c:226)
==27453==

...and many more.  Two observations: hashstrlen was already set
to include the trailing NUL byte (so writing to hashstrlen as
the array offset was indeed writing one byte beyond bounds), and
VIR_ALLOC_N already guarantees zero-initialization (so we already
have a trailing NUL without needing to explicitly write one).

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-12 16:01:30 -06:00
Ján Tomko
f14c8a6be5 Fix type mismatch of virNetDev*NetConfig on non-Linux
Commit b4bbaee changed char* to const char*, but omitted
the non-Linux version.
2014-03-12 18:17:39 +01:00
Chunyan Liu
98c5c53d69 add hostdev pci backend type for xen
Add VIR_DOMAIN_HOSTDEV_PCI_BACKEND_XEN. For legacy xen, it will use "pciback" as
stub driver.
2014-03-12 17:03:23 +00:00
Chunyan Liu
7becc46225 Add parameter checks/annotations to hostdev APIs
Mark many parameters as NONNULL and check for empty list of
hostdevs.
2014-03-12 16:53:33 +00:00
Chunyan Liu
e991b09ddd add 3 wrapper functions for prepare/reattach/update domain hostdevs 2014-03-12 16:53:20 +00:00
Chunyan Liu
4dd9f103fa improve virHostdevUpdate* parameters to make it more widely used
Changes parameter from vm def to specific hostdevs info and name info, so that
it could be used more widely, e.g, could be used without full vm def info.
2014-03-12 16:41:32 +00:00
Daniel P. Berrange
a65e6d3626 Capitalize USB, PCI and SCSI in hostdev variables
Change any variable names with Usb, Pci or Scsi to use
USB, PCI and SCSI since they are abbreviations.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-12 16:38:18 +00:00
Daniel P. Berrange
e9a60dcc7c Remove redundant duplicated 'Hostdev' string method names
Some virHostdevXXXX methods included the string Hostdev again
as a suffix. Change the latter to Device instead.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-12 16:35:30 +00:00
Chunyan Liu
7be4bddea1 Capitalize USB, PCI and SCSI in hostdev methods
Change any method names with Usb, Pci or Scsi to use
USB, PCI and SCSI since they are abbreviations.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-12 16:20:01 +00:00
Daniel P. Berrange
b4bbaeef41 Fixed const-ness of parameters in netdev/hostdev code
Various methods in virnetdev.c and virhostdev.c were missing
const-ness for several char * parameters.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-12 16:03:06 +00:00
Chunyan Liu
1c6ee84c9d improve parameter name to let it more meaningful 2014-03-12 16:03:06 +00:00
Chunyan Liu
1fabf06ca5 move virHostdevNodeDevice* to virhostdev.c 2014-03-12 16:03:06 +00:00
Chunyan Liu
a4797138ad move virHostdevReAttachHostScsiDevices to virhostdev.c 2014-03-12 16:03:06 +00:00
Chunyan Liu
2d961cf3ba move virHostdevReAttachUsbHostdevs to virhostdev.c 2014-03-12 16:03:05 +00:00
Chunyan Liu
5035f75fed move virHostdevPrepareHostSCSIDevices to virhostdev.c 2014-03-12 16:03:05 +00:00
Chunyan Liu
1c310c609c move virHostdevPrepareHostUSBDevices to virhostdev.c 2014-03-12 16:03:05 +00:00
Chunyan Liu
00729f4559 move virHostdevUpdate* functions to virhostdev.c 2014-03-12 16:03:05 +00:00
Chunyan Liu
899b261127 move virHostdevPrepare(ReAttach)PCIDevices to virhostdev.c 2014-03-12 16:03:05 +00:00
Chunyan Liu
6b306d66fa virhostdev: use virObject to virHostdevManager to keep reference
Use virObject to virHostdevManager, so that each driver using virHostdevManager
can keep a reference to it, and through counting refs to make virHostdevManager
get freed.
2014-03-12 16:03:04 +00:00
Ján Tomko
7b91dc3ecd Introduce vircommandpriv.h for functions used by tests
So far it's just virCommandSetDryRun.
2014-03-12 15:53:16 +01:00
Eric Blake
e686ce8aa2 iptables: don't log command probe failures
Commit b9dd878f caused a regression in iptables interaction by
logging non-zero status at a higher level than VIR_INFO.  Revert
that portion of the commit, as well as adding a comment explaining
why we check the status ourselves.

Reported by Nehal J Wani.

* src/util/viriptables.c (virIpTablesOnceInit): Undo log regression.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-11 17:43:47 -06:00
Daniel P. Berrange
dafa39adbc Remove unused ebtablesRemoveForwardPolicyReject method
The ebtablesRemoveForwardPolicyReject method was unused and
would not do anything useful even if called.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:52 +00:00
Daniel P. Berrange
6e69008f3e Remove worthless ebtRules data structure
The ebtRules data structure serves no useful purpose as
the table name is never used and only 1 single chain name
needs to be stored. Just store the chain name directly
in the ebtablesContext instead.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:52 +00:00
Daniel P. Berrange
78629cf531 Remove data structure holding list of ebtables rules
When adding/removing ebtables rules, the code would keep
an array of all rules in memory. This list of rules was
never used for any purpose and would be lost if libvirtd
restarted. Delete all the unused code.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:52 +00:00
Daniel P. Berrange
ca3dafef41 Remove unused variables from ebtablesContext
The input_filter and nat_postrouting variables were never
used to create any firewall rules.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:51 +00:00
Daniel P. Berrange
c383e13a37 Make ebtablesForwardPolicyReject static
The ebtablesForwardPolicyReject method is only used internally
to the ebtables code and thus should have been static.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:51 +00:00
Daniel P. Berrange
184d464661 Remove decl of method which doesn't exist in virebtables.h
There is no impl of the ebtablesSaveRules method and nothing
attempts to use it.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:51 +00:00
Daniel P. Berrange
10ec072545 Add helper APIs to track if libvirtd or loadable modules have changed
The future QEMU capabilities cache needs to be able to invalidate
itself if the libvirtd binary or any loadable modules are changed
on disk. Record the 'ctime' value for these binaries and provide
helper APIs to query it. This approach assumes that if libvirt.so
is changed, then libvirtd will also change, which should usually
be the case with libtool's wrapper scripts that cause libvirtd to
get re-linked

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 10:51:49 +00:00
Daniel P. Berrange
3a7fe8d508 Add helper APIs for generating cryptographic hashes
GNULIB provides APIs for calculating md5 and sha256 hashes,
but these APIs only return you raw byte arrays. Most users
in libvirt want the hash in printable string format. Add
some helper APIs in util/vircrypto.{c,h} for doing this.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-10 16:39:18 +00:00
Ján Tomko
9b9d7704b5 Change file names in comments to match the files they are in
Some of these are leftovers from renaming the files, others
are just typos.

Also introduce an ugly awk script to enforce this.
2014-03-10 14:26:04 +01:00
Michal Privoznik
fb9bec1055 src/util: Utilize more of VIR_(APPEND|INSERT|DELETE)_ELEMENT
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-03-10 13:45:11 +01:00
John Ferlan
ea1eadd6a3 virscsi: Introduce virSCSIDeviceUsedByInfoFree
This resolves a Coverity RESOURCE_LEAK issue introduced by commit
id 'de6fa535' where the virSCSIDeviceSetUsedBy() didn't VIR_FREE
the 'copy' or possibly VIR_STRDUP()'d values.  It also ensures that
the VIR_APPEND_ELEMENT is successful...
2014-03-07 12:24:44 -05:00
Michael Chapman
1af9800b55 virIdentityGetSystem: don't fail if SELinux is disabled
If SELinux is compiled into libvirt but it is disabled on the host,
libvirtd logs:

  error : virIdentityGetSystem:173 : Unable to lookup SELinux process
  context: Invalid argument

on each and every client connection.

Use is_selinux_enabled() to skip retrieval of the process's SELinux
context if SELinux is disabled.

Signed-off-by: Michael Chapman <mike@very.puzzling.org>
2014-03-07 15:01:33 +01:00
Chunyan Liu
6b4c0a635e add virhostdev files to maintain global state of host devices
Signed-off-by: Chunyan Liu <cyliu@suse.com>
2014-03-04 12:28:45 +00:00
Chunyan Liu
de6fa535b0 add 'driver' info to used_by
Specify which driver and which domain in used_by area to avoid conflict among
different drivers.

Signed-off-by: Chunyan Liu <cyliu@suse.com>
2014-03-04 12:24:13 +00:00
Ján Tomko
12ee0b98d3 Check if systemd is running before creating machines
If systemd is installed, but is not the init system,
systemd-machined fails with an unhelpful error message:
Launch helper exited with unknown return code 1

Currently we only check if the "machine1" service is
available (in ListActivatableNames).
Also check if "systemd1" service is registered with DBus
(ListNames).

This fixes https://bugs.gentoo.org/show_bug.cgi?id=493246#c22
2014-03-04 09:14:52 +01:00
Ján Tomko
65a4cb03c7 Split out most of virDBusIsServiceEnabled
Introduce virDBusIsServiceInList which can be used to call other
methods for listing services (ListNames), not just ListActivatableNames.

No functional change, fixed the 'Retruns' typo.
2014-03-04 09:14:52 +01:00
Eric Blake
25f87817ab virFork: simplify semantics
The old semantics of virFork() violates the priciple of good
usability: it requires the caller to check the pid argument
after use, *even when virFork returned -1*, in order to properly
abort a child process that failed setup done immediately after
fork() - that is, the caller must call _exit() in the child.
While uses in virfile.c did this correctly, uses in 'virsh
lxc-enter-namespace' and 'virt-login-shell' would happily return
from the calling function in both the child and the parent,
leading to very confusing results. [Thankfully, I found the
problem by inspection, and can't actually trigger the double
return on error without an LD_PRELOAD library.]

It is much better if the semantics of virFork are impossible
to abuse.  Looking at virFork(), the parent could only ever
return -1 with a non-negative pid if it misused pthread_sigmask,
but this never happens.  Up until this patch series, the child
could return -1 with non-negative pid if it fails to set up
signals correctly, but we recently fixed that to make the child
call _exit() at that point instead of forcing the caller to do
it.  Thus, the return value and contents of the pid argument are
now redundant (a -1 return now happens only for failure to fork,
a child 0 return only happens for a successful 0 pid, and a
parent 0 return only happens for a successful non-zero pid),
so we might as well return the pid directly rather than an
integer of whether it succeeded or failed; this is also good
from the interface design perspective as users are already
familiar with fork() semantics.

One last change in this patch: before returning the pid directly,
I found cases where using virProcessWait unconditionally on a
cleanup path of a virFork's -1 pid return would be nicer if there
were a way to avoid it overwriting an earlier message.  While
such paths are a bit harder to come by with my change to a direct
pid return, I decided to keep the virProcessWait change in this
patch.

* src/util/vircommand.h (virFork): Change signature.
* src/util/vircommand.c (virFork): Guarantee that child will only
return on success, to simplify callers.  Return pid rather than
status, now that the situations are always the same.
(virExec): Adjust caller, also avoid open-coding process death.
* src/util/virprocess.c (virProcessWait): Tweak semantics when pid
is -1.
(virProcessRunInMountNamespace): Adjust caller.
* src/util/virfile.c (virFileAccessibleAs, virFileOpenForked)
(virDirCreate): Likewise.
* tools/virt-login-shell.c (main): Likewise.
* tools/virsh-domain.c (cmdLxcEnterNamespace): Likewise.
* tests/commandtest.c (test23): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:32 -07:00
Eric Blake
b9dd878ff8 util: make it easier to grab only regular command exit
Auditing all callers of virCommandRun and virCommandWait that
passed a non-NULL pointer for exit status turned up some
interesting observations.  Many callers were merely passing
a pointer to avoid the overall command dying, but without
caring what the exit status was - but these callers would
be better off treating a child death by signal as an abnormal
exit.  Other callers were actually acting on the status, but
not all of them remembered to filter by WIFEXITED and convert
with WEXITSTATUS; depending on the platform, this can result
in a status being reported as 256 times too big.  And among
those that correctly parse the output, it gets rather verbose.
Finally, there were the callers that explicitly checked that
the status was 0, and gave their own message, but with fewer
details than what virCommand gives for free.

So the best idea is to move the complexity out of callers and
into virCommand - by default, we return the actual exit status
already cleaned through WEXITSTATUS and treat signals as a
failed command; but the few callers that care can ask for raw
status and act on it themselves.

* src/util/vircommand.h (virCommandRawStatus): New prototype.
* src/libvirt_private.syms (util/command.h): Export it.
* docs/internals/command.html.in: Document it.
* src/util/vircommand.c (virCommandRawStatus): New function.
(virCommandWait): Adjust semantics.
* tests/commandtest.c (test1): Test it.
* daemon/remote.c (remoteDispatchAuthPolkit): Adjust callers.
* src/access/viraccessdriverpolkit.c (virAccessDriverPolkitCheck):
Likewise.
* src/fdstream.c (virFDStreamCloseInt): Likewise.
* src/lxc/lxc_process.c (virLXCProcessStart): Likewise.
* src/qemu/qemu_command.c (qemuCreateInBridgePortWithHelper):
Likewise.
* src/xen/xen_driver.c (xenUnifiedXendProbe): Simplify.
* tests/reconnect.c (mymain): Likewise.
* tests/statstest.c (mymain): Likewise.
* src/bhyve/bhyve_process.c (virBhyveProcessStart)
(virBhyveProcessStop): Don't overwrite virCommand error.
* src/libvirt.c (virConnectAuthGainPolkit): Likewise.
* src/openvz/openvz_driver.c (openvzDomainGetBarrierLimit)
(openvzDomainSetBarrierLimit): Likewise.
* src/util/virebtables.c (virEbTablesOnceInit): Likewise.
* src/util/viriptables.c (virIpTablesOnceInit): Likewise.
* src/util/virnetdevveth.c (virNetDevVethCreate): Fix debug
message.
* src/qemu/qemu_capabilities.c (virQEMUCapsInitQMP): Add comment.
* src/storage/storage_backend_iscsi.c
(virStorageBackendISCSINodeUpdate): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:32 -07:00
Eric Blake
c72e76c3d9 util: make it easier to grab only regular process exit
Right now, a caller waiting for a child process either requires
the child to have status 0, or must use WIFEXITED() and friends
itself.  But in many cases, we want the middle ground of treating
fatal signals as an error, and directly accessing the normal exit
value without having to use WEXITSTATUS(), in order to easily
detect an expected non-zero exit status.  This adds the middle
ground to the low-level virProcessWait; the next patch will add
it to virCommand.

* src/util/virprocess.h (virProcessWait): Alter signature.
* src/util/virprocess.c (virProcessWait): Add parameter.
(virProcessRunInMountNamespace): Adjust caller.
* src/util/vircommand.c (virCommandWait): Likewise.
* src/util/virfile.c (virFileAccessibleAs): Likewise.
* src/lxc/lxc_container.c (lxcContainerHasReboot)
(lxcContainerAvailable): Likewise.
* daemon/libvirtd.c (daemonForkIntoBackground): Likewise.
* tools/virt-login-shell.c (main): Likewise.
* tools/virsh-domain.c (cmdLxcEnterNamespace): Likewise.
* tests/testutils.c (virtTestCaptureProgramOutput): Likewise.
* tests/commandtest.c (test23): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:31 -07:00
Eric Blake
8b24a803ad util: preserve exit status from mount namespace callback
The documentation of namespace callbacks was inconsistent on whether
it preserved positive return values.  Now that we have a dedicated
EXIT_CANCELED to flag all errors before getting to the callback,
it is possible to use positive return values (not that any of the
current callers do, but it is better to match the docs).

Also, while vircommand.c is careful to close fds that a child should
not have, it's still better to be in the practice of setting
FD_CLOEXEC up front.

* src/util/virprocess.c (virProcessRunInMountNamespace): Tweak
return value to pass back non-zero status.  Avoid leaking pipe fds
to other threads.
* src/util/virprocess.h: Fix comment.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:31 -07:00
Eric Blake
2b4f162eb4 util: make it easier to reflect child exit status
Thanks to namespaces, we have a couple of places in the code
base that want to reflect a child exit status, including the
ability to detect death by a signal, back to a grandparent.
Best to make it a reusable function.

* src/util/virprocess.h (virProcessExitWithStatus): New prototype.
* src/libvirt_private.syms (util/virprocess.h): Export it.
* src/util/virprocess.c (virProcessExitWithStatus): New function.
* tests/commandtest.c (test23): Test it.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:31 -07:00
Eric Blake
631923e7f2 virFork: give specific status on failure prior to exec
When a child fails without exec'ing, we want a well-known status;
best is to match what env(1), nice(1), su(1), and other wrapper
programs do.  This patch adds enum values that later patches will
use, and sets up virFork as the first client of EXIT_CANCELED
for errors detected prior to even attempting exec, as well as
virExec to distinguish between a missing executable vs. a binary
that cannot be executed.

This is a slight semantic change in the unlikely case of a child
process failing to restore its signal mask - we now kill the
child with a known status instead of relying on the caller to
notice and do an appropriate _exit().  A subsequent patch will
make further cleanups based on an audit of all callers.

* src/internal.h (EXIT_CANCELED, EXIT_CANNOT_INVOKE)
(EXIT_ENOENT): New enum.
* src/util/vircommand.c (virFork): Document specific exit value if
child aborts early.
(virExec): Distinguish between various exec failures.
* tests/commandtest.c (test1): Enhance test.
(test22): New test.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-03-03 12:40:31 -07:00
Daniel P. Berrange
f223b96051 Add comments describing the different log sources
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-28 17:38:46 +00:00
Daniel P. Berrange
0915053e97 Include error domain and code in log messages from errors
When a virError is raised, pass the error domain and code
onto the systemd journald using metadata fields.

This allows error messages to be queried by code eg

  $ journalctl LIBVIRT_CODE=43

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-28 17:38:46 +00:00
Daniel P. Berrange
21d370f0b9 Fix journald PRIORITY values
The systemd journal expects log record PRIORITY values to
be encoded using the syslog compatible numbering scheme,
not libvirt's own native numbering scheme. We must therefore
apply a conversion.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-28 17:37:38 +00:00
Daniel P. Berrange
54209df345 Send virLogMetadata fields onto the journal
The systemd journal accepts arbitrary user specified log
fields. These can be passed into virLogMessage via the
virLogMetadata structure. Allow up to 5 custom fields to
be reported by libvirt callers.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-28 17:37:38 +00:00
Nehal J Wani
969493f91d Fix memory leak in virSCSIDeviceListDel()
While running virscsitest, it was found that valgrind pointed out the following
memory leak:

==320== 5 bytes in 1 blocks are definitely lost in loss record 4 of 37
==320==    at 0x4A069EE: malloc (vg_replace_malloc.c:270)
==320==    by 0x3E6CE81171: strdup (strdup.c:43)
==320==    by 0x4CB28DF: virStrdup (virstring.c:554)
==320==    by 0x4CAC987: virSCSIDeviceSetUsedBy (virscsi.c:289)
==320==    by 0x402321: test2 (virscsitest.c:100)
==320==    by 0x403231: virtTestRun (testutils.c:199)
==320==    by 0x402121: mymain (virscsitest.c:180)
==320==    by 0x4039AD: virtTestMain (testutils.c:782)
==320==    by 0x3E6CE1ED1C: (below main) (libc-start.c:226)
==320==

Introduced by commit fd243fc.
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2014-02-26 11:41:40 +01:00
Michal Privoznik
c0d162c68c virNetDevVethCreate: Serialize callers
Consider dozen of LXC domains, each of them having this type of interface:

    <interface type='network'>
      <mac address='52:54:00:a7:05:4b'/>
      <source network='default'/>
    </interface>

When starting these domain in parallel, all workers may meet in
virNetDevVethCreate() where a race starts. Race over allocating veth
pairs because allocation requires two steps:

  1) find first nonexistent '/sys/class/net/vnet%d/'
  2) run 'ip link add ...' command

Now consider two threads. Both of them find N as the first unused veth
index but only one of them succeeds allocating it. The other one fails.
For such cases, we are running the allocation in a loop with 10 rounds.
However this is very flaky synchronization. It should be rather used
when libvirt is competing with other process than when libvirt threads
fight each other. Therefore, internally we should use mutex to serialize
callers, and do the allocation in loop (just in case we are competing
with a different process). By the way we have something similar already
since 1cf97c87.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-26 08:50:47 +01:00
Eric Blake
fa2e4dbfd6 build: fix cgroups on non-Linux
Running ./autobuild.sh detected a mingw failure:

  CCLD     libvirt.la
Cannot export virCgroupGetPercpuStats: symbol not defined
Cannot export virCgroupSetOwner: symbol not defined

* src/util/vircgroup.c (virCgroupGetPercpuStats)
(virCgroupSetOwner): Implement stubs.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-02-25 17:38:46 -07:00
Richard Weinberger
6fb42d7cdc Ensure systemd cgroup ownership is delegated to container with userns
This function is needed for user namespaces, where we need to chmod()
the cgroup to the initial uid/gid such that systemd is allowed to
use the cgroup.

Signed-off-by: Richard Weinberger <richard@nod.at>
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-24 15:35:47 +00:00
Daniel P. Berrange
66e3a3e914 Add virStringReplace method for substring replacement
Add a virStringReplace method to virstring.{h,c} to perform
substring matching and replacement

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-24 10:51:22 +00:00
Manuel VIVES
12aa71dfde Add virStringSearch method for regex matching
Add a virStringSearch method to virstring.{c,h} which performs
a regex match against a string and returns the matching substrings.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-24 10:46:28 +00:00
Michal Privoznik
68954fb25c virNetServerRun: Notify systemd that we're accepting clients
Systemd does not forget about the cases, where client service needs to
wait for daemon service to initialize and start accepting new clients.
Setting a dependency in client is not enough as systemd doesn't know
when the daemon has initialized itself and started accepting new
clients. However, it offers a mechanism to solve this. The daemon needs
to call a special systemd function by which the daemon tells "I'm ready
to accept new clients". This is exactly what we need with
libvirtd-guests (client) and libvirtd (daemon). So now, with this
change, libvirt-guests.service is invoked not any sooner than
libvirtd.service calls the systemd notify function.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-24 10:54:48 +01:00
Michal Privoznik
ba79e3879e virSystemdCreateMachine: Set dependencies for slices
https://bugzilla.redhat.com/show_bug.cgi?id=1031696

When creating a new domain, we let systemd know about it by calling
CreateMachine() function via dbus. Systemd then creates a scope and
places domain into it. However, later when the host is shutting
down, systemd computes the shutdown order to see what processes can
be shut down in parallel. And since we were not setting
dependencies at all, the slices (and thus domains) were most likely
killed before libvirt-guests.service. So user domains that had to
be saved, shut off, whatever were in fact killed.  This problem can
be solved by letting systemd know that scopes we're creating must
not be killed before libvirt-guests.service.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-24 10:21:00 +01:00
Ján Tomko
abf1daf0d7 Add a stub for virCgroupGetDomainTotalCpuStats
Commit 6515889 broke the build on FreeBSD:
In function `qemuDomainGetCPUStats':
/../../src/qemu/qemu_driver.c:16102:
undefined reference to `virCgroupGetDomainTotalCpuStats'
2014-02-21 09:10:48 +01:00
Thorsten Behrens
4b3b2f6ceb Implement domainGetCPUStats for lxc driver. 2014-02-20 16:20:09 +01:00
Thorsten Behrens
65158899b7 Make qemuGetDomainTotalCPUStats a virCgroup function.
To reuse this from other drivers, like lxc.
2014-02-20 16:20:09 +01:00
Thorsten Behrens
a2bb187c7e Add util virCgroupGetBlkioIo*Serviced methods.
This reads blkio stats from blkio.throttle.io_service_bytes and
blkio.throttle.io_serviced.
2014-02-20 16:20:09 +01:00
Ján Tomko
057d26b2ac Fix build of portallocator on mingw
IN6ADDR_ANY_INIT does not seem to be working as expected on MinGW:
error: missing braces around initializer [-Werror=missing-braces]
         .sin6_addr = IN6ADDR_ANY_INIT,

Use the in6addr_any variable instead.

Reported by Daniel P. Berrange.
2014-02-20 10:16:07 +01:00
Roman Bogorodskiy
0eb4a5f4f1 bhyve: add a basic driver
At this point it has a limited functionality and is highly
experimental. Supported domain operations are:

  * define
  * start
  * destroy
  * dumpxml
  * dominfo

It's only possible to have only one disk device and only one
network, which should be of type bridge.
2014-02-19 14:21:50 +00:00
Li Zhang
b39275954b conf: Remove the implicit PS2 devices for non-X86 platforms
PS2 devices only work on X86 platform, other platforms may need
USB devices instead. Athough it doesn't influence the QEMU command line,
it's not right to add PS2 mouse/keyboard for non-X86 platform.

Signed-off-by: Li Zhang <zhlcindy@linux.vnet.ibm.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2014-02-19 09:16:31 +01:00
Ján Tomko
adc8b2afbb Fix conflicting types of virInitctlSetRunLevel
aebbcdd didn't change the non-linux definition of the function,
breaking the build on FreeBSD:

../../src/util/virinitctl.c:164: error: conflicting types for
'virInitctlSetRunLevel'
../../src/util/virinitctl.h:40: error: previous declaration of
'virInitctlSetRunLevel' was here
2014-02-18 15:05:06 +01:00
Michal Privoznik
f1ab06e43d network: Introduce network hooks
There might be some use cases, where user wants to prepare the host or
its environment prior to starting a network and do some cleanup after
the network has been shut down. Consider all the functionality that
libvirt doesn't currently have as an example what a hook script can
possibly do.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-18 14:46:49 +01:00
Eric Blake
aebbcdd33c CVE-2013-6456: Avoid unsafe use of /proc/$PID/root in LXC shutdown/reboot code
Use helper virProcessRunInMountNamespace in lxcDomainShutdownFlags and
lxcDomainReboot.  Otherwise, a malicious guest could use symlinks
to force the host to manipulate the wrong file in the host's namespace.

Idea by Dan Berrange, based on an initial report by Reco
<recoverym4n@gmail.com> at
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=732394

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-02-18 12:59:02 +00:00
Daniel P. Berrange
7c72ef6f55 Add helper for running code in separate namespaces
Implement virProcessRunInMountNamespace, which runs callback of type
virProcessNamespaceCallback in a container namespace. This uses a
child process to run the callback, since you can't change the mount
namespace of a thread. This implies that callbacks have to be careful
about what code they run due to async safety rules.

Idea by Dan Berrange, based on an initial report by Reco
<recoverym4n@gmail.com> at
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=732394

Signed-off-by: Daniel Berrange <berrange@redhat.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2014-02-18 12:45:41 +00:00
Daniel P. Berrange
c321bfc5c3 Add virFileMakeParentPath helper function
Add a helper function which takes a file path and ensures
that all directory components leading up to the file exist.
IOW, it strips the filename part of the path and passes
the result to virFileMakePath.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-02-18 12:39:06 +00:00
Ján Tomko
0ee9081215 Support IPv6 in port allocator
Also try to bind on IPv6 to check if the port is occupied.

Change the mocked bind in the test to return EADDRINUSE
for some ports only for the IPv4/IPv6 socket if we're testing
on a host with IPv6 compiled in.

Also mock socket() to make it fail with EAFNOTSUPPORTED
if LIBVIRT_TEST_IPV4ONLY is set in the environment, to
simulate a host without IPv6 support in the kernel. The
tests are repeated again with this variable set.

https://bugzilla.redhat.com/show_bug.cgi?id=1025407
2014-02-14 13:18:35 +01:00
Ján Tomko
531bc0bbd0 Split out bind() from virPortAllocatorAcquire 2014-02-14 13:18:35 +01:00
Cédric Bosdonnat
3daa14834a Improve virConf parse to handle LXC config format
virConf now honours a VIR_CONF_FLAG_LXC_FORMAT flag to handle LXC
configuration files. The differences are that property names can
contain '.' character and values are all strings without any bounding
quotes.

Provide a new virConfWalk function calling a handler on all non-comment
values. This function will be used by the LXC conversion code to loop
over LXC configuration lines.
2014-02-12 17:52:46 +00:00
Cédric Bosdonnat
d385239260 Fixed build with clang.
Two unused global variables, and DBUS_TYPE_INVALID used as a const
char*.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-02-12 06:36:17 -07:00
Laine Stump
0144d72963 build: correctly check for SOICGIFVLAN GET_VLAN_VID_CMD command
In order to make a client-only build successful on RHEL4 (yes, you
read that correctly!), commit 3ed2e54 modified src/util/virnetdev.c so
that the functional version of virNetDevGetVLanID() was only compiled
if GET_VLAN_VID_CMD was defined. However, it is *never* defined, but
is only an enum value, so the proper version was no longer compiled
even on platforms that support it. This resulted in the vlan tag not
being properly set for guest traffic on VEPA mode guest macvtap
interfaces that were bound to a vlan interface (that's the only place
that libvirt currently uses virNetDevGetVLanID)

Since there is no way to compile conditionally based on the presence
of an enum value, this patch modifies configure.ac to check for said
enum value with AC_CHECK_DECLS(), which #defines
HAVE_DECL_GET_VLAN_VID_CMD to 1 if it's successful compiling a test
program that uses GET_VLAN_VID_CMD (and still #defines it, but to 0,
if it's not successful).  We can then make the compilation of
virNetDevGetVLanID() conditional on the value of
HAVE_DECL_GET_VLAN_VID_CMD.
2014-02-11 01:43:38 +02:00
John Ferlan
b60644f38f virpci: Resolve coverity issues
Coverity complains about "USE_AFTER_FREE" due to how virPCIDeviceSetStubDriver
"could" return either -1, 0, or 1 from the VIR_STRDUP() and then possibly makes
a call to virPCIDeviceDetach().

The only way this could happen is if NULL were passed as the "driver" name
and virStrdup() returned 0.  Since the calling functions check < 0 on the
initial function call, the 0 possibility causes Coverity to complain.

To fix this - enforce that the second parameter is not NULL using
ATTRIBUTE_NONNULL(2) for the function prototype, then in virPCIDeviceDetach
add an sa_assert(dev->stubDriver). This will result in Coverity not complaining
any more.
2014-02-07 10:58:24 -05:00
John Ferlan
19259574d5 Honor blacklist for modprobe command
https://bugzilla.redhat.com/show_bug.cgi?id=1045124

When loading modules, libvirt does not honor the modprobe blacklist.
Use the new virKModLoad() API in order to attempt load with blacklist check.
Use the new virKModIsBlacklisted() API to check if the failure to load
was due to the blacklist

Signed-off-by: John Ferlan <jferlan@redhat.com>
2014-02-04 10:43:53 -05:00
John Ferlan
4a2179ea92 utils: Introduce functions for kernel module manipulation
virKModConfig()        - Return a buffer containing kernel module configuration
virKModLoad()          - Load a specific module into the kernel configuration
virKModUnload()        - Unload a specific module from the kernel configuration
virKModIsBlacklisted() - Determine whether a module is blacklisted within
                         the kernel configuration
2014-02-04 08:52:27 -05:00
Daniel P. Berrange
0240d94c36 Remove windows thread implementation in favour of pthreads
There are a number of pthreads impls available on Win32
these days, in particular the mingw64 project has a good
impl. Delete the native windows thread implementation and
rely on using pthreads everywhere.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-01-30 18:00:20 +00:00
Daniel P. Berrange
c065984b58 Add a read/write lock implementation
Add virRWLock backed up by a POSIX rwlock primitive

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-01-30 18:00:20 +00:00
Osier Yang
b1b81efe9a util: Accept test data path for scsi device's sg_path
Commit 10c9ceff6d intended to introduce new argument for the
testing purpose, but it missed the similar changing of the
device's sg_path. The problem was hidden since my laptop has
the /dev/sg0 and /dev/sg1.  A later patch will modify the tests
accordingly.

Signed-off-by: Osier Yang <jyang@redhat.com>
Reported-by: Pavel Hrdina <phrdina@redhat.com>
2014-01-30 16:34:43 +01:00
Osier Yang
10c9ceff6d util: Add one argument for several scsi utils
To support passing the path of the test data to the utils, one
more argument is added to virSCSIDeviceGetSgName,
virSCSIDeviceGetDevName, and virSCSIDeviceNew, and the related
code is changed accordingly.

Later tests for the scsi utils will be based on this patch.

Signed-off-by: Osier Yang <jyang@redhat.com>
2014-01-30 15:48:28 +08:00
Osier Yang
fd243fc4ad qemu: Don't fail if the SCSI host device is shareable between domains
It doesn't make sense to fail if the SCSI host device is specified
as "shareable" explicitly between domains (NB, it works if and only
if the device is specified as "shareable" for *all* domains,
otherwise it fails).

To fix the problem, this patch introduces an array for virSCSIDevice
struct, which records all the names of domain which are using the
device (note that the recorded domains must specify the device as
shareable).  And the change on the data struct brings on many
subsequent changes in the code.

Prior to this patch, the "shareable" tag didn't work as expected,
it actually work like "non-shareable".  So this patch also added notes
in formatdomain.html to declare the fact.

* src/util/virscsi.h:
  - Remove virSCSIDeviceGetUsedBy
  - Change definition of virSCSIDeviceGetUsedBy and virSCSIDeviceListDel
  - Add virSCSIDeviceIsAvailable

* src/util/virscsi.c:
  - struct virSCSIDevice: Change "used_by" to be an array; Add
    "n_used_by" as the array count
  - virSCSIDeviceGetUsedBy: Removed
  - virSCSIDeviceFree: frees the "used_by" array
  - virSCSIDeviceSetUsedBy: Copy the domain name to avoid potential
    memory corruption
  - virSCSIDeviceIsAvailable: New
  - virSCSIDeviceListDel: Change the logic, for device which is already
    in the list, just remove the corresponding entry in "used_by". And
    since it's only used in one place, we can safely removing the code
    to find out the dev in the list first.
  - Copyright updating

* src/libvirt_private.sys:
  - virSCSIDeviceGetUsedBy: Remove
  - virSCSIDeviceIsAvailable: New

* src/qemu/qemu_hostdev.c:
  - qemuUpdateActiveScsiHostdevs: Check if the device existing before
    adding it to the list;
  - qemuPrepareHostdevSCSIDevices: Error out if the not all domains
    use the device as "shareable"; Also don't try to add the device
    to the activeScsiHostdevs list if it already there; And make
    more sensible error w.r.t the current "shareable" value in
    driver->activeScsiHostdevs.
  - qemuDomainReAttachHostScsiDevices: Change the logic according
    to the changes on helpers.

Signed-off-by: Osier Yang <jyang@redhat.com>
2014-01-30 15:46:24 +08:00
Roman Bogorodskiy
d779d218d4 maint: add configure checks for BSD CPU affinity
Check for presence of sys/cpuset.h header and cpuset_getaffinity()
in configure instead of just using #ifdef __FreeBSD__ for that code.
2014-01-29 12:11:48 -07:00
Michal Privoznik
122cd16982 Revert "networkAllocateActualDevice: Set QoS for bridgeless networks too"
This reverts commit 2996e6be19
and some parts of 2636dc8c4d.

The former one tried to implement QoS setting on bridgeless networks.
However, as discussed upstream [1], the patch is far away from being
useful in even a single case. The whole idea of network QoS is to have
aggregated limits over several interfaces. This patch is doing
completely the opposite when merging two QoS settings (from the network
and the domain interface) into one which is then set at the domain
interface itself, not the network.

The latter one is the test for the previous one. Now none of them makes
sense.

1: https://www.redhat.com/archives/libvir-list/2014-January/msg01441.html

Conflicts:
	tests/virnetdevbandwidthtest.c: New test has been introduced since
    then.
2014-01-29 19:01:19 +01:00
Michal Privoznik
550a2ceffb virCommand: Introduce virCommandSetDryRun
There are some units within libvirt that utilize virCommand API to run
some commands and deserve own unit testing. These units are, however,
not desired to be rewritten to dig virCommand API usage out. As a great
example virNetDevBandwidth could be used. The problem with the bandwidth
unit is: it uses virCommand API heavily. Therefore we need a mechanism
to not really run a command, but rather see its string representation
after which we can decide if the unit construct the correct sequence of
commands or not.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-01-29 18:01:36 +01:00
Roman Bogorodskiy
c022fbc9bb BSD: implement virProcess{Get,Set}Affinity
Implement virProcess{Get,Set}Affinity() using cpuset_getaffinity()
and cpuset_setaffinity() calls. Quick search showed that they are
only available on FreeBSD, so placed it inside existing #ifdef
blocks for FreeBSD instead of adding configure checks.
2014-01-27 09:51:55 -07:00
Michal Privoznik
2996e6be19 networkAllocateActualDevice: Set QoS for bridgeless networks too
https://bugzilla.redhat.com/show_bug.cgi?id=1055484

Currently, libvirt's XML schema of network allows QoS to be defined for
every network even though it has no bridge. For instance:

<network>
    <name>vdsm-no-bridge</name>
    <forward mode='passthrough'>
      <interface dev='em1.10'/>
    </forward>
    <bandwidth>
        <inbound average='1000' peak='5000' burst='1024'/>
        <outbound average='1000' burst='1024'/>
    </bandwidth>
</network>

The bandwidth limitations can be, however, applied even on such
networks. In fact, they are going to be applied on the interface that
will be connected to the network on a domain startup. This approach,
however, has one limitation. With bridged networks, there are two points
where QoS can be set: bridge and domain interface. The lower limit of
the two is enforced then. For instance, if the interface has 10Mbps
average, but the network only 1Mbps, there's no way for interface to
transmit packets faster than the 1Mbps limit. With two points this is
enforced by kernel.  With only one point, we must combine both QoS
settings into one which is set afterwards. Look at
virNetDevBandwidthMinimal() and you'll understand immediately what I
mean.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-01-27 12:11:27 +01:00
Osier Yang
88ae5dc759 storage: Fix the memory leak
The return value of virGetFCHostNameByWWN is a strdup'ed string.
Also add comments to declare that the caller should take care of
freeing it.
2014-01-23 21:39:05 +08:00
Osier Yang
7519958735 util: Fix the indention
Left in the git cache without commit before pushing. Pushed under
build breaker and trivial rule.
2014-01-23 18:16:11 +08:00
Osier Yang
2b66504ded util: Add "shareable" field for virSCSIDevice struct
Unlike the host devices of other types, SCSI host device XML supports
"shareable" tag. This patch introduces it for the virSCSIDevice struct
for a later patch use (to detect if the SCSI device is shareable when
preparing the SCSI host device in QEMU driver).
2014-01-23 17:52:33 +08:00
Osier Yang
ae2860b4c6 util: Correct the NUMA node range checking
There are 2 issues here: First we shouldn't add "1" to the return
value of numa_max_node(), since the semanteme of the error message
was changed, it's not saying about the number of total NUMA nodes
anymore.  Second, the value of "bit" is the position of the first
bit which exceeds either numa_max_node() or NUMA_NUM_NODES, it can
be any number in the range, so saying "bigger than $bit" is quite
confused now. For example, assuming there is a NUMA machine which
has 10 NUMA nodes, and one specifies the "nodeset" as "0,5,88",
the error message will be like:

Nodeset is out of range, host cannot support NUMA node bigger than 88

It sounds like all NUMA node number less than 88 is fine, but
actually the maximum NUMA node number the machine supports is 9.

This patch fixes the issues by removing the addition with "1" and
simplifies the error message as "NUMA node $bit is out of range".
Also simplifies the comparision in the while loop by getting the
smaller one of numa_max_node() and NUMA_NUM_NODES up front.
2014-01-23 13:19:56 +08:00
Roman Bogorodskiy
881c6c0047 Use AC_PATH_PROG to search for dmidecode
This is useful in certain circumstances, for example when
libvirtd is being executed by FreeBSD rc script, it cannot find
dmidecode installed from FreeBSD ports because it doesn't have
/usr/local (default prefix for ports) in PATH.
2014-01-20 09:34:53 -07:00
Thorsten Behrens
721949059b maint: align whitespaces with project conventions. 2014-01-20 14:35:08 +01:00
Jiri Denemark
124affae84 pci: Publish some internal code for virpcitest
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2014-01-20 13:58:04 +01:00
Jiri Denemark
d8ab981bdd pci: Fix failure paths in detach
https://bugzilla.redhat.com/show_bug.cgi?id=1046919

Since commit v0.9.0-47-g4e8969e (released in 0.9.1) some failures during
device detach were reported to callers of virPCIDeviceBindToStub as
success. For example, even though a device seemed to be detached

    virsh # nodedev-detach pci_0000_07_05_0 --driver vfio
    Device pci_0000_07_05_0 detached

one could find similar message in libvirt logs:

    Failed to bind PCI device '0000:07:05.0' to vfio-pci: No such device

This patch fixes these paths and also avoids overwriting real errors
with errors encountered during a cleanup phase.
2014-01-20 13:58:04 +01:00
Jiri Denemark
c982e5e84f pci: Make reattach work for unbound devices
https://bugzilla.redhat.com/show_bug.cgi?id=1046919

When a PCI device is not bound to any driver, reattach should just
trigger driver probe rather than failing with

    Invalid device 0000:00:19.0 driver file
    /sys/bus/pci/devices/0000:00:19.0/driver is not a symlink

While virPCIDeviceGetDriverPathAndName was documented to return success
and NULL driver and path when a device is not attached to any driver but
didn't do so. Thus callers could not distinguish unbound devices from
failures.

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2014-01-20 13:58:04 +01:00
Gao feng
3b431929a2 blkio: Setting throttle blkio cgroup for domain
This patch introduces virCgroupSetBlkioDeviceReadIops,
virCgroupSetBlkioDeviceWriteIops,
virCgroupSetBlkioDeviceReadBps and
virCgroupSetBlkioDeviceWriteBps,

we can use these interfaces to set up throttle
blkio cgroup for domain.

This patch also adds the new throttle blkio cgroup
elements to the test xml.

Signed-off-by: Guan Qiang <hzguanqiang@corp.netease.com>
Signed-off-by: Gao feng <gaofeng@cn.fujitsu.com>
2014-01-20 10:52:44 +08:00
Pavel Hrdina
67fbf129fc Fix possible memory leak in util/virxml.c
A "xmlstr" string may not be assigned into a "doc" pointer and it
could cause memory leak. To fix it if the "doc" pointer is NULL and
the "xmlstr" string is not assigned we should free it.

This has been found by coverity.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2014-01-15 11:11:34 +01:00
Eric Blake
c91d13bd0f build: fix build on mingw with winpthreads
On my Fedora 20 box with mingw cross-compiler, the build failed with:

../../src/rpc/virnetclient.c: In function 'virNetClientSetTLSSession':
../../src/rpc/virnetclient.c:745:14: error: unused variable 'oldmask' [-Werror=unused-variable]
     sigset_t oldmask, blockedsigs;
              ^

I traced it to the fact that mingw64-winpthreads installs a header
that does #define pthread_sigmask(...) 0, which means any argument
only ever passed to pthread_sigmask is reported as unused.  This
patch works around the compilation failure, with behavior no worse
than what mingw already gives us regarding the function being a
no-op.

* configure.ac (pthread_sigmask): Probe for broken mingw macro.
* src/util/virutil.h (pthread_sigmask): Rewrite to something that
avoids unused variables.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-13 09:14:11 -07:00
Osier Yang
6f9894856c util: Use new array management macros
Like commit 94a26c7e from Eric Blake, the old fuzzy code should
be replaced by the new array management macros now.

And the type of scsi->count should be changed into "size_t", and
thus virSCSIDeviceListCount should return size_t instead, similar
for vir{PCI,USB}DeviceListCount.
2014-01-08 23:00:34 +08:00
Lénaïc Huard
538daf7f3a Fix bridge configuration when OUTPUT policy is DROP on the host
When the host is configured with very restrictive firewall (default policy
is DROP for all chains, including OUTPUT), the bridge driver for Linux
adds netfilter entries to allow DHCP and DNS requests to go from the VM
to the dnsmasq of the host.

The issue that this commit fixes is the fact that a DROP policy on the OUTPUT
chain blocks the DHCP replies from the host’s dnsmasq to the VM.
As DHCP replies are sent in UDP, they are not caught by any --ctstate ESTABLISHED
rule and so, need to be explicitly allowed.

Signed-off-by: Lénaïc Huard <lenaic@lhuard.fr.eu.org>
2014-01-07 18:18:29 +01:00
Thadeu Lima de Souza Cascardo
9a3d7a4778 Read PCI class from sysfs class file instead of config space.
When determining if a device is behind a PCI bridge, the PCI device
class is checked by reading the config space. However, there are some
devices which have the wrong class on the config space, but the class is
initialized by Linux correctly as a PCI BRIDGE. This class can be read
by the sysfs file '/sys/bus/pci/devices/xxxx:xx:xx.x/class'.

One example of such bridge is IBM PCI Bridge 1014:03b9, which is
identified as a Host Bridge when reading the config space.

Signed-off-by: Thadeu Lima de Souza Cascardo <cascardo@linux.vnet.ibm.com>
2014-01-07 17:33:59 +01:00
Eric Blake
d219826c65 maint: improve VIR_ERR_OPERATION_DENIED usage
Some of our operation denied messages are outright stupid; for
example, if virIdentitySetAttr fails:

error: operation Identity attribute is already set forbidden for read only access

This patch fixes things to a saner:

error: operation forbidden: Identity attribute is already set

It also consolidates the most common usage pattern for operation
denied errors: read-only connections preventing a public API.  In
this case, 'virsh -r -c test:///default destroy test' changes from:

error: operation virDomainDestroy forbidden for read only access

to:

error: operation forbidden: read only access prevents virDomainDestroy

Note that we were previously inconsistent on which APIs used
VIR_FROM_DOM (such as virDomainDestroy) vs. VIR_FROM_NONE (such as
virDomainPMSuspendForDuration).  After this patch, all uses
consistently use VIR_FROM_NONE, on the grounds that it is unlikely
that a caller learning that a call is denied can do anything in
particular with extra knowledge which error domain the call belongs
to (similar to what we did in commit baa7244).

* src/util/virerror.c (virErrorMsg): Rework OPERATION_DENIED error
message.
* src/internal.h (virCheckReadOnlyGoto): New macro.
* src/util/virerror.h (virReportRestrictedError): New macro.
* src/libvirt-lxc.c: Use new macros.
* src/libvirt-qemu.c: Likewise.
* src/libvirt.c: Likewise.
* src/locking/lock_daemon.c (virLockDaemonClientNew): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-06 08:29:29 -07:00
Eric Blake
baa7244951 maint: improve VIR_ERR_NO_SUPPORT usage
We weren't very consistent in our use of VIR_ERR_NO_SUPPORT; many
users just passed __FUNCTION__ on, while others passed "%s" to
silence over-eager compilers that warn about __FUNCTION__ not
containing any %.  It's nicer to route all these uses through
a single macro, so that if we ever need to change the reporting,
we can do it in one place.

I verified that 'virsh -c test:///default qemu-monitor-command test foo'
gives the same error message before and after this patch:
error: this function is not supported by the connection driver: virDomainQemuMonitorCommand

Note that in libvirt.c, we were inconsistent on whether virDomain*
API used virLibConnError() (with VIR_FROM_NONE) or virLibDomainError()
(with VIR_FROM_DOMAIN); this patch unifies these errors to all use
VIR_FROM_NONE, on the grounds that it is unlikely that a caller
learning that a call is unimplemented can do anything in particular
with extra knowledge of which error domain it belongs to.

One particular change to note is virDomainOpenGraphics which was
trying to fail with VIR_ERR_NO_SUPPORT after a failed
VIR_DRV_SUPPORTS_FEATURE check; all other places that fail a
feature check report VIR_ERR_ARGUMENT_UNSUPPORTED.

* src/util/virerror.h (virReportUnsupportedError): New macro.
* src/libvirt-qemu.c: Use new macro.
* src/libvirt-lxc.c: Likewise.
* src/lxc/lxc_driver.c: Likewise.
* src/security/security_manager.c: Likewise.
* src/util/virinitctl.c: Likewise.
* src/libvirt.c: Likewise.
(virDomainOpenGraphics): Use correct error for unsupported feature.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-04 12:15:08 -07:00
Eric Blake
8f6c845f17 maint: avoid nested public calls
Having one API call into another is generally not good; among
other issues, it gives confusing logs, and is not quite as
efficient.

This fixes several instances, but not all: we still have instances
in both libvirt.c and in backend hypervisors (lxc and qemu) calling
the public virTypedParamsGetString and friends, which dispatch
errors immediately.  I'm not sure if it is worth trying to clean
that up in a separate patch (such a cleanup may be easiest by
separating the public function into a wrapper around the internal,
then tweaking internal.h so that internal users directly use the
internal function).

* src/libvirt.c (virDomainGetUUIDString, virNetworkGetUUIDString)
(virStoragePoolGetUUIDString, virSecretGetUUIDString)
(virNWFilterGetUUIDString): Avoid nested public API call.
* src/util/virtypedparam.c (virTypedParamsReplaceString): Don't
dispatch errors here.
(virTypedParamsGet): No need to reset errors.
(virTypedParamsGetBoolean): Use consistent ordering.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-04 07:13:09 -07:00
Eric Blake
13f8372007 maint: improve debug of libvirt-{qemu,lxc} apis
I noticed that the virDomainQemuMonitorCommand debug output wasn't
telling me the name of the domain it was working on.  While it was
easy enough to determine which pointer matches the domain based on
other log messages, it is nicer to be consistent.

* src/util/viruuid.h (VIR_UUID_DEBUG): Moved here from...
* src/libvirt.c (VIR_UUID_DEBUG): ...here.
(VIR_ARG15, VIR_HAS_COMMA, VIR_DOMAIN_DEBUG_EXPAND)
(VIR_DOMAIN_DEBUG_PASTE, VIR_DOMAIN_DEBUG_0, VIR_DOMAIN_DEBUG_1)
(VIR_DOMAIN_DEBUG_2, VIR_DOMAIN_DEBUG): Move...
* src/datatypes.h: ...here.
* src/libvirt-qemu.c (virDomainQemuMonitorCommand)
(virDomainQemuAgentCommand): Better debug messages.
* src/libvirt-lxc.c (virDomainLxcOpenNamespace): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-02 22:17:11 -07:00
Eric Blake
c8f95fff63 event: improve public API docs
Since libvirt 0.9.3, the entire virevent.c file has been a public
API, so improve the documentation in this file.  Also, fix a
potential core dump - it could only be triggered by bogus use of
the API and would only affect the caller (not libvirtd), but we
might as well be nice.

* src/libvirt.c (virConnectSetKeepAlive)
(virConnectDomainEventRegister, virConnectDomainEventRegisterAny)
(virConnectNetworkEventRegisterAny): Document event loop requirement.
* src/util/virevent.c (virEventAddHandle, virEventRemoveHandle)
(virEventAddTimeout, virEventRemoveTimeout): Likewise.
(virEventUpdateHandle, virEventUpdateTimeout): Likewise, and avoid
core dump if caller didn't register handler.
(virEventRunDefaultImpl): Expand example, and set up code block in
html docs.
(virEventRegisterImpl, virEventRegisterDefaultImpl): Document more
on the use of the event loop.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-01-02 07:29:54 -07:00
Eric Blake
9d30e078be maint: fix typo in error message
* src/util/virerror.h (virReportInvalidZeroArg): Fix double space.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-12-27 14:30:25 -07:00
Michal Privoznik
72ffbd1bf3 virkeycode: Allow ANSI_A
https://bugzilla.redhat.com/show_bug.cgi?id=1044806

Currently, sending the ANSI_A keycode from os_x codepage doesn't work as
it has a special value of 0x0. Our internal code handles that no
different to other not defined keycodes. Hence, in order to allow it we
must change all the undefined keycodes from 0 to -1 and adapt some code
too.

  # virsh send-key guestname --codeset os_x ANSI_A
  error: invalid keycode: 'ANSI_A'

  # virsh send-key guestname --codeset os_x ANSI_B
  # virsh send-key guestname --codeset os_x ANSI_C

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2013-12-24 17:36:47 +01:00
Daniel P. Berrange
7d3a1c8bd1 Fix race leading to crash when setting up dbus watches
Currently the virDBusAddWatch does

  virEventAddHandle(fd, flags,
                    virDBusWatchCallback,
                    watch, NULL);
  dbus_watch_set_data(watch, info, virDBusWatchFree);

Unfortunately this is racy - since the event loop is in a
different thread, the virDBusWatchCallback method may be
run before we get to calling dbus_watch_set_data. We must
reverse the order of these calls

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

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-12-18 16:59:02 +00:00
Eric Blake
fca4f23340 object: require maximal alignment in base class
Recent changes to events (commit 8a29ffcf) resulted in new compile
failures on some targets (such as ARM OMAP5):
conf/domain_event.c: In function 'virDomainEventDispatchDefaultFunc':
conf/domain_event.c:1198:30: error: cast increases required alignment of
target type [-Werror=cast-align]
conf/domain_event.c:1314:34: error: cast increases required alignment of
target type [-Werror=cast-align]
cc1: all warnings being treated as errors

The error is due to alignment; the base class is merely aligned
to the worst of 'int' and 'void*', while the child class must
be aligned to a 'long long'.  The solution is to include a
'long long' (and for good measure, a function pointer) in the
base class to ensure correct alignment regardless of what a
child class may add, but to wrap the inclusion in a union so
as to not incur any wasted space.  On a typical x86_64 platform,
the base class remains 16 bytes; on i686, the base class remains
12 bytes; and on the impacted ARM platform, the base class grows
from 12 bytes to 16 bytes due to the increase of alignment from
4 to 8 bytes.

Reported by Michele Paolino and others.

* src/util/virobject.h (_virObject): Use a union to ensure that
subclasses never have stricter alignment than the parent.
* src/util/virobject.c (virObjectNew, virObjectUnref)
(virObjectRef): Adjust clients.
* src/libvirt.c (virConnectRef, virDomainRef, virNetworkRef)
(virInterfaceRef, virStoragePoolRef, virStorageVolRef)
(virNodeDeviceRef, virSecretRef, virStreamRef, virNWFilterRef)
(virDomainSnapshotRef): Likewise.
* src/qemu/qemu_monitor.c (qemuMonitorOpenInternal)
(qemuMonitorClose): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-12-13 05:59:38 -07:00
Martin Kletzander
231656bbeb cgroups: Redefine what "unlimited" means wrt memory limits
Since kernel 3.12 (commit 34ff8dc08956098563989d8599840b130be81252 in
linux-stable.git in particular) the value for 'unlimited' in cgroup
memory limits changed from LLONG_MAX to ULLONG_MAX.  Due to rather
unfortunate choice of our VIR_DOMAIN_MEMORY_PARAM_UNLIMITED constant
(which we transfer as an unsigned long long in Kibibytes), we ended up
with the situation described below (applies to x86_64):

 - 2^64-1 (ULLONG_MAX) -- "unlimited" in kernel = 3.12

 - 2^63-1 (LLONG_MAX) -- "unlimited" in kernel < 3.12
 - 2^63-1024 -- our PARAM_UNLIMITED scaled to Bytes

 - 2^53-1 -- our PARAM_UNLIMITED unscaled (in Kibibytes)

This means that when any number within (2^63-1, 2^64-1] is read from
memory cgroup, we are transferring that number instead of "unlimited".
Unfortunately, changing VIR_DOMAIN_MEMORY_PARAM_UNLIMITED would break
ABI compatibility and thus we have to resort to a different solution.

With this patch every value greater than PARAM_UNLIMITED means
"unlimited".  Even though this may seem misleading, we are already in
such unclear situation when running 3.12 kernel with memory limits set
to 2^63.

One example showing most of the problems at once (with kernel 3.12.2):
 # virsh memtune asdf --hard-limit 9007199254740991 --swap-hard-limit -1
 # echo 12345678901234567890 >\
/sys/fs/cgroup/memory/machine/asdf.libvirt-qemu/memory.soft_limit_in_bytes
 # virsh memtune asdf
 hard_limit     : 18014398509481983
 soft_limit     : 12056327051986884
 swap_hard_limit: 18014398509481983

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2013-12-10 08:38:46 +01:00
Zhou Yimin
036aeca721 Cgroup: Replace 'newpath' with 'newPath'
Unifying codding style, replace 'newpath' with 'newPath'.

From: Zhou Yimin <zhouyimin@huawei.com>
2013-12-06 16:18:14 +01:00
Michal Privoznik
e925aad324 virThreadPoolFree: Set n(Prio)Workers after the pool is locked
In 78839da I am trying to join the worker threads. However, I can't
sipmly reuse pool->nWorkers (same applies for pool->nPrioWorkers),
because of the following flow that is currently implemented:

1) the main thread executing virThreadPoolFree sets pool->quit = true,
wakes up all the workers and wait on pool->quit_cond.

2) A worker is woken up and see quit request. It immediately jumps of
the while() loop and decrements pool->nWorkers (or pool->nPrioWorkers in
case of priority worker). The last thread signalizes pool->quit_cond.

3) Main thread is woken up, with both pool->nWorkers and
pool->nPrioWorkers being zero.

So there's a need to copy the original value of worker thread counts
into local variables. However, these need to set *after* the check for
pool being NULL (dereferencing a NULL is no no). And for safety they can
be set right after the pool is locked.

Reported-by: John Ferlan <jferlan@redhat.com>
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2013-12-05 15:52:23 +01:00
Michal Privoznik
78839da0bb virThreadPoolFree: Join worker threads
Even though currently we are freeing the pool of worker threads at the
daemon very end, nothing holds us back in joining the worker threads.
Moreover, we avoid leaks like this:

==26697== 1,680 bytes in 5 blocks are possibly lost in loss record 913 of 942
==26697==    at 0x4C2BDE4: calloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==26697==    by 0x4011131: allocate_dtv (in /lib64/ld-2.16.so)
==26697==    by 0x401176D: _dl_allocate_tls (in /lib64/ld-2.16.so)
==26697==    by 0x8499602: pthread_create@@GLIBC_2.2.5 (in /lib64/libpthread-2.16.so)
==26697==    by 0x52F53E9: virThreadCreate (virthreadpthread.c:188)
==26697==    by 0x52F5D4F: virThreadPoolNew (virthreadpool.c:221)
==26697==    by 0x53F30DB: virNetServerNew (virnetserver.c:377)
==26697==    by 0x11C6ED: main (libvirtd.c:1366)

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2013-12-04 16:36:46 +01:00
Daniel P. Berrange
84fd470d3d Fix bug in identifying sub-mounts
The code for extracting sub-mounts would just do a STRPREFIX
check on the mount. This was flawed because if there were
the following mounts

 /etc/aliases
 /etc/aliases.db

and '/etc/aliases' was asked for, it would return both even
though the latter isn't a sub-mount.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-11-28 11:49:01 +00:00
Daniel P. Berrange
d45b833d14 Pull lxcContainerGetSubtree out into shared virfile module
Move the code for lxcContainerGetSubtree into the virfile
module creating 2 new functions

  int virFileGetMountSubtree(const char *mtabpath,
                             const char *prefix,
                             char ***mountsret,
                             size_t *nmountsret);
  int virFileGetMountReverseSubtree(const char *mtabpath,
                                    const char *prefix,
                                    char ***mountsret,
                                    size_t *nmountsret);

Add a new virfiletest.c test case to validate the new code.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-11-28 11:49:01 +00:00
Daniel P. Berrange
c60a2713d6 Introduce standard methods for sorting strings with qsort
Add virStringSortCompare and virStringSortRevCompare as
standard functions to use with qsort.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2013-11-28 11:29:46 +00:00
Eric Blake
c7c84fa54a maint: fix comma style issues: util
Most of our code base uses space after comma but not before;
fix the remaining uses before adding a syntax check.

* src/util/vircommand.c: Consistently use commas.
* src/util/virlog.c: Likewise.
* src/util/virnetdevbandwidth.c: Likewise.
* src/util/virnetdevmacvlan.c: Likewise.
* src/util/virnetdevvportprofile.c: Likewise.
* src/util/virnetlink.c: Likewise.
* src/util/virpci.c: Likewise.
* src/util/virsysinfo.c: Likewise.
* src/util/virusb.c: Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2013-11-20 09:14:55 -07:00
Ján Tomko
a18fa05a8f Remove redundant braces 2013-11-20 12:35:47 +01:00