mirror of
https://github.com/retspen/webvirtcloud
synced 2026-11-08 11:16:47 +00:00
fix(networks): a network's addresses are read as libvirt writes them, and its changes keep each other
Reviewed with Codex against libvirt's network format and driver.
- Addresses: wvmNetwork found a network's <ip> by its text, so one
written as <ip .../> or <ip><dhcp>... without whitespace had none,
and a second address of a family overwrote the first. ip_networks
reads every <ip> in order, its index being libvirt's parentIndex:
family (ipv4 when written), address, subnet, DHCP (a <dhcp>, also
with fixed addresses only), first range and fixed addresses. The
parentIndex was guessed from the number of families, wrong when IPv6
comes first; changes now name the address by its index.
- One read: the page read the network's XML once per getter, ten or
more round trips; it reads it once (a cached_property of the
request's wvmNetwork). A change starts from the saved definition
read anew (VIR_NETWORK_XML_INACTIVE), not the running one: two QoS
changes on a running network no longer undo the first. The XML
editor shows and changes the saved definition, and defines this
network only (its name, and its UUID if given), read for that with
no entity expanded and handed to libvirt as written; an XML declaring
its encoding is taken. The actions go back to the network's page by
its own URL.
- Fixed addresses are found by the address they had (a hidden field),
not by the editable box: changing it and pressing Delete deleted
another entry or none. A change deletes the entry and adds it anew
from a copy, keeping what the page does not show (a client id, a
lease), and puts it back if the add fails: libvirt's own change
finds an entry by any of its MAC, address or name, so it could
replace another entry, and never by an IPv6 DUID. The address must
be of the subnet, not the host's, and neither it, the MAC or DUID
nor the name another entry's; an entry gone meanwhile is refused,
not added anew; an unchanged one writes no audit row. They can be
added while the network is stopped; a running network saved with
other addresses than it runs with is not changed live, as
parentIndex would name another <ip> of it.
- An address without a netmask or prefix takes libvirt's (IPv4 its
class's, IPv6 /64), for its checks and the overlap check.
- The DHCP range must be in the subnet, in order and not take in the
host's address.
- The create form takes a known mode only ("bogus" made an isolated
network, a missing one a server error); NAT and routed networks need
an IPv4 subnet, an isolated one may have none, a bridge or macvtap
network needs its bridge or interface and gets no addresses; IPv6
only with its box (whose value was "false", so never); no name or
subnet of another network of the host. "Fixed Addresses" at create
goes: it made a random-MAC entry for every address of the range,
for no real VM.
- Refusals of a fixed address, the DHCP range, the XML and a QoS
removal are messages, not server errors.
- The IPv6 forwarding of a bridge or macvtap network is the outside
network's, not ROUTE.
- get_networks_info reads each network's XML once and gives its
autostart and addresses too. Unused can_pxe, DHCP lease helpers,
get_uuid and the per-family range and host getters go.
This commit is contained in:
parent
befd1747df
commit
0c9a002ef4
19 changed files with 646 additions and 602 deletions
|
|
@ -24,64 +24,80 @@ def checked_subnet(subnet, version):
|
|||
|
||||
|
||||
class AddNetPool(forms.Form):
|
||||
"""A new network of the host. networks: the host's networks
|
||||
(get_networks_info), whose names it may not take nor overlap their
|
||||
subnets. NAT and routed networks need an IPv4 subnet; an isolated one
|
||||
may have none; a bridge or macvtap network takes its addresses from the
|
||||
outside network, and needs the host's bridge or interface."""
|
||||
|
||||
MODES = ("nat", "route", "none", "bridge", "macvtap")
|
||||
|
||||
name = forms.CharField(
|
||||
error_messages={"required": _("No pool name has been entered")},
|
||||
max_length=20
|
||||
)
|
||||
subnet = forms.CharField(
|
||||
error_messages={"required": _("No IPv4 subnet has been entered")},
|
||||
max_length=20,
|
||||
required=False,
|
||||
)
|
||||
subnet6 = forms.CharField(
|
||||
error_messages={"required": _("No IPv6 subnet has been entered")},
|
||||
max_length=42,
|
||||
required=False,
|
||||
)
|
||||
forward = forms.CharField(max_length=100)
|
||||
subnet = forms.CharField(label=_("IPv4 subnet"), max_length=20, required=False)
|
||||
subnet6 = forms.CharField(label=_("IPv6 subnet"), max_length=42, required=False)
|
||||
forward = forms.ChoiceField(choices=[(mode, mode) for mode in MODES])
|
||||
dhcp4 = forms.BooleanField(required=False)
|
||||
enable_ipv6 = forms.BooleanField(required=False)
|
||||
dhcp6 = forms.BooleanField(required=False)
|
||||
fixed = forms.BooleanField(required=False)
|
||||
bridge_name = forms.CharField(max_length=20, required=False)
|
||||
bridge_name = forms.CharField(label=_("Bridge or interface"), max_length=20, required=False)
|
||||
openvswitch = forms.BooleanField(required=False)
|
||||
|
||||
def __init__(self, *args, networks=(), **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.networks = networks
|
||||
|
||||
def clean_name(self):
|
||||
name = self.cleaned_data["name"]
|
||||
have_symbol = re.match(r"^[a-zA-Z0-9\.\_\-]+$", name)
|
||||
if not have_symbol:
|
||||
if not re.fullmatch(r"[a-zA-Z0-9._-]+", name):
|
||||
raise forms.ValidationError(
|
||||
_("The pool name must not contain any special characters")
|
||||
)
|
||||
elif len(name) > 20:
|
||||
raise forms.ValidationError(
|
||||
_("The pool name must not exceed 20 characters")
|
||||
)
|
||||
if any(net["name"] == name for net in self.networks):
|
||||
raise forms.ValidationError(_("This host has a network of that name"), code="taken")
|
||||
return name
|
||||
|
||||
def clean_subnet(self):
|
||||
return checked_subnet(self.cleaned_data["subnet"], 4)
|
||||
|
||||
def clean(self):
|
||||
cleaned = super().clean()
|
||||
# one fixed address per address of the DHCP range
|
||||
subnet = cleaned.get("subnet")
|
||||
if cleaned.get("fixed") and subnet and ipaddress.ip_network(subnet, strict=False).prefixlen < 24:
|
||||
self.add_error("fixed", _("Fixed addresses need an IPv4 subnet of /24 or smaller"))
|
||||
return cleaned
|
||||
|
||||
def clean_subnet6(self):
|
||||
return checked_subnet(self.cleaned_data["subnet6"], 6)
|
||||
|
||||
def clean_bridge_name(self):
|
||||
bridge_name = self.cleaned_data["bridge_name"]
|
||||
if self.cleaned_data["forward"] in ["bridge", "macvtap"]:
|
||||
have_symbol = re.match(r"^[a-zA-Z0-9\.\_\:\-]+$", bridge_name)
|
||||
if not have_symbol:
|
||||
raise forms.ValidationError(
|
||||
_("The pool bridge name must not contain any special characters")
|
||||
)
|
||||
elif len(bridge_name) > 20:
|
||||
raise forms.ValidationError(
|
||||
_("The pool bridge name must not exceed 20 characters")
|
||||
)
|
||||
return bridge_name
|
||||
if bridge_name and not re.fullmatch(r"[a-zA-Z0-9._:-]+", bridge_name):
|
||||
raise forms.ValidationError(
|
||||
_("The pool bridge name must not contain any special characters")
|
||||
)
|
||||
return bridge_name
|
||||
|
||||
def clean(self):
|
||||
data = super().clean()
|
||||
mode = data.get("forward")
|
||||
if mode in ("bridge", "macvtap"):
|
||||
# the outside network gives the addresses: none of libvirt's
|
||||
data.update(subnet="", subnet6="", dhcp4=False, dhcp6=False)
|
||||
if not data.get("bridge_name") and "bridge_name" not in self.errors:
|
||||
self.add_error("bridge_name", _("This field is required."))
|
||||
else:
|
||||
data["bridge_name"] = ""
|
||||
if mode in ("nat", "route") and not data.get("subnet") and "subnet" not in self.errors:
|
||||
self.add_error("subnet", _("This field is required."))
|
||||
if not data.get("enable_ipv6"):
|
||||
data["subnet6"] = ""
|
||||
elif not data.get("subnet6") and "subnet6" not in self.errors:
|
||||
self.add_error("subnet6", _("This field is required."))
|
||||
if mode != "bridge":
|
||||
data["openvswitch"] = False
|
||||
for field in ("subnet", "subnet6"):
|
||||
if data.get(field) and field not in self.errors:
|
||||
subnet = ipaddress.ip_network(data[field], strict=False)
|
||||
for net in self.networks:
|
||||
taken = next((ip["subnet"] for ip in net["ips"]
|
||||
if ip["subnet"] and ip["subnet"].version == subnet.version and ip["subnet"].overlaps(subnet)), None)
|
||||
if taken:
|
||||
self.add_error(field, _("Network %(net)s has %(subnet)s") % {"net": net["name"], "subnet": taken})
|
||||
break
|
||||
return data
|
||||
|
|
|
|||
|
|
@ -45,16 +45,10 @@
|
|||
<input id="net_dhcp4" type="checkbox" name="dhcp4" value="true" checked>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row bridge_name_form_group_dhcp">
|
||||
<label for="net_fixed" class="col-sm-4 col-form-label">{% trans "Fixed Addresses" %}</label>
|
||||
<div class="col-sm-6">
|
||||
<input id="net_fixed" type="checkbox" name="fixed" value="true">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row bridge_name_form_group_dhcp">
|
||||
<label for="enable_ipv6" class="col-sm-4 col-form-label">{% trans "Enable IPv6" %}</label>
|
||||
<div class="col-sm-6">
|
||||
<input type="checkbox" id="enable_ipv6" name="enable_ipv6" value="false">
|
||||
<input type="checkbox" id="enable_ipv6" name="enable_ipv6" value="true">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row ipv6_group">
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
<div class="row">
|
||||
<label for="ipv4_fixed_subnet" class="col-sm-4 col-form-label">{% trans "Subnet Pool" %}</label>
|
||||
<div class="col-sm-6">
|
||||
<input id="ipv4_fixed_subnet" type="text" readonly class="form-control" name="subnet" value="{{ ipv4_network }}" required pattern="[0-9\/\.]+">
|
||||
<input id="ipv4_fixed_subnet" type="text" readonly class="form-control" name="subnet" value="{{ ipv4.subnet }}" required pattern="[0-9\/\.]+">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
|
|
@ -41,7 +41,7 @@
|
|||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<input name="family" value="ipv4" hidden/>
|
||||
<input name="ip_index" value="{{ ipv4.index }}" hidden/>
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Close" %}</button>
|
||||
<button type="submit" class="btn btn-primary" name="modify_fixed_address">{% trans "Create" %}</button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
<div class="row">
|
||||
<label for="ipv6_fixed_subnet" class="col-sm-4 col-form-label">{% trans "Subnet Pool" %}</label>
|
||||
<div class="col-sm-6">
|
||||
<input id="ipv6_fixed_subnet" type="text" readonly class="form-control" name="subnet" value="{{ ipv6_network }}" required pattern="[0-9\/\.]+">
|
||||
<input id="ipv6_fixed_subnet" type="text" readonly class="form-control" name="subnet" value="{{ ipv6.subnet }}" required pattern="[0-9\/\.]+">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
|
|
@ -41,7 +41,7 @@
|
|||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<input name="family" value="ipv6" hidden/>
|
||||
<input name="ip_index" value="{{ ipv6.index }}" hidden/>
|
||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{% trans "Close" %}</button>
|
||||
<button type="submit" class="btn btn-primary" name="modify_fixed_address">{% trans "Create" %}</button>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -86,27 +86,27 @@
|
|||
{% endif %}
|
||||
</dd>
|
||||
<dt class="col-6">{% trans "Network" %}</dt>
|
||||
<dd class="col-6">{{ ipv4_network|default:"-" }}</dd>
|
||||
<dd class="col-6">{{ ipv4.subnet|default:"-" }}</dd>
|
||||
<dt class="col-6">{% trans "DHCP" %}:</dt>
|
||||
<dd class="col-6">
|
||||
{% if ipv4_dhcp_range_start and ipv4_dhcp_range_end %}
|
||||
{% if ipv4.dhcp %}
|
||||
<span class="badge bg-success-subtle text-success-emphasis">{% trans "ON" %}</span>
|
||||
{% else %}
|
||||
<span class="badge bg-danger-subtle text-danger-emphasis">{% trans "OFF" %}</span>
|
||||
{% endif %}
|
||||
</dd>
|
||||
{% if ipv4_dhcp_range_start and ipv4_dhcp_range_end %}
|
||||
{% if ipv4.range %}
|
||||
{% if state %}
|
||||
<dt class="col-6">{% trans "Start" %}</dt>
|
||||
<dd class="col-6">{{ ipv4_dhcp_range_start }}</dd>
|
||||
<dd class="col-6">{{ ipv4.range.0 }}</dd>
|
||||
<dt class="col-6">{% trans "End" %}</dt>
|
||||
<dd class="col-6">{{ ipv4_dhcp_range_end }}</dd>
|
||||
<dd class="col-6">{{ ipv4.range.1 }}</dd>
|
||||
{% else %}
|
||||
<form class="col-lg-12 ps-0" method="post" role="form" aria-label="Edit dhcp range form">{% csrf_token %}
|
||||
<dt class="col-6">{% trans "Start" %}</dt>
|
||||
<dd class="col-6"><input name="range_start" value="{{ ipv4_dhcp_range_start }}"/></dd>
|
||||
<dd class="col-6"><input name="range_start" value="{{ ipv4.range.0 }}"/></dd>
|
||||
<dt class="col-6">{% trans "End" %}</dt>
|
||||
<dd class="col-6"><input name="range_end" value="{{ ipv4_dhcp_range_end }}"/></dd>
|
||||
<dd class="col-6"><input name="range_end" value="{{ ipv4.range.1 }}"/></dd>
|
||||
<dt class="col-6"></dt>
|
||||
<dd class="col-6 ">
|
||||
<input type="submit"
|
||||
|
|
@ -116,22 +116,20 @@
|
|||
title="{% trans "Edit DHCP Range" %}"
|
||||
/>
|
||||
</dd>
|
||||
<input hidden name="family" value="ipv4"/>
|
||||
<input hidden name="ip_index" value="{{ ipv4.index }}"/>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</dl>
|
||||
|
||||
{% if ipv4_dhcp_range_start and ipv4_dhcp_range_end %}
|
||||
{% if state %}
|
||||
{% include 'modify_ipv4_fixed_address.html' %}
|
||||
{% endif %}
|
||||
{% if ipv4.dhcp %}
|
||||
{% include 'modify_ipv4_fixed_address.html' %}
|
||||
|
||||
<h5 class="mb-3">{% trans "IPv4 Fixed Addresses" %}</h5>
|
||||
|
||||
{% endif %}
|
||||
|
||||
{% if ipv4_fixed_address %}
|
||||
{% if ipv4.hosts %}
|
||||
|
||||
<div class="d-grid col-12">
|
||||
<button class="btn btn-light" role="button" data-bs-toggle="collapse" data-bs-target="#collapseipv4fix" aria-expanded="true" aria-controls="collapseXML">
|
||||
|
|
@ -158,14 +156,15 @@
|
|||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for fix4 in ipv4_fixed_address %}
|
||||
{% for fix4 in ipv4.hosts %}
|
||||
<tr>
|
||||
<form method="post" role="form" aria-label="IPv4 edit/delete form">{% csrf_token %}
|
||||
<td><input class="form-control" value="{{ fix4.mac|default_if_none:"" }}" name="mac" readonly/></td>
|
||||
<td><input class="form-control" value="{{ fix4.ip }}" name="address" /></td>
|
||||
<td><input class="form-control" value="{{ fix4.name }}" name="name" /></td>
|
||||
<td class="text-nowrap">
|
||||
<input hidden name="family" value="ipv4"/>
|
||||
<input hidden name="ip_index" value="{{ ipv4.index }}"/>
|
||||
<input hidden name="original" value="{{ fix4.ip }}"/>
|
||||
{% if fix4.mac %}{# an entry is changed by its MAC #}
|
||||
<button type="submit" class="btn btn-sm btn-primary"
|
||||
name="modify_fixed_address"
|
||||
|
|
@ -194,35 +193,37 @@
|
|||
<dl class="ms-3 row">
|
||||
<dt class="col-6">{% trans "IPv6 Forwarding" %}</dt>
|
||||
<dd class="col-6">
|
||||
{% if not net_forward.0 %}
|
||||
{% if not net_forward.0 or net_forward.0 == "none" %}
|
||||
{% trans "ISOLATE" %}
|
||||
{% else %}
|
||||
{% elif net_forward.0 == "nat" or net_forward.0 == "route" or net_forward.0 == "open" %}
|
||||
{% trans "ROUTE" %}
|
||||
{% else %}
|
||||
{% trans "From the outside network" %}
|
||||
{% endif %}
|
||||
</dd>
|
||||
<dt class="col-6">{% trans "Network" %}</dt>
|
||||
<dd class="col-6">{{ ipv6_network|default:"-" }}</dd>
|
||||
<dd class="col-6">{{ ipv6.subnet|default:"-" }}</dd>
|
||||
<dt class="col-6">{% trans "DHCP" %}</dt>
|
||||
|
||||
<dd class="col-6">
|
||||
{% if ipv6_dhcp_range_start and ipv6_dhcp_range_end %}
|
||||
{% if ipv6.dhcp %}
|
||||
<span class="badge bg-success-subtle text-success-emphasis">{% trans "ON" %}</span>
|
||||
{% else %}
|
||||
<span class="badge bg-danger-subtle text-danger-emphasis">{% trans "OFF" %}</span>
|
||||
{% endif %}
|
||||
</dd>
|
||||
{% if ipv6_dhcp_range_start and ipv6_dhcp_range_end %}
|
||||
{% if ipv6.range %}
|
||||
{% if state %}
|
||||
<dt class="col-6">{% trans "Start" %}</dt>
|
||||
<dd class="col-6">{{ ipv6_dhcp_range_start }}</dd>
|
||||
<dd class="col-6">{{ ipv6.range.0 }}</dd>
|
||||
<dt class="col-6">{% trans "End" %}</dt>
|
||||
<dd class="col-6">{{ ipv6_dhcp_range_end }}</dd>
|
||||
<dd class="col-6">{{ ipv6.range.1 }}</dd>
|
||||
{% else %}
|
||||
<form class="col-lg-12 ps-0" method="post" role="form" aria-label="Edit dhcp range form">{% csrf_token %}
|
||||
<dt class="col-6">{% trans "Start" %}</dt>
|
||||
<dd class="col-6"><input name="range_start" value="{{ ipv6_dhcp_range_start }}"/></dd>
|
||||
<dd class="col-6"><input name="range_start" value="{{ ipv6.range.0 }}"/></dd>
|
||||
<dt class="col-6">{% trans "End" %}</dt>
|
||||
<dd class="col-6"><input name="range_end" value="{{ ipv6_dhcp_range_end }}"/></dd>
|
||||
<dd class="col-6"><input name="range_end" value="{{ ipv6.range.1 }}"/></dd>
|
||||
<dt class="col-6"></dt>
|
||||
<dd class="d-grid col-6">
|
||||
<input
|
||||
|
|
@ -233,20 +234,18 @@
|
|||
title="{% trans "Edit DHCP Range" %}"
|
||||
/>
|
||||
</dd>
|
||||
<input hidden name="family" value="ipv6"/>
|
||||
<input hidden name="ip_index" value="{{ ipv6.index }}"/>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
</dl>
|
||||
|
||||
{% if ipv6_dhcp_range_start and ipv6_dhcp_range_end %}
|
||||
{% if state %}
|
||||
{% include 'modify_ipv6_fixed_address.html' %}
|
||||
{% endif %}
|
||||
{% if ipv6.dhcp %}
|
||||
{% include 'modify_ipv6_fixed_address.html' %}
|
||||
<h5 class="mb-3">{% trans "IPv6 Fixed Addresses" %}</h5>
|
||||
{% endif %}
|
||||
|
||||
{% if ipv6_fixed_address %}
|
||||
{% if ipv6.hosts %}
|
||||
<div class="d-grid col-12">
|
||||
<button class="btn btn-light" role="button" data-bs-toggle="collapse" data-bs-target="#collapseipv6fix" aria-expanded="true" aria-controls="collapseipv6fix">
|
||||
<span>{% bs_icon 'chevron-down' %} </span>
|
||||
|
|
@ -271,14 +270,15 @@
|
|||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for fix6 in ipv6_fixed_address %}
|
||||
{% for fix6 in ipv6.hosts %}
|
||||
<tr>
|
||||
<form method="post" role="form" aria-label="IP v6 edit/delete form">{% csrf_token %}
|
||||
<td><input class="form-control" value="{{ fix6.id|default_if_none:"" }}" name="id" readonly/></td>
|
||||
<td><input class="form-control" value="{{ fix6.ip }}" name="address" /></td>
|
||||
<td><input class="form-control" value="{{ fix6.name }}" name="name" /></td>
|
||||
<td class="text-nowrap">
|
||||
<input hidden name="family" value="ipv6"/>
|
||||
<input hidden name="ip_index" value="{{ ipv6.index }}"/>
|
||||
<input hidden name="original" value="{{ fix6.ip }}"/>
|
||||
{% if fix6.id %}{# an entry is changed by its DUID #}
|
||||
<button type="submit" class="btn btn-sm btn-primary"
|
||||
name="modify_fixed_address"
|
||||
|
|
|
|||
15
networks/tests/driver.py
Normal file
15
networks/tests/driver.py
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
"""libvirt's test driver for the network tests."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import libvirt
|
||||
|
||||
|
||||
def without_inactive_flag(test):
|
||||
"""The test driver refuses VIR_NETWORK_XML_INACTIVE, which real hosts take:
|
||||
the saved definition is read as the running one, the same for a network
|
||||
the test does not change while it runs."""
|
||||
xml_desc = libvirt.virNetwork.XMLDesc
|
||||
patcher = patch.object(libvirt.virNetwork, "XMLDesc", lambda net, flags=0: xml_desc(net, 0))
|
||||
patcher.start()
|
||||
test.addCleanup(patcher.stop)
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
"""The create-network form takes real subnets of the right IP version; one
|
||||
it refuses is a field error, not a server error."""
|
||||
it refuses is a field error, not a server error. Each mode needs its own
|
||||
fields, a known mode only, and no subnet of another network of the host."""
|
||||
|
||||
from django.test import SimpleTestCase
|
||||
from networks.forms import AddNetPool
|
||||
|
|
@ -13,8 +14,7 @@ class SubnetTests(SimpleTestCase):
|
|||
def test_subnets_are_accepted(self):
|
||||
for subnet in ("192.0.2.0/24", "192.0.2.0/30", "255.255.255.252/30"):
|
||||
with self.subTest(subnet=subnet):
|
||||
self.assertTrue(form(subnet=subnet, subnet6="2001:db8::/64").is_valid())
|
||||
self.assertTrue(form().is_valid()) # both optional
|
||||
self.assertTrue(form(subnet=subnet, subnet6="2001:db8::/64", enable_ipv6=True).is_valid())
|
||||
|
||||
def test_a_subnet_that_is_not_one_is_refused(self):
|
||||
for field, value in (
|
||||
|
|
@ -35,3 +35,39 @@ class SubnetTests(SimpleTestCase):
|
|||
):
|
||||
with self.subTest(field=field, value=value):
|
||||
self.assertIn(field, form(**{field: value}).errors)
|
||||
|
||||
|
||||
NETWORKS = [{"name": "default", "ips": [{"subnet": __import__("ipaddress").ip_network("192.168.122.0/24")}]}]
|
||||
|
||||
|
||||
def errors(**fields):
|
||||
f = AddNetPool({"name": "wvc-test-net", **fields}, networks=NETWORKS)
|
||||
f.is_valid()
|
||||
return sorted(f.errors)
|
||||
|
||||
|
||||
class ModeTests(SimpleTestCase):
|
||||
def test_each_mode_needs_its_fields(self):
|
||||
self.assertEqual(errors(forward="nat"), ["subnet"])
|
||||
self.assertEqual(errors(forward="route"), ["subnet"])
|
||||
self.assertEqual(errors(forward="none"), []) # an isolated network may have no address
|
||||
self.assertEqual(errors(forward="bridge"), ["bridge_name"])
|
||||
self.assertEqual(errors(forward="macvtap"), ["bridge_name"])
|
||||
self.assertEqual(errors(forward="none", enable_ipv6=True), ["subnet6"])
|
||||
self.assertEqual(errors(forward="bogus", subnet="192.0.2.0/24"), ["forward"])
|
||||
self.assertEqual(errors(subnet="192.0.2.0/24"), ["forward"]) # no mode: an error, not a server error
|
||||
|
||||
def test_a_bridge_takes_no_addresses_and_ipv6_needs_its_box(self):
|
||||
f = AddNetPool({"name": "br", "forward": "bridge", "bridge_name": "br0", "subnet": "192.0.2.0/24", "dhcp4": True})
|
||||
self.assertTrue(f.is_valid())
|
||||
self.assertEqual((f.cleaned_data["subnet"], f.cleaned_data["dhcp4"]), ("", False))
|
||||
f = AddNetPool({"name": "n", "forward": "nat", "subnet": "192.0.2.0/24", "subnet6": "2001:db8::/64"})
|
||||
self.assertTrue(f.is_valid())
|
||||
self.assertEqual(f.cleaned_data["subnet6"], "")
|
||||
|
||||
def test_a_network_takes_no_name_or_subnet_of_another(self):
|
||||
self.assertEqual(errors(forward="nat", subnet="192.168.122.128/25"), ["subnet"])
|
||||
self.assertEqual(errors(forward="nat", subnet="192.168.0.0/16"), ["subnet"])
|
||||
self.assertEqual(errors(forward="nat", subnet="192.0.2.0/24"), [])
|
||||
f = AddNetPool({"name": "default", "forward": "none"}, networks=NETWORKS)
|
||||
self.assertTrue(f.has_error("name", "taken"))
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ from computes.models import Compute
|
|||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.messages import get_messages
|
||||
from django.test import TestCase
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
from django.urls import reverse
|
||||
|
||||
from logs.models import Logs
|
||||
|
|
@ -34,6 +35,7 @@ class NetworkRowTests(TestCase):
|
|||
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
without_inactive_flag(self)
|
||||
self.compute = Compute.objects.create(name="c1", hostname="localhost", login="", password="", type=4)
|
||||
self.client.force_login(get_user_model().objects.create_superuser("audit-admin", "a@example.com", "pw"))
|
||||
Logs.objects.all().delete() # the login's row
|
||||
|
|
@ -45,13 +47,13 @@ class NetworkRowTests(TestCase):
|
|||
def test_network_actions(self):
|
||||
xml = self.conn.networkLookupByName("lab").XMLDesc(0)
|
||||
self.post({"stop": ""})
|
||||
self.post({"modify_dhcp_range": "", "range_start": "192.0.2.30", "range_end": "192.0.2.40", "family": "ipv4"})
|
||||
self.post({"modify_dhcp_range": "", "range_start": "192.0.2.30", "range_end": "192.0.2.40", "ip_index": "0"})
|
||||
self.post({"start": ""})
|
||||
self.post({"set_autostart": ""})
|
||||
self.post({"unset_autostart": ""})
|
||||
self.post({"modify_fixed_address": "", "name": "web-1", "address": "192.0.2.31",
|
||||
"mac": "52:54:00:00:00:31", "family": "ipv4"})
|
||||
self.post({"delete_fixed_address": "", "address": "192.0.2.31", "family": "ipv4"})
|
||||
"mac": "52:54:00:00:00:31", "ip_index": "0"})
|
||||
self.post({"delete_fixed_address": "", "original": "192.0.2.31", "ip_index": "0"})
|
||||
self.post({"set_qos": "", "qos_direction": "inbound", "qos_average": "100"})
|
||||
self.post({"unset_qos": "", "qos_direction": "inbound"})
|
||||
self.post({"edit_network": "", "edit_xml": xml})
|
||||
|
|
@ -59,7 +61,7 @@ class NetworkRowTests(TestCase):
|
|||
self.post({"delete": ""})
|
||||
self.assertEqual(rows(), [
|
||||
("Network lab: stop", True),
|
||||
("Network lab: set DHCP range IPV4", True),
|
||||
("Network lab: set DHCP range", True),
|
||||
("Network lab: start", True),
|
||||
("Network lab: autostart on", True),
|
||||
("Network lab: autostart off", True),
|
||||
|
|
@ -94,5 +96,5 @@ class NetworkRowTests(TestCase):
|
|||
"dhcp4": "on"})
|
||||
self.client.post(url, {"create": "", "name": "bad name!", "forward": "nat"}) # invalid form
|
||||
response = self.client.post(url, {"create": "", "name": "lab", "forward": "nat", "subnet": "203.0.113.0/24"})
|
||||
self.assertIn("Network pool name already in use", [str(m) for m in get_messages(response.wsgi_request)])
|
||||
self.assertIn("* This host has a network of that name", [str(m) for m in get_messages(response.wsgi_request)])
|
||||
self.assertEqual(rows(), [("Network audit-net: add", True), ("Network lab: add: name already in use", False)])
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
"""A network's DHCP range is changed while the network is stopped, and the
|
||||
page says so only when it was: a running network, a network without a
|
||||
range or an unknown address family is refused with the reason. Runs on a
|
||||
private libvirt test driver: "test:///default" is shared by the whole
|
||||
process."""
|
||||
range, an address it does not have or a range outside its subnet is
|
||||
refused with the reason. Runs on a private libvirt test driver:
|
||||
"test:///default" is shared by the whole process."""
|
||||
|
||||
import tempfile
|
||||
from unittest.mock import patch
|
||||
|
|
@ -12,6 +12,7 @@ from computes.models import Compute
|
|||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.messages import get_messages
|
||||
from django.test import TestCase
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
from django.urls import reverse
|
||||
from lxml import etree
|
||||
|
||||
|
|
@ -34,12 +35,13 @@ class DhcpRangeTests(TestCase):
|
|||
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
without_inactive_flag(self)
|
||||
self.compute = Compute.objects.create(name="dhcp", hostname="localhost", login="", password="", type=4)
|
||||
self.client.force_login(get_user_model().objects.create_superuser("dhcp", "dhcp@example.com", "pw"))
|
||||
|
||||
def change(self, network, family="ipv4"):
|
||||
def change(self, network, index="0", start="192.0.2.30", end="192.0.2.40"):
|
||||
response = self.client.post(reverse("network", args=[self.compute.id, network]), {
|
||||
"modify_dhcp_range": "", "range_start": "192.0.2.30", "range_end": "192.0.2.40", "family": family})
|
||||
"modify_dhcp_range": "", "range_start": start, "range_end": end, "ip_index": index})
|
||||
return [str(m) for m in get_messages(response.wsgi_request)]
|
||||
|
||||
def dhcp_range(self, network):
|
||||
|
|
@ -48,7 +50,7 @@ class DhcpRangeTests(TestCase):
|
|||
|
||||
def test_a_stopped_network_gets_the_new_range(self):
|
||||
self.conn.networkLookupByName("lab").destroy()
|
||||
self.assertEqual(self.change("lab"), ["IPV4 DHCP Range is Changed."])
|
||||
self.assertEqual(self.change("lab"), ["The DHCP range is changed"])
|
||||
self.assertEqual(self.dhcp_range("lab"), ["192.0.2.30", "192.0.2.40"])
|
||||
|
||||
def test_a_running_network_is_refused(self):
|
||||
|
|
@ -59,6 +61,14 @@ class DhcpRangeTests(TestCase):
|
|||
def test_a_network_without_a_range_or_an_unknown_family_is_refused(self):
|
||||
self.conn.networkLookupByName("lab").destroy()
|
||||
self.conn.networkLookupByName("plain").destroy()
|
||||
self.assertEqual(self.change("plain"), ["Network plain has no ipv4 DHCP range"])
|
||||
self.assertEqual(self.change("lab", family="ipx"), ["Network lab has no ipx DHCP range"])
|
||||
self.assertEqual(self.change("plain")[-1], "This address of network plain has no DHCP range")
|
||||
self.assertEqual(self.change("lab", index="1")[-1], "Network lab has no such address")
|
||||
self.assertEqual(self.change("lab", index="x")[-1], "Network lab has no such address")
|
||||
self.assertEqual(self.dhcp_range("lab"), ["192.0.2.10", "192.0.2.20"])
|
||||
|
||||
def test_a_range_outside_the_subnet_or_backwards_is_refused(self):
|
||||
self.conn.networkLookupByName("lab").destroy()
|
||||
self.assertEqual(self.change("lab", end="198.51.100.9")[-1], "The range end 198.51.100.9 is not in 192.0.2.0/24")
|
||||
self.assertEqual(self.change("lab", start="192.0.2.1")[-1], "192.0.2.1 is the host's own address on the network")
|
||||
self.assertEqual(self.change("lab", start="192.0.2.50")[-1], "The range starts at 192.0.2.50, after its end 192.0.2.40")
|
||||
self.assertEqual(self.dhcp_range("lab"), ["192.0.2.10", "192.0.2.20"])
|
||||
|
|
|
|||
|
|
@ -1,57 +1,183 @@
|
|||
"""A new network with fixed addresses gets one per address of its DHCP range,
|
||||
for any /24 or smaller subnet; a network that does not start is not left
|
||||
defined; fixed addresses change on a stopped network and may have no MAC."""
|
||||
"""A network's addresses are read from its XML however libvirt writes it,
|
||||
each <ip> by its own index; a change starts from the saved definition, so
|
||||
two in a row keep each other; a fixed address is found by the address it
|
||||
had and checked against its subnet; the XML editor defines only this
|
||||
network; a network that does not start is not left defined. Runs on a
|
||||
private libvirt test driver: "test:///default" is shared by the whole
|
||||
process."""
|
||||
|
||||
from unittest.mock import patch
|
||||
import tempfile
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import libvirt
|
||||
from django.test import SimpleTestCase
|
||||
from libvirt import VIR_NETWORK_UPDATE_AFFECT_CONFIG, VIR_NETWORK_UPDATE_AFFECT_LIVE, libvirtError
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
from lxml import etree
|
||||
from networks.forms import AddNetPool
|
||||
from vrtManager.network import network_size, wvmNetwork, wvmNetworks
|
||||
from vrtManager.network import ip_networks, network_size, wvmNetwork, wvmNetworks
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
NET = ("<network><name>n1</name><ip address='192.0.2.1' netmask='255.255.255.0'><dhcp>"
|
||||
"<range start='192.0.2.2' end='192.0.2.254'/><host name='paul' ip='192.0.2.20'/></dhcp></ip></network>")
|
||||
NODE = """<node>
|
||||
<network><name>lab</name><bridge name='virbr9'/>
|
||||
<ip family='ipv6' address='2001:db8:1::1' prefix='64'/>
|
||||
<ip family='ipv4' address='192.0.2.1' netmask='255.255.255.0'><dhcp><range start='192.0.2.10' end='192.0.2.20'/>
|
||||
<host name='paul' ip='192.0.2.30'/><host mac='52:54:00:00:00:31' ip='192.0.2.31'/></dhcp></ip>
|
||||
</network>
|
||||
</node>"""
|
||||
|
||||
|
||||
class AddressTests(SimpleTestCase):
|
||||
def test_an_address_without_a_prefix_takes_libvirts(self):
|
||||
tree = etree.fromstring("<network><ip address='192.0.2.1'/><ip address='10.1.2.3'/><ip family='ipv6' address='2001:db8::1'/></network>")
|
||||
self.assertEqual([str(ip["subnet"]) for ip in ip_networks(tree)], ["192.0.2.0/24", "10.0.0.0/8", "2001:db8::/64"])
|
||||
|
||||
def test_every_way_libvirt_writes_an_address(self):
|
||||
compact = "<network><ip address='192.0.2.1' netmask='255.255.255.0'/></network>"
|
||||
static = ("<network><ip address='192.0.2.1' prefix='24'><dhcp><host mac='52:54:00:00:00:01' ip='192.0.2.5'/>"
|
||||
"</dhcp></ip><ip family='ipv6' address='2001:db8::1' prefix='64'/></network>")
|
||||
(ip,) = ip_networks(etree.fromstring(compact))
|
||||
self.assertEqual((ip["index"], ip["family"], str(ip["subnet"]), ip["dhcp"]), (0, "ipv4", "192.0.2.0/24", False))
|
||||
v4, v6 = ip_networks(etree.fromstring(static))
|
||||
# DHCP with fixed addresses only is DHCP too
|
||||
self.assertEqual((v4["dhcp"], v4["range"], v4["hosts"][0]["ip"]), (True, None, "192.0.2.5"))
|
||||
self.assertEqual((v6["index"], v6["family"], str(v6["subnet"])), (1, "ipv6", "2001:db8::/64"))
|
||||
|
||||
|
||||
class NetworkChangeTests(SimpleTestCase):
|
||||
def setUp(self):
|
||||
patcher = patch("vrtManager.connection.connection_manager.get_connection")
|
||||
self.wvm = patcher.start().return_value
|
||||
node = tempfile.NamedTemporaryFile("w", suffix=".xml")
|
||||
self.addCleanup(node.close)
|
||||
node.write(NODE)
|
||||
node.flush()
|
||||
self.conn = libvirt.open(f"test://{node.name}")
|
||||
self.addCleanup(self.conn.close)
|
||||
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
without_inactive_flag(self)
|
||||
|
||||
def create(self, subnet):
|
||||
gateway, mask, dhcp = network_size(subnet, True)
|
||||
wvmNetworks("host", "login", "pw", 1).create_network(
|
||||
"n1", "nat", True, gateway, mask, dhcp, False, None, None, None, "", False, fixed=True)
|
||||
return etree.fromstring(self.wvm.networkDefineXML.call_args.args[0])
|
||||
def network(self):
|
||||
return wvmNetwork("localhost", "", "", 4, "lab")
|
||||
|
||||
def test_fixed_addresses_cover_the_dhcp_range(self):
|
||||
ip = self.create("192.0.2.128/25").find("ip")
|
||||
# the gateway is the subnet's first address, not one ending in .1
|
||||
self.assertEqual((ip.get("address"), ip.get("netmask")), ("192.0.2.129", "255.255.255.128"))
|
||||
hosts = ip.xpath("dhcp/host/@ip")
|
||||
self.assertEqual((hosts[0], hosts[-1], len(hosts)), ("192.0.2.130", "192.0.2.254", 125))
|
||||
def saved(self):
|
||||
return etree.fromstring(self.conn.networkLookupByName("lab").XMLDesc(libvirt.VIR_NETWORK_XML_INACTIVE))
|
||||
|
||||
def test_fixed_addresses_need_a_small_subnet(self):
|
||||
form = AddNetPool({"name": "n1", "forward": "nat", "subnet": "198.51.0.0/16", "dhcp4": True, "fixed": True})
|
||||
self.assertIn("fixed", form.errors)
|
||||
def test_the_page_reads_the_xml_once(self):
|
||||
net = self.network()
|
||||
with patch.object(net.net, "XMLDesc", wraps=net.net.XMLDesc) as xml:
|
||||
net.get_ip_networks(), net.get_network_forward(), net.get_network_mac(), net.get_qos()
|
||||
net.get_bridge_device()
|
||||
self.assertEqual(xml.call_count, 1)
|
||||
|
||||
def test_the_ipv4_address_after_an_ipv6_one_keeps_its_index(self):
|
||||
ipv6, ipv4 = self.network().get_ip_networks()
|
||||
self.assertEqual((ipv6["family"], ipv4["family"], ipv4["index"]), ("ipv6", "ipv4", 1))
|
||||
self.network().modify_fixed_address(1, "", "web", "192.0.2.40", "52:54:00:00:00:40")
|
||||
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host[last()]/@ip"), ["192.0.2.40"])
|
||||
|
||||
def test_two_changes_in_a_row_keep_each_other(self):
|
||||
# a running network keeps its running definition until restarted: a
|
||||
# change made from it would drop the change saved before
|
||||
net = self.network()
|
||||
running = net.net.XMLDesc(0)
|
||||
saved = [running]
|
||||
net.net = MagicMock(**{"XMLDesc.side_effect": lambda flags=0: saved[0] if flags else running})
|
||||
with patch.object(self.conn, "networkDefineXML", side_effect=lambda xml: saved.__setitem__(0, xml)):
|
||||
net.set_qos("inbound", 100, 200, 300)
|
||||
net.set_qos("outbound", 10, 20, 30)
|
||||
self.assertEqual(etree.fromstring(saved[0]).xpath("bandwidth/*/@average"), ["100", "10"])
|
||||
|
||||
def test_a_fixed_address_is_found_by_the_address_it_had(self):
|
||||
net = self.network()
|
||||
# a name-only entry changes too, and the one deleted is the one it was
|
||||
net.modify_fixed_address(1, "192.0.2.30", "paul", "192.0.2.32", "")
|
||||
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host/@ip"), ["192.0.2.31", "192.0.2.32"])
|
||||
net.modify_fixed_address(1, "192.0.2.31", "db", "192.0.2.33", "52:54:00:00:00:31")
|
||||
net.delete_fixed_address(1, "192.0.2.32")
|
||||
self.assertEqual([dict(h.attrib) for h in self.saved().xpath("ip[2]/dhcp/host")],
|
||||
[{"mac": "52:54:00:00:00:31", "name": "db", "ip": "192.0.2.33"}])
|
||||
with self.assertRaisesRegex(OperationError, "has no fixed address 192.0.2.99"):
|
||||
net.delete_fixed_address(1, "192.0.2.99")
|
||||
|
||||
def test_a_change_keeps_what_the_page_does_not_show_and_touches_no_other_entry(self):
|
||||
net = self.network()
|
||||
conn = self.conn.networkLookupByName("lab")
|
||||
conn.destroy()
|
||||
saved = conn.XMLDesc(0).replace("<host mac='52:54:00:00:00:31' ip='192.0.2.31'/>",
|
||||
"<host mac='52:54:00:00:00:31' id='01:02:03:04' ip='192.0.2.31'><lease expiry='1' unit='hours'/></host>")
|
||||
self.conn.networkDefineXML(saved)
|
||||
net = self.network()
|
||||
# the name of another entry is refused before anything changes
|
||||
with self.assertRaisesRegex(OperationError, "The name paul has another fixed address, 192.0.2.30"):
|
||||
net.modify_fixed_address(1, "192.0.2.31", "paul", "192.0.2.35", "52:54:00:00:00:31")
|
||||
with self.assertRaisesRegex(OperationError, "52:54:00:00:00:31 has another fixed address"):
|
||||
net.modify_fixed_address(1, "192.0.2.30", "paul", "192.0.2.30", "52:54:00:00:00:31")
|
||||
net.modify_fixed_address(1, "192.0.2.31", "web", "192.0.2.35", "52:54:00:00:00:31")
|
||||
(host,) = self.saved().xpath("ip[2]/dhcp/host[@ip='192.0.2.35']")
|
||||
self.assertEqual((host.get("id"), host.xpath("string(lease/@expiry)"), host.get("name")), ("01:02:03:04", "1", "web"))
|
||||
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host/@ip"), ["192.0.2.30", "192.0.2.35"])
|
||||
|
||||
def test_an_ipv6_entry_known_by_its_duid_changes(self):
|
||||
self.conn.networkDefineXML(
|
||||
"<network><name>six</name><bridge name='virbr5'/><ip family='ipv6' address='2001:db8:5::1' prefix='64'>"
|
||||
"<dhcp><host id='00:01:00:01:aa:bb' ip='2001:db8:5::10'/></dhcp></ip></network>")
|
||||
net = wvmNetwork("localhost", "", "", 4, "six")
|
||||
net.modify_fixed_address(0, "2001:db8:5::10", "", "2001:db8:5::11", "00:01:00:01:aa:bb")
|
||||
saved = etree.fromstring(self.conn.networkLookupByName("six").XMLDesc(0))
|
||||
self.assertEqual([dict(h.attrib) for h in saved.xpath("ip/dhcp/host")], [{"id": "00:01:00:01:aa:bb", "ip": "2001:db8:5::11"}])
|
||||
|
||||
def test_an_entry_gone_meanwhile_is_not_added_anew(self):
|
||||
with self.assertRaisesRegex(OperationError, "is gone meanwhile"):
|
||||
self.network().modify_fixed_address(1, "192.0.2.99", "x", "192.0.2.40", "")
|
||||
self.assertEqual(self.saved().xpath("ip[2]/dhcp/host/@ip"), ["192.0.2.30", "192.0.2.31"])
|
||||
|
||||
def test_a_running_network_saved_with_other_addresses_is_not_changed_live(self):
|
||||
# parentIndex would name another <ip> of the running network
|
||||
net = self.network()
|
||||
net.net = MagicMock(**{"isActive.return_value": 1, "name.return_value": "lab",
|
||||
"XMLDesc.side_effect": lambda flags=0: NODE.split("<node>")[1].split("</node>")[0]
|
||||
if not flags else "<network><name>lab</name><ip address='192.0.2.1' netmask='255.255.255.0'/></network>"})
|
||||
with self.assertRaisesRegex(OperationError, "runs with other addresses than it has saved"):
|
||||
net.update(0, 0, "<host/>", 0)
|
||||
net.net.update.assert_not_called()
|
||||
|
||||
def test_the_xml_editor_expands_no_entity(self):
|
||||
# a file of the panel's host named by an external entity is not read into the check
|
||||
net = self.network()
|
||||
xml = ('<!DOCTYPE network [<!ENTITY name SYSTEM "file:///etc/hostname">]>'
|
||||
"<network><name>&name;</name></network>")
|
||||
with self.assertRaisesRegex(OperationError, "must define network lab"):
|
||||
net.edit_network(xml)
|
||||
|
||||
def test_the_xml_editor_takes_an_encoding_declaration(self):
|
||||
self.conn.networkLookupByName("lab").destroy()
|
||||
net = self.network()
|
||||
net.edit_network('<?xml version="1.0" encoding="UTF-8"?>\n' + net.config_xml().replace("virbr9", "virbr6"))
|
||||
self.assertEqual(self.saved().xpath("bridge/@name"), ["virbr6"])
|
||||
|
||||
def test_a_fixed_address_is_of_the_subnet_and_its_own(self):
|
||||
net = self.network()
|
||||
for address, why in (("198.51.100.5", "is not in 192.0.2.0/24"), ("192.0.2.1", "the host's own address"),
|
||||
("192.0.2.31", "another entry's fixed address"), ("x", "is not an IP address")):
|
||||
with self.subTest(address=address), self.assertRaisesRegex(OperationError, why):
|
||||
net.modify_fixed_address(1, "192.0.2.30", "paul", address, "")
|
||||
self.assertIs(net.modify_fixed_address(1, "192.0.2.30", "paul", "192.0.2.30", ""), False)
|
||||
|
||||
def test_the_xml_editor_defines_this_network_only(self):
|
||||
self.conn.networkLookupByName("lab").destroy() # its definition read back at once
|
||||
net = self.network()
|
||||
xml = net.config_xml()
|
||||
for other, why in ((xml.replace("<name>lab</name>", "<name>other</name>"), "must define network lab"),
|
||||
(xml.replace(net.net.UUIDString(), "11111111-2222-3333-4444-555555555555"), "keep the network's UUID"),
|
||||
("<network>", "not valid")):
|
||||
with self.subTest(why=why), self.assertRaisesRegex(OperationError, why):
|
||||
net.edit_network(other)
|
||||
net.edit_network(xml.replace("virbr9", "virbr7"))
|
||||
self.assertEqual(self.saved().xpath("bridge/@name"), ["virbr7"])
|
||||
|
||||
def test_a_network_that_does_not_start_is_undefined(self):
|
||||
net = self.wvm.networkDefineXML.return_value
|
||||
net.create.side_effect = libvirtError("network is already in use by interface virbr0")
|
||||
with self.assertRaises(libvirtError):
|
||||
self.create("192.0.2.0/24")
|
||||
net.undefine.assert_called_once_with()
|
||||
net.setAutostart.assert_not_called()
|
||||
|
||||
def test_a_stopped_network_changes_its_configuration_only(self):
|
||||
net = self.wvm.networkLookupByName.return_value
|
||||
net.XMLDesc.return_value = NET
|
||||
for active, flags in ((False, VIR_NETWORK_UPDATE_AFFECT_CONFIG),
|
||||
(True, VIR_NETWORK_UPDATE_AFFECT_CONFIG | VIR_NETWORK_UPDATE_AFFECT_LIVE)):
|
||||
with self.subTest(active=active):
|
||||
net.isActive.return_value = active
|
||||
wvmNetwork("host", "login", "pw", 1, "n1").delete_fixed_address("192.0.2.20")
|
||||
# a host with only a name is named as it is, without an empty MAC
|
||||
self.assertEqual(net.update.call_args.args[3:], ('<host name="paul" ip="192.0.2.20"/>', flags))
|
||||
gateway, mask, dhcp = network_size("192.0.2.0/24", True)
|
||||
with patch.object(libvirt.virNetwork, "create", side_effect=libvirt.libvirtError("in use by virbr0")):
|
||||
with self.assertRaises(libvirt.libvirtError):
|
||||
wvmNetworks("localhost", "", "", 4).create_network(
|
||||
"n1", "nat", True, gateway, mask, dhcp, False, None, None, None, "", False)
|
||||
self.assertNotIn("n1", self.conn.listDefinedNetworks() + self.conn.listNetworks())
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ from computes.models import Compute
|
|||
from django.contrib.auth import get_user_model
|
||||
from django.contrib.messages import get_messages
|
||||
from django.test import TestCase
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
from django.urls import reverse
|
||||
|
||||
NODE = """<node>
|
||||
|
|
@ -31,6 +32,7 @@ class NetworkInUseTests(TestCase):
|
|||
patcher = patch("vrtManager.connection.connection_manager.get_connection", return_value=self.conn)
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
without_inactive_flag(self)
|
||||
compute = Compute.objects.create(name="net-use", hostname="localhost", login="", password="", type=4)
|
||||
self.client.force_login(get_user_model().objects.create_superuser("net-use", "nu@example.com", "pw"))
|
||||
self.url = reverse("network", args=[compute.id, "lab"])
|
||||
|
|
|
|||
|
|
@ -9,12 +9,14 @@ from django.contrib.auth import get_user_model
|
|||
from django.contrib.messages import get_messages
|
||||
from django.test import TestCase
|
||||
from django.urls import reverse
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
|
||||
|
||||
class NetworkQosTests(TestCase):
|
||||
def test_a_rate_that_is_not_a_whole_number_is_refused(self):
|
||||
conn = libvirt.open("test:///default")
|
||||
self.addCleanup(conn.close)
|
||||
without_inactive_flag(self)
|
||||
compute = Compute.objects.create(name="qos-test", hostname="localhost", login="", password="", type=4)
|
||||
self.client.force_login(get_user_model().objects.create_superuser("qos", "qos@example.com", "pw"))
|
||||
url = reverse("network", args=[compute.id, "default"])
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ from django.utils.translation import gettext_lazy as _
|
|||
from libvirt import libvirtError
|
||||
from logs.audit import audit, failed
|
||||
from vrtManager.network import network_size, wvmNetwork, wvmNetworks
|
||||
from vrtManager.util import OperationError
|
||||
|
||||
from networks.forms import AddNetPool
|
||||
|
||||
|
|
@ -21,7 +22,6 @@ def networks(request, compute_id):
|
|||
"""
|
||||
|
||||
compute = get_object_or_404(Compute, pk=compute_id)
|
||||
errors = False
|
||||
|
||||
try:
|
||||
conn = wvmNetworks(
|
||||
|
|
@ -31,59 +31,28 @@ def networks(request, compute_id):
|
|||
compute.type,
|
||||
)
|
||||
networks = conn.get_networks_info()
|
||||
dhcp4 = netmask4 = gateway4 = ""
|
||||
dhcp6 = prefix6 = gateway6 = ""
|
||||
ipv4 = ipv6 = False
|
||||
|
||||
if request.method == "POST":
|
||||
if "create" in request.POST:
|
||||
form = AddNetPool(request.POST)
|
||||
if form.is_valid():
|
||||
data = form.cleaned_data
|
||||
if data["name"] in [net["name"] for net in networks]:
|
||||
msg = _("Network pool name already in use")
|
||||
messages.error(request, msg)
|
||||
failed(request, compute, f"Network {data['name']}", "add", "name already in use")
|
||||
errors = True
|
||||
if (
|
||||
data["forward"] in ["bridge", "macvtap"]
|
||||
and data["bridge_name"] == ""
|
||||
):
|
||||
messages.error(request, _("Please enter bridge/dev name"))
|
||||
errors = True
|
||||
if data["subnet"]:
|
||||
ipv4 = True
|
||||
gateway4, netmask4, dhcp4 = network_size(
|
||||
data["subnet"], data["dhcp4"]
|
||||
)
|
||||
if data["subnet6"]:
|
||||
ipv6 = True
|
||||
gateway6, prefix6, dhcp6 = network_size(
|
||||
data["subnet6"], data["dhcp6"]
|
||||
)
|
||||
if not errors:
|
||||
with audit(request, compute, f"Network {data['name']}", "add"):
|
||||
conn.create_network(
|
||||
data["name"],
|
||||
data["forward"],
|
||||
ipv4,
|
||||
gateway4,
|
||||
netmask4,
|
||||
dhcp4,
|
||||
ipv6,
|
||||
gateway6,
|
||||
prefix6,
|
||||
dhcp6,
|
||||
data["bridge_name"],
|
||||
data["openvswitch"],
|
||||
data["fixed"],
|
||||
)
|
||||
return HttpResponseRedirect(
|
||||
reverse("network", args=[compute_id, data["name"]])
|
||||
)
|
||||
else:
|
||||
for msg_err in form.errors.values():
|
||||
messages.error(request, msg_err.as_text())
|
||||
if request.method == "POST" and "create" in request.POST:
|
||||
form = AddNetPool(request.POST, networks=networks)
|
||||
if form.is_valid():
|
||||
data = form.cleaned_data
|
||||
gateway4 = netmask4 = dhcp4 = gateway6 = prefix6 = dhcp6 = ""
|
||||
if data["subnet"]:
|
||||
gateway4, netmask4, dhcp4 = network_size(data["subnet"], data["dhcp4"])
|
||||
if data["subnet6"]:
|
||||
gateway6, prefix6, dhcp6 = network_size(data["subnet6"], data["dhcp6"])
|
||||
with audit(request, compute, f"Network {data['name']}", "add"):
|
||||
conn.create_network(
|
||||
data["name"], data["forward"],
|
||||
bool(data["subnet"]), gateway4, netmask4, dhcp4,
|
||||
bool(data["subnet6"]), gateway6, prefix6, dhcp6,
|
||||
data["bridge_name"], data["openvswitch"],
|
||||
)
|
||||
return HttpResponseRedirect(reverse("network", args=[compute_id, data["name"]]))
|
||||
if form.has_error("name", "taken"):
|
||||
failed(request, compute, f"Network {form.data['name'].strip()}", "add", "name already in use")
|
||||
for msg_err in form.errors.values():
|
||||
messages.error(request, msg_err.as_text())
|
||||
conn.close()
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
|
|
@ -117,42 +86,30 @@ def network(request, compute_id, pool):
|
|||
net_mac = conn.get_network_mac()
|
||||
net_forward = conn.get_network_forward()
|
||||
qos = conn.get_qos()
|
||||
dhcp_range_start = ipv4_dhcp_range_end = dict()
|
||||
|
||||
ip_networks = conn.get_ip_networks()
|
||||
for family, ip_network in ip_networks.items():
|
||||
if family == "ipv4":
|
||||
ipv4_dhcp_range_start = conn.get_dhcp_range_start(family)
|
||||
ipv4_dhcp_range_end = conn.get_dhcp_range_end(family)
|
||||
ipv4_network = ip_network
|
||||
ipv4_fixed_address = conn.get_dhcp_host_addr(family)
|
||||
elif family == "ipv6":
|
||||
ipv6_dhcp_range_start = conn.get_dhcp_range_start(family)
|
||||
ipv6_dhcp_range_end = conn.get_dhcp_range_end(family)
|
||||
ipv6_network = ip_network
|
||||
ipv6_fixed_address = conn.get_dhcp_host_addr(family)
|
||||
else:
|
||||
raise Exception(_("Unknown Network Family"))
|
||||
|
||||
xml = conn._XMLDesc(0)
|
||||
# the page shows the first address of each family
|
||||
ipv4 = next((ip for ip in ip_networks if ip["family"] == "ipv4"), None)
|
||||
ipv6 = next((ip for ip in ip_networks if ip["family"] == "ipv6"), None)
|
||||
xml = conn.config_xml()
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
return HttpResponseRedirect(reverse("networks", args=[compute_id]))
|
||||
|
||||
if request.method == "POST":
|
||||
subject = f"Network {pool}"
|
||||
here = reverse("network", args=[compute_id, pool])
|
||||
if "start" in request.POST:
|
||||
try:
|
||||
with audit(request, compute, subject, "start"):
|
||||
conn.start()
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
if "stop" in request.POST:
|
||||
try:
|
||||
with audit(request, compute, subject, "stop"):
|
||||
conn.stop()
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
if "delete" in request.POST:
|
||||
|
|
@ -166,71 +123,62 @@ def network(request, compute_id, pool):
|
|||
try:
|
||||
with audit(request, compute, subject, "autostart on"):
|
||||
conn.set_autostart(1)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
if "unset_autostart" in request.POST:
|
||||
try:
|
||||
with audit(request, compute, subject, "autostart off"):
|
||||
conn.set_autostart(0)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
# an address of the network by its index (ip_networks), an entry by the address it had
|
||||
try:
|
||||
ip_index = int(request.POST.get("ip_index", ""))
|
||||
except ValueError:
|
||||
ip_index = -1
|
||||
if "modify_fixed_address" in request.POST:
|
||||
name = request.POST.get("name", "")
|
||||
address = request.POST.get("address", "")
|
||||
family = request.POST.get("family", "ipv4")
|
||||
|
||||
if family == "ipv4":
|
||||
mac_duid = request.POST.get("mac", "")
|
||||
if family == "ipv6":
|
||||
mac_duid = request.POST.get("id", "")
|
||||
|
||||
mac_duid = request.POST.get("mac") or request.POST.get("id", "")
|
||||
try:
|
||||
with audit(request, compute, subject, f"set fixed address {address}"):
|
||||
changed = conn.modify_fixed_address(name, address, mac_duid, family)
|
||||
with audit(request, compute, subject, f"set fixed address {address}") as entry:
|
||||
changed = conn.modify_fixed_address(ip_index, request.POST.get("original", ""),
|
||||
request.POST.get("name", ""), address, mac_duid)
|
||||
entry.skip = changed is False # nothing was done
|
||||
if changed is False:
|
||||
messages.info(request, _("The fixed address is unchanged"))
|
||||
else:
|
||||
messages.success(
|
||||
request,
|
||||
_("Fixed address operation completed for %(family)s")
|
||||
% {"family": family.upper()},
|
||||
)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
except ValueError as val_err:
|
||||
messages.error(request, val_err)
|
||||
messages.success(request, _("The fixed address %(address)s is set") % {"address": address})
|
||||
except (libvirtError, OperationError) as err:
|
||||
messages.error(request, err)
|
||||
return HttpResponseRedirect(here)
|
||||
if "delete_fixed_address" in request.POST:
|
||||
ip = request.POST.get("address", "")
|
||||
family = request.POST.get("family", "ipv4")
|
||||
with audit(request, compute, subject, f"delete fixed address {ip}"):
|
||||
conn.delete_fixed_address(ip, family)
|
||||
messages.success(
|
||||
request,
|
||||
_("%(family)s Fixed Address is Deleted.") % {"family": family.upper()},
|
||||
)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
if "modify_dhcp_range" in request.POST:
|
||||
range_start = request.POST.get("range_start", "")
|
||||
range_end = request.POST.get("range_end", "")
|
||||
family = request.POST.get("family", "ipv4")
|
||||
address = request.POST.get("original", "")
|
||||
try:
|
||||
with audit(request, compute, subject, f"set DHCP range {family.upper()}"):
|
||||
conn.modify_dhcp_range(range_start, range_end, family)
|
||||
messages.success(
|
||||
request,
|
||||
_("%(family)s DHCP Range is Changed.") % {"family": family.upper()},
|
||||
)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
except libvirtError as lib_err:
|
||||
messages.error(request, lib_err)
|
||||
with audit(request, compute, subject, f"delete fixed address {address}"):
|
||||
conn.delete_fixed_address(ip_index, address)
|
||||
messages.success(request, _("The fixed address %(address)s is deleted") % {"address": address})
|
||||
except (libvirtError, OperationError) as err:
|
||||
messages.error(request, err)
|
||||
return HttpResponseRedirect(here)
|
||||
if "modify_dhcp_range" in request.POST:
|
||||
try:
|
||||
with audit(request, compute, subject, "set DHCP range"):
|
||||
conn.modify_dhcp_range(ip_index, request.POST.get("range_start", ""), request.POST.get("range_end", ""))
|
||||
messages.success(request, _("The DHCP range is changed"))
|
||||
except (libvirtError, OperationError) as err:
|
||||
messages.error(request, err)
|
||||
return HttpResponseRedirect(here)
|
||||
if "edit_network" in request.POST:
|
||||
edit_xml = request.POST.get("edit_xml", "")
|
||||
if edit_xml:
|
||||
with audit(request, compute, subject, "change XML"):
|
||||
conn.edit_network(edit_xml)
|
||||
try:
|
||||
with audit(request, compute, subject, "change XML"):
|
||||
conn.edit_network(edit_xml)
|
||||
except (libvirtError, OperationError) as err:
|
||||
messages.error(request, err)
|
||||
return HttpResponseRedirect(here)
|
||||
if conn.is_active():
|
||||
messages.success(
|
||||
request,
|
||||
|
|
@ -241,7 +189,7 @@ def network(request, compute_id, pool):
|
|||
)
|
||||
else:
|
||||
messages.success(request, _("Network XML is changed."))
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
if "set_qos" in request.POST:
|
||||
qos_dir = request.POST.get("qos_direction", "")
|
||||
average = request.POST.get("qos_average") or 0
|
||||
|
|
@ -266,15 +214,15 @@ def network(request, compute_id, pool):
|
|||
)
|
||||
except (libvirtError, ValueError) as err:
|
||||
messages.error(request, err)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
if "unset_qos" in request.POST:
|
||||
qos_dir = request.POST.get("qos_direction", "")
|
||||
try:
|
||||
with audit(request, compute, subject, f"unset QoS {qos_dir}"):
|
||||
conn.unset_qos(qos_dir)
|
||||
except ValueError as err:
|
||||
except (libvirtError, ValueError) as err:
|
||||
messages.error(request, err)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
|
||||
if conn.is_active():
|
||||
messages.success(
|
||||
|
|
@ -290,7 +238,7 @@ def network(request, compute_id, pool):
|
|||
request,
|
||||
_("%(qos_dir)s QoS is deleted") % {"qos_dir": qos_dir.capitalize()},
|
||||
)
|
||||
return HttpResponseRedirect(request.get_full_path())
|
||||
return HttpResponseRedirect(here)
|
||||
conn.close()
|
||||
|
||||
return render(request, "network.html", locals())
|
||||
|
|
|
|||
|
|
@ -1,13 +1,18 @@
|
|||
import copy
|
||||
import ipaddress
|
||||
from functools import cached_property
|
||||
|
||||
from libvirt import (
|
||||
VIR_NETWORK_SECTION_IP_DHCP_HOST,
|
||||
VIR_NETWORK_UPDATE_AFFECT_CONFIG,
|
||||
VIR_NETWORK_UPDATE_AFFECT_LIVE,
|
||||
VIR_NETWORK_UPDATE_COMMAND_ADD_LAST,
|
||||
VIR_NETWORK_UPDATE_COMMAND_DELETE,
|
||||
VIR_NETWORK_UPDATE_COMMAND_MODIFY, libvirtError)
|
||||
VIR_NETWORK_XML_INACTIVE,
|
||||
libvirtError,
|
||||
)
|
||||
from lxml import etree
|
||||
from vrtManager import util
|
||||
import ipaddress
|
||||
|
||||
from vrtManager.connection import wvmConnect
|
||||
|
||||
|
|
@ -28,26 +33,59 @@ def network_size(subnet, dhcp=None):
|
|||
return (gateway, mask, dhcp_pool) if dhcp else (gateway, mask, None)
|
||||
|
||||
|
||||
def default_prefix(address):
|
||||
"""The prefix libvirt gives an address written without one: IPv6 /64, IPv4
|
||||
its class's (A /8, B /16, C /24)."""
|
||||
address = ipaddress.ip_address(address)
|
||||
if address.version == 6:
|
||||
return 64
|
||||
first = int(address) >> 24
|
||||
return 8 if first < 128 else 16 if first < 192 else 24
|
||||
|
||||
|
||||
def ip_networks(tree):
|
||||
"""Each <ip> of a network's XML, in order: its index is libvirt's parentIndex
|
||||
for changes to it. Its family, address (the host's on the network), subnet
|
||||
(by its netmask or prefix, or libvirt's default one), whether it serves
|
||||
DHCP (a <dhcp>, with or without a range: fixed addresses alone are DHCP
|
||||
too), its first range and its fixed addresses."""
|
||||
ips = []
|
||||
for index, ip in enumerate(tree.findall("ip")):
|
||||
address = ip.get("address")
|
||||
mask = ip.get("prefix") or ip.get("netmask") or (default_prefix(address) if address else None)
|
||||
dhcp = ip.find("dhcp")
|
||||
first = dhcp.find("range") if dhcp is not None else None
|
||||
ips.append({
|
||||
"index": index,
|
||||
"family": ip.get("family", "ipv4"),
|
||||
"address": address,
|
||||
"subnet": ipaddress.ip_network(f"{address}/{mask}", strict=False) if mask else None,
|
||||
"dhcp": dhcp is not None,
|
||||
"range": (first.get("start"), first.get("end")) if first is not None else None,
|
||||
"hosts": [{"ip": host.get("ip"), "mac": host.get("mac"), "id": host.get("id"), "name": host.get("name", "")}
|
||||
for host in (dhcp.findall("host") if dhcp is not None else [])],
|
||||
})
|
||||
return ips
|
||||
|
||||
|
||||
class wvmNetworks(wvmConnect):
|
||||
def get_networks_info(self):
|
||||
get_networks = self.get_networks()
|
||||
"""Each network's state, autostart, device (its bridge, or a macvtap
|
||||
network's interface), forward mode and addresses (ip_networks): its
|
||||
XML is read once."""
|
||||
networks = []
|
||||
for network in get_networks:
|
||||
net = self.get_network(network)
|
||||
net_status = net.isActive()
|
||||
try:
|
||||
net_bridge = net.bridgeName()
|
||||
except libvirtError:
|
||||
net_bridge = util.get_xml_path(net.XMLDesc(0), "/network/forward/interface/@dev")
|
||||
|
||||
net_forward = util.get_xml_path(net.XMLDesc(0), "/network/forward/@mode")
|
||||
for name in self.get_networks():
|
||||
net = self.get_network(name)
|
||||
tree = etree.fromstring(net.XMLDesc(0))
|
||||
forward = tree.find("forward")
|
||||
networks.append({
|
||||
"name": network,
|
||||
"status": net_status,
|
||||
"device": net_bridge,
|
||||
"forward": net_forward
|
||||
})
|
||||
|
||||
"name": name,
|
||||
"status": net.isActive(),
|
||||
"autostart": net.autostart(),
|
||||
"device": tree.xpath("string(bridge/@name)") or tree.xpath("string(forward/interface/@dev)"),
|
||||
"forward": forward.get("mode") if forward is not None else None,
|
||||
"ips": ip_networks(tree),
|
||||
})
|
||||
return networks
|
||||
|
||||
def create_network(
|
||||
|
|
@ -64,7 +102,6 @@ class wvmNetworks(wvmConnect):
|
|||
dhcp6,
|
||||
bridge,
|
||||
openvswitch,
|
||||
fixed=False,
|
||||
):
|
||||
esc_name = util.xml_escape(str(name))
|
||||
esc_forward = util.xml_escape(str(forward)) if forward else ""
|
||||
|
|
@ -99,12 +136,8 @@ class wvmNetworks(wvmConnect):
|
|||
dhcp4_0 = util.xml_escape(str(dhcp4[0]))
|
||||
dhcp4_1 = util.xml_escape(str(dhcp4[1]))
|
||||
xml += f"""<dhcp>
|
||||
<range start='{dhcp4_0}' end='{dhcp4_1}' />"""
|
||||
if fixed:
|
||||
first, last = (int(ipaddress.IPv4Address(ip)) for ip in dhcp4)
|
||||
for ip in range(first, last + 1):
|
||||
xml += f"""<host mac='{util.randomMAC()}' ip='{ipaddress.IPv4Address(ip)}' />"""
|
||||
xml += """</dhcp>"""
|
||||
<range start='{dhcp4_0}' end='{dhcp4_1}' />
|
||||
</dhcp>"""
|
||||
xml += """</ip>"""
|
||||
if ipv6:
|
||||
xml += f"""<ip family='ipv6' address='{esc_gateway6}' prefix='{esc_prefix6}'>"""
|
||||
|
|
@ -126,18 +159,32 @@ class wvmNetworks(wvmConnect):
|
|||
|
||||
|
||||
class wvmNetwork(wvmConnect):
|
||||
"""A network of the host. A page reads its running definition once (tree);
|
||||
a change starts from its saved definition read anew (config), so that two
|
||||
changes in a row do not undo each other, and forgets what the page read."""
|
||||
|
||||
def __init__(self, host, login, passwd, conn, net):
|
||||
wvmConnect.__init__(self, host, login, passwd, conn)
|
||||
self.leases = None
|
||||
self.net = self.get_network(net)
|
||||
self.parent_count = len(self.get_ip_networks())
|
||||
|
||||
@cached_property
|
||||
def tree(self):
|
||||
return etree.fromstring(self.net.XMLDesc(0))
|
||||
|
||||
def config(self):
|
||||
return etree.fromstring(self.net.XMLDesc(VIR_NETWORK_XML_INACTIVE))
|
||||
|
||||
def config_xml(self):
|
||||
"""The saved definition, the one the XML editor changes."""
|
||||
return self.net.XMLDesc(VIR_NETWORK_XML_INACTIVE)
|
||||
|
||||
def _define(self, tree):
|
||||
self.wvm.networkDefineXML(etree.tostring(tree).decode())
|
||||
self.__dict__.pop("tree", None)
|
||||
|
||||
def get_name(self):
|
||||
return self.net.name()
|
||||
|
||||
def _XMLDesc(self, flags):
|
||||
return self.net.XMLDesc(flags)
|
||||
|
||||
def get_autostart(self):
|
||||
return self.net.autostart()
|
||||
|
||||
|
|
@ -147,14 +194,9 @@ class wvmNetwork(wvmConnect):
|
|||
def is_active(self):
|
||||
return self.net.isActive()
|
||||
|
||||
def get_uuid(self):
|
||||
return self.net.UUIDString()
|
||||
|
||||
def get_bridge_device(self):
|
||||
try:
|
||||
return self.net.bridgeName()
|
||||
except Exception:
|
||||
return util.get_xml_path(self._XMLDesc(0), "/network/forward/interface/@dev")
|
||||
"""Its bridge, or a macvtap network's interface."""
|
||||
return self.tree.xpath("string(bridge/@name)") or self.tree.xpath("string(forward/interface/@dev)")
|
||||
|
||||
def start(self):
|
||||
self.net.create()
|
||||
|
|
@ -183,231 +225,172 @@ class wvmNetwork(wvmConnect):
|
|||
def update(self, command, section, xml, parentIndex):
|
||||
"""Changes the network's configuration and, while it runs, the running
|
||||
network too (libvirt refuses a live change on a stopped one)."""
|
||||
flags = VIR_NETWORK_UPDATE_AFFECT_CONFIG | (VIR_NETWORK_UPDATE_AFFECT_LIVE if self.is_active() else 0)
|
||||
return self.net.update(command, section, parentIndex, xml, flags)
|
||||
active = self.is_active()
|
||||
if active and self._addresses(self.tree) != self._addresses(self.config()):
|
||||
# parentIndex names the same <ip> in both only when they list the same addresses
|
||||
raise util.OperationError(f"Network {self.net.name()} runs with other addresses than it has saved; "
|
||||
"stop and start it first")
|
||||
flags = VIR_NETWORK_UPDATE_AFFECT_CONFIG | (VIR_NETWORK_UPDATE_AFFECT_LIVE if active else 0)
|
||||
self.net.update(command, section, parentIndex, xml, flags)
|
||||
self.__dict__.pop("tree", None)
|
||||
|
||||
@staticmethod
|
||||
def _addresses(tree):
|
||||
return [(ip.get("family", "ipv4"), ip.get("address")) for ip in tree.findall("ip")]
|
||||
|
||||
def get_ip_networks(self):
|
||||
ip_networks = {}
|
||||
xml = self._XMLDesc(0)
|
||||
if util.get_xml_path(xml, "/network/ip") is None:
|
||||
return ip_networks
|
||||
tree = etree.fromstring(xml)
|
||||
ips = tree.findall(".ip")
|
||||
for ip in ips:
|
||||
address_str = ip.get("address")
|
||||
netmask_str = ip.get("netmask")
|
||||
prefix = ip.get("prefix")
|
||||
family = ip.get("family", "ipv4")
|
||||
mask = prefix if prefix is not None else netmask_str
|
||||
if address_str and mask:
|
||||
ret = ipaddress.ip_network(f"{address_str}/{mask}", strict=False)
|
||||
elif address_str:
|
||||
ret = ipaddress.ip_address(address_str)
|
||||
else:
|
||||
continue
|
||||
ip_networks[family] = ret
|
||||
return ip_networks
|
||||
return ip_networks(self.tree)
|
||||
|
||||
def get_network_mac(self):
|
||||
xml = self._XMLDesc(0)
|
||||
return util.get_xml_path(xml, "/network/mac/@address")
|
||||
return self.tree.xpath("string(mac/@address)")
|
||||
|
||||
def get_network_forward(self):
|
||||
xml = self._XMLDesc(0)
|
||||
fw = util.get_xml_path(xml, "/network/forward/@mode")
|
||||
forward_dev = util.get_xml_path(xml, "/network/forward/@dev")
|
||||
return [fw, forward_dev]
|
||||
"""Its forward mode (None: isolated) and the device it forwards through."""
|
||||
forward = self.tree.find("forward")
|
||||
return [forward.get("mode"), forward.get("dev")] if forward is not None else [None, None]
|
||||
|
||||
def get_dhcp_range(self, family="ipv4"):
|
||||
xml = self._XMLDesc(0)
|
||||
if family == "ipv4":
|
||||
dhcpstart = util.get_xml_path(xml, "/network/ip[not(@family='ipv6')]/dhcp/range[1]/@start")
|
||||
dhcpend = util.get_xml_path(xml, "/network/ip[not(@family='ipv6')]/dhcp/range[1]/@end")
|
||||
if family == "ipv6":
|
||||
dhcpstart = util.get_xml_path(xml, "/network/ip[@family='ipv6']/dhcp/range[1]/@start")
|
||||
dhcpend = util.get_xml_path(xml, "/network/ip[@family='ipv6']/dhcp/range[1]/@end")
|
||||
def _ip(self, index):
|
||||
"""The saved <ip> of that index, and what ip_networks tells of it."""
|
||||
tree = self.config()
|
||||
ips = tree.findall("ip")
|
||||
if not 0 <= index < len(ips):
|
||||
raise util.OperationError(f"Network {self.net.name()} has no such address")
|
||||
return tree, ips[index], ip_networks(tree)[index]
|
||||
|
||||
return None if not dhcpstart or not dhcpend else [ipaddress.ip_address(dhcpstart), ipaddress.ip_address(dhcpend)]
|
||||
def _checked_address(self, ip, address, what):
|
||||
"""address as an address of the <ip> ip (ip_networks): of its family and
|
||||
subnet, and not the host's own."""
|
||||
try:
|
||||
address = ipaddress.ip_address(address)
|
||||
except ValueError:
|
||||
raise util.OperationError(f"{address} is not an IP address") from None
|
||||
if ip["subnet"] is None or address not in ip["subnet"]:
|
||||
raise util.OperationError(f"The {what} {address} is not in {ip['subnet'] or 'the network'}")
|
||||
if address == ipaddress.ip_address(ip["address"]):
|
||||
raise util.OperationError(f"{address} is the host's own address on the network")
|
||||
return address
|
||||
|
||||
def get_dhcp_range_start(self, family="ipv4"):
|
||||
dhcp = self.get_dhcp_range(family)
|
||||
return dhcp[0] if dhcp else None
|
||||
|
||||
def get_dhcp_range_end(self, family="ipv4"):
|
||||
dhcp = self.get_dhcp_range(family)
|
||||
return dhcp[1] if dhcp else None
|
||||
|
||||
def can_pxe(self):
|
||||
xml = self._XMLDesc(0)
|
||||
forward = self.get_network_forward()[0]
|
||||
if forward and forward != "nat":
|
||||
return True
|
||||
return bool(util.get_xml_path(xml, "/network/ip/dhcp/bootp/@file"))
|
||||
|
||||
def get_dhcp_host_addr(self, family="ipv4"):
|
||||
result = []
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
for ipdhcp in tree.findall("./ip"):
|
||||
if family == "ipv4":
|
||||
if ipdhcp.get("family") is not None:
|
||||
continue
|
||||
hosts = ipdhcp.findall("./dhcp/host")
|
||||
for host in hosts:
|
||||
host_ip = host.get("ip")
|
||||
mac = host.get("mac")
|
||||
name = host.get("name", "")
|
||||
result.append({"ip": host_ip, "mac": mac, "name": name})
|
||||
return result
|
||||
if family == "ipv6":
|
||||
hosts = tree.xpath("./ip[@family='ipv6']/dhcp/host")
|
||||
for host in hosts:
|
||||
host_ip = host.get("ip")
|
||||
host_id = host.get("id")
|
||||
name = host.get("name", "")
|
||||
result.append({"ip": host_ip, "id": host_id, "name": name})
|
||||
return result
|
||||
|
||||
def modify_dhcp_range(self, range_start, range_end, family="ipv4"):
|
||||
def modify_dhcp_range(self, index, range_start, range_end):
|
||||
"""Refused while the network runs: the running network would keep the old range."""
|
||||
if self.is_active():
|
||||
raise util.OperationError(f"Stop network {self.net.name()} to change its DHCP range")
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
ip = {"ipv4": "ip[not(@family='ipv6')]", "ipv6": "ip[@family='ipv6']"}.get(family)
|
||||
dhcp_range = tree.xpath(f"{ip}/dhcp/range") if ip else []
|
||||
if not dhcp_range:
|
||||
raise util.OperationError(f"Network {self.net.name()} has no {family} DHCP range")
|
||||
dhcp_range[0].set("start", range_start)
|
||||
dhcp_range[0].set("end", range_end)
|
||||
self.wvm.networkDefineXML(etree.tostring(tree).decode())
|
||||
tree, ip, info = self._ip(index)
|
||||
dhcp_range = ip.find("dhcp/range")
|
||||
if dhcp_range is None:
|
||||
raise util.OperationError(f"This address of network {self.net.name()} has no DHCP range")
|
||||
start = self._checked_address(info, range_start, "range start")
|
||||
end = self._checked_address(info, range_end, "range end")
|
||||
if start > end:
|
||||
raise util.OperationError(f"The range starts at {start}, after its end {end}")
|
||||
if start <= ipaddress.ip_address(info["address"]) <= end:
|
||||
raise util.OperationError(f"The range takes in {info['address']}, the host's own address")
|
||||
dhcp_range.set("start", str(start))
|
||||
dhcp_range.set("end", str(end))
|
||||
self._define(tree)
|
||||
|
||||
def delete_fixed_address(self, ip, family="ipv4"):
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
if family == "ipv4":
|
||||
hosts = tree.xpath("/network/ip[not(@family='ipv6')]/dhcp/host")
|
||||
parent_index = self.parent_count - 2
|
||||
if family == "ipv6":
|
||||
hosts = tree.xpath("/network/ip[@family='ipv6']/dhcp/host")
|
||||
parent_index = self.parent_count - 1
|
||||
for h in hosts:
|
||||
if h.get("ip") == ip:
|
||||
# the host as it is: a host may have only a name and an address
|
||||
new_xml = etree.tostring(h, with_tail=False).decode()
|
||||
self.update(
|
||||
VIR_NETWORK_UPDATE_COMMAND_DELETE,
|
||||
VIR_NETWORK_SECTION_IP_DHCP_HOST,
|
||||
new_xml,
|
||||
parent_index,
|
||||
)
|
||||
break
|
||||
|
||||
def modify_fixed_address(self, name, address, mac_duid, family="ipv4"):
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
name_esc = util.xml_escape(name) if name else ""
|
||||
name_attr = f' name="{name_esc}"' if name else ""
|
||||
mac_esc = util.xml_escape(mac_duid)
|
||||
ip_addr = ipaddress.ip_address(address)
|
||||
if family == "ipv4":
|
||||
new_xml = f'<host mac="{mac_esc}"{name_attr} ip="{ip_addr}"/>'
|
||||
hosts = tree.xpath("./ip[not(@family='ipv6')]/dhcp/host")
|
||||
compare_var = "mac"
|
||||
parent_index = self.parent_count - 2
|
||||
if family == "ipv6":
|
||||
new_xml = f'<host id="{mac_esc}"{name_attr} ip="{ip_addr}"/>'
|
||||
hosts = tree.xpath("./ip[@family='ipv6']/dhcp/host")
|
||||
compare_var = "id"
|
||||
parent_index = self.parent_count - 1
|
||||
new_host_xml = etree.fromstring(new_xml)
|
||||
host = next((h for h in hosts if h.get(compare_var) == mac_duid), None)
|
||||
def delete_fixed_address(self, index, address):
|
||||
_tree, ip, _info = self._ip(index)
|
||||
host = next((h for h in ip.findall("dhcp/host") if h.get("ip") == address), None)
|
||||
if host is None:
|
||||
self.update(
|
||||
VIR_NETWORK_UPDATE_COMMAND_ADD_LAST,
|
||||
VIR_NETWORK_SECTION_IP_DHCP_HOST,
|
||||
new_xml,
|
||||
parent_index,
|
||||
)
|
||||
else:
|
||||
# change the host
|
||||
if host.get("name") == new_host_xml.get("name") and host.get("ip") == new_host_xml.get("ip"):
|
||||
return False
|
||||
else:
|
||||
self.update(
|
||||
VIR_NETWORK_UPDATE_COMMAND_MODIFY,
|
||||
VIR_NETWORK_SECTION_IP_DHCP_HOST,
|
||||
new_xml,
|
||||
parent_index,
|
||||
)
|
||||
raise util.OperationError(f"Network {self.net.name()} has no fixed address {address}")
|
||||
# the host as it is: a host may have only a name and an address
|
||||
self.update(VIR_NETWORK_UPDATE_COMMAND_DELETE, VIR_NETWORK_SECTION_IP_DHCP_HOST,
|
||||
etree.tostring(host, with_tail=False).decode(), index)
|
||||
|
||||
def modify_fixed_address(self, index, original, name, address, mac_duid):
|
||||
"""Adds a fixed address, or changes the one that had the address
|
||||
original, keeping what the page does not show of it (a client id, a
|
||||
lease time). The address must be of the subnet, not the host's, and
|
||||
neither it, the MAC (IPv4) or DUID (IPv6) nor the name another entry's.
|
||||
A change deletes the entry and adds it anew, put back if that fails:
|
||||
libvirt's own change finds an entry by any of its MAC, address or name,
|
||||
another entry's too, and an IPv6 one never by its DUID. Returns False
|
||||
when nothing changes."""
|
||||
_tree, ip, info = self._ip(index)
|
||||
address = self._checked_address(info, address, "fixed address")
|
||||
key = "mac" if info["family"] == "ipv4" else "id"
|
||||
hosts = ip.findall("dhcp/host")
|
||||
old = None
|
||||
if original:
|
||||
old = next((h for h in hosts if h.get("ip") == original), None)
|
||||
if old is None:
|
||||
raise util.OperationError(f"The fixed address {original} is gone meanwhile; reload the page")
|
||||
for other in hosts:
|
||||
if other is old:
|
||||
continue
|
||||
if other.get("ip") == str(address):
|
||||
raise util.OperationError(f"{address} is another entry's fixed address")
|
||||
if mac_duid and other.get(key, "").lower() == mac_duid.lower():
|
||||
raise util.OperationError(f"{mac_duid} has another fixed address, {other.get('ip')}")
|
||||
if name and other.get("name") == name:
|
||||
raise util.OperationError(f"The name {name} has another fixed address, {other.get('ip')}")
|
||||
new = copy.deepcopy(old) if old is not None else etree.Element("host")
|
||||
new.tail = None
|
||||
for attribute, value in ((key, mac_duid), ("name", name), ("ip", str(address))):
|
||||
if value:
|
||||
new.set(attribute, value)
|
||||
elif attribute in new.attrib:
|
||||
del new.attrib[attribute]
|
||||
new_xml = etree.tostring(new).decode()
|
||||
if old is None:
|
||||
self.update(VIR_NETWORK_UPDATE_COMMAND_ADD_LAST, VIR_NETWORK_SECTION_IP_DHCP_HOST, new_xml, index)
|
||||
return True
|
||||
old_xml = etree.tostring(old, with_tail=False).decode()
|
||||
if new_xml == old_xml:
|
||||
return False
|
||||
self.update(VIR_NETWORK_UPDATE_COMMAND_DELETE, VIR_NETWORK_SECTION_IP_DHCP_HOST, old_xml, index)
|
||||
try:
|
||||
self.update(VIR_NETWORK_UPDATE_COMMAND_ADD_LAST, VIR_NETWORK_SECTION_IP_DHCP_HOST, new_xml, index)
|
||||
except libvirtError:
|
||||
self.update(VIR_NETWORK_UPDATE_COMMAND_ADD_LAST, VIR_NETWORK_SECTION_IP_DHCP_HOST, old_xml, index)
|
||||
raise
|
||||
return True
|
||||
|
||||
def get_qos(self):
|
||||
qos_values = {}
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
qos = tree.xpath("/network/bandwidth")
|
||||
if qos:
|
||||
qos = qos[0]
|
||||
|
||||
in_qos = qos.find("inbound")
|
||||
if in_qos is not None:
|
||||
in_av = in_qos.get("average")
|
||||
in_peak = in_qos.get("peak")
|
||||
in_burst = in_qos.get("burst")
|
||||
qos_values["inbound"] = {"average": in_av, "peak": in_peak, "burst": in_burst}
|
||||
|
||||
out_qos = qos.find("outbound")
|
||||
if out_qos is not None:
|
||||
out_av = out_qos.get("average")
|
||||
out_peak = out_qos.get("peak")
|
||||
out_burst = out_qos.get("burst")
|
||||
qos_values["outbound"] = {"average": out_av, "peak": out_peak, "burst": out_burst}
|
||||
for direction in ("inbound", "outbound"):
|
||||
limit = self.tree.find(f"bandwidth/{direction}")
|
||||
if limit is not None:
|
||||
qos_values[direction] = {"average": limit.get("average"), "peak": limit.get("peak"),
|
||||
"burst": limit.get("burst")}
|
||||
return qos_values
|
||||
|
||||
def set_qos(self, direction, average, peak, burst):
|
||||
if direction not in ("inbound", "outbound"):
|
||||
raise ValueError("Direction must be inbound or outbound")
|
||||
|
||||
try:
|
||||
average, peak, burst = int(average), int(peak), int(burst)
|
||||
except ValueError:
|
||||
raise ValueError("QoS rates must be whole numbers")
|
||||
|
||||
xml = f"<{direction} average='{average}' peak='{peak}' burst='{burst}'/>"
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
|
||||
band = tree.xpath("/network/bandwidth")
|
||||
if len(band) == 0:
|
||||
xml = f"<bandwidth>{xml}</bandwidth>"
|
||||
tree.append(etree.fromstring(xml))
|
||||
else:
|
||||
direct = band[0].find(direction)
|
||||
if direct is not None:
|
||||
parent = direct.getparent()
|
||||
parent.remove(direct)
|
||||
parent.append(etree.fromstring(xml))
|
||||
else:
|
||||
band[0].append(etree.fromstring(xml))
|
||||
new_xml = etree.tostring(tree).decode()
|
||||
self.wvm.networkDefineXML(new_xml)
|
||||
tree = self.config()
|
||||
band = tree.find("bandwidth")
|
||||
if band is None:
|
||||
band = etree.SubElement(tree, "bandwidth")
|
||||
for old in band.findall(direction):
|
||||
band.remove(old)
|
||||
etree.SubElement(band, direction, average=str(average), peak=str(peak), burst=str(burst))
|
||||
self._define(tree)
|
||||
|
||||
def unset_qos(self, direction):
|
||||
# direction goes into the XPath below
|
||||
if direction not in ("inbound", "outbound"):
|
||||
raise ValueError("Direction must be inbound or outbound")
|
||||
tree = etree.fromstring(self._XMLDesc(0))
|
||||
for direct in tree.xpath(f"/network/bandwidth/{direction}"):
|
||||
parent = direct.getparent()
|
||||
parent.remove(direct)
|
||||
|
||||
self.wvm.networkDefineXML(etree.tostring(tree).decode())
|
||||
tree = self.config()
|
||||
for limit in tree.findall(f"bandwidth/{direction}"):
|
||||
limit.getparent().remove(limit)
|
||||
self._define(tree)
|
||||
|
||||
def edit_network(self, new_xml):
|
||||
self.wvm.networkDefineXML(new_xml)
|
||||
|
||||
def refresh_dhcp_leases(self):
|
||||
"""Defines this network anew from new_xml: of the same name and, if it
|
||||
names one, the same UUID, not another network."""
|
||||
# read for its name and UUID only, its entities not expanded: libvirt gets the text itself
|
||||
parser = etree.XMLParser(resolve_entities=False, no_network=True)
|
||||
try:
|
||||
self.leases = self.net.DHCPLeases()
|
||||
except Exception as e:
|
||||
self.leases = []
|
||||
raise util.OperationError(f"Error getting {self} DHCP leases: {e}") from e
|
||||
|
||||
def get_dhcp_leases(self):
|
||||
if self.leases is None:
|
||||
self.refresh_dhcp_leases()
|
||||
return self.leases
|
||||
tree = etree.fromstring(new_xml.encode(), parser) # bytes: the XML may declare its encoding
|
||||
except etree.XMLSyntaxError as err:
|
||||
raise util.OperationError(f"The XML is not valid: {err}") from None
|
||||
if tree.tag != "network" or tree.findtext("name") != self.net.name():
|
||||
raise util.OperationError(f"The XML must define network {self.net.name()}")
|
||||
if tree.findtext("uuid") not in (None, self.net.UUIDString()):
|
||||
raise util.OperationError("The XML must keep the network's UUID")
|
||||
self.wvm.networkDefineXML(new_xml)
|
||||
self.__dict__.pop("tree", None)
|
||||
|
|
|
|||
|
|
@ -1,36 +0,0 @@
|
|||
"""refresh_dhcp_leases must raise a real exception (handled as a libvirt error),
|
||||
not a bare string (which Python turns into TypeError, masking the cause)."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
if not settings.configured:
|
||||
settings.configure(MAC_OUI="52:54:10")
|
||||
|
||||
from vrtManager import util
|
||||
from vrtManager.network import wvmNetwork
|
||||
|
||||
|
||||
def network_with_leases(side_effect):
|
||||
net = wvmNetwork.__new__(wvmNetwork)
|
||||
net.leases = None
|
||||
net.net = Mock()
|
||||
net.net.DHCPLeases.side_effect = side_effect
|
||||
return net
|
||||
|
||||
|
||||
class RefreshDhcpLeasesTestCase(unittest.TestCase):
|
||||
def test_a_lease_error_raises_an_operation_error(self):
|
||||
net = network_with_leases(Exception("no DHCP on this network"))
|
||||
with self.assertRaises(util.OperationError):
|
||||
net.refresh_dhcp_leases()
|
||||
|
||||
def test_the_error_keeps_the_cause_and_clears_leases(self):
|
||||
cause = Exception("boom")
|
||||
net = network_with_leases(cause)
|
||||
with self.assertRaises(util.OperationError) as caught:
|
||||
net.refresh_dhcp_leases()
|
||||
self.assertIs(caught.exception.__cause__, cause)
|
||||
self.assertEqual(net.leases, [])
|
||||
|
|
@ -12,7 +12,8 @@ except ImportError:
|
|||
sys.modules["django"] = django_mock
|
||||
sys.modules["django.conf"] = django_mock.conf
|
||||
|
||||
from vrtManager.network import network_size, wvmNetwork
|
||||
from lxml import etree
|
||||
from vrtManager.network import ip_networks, network_size
|
||||
|
||||
|
||||
class TestNetworkSize(unittest.TestCase):
|
||||
|
|
@ -75,23 +76,8 @@ class TestNetworkSize(unittest.TestCase):
|
|||
network_size("invalid.subnet/99")
|
||||
|
||||
|
||||
class DummyNetwork(wvmNetwork):
|
||||
"""Subclass of wvmNetwork with mock XML for isolated IP method testing."""
|
||||
|
||||
def __init__(self, xml_content):
|
||||
self._xml = xml_content
|
||||
self.parent_count = 2
|
||||
self.updates = []
|
||||
|
||||
def _XMLDesc(self, flags):
|
||||
return self._xml
|
||||
|
||||
def update(self, command, section, xml, parent_index, flags):
|
||||
self.updates.append((command, section, xml, parent_index, flags))
|
||||
|
||||
|
||||
class TestWvmNetworkIPOperations(unittest.TestCase):
|
||||
"""Unit tests for IP parsing, DHCP ranges, and host addresses in wvmNetwork."""
|
||||
class TestIpNetworks(unittest.TestCase):
|
||||
"""A network's addresses (ip_networks): subnet, DHCP range and fixed addresses of each family."""
|
||||
|
||||
DUAL_STACK_XML = """<network>
|
||||
<name>default</name>
|
||||
|
|
@ -109,60 +95,15 @@ class TestWvmNetworkIPOperations(unittest.TestCase):
|
|||
</ip>
|
||||
</network>"""
|
||||
|
||||
NO_IP_XML = """<network>
|
||||
<name>isolated</name>
|
||||
<bridge name="virbr1"/>
|
||||
</network>"""
|
||||
def test_dual_stack(self):
|
||||
v4, v6 = ip_networks(etree.fromstring(self.DUAL_STACK_XML))
|
||||
self.assertEqual((str(v4["subnet"]), v4["range"]), ("192.168.100.0/24", ("192.168.100.2", "192.168.100.254")))
|
||||
self.assertEqual(v4["hosts"], [{"ip": "192.168.100.50", "mac": "52:54:00:12:34:56", "id": None, "name": "vm1"}])
|
||||
self.assertEqual((str(v6["subnet"]), v6["range"]), ("2001:db8:ca2:2::/64", ("2001:db8:ca2:2::100", "2001:db8:ca2:2::1ff")))
|
||||
self.assertEqual(v6["hosts"][0]["id"], "0:1:0:1")
|
||||
|
||||
def test_get_ip_networks_dual_stack(self):
|
||||
net = DummyNetwork(self.DUAL_STACK_XML)
|
||||
ip_networks = net.get_ip_networks()
|
||||
self.assertIn("ipv4", ip_networks)
|
||||
self.assertIn("ipv6", ip_networks)
|
||||
self.assertEqual(str(ip_networks["ipv4"]), "192.168.100.0/24")
|
||||
self.assertEqual(str(ip_networks["ipv6"]), "2001:db8:ca2:2::/64")
|
||||
|
||||
def test_get_ip_networks_no_ip(self):
|
||||
net = DummyNetwork(self.NO_IP_XML)
|
||||
ip_networks = net.get_ip_networks()
|
||||
self.assertEqual(ip_networks, {})
|
||||
|
||||
def test_get_dhcp_range_ipv4(self):
|
||||
net = DummyNetwork(self.DUAL_STACK_XML)
|
||||
dhcp = net.get_dhcp_range("ipv4")
|
||||
self.assertIsNotNone(dhcp)
|
||||
self.assertEqual(len(dhcp), 2)
|
||||
self.assertEqual(str(dhcp[0]), "192.168.100.2")
|
||||
self.assertEqual(str(dhcp[1]), "192.168.100.254")
|
||||
|
||||
def test_get_dhcp_range_ipv6(self):
|
||||
net = DummyNetwork(self.DUAL_STACK_XML)
|
||||
dhcp = net.get_dhcp_range("ipv6")
|
||||
self.assertIsNotNone(dhcp)
|
||||
self.assertEqual(len(dhcp), 2)
|
||||
self.assertEqual(str(dhcp[0]), "2001:db8:ca2:2::100")
|
||||
self.assertEqual(str(dhcp[1]), "2001:db8:ca2:2::1ff")
|
||||
|
||||
def test_get_dhcp_range_empty(self):
|
||||
net = DummyNetwork(self.NO_IP_XML)
|
||||
self.assertIsNone(net.get_dhcp_range("ipv4"))
|
||||
self.assertIsNone(net.get_dhcp_range("ipv6"))
|
||||
|
||||
def test_get_dhcp_range_start_and_end(self):
|
||||
net = DummyNetwork(self.DUAL_STACK_XML)
|
||||
self.assertEqual(str(net.get_dhcp_range_start("ipv4")), "192.168.100.2")
|
||||
self.assertEqual(str(net.get_dhcp_range_end("ipv4")), "192.168.100.254")
|
||||
self.assertEqual(str(net.get_dhcp_range_start("ipv6")), "2001:db8:ca2:2::100")
|
||||
self.assertEqual(str(net.get_dhcp_range_end("ipv6")), "2001:db8:ca2:2::1ff")
|
||||
|
||||
def test_modify_fixed_address_validation(self):
|
||||
net = DummyNetwork(self.DUAL_STACK_XML)
|
||||
# Invalid IP address must raise ValueError
|
||||
with self.assertRaises(ValueError):
|
||||
net.modify_fixed_address("bad_host", "999.999.999.999", "52:54:00:11:22:33", family="ipv4")
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
net.modify_fixed_address("bad_host", "not-an-ip", "0:1:0:2", family="ipv6")
|
||||
def test_no_address(self):
|
||||
self.assertEqual(ip_networks(etree.fromstring("<network><name>isolated</name><bridge name='virbr1'/></network>")), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
"""Values from requests do not change the XPath queries they are used in."""
|
||||
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
|
|
@ -57,7 +58,7 @@ class XPathValueTests(unittest.TestCase):
|
|||
def test_qos_direction_must_be_known(self):
|
||||
net = wvmNetwork.__new__(wvmNetwork)
|
||||
net.wvm = FakeConn()
|
||||
net._XMLDesc = lambda flags: "<network><bandwidth><inbound average='1'/><outbound average='2'/></bandwidth></network>"
|
||||
net.net = Mock(**{"XMLDesc.return_value": "<network><bandwidth><inbound average='1'/><outbound average='2'/></bandwidth></network>"})
|
||||
with self.assertRaises(ValueError):
|
||||
net.unset_qos("*")
|
||||
net.unset_qos("inbound")
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import libvirt
|
|||
from computes.models import Compute
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
from django.urls import NoReverseMatch, URLPattern, URLResolver, get_resolver, reverse
|
||||
from instances.models import Flavor, Instance
|
||||
from lxml import html
|
||||
|
|
@ -27,6 +28,7 @@ class PageTests(TestCase):
|
|||
"""(URL name, parsed page) for every HTML page; asserts the main ones are among them."""
|
||||
conn = libvirt.open("test:///default")
|
||||
self.addCleanup(conn.close)
|
||||
without_inactive_flag(self)
|
||||
compute = Compute.objects.create(name="testdrv", hostname="localhost", login="", password="", type=4)
|
||||
vm = Instance.objects.create(compute=compute, name="test", uuid=conn.lookupByName("test").UUIDString())
|
||||
Flavor.objects.create(label="second", memory=512, vcpu=1, disk=10) # the flavor modals repeat per flavor
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import libvirt
|
|||
from computes.models import Compute
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import TestCase
|
||||
from networks.tests.driver import without_inactive_flag
|
||||
from django.urls import reverse
|
||||
from lxml import html
|
||||
|
||||
|
|
@ -17,6 +18,7 @@ class StatusContrastTests(TestCase):
|
|||
def setUp(self):
|
||||
self.conn = libvirt.open("test:///default")
|
||||
self.addCleanup(self.conn.close)
|
||||
without_inactive_flag(self)
|
||||
self.compute = Compute.objects.create(name="contrast", hostname="localhost", login="", password="", type=4)
|
||||
self.client.force_login(get_user_model().objects.create_superuser("contrast", "c@example.com", "pw"))
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue