diff --git a/munet/__main__.py b/munet/__main__.py index 8ca5575..719f2a7 100644 --- a/munet/__main__.py +++ b/munet/__main__.py @@ -21,6 +21,7 @@ from .cleanup import cleanup_previous from .cleanup import is_running_in_rundir from .compat import PytestConfig +from .exceptions import MunetConfigError logger = None @@ -207,8 +208,10 @@ def main(*args): status = asyncio.get_event_loop().run_until_complete(async_main(args, config)) except KeyboardInterrupt: logger.info("Exiting, received KeyboardInterrupt in main") + except MunetConfigError as error: + logger.critical("Exiting, topology config error: %s", error) except Exception as error: - logger.info("Exiting, unexpected exception %s", error, exc_info=True) + logger.info("Exiting, unexpected exception: %s", error, exc_info=True) return status diff --git a/munet/base.py b/munet/base.py index 8ff9c79..8026727 100644 --- a/munet/base.py +++ b/munet/base.py @@ -29,6 +29,7 @@ from . import config as munet_config from . import linux +from .exceptions import MunetConfigError try: import pexpect @@ -50,10 +51,6 @@ detailed_cmd_logging = False -class MunetError(Exception): - """A generic munet error.""" - - class CalledProcessError(subprocess.CalledProcessError): """Improved logging subclass of subprocess.CalledProcessError.""" @@ -2740,13 +2737,14 @@ def __init__(self, name=None, mtu=None, unet=None, **kwargs): super().__init__(name, pid=unet_pid, nsflags=unet.nsflags, unet=unet, **kwargs) - self.set_intf_basename(self.name + "-e") + self.set_intf_basename("br{}".format(self.id) + "-e") self.mtu = mtu self.logger.debug("Bridge: Creating") - # assert len(self.name) <= 16 # Make sure fits in IFNAMSIZE + if len(name) >= 16: # Make sure fits in IFNAMSIZE + raise MunetConfigError(f"Bridge name exceeds 15 chars: {name!r}") self.cmd_raises(f"ip link delete {name} || true") self.cmd_raises(f"ip link add {name} type bridge") if self.mtu: @@ -2956,18 +2954,22 @@ def add_link(self, node1, node2, if1, if2, mtu=None, **intf_constraints): node2 = self.hosts[node2] name2 = node2.name + hostnames = () if name1 in self.switches: - assert name2 in self.hosts + hostnames = (name2,) elif name2 in self.switches: - assert name1 in self.hosts + hostnames = (name1,) name1, name2 = name2, name1 if1, if2 = if2, if1 else: # p2p link - assert name1 in self.hosts - assert name2 in self.hosts + hostnames = (name1, name2) isp2p = True + for name in hostnames: + if name not in self.hosts: + raise MunetConfigError(f"Unknown host: {name!r}") + lname = "{}:{}-{}:{}".format(name1, if1, name2, if2) self.logger.debug("%s: add_link %s%s", self, lname, " p2p" if isp2p else "") self.links[lname] = (name1, if1, name2, if2) @@ -3008,11 +3010,16 @@ def add_link(self, node1, node2, if1, if2, mtu=None, **intf_constraints): if mtu is None: mtu = switch.mtu - if len(nsif1) > 16: - self.logger.error('"%s" len %s > 16', nsif1, len(nsif1)) - elif len(nsif2) > 16: - self.logger.error('"%s" len %s > 16', nsif2, len(nsif2)) - assert len(nsif1) < 16 and len(nsif2) < 16 # Make sure fits in IFNAMSIZE + if len(nsif1) >= 16: + self.logger.error('"%s" len %s >= 16', nsif1, len(nsif1)) + elif len(nsif2) >= 16: + self.logger.error('"%s" len %s >= 16', nsif2, len(nsif2)) + + # Make sure fits in IFNAMSIZE + if len(nsif1) >= 16: + raise MunetConfigError(f"Interface name exceeds 15 chars: {nsif1!r}") + if len(nsif2) >= 16: + raise MunetConfigError(f"Interface name exceeds 15 chars: {nsif2!r}") self.logger.debug("%s: Creating veth pair for link %s", self, lname) diff --git a/munet/config.py b/munet/config.py index 8df91df..11427d7 100644 --- a/munet/config.py +++ b/munet/config.py @@ -13,6 +13,7 @@ from copy import deepcopy from typing import overload +from .exceptions import MunetConfigError def find_with_kv(lst, k, v): if lst: @@ -58,7 +59,7 @@ def merge_using_key(a, b, k): def list_to_dict_with_key(lst, k): - """Convert a YANG styl list of objects to dict of objects. + """Convert a YANG style list of objects to dict of objects. This function converts a YANG style list of objects (dictionaries) to a plain python dictionary of objects (dictionaries). The value for the supplied key for each @@ -70,10 +71,19 @@ def list_to_dict_with_key(lst, k): lst: a *list* of python dictionary objects. k: the key value contained in each dictionary object in the list. + Raises: + MunetConfigError if duplicate keys are present + Returns: A dictionary of objects (dictionaries). """ - return {x[k]: x for x in (lst if lst else [])} + result = {} + for x in lst or []: + key = x[k] + if key in result: + raise MunetConfigError(f"Duplicate '{k}' value: {key!r}") + result[key] = x + return result def config_to_dict_with_key(c, ck, k): @@ -87,10 +97,16 @@ def config_to_dict_with_key(c, ck, k): ck: The key identifying the list of objects from ``c``. k: The key to pass to :py:func:`list_to_dict_with_key`. + Raises: + MunetConfigError if duplicate keys are present + Returns: A dictionary of objects (dictionaries). """ - c[ck] = list_to_dict_with_key(c.get(ck, []), k) + try: + c[ck] = list_to_dict_with_key(c.get(ck, []), k) + except MunetConfigError as error: + raise MunetConfigError(f"Invalid '{ck}' configuration: {error}") from error return c[ck] diff --git a/munet/exceptions.py b/munet/exceptions.py new file mode 100644 index 0000000..2383316 --- /dev/null +++ b/munet/exceptions.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# November 18 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"""A module that defines munet exceptions.""" + + +class MunetError(Exception): + """A generic munet error.""" + + +class MunetConfigError(MunetError): + """Invalid munet topology or configuration.""" diff --git a/munet/mutest/__main__.py b/munet/mutest/__main__.py index 68d799d..18f30f6 100644 --- a/munet/mutest/__main__.py +++ b/munet/mutest/__main__.py @@ -26,6 +26,7 @@ from munet.base import Bridge from munet.cli import async_cli from munet.compat import PytestConfig +from munet.exceptions import MunetConfigError from munet.mutest import userapi as uapi from munet.native import L3NodeMixin from munet.native import Munet @@ -69,6 +70,9 @@ async def get_unet( pytestconfig=PytestConfig(args), unshare_inline=unshare, ) + except MunetConfigError as error: + # Config errors are expected user errors; propagate without a traceback. + raise except Exception as error: logging.debug("unet build failed: %s", error, exc_info=True) raise @@ -327,6 +331,9 @@ async def run_tests(args): errlog.warning("KeyboardInterrupt while running test %s", test_name) passed, failed, e = 0, 0, error raise + except MunetConfigError as error: + errlog.error("Topology error in test %s: %s", test, error) + passed, failed, e = 0, 0, error except Exception as error: logging.error( "Error executing test %s: %s", test, error, exc_info=True diff --git a/munet/native.py b/munet/native.py index acc5d0e..4bef153 100644 --- a/munet/native.py +++ b/munet/native.py @@ -38,7 +38,6 @@ from .base import Commander from .base import InterfaceMixin from .base import LinuxNamespace -from .base import MunetError from .base import SharedNamespace from .base import Timeout from .base import _async_get_exec_path @@ -52,6 +51,8 @@ from .config import find_matching_net_config from .config import find_with_kv from .config import merge_kind_config +from .exceptions import MunetError +from .exceptions import MunetConfigError from .watchlog import WatchLog AUTO_LOOPBACK_IPV4_BASE = ipaddress.ip_interface("10.255.0.0/32") @@ -107,7 +108,8 @@ def get_ip_network(c, brid, ipv6=False): return ifip except ValueError: return ipaddress.ip_network(ip) - assert brid < 0xFDFF # Limited to 10.0.0.0/16 through 10.253.0.0/16 blocks + if brid >= 0xFDFF: # Limited to 10.0.0.0/16 through 10.253.0.0/16 blocks + raise MunetConfigError("Bridge IDs exhausted (0xFDFF Max)") if ipv6: return make_ip_interface("fc00::fe/64", brid) return make_ip_interface("10.0.0.254/24", brid) @@ -792,7 +794,8 @@ def __init__(self, *args, unet=None, **kwargs): self.cmd_raises("sysctl -w net.ipv6.conf.all.disable_ipv6=0") self.cmd_raises("sysctl -w net.ipv6.conf.all.forwarding=1") - assert self.id < 0x7FFF # Limited to 10.254.0.0/16 block + if self.id >= 0x7FFF: # Limited to 10.254.0.0/16 block + raise MunetConfigError("Node IDs exhausted (0x7FFF Max)") self.next_p2p_network = ipaddress.ip_network( f"10.254.{self.id & 0xFF}.{(self.id & 0x7F00) >> 7}/31" ) @@ -986,13 +989,15 @@ def get_ifname(self, netname): def set_dummy_addr(self, cconf): if ip := cconf.get("ip"): ipaddr = ipaddress.ip_interface(ip) - assert ipaddr.version == 4 + if ipaddr.version != 4: + raise MunetConfigError(f"'ip' address {ip!r} is not IPv4") else: ipaddr = None if ip := cconf.get("ipv6"): ip6addr = ipaddress.ip_interface(ip) - assert ip6addr.version == 6 + if ip6addr.version != 6: + raise MunetConfigError(f"'ipv6' address {ip!r} is not IPv6'") else: ip6addr = None @@ -1011,7 +1016,8 @@ def set_dummy_addr(self, cconf): def set_lan_addr(self, switch, cconf): if ip := cconf.get("ip"): ipaddr = ipaddress.ip_interface(ip) - assert ipaddr.version == 4 + if ipaddr.version != 4: + raise MunetConfigError(f"'ip' address {ip!r} is not IPv4") elif self.unet.autonumber and "ip" not in cconf: self.logger.debug( "%s: prefixlen of switch %s is %s", @@ -1026,7 +1032,8 @@ def set_lan_addr(self, switch, cconf): if ip := cconf.get("ipv6"): ip6addr = ipaddress.ip_interface(ip) - assert ipaddr.version == 6 + if ip6addr.version != 6: + raise MunetConfigError(f"'ipv6' address {ip!r} is not IPv6") elif self.unet.ipv6_enable and self.unet.autonumber and "ipv6" not in cconf: self.logger.debug( "%s: prefixlen of switch %s is %s", @@ -1351,7 +1358,8 @@ def __init__(self, name, config, **kwargs): self.container_id = None self.container_image = config["image"] self.extra_mounts = [] - assert self.container_image + if not self.container_image: + raise MunetConfigError("Container 'image' is missing") self.cmd_p = None self.cmd_pid = None @@ -1788,7 +1796,8 @@ def __init__(self, name, config, **kwargs): self.launch_pid = None self.qemu_config = config["qemu"] self.extra_mounts = [] - assert self.qemu_config + if not self.qemu_config: + raise MunetConfigError("'qemu' config is missing") self.cmdrepl = None self.conrepl = None self.is_kvm = False @@ -1973,7 +1982,10 @@ def mount_volumes(self): if not self.test_nsonly("-e", src): self.cmd_raises_nsonly(f"mkdir -p {src}") dst = m.get("dst", m.get("destination")) - assert dst, "destination path required for mount" + if not dst: + raise MunetConfigError( + f"'destination' path of mount {src!r} is missing" + ) # Implicitly guess "bind" or "tmpfs". Alternatives are manually specified. mtype = "tmpfs" if src == "" else "bind" @@ -1983,7 +1995,8 @@ def mount_volumes(self): if k in ["destination", "dst", "source", "src"]: continue if k == "type": - assert v in ["bind", "tmpfs", "usb"] + if not v in ["bind", "tmpfs", "usb"]: + raise MunetConfigError(f"Mount {src!r} type {v!r} is unknown") mtype = v continue if not v: @@ -2249,7 +2262,7 @@ async def mount_mounts(self): elif mtype == "usb": con.cmd_raises(f"test -d {mp}") # Directory should already exist! else: - assert False, "Unknown L3QemuVM mount option" + raise MunetConfigError(f"Mount option {mtype!r} is unknown") async def renumber_interfaces(self): """Re-number the interfaces. @@ -2517,9 +2530,10 @@ def _gen_cloud_init(self): if not geniso: mfbin = get_exec_path_host("mkfs.vfat") mcbin = get_exec_path_host("mcopy") - assert ( - mfbin and mcbin - ), "genisoimage or mkfs.vfat,mcopy needed to gen cloud-init disk" + if not (mfbin and mcbin): + raise MunetConfigError( + "genisoimage or mkfs.vfat,mcopy needed to gen cloud-init disk" + ) # # cloud-init: meta-data @@ -2534,7 +2548,10 @@ def _gen_cloud_init(self): ssh_auth_s = "" if bool(self.ssh_keyfile): pubkey = commander.cmd_raises(f"ssh-keygen -y -f {self.ssh_keyfile}") - assert pubkey, f"Can't extract public key from {self.ssh_keyfile}" + if not pubkey: + raise MunetConfigError( + f"Can't extract public key from {self.ssh_keyfile!r}" + ) pubkey = pubkey.strip() ssh_auth_s = f'ssh_authorized_keys: ["{pubkey}"]' @@ -3293,7 +3310,11 @@ async def _async_build(self, logger=None): await self.add_native_link(switch, node, swconf, cconf) elif cconf["name"] not in node.intfs: # Only add the p2p interface if not already there. - other = self.hosts[to] + other = self.hosts.get(to, None) + if not other: + raise MunetConfigError( + f"'connection' from {name!r} to non-existent node {to!r}" + ) oconf = find_matching_net_config(name, cconf, other.config) await self.add_native_link(node, other, cconf, oconf) @@ -3339,19 +3360,30 @@ async def add_native_link(self, node1, node2, c1=None, c2=None): c1 = {} if c1 is None else c1 c2 = {} if c2 is None else c2 + hostnames = () if node1.name in self.switches: - assert node2.name in self.hosts + hostnames = (node2.name,) elif node2.name in self.switches: - assert node1.name in self.hosts + hostnames = (node1.name,) node1, node2 = node2, node1 c1, c2 = c2, c1 else: # p2p link - assert node1.name in self.hosts - assert node1.name in self.hosts - assert c1 and c2 + hostnames = (node1.name, node2.name) + if not c1: + raise MunetConfigError( + f"'connection' to {node2.name!r} is missing from {node1.name!r}" + ) + if not c2: + raise MunetConfigError( + f"'connection' to {node1.name!r} is missing from {node2.name!r}" + ) isp2p = True + for name in hostnames: + if name not in self.hosts: + raise MunetConfigError(f"Unknown host: {name!r}") + if "name" not in c1: c1["name"] = node1.get_next_intf_name() if1 = c1["name"] @@ -3369,10 +3401,24 @@ async def add_native_link(self, node1, node2, c1=None, c2=None): await n.add_phy_intf(c["physical"], c["name"]) do_add_link = False if do_add_link: - assert "hostintf" not in c1 - assert "hostintf" not in c2 - assert "physical" not in c1 - assert "physical" not in c2 + # pylint: disable=line-too-long + if "hostintf" in c1: + raise MunetConfigError( + f"'hostintf' unexpectedly configured in 'connection' {node1.name!r} to {node2.name!r}" + ) + if "hostintf" in c2: + raise MunetConfigError( + f"'hostintf' unexpectedly configured in 'connection' {node2.name!r} to {node1.name!r}" + ) + if "physical" in c1: + raise MunetConfigError( + f"'physical' unexpectedly configured in 'connection' {node1.name!r} to {node2.name!r}" + ) + if "physical" in c2: + raise MunetConfigError( + f"'physical' unexpectedly configured in 'connection' {node2.name!r} to {node1.name!r}" + ) + # pylint: enable=line-too-long if isp2p: mtu1 = c1.get("mtu") @@ -3438,9 +3484,10 @@ def coverage_setup(self): common = os.path.commonprefix([common, f]) if not common: break - assert ( - bdir - ), "Can't locate build directory for coverage data, use --cov-build-dir" + if not bdir: + raise MunetConfigError( + "Can't locate build directory for coverage data, use --cov-build-dir" + ) bdir = Path(bdir).resolve() rundir = Path(self.rundir).resolve() @@ -3505,7 +3552,8 @@ async def load_images(self, images): if not tasks: return _, pending = await asyncio.wait(tasks, timeout=600) - assert not pending, "Failed to pull container images" + if pending: + raise MunetConfigError("Failed to pull container images") async def run(self): tasks = [] diff --git a/munet/parser.py b/munet/parser.py index b98353a..c56ea56 100644 --- a/munet/parser.py +++ b/munet/parser.py @@ -30,7 +30,8 @@ except ImportError: jsonschema = None -from .config import list_to_dict_with_key +from .config import config_to_dict_with_key +from .exceptions import MunetConfigError from .native import Munet @@ -261,8 +262,7 @@ def load_kinds(args, search=None): # validator = jsonschema.validators.Draft202012Validator(get_schema()) # validator.validate(instance=config) - kinds_list = config.get("kinds", []) - kinds_dict = list_to_dict_with_key(kinds_list, "name") + kinds_dict = config_to_dict_with_key(config, "kinds", "name") if kinds_dict: logging.info("Loading kinds config from %s", config["config_pathname"]) if "kinds" in kinds: @@ -324,7 +324,7 @@ async def async_build_topology( # load kinds along search path and merge into config kinds = load_kinds(args, search=search) - config_kinds_dict = list_to_dict_with_key(config.get("kinds", []), "name") + config_kinds_dict = config_to_dict_with_key(config, "kinds", "name") config["kinds"] = {**kinds.get("kinds", {}), **config_kinds_dict} # mere CLI command from kinds into config as well. @@ -356,6 +356,10 @@ async def async_build_topology( try: await unet._async_build(logger) # pylint: disable=W0212 + except MunetConfigError as error: + logging.critical("Failure building munet topology: %s", error) + await unet.async_delete() + raise except Exception as error: logging.critical("Failure building munet topology: %s", error, exc_info=True) await unet.async_delete() diff --git a/tests/config/intf-limits/munet.yaml b/tests/config/intf-limits/munet.yaml new file mode 100644 index 0000000..d8e81ea --- /dev/null +++ b/tests/config/intf-limits/munet.yaml @@ -0,0 +1,12 @@ +version: 1 +topology: + networks-autonumber: true + networks: + - name: net-max-15-char + nodes: + - name: node-max-unlimited-char + connections: + - to: net-max-15-char + name: itf-max-15-char + + diff --git a/tests/config/intf-limits/test_intf_limits.py b/tests/config/intf-limits/test_intf_limits.py new file mode 100644 index 0000000..2144525 --- /dev/null +++ b/tests/config/intf-limits/test_intf_limits.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 eval: (blacken-mode 1) -*- +# SPDX-License-Identifier: GPL-2.0-or-later +# +# November 18 2026, Liam Brady +# +# Copyright 2026, LabN Consulting, L.L.C. +# +"Testing of intf config limits" + +import pytest + +# All tests are coroutines +pytestmark = pytest.mark.asyncio + + +async def test_config_intf_limits(unet_share): + unet = unet_share + rn = unet.hosts["node-max-unlimited-char"] + output = rn.cmd_raises("ip link") + assert "itf-max-15-char" in output + + output = unet.cmd_raises("ip link") + assert "net-max-15-char" in output + assert "br1-e0" in output diff --git a/tests/config/qdisc/test_qdisc_cmd.py b/tests/config/qdisc/test_qdisc_cmd.py index 00184e0..c4c8e43 100644 --- a/tests/config/qdisc/test_qdisc_cmd.py +++ b/tests/config/qdisc/test_qdisc_cmd.py @@ -19,18 +19,18 @@ async def test_config_cmd(unet_share): unet = unet_share - output = unet.cmd_raises("tc q | grep 'dev net1-e0'") - logging.debug("qdisc for dev net1-e0 output found: %s", output) + output = unet.cmd_raises("tc q | grep 'dev br1-e0'") + logging.debug("qdisc for dev br1-e0 output found: %s", output) logging.debug("expects delay='16', jitter='30', loss='40', rate='800'") assert re.search(r"delay 16us\s+29us.*loss 40%.*rate 800bit", output, re.DOTALL) - output = unet.cmd_raises("tc q | grep 'dev net1-e1'") - logging.debug("qdisc for dev net1-e1 output found: %s", output) + output = unet.cmd_raises("tc q | grep 'dev br1-e1'") + logging.debug("qdisc for dev br1-e1 output found: %s", output) logging.debug("expects delay='6', jitter='20', loss='50', rate='810'") assert re.search(r"delay 17us\s+27us.*loss 38%.*rate 808bit", output, re.DOTALL) - output = unet.cmd_raises("tc q | grep 'dev net1-e2'") - logging.debug("qdisc for dev net1-e2 output found: %s", output) + output = unet.cmd_raises("tc q | grep 'dev br1-e2'") + logging.debug("qdisc for dev br1-e2 output found: %s", output) logging.debug("expects delay='13'") assert "delay 13us" in output assert "loss" not in output