Commit Graph

541 Commits

Author SHA1 Message Date
John Ferlan
4fac5a9fd3 Use virGetLastErrorMessage to avoid Coverity message
Both instances use VIR_WARN() to print the error from a failed
virDBusGetSystemBus() call.  Rather than use the virGetLastError
and need to check for valid return err pointer, just use the
virGetLastErrorMessage.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2016-05-09 19:33:56 -04:00
Cole Robinson
26af7e4e93 network: Fix segfault on daemon reload
We will segfault of a daemon reload picks up a new network config
that needs to be autostarted. We shouldn't be passing NULL for
network_driver here. This seems like it was missed in the larger
rework in commit 1009a61e
2016-05-02 10:06:04 -04:00
Martin Kletzander
c36b1f7b6a Change virDevicePCIAddress to virPCIDeviceAddress
We had both and the only difference was that the latter also included
information about multifunction setting.  The problem with that was that
we couldn't use functions made for only one of the structs (e.g.
parsing).  To consolidate those two structs, use the one in virpci.h,
include that in domain_conf.h and add the multifunction member in it.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2016-05-02 15:46:23 +02:00
Laine Stump
bf3d9f305e network: fix DHCPv6 on networks with prefix != 64
According to the dnsmasq manpage, the netmask for IPv4 address ranges
will be auto-deteremined from the interface dnsmasq is listening on,
but it can't do this for IPv6 for some reason - it instead assumes a
network prefix of 64 for all IPv6 address ranges. If this is
incorrect, dnsmasq will refuse to give out an address to clients,
instead logging this message:

 dnsmasq-dhcp[2380]: no address range available for DHCPv6 request via virbr0

The solution is for libvirt to add ",$prefix" to all IPv6 dhcp-range
arguments when building the dnsmasq.conf file.

Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1033739
2016-04-21 15:06:25 -04:00
Cole Robinson
e7db227810 util: Add virGettextInitialize, convert the code
Take setlocale/gettext error handling pattern from tools/virsh-*
and use it for all standalone binaries via a new shared
virGettextInitialize routine. The virsh* pattern differed slightly
from other callers. All users now consistently:

* Ignore setlocale errors. virsh has done this forever, presumably for
  good reason. This has been partially responsible for some bug reports:

  https://bugzilla.redhat.com/show_bug.cgi?id=1312688
  https://bugzilla.redhat.com/show_bug.cgi?id=1026514
  https://bugzilla.redhat.com/show_bug.cgi?id=1016158

* Report the failed function name
* Report strerror
2016-04-14 13:22:40 -04: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
0dc49e237a network: Remove extraneous ATTRIBUTE_NONNULL
Commit id '3992ff14' added the prototype for networkGetActualType
with 1 parameter, but added 2 ATTRIBUTE_NONNULL's (assume from a
cut-n-paste), just remove (2).
2016-04-05 05:43:47 -04:00
Laine Stump
3992ff14e5 network: new function networkGetActualType
There are times when it's necessary to learn the actual type of a
network connection before any resources have been allocated
(e.g. during qemuProcessPrepareDomain()), but in the past it was
necessary to call networkAllocateActualDevice() in order to have the
actual type filled in.

This new function returns the type of network that *will be* setup
once it actually happens, but without making any changes on the host.
2016-04-04 07:03:12 -04:00
Laine Stump
b41261f010 network: call proper start/stop functions for macvtap bridge-mode networks
networkStartNetwork() and networkShutdownNetwork() were calling the
wrong type-specific function in the case of networks that were
configured for macvtap ("direct") bridge mode - they were instead
calling the functions for a tap+bridge network. Currently none of
these functions does anything (they just return 0) so it hasn't
created any problems, but that could change in the future.
2016-03-25 13:28:34 -04:00
Laine Stump
2a537fe187 network: differentiate macvtap/bridge from host-bridge based networks
Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1316465

An attempt to simplify the code for the VIR_NETWORK_FORWARD_BRIDGE
case of networkUpdateState in commit b61db335 (first in release
1.2.14) resulted in networks based on macvtap bridge mode being
erroneously marked as inactive any time libvirtd was restarted.

The problem is that the original code had differentiated between a
network using tap devices to connect to an existing host-bridge device
(forward mode of VIR_NETWORK_FORWARD_BRIDGE and a non-NULL
def->bridge), and one using macvtap bridge mode to connect to any
ethernet device (still forward mode VIR_NETWORK_FORWARD_BRIDGE, but
null def->bridge), but the changed code assumed that all networks with
VIR_NETWORK_FORWARD_BRIDGE were tap + host-bridge networks, so a null
def->bridge was interpreted as "inactive".

This patch restores the original code in networkUpdateState
2016-03-25 13:21:29 -04: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
Shanzhi Yu
347035f959 qemu: improve the error when try to undefine transient network
Resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1315059

Signed-off-by: Shanzhi Yu <shyu@redhat.com>
2016-03-07 10:15:53 +01:00
Laine Stump
eb72bd63c1 network: consolidated info log for all network allocate/free operations
There are three functions that deal with allocating and freeing
devices from a networks netdev/pci device pool:
network(Allocate|Notify|Release)ActualDevice(). These functions also
maintain a counter of the number of domains currently using a network
(regardless of whether or not that network uses a device pool). Each
of these functions had multiple log messages (output using VIR_DEBUG)
that were in slightly different formats and gave varying amounts of
information.

This patch creates a single function to log the pertinent information
in a consistent manner for all three of these functions. Along with
assuring that all the functions produce a consistent form of output
(and making it simpler to change), it adds the MAC address of the
domain interface involved in the operation, making it possible to
verify which interface of which domain the operation is being done for
(assuming that all MAC addresses are unique, of course).

All of these messages are raised from DEBUG to INFO, since they don't
happen that often (once per interface per domain/libvirtd start or
domain stop), and can be very informative and helpful - eliminating
the need to log debug level messages makes it much easier to sort
these out.
2016-02-14 11:28:45 -05:00
Laine Stump
3ea8b8b87f network: consolidate connection count updates for device pool
networkReleaseActualDevice() and networkNotifyActualDevice() both were
updating the individual devices' connections count in two separate
places (unlike networkAllocateActualDevice() which does it in a single
unified place after success:). The code is correct, but prone to
confusion / later breakage. All of these updates are anyway located at
the end of if/else clauses that are (with the exception of a single
VIR_DEBUG() in each case) immediately followed by the success: label
anyway, so this patch replaces the duplicated ++/-- instructions with
a single ++/-- inside a qualifying "if (dev)" down below success:.
(NB: if dev != NULL, by definition we are using a device (either pci
or netdev, doesn't matter for these purposes) from the network's pool)

The VIR_DEBUG args (which will be replaced in a followup patch anyway)
were all adjusted to account for the connection count being out of
date at the time.
2016-02-14 11:27:27 -05:00
Ján Tomko
99a6f30db0 leaseshelper: swap two parameters of virLeaseNew
My commit e11aa74 messed up the parameter order.

Reported by John Ferlan.
2016-02-09 13:15:59 +01:00
Ján Tomko
e11aa74933 leaseshelper: split out virLeaseNew
For the actions ADD and OLD, split out creating the new lease object,
as well as getting the environment variables that do not affect
the parsing of command line arguments.
2016-02-09 08:48:14 +01:00
Joao Martins
d239a5427f conf: add caps to virDomainDefFormat*
And use the newly added caps->host.netprefix (if it exists) for
interface names that match the autogenerated target names.

Signed-off-by: Joao Martins <joao.m.martins@oracle.com>
2016-02-04 12:38:26 +00:00
Ján Tomko
ce9085eba1 leaseshelper: reduce indentation level in virLeaseReadCustomLeaseFile
Instead of nested ifs, jump out early.

Mostly whitespace changes.
2016-01-20 10:01:52 +01:00
Ján Tomko
d7049a67b6 leaseshelper: remove useless comparison
We do not care if the mac was specified in the delete section,
we are going to delete the record anyway.
2016-01-20 09:35:50 +01:00
Ján Tomko
99569948d3 leaseshelper: move comment about adding IPv6 leases
The comment is relevant to the ADD action, not DEL.
2016-01-20 09:34:47 +01:00
Ján Tomko
21fb379549 leaseshelper: split out virLeasePrintLeases
Introduce a function for printing the leases on the 'init' operation.
2016-01-20 09:33:44 +01:00
Ján Tomko
7f9c425bfb leaseshelper: split out custom leases file read
Introduce virLeaseReadCustomLeaseFile which will populate
the new leases array with all the leases, except for expired
ones and the ones matching 'ip_to_delete'.

This removes five variables from main().
2016-01-20 09:33:44 +01:00
Ján Tomko
9e7e7662bf leaseshelper: store server_duid as an allocated string
We either use the value from the environment variable, or learn it from
the existing lease file.

In the second case, the pointer would be pointing into the JSON object
of the first lease with a DUID, owned by leases_array, then
leases_array_new.

Always allocate the string instead, making obvious who should free the
string.
2016-01-20 09:33:44 +01:00
Ján Tomko
df9fe124d6 leaseshelper: fix crash when no mac is specified
If dnsmasq specified DNSMASQ_IAID (so we're dealing with an IPv6
lease) but no DNSMASQ_MAC, we skip creation of the new lease object.

Also skip adding it to the leases array.

https://bugzilla.redhat.com/show_bug.cgi?id=1202350
2016-01-20 09:32:59 +01:00
Ján Tomko
1e6d87bdfc bridge: check for invalid MAC in networkGetDHCPLeases
Instead of comparing garbage strings against real MAC addresses,
introduce an error mesage for unparsable ones:

$ virsh net-dhcp-leases default  --mac t12
error: Failed to get leases info for default
error: invalid MAC address: t12

https://bugzilla.redhat.com/show_bug.cgi?id=1261432
2015-12-03 10:15:22 +01:00
Laine Stump
f391889f4e nodedev: report maxCount for virtual_functions capability
A PCI device may have the capability to setup virtual functions (VFs)
but have them currently all disabled. Prior to this patch, if that was
the case the the node device XML for the device wouldn't report any
virtual_functions capability.

With this patch, if a file called "sriov_totalvfs" is found in the
device's sysfs directory, its contents will be interpreted as a
decimal number, and that value will be reported as "maxCount" in a
capability element of the device's XML, e.g.:

   <capability type='virtual_functions' maxCount='7'/>

This will be reported regardless of whether or not any VFs are
currently enabled for the device.

NB: sriov_numvfs (the number of VFs currently active) is also
available in sysfs, but that value is implied by the number of items
in the list that is inside the capability element, so there is no
reason to explicitly provide it as an attribute.

sriov_totalvfs and sriov_numvfs are available in kernels at least as far
back as the 2.6.32 that is in RHEL6.7, but in the case that they
simply aren't there, libvirt will behave as it did prior to this patch
- no maxCount will be displayed, and the virtual_functions capability
will be absent from the device's XML when 0 VFs are enabled.
2015-11-24 12:31:04 -05:00
Maxim Perevedentsev
0f7436ca54 network: wait for DAD to finish for bridge IPv6 addresses
commit db488c79 assumed that dnsmasq would complete IPv6 DAD before
daemonizing, but in reality it doesn't wait, which creates problems
when libvirt's bridge driver sets the matching "dummy tap device" to
IFF_DOWN prior to DAD completing.

This patch waits for DAD completion by periodically polling the kernel
using netlink to check whether there are any IPv6 addresses assigned
to bridge which have a 'tentative' state (if there are any in this
state, then DAD hasn't yet finished). After DAD is finished, execution
continues. To avoid an endless hang in case something was wrong with
the kernel's DAD, we wait a maximum of 5 seconds.
2015-10-28 21:48:04 -04:00
Michal Privoznik
4f77c48cba virJSONValueArraySize: return ssize_t
The internal representation of a JSON array counts the items in
size_t. However, for some reason, when asking for the count it's
reported as int. Firstly, we need the function to return a signed
type as it's returning -1 on an error. But, not every system has
integer the same size as size_t. Therefore, lets return ssize_t.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-10-09 15:25:08 +02:00
Michal Privoznik
f7fba69bd7 networkBandwidthGenericChecks: Drop useless check
There's a check right at the beginning of the function that
shortcuts if the function was called over all NULL arguments.
However, this was meant just as a fool-proof check so that we
don't crash if function is used in a bad manner. Anyway, it makes
Coverity unhappy as it then thinks any of the arguments could be
NULL. Well, with the current state of the code it can't.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-12 10:57:36 +02:00
Michal Privoznik
ef6b3b625d networkBandwidthUpdate: Don't blindly dereference pointers
It may happen that an interface don't have any bandwidth set and
a new one is to be set. In that case, @ifaceBand will be NULL.
This will cause troubles later in the code when deciding what to
do.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-12 10:57:36 +02:00
Michal Privoznik
812932bea2 bridge_driver: Introduce networkBandwidthUpdate
So, if a domain vNIC's bandwidth has been successfully set, it's
possible that because @floor is set on network's bridge, this
part may need updating too. And that's exactly what this function
does. While the previous commit introduced a function to check if
@floor can be satisfied, this does all the hard work. In general,
there may be three, well four possibilities:

  1) No change in @floor value (either it remain unset, or its
  value hasn't changed)

  2) The @floor value has changed from a non-zero to a non-zero
  value

  3) New @floor is to be set

  4) Old @floor must be cleared out

The difference between 2), 3) and 4) is, that while in 2) the QoS
tree on the network's bridge already has a special class for the
vNIC, in 3) the class must be created from scratch. In 4) it must
be removed. Fortunately, we have helpers for all three
interesting cases.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-11 16:10:32 +02:00
Michal Privoznik
41a1531de5 bridge_driver: Introduce networkBandwidthChangeAllowed
When a domain vNIC's bandwidth is to be changed (at runtime) it is
possible that guaranteed minimal bandwidth (@floor) will change too.
Well, so far it is, because we still don't have an implementation that
allows setting it dynamically, so it's effectively erased on:

    #virsh domiftune $dom vnet0 --inbound 0

However, that's slightly unfortunate. We do some checks on domain
startup to see if @floor can be guaranteed. We ought do the same if
QoS is changed at runtime.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-11 16:10:32 +02:00
Michal Privoznik
45090449c4 virNetDevBandwidthUpdateRate: turn class_id into integer
This is no functional change. It's just that later in the series we
will need to pass class_id as an integer.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-08-11 16:10:32 +02:00
Martin Kletzander
0e3ad241f3 network: Add another collision check into networkCheckRouteCollision
The comment above that function says: "This function can be a lot more
exhaustive, ...", so let's be.

Check for collisions between routes in the system and static routes
being added explicitly from the <route/> element of the network XML.

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

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-07-14 09:56:44 +02:00
Ján Tomko
12b949dfb2 maint: remove incorrect apostrophes from 'its' 2015-06-04 10:01:42 +02:00
Laine Stump
55ace7c478 util: report all address range errors in virSocketAddrGetRange()
There are now many more reasons that virSocketAddrGetRange() could
fail, so it is much more informative to report the error there instead
of in the caller. (one of the two callers was previously assuming
success, which is almost surely safe based on the parsing that has
already happened to the config by that time, but it still is nicer to
account for an error "just in case")

Part of fix for: https://bugzilla.redhat.com/show_bug.cgi?id=985653
2015-06-02 12:40:07 -04:00
Laine Stump
198d503c64 network: cleanup range loop in networkDnsmasqConfContents
This loop had automatic variable definitions mixed with code. This
patch moves the definitions to the top of the function and puts
cleanup for them at the bottom. No functional change.

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

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

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=985653
2015-06-02 12:40:07 -04:00
John Ferlan
38f0fc19af network: Resolve Coverity FORWARD_NULL
To silence Coverity just add a 'p &&' in front of the check in
networkFindUnusedBridgeName after the strchr() call.  Even though
we know it's not possible to have strchr return NULL since the only
way into the function is if there is a '%' in def->bridge or it's NULL.

Signed-off-by: John Ferlan <jferlan@redhat.com>
2015-05-24 07:01:48 -04:00
Martin Kletzander
564dd53791 Fix build --without-network
In order not to bring in any link dependencies, bridge driver doesn't
use the usual stubs as other conditionally-built code does.  However,
having the function as a macro imposes a problem with possibly unused
variables if just defined as "0".  This was worked around by using
(dom=dom, iface=iface, 0) which should act like a 0 if used in a
condition.  However, gcc still bugs about that, so I came up with
another way how to fix that.

Using static inline functions in the header won't collide with anything,
it fixes the bug and does one thing that the macro didn't do.  It checks
whenther passed variables are pointers of compatible type.  It has only
one downside, and that is that we need to either a) define it with
ATTRIBUTE_UNUSED, which needs an exception in cfg.mk or b) do something
like ignore_value(variable); in the function body.  I went with the
first variant.

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-05-13 15:04:41 +02:00
Ján Tomko
076dd37995 Ignore bridge template names with multiple printf conversions
For some reason, we allow a bridge name with %d in it, which we replace
with an unsigned integer to form a bridge name that does not yet exist
on the host.

Do not blindly pass it to virAsprintf if it's not the only conversion,
to prevent crashing on input like:

<network>
  <name>test</name>
  <forward mode='none'/>
  <bridge name='virbr%d%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s'/>
</network>

Ignore any template strings that do not have exactly one %d conversion,
like we do in various drivers before calling virNetDevTapCreateInBridgePort.
2015-05-11 14:14:33 +02:00
Laine Stump
37b8bc6f12 network: check for bridge name conflict with existing devices
Since some people use the same naming convention as libvirt for bridge
devices they create outside the context of libvirt, it is much nicer
if we check for those devices when looking for a bridge device name to
auto-assign to a new network.
2015-04-28 01:21:41 -04:00
Laine Stump
a28d3e485f network: move auto-assign of bridge name from XML parser to net driver
We already check that any auto-assigned bridge device name for a
virtual network (e.g. "virbr1") doesn't conflict with the bridge name
for any existing libvirt network (via virNetworkSetBridgeName() in
conf/network_conf.c).

We also want to check that the name doesn't conflict with any bridge
device created on the host system outside the control of libvirt
(history: possibly due to the ploriferation of references to libvirt's
bridge devices in HOWTO documents all around the web, it is not
uncommon for an admin to manually create a bridge in their host's
system network config and name it "virbrX"). To add such a check to
virNetworkBridgeInUse() (which is called by virNetworkSetBridgeName())
we would have to call virNetDevExists() (from util/virnetdev.c); this
function calls ioctl(SIOCGIFFLAGS), which everyone on the mailing list
agreed should not be done from an XML parsing function in the conf
directory.

To remedy that problem, this patch removes virNetworkSetBridgeName()
from conf/network_conf.c and puts an identically functioning
networkBridgeNameValidate() in network/bridge_driver.c (because it's
reasonable for the bridge driver to call virNetDevExists(), although
we don't do that yet because I wanted this patch to have as close to 0
effect on function as possible).

There are a couple of inevitable changes though:

1) We no longer check the bridge name during
   virNetworkLoadConfig(). Close examination of the code shows that
   this wasn't necessary anyway - the only *correct* way to get XML
   into the config files is via networkDefine(), and networkDefine()
   will always call networkValidate(), which previously called
   virNetworkSetBridgeName() (and now calls
   networkBridgeNameValidate()). This means that the only way the
   bridge name can be unset during virNetworkLoadConfig() is if
   someone edited the config file on disk by hand (which we explicitly
   prohibit).

2) Just on the off chance that somebody *has* edited the file by hand,
   rather than crashing when they try to start their malformed
   network, a check for non-NULL bridge name has been added to
   networkStartNetworkVirtual().

   (For those wondering why I don't instead call
   networkValidateBridgeName() there to set a bridge name if one
   wasn't present - the problem is that during
   networkStartNetworkVirtual(), the lock for the network being
   started has already been acquired, but the lock for the network
   list itself *has not* (because we aren't adding/removing a
   network). But virNetworkBridgeInuse() iterates through *all*
   networks (including this one) and locks each network as it is
   checked for a duplicate entry; it is necessary to lock each network
   even before checking if it is the designated "skip" network because
   otherwise some other thread might acquire the list lock and delete
   the very entry we're examining. In the end, permitting a setting of
   the bridge name during network start would require that we lock the
   entire network list during any networkStartNetwork(), which
   eliminates a *lot* of parallelism that we've worked so hard to
   achieve (it can make a huge difference during libvirtd startup). So
   rather than try to adjust for someone playing against the rules, I
   choose to instead give them the error they deserve.)

3) virNetworkAllocateBridge() (now removed) would leak any "template"
   string set as the bridge name. Its replacement
   networkFindUnusedBridgeName() doesn't leak the template string - it
   is properly freed.
2015-04-28 01:20:11 -04:00
Ján Tomko
031323830d Support IPv6 in networkGetNetworkAddress
We've been explicitly requesting IPv4 for some reason,
even if there were only IPv6 addresses in the network
definition.

https://bugzilla.redhat.com/show_bug.cgi?id=1192318
2015-04-10 15:01:17 +02:00
John Ferlan
61fee39967 util: Replace virNetDevGetIPv4Address with virNetDevGetIPAddress
Rename it to virNetDevGetIPv4AddressIoctl and make
virNetDevGetIPAddress a wrapper around it, allowing
other ways of getting the address to be implemented,
and still falling back to the old method.

Signed-off-by: John Ferlan <jferlan@redhat.com>
Signed-off-by: Ján Tomko <jtomko@redhat.com>
2015-04-10 15:01:17 +02:00
Michal Privoznik
d9706aea18 network_conf: Drop virNetworkObjIsDuplicate
This function does not make any sense now, that network driver is
(almost) dropped. I mean, previously, when threads were
serialized, this function was there to check, if no other network
with the same name or UUID exists. However, nowadays that threads
can run more in parallel, this function is useless, in fact it
gives misleading return values. Consider the following scenario.
Two threads, both trying to define networks with same name but
different UUID (e.g. because it was generated during XML parsing
phase, whatever). Lets assume that both threads are about to call
networkValidate() which immediately calls
virNetworkObjIsDuplicate().

T1: calls virNetworkObjIsDuplicate() and since no network with
given name or UUID exist, success is returned.
T2: calls virNetworkObjIsDuplicate() and since no network with
given name or UUID exist, success is returned.

T1: calls virNetworkAssignDef() and successfully places its
network into the virNetworkObjList.
T2: calls virNetworkAssignDef() and since network with the same
name exists, the network definition is replaced.

Okay, this is mainly because virNetworkAssignDef() does not check
whether name and UUID matches. Well, lets make it so! And drop
useless function too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-23 09:56:15 +01:00
Michal Privoznik
dd7bfb2cdc networkStateInitialize: Don't lock network driver
There's no need to lock the network driver, as network driver
initialization is done prior accepting any client. There's nobody
to hop in and do something over partially initialized driver. Nor
qemu driver is doing that.

==30532== Observed (incorrect) order is: acquisition of lock at 0x1439EF50
==30532==    at 0x4C31A26: pthread_mutex_lock (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0x5324895: virMutexLock (virthread.c:88)
==30532==    by 0x5307E86: virObjectLock (virobject.c:323)
==30532==    by 0x5396440: virNetworkObjListForEach (network_conf.c:4511)
==30532==    by 0x19B29308: networkStateInitialize (bridge_driver.c:686)
==30532==    by 0x53E1CCC: virStateInitialize (libvirt.c:777)
==30532==    by 0x11DEB7: daemonRunStateInit (libvirtd.c:906)
==30532==    by 0x5324B6A: virThreadHelper (virthread.c:197)
==30532==    by 0x4C30456: ??? (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0xA1EC1F2: start_thread (in /lib64/libpthread-2.19.so)
==30532==    by 0xA4EDC8C: clone (in /lib64/libc-2.19.so)
==30532==
==30532==  followed by a later acquisition of lock at 0x1439CD60
==30532==    at 0x4C31A26: pthread_mutex_lock (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0x5324895: virMutexLock (virthread.c:88)
==30532==    by 0x19B27B2C: networkDriverLock (bridge_driver.c:102)
==30532==    by 0x19B27B60: networkGetDnsmasqCaps (bridge_driver.c:113)
==30532==    by 0x19B2856A: networkUpdateState (bridge_driver.c:389)
==30532==    by 0x53963E9: virNetworkObjListForEachHelper (network_conf.c:4488)
==30532==    by 0x52E2224: virHashForEach (virhash.c:521)
==30532==    by 0x539645B: virNetworkObjListForEach (network_conf.c:4512)
==30532==    by 0x19B29308: networkStateInitialize (bridge_driver.c:686)
==30532==    by 0x53E1CCC: virStateInitialize (libvirt.c:777)
==30532==    by 0x11DEB7: daemonRunStateInit (libvirtd.c:906)
==30532==    by 0x5324B6A: virThreadHelper (virthread.c:197)
==30532==
==30532== Required order was established by acquisition of lock at 0x1439CD60
==30532==    at 0x4C31A26: pthread_mutex_lock (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0x5324895: virMutexLock (virthread.c:88)
==30532==    by 0x19B27B2C: networkDriverLock (bridge_driver.c:102)
==30532==    by 0x19B28DF9: networkStateInitialize (bridge_driver.c:609)
==30532==    by 0x53E1CCC: virStateInitialize (libvirt.c:777)
==30532==    by 0x11DEB7: daemonRunStateInit (libvirtd.c:906)
==30532==    by 0x5324B6A: virThreadHelper (virthread.c:197)
==30532==    by 0x4C30456: ??? (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0xA1EC1F2: start_thread (in /lib64/libpthread-2.19.so)
==30532==    by 0xA4EDC8C: clone (in /lib64/libc-2.19.so)
==30532==
==30532==  followed by a later acquisition of lock at 0x1439EF50
==30532==    at 0x4C31A26: pthread_mutex_lock (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0x5324895: virMutexLock (virthread.c:88)
==30532==    by 0x5307E86: virObjectLock (virobject.c:323)
==30532==    by 0x538A09C: virNetworkAssignDef (network_conf.c:527)
==30532==    by 0x5391EB2: virNetworkLoadState (network_conf.c:3008)
==30532==    by 0x53922D4: virNetworkLoadAllState (network_conf.c:3128)
==30532==    by 0x19B2929A: networkStateInitialize (bridge_driver.c:671)
==30532==    by 0x53E1CCC: virStateInitialize (libvirt.c:777)
==30532==    by 0x11DEB7: daemonRunStateInit (libvirtd.c:906)
==30532==    by 0x5324B6A: virThreadHelper (virthread.c:197)
==30532==    by 0x4C30456: ??? (in /usr/lib64/valgrind/vgpreload_helgrind-amd64-linux.so)
==30532==    by 0xA1EC1F2: start_thread (in /lib64/libpthread-2.19.so)

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

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

Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2015-03-23 09:01:30 +01:00
John Ferlan
0e3c68acd8 network: Resolve Coverity FORWARD_NULL
The following is a long winded way to say this patch is avoiding a
false positive.

Coverity complains that calling networkPlugBandwidth() could eventually
end up with a NULL dereference on iface->bandwidth because in the
networkAllocateActualDevice there's a check of 'iface->bandwidth'
before deciding to try to use the 'portgroup' if it exists or to not
perferm the virNetDevBandwidthCopy if 'bandwidth' is not NULL.

Later in networkPlugBandwidth the 'iface->bandwidth' is sourced from
virDomainNetGetActualBandwidth - which would be either iface->bandwidth
or (preferably) iface->data.network.actual->bandwidth which would have
been filled in from either 'iface->bandwidth' or 'portgroup->bandwidth'
back in networkAllocateActualDevice

There *is* a check in networkCheckBandwidth for the result of the
virDomainNetGetActualBandwidth being NULL and a return 1 based on
that which would cause networkPlugBandwidth to exit properly and thus
never hit the condition that Coverity complains about.

However, since Coverity checks all paths - it somehow believes that
a return of 0 by networkCheckBandwidth in this condition would end
up causing the possible NULL dereference. The "fix" to silence Coverity
is to not have networkCheckBandwidth also call virDomainNetGetActualBandwidth
in order to get the ifaceBand, but rather have it accept it as an argument
which causes Coverity to "see" that it's the exit condition of 1 that won't
have the possible NULL dereference.  Since we're passing that, I added the
passing of iface->mac rather than passing iface as well. This just hopefully
makes sure someone doesn't undo this in the future...
2015-03-18 06:56:24 -04:00
Eric Blake
eea08abec5 network: avoid memory leak of dnsmasq capabilities
Valgrind detected a leak:

==17820== 102 (56 direct, 46 indirect) bytes in 1 blocks are definitely lost in loss record 479 of 646
==17820==    at 0x4A08946: calloc (in /usr/lib64/valgrind/vgpreload_memcheck-amd64-linux.so)
==17820==    by 0x508521A: virAllocVar (viralloc.c:560)
==17820==    by 0x50D9FCA: virObjectNew (virobject.c:193)
==17820==    by 0x50A4FD9: dnsmasqCapsNewEmpty (virdnsmasq.c:784)
==17820==    by 0x50A514E: dnsmasqCapsNewFromBinary (virdnsmasq.c:830)
==17820==    by 0x1B508287: networkStateInitialize (bridge_driver.c:666)

It looks like commit 172acef introduced the problem, because
networkGetDnsmasqCaps() increments the reference count but an
early exit never does a matching decrement.

* src/network/bridge_driver.c (networkStateCleanup): Plug leak.

Signed-off-by: Eric Blake <eblake@redhat.com>
2015-03-14 21:01:26 -06:00
Michal Privoznik
eb7b635582 bridge_driver: Use more of networkObjFromNetwork
Now that the network driver lock is ash heap of history,
we can use more of networkObjFromNetwork().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-13 15:55:56 +01:00
Michal Privoznik
af338d5f51 bridge_driver: Drop networkDriverLock() from almost everywhere
Now that we have fine grained locks, there's no need to
lock the whole driver. We can rely on self-locking APIs.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-13 15:55:56 +01:00
Michal Privoznik
376b97799e struct _virNetworkDriverState: Annotate items
In order to drop network driver lock, lets annotate which
structure items are immutable, which have self-locking
APIs and so on.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-13 15:55:56 +01:00
Michal Privoznik
172acef486 network_driver: Use accessor for dnsmasqCaps
This is not an immutable pointer and can change during lifetime.
Therefore, in order to drop network driver lock, we must use an
internal accessor which does not lock the network driver yet, but
it will soon. Now it merely returns an referenced object.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-13 15:55:56 +01:00
Michal Privoznik
1009a61ecb bridge_driver: Don't access global driver randomly
Well, network driver code has the driver accessible as a global
variable. This makes any rework hard, as it's unclear where the
variable is accessed and/or modified. Lets just pass the driver
as a parameter to all functions where needed.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-13 15:55:56 +01:00
Michal Privoznik
68818dcdd5 virNetworkObjFindBy*: Return an reference to found object
This patch turns both virNetworkObjFindByUUID() and
virNetworkObjFindByName() to return an referenced object so that
even if caller unlocks it, it's for sure that object won't
disappear meanwhile. Especially if the object (in general) is
locked and unlocked during the caller run.
Moreover, this commit is nicely small, since the object unrefing
can be done in virNetworkObjEndAPI().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-11 16:58:49 +01:00
Michal Privoznik
37c2bad77d bridge_driver: Use virNetworkObjEndAPI
So far, this is pure code replacement. But once we introduce
reference counting to virNetworkObj this will be more handy as
there'll be only one function to change: virNetworkObjEndAPI().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-11 16:58:48 +01:00
Michal Privoznik
ea57049156 network_conf: Make virNetworkObj actually virObject
So far it's just a structure which happens to have 'Obj' in its
name, but otherwise it not related to virObject at all. No
reference counting, not virObjectLock(), nothing.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-11 16:58:48 +01:00
Michael Chapman
a6ec4f472d {domain, network}_conf: disable autostart when deleting config
Undefining a running, autostarted domain removes the autostart link, but
dom->autostart is not cleared. If the domain is subsequently redefined,
libvirt thinks it is already autostarted and will not create the link
even if requested:

  # virsh dominfo example | grep Autostart
  Autostart:      enable

  # ls /etc/libvirt/qemu/autostart/example.xml
  /etc/libvirt/qemu/autostart/example.xml

  # virsh undefine example
  Domain example has been undefined

  # virsh define example.xml
  Domain example defined from example.xml

  # virsh dominfo example | grep Autostart
  Autostart:      enable

  # virsh autostart example
  Domain example marked as autostarted

  # ls /etc/libvirt/qemu/autostart/example.xml
  ls: cannot access /etc/libvirt/qemu/autostart/example.xml: No such file or directory

This commit ensures dom->autostart is cleared whenever the config and
autostart link (if present) are removed.

The bridge network driver cleared this flag itself in networkUndefine.
This commit moves this into virNetworkDeleteConfig for symmetry with
virDomainDeleteConfig, and to ensure it is not missed in future network
drivers.

Signed-off-by: Michael Chapman <mike@very.puzzling.org>
2015-03-11 07:16:25 +01:00
Ján Tomko
7b2f12fe28 Use virBitmapNextClearBit in networkNextClassID
Instead of finding the next clear bit by calling virBitmapGetBit
in a loop, use the virBitmapNextClearBit helper.
2015-03-10 13:45:51 +01:00
Michal Privoznik
88aed14f12 network_conf: Turn virNetworkObjList into virObject
Well, one day this will be self-locking object, but not today.
But lets prepare the code for that! Moreover,
virNetworkObjListFree() is no longer needed, so turn it into
virNetworkObjListDispose().

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-09 14:03:30 +01:00
Michal Privoznik
b61db335f9 bridge_driver: Adapt to new virNetworkObjList accessors
Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-09 14:03:30 +01:00
Michal Privoznik
53cae19561 conf: s/virNetworkFindByName/virNetworkObjFindByName/
It's returning virNetworkObjPtr after all. And it matches the
pattern laid out by domain_conf.h.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:12:16 +01:00
Michal Privoznik
82f240ae56 conf: s/virNetworkFindByUUID/virNetworkObjFindByUUID/
It's returning virNetworkObjPtr after all. And it matches the
pattern laid out by domain_conf.h.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:11:40 +01:00
Michal Privoznik
2ea3ce332b bridge_driver: s/virNetworkObjList/virNetworkObjListPtr/
In order to hide the object internals (and use just accessors
everywhere), lets store a pointer to the object, instead of object
itself.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:11:24 +01:00
Michal Privoznik
bbbc7e41e0 virNetworkObjListExport: Pass virNetworkObjListPtr
Instead of copying the whole object onto stack when calling the
function, just pass the pointer to the object and save up some
space on the stack. Moreover, this prepares the code to hide the
virNetworkObjList structure into network_conf.c and use accessors
only.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:09:30 +01:00
Michal Privoznik
5c6b8226f3 networkGetNetworkAddress: Drop empty 'error' label
Moreover, there are two points within the function, where we're
missing 'goto cleanup'. Fix this too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:08:24 +01:00
Michal Privoznik
7b8c12d8ce bridge_driver: Don't check network active unlocked
Okay, this is mainly for educational purposes since is called
from single point only with all the possible locks held. So
there's no way for other thread to hop in and do something wrong.
Nevertheless, we should not give bad example.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:08:07 +01:00
Michal Privoznik
bf1afdd491 networkLookupByUUID: Improve error message
We have this function networkObjFromNetwork() which for given
virNetworkPtr tries to find corresponding virNetworkObjPtr. If no
object is found, a nice error message is printed out:

  no network with matching uuid '$uuid' ($name)

Let's improve the error message produced by networkLookupByUUID to
follow that logic.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2015-03-04 10:07:59 +01:00
Laine Stump
118b240808 network: only clear bandwidth if it has been set
libvirt was unconditionally calling virNetDevBandwidthClear() for
every interface (and network bridge) of a type that supported
bandwidth, whether it actually had anything set or not. This doesn't
hurt anything (unless ifname == NULL!), but is wasteful.

This patch makes sure that all calls to virNetDevBandwidthClear() are
qualified by checking that the interface really had some bandwidth
setup done, and checks for a null ifname inside
virNetDevBandwidthClear(), silently returning success if it is null
(as well as removing the ATTRIBUTE_NONNULL from that function's
prototype, since we can't guarantee that it is never null,
e.g. sometimes a type='ethernet' interface has no ifname as it is
provided on the fly by qemu).
2015-02-25 13:09:34 -05:00
Laine Stump
8f8e581a17 network: allow <pf> together with <interface>/<address> in network status
The function that parses the <forward> subelement of a network used to
fail/log an error if the network definition contained both a <pf>
element as well as at least one <interface> or <address> element. That
check was present because the configuration of a network should have
either one <pf>, one or more <interface>, or one or more <address>,
but never combinations of multiple kinds.

This caused a problem when libvirtd was restarted with a network
already active - when a network with a <pf> element is started, the
referenced PF (Physical Function of an SRIOV-capable network card) is
checked for VFs (Virtual Functions), and the <forward> is filled in
with a list of all VFs for that PF either in the form of their PCI
addresses (a list of <address>) or their netdev names (a list of
<interface>); the <pf> element is not removed though. When libvirtd is
restarted, it parses the network status and finds both the original
<pf> from the config, as well as the list of either <address> or
<interface>, fails the parse, and the network is not added to the
active list. This failure is often obscured because the network is
marked as autostart so libvirt immediately restarts it.

It seems odd to me that <interface> and <address> are stored in the
same array rather than keeping two separate arrays, and having
separate arrays would have made the check much simpler. However,
changing to use two separate arrays would have required changes in
more places, potentially creating more conflicts and (more
importantly) more possible regressions in the event of a backport, so
I chose to keep the existing data structure in order to localize the
change.

It appears that this problem has been in the code ever since support
for <pf> was added (0.9.10), but until commit
34cc3b2f10 (first in libvirt 1.2.4)
networks with interface pools were not properly marked as active on
restart anyway, so there is no point in backporting this patch any
further than that.
2015-02-20 15:06:30 -05:00
Jiri Denemark
bc6e206322 Search for schemas and cpu_map.xml in source tree
Not all files we want to find using virFileFindResource{,Full} are
generated when libvirt is built, some of them (such as RNG schemas) are
distributed with sources. The current API was not able to find source
files if libvirt was built in VPATH.

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

Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2015-02-19 15:25:04 +01:00
Laine Stump
2aa7ce6334 network: don't allow multiple portgroups with the same name in a network
When defining and creating networks, we have been checking to make
sure there is only a single "default" portgroup, but haven't verified
that no two portgroups have the same name. We *do* check for multiple
definitions when updating the portgroups in an existing network
though.

This patch adds a check to networkValidate(), which is called when a
network is defined or created, to disallow duplicate names. It would
actually make sense to do this in the network XML parser (since it's
not really "something that might make sense but isn't supported by
this driver", but is instead "something that should never be
allowed"), but doing that carries the danger of causing errors when
rereading the config of existing networks when libvirtd is restarted
after an upgrade, and that would result in networks disappearing from
libvirt's list. (I'm thinking I should change the error to "XML_ERROR"
instead of "UNSUPPORTED", even though that's not the type of error
that networkValidate is intended for)

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1115858
2015-02-06 10:37:54 -05:00
Daniel P. Berrange
55ea7be7d9 Removing probing of secondary drivers
For stateless, client side drivers, it is never correct to
probe for secondary drivers. It is only ever appropriate to
use the secondary driver that is associated with the
hypervisor in question. As a result the ESX & HyperV drivers
have both been forced to do hacks where they register no-op
drivers for the ones they don't implement.

For stateful, server side drivers, we always just want to
use the same built-in shared driver. The exception is
virtualbox which is really a stateless driver and so wants
to use its own server side secondary drivers. To deal with
this virtualbox has to be built as 3 separate loadable
modules to allow registration to work in the right order.

This can all be simplified by introducing a new struct
recording the precise set of secondary drivers each
hypervisor driver wants

struct _virConnectDriver {
    virHypervisorDriverPtr hypervisorDriver;
    virInterfaceDriverPtr interfaceDriver;
    virNetworkDriverPtr networkDriver;
    virNodeDeviceDriverPtr nodeDeviceDriver;
    virNWFilterDriverPtr nwfilterDriver;
    virSecretDriverPtr secretDriver;
    virStorageDriverPtr storageDriver;
};

Instead of registering the hypervisor driver, we now
just register a virConnectDriver instead. This allows
us to remove all probing of secondary drivers. Once we
have chosen the primary driver, we immediately know the
correct secondary drivers to use.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2015-01-27 12:02:04 +00:00
Josh Stone
298fa4858c network: Let domains be restricted to local DNS
This adds a new "localOnly" attribute on the domain element of the
network xml.  With this set to "yes", DNS requests under that domain
will only be resolved by libvirt's dnsmasq, never forwarded upstream.

This was how it worked before commit f69a6b987d, and I found that
functionality useful.  For example, I have my host's NetworkManager
dnsmasq configured to forward that domain to libvirt's dnsmasq, so I can
easily resolve guest names from outside.  But if libvirt's dnsmasq
doesn't know a name and forwards it to the host, I'd get an endless
forwarding loop.  Now I can set localOnly="yes" to prevent the loop.

Signed-off-by: Josh Stone <jistone@redhat.com>
2015-01-20 01:07:18 -05:00
Cédric Bosdonnat
ca481a6f8f Move code related to network routes to networkcommon_conf.[ch]
Moving code for parsing and formatting network routes to
networkcommon_conf helps reusing those routes for domains. The route
definition has been hidden to help reducing the number of unnecessary
checks in the format function.
2015-01-16 10:14:03 +01:00
Nehal J Wani
18ec863d19 networkGetDHCPLeases: Remove unnecessary error reporting
Lack of a lease (whether mac is given or not) is a normal expected
scenario, since we are already filling in rv with nleases (which is
okay as 0 if there is no lease).  There is no need to raise an error.

This fixes:

> virsh # net-dhcp-leases --mac 00:50:56:c0:00:01  default
> error: Failed to get leases info for default
> error: internal error: no lease with matching MAC address: 00:50:56:c0:00:01

Signed-off-by: Nehal J Wani <nehaljw.kkd1@gmail.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2015-01-05 16:58:18 -07:00
Cédric Bosdonnat
2b0598c836 Renamed virNetDevSetIPv4Address to virNetDevSetIPAddress
Renamed virNetDevSetIPv4Address as it also handles IPv6 addresses.
2015-01-05 20:24:04 +01:00
Laine Stump
8a144c9045 network: setup bridge devices for macTableManager='libvirt'
When the bridge device for a network has macTableManager='libvirt' the
intent is that all kernel management of the bridge's MAC table
(Forwarding Database, or fdb, in the case of a Linux Host Bridge) be
disabled, with libvirt handling updates to the table instead. The
setup required for the bridge itself is:

1) set the "vlan_filtering" property of the bridge device to 1.

2) If the bridge has a "Dummy" tap device used to set a fixed MAC
address on the bridge (which is always the case for a bridge created
by libvirt, and never the case for a bridge created by the host system
network config), turn off learning and unicast_flood on this tap (this
is needed even though this tap is never IFF_UP, because the kernel
ignores the IFF_UP flag of devices when using their settings to
automatically decide whether or not to turn off promiscuous mode for
any attached device).

(1) is done both for libvirt-created/managed bridges, and for bridges
that are created by the host system config, while (2) is done only for
bridges created by libvirt (i.e. for forward modes of nat, routed, and
isolated bridges)

There is no attempt to turn vlan_filtering off when destroying the
network because in the case of a libvirt-created bridge, the bridge is
about to be destroyed anyway, and in the case of a system bridge, if
the other devices attached to the bridge could operate properly before
destroying libvirt's network object, they will continue to operate
properly (this is similar to the way that libvirt will enable
ip_forwarding whenever a routed/natted network is started, but will
never attempt to disable it if they are stopped).
2014-12-08 14:47:06 -05:00
Laine Stump
33f4a8bc03 network: store network macTableManager setting in NetDef actual object
At the time that the network driver allocates a connection to a
network, the tap device that will be used hasn't yet been created -
that will be done later by qemu (or lxc or whoever) - but if the
network has macTableManager='libvirt', then when we do get around to
creating the tap device, we will need to add an entry for it to the
network bridge's fdb (forwarding database) *and* turn off learning and
unicast_flood for that tap device in the bridge's sysfs settings. This
means that qemu needs to know both the bridge name as well as the
setting of macTableManager, so we either need to create a new API to
retrieve that info, or just pass it back in the ActualNetDef that is
created during networkAllocateActualDevice. We choose the latter
method, since it's already done for the bridge device, and it has the
side effect of making the information available in domain status.

(NB: in the future, I think that the tap device should actually be
created by networkAllocateActualDevice(), as that will solve several
other problems, but that is a battle for another day, and this
information will still be useful outside the network driver)
2014-12-08 14:45:09 -05:00
Laine Stump
a360912179 network: save bridge name in ActualNetDef when actualType==network too
When the actualType of a virDomainNetDef is "network", it means that
we are connecting to a libvirt-managed network (routed, natted, or
isolated) which does use a bridge device (created by libvirt). In the
past we have required drivers such as qemu to call the public API to
retrieve the bridge name in this case (even though it is available in
the NetDef's ActualNetDef if the actualType is "bridge" (i.e., an
externally-created bridge that isn't managed by libvirt). There is no
real reason for this difference, and as a matter of fact it
complicates things for qemu. Also, there is another bridge-related
attribute (macTableManager) that will need to be available in both
cases, so this makes things consistent.

In order to avoid problems when restarting libvirtd after an update
from an older version that *doesn't* store the network's bridgename in
the ActualNetDef, we also need to put it in place during
networkNotifyActualDevice() (this function is run for each interface
of each domain whenever libvirtd is restarted).

Along with making the bridge name available in the internal object, it
is also now reported in the <source> element of the <interface> state
XML (or the <actual> subelement in the internally-stored format).

The one oddity about this change is that usually there is a separate
union for every different "type" in a higher level object (e.g. in the
case of a virDomainNetDef there are separate "network" and "bridge"
members of the union that pivots on the type), but in this case
network and bridge types both have exactly the same attributes, so the
"bridge" member is used for both type==network and type==bridge.
2014-12-08 14:43:42 -05:00
Michal Privoznik
abef016496 networkValidate: Disallow bandwidth in portgroups too
https://bugzilla.redhat.com/show_bug.cgi?id=1115292

In one of the previous commits (eafb53fe) we disallowed
network-wide bandwidth to some network types. However, we
forgot about <portgroups/> which can have <bandwidth/> too.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-12-05 08:23:37 +01:00
Peter Krempa
b17c0f0e9a leaseshelper: Fix incorrect alignment of a switch case
Introduced in ca6dbdd047
2014-12-03 18:47:24 +01:00
Peter Krempa
3be8c1f002 leaseshelper: Skip entries missing expiry time on INIT action
Coverity pointed out that in other places we always check the return
value from virJSONValueObjectGetNumberLong() but not in the new addition
in leaseshelper. To solve the issue and also be more robust in case
somebody would corrupt the file, skip outputting of the lease entry in
case the expiry time is missing.
2014-12-03 18:47:09 +01:00
Peter Krempa
421406808a network: dnsmasq: Don't format lease file path
Now that we don't use the leases file at all for leases just don't
format it into the config and use the leaseshelper to do all the
lifting.
2014-12-03 14:22:40 +01:00
Peter Krempa
ca6dbdd047 leaseshelper: Refactor control flow
Untangle a few conditions into a case statement and improve reporting of
invaid commands.
2014-12-03 14:22:40 +01:00
Nehal J Wani
0f87054b61 leaseshelper: improvements to support all events
This patch enables the helper program to detect event(s) triggered when
there is a change in lease length or expiry and client-id. This
transfers complete control of leases database to libvirt and obsoletes
use of the lease database file (<network-name>.leases). That file will
not be created, read, or written.  This is achieved by adding the option
--leasefile-ro to dnsmasq and passing a custom env var to leaseshelper,
which helps us map events related to leases with their corresponding
network bridges, no matter what the event be.

Also, this requires the addition of a new non-lease entry in our custom
lease database: "server-duid". It is required to identify a DHCPv6
server.

Now that dnsmasq doesn't maintain its own leases database, it relies on
our helper program to tell it about previous leases and server duid.
Thus, this patch makes our leases program honor an extra action: "init",
in which it sends the known info in a particular format to dnsmasq
by printing it to stdout.

The drawback of this change is that upgrade to this new approach does
not transfer the existing leases for the network if the leaseshelper
wasn't already used.
2014-12-03 14:22:40 +01:00
Jiri Denemark
dabb23e6d9 network: Fix upgrade from libvirt older than 1.2.4
Starting from libvirt-1.2.4, network state XML files moved to another
directory (see commit b9e95491) and libvirt automatically migrates the
network state files to a new location. However, the code used
dirent.d_type which is not supported by all filesystems. Thus, when
libvirt was upgraded on a host which used such filesystem, network state
XMLs were not properly moved and running networks disappeared from
libvirt.

This patch falls back to lstat() whenever dirent.d_type is DT_UNKNOWN to
fix this issue.

https://bugzilla.redhat.com/show_bug.cgi?id=1167145
Signed-off-by: Jiri Denemark <jdenemar@redhat.com>
2014-11-27 09:58:54 +01:00
Martin Kletzander
138c2aee01 Remove unnecessary curly brackets in rest of src/[a-n]*/
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-11-14 17:13:36 +01:00
Daniel P. Berrange
637c8aeef6 Remove use of networkPrivateData from network driver
The shared network driver is stateful and inside the daemon so
there is no need to use the networkPrivateData field to get the
driver handle. Just access the global driver handle directly.

Many places already directly accessed the global driver handle
in any case, so the code could never work without relying on
this.
2014-11-07 11:12:50 +01:00
Luyao Huang
45d9ea5cdd network: fix call virNetworkEventLifecycleNew when networkStartNetwork fail
When start a network fail, libvirt still call virNetworkEventLifecycleNew
to send a event.

Signed-off-by: Luyao Huang <lhuang@redhat.com>
2014-11-06 15:13:55 +01:00
Eric Blake
ff99c79195 maint: avoid static zero init in helpers
C guarantees that static variables are zero-initialized.  Some older
compilers (and also gcc -fno-zero-initialized-in-bss) create larger
binaries if you explicitly zero-initialize a static variable.

* src/conf/nwfilter_conf.c: Fix initialization.
* src/cpu/cpu_x86.c: Likewise.
* src/interface/interface_backend_netcf.c: Likewise.
* src/locking/lock_daemon.c: Likewise.
* src/locking/lock_driver_lockd.c: Likewise.
* src/locking/lock_driver_sanlock.c: Likewise.
* src/network/bridge_driver.c: Likewise.
* src/node_device/node_device_udev.c: Likewise.
* src/nwfilter/nwfilter_learnipaddr.c: Likewise.
* src/rpc/virnetserver.c: Likewise.
* src/security/security_selinux.c
(virSecuritySELinuxGenSecurityLabel): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-10-29 09:55:09 -06:00
Laine Stump
cfddf59cee network: set interface actual trustGuestRxFilters from network/portgroup
As is done with other items such as vlan, virtualport, and bandwidth,
set the actual trustGuestRxFilters value to be used by a domain
interface according to a merge of the same attribute in the interface,
portgroup, and network in use. the interface setting always takes
precedence (if specified), followed by portgroup, and finally the
setting in the network is used if it's not specified in the interface
or portgroup.
2014-10-06 11:58:57 -04:00
Ján Tomko
b20d39a56f Wire up the interface backend options
Pass the user-specified tun path down when creating tap device
when called from the qemu driver.

Also honor the vhost device path specified by user.
2014-09-16 16:02:34 +02:00
John Ferlan
d3f0708e84 network: Resolve Coverity FORWARD_NULL
If the VIR_STRDUP(exptime,...) fails, then we will jump to cleanup,
no need to check if exptime is set which causes Coverity to issue
a complaint in the virStrToLong_ll call because there wasn't a check
for a NULL value while there was one for the reference right after
the VIR_STRDUP().

Signed-off-by: John Ferlan <jferlan@redhat.com>
2014-09-11 08:10:13 -04:00
Eric Blake
625e04a86e maint: use hanging curly braces
Our style overwhelmingly uses hanging braces (the open brace
hangs at the end of the compound condition, rather than on
its own line), with the primary exception of the top level function
body.  Fix the few remaining outliers, before adding a syntax
check in a later patch.

* src/interface/interface_backend_netcf.c (netcfStateReload)
(netcfInterfaceClose, netcf_to_vir_err): Correct use of { in
compound statement.
* src/conf/domain_conf.c (virDomainHostdevDefFormatSubsys)
(virDomainHostdevDefFormatCaps): Likewise.
* src/network/bridge_driver.c (networkAllocateActualDevice):
Likewise.
* src/util/virfile.c (virBuildPathInternal): Likewise.
* src/util/virnetdev.c (virNetDevGetVirtualFunctions): Likewise.
* src/util/virnetdevmacvlan.c
(virNetDevMacVLanVPortProfileCallback): Likewise.
* src/util/virtypedparam.c (virTypedParameterAssign): Likewise.
* src/util/virutil.c (virGetWin32DirectoryRoot)
(virFileWaitForDevices): Likewise.
* src/vbox/vbox_common.c (vboxDumpNetwork): Likewise.
* tests/seclabeltest.c (main): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-09-04 15:18:43 -06:00
Eric Blake
ff78ff7c93 maint: use consistent if-else braces in conf and friends
I'm about to add a syntax check that enforces our documented
HACKING style of always using matching {} on if-else statements.

This patch focuses on code shared between multiple drivers.

* src/conf/domain_conf.c (virDomainFSDefParseXML)
(virSysinfoParseXML, virDomainNetDefParseXML)
(virDomainWatchdogDefParseXML)
(virDomainRedirFilterUSBDevDefParseXML): Correct use of {}.
* src/conf/interface_conf.c (virInterfaceDefParseDhcp)
(virInterfaceDefParseIp, virInterfaceVlanDefFormat)
(virInterfaceDefParseStartMode, virInterfaceDefParseBondMode)
(virInterfaceDefParseBondMiiCarrier)
(virInterfaceDefParseBondArpValid): Likewise.
* src/conf/node_device_conf.c (virNodeDevCapStorageParseXML):
Likewise.
* src/conf/nwfilter_conf.c (virNWFilterRuleDetailsParse)
(virNWFilterRuleParse, virNWFilterDefParseXML): Likewise.
* src/conf/secret_conf.c (secretXMLParseNode): Likewise.
* src/cpu/cpu_x86.c (x86Baseline, x86FeatureLoad, x86ModelLoad):
Likewise.
* src/network/bridge_driver.c (networkKillDaemon)
(networkDnsmasqConfContents): Likewise.
* src/node_device/node_device_hal.c (dev_refresh): Likewise.
* src/nwfilter/nwfilter_gentech_driver.c (virNWFilterInstantiate):
Likewise.
* src/nwfilter/nwfilter_ebiptables_driver.c
(_iptablesCreateRuleInstance): Likewise.
* src/storage/storage_backend_disk.c
(virStorageBackendDiskBuildPool): Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-09-04 08:53:21 -06:00
John Ferlan
2a4e26bdc1 bridge_driver: Resolve Coverity RESOURCE_LEAK
In the error path the 'ipaddr' wasn't VIR_FREE'd before jumping to cleanup
2014-08-28 08:12:16 -04:00
Laine Stump
7809615056 network: fix crash when starting a network with no <pf> element
Martin Kletzander pointed out in email that my commit 2a193f64
introduced a crash in networkCreateInterfacePool() during startup of
any network that doesn't have a <pf> subelement of its <forward>
element. He also supplied a patch.

 http://www.redhat.com/archives/libvir-list/2014-August/msg00655.html

I expanded on that patch by cleaning up now-extraneous checks in the
callers of networkCreateInterfacePool().

Fortunately the offending patch hasn't been in any release, and hasn't
been (to my knowledge) backported to any other branch.
2014-08-15 02:42:52 -04:00
Laine Stump
2a193f6458 network: populate interface pool immediately when network is started
When a network is defined with "<pf dev='xyz'/>", libvirt will query
sysfs to learn the list of all virtual functions (VF) associated with
that Physical Function (PF) then populate the network's interface pool
accordingly. This action was previously done only when the first guest
actually requested an interface from the network. This patch changes
it to populate the pool immediately when the network is started. This
way any problems with the PF or its VFs will become apparent sooner.

Note that we can't remove the old calls to networkCreateInterfacePool
that happen whenever a guest requests an interface - doing so would be
asking for failures on hosts that had libvirt upgraded with a network
that had been started but not yet used.

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1047818
2014-08-11 17:34:28 -04:00
Laine Stump
cd7759cb96 network: make networkCreateInterfacePool more robust
networkCreateInterfacePool was a bit loose in its error cleanup, which
could result in a network definition with interfaces in the pool that
were NULL. This would in turn lead to a libvirtd crash when a guest
tried to attach an interface using the network with that pool.

In particular this would happen when creating a pool to be used for
macvtap connections. macvtap needs the netdev name of the virtual
function in order to use it, and each VF only has a netdev name if it
is currently bound to a network driver. If one of the VFs of a PF
happened to be bound to the pci-stub or vfio-pci driver (indicating
it's already in use for PCI passthrough), or no driver at all, it
would have no name. In this case networkCreateInterfacePool would
return an error, but would leave the netdef->forward.nifs set to the
total number of VFs in the PF. The interface attach that triggered
calling of networkCreateInterfacePool (it uses a "lazy fill" strategy)
would simply fail, but the very next attempt to attach an interface
using the same network pool would result in a crash.

This patch refactors networkCreateInterfacePool to bring it more in
line with current coding practices (label name, use of a switch with
no default case) as well as providing the following two changes to
behavior:

1) If a VF with no netdev name is encountered, just log a warning and
continue; only fail if exactly 0 devices are found to put in the pool.

2) If the function fails, clean up any partial interface pool and set
netdef->forward.nifs to 0.

This resolves: https://bugzilla.redhat.com/show_bug.cgi?id=1111455
2014-08-11 17:34:20 -04:00
Ján Tomko
6dac5d06f5 Don't overwrite errors from virNetDevBandwidthSet
Otherwise this beautiful error would be overwritten when
the function is called with a really high rate number:

2014-07-28 12:51:47.920+0000: 2304: error : virCommandWait:2399 :
internal error: Child process (/sbin/tc class add dev vnet0 parent 1:
classid 1:1 htb rate 4294968kbps) unexpected exit status 1: Illegal "rate"
Usage: ... qdisc add ... htb [default N] [r2q N]
 default  minor id of class to which unclassified packets are sent {0}
 r2q      DRR quantums are computed as rate in Bps/r2q {10}
 debug    string of 16 numbers each 0-3 {0}

... class add ... htb rate R1 [burst B1] [mpu B] [overhead O]
                      [prio P] [slot S] [pslot PS]
                      [ceil R2] [cburst B2] [mtu MTU] [quantum Q]
 rate     rate allocated to this class (class can still borrow)
 burst    max bytes burst which can be accumulated during idle period {computed}
 mpu      minimum packet size used in rate computations
 overhead per-packet size overhead used in rate computations
 linklay  adapting to a linklayer e.g. atm
 ceil     definite upper class rate (no borrows) {rate}
 cburst   burst but for ceil {computed}
 mtu      max packet size we create rate map for {1600}
 prio     priority of leaf; lowe

https://bugzilla.redhat.com/show_bug.cgi?id=1043735
2014-08-04 16:59:28 +02:00
Laine Stump
c0788af07d network: always set disable_ipv6, even when it should be 0
libvirt previously only touched an interface's disable_ipv6 setting in
sysfs if it needed to be set to 1, assuming that 0 is the
default. Apparently that isn't always the case though (kernel 3.15.7-1
in Arch Linux reportedly defaults a new interface's disable_ipv6
setting to 1) so this patch explicitly sets it to 0 or 1 as
appropriate.
2014-08-02 21:51:24 -04:00
Nehal J Wani
6675a0ab65 leaseshelper: avoid mem leak after storing lease entries
Contents of existing lease file were being stored in a variable
which was never freed.
2014-07-23 19:27:39 -06:00
Ján Tomko
bb018ce6c8 Introduce virTristateBool enum type
Replace all three-state (default/yes/no) enums with it:
virDomainBIOSUseserial
virDomainBootMenu
virDomainPMState
virDomainGraphicsSpiceClipboardCopypaste
virDomainGraphicsSpiceAgentFileTransfer
virNetworkDNSForwardPlainNames
2014-07-23 12:37:39 +02:00
Ján Tomko
92a8e72f9d Use virBufferCheckError everywhere we report OOM error
Replace:
if (virBufferError(&buf)) {
    virBufferFreeAndReset(&buf);
    virReportOOMError();
    ...
}

with:
if (virBufferCheckError(&buf) < 0)
    ...

This should not be a functional change (unless some callers
misused the virBuffer APIs - a different error would be reported
then)
2014-07-03 10:48:14 +02:00
Ján Tomko
0979aaf846 Remove useless condition in networkRadvdConfContents
If v6present is false, this code is not reachable.
Also, there is no need to check for errors twice.
2014-07-03 10:41:15 +02:00
Ján Tomko
e87ab4c68d Fix indentation in bridge driver 2014-07-03 10:41:15 +02:00
Peter Krempa
02bffd47bd net: merge virNetworkGetDHCPLeases and virNetworkGetDHCPLeasesForMAC
Instead of maintaining two very similar APIs, add the "@mac" parameter
to virNetworkGetDHCPLeases and kill virNetworkGetDHCPLeasesForMAC. Both
of those functions would return data the same way, so making @mac an
optional filter simplifies a lot of stuff.
2014-06-27 09:38:13 +02:00
Peter Krempa
11863f7067 bridge: leases: Fix potential crash caused by use after free
Don't free individual JSON array members as the array will be freed at
the end. This may potentially lead to a crash although it didn't crash
on my setup.
2014-06-24 15:17:22 +02:00
Ján Tomko
15b46520e5 Free DHCP leases file in networkGetDHCPLeasesHelper
Introduced by commit ba51398
2014-06-24 14:41:50 +02:00
Daniel P. Berrange
6512c8b456 Change 'interface' to 'iface' in virNetworkDHCPLease
Variables/fields named 'interface' clash with system
header symbols on some platforms.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-06-24 13:30:16 +01:00
Nehal J Wani
ba5139821a net-dhcp-leases: Private implementation inside network
Query the network driver for the path of the custom leases file for the given
virtual network and parse it to retrieve info.

src/network/bridge_driver.c:
* Implement networkGetDHCPLeases
* Implement networkGetDHCPLeasesForMAC
* Implement networkGetDHCPLeasesHelper
2014-06-24 12:26:31 +01:00
Peter Krempa
b9f8a2f25e network: bridge: Avoid freeing uninitialized pointer on cleanup path
The cleanup path in networkBuildDhcpDaemonCommandLine could cause a
crash by freeing uninitialized pointer.
2014-06-17 10:03:53 +02:00
Peter Krempa
0657ed2a5c net: leaseshelper: Refactor copying of old entries to avoid double free
When copying entries from the old lease file into the new array the old
code would copy the pointer of the json object into the second array
without removing it from the first. Afterwards when both arrays were
freed this might lead to a crash due to access of already freed memory.

Refactor the code to use the new array item stealing helper added to the
json code so that the entry resides just in one array.
2014-06-17 09:10:08 +02:00
Peter Krempa
45d51681ce net: leaseshelper: Ignore corrupted lease file and rewrite it
Instead of reporting an error and terminating, rewrite the file with
the newly learned info.
2014-06-17 09:02:26 +02:00
Peter Krempa
f1385e222e net: leaseshelper: Don't crash if DNSMASQ doesn't provide lease expiry
The value is provided via environment and causes a crash if not defined.
2014-06-17 08:55:50 +02:00
Pavel Hrdina
647bdf02d8 leaseshelper: fix another crash
We create a 'lease_new' when we are adding new lease entry, then later
in the code we add the 'lease_new' into a 'leases_array_new' which
leads into the crash because we double free the 'lease_new'.

To prevent the double free we set the 'lease_new' to NULL after
successful append into the 'leases_array_new'.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2014-06-16 14:41:19 +02:00
Pavel Hrdina
a93504cca4 leaseshelper: fix crash
Commit baafe668 introduced new leaseshelper with a crash of freeing
env string. Calling 'getenv()' inside 'virGetEnvAllowSUID()' may
return a static string and we definitely should not free it.

The author probably want to free the copy of that string.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2014-06-11 17:21:11 +02:00
Peter Krempa
23c2763b4f network: bridge: Avoid memory leak from networkBuildDhcpDaemonCommandLine
If the leasehelper_path couldn't be found the code would leak the
freshly constructed command structure. Re-arrange code to avoid the
problem.

Found by coverity, broken by baafe668fa.
2014-06-03 14:34:23 +02:00
Julio Faracco
5a2bd4c917 conf: more enum cleanups in "src/conf/domain_conf.h"
In "src/conf/domain_conf.h" there are many enum declarations. The
cleanup in this header filer was started, but it wasn't enough and
there are many other files that has enum variables declared. So, the
commit was starting to be big. This commit finish the cleanup in this
header file and in other files that has enum variables, parameters,
or functions declared.

Signed-off-by: Julio Faracco <jcfaracco@gmail.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2014-06-02 15:32:58 -06:00
Pavel Hrdina
f8a0c9edf0 Fix build on freebsd
On freebsd there isn't known "setlocale" so we have to include locale.h
2014-06-02 16:45:42 +02:00
Nehal J Wani
baafe668fa Add helper program to create custom leases
Introduce helper program to catch events from dnsmasq and maintain a custom
lease file per network. It supports dhcpv4 and dhcpv6. The file is saved as
"<interface-name>.status".

Each lease contains the following info:
<expiry-time (epoch time)> <mac> <iaid> <ip-address> <hostname> <clientid>

Example of custom leases file content:
[
    {
        "iaid": "1221229",
        "ip-address": "2001:db8:ca2:2:1::95",
        "mac-address": "52:54:00:12:a2:6d",
        "hostname": "Fedora20",
        "client-id": "00:04:1a:c1:d9:6b:5a:0a:e2:bc:f8:4b:1e:37:2e:38:22:55",
        "expiry-time": 1393244216
    },
    {
        "ip-address": "192.168.150.208",
        "mac-address": "52:54:00:11:56:b3",
        "hostname": "Wani-PC",
        "client-id": "01:52:54:00:11:56:b3",
        "expiry-time": 1393244248
    }
]

src/Makefile.am:
   * Add options to compile the helper program

src/network/bridge_driver.c:
   * Introduce networkDnsmasqLeaseFileNameCustom()
   * Invoke helper program along with dnsmasq
   * Delete the .status file when corresponding n/w is destroyed.

src/network/leaseshelper.c
   * Helper program to create the custom lease file
2014-06-02 11:45:10 +01:00
Julio Faracco
6000705ab1 conf: use typedefs for enums in "src/conf/{network,interface}_conf.h"
In "src/conf/" there are many enumeration (enum) declarations.
Similar to the recent cleanup to "src/util" directory, it's
better to use a typedef for variable types, function types and
other usages. Other enumeration and folders will be changed to
typedef's in the future. Most of the files changed in this commit
are reltaed to Network (network_conf.* and interface_conf.*) enums.

Signed-off-by: Julio Faracco <jcfaracco@gmail.com>
Signed-off-by: Eric Blake <eblake@redhat.com>
2014-05-05 16:04:53 -06:00
Laine Stump
a431523444 network: use virDirRead in networkMigrateStateFiles
This attempts to follow the same variable name and usage patterns as
the other conversions to virDirRead().
2014-04-28 17:52:46 -06:00
Laine Stump
34cc3b2f10 network: centralize check for active network during interface attach
The check for a network being active during interface attach was being
done individually in several places (by both the lxc driver and the
qemu driver), but those places were too specific, leading to it *not*
being checked when allocating a connection/device from a macvtap or
hostdev network.

This patch puts a single check in networkAllocateActualDevice(), which
is always called before the any network interface is attached to any
type of domain. It also removes all the other now-redundant checks
from the lxc and qemu drivers.

NB: the following patches are prerequisites for this patch, in the
case that it is backported to any branch:

  440beeb network: fix virNetworkObjAssignDef and persistence
  8aaa5b6 network: create statedir during driver initialization
  b9e9549 network: change location of network state xml files
  411c548 network: set macvtap/hostdev networks active if their state
          file exists

This fixes:

  https://bugzilla.redhat.com/show_bug.cgi?id=880483
2014-04-27 12:22:36 +03:00
Laine Stump
411c548668 network: set macvtap/hostdev networks active if their state file exists
libvirt attempts to determine at startup time which networks are
already active, and set their active flags. Previously it has done
this by assuming that all networks are inactive, then setting the
active flag if the network has a bridge device associated with it and
that bridge device exists. This is not useful for macvtap and hostdev
based networks, since they do not use a bridge device.

Of course the reason that such a check had to be done was that the
presence of a status file in the network "stateDir" couldn't be
trusted as an indicator of whether or not a network was active. This
was due to the network driver mistakenly using
/var/lib/libvirt/network to store the status files, rather than
/var/run/libvirt/network (similar to what is done by every other
libvirt driver that stores status xml for its objects). The difference
is that /var/run is cleared out when the host reboots, so you can be
assured that the state file you are seeing isn't just left over from a
previous boot of the host.

Now that the network driver has been switched to using
/var/run/libvirt/network for status, we can also modify it to assume
that any network with an existing status file is by definition active
- we do this when reading the status file. To fine tune the results,
networkFindActiveConfigs() is changed to networkUpdateAllState(),
and only sets active = 0 if the conditions for particular network
types are *not* met.

The result is that during the first run of libvirtd after the host
boots, there are no status files, so no networks are active. Any time
libvirtd is restarted, any network with a status file will be marked
as active (unless the network uses a bridge device and that device for
some reason doesn't exist).
2014-04-27 12:20:39 +03:00
Laine Stump
b9e95491d1 network: change location of network state xml files
For some reason these have been stored in /var/lib, although other
drivers (e.g. qemu and lxc) store their state files in /var/run.

It's much nicer to store state files in /var/run because it is
automatically cleared out when the system reboots. We can then use
existence of the state file as a convenient indicator of whether or
not a particular network is active.

Since changing the location of the state files by itself will cause
problems in the case of a *live* upgrade from an older libvirt that
uses /var/lib (because current status of active networks will be
lost), the network driver initialization has been modified to migrate
any network state files from /var/lib to /var/run.

This will not help those trying to *downgrade*, but in practice this
will only be problematic in two cases

1) If there are networks with network-wide bandwidth limits configured
   *and in use* by a guest during a downgrade to "old" libvirt. In this
   case, the class ID's used for that network's tc rules, as well as
   the currently in-use bandwidth "floor" will be forgotten.

2) If someone does this: 1) upgrade libvirt, 2) downgrade libvirt, 3)
   modify running state of network (e.g. add a static dhcp host, etc),
   4) upgrade. In this case, the modifications to the running network
   will be lost (but not any persistent changes to the network's
   config).
