Commit Graph

2630 Commits

Author SHA1 Message Date
Ján Tomko
d5a49e5d4c qemuExecuteEthernetScript: move to util
This is just a wrapper for virCommand that takes two strings
and runs them.

Move it to virnetdev.c for easier mocking.
2016-04-13 15:01:17 +02:00
Peter Krempa
dcf02a704f util: Rename and move virStrIsPrint to virStringIsPrintable 2016-04-13 08:15:24 +02:00
Andrea Bolognani
c81f058bd0 util: Fix 'exempt from syntax-check' comment 2016-04-12 10:30:10 +02:00
Pavel Hrdina
7fb81831fc build: cleanup GCC < 4.6 -Wlogical-op workaround
Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2016-04-11 12:09:11 +02:00
Peter Krempa
a3510e33d3 util: netdev: Don't crash in virNetDevSetIPAddress if @peer is NULL
VIR_SOCKET_ADDR_VALID dereferences the pointer, thus if we pass NULL
into virNetDevSetIPAddress it crashes. Regression introduced by
b3d069872c.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1325120
2016-04-08 14:28:11 +02:00
Andrea Bolognani
4572997aca netdev: Use the correct pointer type for virSocketAddrFormat()
virSocketAddrFormat() wants a single pointer, not a double pointer.

Fixes the following compilation error on FreeBSD:

  util/virnetdev.c:1448:72: error: incompatible pointer types passing
   'virSocketAddr **' to parameter of type 'const virSocketAddr *';
   remove & [-Werror,-Wincompatible-pointer-types]
      if (VIR_SOCKET_ADDR_VALID(peer) && !(peerstr = virSocketAddrFormat(&peer)))
                                                                         ^~~~~
  ./util/virsocketaddr.h:92:48: note: passing argument to parameter 'addr' here
  char *virSocketAddrFormat(const virSocketAddr *addr);
                                                 ^
2016-04-08 13:05:31 +02:00
Roman Bogorodskiy
edc028d122 util: move ENODATA redefine to internal.h
FreeBSD lacks ENODATA, and viruuid.c redefines it to EIO, but it's not
actually using it. On the other hand, we have virrandom.c that's using
ENODATA. So make this re-definition common by moving it to internal.h,
so all the current and possible future users don't need to care about
that.
2016-04-08 10:20:10 +03:00
Vasiliy Tolstov
b3d069872c virnetdev allow to set peer address
Signed-off-by: Vasiliy Tolstov <v.tolstov@selfip.ru>
2016-04-07 18:22:58 +01:00
John Ferlan
6af73f53c6 util: Introduce virRandomBytes
Using the existing virUUIDGenerateRandomBytes, move API to virrandom.c
rename it to virRandomBytes and add it to libvirt_private.syms.

This will be used as a fallback for generating a domain master key.
2016-04-06 20:27:09 -04:00
Andrea Bolognani
fbd4db79e4 Revert "hostdev: Use actual device when reattaching"
This reverts commit ee4cfb5643.

Since we're still not persisting our bookkeeping lists across
daemon restarts, we might have lost some information
virPCIDeviceReattach() relies on, for example whether the
device needs to be unbound from the stub driver.

As a result, if the daemon has been restarted in the meantime,
the device might end up remaining bound to the stub driver even
after 'virsh nodedev-reattach' or similar has been called, with
no way of giving it back to the host short of messing with
sysfs behind libvirt's back.

Revert back to the previous behavior of always trying to bind
the device to the host driver, regardless of its status when it
was detached, until persistent bookkeeping lists have been
implemented.
2016-04-01 17:06:53 +02:00
Michal Privoznik
2cbdd64adf virPerfReadEvent: Prefer saferead over read
Do I really need to explain why?
Well, if read() is interrupted int the middle of reading, we will
never read the rest (even though it's highly unlikely as we are
reading just 8 bytes).

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-31 17:25:21 +02:00
Michal Privoznik
ed504ba392 virDomain{Get,Set}PerfEvents: support --config --live --current
Now that we have @flags we can support changing perf events just
in active or inactive configuration regardless of the other.
Previously, calling virDomainSetPerfEvents set events in both
active and inactive configuration at once. Even though we allow
users to set perf events that are to be enabled once domain is
started up. The virDomainGetPerfEvents API was flawed too. It
returned just runtime info.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-31 10:42:46 +02:00
Peter Krempa
917426c8d7 util: bitmap: Introduce self-expanding bitmap APIs
In some cases it's impractical to use the regular APIs as the bitmap
size needs to be pre-declared. These new APIs allow to use bitmaps that
self expand.

The new code adds a property to the bitmap to track the allocation of
memory so that VIR_RESIZE_N can be used.
2016-03-29 21:25:41 +02:00
Roman Bogorodskiy
4ed5937d71 perf: fix build on non-Linux
* Sync stubbed functions with prototypes
 * Add missing ATTRIBUTE_UNUSED where needed

Pushing under the build breaker rule.
2016-03-29 19:26:47 +03:00
Qiaowei Ren
28b446292b perf: implement a set of util functions for perf event
This patch implement a set of interfaces for perf event. Based on
these interfaces, we can implement internal driver API for perf,
and get the results of perf conuter you care about.

Signed-off-by: Qiaowei Ren <qiaowei.ren@intel.com>
Message-id: 1459171833-26416-4-git-send-email-qiaowei.ren@intel.com
2016-03-29 13:13:05 +01:00
Laine Stump
5b5f12cffa util: avoid getting stuck on macvtapN name created outside libvirt
After the patches that added tracking of in-use macvtap names (commit
370608, first appearing in libvirt-1.3.2), if the function to allocate
a new macvtap device came to a device name created outside libvirt, it
would retry the same device name MACVLAN_MAX_ID (8191) times before
finally giving up in failure.

The problem was that virBitmapNextClearBit was always being called
with "0" rather than the value most recently checked (which would
increment each time through the loop), so it would always return the
same id (since we dutifully release that id after failing to create a
new device using it).

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

Signed-off-by: Laine Stump <laine@laine.org>
2016-03-28 12:52:50 -04:00
Erik Skultety
cd000d3a0b virlog: Refactor virLogParseFilters
Patch 0b231195 refactored logging output parser to make it more readable.
This patch does similar thing to logging filter parser.
2016-03-24 16:39:28 +01:00
Andrea Bolognani
ee4cfb5643 hostdev: Use actual device when reattaching
Instead of forcing the values for the unbind_from_stub, remove_slot
and reprobe properties, look up the actual device and use that when
calling virPCIDeviceReattach().

This ensures the device is restored to its original state after
reattach: for example, if it was not bound to any driver before
detach, it will not be bound forcefully during reattach.
2016-03-23 11:38:20 +01:00
Andrea Bolognani
c3e2f6e37d hostdev: Save netdev configuration of actual device
We would be just fine looking up the information in pcidevs most
of the time; however, some corner cases would not be handled
properly, so look up the actual device instead.
2016-03-23 11:38:20 +01:00
Andrea Bolognani
811286090f hostdev: Streamline device ownership tracking
After this patch, ownership of virPCIDevice instances is very easy
to keep track of: for each host PCI device, the only instance that
actually matters is the one inside one of the bookkeeping list.

Whenever some operation needs to be performed on a PCI device, the
actual device is looked up first; when this is not the case, a
comment explains the reason.
2016-03-23 11:38:14 +01:00
Andrea Bolognani
6da6bf2f30 hostdev: Stop early if unmanaged devices have not been detached
Unmanaged devices, as the name suggests, are not detached
automatically from the host by libvirt before being attached to a
guest: it's the user's responsability to detach them manually
beforehand. If that preliminary step has not been performed, the
attach operation can't complete successfully.

Instead of relying on the lower layers to error out with cryptic
messages such as

  error: Failed to attach device from /tmp/hostdev.xml
  error: Path '/dev/vfio/12' is not accessible: No such file or directory

prevent the situation altogether and provide the user with a more
useful error message.
2016-03-23 10:58:18 +01:00
Andrea Bolognani
df490e7c9b hostdev: Detect untracked inactive devices
Unmanaged devices are attached to guests in two steps: first,
the device is detached from the host and marked as inactive;
subsequently, it is marked as active and attached to the guest.

If the daemon is restarted between these two operations, we lose
track of the inactive device.

Steps 5 and 6 of virHostdevPreparePCIDevices() already subtly
take care of this situation, but some planned changes will make
it so that's no longer the case. Plus, explicit is always better
than implicit.
2016-03-23 10:58:11 +01:00
Martin Kletzander
573c41a275 util: Add virSocketAddrSetIPv[46]AddrNetOrder and use it
This allows setting the address in host and/or network order and makes
the naming consistent.  Now you don't need to call [hn]to[nh]l()
functions as that is taken care of by these functions.  Also, now
the *NetOrder take the address in network order, the other functions in
host order so the naming and usage is consistent.  Some places were
having the address in network order and calling ntohl() just so the
original function can call htonl() again.  This makes it nicer to read.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-03-21 11:28:33 +01:00
Martin Kletzander
d77ffb6876 nodedev: Expose PCI header type
If we expose this information, which is one byte in every PCI config
file, we let all mgmt apps know whether the device itself is an endpoint
or not so it's easier for them to decide whether such device can be
passed through into a VM (endpoint) or not (*-bridge).

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

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-03-18 17:35:06 +01:00
Michal Privoznik
7dbcb26f7f nss: Implement _nss_libvirt_gethostbyname3_r
The implementation is pretty straightforward. Moreover, because
of the nature of things, gethostbyname_r and gethostbyname2_r can
be implemented at the same time too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-18 17:29:53 +01:00
Michal Privoznik
1ca59d89c6 virsocketaddr: Introduce virSocketAddrSetIPv6Addr
This is a missing counterpart for virSocketAddrSetIPv4Addr()
and is going to be needed later in the tests.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-18 17:29:53 +01:00
Michal Privoznik
4122137871 virLeaseReadCustomLeaseFile: Allow server_duid to be NULL
This function is going to be used later in such context where the
argument makes no sense. Teach this function to cope with that
instead of the caller having to deal with passing some dummy
argument.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-18 17:29:53 +01:00
Michal Privoznik
fd9514f8d2 Export virLease* functions for leases file handling
These functions are going to be reused very shortly. So instead
of duplicating the code, lets move them into utils module.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-18 17:29:53 +01:00
Michal Privoznik
865764de06 Drop paths.h include
We include the file in plenty of places. This is mostly due to
historical reasons. The only place that needs something from the
header file is storage_backend_fs which opens _PATH_MOUNTED. But
it gets the file included indirectly via mntent.h. At no other
place in our code we need _PATH_.*. Drop the include and
configure check then.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-18 09:43:45 +01:00
Erik Skultety
e6367dd408 virlog: Fix build breaker with "comparison between signed and unsigned"
Refactor series 0b231195 worked with virLogDestination type which, depending
on the compiler, might be (and probably will be) an unsigned data type.
However, virEnumFromString may return -1 in case of an error. So, when enum
happens to be unsigned, some compilers will naturally complain about foo:
    'if (foo < 0)'
