1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 17:06:09 +00:00

fix(nwfilters): two changes at once do not undo each other

A rule or reference change reads a filter and defines it again whole:
two admins changing one filter at once each defined their copy, and the
second removed the first's rule. Changes to a host's filters (create,
clone, delete, rules, references, XML) now run one at a time; one that
finds another running is told to try again.

A VM's NIC form sends back its source, model, filter and MAC whole: a
form opened before another admin changed the NIC's filter put the old
filter back. The form now sends a fingerprint of the NIC as it showed
it, and a NIC changed meanwhile is refused.
This commit is contained in:
catborise 2026-11-13 11:24:33 +03:00
parent 2f7516b7f9
commit b664e34161
12 changed files with 714 additions and 631 deletions

View file

@ -366,6 +366,7 @@
<p class="small text-body-secondary">{% trans "The VM is running: the changes apply at its next start." %}</p>
{% endif %}
<input type="hidden" name="net-old-mac-{{ forloop.counter0 }}" value="{{ network.mac }}">
<input type="hidden" name="net-seen-{{ forloop.counter0 }}" value="{{ network.seen }}">
<div class="row g-3">
<div class="col-12">
<label class="form-label" for="net-source-{{ forloop.counter0 }}">{% trans "Source" %}</label>

View file

@ -45,6 +45,23 @@ class ChangeNetworkViewTestCase(TestCase):
"net-model-1": "virtio"}, HTTP_REFERER="/instances/%d/" % self.instance.id)
self.assertEqual([str(m) for m in get_messages(response.wsgi_request)], ["Network device changed"])
def test_a_form_shown_before_another_change_is_refused(self):
# another admin changed the NIC's filter meanwhile: saving the model would undo it
def post(seen):
with patch("instances.models.wvmInstance") as wvm:
wvm.return_value.get_status.return_value = 5
wvm.return_value.get_net_devices.return_value = [{"mac": "52:54:00:00:00:02", "seen": "now"}]
response = self.client.post(self.url, {"net-old-mac-1": "52:54:00:00:00:02", "net-model-1": "e1000",
"net-seen-1": seen}, HTTP_REFERER="/instances/%d/" % self.instance.id)
self.client.cookies.pop("messages", None)
return wvm.return_value.change_network, [str(m) for m in get_messages(response.wsgi_request)]
change, messages = post("before")
change.assert_not_called()
self.assertEqual(messages, ["Network interface 52:54:00:00:00:02 was changed meanwhile; reload the page"])
change, messages = post("now")
change.assert_called_once()
def test_invalid_mac_is_rejected(self):
change = self.post({
"net-old-mac-0": "52:54:00:00:00:01",

View file

@ -2019,6 +2019,12 @@ def change_network(request, pk):
messages.error(request, err)
return redirect(back)
# the form keeps what it does not change: one shown before another change would undo it
shown = next((net for net in instance.config_networks if net["mac"] == old_mac), None)
if shown and request.POST.get(f"net-seen-{num}") != shown["seen"]:
messages.error(request, _("Network interface %(mac)s was changed meanwhile; reload the page") % {"mac": old_mac})
return redirect(back)
# no source: the NIC keeps the one it has, which the host's lists may not show
raw_source = request.POST.get(f"net-source-{num}", "")
(source, source_type) = utils.get_network_tuple(raw_source) if raw_source else (None, None)

Binary file not shown.

File diff suppressed because it is too large Load diff

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -95,6 +95,21 @@ class FilterRedefineTests(TestCase):
_, response = self.defined({"del_nwfilter_rule": "", "index": "1", "rule": text(XML, "rule", 1)})
self.assertIn("Invalid value for attribute 'action'", " ".join(str(m) for m in get_messages(response.wsgi_request)))
def test_a_change_waits_for_no_other_change_of_the_hosts_filters(self):
# two at once each define the filter as they read it: the second would undo the first
from operations import claims
with patch("nwfilters.views.one_change", side_effect=claims.Busy("nwfilters:1")):
for url, data in ((self.url, {"add_nwfilter_rule": "", "nwfilterrule_xml": "<rule action='drop' direction='in'/>"}),
(self.list_url, {"del_nwfilter": "", "nwfiltername": "web"})):
with self.subTest(url):
response = self.client.post(url, data)
self.assertIn("short operation", " ".join(str(m) for m in get_messages(response.wsgi_request)))
self.client.cookies.pop("messages", None)
self.wvm.nwfilterDefineXMLFlags.assert_not_called()
self.wvm.nwfilterLookupByName.return_value.undefine.assert_not_called()
ALIKE = (f"<filter name='web' chain='root'><uuid>{UUID}</uuid>"
"<rule action='accept' direction='in' priority='500'><tcp dstportstart='22'/></rule>"
@ -186,3 +201,4 @@ class PageTests(TestCase):
self.wvm.listAllNWFilters.return_value.append(clean)
page = html.fromstring(self.client.get(url).content)
self.assertEqual(page.xpath("//a[text()='clean-traffic']/@href"), [reverse("nwfilter", args=[self.compute.id, "clean-traffic"])])

View file

@ -7,10 +7,19 @@ from django.urls import reverse
from instances.models import Instance
from libvirt import libvirtError
from logs.audit import audit
from operations import claims
from operations.models import Claim
from operations.utils import busy_message
from vrtManager import util
from vrtManager.nwfilters import wvmNWFilter, wvmNWFilters
def one_change(compute):
"""The host's filters for one change: read, checked and defined while no
other change of them runs, which it would undo."""
return claims.hold({claims.nwfilters_key(compute.pk): Claim.EXCLUSIVE})
@superuser_only
def nwfilters(request, compute_id):
"""The host's network filters; one created, cloned or deleted, after
@ -23,21 +32,22 @@ def nwfilters(request, compute_id):
if request.method == "POST":
name = request.POST.get("nwfiltername", "")
if "create_nwfilter" in request.POST:
xml = request.POST.get("nwfilter_xml", "")
try: # the row names the filter where the XML does
new_name = util.parse_xml(xml).get("name")
except util.OperationError:
new_name = None
with audit(request, compute, f"Network filter {new_name or '(no name)'}", "add"):
conn.create_nwfilter(xml)
elif "cln_nwfilter" in request.POST:
clone_name = request.POST.get("cln_name", "")
with audit(request, compute, f"Network filter {name}", f"clone as {clone_name}"):
conn.clone_nwfilter(name, clone_name)
elif "del_nwfilter" in request.POST:
with audit(request, compute, f"Network filter {name}", "delete"):
conn.delete_nwfilter(name)
with one_change(compute):
if "create_nwfilter" in request.POST:
xml = request.POST.get("nwfilter_xml", "")
try: # the row names the filter where the XML does
new_name = util.parse_xml(xml).get("name")
except util.OperationError:
new_name = None
with audit(request, compute, f"Network filter {new_name or '(no name)'}", "add"):
conn.create_nwfilter(xml)
elif "cln_nwfilter" in request.POST:
clone_name = request.POST.get("cln_name", "")
with audit(request, compute, f"Network filter {name}", f"clone as {clone_name}"):
conn.clone_nwfilter(name, clone_name)
elif "del_nwfilter" in request.POST:
with audit(request, compute, f"Network filter {name}", "delete"):
conn.delete_nwfilter(name)
return HttpResponseRedirect(request.get_full_path())
# the VMs first: a list without them would offer to delete filters in use
@ -49,6 +59,9 @@ def nwfilters(request, compute_id):
messages.error(request, lib_err)
if request.method == "POST": # a host not reached as well: nothing was changed
return HttpResponseRedirect(request.get_full_path())
except claims.Busy as busy: # another change of the host's filters runs
messages.error(request, busy_message(busy, request.user))
return HttpResponseRedirect(request.get_full_path())
return render(request, "nwfilters.html", {"nwfilters": nwfilters_all, "compute": compute})
@ -66,24 +79,27 @@ def nwfilter(request, compute_id, nwfltr):
post = request.POST
subject = f"Network filter {nwfltr}"
try:
if "edit_nwfilter" in post:
with audit(request, compute, subject, "change XML"):
nwfilter.edit(post.get("edit_xml", ""), post.get("seen", ""))
elif "add_nwfilter_rule" in post:
with audit(request, compute, subject, "add rule"):
nwfilter.add_rule(post.get("nwfilterrule_xml", ""))
elif "del_nwfilter_rule" in post:
with audit(request, compute, subject, "delete rule"):
nwfilter.delete_rule(post.get("index", ""), post.get("rule", ""))
elif "add_nwfilter_ref" in post:
ref_name = post.get("nwfilters_select", "")
with audit(request, compute, subject, f"add reference {ref_name}"):
nwfilter.add_ref(ref_name)
elif "del_nwfilter_ref" in post:
with audit(request, compute, subject, "delete reference") as entry:
entry.action = f"delete reference {nwfilter.delete_ref(post.get('index', ''), post.get('ref', ''))}"
with one_change(compute):
if "edit_nwfilter" in post:
with audit(request, compute, subject, "change XML"):
nwfilter.edit(post.get("edit_xml", ""), post.get("seen", ""))
elif "add_nwfilter_rule" in post:
with audit(request, compute, subject, "add rule"):
nwfilter.add_rule(post.get("nwfilterrule_xml", ""))
elif "del_nwfilter_rule" in post:
with audit(request, compute, subject, "delete rule"):
nwfilter.delete_rule(post.get("index", ""), post.get("rule", ""))
elif "add_nwfilter_ref" in post:
ref_name = post.get("nwfilters_select", "")
with audit(request, compute, subject, f"add reference {ref_name}"):
nwfilter.add_ref(ref_name)
elif "del_nwfilter_ref" in post:
with audit(request, compute, subject, "delete reference") as entry:
entry.action = f"delete reference {nwfilter.delete_ref(post.get('index', ''), post.get('ref', ''))}"
except libvirtError as err: # OperationError too: a filter changed meanwhile, XML refused
messages.error(request, err)
except claims.Busy as busy: # another change of the host's filters runs
messages.error(request, busy_message(busy, request.user))
return HttpResponseRedirect(request.get_full_path())
name = nwfilter.get_name()

View file

@ -53,6 +53,11 @@ def volume_key(compute_id, pool, name):
return f"volume:{compute_id}:{pool}/{name}"
def nwfilters_key(compute_id):
"""A host's network filters: one change at a time, read and defined."""
return f"nwfilters:{compute_id}"
def name_key(name):
"""A VM name is the panel's on every compute (the name checks are global)."""
return f"name:{name}"

View file

@ -931,6 +931,8 @@ class wvmInstance(wvmConnect):
"filterref": filterref_inst,
"inbound": inbound,
"outbound": outbound,
# the NIC as a form shows it: a form shown before another change is refused
"seen": util.digest(etree.tostring(net, encoding="unicode", with_tail=False)),
}
)
return result

View file

@ -117,6 +117,16 @@ class TestAddNetworkXml(unittest.TestCase):
iface = self.attached(mac_address="", source="default")
self.assertIsNone(iface.find("mac"))
def test_a_nic_is_seen_as_its_definition_reads(self):
# the fingerprint a form sends back: another change to the NIC gives another
inst = stopped_instance()
before = {nic["mac"]: nic["seen"] for nic in inst.get_net_devices(config=True)}
inst._XMLDesc.return_value = DOMAIN_XML.replace("<model type='virtio'/>\n<bandwidth>",
"<model type='virtio'/><filterref filter='clean-traffic'/>\n<bandwidth>")
after = {nic["mac"]: nic["seen"] for nic in inst.get_net_devices(config=True)}
self.assertNotEqual(before["52:54:00:00:00:02"], after["52:54:00:00:00:02"])
self.assertEqual(before["52:54:00:00:00:01"], after["52:54:00:00:00:01"])
if __name__ == "__main__":
unittest.main()