2014-04-27 12:19:57 +03:00
Laine Stump
8aaa5b68ef network: create statedir during driver initialization
This directory should be created when the network driver is first
started up, not just when a dhcp daemon is run. This hasn't posed a
problem in the past, because the directory has always been
pre-existing.
2014-04-27 12:19:13 +03:00
Laine Stump
440beeb7ac network: fix virNetworkObjAssignDef and persistence
Experimentation showed that if virNetworkCreateXML() was called for a
network that was already defined, and then the network was
subsequently shutdown, the network would continue to be persistent
after the shutdown (expected/desired), but the original config would
be lost in favor of the transient config sent in with
virNetworkCreateXML() (which would then be the new persistent config)
(obviously unexpected/not desired).

To fix this, virNetworkObjAssignDef() has been changed to

1) properly save/free network->def and network->newDef for all the
various combinations of live/active/persistent, including some
combinations that were previously considered to be an error but didn't
need to be (e.g. setting a "live" config for a network that isn't yet
active but soon will be - that was previously considered an error,
even though in practice it can be very useful).

2) automatically set the persistent flag whenever a new non-live
config is assigned to the network (and clear it when the non-live
config is set to NULL). the libvirt network driver no longer directly
manipulates network->persistent, but instead relies entirely on
virNetworkObjAssignDef() to do the right thing automatically.

After this patch, the following sequence will behave as expected:

virNetworkDefineXML(X)
virNetworkCreateXML(X') (same name but some config different)
virNetworkDestroy(X)

At the end of these calls, the network config will remain as it was
after the initial virNetworkDefine(), whereas previously it would take
on the changes given during virNetworkCreateXML().

Another effect of this tighter coupling between a) setting a !live def
and b) setting/clearing the "persistent" flag, is that future patches
which change the details of network lifecycle management
(e.g. upcoming patches to fix detection of "active" networks when
libvirtd is restarted) will find it much more difficult to break
persistence functionality.
2014-04-27 11:02:05 +03:00
Daniel P. Berrange
c13a952f69 Replace virNetworkObjPtr with virNetworkDefPtr in network platform APIs
The networkCheckRouteCollision, networkAddFirewallRules and
networkRemoveFirewallRules APIs all take a virNetworkObjPtr
instance, but only ever access the 'def' member. It thus
simplifies testing if the APIs are changed to just take a
virNetworkDefPtr instead

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
a66fc27d89 Convert bridge driver over to use new firewall APIs
Update the iptablesXXXX methods so that instead of directly
executing iptables commands, they populate rules in an
instance of virFirewallPtr. The bridge driver can thus
construct the ruleset and then invoke it in one operation
having rollback handled automatically.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-25 15:44:09 +01:00
Daniel P. Berrange
3cfa19da22 Replace Pci with PCI throughout
Since it is an abbreviation, PCI should always be fully
capitalized or full lower case, never Pci.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-04-08 11:15:55 +01:00
Laine Stump
6612d1adb7 network: fix problems with SRV records
A patch submitted by Steven Malin last week pointed out a problem with
libvirt's DNS SRV record configuration:

  https://www.redhat.com/archives/libvir-list/2014-March/msg00536.html

