mirror of
https://github.com/retspen/webvirtcloud
synced 2026-11-11 12:46:49 +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())
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue