From f09df1c6f8abf35db6fefd0d055a13242b8ff6ee Mon Sep 17 00:00:00 2001 From: Jafar Al-Gharaibeh Date: Sun, 6 Sep 2026 19:48:12 -0500 Subject: [PATCH 1/3] munet: apply bridged node delay/rate/loss on a switch IFB Host-to-switch netem/tbf was installed on the node NIC and replaced the DUT's root qdisc. Keep the old TX meaning: node attachment constraints shape that node's outbound via an IFB on the switch veth ingress. Switch-attachment constraints still shape switch outbound. P2P stays on the node; warn instead of inventing a switch. Switch TC tests use a per-test munet so they do not share leftover interfaces with the module munet. Signed-off-by: Jafar Al-Gharaibeh --- munet/base.py | 55 +++++++++++++----- munet/native.py | 67 ++++++++++++++++++++-- tests/basic/test_switch_constraints.py | 77 ++++++++++++++++++++++++++ tests/config/qdisc/test_qdisc_cmd.py | 22 ++++++-- 4 files changed, 199 insertions(+), 22 deletions(-) create mode 100644 tests/basic/test_switch_constraints.py diff --git a/munet/base.py b/munet/base.py index 8ff9c79..c44b2d4 100644 --- a/munet/base.py +++ b/munet/base.py @@ -1783,6 +1783,24 @@ def get_number(c, v, d=None): return netem_args, tbf_args + def _add_tc_qdiscs(self, nsifname, constraints): + netem_args, tbf_args = self.get_linux_tc_args(nsifname, constraints) + if not netem_args and not tbf_args: + return False + count = 1 + selector = f"root handle {count}:" + if netem_args: + self.cmd_raises( + f"tc qdisc add dev {nsifname} {selector} netem {netem_args}" + ) + count += 1 + selector = f"parent {count-1}: handle {count}" + # Place rate limit after delay otherwise limit/burst too complex + if tbf_args: + self.cmd_raises(f"tc qdisc add dev {nsifname} {selector} tbf {tbf_args}") + self.cmd_raises(f"tc qdisc show dev {nsifname}") + return True + def set_intf_constraints(self, ifname, **constraints): """Set interface outbound constraints. @@ -1801,21 +1819,32 @@ def set_intf_constraints(self, ifname, **constraints): rate (int): bits per second, string allows for use of {KMGTKiMiGiTi} prefixes "i" means K == 1024 otherwise K == 1000. """ + self._add_tc_qdiscs(self.get_ns_ifname(ifname), constraints) + + def set_intf_ingress_constraints(self, ifname, **constraints): + """Shape packets arriving on ifname via an IFB in this namespace. + + Used on a switch port so a node's delay/rate/loss still apply to that + node's outbound traffic (same as a qdisc on the node NIC) without + taking the node's root qdisc. + """ nsifname = self.get_ns_ifname(ifname) netem_args, tbf_args = self.get_linux_tc_args(nsifname, constraints) - count = 1 - selector = f"root handle {count}:" - if netem_args: - self.cmd_raises( - f"tc qdisc add dev {nsifname} {selector} netem {netem_args}" - ) - count += 1 - selector = f"parent {count-1}: handle {count}" - # Place rate limit after delay otherwise limit/burst too complex - if tbf_args: - self.cmd_raises(f"tc qdisc add dev {nsifname} {selector} tbf {tbf_args}") - - self.cmd_raises(f"tc qdisc show dev {nsifname}") + if not netem_args and not tbf_args: + return + ifb = "ifb" + re.sub(r"[^A-Za-z0-9]", "", nsifname) + ifb = ifb[:15] or "ifb0" + # Modules are host-global. The munet mount ns often has no + # /lib/modules, so modprobe inside it fails even when ifb is loaded. + commander.cmd_status("modprobe ifb", warn=False) + self.cmd_raises(f"ip link add {ifb} type ifb") + self.cmd_raises(f"ip link set {ifb} up") + self.cmd_raises(f"tc qdisc add dev {nsifname} handle ffff: ingress") + self.cmd_raises( + f"tc filter add dev {nsifname} parent ffff: protocol all " + f"u32 match u32 0 0 action mirred egress redirect dev {ifb}" + ) + self._add_tc_qdiscs(ifb, constraints) class LinuxNamespace(Commander, InterfaceMixin): diff --git a/munet/native.py b/munet/native.py index acc5d0e..44710c2 100644 --- a/munet/native.py +++ b/munet/native.py @@ -3332,6 +3332,34 @@ async def add_dummy_link(self, node1, c1=None): super().add_dummy(node1, if1, **c1) node1.set_dummy_addr(c1) + _TC_KEYS = ( + "delay", + "jitter", + "jitter-correlation", + "loss", + "loss-correlation", + "rate", + ) + + @staticmethod + def _tc_pick(config): + """Copy linux TC keys from config.""" + if not config: + return {} + out = {} + for key in Munet._TC_KEYS: + if config.get(key) is not None: + out[key] = config[key] + return out + + @staticmethod + def _tc_constraints(*configs): + """Merge unprefixed TC keys; later configs override earlier ones.""" + out = {} + for config in configs: + out.update(Munet._tc_pick(config)) + return out + async def add_native_link(self, node1, node2, c1=None, c2=None): """Add a link between switch and node or 2 nodes.""" isp2p = False @@ -3392,10 +3420,41 @@ async def add_native_link(self, node1, node2, c1=None, c2=None): if isinstance(node1, ExternalNetwork): pass - elif "physical" not in c1 and not node1.is_vm: - node1.set_intf_constraints(if1, **c1) - if "physical" not in c2 and not node2.is_vm: - node2.set_intf_constraints(if2, **c2) + elif isp2p: + # Both veth ends live inside the nodes. There is no outside + # device to own the "link" unless we insert a mid-netns. + if "physical" not in c1 and not node1.is_vm: + tx = Munet._tc_constraints(c1) + if tx: + self.logger.warning( + "%s: p2p constraints on %s:%s stay inside the node", + self, + node1.name, + if1, + ) + node1.set_intf_constraints(if1, **tx) + if "physical" not in c2 and not node2.is_vm: + tx = Munet._tc_constraints(c2) + if tx: + self.logger.warning( + "%s: p2p constraints on %s:%s stay inside the node", + self, + node2.name, + if2, + ) + node2.set_intf_constraints(if2, **tx) + elif "physical" not in c2: + # Host-to-switch: keep the old one-way meaning. + # c1 (switch attachment) still shapes switch outbound (into + # the node). c2 (node attachment) used to shape the node NIC + # outbound; do that on an IFB of the switch veth instead so + # the DUT keeps its root qdisc. + switch_tc = Munet._tc_constraints(c1) + node_tc = Munet._tc_constraints(c2) + if switch_tc: + node1.set_intf_constraints(if1, **switch_tc) + if node_tc: + node1.set_intf_ingress_constraints(if1, **node_tc) def add_l3_node(self, name, config=None, **kwargs): """Add a node to munet.""" diff --git a/tests/basic/test_switch_constraints.py b/tests/basic/test_switch_constraints.py new file mode 100644 index 0000000..950a357 --- /dev/null +++ b/tests/basic/test_switch_constraints.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# September 6 2026, Jafar Al-Gharaibeh +# +"Testing of interface constraints applied on the switch side of links." + +import logging +import re + +import pytest + +from munet import Munet + +# All tests are coroutines +pytestmark = pytest.mark.asyncio + + +@pytest.fixture(scope="function", name="unet_case") +async def unet_case_(request, rundir, pytestconfig): + """Per-test munet so switch/node names do not collide with other cases.""" + unshare = bool(request.param) if hasattr(request, "param") else True + logging.info("Creating munet with%s inline unshare", "" if unshare else "out") + unet = Munet(rundir=rundir, unshare_inline=unshare, pytestconfig=pytestconfig) + try: + yield unet + finally: + await unet.async_delete() + + +async def ping_average_rtt(r, other, oifname): + oip = other.get_intf_addr(oifname).ip + await r.async_cmd_raises(f"ping -w1 -c1 {oip}") + o = await r.async_cmd_raises(f"ping -i.1 -c5 {oip}") + m = re.search(r"min/avg/max/mdev = ([^/]+)/([^/]+)([^/]+)/([^ ]+) ms", o) + return float(m.group(2)) + + +@pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) +async def test_switch_constraints_outside_node(unet_case): + """Node delay/rate stay TX-shaped, but the qdisc lives in the switch ns.""" + unet = unet_case + unet.autonumber = True + + r1 = unet.add_l3_node("r1") + r2 = unet.add_l3_node("r2") + sw1 = unet.add_network("sw1", {"ip": "auto"}) + + delay = 50000 + await unet.add_native_link(sw1, r1, {}, {"delay": delay}) + await unet.add_native_link(sw1, r2, {}, {"delay": delay}) + + rif1 = r1.net_intfs[sw1.name] + rif2 = r2.net_intfs[sw1.name] + sif1 = sw1.intfs[0] + sif2 = sw1.intfs[1] + + r1q = await r1.async_cmd_raises(f"tc qdisc show dev {rif1}") + r2q = await r2.async_cmd_raises(f"tc qdisc show dev {rif2}") + s1q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif1}") + s2q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif2}") + swq = await sw1.async_cmd_raises("tc qdisc show") + logging.info("node qdiscs: %s | %s", r1q, r2q) + logging.info("switch port qdiscs: %s | %s", s1q, s2q) + logging.info("switch ns qdiscs: %s", swq) + assert "netem" not in r1q + assert "netem" not in r2q + assert "ingress" in s1q + assert "ingress" in s2q + assert "netem" not in s1q + assert "netem" not in s2q + assert "netem" in swq + + exp_avg = (delay + delay) / 1000 + avg = await ping_average_rtt(r1, r2, rif2) + logging.info("ping average RTT: %s", avg) + assert (exp_avg - 1) < avg < (exp_avg + 2) diff --git a/tests/config/qdisc/test_qdisc_cmd.py b/tests/config/qdisc/test_qdisc_cmd.py index 00184e0..f31726c 100644 --- a/tests/config/qdisc/test_qdisc_cmd.py +++ b/tests/config/qdisc/test_qdisc_cmd.py @@ -38,19 +38,31 @@ async def test_config_cmd(unet_share): h1 = unet.hosts["h1"] output = h1.cmd_raises("tc q | grep 'dev eth0'") - logging.debug("qdisc for dev eth0 output found: %s", output) - logging.debug("expects delay='200', jitter='60', loss='70', rate='1600'") + logging.debug("qdisc for h1 eth0 found: %s", output) + logging.debug("node delay is on the switch IFB, not the node NIC") + assert "delay" not in output + assert "loss" not in output + assert "rate" not in output + + net1 = unet.switches["net1"] + output = net1.cmd_raises("tc q | grep 'dev ifbnet1e0'") + logging.debug("qdisc for ifbnet1e0 (h1 TX) found: %s", output) assert re.search(r"delay 200us\s+59us.*loss 70%.*rate 1600bit", output, re.DOTALL) h2 = unet.hosts["h2"] output = h2.cmd_raises("tc q | grep 'dev eth0'") - logging.debug("qdisc for dev eth0 output found: %s", output) - logging.debug("expects delay='209', jitter='60', loss='70', rate='1600'") + logging.debug("qdisc for h2 eth0 found: %s", output) + assert "delay" not in output + assert "loss" not in output + assert "rate" not in output + + output = net1.cmd_raises("tc q | grep 'dev ifbnet1e1'") + logging.debug("qdisc for ifbnet1e1 (h2 TX) found: %s", output) assert re.search(r"delay 209us\s+59us.*loss 70%.*rate 1600bit", output, re.DOTALL) h3 = unet.hosts["h3"] output = h3.cmd_raises("tc q | grep 'dev eth0'") - logging.debug("qdisc for dev eth0 output found: %s", output) + logging.debug("qdisc for h3 eth0 found: %s", output) logging.debug("expects none") assert "delay" not in output assert "loss" not in output From c9b45ea4fdc4fb314aa7d87eb8fb5c6448e82393 Mon Sep 17 00:00:00 2001 From: Jafar Al-Gharaibeh Date: Thu, 24 Sep 2026 20:37:41 -0500 Subject: [PATCH 2/3] munet: shape both directions with transmit/receive containers Wrap TC constraints in optional "transmit" and "receive" containers, relative to the owner of the config: the network for network config, the node for node connections. Unwrapped constraints are deprecated and keep meaning transmit. Host-to-switch links shape both directions on the switch port so the DUT keeps its root qdisc: network transmit and node receive toward the node (switch egress), network receive and node transmit from the node (IFB). Node values win. For p2p, a node's receive is applied on the peer's egress. Schema is generated from the YANG in README.org. Signed-off-by: Jafar Al-Gharaibeh --- README.org | 131 +++++++- doc/source/config.rst | 84 ++++- munet/munet-schema.json | 440 +++++++++++++++++++++++++ munet/native.py | 62 ++-- tests/basic/test_switch_constraints.py | 152 +++++++++ tests/config/qdisc/munet.yaml | 12 + tests/config/qdisc/test_qdisc_cmd.py | 16 + 7 files changed, 851 insertions(+), 46 deletions(-) diff --git a/README.org b/README.org index 21c71cf..89f635f 100644 --- a/README.org +++ b/README.org @@ -103,9 +103,29 @@ module: labn-munet-config | | +--rw loss? uint64 | | +--rw loss-correlation? decimal64 | | +--rw rate - | | +--rw rate? number64 - | | +--rw limit? number64 - | | +--rw burst? number64 + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw transmit + | | | +--rw delay? uint64 + | | | +--rw jitter? uint64 + | | | +--rw jitter-correlation? decimal64 + | | | +--rw loss? uint64 + | | | +--rw loss-correlation? decimal64 + | | | +--rw rate + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw receive + | | +--rw delay? uint64 + | | +--rw jitter? uint64 + | | +--rw jitter-correlation? decimal64 + | | +--rw loss? uint64 + | | +--rw loss-correlation? decimal64 + | | +--rw rate + | | +--rw rate? number64 + | | +--rw limit? number64 + | | +--rw burst? number64 | +--rw env* [name] | | +--rw name string | | +--rw value? string @@ -145,6 +165,26 @@ module: labn-munet-config | | | +--rw rate? number64 | | | +--rw limit? number64 | | | +--rw burst? number64 + | | +--rw transmit + | | | +--rw delay? uint64 + | | | +--rw jitter? uint64 + | | | +--rw jitter-correlation? decimal64 + | | | +--rw loss? uint64 + | | | +--rw loss-correlation? decimal64 + | | | +--rw rate + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw receive + | | | +--rw delay? uint64 + | | | +--rw jitter? uint64 + | | | +--rw jitter-correlation? decimal64 + | | | +--rw loss? uint64 + | | | +--rw loss-correlation? decimal64 + | | | +--rw rate + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 | | +--rw connections* [to] | | +--rw to string | | +--rw name? string @@ -155,9 +195,29 @@ module: labn-munet-config | | +--rw loss? uint64 | | +--rw loss-correlation? decimal64 | | +--rw rate - | | +--rw rate? number64 - | | +--rw limit? number64 - | | +--rw burst? number64 + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw transmit + | | | +--rw delay? uint64 + | | | +--rw jitter? uint64 + | | | +--rw jitter-correlation? decimal64 + | | | +--rw loss? uint64 + | | | +--rw loss-correlation? decimal64 + | | | +--rw rate + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw receive + | | +--rw delay? uint64 + | | +--rw jitter? uint64 + | | +--rw jitter-correlation? decimal64 + | | +--rw loss? uint64 + | | +--rw loss-correlation? decimal64 + | | +--rw rate + | | +--rw rate? number64 + | | +--rw limit? number64 + | | +--rw burst? number64 | +--rw nodes* [name] | +--rw id? uint32 | +--rw kind? -> ../../../kinds/name @@ -217,9 +277,29 @@ module: labn-munet-config | | +--rw loss? uint64 | | +--rw loss-correlation? decimal64 | | +--rw rate - | | +--rw rate? number64 - | | +--rw limit? number64 - | | +--rw burst? number64 + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw transmit + | | | +--rw delay? uint64 + | | | +--rw jitter? uint64 + | | | +--rw jitter-correlation? decimal64 + | | | +--rw loss? uint64 + | | | +--rw loss-correlation? decimal64 + | | | +--rw rate + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw receive + | | +--rw delay? uint64 + | | +--rw jitter? uint64 + | | +--rw jitter-correlation? decimal64 + | | +--rw loss? uint64 + | | +--rw loss-correlation? decimal64 + | | +--rw rate + | | +--rw rate? number64 + | | +--rw limit? number64 + | | +--rw burst? number64 | +--rw env* [name] | | +--rw name string | | +--rw value? string @@ -568,6 +648,30 @@ munet> } } + grouping directional-intf-constraints { + description + "Traffic control constraints by direction. Direction is relative to + the owner of the config: the node for node connections, and the + network (bridge) for network config."; + uses intf-constraints { + status deprecated; + description + "Constraints outside of ./transmit or ./receive apply to transmit. + Use ./transmit instead."; + } + container transmit { + description + "Constraints on traffic sent by this end (local egress). These + override the deprecated unwrapped constraints."; + uses intf-constraints; + } + container receive { + description + "Constraints on traffic received by this end (local ingress)."; + uses intf-constraints; + } + } + grouping common-node { description "Common node properties"; leaf-list ip { @@ -879,7 +983,7 @@ munet> default "virtio-net-pc"; description "driver name for qemu based interfaces"; } - uses intf-constraints; + uses directional-intf-constraints; } list env { key name; @@ -1158,7 +1262,7 @@ munet> } /* default network tc parameters */ - uses intf-constraints; + uses directional-intf-constraints; list connections { key to; @@ -1166,7 +1270,8 @@ munet> "Overriding network side configuration for connections to nodes from this network. If the default network tc parameters are not being overriden for a specific node connection then this configuration is - not required."; + not required. Here transmit is traffic toward the node and receive + is traffic from the node."; leaf to { type string; @@ -1182,7 +1287,7 @@ munet> "The remote name of the connection. This is used for disambiguation when there are multiple connections to the same remote node."; } - uses intf-constraints; + uses directional-intf-constraints; } } diff --git a/doc/source/config.rst b/doc/source/config.rst index 84944ca..41bc85b 100644 --- a/doc/source/config.rst +++ b/doc/source/config.rst @@ -118,6 +118,26 @@ Tree diagram for network config:: | +--rw rate? number64 | +--rw limit? number64 | +--rw burst? number64 + +--rw transmit + | +--rw delay? uint64 + | +--rw jitter? uint64 + | +--rw jitter-correlation? decimal64 + | +--rw loss? uint64 + | +--rw loss-correlation? decimal64 + | +--rw rate + | +--rw rate? number64 + | +--rw limit? number64 + | +--rw burst? number64 + +--rw receive + | +--rw delay? uint64 + | +--rw jitter? uint64 + | +--rw jitter-correlation? decimal64 + | +--rw loss? uint64 + | +--rw loss-correlation? decimal64 + | +--rw rate + | +--rw rate? number64 + | +--rw limit? number64 + | +--rw burst? number64 +--rw connections* [to] +--rw to string +--rw name? string @@ -128,15 +148,55 @@ Tree diagram for network config:: +--rw loss? uint64 +--rw loss-correlation? decimal64 +--rw rate - +--rw rate? number64 - +--rw limit? number64 - +--rw burst? number64 + | +--rw rate? number64 + | +--rw limit? number64 + | +--rw burst? number64 + +--rw transmit + | +--rw delay? uint64 + | +--rw jitter? uint64 + | +--rw jitter-correlation? decimal64 + | +--rw loss? uint64 + | +--rw loss-correlation? decimal64 + | +--rw rate + | +--rw rate? number64 + | +--rw limit? number64 + | +--rw burst? number64 + +--rw receive + +--rw delay? uint64 + +--rw jitter? uint64 + +--rw jitter-correlation? decimal64 + +--rw loss? uint64 + +--rw loss-correlation? decimal64 + +--rw rate + +--rw rate? number64 + +--rw limit? number64 + +--rw burst? number64 The ``connections`` configuration is entirely optional, and is present to allow overriding default network quality parameters (e.g., ``delay``, ``jitter``, etc). If no override is required it is enough for the nodes to specify their connection to the network. +Network quality parameters are directional and relative to the network: +``transmit`` shapes traffic the network sends toward a node, and ``receive`` +shapes traffic the network receives from a node. Both are applied on the +network's bridge port, so the node's own qdiscs are left untouched. Parameters +given outside of ``transmit``/``receive`` are deprecated and apply to +``transmit``. + +For example, to shape both directions between ``wan1`` and ``r1``:: + + networks: + - name: wan1 + connections: + - to: r1 + transmit: + delay: 2500 + rate: { rate: "15M", burst: 16384, limit: 131072 } + receive: + delay: 2500 + rate: { rate: "5M", burst: 16384, limit: 131072 } + Nodes ^^^^^ @@ -234,9 +294,21 @@ Tree diagram for node connections:: | | +--rw loss? uint64 | | +--rw loss-correlation? decimal64 | | +--rw rate - | | +--rw rate? number64 - | | +--rw limit? number64 - | | +--rw burst? number64 + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 + | | +--rw transmit + | | | ... same constraints as above + | | +--rw receive + | | ... same constraints as above + +Connection quality parameters are relative to the node: ``transmit`` shapes +traffic the node sends and ``receive`` shapes traffic the node receives. +Parameters given outside of ``transmit``/``receive`` are deprecated and apply to +``transmit``. For connections to a network both directions are shaped on the +network's bridge port, and node values override network values. For +point-to-point connections the shaping is applied on the sending node's +interface, combining the sender's ``transmit`` with the receiver's ``receive``. Mounts diff --git a/munet/munet-schema.json b/munet/munet-schema.json index ca3a004..b97c7fa 100644 --- a/munet/munet-schema.json +++ b/munet/munet-schema.json @@ -292,6 +292,116 @@ ] } } + }, + "transmit": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } + }, + "receive": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } } } } @@ -479,6 +589,116 @@ } } }, + "transmit": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } + }, + "receive": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } + }, "connections": { "type": "array", "items": { @@ -542,6 +762,116 @@ ] } } + }, + "transmit": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } + }, + "receive": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } } } } @@ -783,6 +1113,116 @@ ] } } + }, + "transmit": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } + }, + "receive": { + "type": "object", + "properties": { + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } } } } diff --git a/munet/native.py b/munet/native.py index 44710c2..e8077f0 100644 --- a/munet/native.py +++ b/munet/native.py @@ -3329,7 +3329,7 @@ async def add_dummy_link(self, node1, c1=None): do_add_dummy = False if do_add_dummy: - super().add_dummy(node1, if1, **c1) + super().add_dummy(node1, if1, mtu=c1.get("mtu"), **Munet._tc_transmit(c1)) node1.set_dummy_addr(c1) _TC_KEYS = ( @@ -3360,6 +3360,20 @@ def _tc_constraints(*configs): out.update(Munet._tc_pick(config)) return out + @staticmethod + def _tc_transmit(config): + """TC for local egress: deprecated unwrapped keys, then ``transmit``.""" + if not config: + return {} + return Munet._tc_constraints(config, config.get("transmit")) + + @staticmethod + def _tc_receive(config): + """TC for local ingress from ``receive``.""" + if not config: + return {} + return Munet._tc_pick(config.get("receive")) + async def add_native_link(self, node1, node2, c1=None, c2=None): """Add a link between switch and node or 2 nodes.""" isp2p = False @@ -3423,38 +3437,32 @@ async def add_native_link(self, node1, node2, c1=None, c2=None): elif isp2p: # Both veth ends live inside the nodes. There is no outside # device to own the "link" unless we insert a mid-netns. - if "physical" not in c1 and not node1.is_vm: - tx = Munet._tc_constraints(c1) - if tx: - self.logger.warning( - "%s: p2p constraints on %s:%s stay inside the node", - self, - node1.name, - if1, - ) - node1.set_intf_constraints(if1, **tx) - if "physical" not in c2 and not node2.is_vm: - tx = Munet._tc_constraints(c2) + # Each end's egress carries its own transmit and the peer's + # receive; the sender's transmit wins on overlapping keys. + for n, intf, c, oc in ((node1, if1, c1, c2), (node2, if2, c2, c1)): + if "physical" in c or n.is_vm: + continue + tx = {**Munet._tc_receive(oc), **Munet._tc_transmit(c)} if tx: self.logger.warning( "%s: p2p constraints on %s:%s stay inside the node", self, - node2.name, - if2, + n.name, + intf, ) - node2.set_intf_constraints(if2, **tx) + n.set_intf_constraints(intf, **tx) elif "physical" not in c2: - # Host-to-switch: keep the old one-way meaning. - # c1 (switch attachment) still shapes switch outbound (into - # the node). c2 (node attachment) used to shape the node NIC - # outbound; do that on an IFB of the switch veth instead so - # the DUT keeps its root qdisc. - switch_tc = Munet._tc_constraints(c1) - node_tc = Munet._tc_constraints(c2) - if switch_tc: - node1.set_intf_constraints(if1, **switch_tc) - if node_tc: - node1.set_intf_ingress_constraints(if1, **node_tc) + # Host-to-switch: shape on the switch port so the node keeps its + # root qdisc. Switch transmit and node receive shape traffic + # toward the node (switch egress). Switch receive and node + # transmit shape traffic from the node (IFB on switch ingress). + # Node values win on overlapping keys. + toward_node = {**Munet._tc_transmit(c1), **Munet._tc_receive(c2)} + from_node = {**Munet._tc_receive(c1), **Munet._tc_transmit(c2)} + if toward_node: + node1.set_intf_constraints(if1, **toward_node) + if from_node: + node1.set_intf_ingress_constraints(if1, **from_node) def add_l3_node(self, name, config=None, **kwargs): """Add a node to munet.""" diff --git a/tests/basic/test_switch_constraints.py b/tests/basic/test_switch_constraints.py index 950a357..3cfb69d 100644 --- a/tests/basic/test_switch_constraints.py +++ b/tests/basic/test_switch_constraints.py @@ -75,3 +75,155 @@ async def test_switch_constraints_outside_node(unet_case): avg = await ping_average_rtt(r1, r2, rif2) logging.info("ping average RTT: %s", avg) assert (exp_avg - 1) < avg < (exp_avg + 2) + + +@pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) +async def test_switch_transmit_and_receive(unet_case): + """Switch transmit is node RX; receive is node TX (IFB). Together RTT.""" + unet = unet_case + unet.autonumber = True + + r1 = unet.add_l3_node("r1") + r2 = unet.add_l3_node("r2") + sw1 = unet.add_network("sw1", {"ip": "auto"}) + + delay = 50000 + swc = {"transmit": {"delay": delay}, "receive": {"delay": delay}} + await unet.add_native_link(sw1, r1, dict(swc), {}) + await unet.add_native_link(sw1, r2, dict(swc), {}) + + rif2 = r2.net_intfs[sw1.name] + sif1 = sw1.intfs[0] + sif2 = sw1.intfs[1] + r1q = await r1.async_cmd_raises(f"tc qdisc show dev {r1.net_intfs[sw1.name]}") + s1q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif1}") + s2q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif2}") + swq = await sw1.async_cmd_raises("tc qdisc show") + logging.info("node qdisc: %s", r1q) + logging.info("switch ports: %s | %s", s1q, s2q) + logging.info("switch ns: %s", swq) + assert "netem" not in r1q + assert "ingress" in s1q and "netem" in s1q + assert "ingress" in s2q and "netem" in s2q + assert "ifb" in swq + + # TX + RX on each hop: 4 * 50ms + exp_avg = (delay * 4) / 1000 + avg = await ping_average_rtt(r1, r2, rif2) + logging.info("ping average RTT: %s", avg) + assert (exp_avg - 1) < avg < (exp_avg + 2) + + +def test_tc_directions(): + """Unwrapped keys are transmit; containers override and split direction.""" + # pylint: disable=protected-access + assert not Munet._tc_transmit(None) + assert not Munet._tc_receive(None) + assert not Munet._tc_receive({"delay": 1000}) + + conf = { + "name": "eth0", + "delay": 1000, + "loss": 5, + "transmit": {"delay": 2000, "rate": {"rate": "15M"}}, + "receive": {"delay": 3000}, + } + tx = Munet._tc_transmit(conf) + rx = Munet._tc_receive(conf) + assert tx == {"delay": 2000, "loss": 5, "rate": {"rate": "15M"}} + assert rx == {"delay": 3000} + assert Munet._tc_transmit({"delay": 1000}) == {"delay": 1000} + + +@pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) +async def test_switch_legacy_transmit_only(unet_case): + """Deprecated unwrapped switch TC is transmit: switch egress (no IFB).""" + unet = unet_case + unet.autonumber = True + + r1 = unet.add_l3_node("r1") + r2 = unet.add_l3_node("r2") + sw1 = unet.add_network("sw1", {"ip": "auto"}) + + delay = 50000 + await unet.add_native_link(sw1, r1, {"delay": delay}, {}) + await unet.add_native_link(sw1, r2, {"delay": delay}, {}) + + rif2 = r2.net_intfs[sw1.name] + sif1 = sw1.intfs[0] + sif2 = sw1.intfs[1] + r1q = await r1.async_cmd_raises(f"tc qdisc show dev {r1.net_intfs[sw1.name]}") + s1q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif1}") + s2q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif2}") + swq = await sw1.async_cmd_raises("tc qdisc show") + logging.info("node qdisc: %s", r1q) + logging.info("switch ports: %s | %s", s1q, s2q) + logging.info("switch ns: %s", swq) + assert "netem" not in r1q + assert "ingress" not in s1q and "netem" in s1q + assert "ingress" not in s2q and "netem" in s2q + assert "ifb" not in swq + + exp_avg = (delay + delay) / 1000 + avg = await ping_average_rtt(r1, r2, rif2) + logging.info("ping average RTT: %s", avg) + assert (exp_avg - 1) < avg < (exp_avg + 2) + + +@pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) +async def test_switch_node_receive(unet_case): + """Node receive on a network link shapes switch egress, not the node.""" + unet = unet_case + unet.autonumber = True + + r1 = unet.add_l3_node("r1") + r2 = unet.add_l3_node("r2") + sw1 = unet.add_network("sw1", {"ip": "auto"}) + + delay = 50000 + await unet.add_native_link(sw1, r1, {}, {"receive": {"delay": delay}}) + await unet.add_native_link(sw1, r2, {}, {"receive": {"delay": delay}}) + + rif2 = r2.net_intfs[sw1.name] + sif1 = sw1.intfs[0] + r1q = await r1.async_cmd_raises(f"tc qdisc show dev {r1.net_intfs[sw1.name]}") + s1q = await sw1.async_cmd_raises(f"tc qdisc show dev {sif1}") + swq = await sw1.async_cmd_raises("tc qdisc show") + logging.info("node qdisc: %s", r1q) + logging.info("switch port: %s", s1q) + logging.info("switch ns: %s", swq) + assert "netem" not in r1q + assert "ingress" not in s1q and "netem" in s1q + assert "ifb" not in swq + + exp_avg = (delay + delay) / 1000 + avg = await ping_average_rtt(r1, r2, rif2) + logging.info("ping average RTT: %s", avg) + assert (exp_avg - 1) < avg < (exp_avg + 2) + + +@pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) +async def test_p2p_receive(unet_case): + """P2P receive is applied on the peer's egress.""" + unet = unet_case + unet.autonumber = True + + r1 = unet.add_l3_node("r1") + r2 = unet.add_l3_node("r2") + + ifname = "p2p0" + delay = 50000 + c1 = {"name": ifname, "receive": {"delay": delay}} + c2 = {"name": ifname} + await unet.add_native_link(r1, r2, c1, c2) + + r1q = await r1.async_cmd_raises(f"tc qdisc show dev {ifname}") + r2q = await r2.async_cmd_raises(f"tc qdisc show dev {ifname}") + logging.info("node qdiscs: %s | %s", r1q, r2q) + assert "netem" not in r1q + assert "netem" in r2q + + exp_avg = delay / 1000 + avg = await ping_average_rtt(r1, r2, ifname) + logging.info("ping average RTT: %s", avg) + assert (exp_avg - 1) < avg < (exp_avg + 2) diff --git a/tests/config/qdisc/munet.yaml b/tests/config/qdisc/munet.yaml index 3d36c60..9498ebb 100644 --- a/tests/config/qdisc/munet.yaml +++ b/tests/config/qdisc/munet.yaml @@ -16,6 +16,11 @@ topology: rate: 810 - to: h3 delay: 14 + - to: h4 + transmit: + delay: 2000 + receive: + delay: 3000 nodes: - name: h1 @@ -37,3 +42,10 @@ topology: - name: h3 connections: - to: net1 + - name: h4 + connections: + - to: net1 + transmit: + loss: 20 + receive: + loss: 10 diff --git a/tests/config/qdisc/test_qdisc_cmd.py b/tests/config/qdisc/test_qdisc_cmd.py index f31726c..14aa969 100644 --- a/tests/config/qdisc/test_qdisc_cmd.py +++ b/tests/config/qdisc/test_qdisc_cmd.py @@ -67,3 +67,19 @@ async def test_config_cmd(unet_share): assert "delay" not in output assert "loss" not in output assert "rate" not in output + + h4 = unet.hosts["h4"] + output = h4.cmd_raises("tc q | grep 'dev eth0'") + logging.debug("qdisc for h4 eth0 found: %s", output) + assert "delay" not in output + assert "loss" not in output + + # Toward h4: network transmit plus h4 receive, on the switch port. + output = unet.cmd_raises("tc q | grep 'dev net1-e3'") + logging.debug("qdisc for dev net1-e3 (h4 RX) found: %s", output) + assert re.search(r"delay 2ms.*loss 10%", output, re.DOTALL) + + # From h4: network receive plus h4 transmit, on the switch IFB. + output = net1.cmd_raises("tc q | grep 'dev ifbnet1e3'") + logging.debug("qdisc for ifbnet1e3 (h4 TX) found: %s", output) + assert re.search(r"delay 3ms.*loss 20%", output, re.DOTALL) From 19bb4928b85aa8605f088a125dd1fd7882f2487c Mon Sep 17 00:00:00 2001 From: Jafar Al-Gharaibeh Date: Tue, 20 Oct 2026 21:12:05 -0500 Subject: [PATCH 3/3] munet: add per-peer transmit constraints on networks A network connection's transmit can now list peers, giving traffic from a specific sending node toward that connection's node its own delay/rate/loss. This allows different link quality for each ordered pair of nodes on the same network. Each port of a network that uses peers marks arriving packets with a per-node skb mark. The receiving node's port uses a drr qdisc with one class per peer, selected by fw filter on that mark, and a default class for everything else. Classifying by ingress port rather than MAC keeps this working for VMs, MAC changes, and broadcast/multicast. Signed-off-by: Jafar Al-Gharaibeh --- README.org | 35 ++++++++++++-- doc/source/config.rst | 36 ++++++++++++-- munet/base.py | 66 ++++++++++++++++++++++---- munet/munet-schema.json | 61 ++++++++++++++++++++++++ munet/native.py | 33 +++++++++++-- tests/basic/test_switch_constraints.py | 54 +++++++++++++++++++++ tests/config/qdisc/munet.yaml | 3 ++ tests/config/qdisc/test_qdisc_cmd.py | 5 +- 8 files changed, 272 insertions(+), 21 deletions(-) diff --git a/README.org b/README.org index 89f635f..2c032db 100644 --- a/README.org +++ b/README.org @@ -205,9 +205,20 @@ module: labn-munet-config | | | +--rw loss? uint64 | | | +--rw loss-correlation? decimal64 | | | +--rw rate - | | | +--rw rate? number64 - | | | +--rw limit? number64 - | | | +--rw burst? number64 + | | | | +--rw rate? number64 + | | | | +--rw limit? number64 + | | | | +--rw burst? number64 + | | | +--rw peers* [peer] + | | | +--rw peer string + | | | +--rw delay? uint64 + | | | +--rw jitter? uint64 + | | | +--rw jitter-correlation? decimal64 + | | | +--rw loss? uint64 + | | | +--rw loss-correlation? decimal64 + | | | +--rw rate + | | | +--rw rate? number64 + | | | +--rw limit? number64 + | | | +--rw burst? number64 | | +--rw receive | | +--rw delay? uint64 | | +--rw jitter? uint64 @@ -1287,7 +1298,23 @@ munet> "The remote name of the connection. This is used for disambiguation when there are multiple connections to the same remote node."; } - uses directional-intf-constraints; + uses directional-intf-constraints { + augment "transmit" { + description "Per-sender overrides for traffic toward the node."; + list peers { + key peer; + description + "Constraints for traffic sent by a peer node on this network + toward this connection's node. Constraints not given here + are taken from ../ (transmit) and the node's receive."; + leaf peer { + type string; + description "Name of the sending node."; + } + uses intf-constraints; + } + } + } } } diff --git a/doc/source/config.rst b/doc/source/config.rst index 41bc85b..0b1d405 100644 --- a/doc/source/config.rst +++ b/doc/source/config.rst @@ -158,9 +158,20 @@ Tree diagram for network config:: | +--rw loss? uint64 | +--rw loss-correlation? decimal64 | +--rw rate - | +--rw rate? number64 - | +--rw limit? number64 - | +--rw burst? number64 + | | +--rw rate? number64 + | | +--rw limit? number64 + | | +--rw burst? number64 + | +--rw peers* [peer] + | +--rw peer string + | +--rw delay? uint64 + | +--rw jitter? uint64 + | +--rw jitter-correlation? decimal64 + | +--rw loss? uint64 + | +--rw loss-correlation? decimal64 + | +--rw rate + | +--rw rate? number64 + | +--rw limit? number64 + | +--rw burst? number64 +--rw receive +--rw delay? uint64 +--rw jitter? uint64 @@ -197,6 +208,25 @@ For example, to shape both directions between ``wan1`` and ``r1``:: delay: 2500 rate: { rate: "5M", burst: 16384, limit: 131072 } +A connection's ``transmit`` may also list ``peers`` to give traffic from a +specific sending node on the network its own parameters, so each pair of nodes +can have different link quality in each direction. Parameters not given for a +peer are taken from the connection's ``transmit`` (and the node's ``receive``). +Traffic is classified by the bridge port it arrived on, so this also applies to +broadcast and multicast. For example, to make ``r1`` to ``r2`` slow and lossy +while other nodes reach ``r2`` with the default delay:: + + networks: + - name: radio + connections: + - to: r2 + transmit: + delay: 1000 + peers: + - peer: r1 + delay: 20000 + loss: 5 + Nodes ^^^^^ diff --git a/munet/base.py b/munet/base.py index c44b2d4..b4cdf01 100644 --- a/munet/base.py +++ b/munet/base.py @@ -1783,18 +1783,17 @@ def get_number(c, v, d=None): return netem_args, tbf_args - def _add_tc_qdiscs(self, nsifname, constraints): + def _add_tc_qdiscs(self, nsifname, constraints, parent="root", handle=1): + """Add netem then tbf under `parent`, using qdisc handles from `handle`.""" netem_args, tbf_args = self.get_linux_tc_args(nsifname, constraints) if not netem_args and not tbf_args: return False - count = 1 - selector = f"root handle {count}:" + selector = f"{parent} handle {handle:x}:" if netem_args: self.cmd_raises( f"tc qdisc add dev {nsifname} {selector} netem {netem_args}" ) - count += 1 - selector = f"parent {count-1}: handle {count}" + selector = f"parent {handle:x}: handle {handle + 1:x}:" # Place rate limit after delay otherwise limit/burst too complex if tbf_args: self.cmd_raises(f"tc qdisc add dev {nsifname} {selector} tbf {tbf_args}") @@ -1821,16 +1820,64 @@ def set_intf_constraints(self, ifname, **constraints): """ self._add_tc_qdiscs(self.get_ns_ifname(ifname), constraints) - def set_intf_ingress_constraints(self, ifname, **constraints): + def set_intf_peer_constraints(self, ifname, constraints, peers): + """Set interface outbound constraints that depend on the sender. + + Packets are classified by the skb mark set where they entered this + namespace (see `set_intf_ingress_constraints()`). Each (mark, + constraints) pair in `peers` gets its own class; all other packets use + `constraints`. + + Args: + ifname: the name of the interface + constraints (dict): constraints for packets not matching a peer. + peers (list): (mark, constraints) pairs. + """ + nsifname = self.get_ns_ifname(ifname) + self.cmd_raises(f"tc qdisc add dev {nsifname} root handle 1: drr") + classes = [(None, constraints)] + list(peers) + for minor, (mark, c) in enumerate(classes, start=1): + classid = f"1:{minor:x}" + self.cmd_raises( + f"tc class add dev {nsifname} parent 1: classid {classid} drr" + ) + # Each class uses qdisc handles 2*minor (netem) and 2*minor+1 (tbf). + self._add_tc_qdiscs( + nsifname, c, parent=f"parent {classid}", handle=2 * minor + ) + if mark is not None: + self.cmd_raises( + f"tc filter add dev {nsifname} parent 1: protocol all " + f"prio 1 handle {mark} fw classid {classid}" + ) + # drr drops unclassified packets, so send the rest to the default class. + self.cmd_raises( + f"tc filter add dev {nsifname} parent 1: protocol all prio 2 " + "matchall classid 1:1" + ) + self.cmd_raises(f"tc qdisc show dev {nsifname}") + + def set_intf_ingress_constraints(self, ifname, mark=None, **constraints): """Shape packets arriving on ifname via an IFB in this namespace. Used on a switch port so a node's delay/rate/loss still apply to that node's outbound traffic (same as a qdisc on the node NIC) without - taking the node's root qdisc. + taking the node's root qdisc. If `mark` is given, arriving packets are + also tagged with that skb mark so the egress port can classify them by + sender (see `set_intf_peer_constraints()`). """ nsifname = self.get_ns_ifname(ifname) netem_args, tbf_args = self.get_linux_tc_args(nsifname, constraints) - if not netem_args and not tbf_args: + shape = bool(netem_args or tbf_args) + if not shape and mark is None: + return + self.cmd_raises(f"tc qdisc add dev {nsifname} handle ffff: ingress") + if mark is not None: + self.cmd_raises( + f"tc filter add dev {nsifname} parent ffff: protocol all prio 1 " + f"matchall action skbedit mark {mark} continue" + ) + if not shape: return ifb = "ifb" + re.sub(r"[^A-Za-z0-9]", "", nsifname) ifb = ifb[:15] or "ifb0" @@ -1839,9 +1886,8 @@ def set_intf_ingress_constraints(self, ifname, **constraints): commander.cmd_status("modprobe ifb", warn=False) self.cmd_raises(f"ip link add {ifb} type ifb") self.cmd_raises(f"ip link set {ifb} up") - self.cmd_raises(f"tc qdisc add dev {nsifname} handle ffff: ingress") self.cmd_raises( - f"tc filter add dev {nsifname} parent ffff: protocol all " + f"tc filter add dev {nsifname} parent ffff: protocol all prio 2 " f"u32 match u32 0 0 action mirred egress redirect dev {ifb}" ) self._add_tc_qdiscs(ifb, constraints) diff --git a/munet/munet-schema.json b/munet/munet-schema.json index b97c7fa..186d097 100644 --- a/munet/munet-schema.json +++ b/munet/munet-schema.json @@ -815,6 +815,67 @@ ] } } + }, + "peers": { + "type": "array", + "items": { + "type": "object", + "properties": { + "peer": { + "type": "string" + }, + "delay": { + "type": "integer" + }, + "jitter": { + "type": "integer" + }, + "jitter-correlation": { + "type": "string" + }, + "loss": { + "type": "integer" + }, + "loss-correlation": { + "type": "string" + }, + "rate": { + "type": "object", + "properties": { + "rate": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "limit": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + }, + "burst": { + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + } + } + } + } } } }, diff --git a/munet/native.py b/munet/native.py index e8077f0..12d553e 100644 --- a/munet/native.py +++ b/munet/native.py @@ -3006,6 +3006,7 @@ def __init__( self.built = False self.tapcount = 0 + self.tc_marks = {} self.cmd_raises(f"mkdir -p {self.rundir} && chmod 755 {self.rundir}") self.set_ns_cwd(self.rundir) @@ -3374,6 +3375,18 @@ def _tc_receive(config): return {} return Munet._tc_pick(config.get("receive")) + @staticmethod + def _tc_peers(config): + """TC from ``transmit/peers``, keyed by the sending peer's name.""" + if not config: + return {} + peers = (config.get("transmit") or {}).get("peers") or [] + return {p["peer"]: Munet._tc_pick(p) for p in peers} + + def _tc_mark(self, name): + """Return the skb mark that tags traffic sent by node `name`.""" + return self.tc_marks.setdefault(name, len(self.tc_marks) + 1) + async def add_native_link(self, node1, node2, c1=None, c2=None): """Add a link between switch and node or 2 nodes.""" isp2p = False @@ -3459,10 +3472,24 @@ async def add_native_link(self, node1, node2, c1=None, c2=None): # Node values win on overlapping keys. toward_node = {**Munet._tc_transmit(c1), **Munet._tc_receive(c2)} from_node = {**Munet._tc_receive(c1), **Munet._tc_transmit(c2)} - if toward_node: + # Per-peer transmit overrides classify on the skb mark that the + # sender's port sets on ingress, so every port of a network that + # uses peers marks what it receives. + peers = Munet._tc_peers(c1) + if peers: + peer_tc = [ + (self._tc_mark(peer), {**toward_node, **tc}) + for peer, tc in peers.items() + ] + node1.set_intf_peer_constraints(if1, toward_node, peer_tc) + elif toward_node: node1.set_intf_constraints(if1, **toward_node) - if from_node: - node1.set_intf_ingress_constraints(if1, **from_node) + mark = None + netconns = node1.config.get("connections") or [] + if peers or any(Munet._tc_peers(c) for c in netconns): + mark = self._tc_mark(node2.name) + if from_node or mark is not None: + node1.set_intf_ingress_constraints(if1, mark=mark, **from_node) def add_l3_node(self, name, config=None, **kwargs): """Add a node to munet.""" diff --git a/tests/basic/test_switch_constraints.py b/tests/basic/test_switch_constraints.py index 3cfb69d..48926d1 100644 --- a/tests/basic/test_switch_constraints.py +++ b/tests/basic/test_switch_constraints.py @@ -7,6 +7,7 @@ import logging import re +from copy import deepcopy import pytest @@ -134,6 +135,59 @@ def test_tc_directions(): assert rx == {"delay": 3000} assert Munet._tc_transmit({"delay": 1000}) == {"delay": 1000} + assert not Munet._tc_peers(None) + assert not Munet._tc_peers(conf) + peers = Munet._tc_peers( + {"transmit": {"peers": [{"peer": "r1", "delay": 10, "name": "x"}]}} + ) + assert peers == {"r1": {"delay": 10}} + assert "peers" not in Munet._tc_transmit({"transmit": {"peers": []}}) + + +@pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) +async def test_switch_transmit_peers(unet_case): + """Per-peer transmit shapes only that peer's traffic toward the node.""" + unet = unet_case + unet.autonumber = True + + peer_delay = 50000 + default_delay = 10000 + r2conn = { + "to": "r2", + "transmit": { + "delay": default_delay, + "peers": [{"peer": "r1", "delay": peer_delay}], + }, + } + sw1 = unet.add_network("sw1", {"ip": "auto", "connections": [r2conn]}) + r1 = unet.add_l3_node("r1") + r2 = unet.add_l3_node("r2") + r3 = unet.add_l3_node("r3") + + # Link r2 before its peer r1 so marks do not depend on link order. + await unet.add_native_link(sw1, r2, deepcopy(r2conn), {}) + await unet.add_native_link(sw1, r1, {}, {}) + await unet.add_native_link(sw1, r3, {}, {}) + + s2q = await sw1.async_cmd_raises(f"tc qdisc show dev {sw1.intfs[0]}") + logging.info("r2 switch port qdiscs: %s", s2q) + assert "drr" in s2q + r2q = await r2.async_cmd_raises(f"tc qdisc show dev {r2.net_intfs[sw1.name]}") + assert "netem" not in r2q + + # One way delays: r1 -> r2 peer_delay, r3 -> r2 default_delay, rest none. + avg = await ping_average_rtt(r1, r2, r2.net_intfs[sw1.name]) + logging.info("r1 <-> r2 RTT: %s", avg) + assert (peer_delay / 1000 - 1) < avg < (peer_delay / 1000 + 2) + + avg = await ping_average_rtt(r3, r2, r2.net_intfs[sw1.name]) + logging.info("r3 <-> r2 RTT: %s", avg) + assert (default_delay / 1000 - 1) < avg < (default_delay / 1000 + 2) + + avg = await ping_average_rtt(r1, r3, r3.net_intfs[sw1.name]) + logging.info("r1 <-> r3 RTT: %s", avg) + assert avg < 2 + @pytest.mark.parametrize("unet_case", [False, True], indirect=["unet_case"]) async def test_switch_legacy_transmit_only(unet_case): diff --git a/tests/config/qdisc/munet.yaml b/tests/config/qdisc/munet.yaml index 9498ebb..545fddc 100644 --- a/tests/config/qdisc/munet.yaml +++ b/tests/config/qdisc/munet.yaml @@ -19,6 +19,9 @@ topology: - to: h4 transmit: delay: 2000 + peers: + - peer: h1 + delay: 4000 receive: delay: 3000 diff --git a/tests/config/qdisc/test_qdisc_cmd.py b/tests/config/qdisc/test_qdisc_cmd.py index 14aa969..7248d23 100644 --- a/tests/config/qdisc/test_qdisc_cmd.py +++ b/tests/config/qdisc/test_qdisc_cmd.py @@ -74,10 +74,13 @@ async def test_config_cmd(unet_share): assert "delay" not in output assert "loss" not in output - # Toward h4: network transmit plus h4 receive, on the switch port. + # Toward h4: network transmit plus h4 receive, on the switch port. Traffic + # from h1 gets its own class with the peer delay. output = unet.cmd_raises("tc q | grep 'dev net1-e3'") logging.debug("qdisc for dev net1-e3 (h4 RX) found: %s", output) + assert "drr" in output assert re.search(r"delay 2ms.*loss 10%", output, re.DOTALL) + assert re.search(r"delay 4ms.*loss 10%", output, re.DOTALL) # From h4: network receive plus h4 transmit, on the switch IFB. output = net1.cmd_raises("tc q | grep 'dev ifbnet1e3'")