When searching for that message later, I found another series that had
been posted by Guannan Ren back in 2012 that somehow slipped between
the cracks:

  https://www.redhat.com/archives/libvir-list/2012-July/msg00236.html

That patch was very much out of date, but also pointed out some real
problems.

This patch fixes all the noted problems by refactoring
virNetworkDNSSrvDefParseXML() and networkDnsmasqConfContents(), then
verifies those fixes by added several new records to the test case.

Problems fixed:

* both service and protocol now have an underscore ("_") prepended on
  the commandline, as required by RFC2782.

  <srv service='sip' protocol='udp' domain='example.com'
       target='tests.example.com' port='5060' priority='10'
       weight='150'/>

  before: srv-host=sip.udp.example.com,tests.example.com,5060,10,150
  after:  srv-host=_sip._udp.example.com,tests.example.com,5060,10,150

* if "domain" wasn't specified in the <srv> element, the extra
  trailing "." will no longer be added to the dnsmasq commandline.

  <srv service='sip' protocol='udp' target='tests.example.com'
       port='5060' priority='10' weight='150'/>

  before: srv-host=sip.udp.,tests.example.com,5060,10,150
  after:  srv-host=_sip._udp,tests.example.com,5060,10,150

* when optional attributes aren't specified, the separating comma is
  also now not placed on the dnsmasq commandline. If optional
  attributes in the middle of the line are not specified, they are
  replaced with a default value in the commandline (1 for port, 0 for
  priority and weight).

  <srv service='sip' protocol='udp' target='tests.example.com'
       port='5060'/>

  before: srv-host=sip.udp.,tests.example.com,5060,,
  after:  srv-host=_sip._udp,tests.example.com,5060

  (actually the would have generated an error, because "optional"
  attributes weren't really optional.)

* The allowed characters for both service and protocol are now limited
  to alphanumerics, plus a few special characters that are found in
  existing names in /etc/services and /etc/protocols. (One exception
  is that both of these files contain names with an embedded ".", but
  "."  can't be used in these fields of an SRV record because it is
  used as a field separator and there is no method to escape a "."
  into a field.) (Previously only the strings "tcp" and "udp" were
  allowed for protocol, but this restriction has been removed, since
  RFC2782 specifically says that it isn't limited to those, and that
  anyway it is case insensitive.)

* the "domain" attribute is no longer required in order to recognize
  the port, priority, and weight attributes during parsing. Only
  "target" is required for this.

* if "target" isn't specified, port, priority, and weight are not
  allowed (since they are meaningless - an empty target means "this
  service is *not available* for this domain").

* port, priority, and weight are now truly optional, as the comments
  originally suggested, but which was not actually true.
2014-03-26 16:42:43 +02:00
Ján Tomko
c97cfce291 Indent top-level labels by one space in src/network/ 2014-03-25 14:58:39 +01:00
Martin Kletzander
5d734987fd Use K&R style for curly braces in src/network/bridge_driver.c
Signed-off-by: Martin Kletzander <mkletzan@redhat.com>
2014-03-20 17:16:39 +01: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
Pavel Hrdina
b396fae9e2 Fix issue found by coverity and cleanup
Coverity found an issue in lxc_driver and uml_driver that we don't
check the return value of register functions.

I've also updated all other places and unify the way we check the
return value.

Signed-off-by: Pavel Hrdina <phrdina@redhat.com>
2014-03-17 15:02:51 +01:00
Daniel P. Berrange
a84f9bd555 Remove many decls from bridge driver platform header
The bridge_driver_platform.h defines many functions that
a platform driver must implement. Only two of these
functions are actually called from the main bridge driver
code. The remainder can be made internal to the linux
driver only.

Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2014-03-11 11:01:51 +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
Laine Stump
eed46d4cfe network: unplug bandwidth and call networkRunHook only when appropriate
According to commit b4e0299d if networkAllocateActualDevice() was
successful, it will *always* allocate an iface->data.network.actual,
so we can use this during networkReleaseActualDevice() to know if
there is really anything to undo. We were properly using this
information to only decrement the network connections counter if it
had previously been incremented, but we were unconditionally
unplugging bandwidth and calling the "unplugged" network hook for
*all* interfaces (during qemuProcessStop()) whether they had been
previously plugged or not. This caused problems if a domain failed to
start at some time prior to all interfaces being allocated. (I
encountered this when an interface had a bandwidth floor set but no
inbound QoS).

This patch changes both the call to networkUnplugBandwidth() and the
call to networkRunHook() to only be called if there was a previous
call to "plug" for the same interface.
2014-02-26 13:08:56 +02:00
Laine Stump
0700a3dac4 network: don't even call networkRunHook if there is no network
networkAllocateActualDevice() is called for *all* interfaces, not just
those with type='network'. In that case, it will jump down to its
validate: label immediately, without allocating anything. After
validation is done, two counters are potentially updated (one for the
network, and one for any particular physical device that is chosen),
and then networkRunHook() is called.

This patch refactors that code a slight bit so that networkRunHook()
doesn't get called if netdef is NULL (i.e. type != network) and to
place the conditional increment of dev->connections inside the "if
(netdef)" as well - dev can never be non-null if netdef is null
(because "dev" is the pointer to a device in a network's pool of
devices), so this doesn't have any functional effect, it just makes
the code clearer.
2014-02-26 13:03:49 +02:00
Laine Stump
2122cf3979 network: include plugged interface XML in "plugged" network hook
The network hook script gets called whenever an interface is plugged
into or unplugged from a network, but even though the full XML of both
the network and the domain is included, there is no reasonable way to
determine what exact resources the plugged interface is using:

1) Prior to a recent patch which modified the status XML of interfaces
to include the information about actual hardware resources used, it
would be possible to scan through the domain XML output sent to the
hook, and from there find the correct interface, but that interface
definition would not include any runtime info (e.g. bandwidth or vlan
taken from a portgroup, or which physdev was used in case of a macvtap
network).

2) After the patch modifying the status XML of interfaces, the network
name would no longer be included in the domain XML, so it would be
completely impossible to determine which interface was the one being
plugged.