2016-03-16 21:33:11 +01:00
Erik Skultety
0b231195cb virlog: Refactor virLogParseOutputs
The problem with the original virLogParseOutputs method was that the way it
parsed the input, walking the string char by char and using absolute jumps
depending on the virLogDestination type, was rather complicated to read.
This patch utilizes virStringSplit method twice, first time to filter out any
spaces and split the input to individual log outputs and then for each
individual output to tokenize it by to the parts according to our
PRIORITY:DESTINATION?(:DATA) format. Also, to STREQLEN for matching destination
was replaced with virDestinationTypeFromString call.
2016-03-16 14:28:24 +01:00
Erik Skultety
034337fb85 virlog: Introduce Type{To,From}String for virLogDestination
In order to refactor the ugly virLogParseOutputs method, this is a neat way of
finding out whether the destination type (in the form of a string) user
provided is a valid one. As a bonus, if it turns out it is valid, we get the
actual enum which will later be passed to any of virLogAddOutput methods right
away.
2016-03-16 14:24:15 +01:00
Andrea Bolognani
5fc68bd4b1 hostdev: Add more comments
These comments explain the difference between a virPCIDevice
instance used for lookups and an actual device instance; some
information is also provided for specific uses.
2016-03-15 10:34:58 +01:00
Andrea Bolognani
800dd16d84 hostdev: Use consistent variable names
This is not just a cosmetic change: the name of the variable now
gives a hint about what it is supposed to be used for.
2016-03-15 10:33:18 +01:00
Andrea Bolognani
4cdbff3d52 hostdev: Remove virHostdevGetActivePCIHostDeviceList()
virHostdevGetPCIHostDeviceList() is similar but does not filter out
devices that are not in the active list; that said, we are looking
up the device in the active list just a few lines after anyway, so
we might as well just keep a single function around.

This also helps stress the fact the objects contained in pcidevs are
only for looking up the actual devices, which is something later
commits will make even more explicit.
2016-03-15 10:33:17 +01:00
Andrea Bolognani
8e3ac3ed73 hostdev: Rename usesVfio -> usesVFIO
Acronyms should be written in all caps.
2016-03-14 14:55:47 +01:00
Andrea Bolognani
95c65ae193 hostdev: Rename hostdev_mgr -> mgr
We're in the hostdev module, so mgr is not an ambiguous name, and
in fact it's already used in some cases. Switch all the code over.

Take the chance to shorten declaration of
virHostdevIsPCINodeDeviceUsedData structures.
2016-03-14 14:55:47 +01:00
Andrea Bolognani
36243a0c62 hostdev: Look up devices using IDs when possible
When we want to look up a device in a device list and we already
have the IDs from another source, we can simply use
virPCIDeviceListFindByIDs() instead of creating a temporary device
object.
2016-03-14 14:55:47 +01:00
Andrea Bolognani
e57e9413ac hostdev: Change argument order for virHostdevReattachPCIDevice()
The new order aligns better with the virHostdev prefix.
2016-03-14 14:55:47 +01:00
Andrea Bolognani
5ce91139da hostdev: virHostdevIsPCINetDevice() should return a bool
The only possible return values are true and false, so the return
type should be bool instead of int.
2016-03-14 14:55:47 +01:00
Andrea Bolognani
2ec4664b1e hostdev: Rework resetvfnetconfig loop condition
If 'last_processed_hostdev_vf != -1' is false then, since the
loop counter 'i' starts at 0, 'i <= last_processed_hostdev_vf'
can't possibly be true and the loop body will never be executed.

However, since 'i' is unsigned and 'last_processed_hostdev_vf'
is signed, we can't just get rid of the check completely; what
we can do is move it outside of the loop to avoid checking its
value on every iteration and cluttering the actual loop
condition.
2016-03-14 14:55:47 +01:00
Martin Kletzander
62be54861b virerror: Introduce new error type NO_SERVER
This serves the same purpose as VIR_ERR_NO_xxx where xxx is any object
that API can be called upon.  Only this particular one is used for
daemon's servers.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-03-11 12:58:41 +01:00
Cole Robinson
adefc561cc util: virfile: Only setuid for virFileRemove if on NFS
NFS with root-squash is the only reason we need to do setuid/setgid
crazyness in virFileRemove, so limit that behavior to the NFS case.
2016-03-09 16:07:18 -05:00
Cole Robinson
7cf5343709 util: virfile: Clarify setuid usage for virFileRemove
Break these checks out into their own function, and clearly document
each one. This shouldn't change behavior
2016-03-09 16:06:56 -05:00
Andrea Bolognani
12a1631440 hostdev: Remove explicit NULL checks
NULL checks are performed implicitly in the rest of the module,
including other allocations in the very same function.
2016-03-08 10:44:01 +01:00
Andrea Bolognani
a54de18a54 hostdev: Fix indentation 2016-03-08 10:44:01 +01:00
Andrea Bolognani
a67b14a975 hostdev: Remove inaccurate comment
The comment claimed that virPCIDeviceReattach() does not reattach
a device to the host driver; except it actually does, so the
comment is just confusing and we're better off removing it.
2016-03-08 10:42:26 +01:00
Andrea Bolognani
be70acb788 hostdev: Make comments easier to change later
Replace the term "loop" with the more generic "step". This allows us
to be more flexible and eg. have a step that consists in a single
function call.

Don't include the number of steps in the first comment of the
function, so that we can add or remove steps without having to worry
about keeping that comment in sync.

For the same reason, remove the summary contained in that comment.

Clean up some weird vertical spacing while we're at it.
2016-03-08 10:42:25 +01:00
Michal Privoznik
be8b536af1 Drop inline keyword from some functions.
While trying to build with -Os I've encountered some build
failures.

util/vircommand.c: In function 'virCommandAddEnvFormat':
util/vircommand.c:1257:1: error: inlining failed in call to 'virCommandAddEnv': call is unlikely and code size would grow [-Werror=inline]
 virCommandAddEnv(virCommandPtr cmd, char *env)
 ^
util/vircommand.c:1308:5: error: called from here [-Werror=inline]
     virCommandAddEnv(cmd, env);
     ^
This function is big enough for the compiler to be not inlined.
This is the error message I'm seeing:

Then virDomainNumatuneNodeSpecified is exported and called from
other places. It shouldn't be inlined then.

In file included from network/bridge_driver_platform.h:30:0,
                 from network/bridge_driver_platform.c:26:
network/bridge_driver_linux.c: In function 'networkRemoveRoutingFirewallRules':
./conf/network_conf.h:350:1: error: inlining failed in call to 'virNetworkDefForwardIf.constprop': call is unlikely and code size would grow [-Werror=inline]
 virNetworkDefForwardIf(const virNetworkDef *def, size_t n)
 ^

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-03-03 14:39:57 +01:00
John Ferlan
0b36b0e9ce util: Cleanup error path for virPolkitAgentCreate
More fallout from changing to using virPolkitAgent and handling error
paths.  Needed to clear the 'cmd' once stored and of course add the
virCommandFree(cmd) in the error: label.
2016-03-02 13:59:37 -05:00
John Ferlan
95aa101795 util: Fix missing initializer for agent
In virPolkitAgentCreate neglected to initialize agent to NULL. If
there was an error in the pipe, then we jump to error and would have
an issue. Found by coverity.
2016-03-01 19:36:37 -05:00
Jiri Denemark
254b028943 util: Fix build without polkit
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2016-03-01 15:51:37 +01:00
Henning Schild
ff16bde100 qemu_cgroup: use virCgroupAddTask instead of virCgroupMoveTask
qemuProcessSetupEmulator runs at a point in time where there is only
the qemu main thread. Use virCgroupAddTask to put just that one task
into the emulator cgroup. That patch makes virCgroupMoveTask and
virCgroupAddTaskStrController obsolete.

Signed-off-by: Henning Schild <henning.schild@siemens.com>
2016-03-01 14:07:27 +00:00
John Ferlan
6fb96a7f8b util: Introduce API's for Polkit text authentication
Introduce virPolkitAgentCreate and virPolkitAgentDestroy

virPolkitAgentCreate will run the polkit pkttyagent image as an asynchronous
command in order to handle the local agent authentication via stdin/stdout.
The code makes use of the pkttyagent --notify-fd mechanism to let it know
when the agent is successfully registered.

virPolkitAgentDestroy will close the command effectively reaping our
child process
2016-03-01 06:50:16 -05:00
John Ferlan
1d35f6ffe1 polkit: Adjust message when authentication agent isn't found
When there isn't a ssh -X type session running and a user has not
been added to the libvirt group, attempts to run 'virsh -c qemu:///system'
commands from an otherwise unprivileged user will fail with rather
generic or opaque error message:

    "error: authentication failed: no agent is available to authenticate"

This patch will adjust the error code and message to help reflect the
situation that the problem is the requested mechanism is UNAVAILABLE and
a slightly more descriptive error. The result on a failure then becomes:

    "error: authentication unavailable: no polkit agent available to
            authenticate action 'org.libvirt.unix.manage'"

A bit more history on this - at one time a failure generated the
following type message when running the 'pkcheck' as a subprocess:

"error: authentication failed: polkit\56retains_authorization_after_challenge=1
Authorization requires authentication but no agent is available."

but, a patch was generated to adjust the error message to help provide
more details about what failed. This was pushed as commit id '96a108c99'.
That patch prepended a "polkit: " to the output. It really didn't solve
the problem, but gave a hint.

After some time it was deemed using DBus API calls directly was a
better way to go (since pkcheck calls them anyway). So, commit id
'1b854c76' (more or less) copied the code from remoteDispatchAuthPolkit
and adjusted it. Then commit id 'c7542573' adjusted the remote.c
code to call the new API (virPolkitCheckAuth). Finally, commit id
'308c0c5a' altered the code to call DBus APIs directly. In doing
so, it reverted the failing error message to the generic message
that would have been received from DBus anyway.
2016-03-01 06:50:16 -05:00
Henning Schild
85d7480654 vircgroup: one central point for adding tasks to cgroups
Use virCgroupAddTaskController in virCgroupAddTask so we have one
single point where we add tasks to cgroups.

Signed-off-by: Henning Schild <henning.schild@siemens.com>
2016-03-01 11:20:56 +00:00
Andrea Bolognani
b2ce5b027c hostdev: Remove temporary variable when checking for VF
The virHostdevIsVirtualFunction() was called exactly twice, and in
both cases the return value was saved to a temporary variable before
being checked. This would be okay if it improved readability, but in
this case is pretty pointless.

Get rid of the temporary variable and check the return value
directly; while at it, change the check from '<= 0' to '!= 1' to
align it with the way other similar *IsVirtualFunction() functions
are used thorough the code.
2016-02-25 17:09:53 +01:00
Andrea Bolognani
dec3a4a135 netdev: Use virNetDevIsVirtualFunction() properly
virNetDevIsVirtualFunction() returns 1 if the interface is a
virtual function, 0 if it isn't and -1 on error. This means that,
despite the name suggesting otherwise, using it as a predicate is
not correct.

Fix two callers that were doing so adding an explicit check on
the return value.
2016-02-25 17:09:52 +01:00
Jiri Denemark
04e10925a1 util: Avoid calling closedir(NULL)
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2016-02-25 12:50:12 +01:00
Andrea Bolognani
dad0ae1c1f hostdev: Minor style adjustments
Mostly labels names and whitespace.

No functional changes.
2016-02-22 17:32:48 +01:00
Marc-André Lureau
ef766337ff util: TristateBool and TristateSwitch are interchangeable
It may be useful in some cases to call TristateSwitch helper with TristateBool.
Document that enum values equivalency in the code.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
2016-02-22 15:13:56 +01:00
Andrea Bolognani
d8fc7e05f8 gic: Introduce VIR_GIC_VERSION_DEFAULT alias
GIC v2 is the default, but checking against that specific version when
we want to know whether the default has been selected is potentially
error prone; using an alias instead makes it safer.
2016-02-19 18:24:58 +01:00
Peter Krempa
9268b9ad48 util: Use virBitmapIsBitSet in freebsd impl of virProcessSetAffinity
Use the helper that does not return errors to fix spuriously looking
dead return of -1.
2016-02-19 15:23:54 +01:00
Michal Privoznik
6bfb03ae15 vircgroup: Update virCgroupDenyDevicePath stub
In cf113e8d we changed the declaration of
virCgroupAllowDevicePath() and virCgroupDenyDevicePath().
However, while updating the stub for non-cgroup platforms for the
former we forgot to update the latter too causing a build
failure.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-02-17 14:25:35 +01:00
Erik Skultety
353de572a6 util: Refactor virHashForEach so it returns as soon as an iterator fails
The method will now return 0 on success and -1 on error, rather than number of
items which it iterated over before it returned back to the caller. Since the
only place where we actually check the number of elements iterated is in
virhashtest, return value of 0 and -1 can be a pretty accurate hint that it
iterated over all the items. However, if we really want to know the number of
items iterated over (like virhashtest does), a counter has to be provided
through opaque data to each iterator call. This patch adjusts return value of
virHashForEach, refactors the body, so it returns as soon as one of the
iterators fail and adjusts virhashtest to reflect these changes.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2016-02-17 12:46:34 +01:00
Erik Skultety
cc48d3a122 util: Add a return value to void hash iterators
Our existing virHashForEach method iterates through all items disregarding the
fact, that some of the iterators might have actually failed. Errors are usually
dispatched through an error element in opaque data which then causes the
original caller of virHashForEach to return -1. In that case, virHashForEach
could return as soon as one of the iterators fail. This patch changes the
iterator return type and adjusts all of its instances accordingly, so the
actual refactor of virHashForEach method can be dealt with later.

Signed-off-by: Erik Skultety <eskultet@redhat.com>
2016-02-17 12:46:34 +01:00
Peter Krempa
cf113e8d54 util: cgroup: Allow ignoring EACCES in virCgroup(Allow|Deny)DevicePath
When adding disk images to ACL we may call those functions on NFS
shares. In that case we might get an EACCES, which isn't really relevant
since NFS would not hold a block device. This patch adds a flag that
allows to stop reporting an error on EACCES to avoid spaming logs.

Currently there's no functional change.
2016-02-17 10:54:05 +01:00
Peter Krempa
9cd5da710e util: cgroup: Drop virCgroup(Allow|Deny)DeviceMajor
Since commit 47e5b5ae virCgroupAllowDevice allows to pass -1 as either
the minor or major device number and it automatically uses '*' in place
of that. Reuse the new approach through the code and drop the duplicated
functions.
2016-02-17 10:54:05 +01:00
Peter Krempa
f42b5c327f util: cgroup: Instrument virCgroupDenyDevice to handle -1 device number as *
Similarly to commit 47e5b5ae virCgroupDenyDevice will handle -1 as *.
2016-02-17 10:54:05 +01:00
Andrea Bolognani
e76bef7f7b gic: Introduce virGICVersion enumeration
We currently blindly accept any numeric value as a GIC version, even
though only GIC v2 and GIC v3 actually exist; on the other hand, we
reject "host", which is a perfectly legitimate value for QEMU guests.

This new enumeration contains all GIC versions libvirt is aware of.
2016-02-16 14:58:58 +01:00
Ján Tomko
d616544077 Spell VMware with a lowercase w
Replace all occurrences of VMWare outside the news.
2016-02-15 15:35:48 +01:00
Laine Stump
9cb8b0e5a4 util: clean up and expand 802.1QbX negotiation logging
The existing log messages for this have several problems; there are
two lines of log when one will suffice, they duplicate the function
name in log message (when it's already included by VIR_DEBUG), they're
missing some useful bits, they get logged even when the call is a NOP.

This patch cleans up the problems with those existing logs, and also
adds a new VIR_INFO-level log down at the function that is actually
creating and sending the netlink message that logs *everything* going
into the netlink message (which turns out to be much more useful in
practice for me; I didn't want to eliminate the logs at the existing
location though, in case they are useful in some scenario I'm
unfamiliar with; anyway those logs are remaining at debug level, so it
shouldn't be a bother to anyone).
2016-02-14 11:29:41 -05:00
Michal Privoznik
862298a2e7 dbus: Don't unref NULL messages
Apparently we are not the only ones with dumb free functions
because dbus_message_unref() does not accept NULL either. But if
I were to vote, this one is even more evil. Instead of returning
an error just like we do it immediately dereference any pointer
passed and thus crash you app. Well done DBus!

  Program received signal SIGSEGV, Segmentation fault.
  [Switching to Thread 0x7f878ebda700 (LWP 31264)]
  0x00007f87be4016e5 in ?? () from /usr/lib64/libdbus-1.so.3
  (gdb) bt
  #0  0x00007f87be4016e5 in ?? () from /usr/lib64/libdbus-1.so.3
  #1  0x00007f87be3f004e in dbus_message_unref () from /usr/lib64/libdbus-1.so.3
  #2  0x00007f87bf6ecf95 in virSystemdGetMachineNameByPID (pid=9849) at util/virsystemd.c:228
  #3  0x00007f879761bd4d in qemuConnectCgroup (driver=0x7f87600a32a0, vm=0x7f87600c7550) at qemu/qemu_cgroup.c:909
  #4  0x00007f87976386b7 in qemuProcessReconnect (opaque=0x7f87600db840) at qemu/qemu_process.c:3386
  #5  0x00007f87bf6edfff in virThreadHelper (data=0x7f87600d5580) at util/virthread.c:206
  #6  0x00007f87bb602334 in start_thread (arg=0x7f878ebda700) at pthread_create.c:333
  #7  0x00007f87bb3481bd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:109
  (gdb) frame 2
  #2  0x00007f87bf6ecf95 in virSystemdGetMachineNameByPID (pid=9849) at util/virsystemd.c:228
  228         dbus_message_unref(reply);
  (gdb) p reply
  $1 = (DBusMessage *) 0x0

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-02-11 11:35:02 +01:00
Ján Tomko
21e2e08191 virhook: do not save the return value of virBuildPath
This function returns -1 on allocation error, there's no
need to check the path for NULL again.
2016-02-11 08:05:17 +01:00
Michal Privoznik
d1a7102389 virStringListLength: Ensure const correctness
The virStringListLength function does not ever modify the passed
string list. It merely counts the items in it. Make sure that we
reflect this bit in the function header.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>

(crobinso: fix up spacing and squash in sheepdog bit suggested
 by Andrea)
2016-02-09 15:44:58 -05:00
Martin Kletzander
ea913d185d util: Get rid of virStringListLen()
It does exactly the same thing as virStringListLength() and it's used in
one place only.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-02-09 16:46:14 +01:00
Michal Privoznik
a0aa92a24b vircgroup: Update virCgroupGetPercpuStats stump
In the commit 7938b533 we've changed the function signature,
however forgot to update stump that's used on systems without
CGroups causing a build failure.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-02-08 14:06:30 +01:00
Peter Krempa
7938b533d5 cgroup: Prepare for sparse vCPU topologies in virCgroupGetPercpuStats
Pass a bitmap of enabled guest vCPUs to virCgroupGetPercpuStats so that
non-continuous vCPU topologies can be used.
2016-02-08 09:51:34 +01:00
John Ferlan
b8c0f18654 util: Fix virCgroupNewMachine ATTRIBUTE_NONNULL args
Commit id 'c3bd0019c0' removed arg3, but forgot to adjust the numbers
for NONNULL - caused build failure for coverity
2016-02-06 06:45:46 -05:00
Michal Privoznik
a3b168d01a virSystemdGetMachineNameByPID: Initialize @reply
I've noticed that variable @reply is not initialized and if
something at the beginning of the function fails, e.g.
virDBusGetSystemBus(), the control jump straight to cleanup label
where dbus_message_unref() is then called over this uninitialized
variable.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-02-05 17:17:45 +01:00
Michal Privoznik
065054daa7 virnetdevbandwidth: Compute quantum value
I've noticed couple of warning in dmesg while debugging
something:

[ 9683.973754] HTB: quantum of class 10001 is big. Consider r2q change.
[ 9683.976460] HTB: quantum of class 10002 is big. Consider r2q change.

I've read the HTB documentation and linux kernel code to find out
what's wrong. Basically we need to pass another argument
"quantum" to our tc cmd line because the default computed by HTB
does not always work in which case the warning message is printed
out.

You can read more details here:

http://luxik.cdi.cz/~devik/qos/htb/manual/userg.htm#sharing

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-02-05 16:43:19 +01:00
Peter Krempa
9479642fd3 util: bitmap: Introduce bitmap subtraction
Performs binary subtraction of two bitmaps. Stores result in the first
operand.
2016-02-05 16:21:45 +01:00
Martin Kletzander
c3bd0019c0 systemd: Modernize machine naming
So, systemd-machined has this philosophy that machine names are like
hostnames and hence should follow the same rules.  But we always allowed
international characters in domain names.  Thus we need to modify the
machine name we are passing to systemd.

In order to change some machine names that we will be passing to systemd,
we also need to call TerminateMachine at the end of a lifetime of a
domain.  Even for domains that were started with older libvirt.  That
can be achieved thanks to virSystemdGetMachineNameByPID().  And because
we can change machine names, we can get rid of the inconsistent and
pointless escaping of domain names when creating machine names.

So this patch modifies the naming in the following way.  It creates the
name as <drivername>-<id>-<name> where invalid hostname characters are
stripped out of the name and if the resulting name is longer, it
truncates it to 64 characters.  That way we can start domains we
couldn't start before.  Well, at least on systemd.

To make it work all together, the machineName (which is needed only with
systemd) is saved in domain's private data.  That way the generation is
moved to the driver and we don't need to pass various unnecessary
arguments to cgroup functions.

The only thing this complicates a bit is the scope generation when
validating a cgroup where we must check both old and new naming, so a
slight modification was needed there.

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

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-02-05 16:11:50 +01:00
Erik Skultety
8cd1d546e6 util: Export remoteSerializeTypedParameters internally via util
Same as for deserializer, this method might get handy for admin one day.
The major reason for this patch is to stay consistent with idea, i.e.
when deserializer can be shared, why not serializer as well. The only
problem to be solved was that the daemon side serializer uses a code
snippet which handles sparse arrays returned by some APIs as well as
removes any string parameters that can't be returned to older clients.
This patch makes of the new virTypedParameterRemote datatype introduced
by one of the pvious patches.
2016-02-03 15:46:45 +01:00
Erik Skultety
9afc115f73 util: Export remoteFreeTypedParameters internally via util
Since the method is static to remote_driver, it can't even be used by our
daemon. Other than that, it would be useful to be able to use it with admin as
well. This patch uses the new virTypedParameterRemote datatype introduced in
one of previous patches.
2016-02-03 15:46:45 +01:00
Erik Skultety
0472cef685 util: Export remoteDeserializeTypedParameters internally via util
Currently, the deserializer is hardcoded into remote_driver which makes
it impossible for admin to use it. One way to achieve a shared implementation
(besides moving the code to another module) would be pass @ret_params_val as a
void pointer as opposed to the remote_typed_param pointer and add a new extra
argument specifying which of those two protocols is being used and typecast
the pointer at the function entry. An example from remote_protocol:

struct remote_typed_param_value {
        int type;
        union {
                int i;
                u_int ui;
                int64_t l;
                uint64_t ul;
                double d;
                int b;
                remote_nonnull_string s;
        } remote_typed_param_value_u;
};
typedef struct remote_typed_param_value remote_typed_param_value;

struct remote_typed_param {
        remote_nonnull_string field;
        remote_typed_param_value value;
};

That would leave us with a bunch of if-then-elses that needed to be used across
the method. This patch takes the other approach using the new datatype
introduced in one of earlier commits.
2016-02-03 15:46:45 +01:00
Erik Skultety
41a459947f util: Introduce virTypedParameterRemote datatype
Both admin and remote protocols define their own types
(remote_typed_param vs admin_typed_param). Because of the naming convention,
admin typed params wouldn't be able to reuse the serialization/deserialization
methods, which are tailored for use by remote protocol, even if those method
were exported properly. In that case, introduce a new internal data type
structurally copying both admin and remote protocols which, eventually, would
allow serializer and deserializer to be used in a more generic way.
2016-02-03 15:46:45 +01:00
Martin Kletzander
92757d4d2d systemd: Add virSystemdGetMachineNameByPID
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-02-03 14:57:43 +01:00
Martin Kletzander
9ba2646291 Revert "systemd: Escape only needed characters for machined"
This reverts commit 0e0149ce91.

That commit was added to comply with systemd rules that were changed in
the meantime, so this patch is pointless.
2016-02-03 14:44:37 +01:00
Peter Krempa
58578f83bc cgroup: Clean up virCgroupGetPercpuStats
Use 'ret' for return variable name, clarify use of 'param_idx' and avoid
unnecessary 'success' label. No functional changes. Also document the
function.
2016-02-03 13:10:04 +01:00
Andrea Bolognani
11ef5869fb pci: Use bool return type for some virPCIDeviceGet*() functions
The affected functions are:

  virPCIDeviceGetManaged()
  virPCIDeviceGetUnbindFromStub()
  virPCIDeviceGetRemoveSlot()
  virPCIDeviceGetReprobe()

Change their return type from unsigned int to bool: the corresponding
members in struct _virPCIDevice are defined as bool, and even the
corresponding virPCIDeviceSet*() functions take a bool value as input
so there's no point in these functions having unsigned int as return
type.

Suggested-by: John Ferlan <jferlan@redhat.com>
2016-01-28 17:27:58 +01:00
Andrea Bolognani
171607296d pci: Add debug messages when unbinding from stub driver
Unbinding a PCI device from the stub driver can require several steps,
and it can be useful for debugging to be able to trace which of these
steps are performed and which are skipped for each device.
2016-01-28 12:20:53 +01:00
Andrea Bolognani
771eaeb2b3 pci: Phase out virPCIDeviceReattachInit()
The name is confusing, and there are just two uses: one is a test case,
and the other will be removed as part of an upcoming refactoring of
the hostdev code.
2016-01-28 11:31:28 +01:00
Andrea Bolognani
d87f0c0052 virnetdevopenvswitch: Don't call strlen() twice on the same string
Commit 871e10f fixed a memory corruption error, but called strlen()
twice on the same string to do so. Even though the compiler is
probably smart enough to optimize the second call away, having a
single invocation makes the code slightly cleaner.

Suggested-by: Michal Privoznik <mprivozn@redhat.com>
2016-01-27 13:01:24 +01:00
Michal Privoznik
720bc953f8 virnetdevmacvlan: Provide stubs for build without macvtap
In 370608b4c7 we have introduced two new internal APIs.
However, there are no stubs for build without macvtap. Therefore
build on systems lacking macvtap support (e.g. mingw or freebds)
fails when trying to link.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-01-27 10:07:46 +01:00
Jason J. Herne
871e10fc95 Fix libvirtd free() segfault when migrating guest with deleted open vswitch port
libvirtd crashes on free()ing portData for an open vswitch port if that port
was deleted.  To reproduce:

ovs-vsctl del-port vnet0
virsh migrate --live kvm1 qemu+ssh://dstHost/system

Error message:
libvirtd: *** Error in `/usr/sbin/libvirtd': free(): invalid pointer: 0x000003ff90001e20 ***

The problem is that virCommandRun can return an empty string in the event that
the port being queried does not exist. When this happens then we are
unconditionally overwriting a newline character at position strlen()-1. When
strlen is 0, we overwrite memory that does not belong to the string.

The fix: Only overwrite the newline if the string is not empty.

Reviewed-by: Bjoern Walk <bwalk@linux.vnet.ibm.com>
Signed-off-by: Jason J. Herne <jjherne@linux.vnet.ibm.com>
2016-01-27 10:01:58 +01:00
Laine Stump
370608b4c7 util: keep/use a bitmap of in-use macvtap devices
This patch creates two bitmaps, one for macvlan device names and one
for macvtap. The bitmap position is used to indicate that libvirt is
currently using a device with the name macvtap%d/macvlan%d, where %d
is the position in the bitmap. When requested to create a new
macvtap/macvlan device, libvirt will now look for the first clear bit
in the appropriate bitmap and derive the device name from that rather
than just starting at 0 and counting up until one works.

When libvirtd is restarted, the qemu driver code that reattaches to
active domains calls the appropriate function to "re-reserve" the
device names as it is scanning the status of running domains.

Note that it may seem strange that the retry counter now starts at
8191 instead of 5. This is because we now don't do a "pre-check" for
the existence of a device once we've reserved it in the bitmap - we
move straight to creating it; although very unlikely, it's possible
that someone has a running system where they have a large number of
network devices *created outside libvirt* named "macvtap%d" or
"macvlan%d" - such a setup would still allow creating more devices
with the old code, while a low retry max in the new code would cause a
failure. Since the objective of the retry max is just to prevent an
infinite loop, and it's highly unlikely to do more than 1 iteration
anyway, having a high max is a reasonable concession in order to
prevent lots of new failures.
2016-01-26 12:20:04 -05:00
Leno Hou
8c70d04bab util: increase libnl buffer size
In the following cases nl_recv() was returning the error "No buffer
space available":

* When switching CPUs to offline/online in a system more than 128 cpus
* When using virsh to destroy domain in a system with many interfaces

This patch sets the buffer size for all netlink sockets created by
libnl to 128K and turns on message peeking for nl_recv(). This
eliminates the "No buffer space available" errors seen in the cases
above, and also preempts other future errors the smaller buffers could
have caused.

Signed-off-by: Leno Hou <houqy@linux.vnet.ibm.com>
Signed-off-by: Laine Stump <laine@laine.org>
2016-01-26 12:20:04 -05:00
Michal Privoznik
c7f5e26b5f vircgroup: Finish renaming of virCgroupIsolateMount
In dc576025c3 we renamed virCgroupIsolateMount function to
virCgroupBindMount. However, we forgot about one occurrence in
section of the code which provides stubs for platforms without
support for CGroups like *BSD for instance.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2016-01-26 17:39:47 +01:00
Daniel P. Berrange
dc576025c3 lxc: don't try to hide parent cgroups inside container
On the host when we start a container, it will be
placed in a cgroup path of

   /machine.slice/machine-lxc\x2ddemo.scope

under /sys/fs/cgroup/*

Inside the containers' namespace we need to setup
/sys/fs/cgroup mounts, and currently will bind
mount /machine.slice/machine-lxc\x2ddemo.scope on
the host to appear as / in the container.

While this may sound nice, it confuses applications
dealing with cgroups, because /proc/$PID/cgroup
now does not match the directory in /sys/fs/cgroup

This particularly causes problems for systems and
will make it create repeated path components in
the cgroup for apps run in the container eg

  /machine.slice/machine-lxc\x2ddemo.scope/machine.slice/machine-lxc\x2ddemo.scope/user.slice/user-0.slice/session-61.scope

This also causes any systemd service that uses
sd-notify to fail to start, because when systemd
receives the notification it won't be able to
identify the corresponding unit it came from.
In particular this break rabbitmq-server startup

Future kernels will provide proper cgroup namespacing
which will handle this problem, but until that time
we should not try to play games with hiding parent
cgroups.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2016-01-26 16:11:32 +00:00