To solve that problem, this patch includes a single <interface>
element at the beginning of the XML sent to the network hook for
"plugged" and "unplugged" (just inside <hookData>) that is the status
XML of the interface being plugged. This XML will include all info
gathered from the chosen network and portgroup.

NB: due to hardcoded spaces in all of the device *Format() functions,
the <interface> element inside the <hookData> will be indented by 6
spaces rather than 2. I had intended to fix this, but it turns out
that to make virDomainNetDefFormat() indentation relative, I would
have to do the same to virDomainDeviceInfoFormat(), and that function
is called from 19 places - making that a prerequisite of this patch
would cause too many merge difficulties if we needed to backport
network hooks, so I chose to ignore the problem here and fix the
problem for *all* devices in a followup later.
2014-02-25 16:07:36 +02:00
Michal Privoznik
83c404ff9b networkRunHook: Run hook only if possible
Currently, networkRunHook() is called in networkAllocateActualDevice and
friends. These functions, however, doesn't necessarily work on networks,
For example, if domain's interface is defined in this fashion:

    <interface type='bridge'>
      <mac address='52:54:00:0b:3b:16'/>
      <source bridge='virbr1'/>
      <model type='rtl8139'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x09' function='0x0'/>
    </interface>

The networkAllocateActualDevice jumps directly onto 'validate' label as
the interface is not type of 'network'. Hence, @network is left
initialized to NULL and networkRunHook(network, ...) is called. One of
the things that the hook function does is dereference @network. Soupir.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-20 08:56:17 +01:00
Michal Privoznik
4d88294483 bridge_driver.h: Fix build --without-network
The networkNotifyActualDevice function is accepting two arguments, not
one:

qemu/qemu_process.c: In function 'qemuProcessNotifyNets':
qemu/qemu_process.c:2776:47: error: macro "networkNotifyActualDevice" passed 2 arguments, but takes just 1
         if (networkNotifyActualDevice(def, net) < 0)
                                               ^

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-18 19:52:39 +01:00
Michal Privoznik
9de7309125 network: Taint networks that are using hook script
Basically, the idea is copied from domain code, where tainting
exists for a while. Currently, only one taint reason exists -
VIR_NETWORK_TAINT_HOOK to mark those networks which caused invoking
of hook script.

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-18 14:46:49 +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
Michal Privoznik
e209c07760 networkStartNetwork: Be more verbose
The lack of debug printings might be frustrating in the future.
Moreover, this function doesn't follow the usual pattern we have in the
rest of the code:

  int ret = -1;
  /* do some work */
  ret = 0;
cleanup:
  /* some cleanup work */
  return ret;

Signed-off-by: Michal Privoznik <mprivozn@redhat.com>
2014-02-10 11:47:24 +01:00
Eric Blake
11f20e43f1 event: move event filtering to daemon (regression fix)
https://bugzilla.redhat.com/show_bug.cgi?id=1058839

Commit f9f56340 for CVE-2014-0028 almost had the right idea - we
need to check the ACL rules to filter which events to send.  But
it overlooked one thing: the event dispatch queue is running in
the main loop thread, and therefore does not normally have a
current virIdentityPtr.  But filter checks can be based on current
identity, so when libvirtd.conf contains access_drivers=["polkit"],
we ended up rejecting access for EVERY event due to failure to
look up the current identity, even if it should have been allowed.

Furthermore, even for events that are triggered by API calls, it
is important to remember that the point of events is that they can
be copied across multiple connections, which may have separate
identities and permissions.  So even if events were dispatched
from a context where we have an identity, we must change to the
correct identity of the connection that will be receiving the
event, rather than basing a decision on the context that triggered
the event, when deciding whether to filter an event to a
particular connection.

If there were an easy way to get from virConnectPtr to the
appropriate virIdentityPtr, then object_event.c could adjust the
identity prior to checking whether to dispatch an event.  But
setting up that back-reference is a bit invasive.  Instead, it
is easier to delay the filtering check until lower down the
stack, at the point where we have direct access to the RPC
client object that owns an identity.  As such, this patch ends
up reverting a large portion of the framework of commit f9f56340.
We also have to teach 'make check' to special-case the fact that
the event registration filtering is done at the point of dispatch,
rather than the point of registration.  Note that even though we
don't actually use virConnectDomainEventRegisterCheckACL (because
the RegisterAny variant is sufficient), we still generate the
function for the purposes of documenting that the filtering
takes place.

Also note that I did not entirely delete the notion of a filter
from object_event.c; I still plan on using that for my upcoming
patch series for qemu monitor events in libvirt-qemu.so.  In
other words, while this patch changes ACL filtering to live in
remote.c and therefore we have no current client of the filtering
in object_event.c, the notion of filtering in object_event.c is
still useful down the road.

* src/check-aclrules.pl: Exempt event registration from having to
pass checkACL filter down call stack.
* daemon/remote.c (remoteRelayDomainEventCheckACL)
(remoteRelayNetworkEventCheckACL): New functions.
(remoteRelay*Event*): Use new functions.
* src/conf/domain_event.h (virDomainEventStateRegister)
(virDomainEventStateRegisterID): Drop unused parameter.
* src/conf/network_event.h (virNetworkEventStateRegisterID):
Likewise.
* src/conf/domain_event.c (virDomainEventFilter): Delete unused
function.
* src/conf/network_event.c (virNetworkEventFilter): Likewise.
* src/libxl/libxl_driver.c: Adjust caller.
* src/lxc/lxc_driver.c: Likewise.
* src/network/bridge_driver.c: Likewise.
* src/qemu/qemu_driver.c: Likewise.
* src/remote/remote_driver.c: Likewise.
* src/test/test_driver.c: Likewise.
* src/uml/uml_driver.c: Likewise.
* src/vbox/vbox_tmpl.c: Likewise.
* src/xen/xen_driver.c: Likewise.

Signed-off-by: Eric Blake <eblake@redhat.com>
2014-02-05 08:03:31 -07:00