diff --git a/scripts/build_deb.py b/scripts/build_deb.py index 82f7ced7..e7c86a07 100644 --- a/scripts/build_deb.py +++ b/scripts/build_deb.py @@ -65,7 +65,7 @@ AARCH64 = 183 # Explicit runtime manifest for the default slim .deb payload. RUNTIME_TOP_DIRS = frozenset({ - "runtime", "spark_transport", "integrations", "packaging", + "runtime", "spark_transport", "sparkring_fabric", "integrations", "packaging", "profiles", "recipes", "scripts", "third_party", }) RUNTIME_ROOT_FILES = frozenset({ diff --git a/scripts/check_repository_layout.py b/scripts/check_repository_layout.py index c4678777..42220a1d 100644 --- a/scripts/check_repository_layout.py +++ b/scripts/check_repository_layout.py @@ -39,7 +39,7 @@ def validate_locked_profile_assets(root=ROOT): def validate_imports(root=ROOT): paths = [] - for directory in ('runtime', 'integrations', 'scripts', 'spark_transport/fabric'): + for directory in ('runtime', 'integrations', 'scripts', 'spark_transport/fabric', 'sparkring_fabric'): paths.extend((root/directory).rglob('*.py')) for path in paths: tree = ast.parse(path.read_text(encoding='utf-8-sig'), filename=str(path)) diff --git a/spark_transport/libsircl/tests/test_site_routes.py b/spark_transport/libsircl/tests/test_site_routes.py index c4c232a1..f5df0536 100644 --- a/spark_transport/libsircl/tests/test_site_routes.py +++ b/spark_transport/libsircl/tests/test_site_routes.py @@ -30,14 +30,21 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] -PACKAGE = os.environ.get("SIRCL_PACKAGE", "") +REPO_ROOT = ROOT.parents[1] +FABRIC_PACKAGE = str(REPO_ROOT / "sparkring_fabric") SHARE = 393216 # 75 % of SIRCL's 512 KiB hairpin queue (routes.RELAY_QUEUE_SHARE x DEFAULT_HAIRPIN_QUEUE) +def _clean_env() -> dict[str, str]: + """Environment with no spark_transport/sircl on PYTHONPATH or SIRCL_PACKAGE.""" + env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "SIRCL_PACKAGE")} + env["PYTHONIOENCODING"] = "utf-8" + return env + + def plan(*arguments: str) -> dict: - environment = dict(os.environ, PYTHONPATH=PACKAGE, PYTHONIOENCODING="utf-8") process = subprocess.run([sys.executable, str(ROOT / "tools" / "site_routes.py"), *arguments, "--json"], - env=environment, capture_output=True, text=True, timeout=120) + env=_clean_env(), capture_output=True, text=True, timeout=120) if process.returncode: raise AssertionError(f"site_routes.py {' '.join(arguments)}: {process.stderr}") return json.loads(process.stdout) @@ -52,13 +59,17 @@ def windows(text: str) -> dict[int, list[int]]: return found -@unittest.skipUnless(PACKAGE and (Path(PACKAGE) / "sparkring_sircl").is_dir(), - "SIRCL_PACKAGE does not name a directory holding sparkring_sircl") +@unittest.skipUnless((Path(FABRIC_PACKAGE) / "sparkring_fabric").is_dir(), + "sparkring_fabric package directory is not present") class SiteRoutesP2PTests(unittest.TestCase): @classmethod def setUpClass(cls): - sys.path.insert(0, PACKAGE) - from sparkring_sircl import routes + if FABRIC_PACKAGE not in sys.path: + sys.path.insert(0, FABRIC_PACKAGE) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + from sparkring_fabric import routes cls.routes = routes @@ -157,7 +168,7 @@ def test_session_shares_outside_zero_to_one_are_refused(self): with self.subTest(value=value): process = subprocess.run([sys.executable, str(ROOT / "tools" / "site_routes.py"), "--layout", "ring:8", "--session-share", value], - env=dict(os.environ, PYTHONPATH=PACKAGE), capture_output=True, text=True, + env=_clean_env(), capture_output=True, text=True, timeout=120) self.assertEqual(process.returncode, 2) self.assertIn("--session-share", process.stderr) @@ -197,7 +208,7 @@ def test_a_plan_that_overfills_a_relay_queue_is_refused(self): one relay queue then hold more than its share, and the tool refuses the plan, naming the queue.""" process = subprocess.run([sys.executable, str(ROOT / "tools" / "site_routes.py"), "--layout", "path:0-7", "--lanes", "2", "--chunk", "65536"], - env=dict(os.environ, PYTHONPATH=PACKAGE), capture_output=True, text=True, + env=_clean_env(), capture_output=True, text=True, timeout=120) self.assertEqual(process.returncode, 1, process.stdout) self.assertIn("above its share of 393216", process.stderr) @@ -236,12 +247,38 @@ def test_ring_only_emits_neighbor_routes_without_relays(self): def test_ring_only_refuses_relayed_closing_edge(self): process = subprocess.run([sys.executable, str(ROOT / "tools" / "site_routes.py"), "--layout", "path:0-3", "--lanes", "2", "--ring-only"], - env=dict(os.environ, PYTHONPATH=PACKAGE), capture_output=True, text=True, + env=_clean_env(), capture_output=True, text=True, timeout=120) self.assertEqual(process.returncode, 1, process.stdout) self.assertIn("--ring-only", process.stderr) self.assertEqual(process.stdout, "") + def test_runs_without_sparkring_sircl_on_sys_path(self): + """site_routes.py depends only on sparkring_fabric and never imports sparkring_sircl.""" + script = ( + "import importlib.util, json, sys\n" + "class BlockSircl:\n" + " def find_spec(self, fullname, path, target=None):\n" + " if fullname == 'sparkring_sircl' or fullname.startswith('sparkring_sircl.'):\n" + " raise AssertionError(f'unexpected import of {fullname}')\n" + " return None\n" + "sys.meta_path.insert(0, BlockSircl())\n" + "assert not any('spark_transport/sircl' in p.replace('\\\\', '/') for p in sys.path)\n" + f"spec = importlib.util.spec_from_file_location('site_routes', {str(ROOT / 'tools' / 'site_routes.py')!r})\n" + "mod = importlib.util.module_from_spec(spec)\n" + "spec.loader.exec_module(mod)\n" + "rc = mod.main(['--layout', 'ring:8', '--lanes', '2', '--json'])\n" + "assert rc == 0, rc\n" + "assert 'sparkring_sircl' not in sys.modules\n" + "assert 'sparkring_fabric.routes' in sys.modules\n" + ) + process = subprocess.run([sys.executable, "-I", "-c", script], env=_clean_env(), + capture_output=True, text=True, timeout=120) + self.assertEqual(process.returncode, 0, process.stderr) + payload = json.loads(process.stdout) + self.assertEqual(payload["layout"], "ring:8") + self.assertEqual(len(payload["ranks"]), 8) + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/spark_transport/libsircl/tools/site_routes.py b/spark_transport/libsircl/tools/site_routes.py index 17159ef3..f8a6ebf1 100644 --- a/spark_transport/libsircl/tools/site_routes.py +++ b/spark_transport/libsircl/tools/site_routes.py @@ -1,13 +1,13 @@ #!/usr/bin/env python3 -"""Per-rank libsircl settings of a SIRCL layout, from SIRCL's own route planner. +"""Per-rank libsircl settings of a fabric layout, from sparkring_fabric's route planner. -For a layout such as ``path:0-1``, ``path:0-3`` or ``ring:8`` and a lane count, SIRCL's routes module -(``sparkring_sircl.routes``: ``Layout.parse``, ``derive_routes``, ``chain_order``, ``forward_windows``, -``ring_window`` and ``ring_queues``) gives every rank's route map, the chain order of cable neighbors, -the forward window of every lane that crosses relays and the plan of the ring that closes the chain, and -SIRCL's point-to-point budget (``sparkring_sircl.p2p.budget``: ``LaneSet``, ``session_reservation``, -``allocate``) the window of every relayed lane of a point-to-point channel. This tool prints them as -libsircl's environment, one line per rank (rank r of the layout runs at libsircl position r): +For a layout such as ``path:0-1``, ``path:0-3`` or ``ring:8`` and a lane count, ``sparkring_fabric.routes`` +(``Layout.parse``, ``derive_routes``, ``chain_order``, ``forward_windows``, ``ring_window`` and ``ring_queues``) +gives every rank's route map, the chain order of cable neighbors, the forward window of every lane that crosses +relays and the plan of the ring that closes the chain, and ``sparkring_fabric.budget`` (``LaneSet``, +``session_reservation``, ``allocate``) gives the window of every relayed lane of a point-to-point channel. +This tool has zero dependency on ``sparkring_sircl`` and prints them as libsircl's environment, one line per +rank (rank r of the layout runs at libsircl position r): LIBSIRCL_POSITION=r SIRCL_PEER_ROUTES=... LIBSIRCL_CHAIN_ORDER=... LIBSIRCL_RELAYED_LANES=... LIBSIRCL_FORWARD_WINDOWS=... LIBSIRCL_RING_WINDOW=... LIBSIRCL_P2P_WINDOWS=... @@ -60,15 +60,17 @@ layout whose ring closes over direct cables (zero relay rules, zero diagonal routes or queue pairs). Layouts whose ring has a relayed edge (such as ``path:0-3``) are refused with exit status 1. -Usage (SIRCL's package on PYTHONPATH, or installed): +Usage (runs uninstalled from a repository checkout, or with sparkring-fabric installed): python3 tools/site_routes.py --layout ring:8 --lanes 2 [--ring-only] [--p2p-reserve session|none] [--ring-schedules] [--session-share F] [--json] """ from __future__ import annotations import argparse +import importlib import json import sys +from pathlib import Path # The native layers' window caps: SIRCL's native proxy accepts a forward or ring window of 1 to 60 chunks # (ROCE_CREDIT - 4), its point-to-point library 1 to 120 chunks. @@ -77,6 +79,26 @@ P2P_MAX_CHUNKS = 120 +def _ensure_sparkring_fabric() -> None: + """Make standalone ``sparkring_fabric`` importable from a checkout without touching ``spark_transport/sircl``.""" + try: + importlib.import_module("sparkring_fabric.routes") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + def share_value(text: str) -> float: value = float(text) if not 0 < value <= 1: @@ -103,9 +125,8 @@ def main(argv: list[str] | None = None) -> int: help="the fraction of every relay queue's share the collective session is sized against") parser.add_argument("--json", action="store_true") args = parser.parse_args(argv) - from sparkring_sircl import routes - from sparkring_sircl.p2p import budget - from sparkring_sircl.p2p import protocol as p2p_protocol + _ensure_sparkring_fabric() + from sparkring_fabric import budget, routes layout = routes.Layout.parse(args.layout) group = routes.derive_routes(layout, args.lanes) @@ -120,10 +141,9 @@ def main(argv: list[str] | None = None) -> int: # link window chunk; a rank whose ring lanes cross a relay queue gets the window, the others 0. ring_window, problems, relayed = None, ["no chain order"], set() if order is not None: - from sparkring_sircl import protocol - ring_window, problems = routes.ring_window(layout, maps, order, chunk=protocol.LINK_WINDOW_CHUNK, + ring_window, problems = routes.ring_window(layout, maps, order, chunk=routes.LINK_WINDOW_CHUNK, queue_bytes=session_queue) - ring_window = min(ring_window, RING_MAX_CHUNKS * protocol.LINK_WINDOW_CHUNK) + ring_window = min(ring_window, RING_MAX_CHUNKS * routes.LINK_WINDOW_CHUNK) relayed = {rank for members in routes.ring_queues(layout, maps, order).values() for rank, _, _ in members} if args.ring_only: if order is None or problems or relayed: @@ -151,9 +171,9 @@ def main(argv: list[str] | None = None) -> int: for row in rows: print(" ".join(f"{name}={value}" for name, value in row["env"].items())) return 0 - # Point-to-point windows of every ordered pair's relayed lanes (SIRCL's p2p/budget.py). - p2p_max = p2p_protocol.DEFAULT_WINDOW_BYTES if args.p2p_max_window is None else args.p2p_max_window - p2p_chunk = p2p_protocol.DEFAULT_CHUNK_BYTES if args.p2p_chunk is None else args.p2p_chunk + # Point-to-point windows of every ordered pair's relayed lanes (sparkring_fabric.budget). + p2p_max = budget.DEFAULT_P2P_WINDOW_BYTES if args.p2p_max_window is None else args.p2p_max_window + p2p_chunk = budget.DEFAULT_P2P_CHUNK_BYTES if args.p2p_chunk is None else args.p2p_chunk lane_set = budget.LaneSet.of("layout", layout, args.lanes) reserved = {} if args.p2p_reserve == "session": diff --git a/spark_transport/sircl/sparkring_sircl/fabric/__init__.py b/spark_transport/sircl/sparkring_sircl/fabric/__init__.py index 2e954ae9..4a38904b 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/__init__.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/__init__.py @@ -1,40 +1,37 @@ -"""Relay plan installer for SIRCL ring sessions on a switchless ring of DGX Sparks. +"""Compatibility shim: canonical fabric relay installer now lives in ``sparkring_fabric.fabric``.""" -SIRCL sessions read host networking but never configure it: members of a -group that share no cable reach each other through ConnectX-7 relays, and the -relay plan is installed by site tooling before a session starts. This -subpackage is that tooling. It derives a layout's plan from SIRCL's own route -module (:mod:`sparkring_sircl.routes`), so the lanes SIRCL derives and the -relays installed cannot disagree, and it installs, compares and removes the -plan on the Sparks over SSH. SIRCL's session code never imports it. +from __future__ import annotations -Per Spark the plan holds: +import importlib +import sys +from pathlib import Path -- origin routes: a /32 route, scope link, over the lane's local network - device, with a permanent neighbour entry holding the adjacent Spark's MAC; -- relay count tags: one marker process per RDMA device (``mesh_marker.c``) - installs mlx5 RDMA-TX rules that rewrite the EtherType of RoCE packets to - each routed destination into ``TAG(k) = 0x88b4 + k``, ``k`` relays left; -- relay filters: on the ingress of the device that receives a relayed lane, a - hardware flower filter per tag that sets the next Spark's MAC, rewrites the - tag to ``TAG(k - 1)`` (``TAG(0)`` is IPv4) and redirects out of the other - port. +_SUBMODULES = ("layouts", "plan", "commands", "state", "diff", "ops", "report", "cli") -Layouts (:mod:`.layouts`): ``ring8`` (the universal relay table), ``2xTP4``, -``4xTP2`` and custom groups of consecutive Sparks, wrap-around included. With -several groups on one ring, routes and tags exist only for same-group -destinations on that group's members, and relay filters only where a member -lies inside a carried path of its own group. -Modules: :mod:`.layouts` (groups), :mod:`.plan` (derivation, isolation and -trace checks), :mod:`.commands` (shell commands and ownership marks), -:mod:`.state` (parsing what a Spark holds), :mod:`.diff` (comparison and -apply scripts), :mod:`.ops` (read, compare, apply), :mod:`.report` (text) and -:mod:`.cli` (``python -m sparkring_sircl.fabric``). The host-command -simulator for tests is :mod:`sparkring_sircl.testing.relay_hosts`. +def _ensure_sparkring_fabric() -> None: + try: + importlib.import_module("sparkring_fabric.fabric") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return -Status: implemented; CPU-tested against the simulator. The ``ring8`` plan -reproduces the universal relay table object for object; the table's shell -installer is the tests' reference (``tests/fabric_reference.py``). The -installer has not run on a ring. -""" + +_ensure_sparkring_fabric() +_canonical = importlib.import_module("sparkring_fabric.fabric") +for _name in _SUBMODULES: + _mod = importlib.import_module(f"sparkring_fabric.fabric.{_name}") + sys.modules[f"{__name__}.{_name}"] = _mod + setattr(_canonical, _name, _mod) +sys.modules[__name__] = _canonical diff --git a/spark_transport/sircl/sparkring_sircl/fabric/cli.py b/spark_transport/sircl/sparkring_sircl/fabric/cli.py index 84766859..fc2d6a27 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/cli.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/cli.py @@ -1,267 +1,30 @@ -"""``python -m sparkring_sircl.fabric ``: the relay plan installer. - -Commands and their safety classes (``RUNBOOK.md``, section "Relay plan -installer"): - -- ``plan`` (OFFLINE): a layout's relay plan, from a facts file or with - placeholders for addresses and MACs; -- ``facts`` (READ-ONLY REMOTE): the Sparks' fabric addresses and MACs as a - facts file for ``plan``; -- ``show`` (READ-ONLY REMOTE): the relay objects every Spark holds: routes, - neighbours, marker processes and relay filters, labelled by group; -- ``diff`` (READ-ONLY REMOTE): the Sparks compared with a layout's plan; -- ``up`` and ``down``: without ``--apply`` a dry run (READ-ONLY REMOTE) that - prints every change and the exact script per Spark; with ``--apply`` - (MUTATES HOST) the scripts run on the selected groups' Sparks, which are - then read again and compared with the plan to verify; -- ``marker``: the marker executable on every Spark (READ-ONLY REMOTE); with - ``--apply`` it is compiled and installed where it is missing (MUTATES HOST). - -Exit codes: 0 done (``diff``: no host changes); 1 ``diff`` found host -changes, a Spark was unreachable, or applying or verifying failed; 2 invalid -input; 3 blockers stopped a dry run or ``--apply``, or a group cannot be -planned. -""" +"""Compatibility shim: canonical implementation lives in ``sparkring_fabric.fabric.cli``.""" from __future__ import annotations -import argparse -import json +import importlib import sys from pathlib import Path -from .. import routes -from ..ring.site import Site, SiteError -from . import commands, layouts, ops, report -from . import plan as plan_mod -from .layouts import FabricError - -MARKER_SOURCE = Path(__file__).with_name("mesh_marker.c") - - -def _positions(text: str | None, size: int) -> list[int]: - if text is None or text.strip() == "all": - return list(range(size)) - return sorted({position for group in layouts.parse_groups(text, size) for position in group}) - - -def _layout(args, ring_size: int) -> layouts.FabricLayout: - return layouts.resolve(ring_size=ring_size, layout=args.layout, groups=args.groups, name=args.name, - relay_egress=args.relay_egress) - - -def _print_outcome(outcome: ops.Outcome, args, *, scripts: bool) -> None: - print(report.render_outcome(outcome, verbose=args.verbose, scripts=scripts)) - print(report.summary_line(outcome)) - - -def _route_check(outcome: ops.Outcome, site: Site, executor: ops.Executor, *, installed_only: bool) -> int: - """``ip route get`` of every lane destination on its origin Spark, as the harness and launcher check it.""" - if outcome.mode != "up" or not outcome.plans: - return 0 - problems = ops.check_lane_routes(site, outcome, executor, installed_only=installed_only) - checked = sum(len(found) for found in ops.lane_route_checks(outcome, installed_only=installed_only).values()) - for position, found in sorted(problems.items()): - for problem in found: - print(f"ROUTE CHECK {site.host(position).name}: {problem}") - count = sum(len(found) for found in problems.values()) - print(f"route check: {checked - count} of {checked} lane destination(s) resolve over their lane's device" - + (" (destinations whose origin route is still to be added are not checked)" if installed_only else "")) - return count - - -def _apply(outcome: ops.Outcome, site: Site, executor: ops.Executor, args, marker: commands.MarkerConfig) -> int: - if outcome.blocked: - print("apply refused: resolve the blockers above (nothing was changed)") - return 3 - if not outcome.pending: - print("nothing to apply: the Sparks already hold the plan") - return 0 - results = ops.apply(outcome, site, executor) - failed = False - for position, result in sorted(results.items()): - text = (result.stdout + result.stderr).strip() - print(f"{site.host(position).name}: exit {result.returncode}" + (f": {text[-1500:]}" if text else "")) - failed |= not result.ok - positions = [position for group in outcome.groups for position in group.order] - states = ops.gather(site, positions, executor, marker) - verify = ops.evaluate(site, outcome.layout, outcome.groups, states, mode=outcome.mode, marker=marker, - adopt=args.adopt, check_hostname=not args.skip_hostname_check, max_relays=args.max_relays) - leftovers = [(d, change) for d in verify.diffs for change in d.pending] - for d, change in leftovers: - print(f"after apply, {d.name} still differs: {change.text()}") - for d in verify.diffs: - for blocker in d.blockers: - print(f"after apply, {d.name}: {blocker}") - route_problems = _route_check(verify, site, executor, installed_only=False) - if failed or leftovers or verify.blocked or route_problems: - print("verification failed: run `diff` (or `show`) and inspect the Sparks named above") - return 1 - print(f"verified: {len(verify.diffs)} Spark(s) hold the {outcome.mode} state of " - + ", ".join(group.label for group in outcome.groups)) - return 0 - -def _marker_command(site: Site, positions: list[int], executor: ops.Executor, args, - marker: commands.MarkerConfig) -> int: - states = ops.gather(site, positions, executor, marker) - print(report.render_marker_status(states, marker)) - targets = [p for p in positions if states[p].reachable and ( - args.rebuild or bool(states[p].marker_problems(marker.path, expected_sha256=marker.expected_sha256)))] - if not targets: - print("every reachable Spark has the marker executable") - return 0 if all(states[p].reachable for p in positions) else 1 - source = MARKER_SOURCE.read_text(encoding="utf-8") - scripts = {p: commands.marker_build_script(site.host(p).name, marker, source) for p in targets} - names = ", ".join(site.host(p).name for p in targets) - if not args.apply: - print(f"dry run: --apply compiles {MARKER_SOURCE.name} and installs {marker.path} on {names}") - if args.scripts: - print(scripts[targets[0]]) - return 0 - failed = False - for position in targets: - result = executor(site.host(position).ssh, scripts[position], ops.APPLY_TIMEOUT) - text = (result.stdout + result.stderr).strip() - print(f"{site.host(position).name}: exit {result.returncode}: {text[-800:]}") - failed |= not result.ok - return 1 if failed else 0 - - -def _parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(prog="python -m sparkring_sircl.fabric", description=__doc__, - formatter_class=argparse.RawDescriptionHelpFormatter) - commands_parser = parser.add_subparsers(dest="command", required=True) - - def layout_options(sub: argparse.ArgumentParser) -> None: - sub.add_argument("--layout", help="ring8 (universal relay table), 2xTP4, 4xTP2, or ring") - sub.add_argument("--groups", help="custom groups instead of --layout: '0-3;4-7', '7,0,1,2' or '7-2'") - sub.add_argument("--name", help="name of a custom layout (recorded on the Sparks)") - sub.add_argument("--group", help="act on one group of the layout: index, label (path:4-5-6-7) or members") - sub.add_argument("--relay-egress", choices=layouts.RELAY_EGRESS, - help="relay egress function (default: same for the whole ring, sibling otherwise)") - sub.add_argument("--max-relays", type=int, default=routes.DEFAULT_MAX_RELAYS, - help=f"relay limit per lane (default {routes.DEFAULT_MAX_RELAYS}, the qualified limit; " - "higher values are research-only)") - - def remote_options(sub: argparse.ArgumentParser) -> None: - sub.add_argument("--site", required=True, type=Path, help="site file (sircl-ring-site/v1)") - sub.add_argument("--marker", default=commands.DEFAULT_MARKER, - help=f"marker executable on the Sparks (default {commands.DEFAULT_MARKER})") - sub.add_argument("--skip-hostname-check", action="store_true", - help="accept a host whose name differs from its site entry's name") - - plan_parser = commands_parser.add_parser("plan", help="print a layout's relay plan (OFFLINE)") - layout_options(plan_parser) - plan_parser.add_argument("--facts", type=Path, help="facts file (sparkring-fabric-facts/v1); else placeholders") - plan_parser.add_argument("--site", type=Path, help="site file, for Spark names and the ring size") - plan_parser.add_argument("--ring-size", type=int, help="ring size without a site or facts file (default 8)") - plan_parser.add_argument("--json", action="store_true") - plan_parser.add_argument("--brief", action="store_true", help="groups and route maps only") - - facts_parser = commands_parser.add_parser("facts", help="read the Sparks' fabric addresses and MACs") - remote_options(facts_parser) - facts_parser.add_argument("--sparks", help="positions to read (default all), e.g. '0-3'") - facts_parser.add_argument("--output", type=Path, help="write the facts file here instead of printing it") - - show_parser = commands_parser.add_parser("show", help="show every Spark's relay objects (READ-ONLY REMOTE)") - remote_options(show_parser) - show_parser.add_argument("--sparks", help="positions to read (default all), e.g. '0-3'") - show_parser.add_argument("--raw", action="store_true", help="also print the raw read-script output") - - for name, text in (("diff", "compare the Sparks with a layout's plan (READ-ONLY REMOTE)"), - ("up", "install a layout's plan: dry run unless --apply (MUTATES HOST)"), - ("down", "remove a layout's groups: dry run unless --apply (MUTATES HOST)")): - sub = commands_parser.add_parser(name, help=text) - remote_options(sub) - layout_options(sub) - sub.add_argument("--adopt", action="store_true", - help="take over relay routes and neighbours that lack the ownership mark") - sub.add_argument("--verbose", action="store_true", help="also list unchanged objects") - if name == "diff": - sub.add_argument("--scripts", action="store_true", help="print the scripts `up` would run") - else: - sub.add_argument("--apply", action="store_true", help="change the Sparks (MUTATES HOST)") - sub.add_argument("--no-scripts", action="store_true", help="omit the per-Spark scripts") - - marker_parser = commands_parser.add_parser("marker", help="the marker executable: status, or build with --apply") - remote_options(marker_parser) - marker_parser.add_argument("--sparks", help="positions (default all)") - marker_parser.add_argument("--apply", action="store_true", help="compile and install it (MUTATES HOST)") - marker_parser.add_argument("--rebuild", action="store_true", help="rebuild where it exists too") - marker_parser.add_argument("--scripts", action="store_true", help="print the build script") - return parser - - -def main(argv: list[str] | None = None, *, executor: ops.Executor | None = None) -> int: - args = _parser().parse_args(argv) - run = executor or ops.ssh_executor +def _ensure_sparkring_fabric() -> None: try: - if args.command == "plan": - site = Site.load(args.site) if args.site else None - if args.facts: - facts = plan_mod.Facts.from_json(json.loads(args.facts.read_text(encoding="utf-8"))) - size = args.ring_size or (site.size if site else max(facts.positions) + 1) - else: - size = args.ring_size or (site.size if site else 8) - names = [host.name for host in site.ring] if site else [f"spark{i}" for i in range(size)] - facts = plan_mod.Facts.symbolic_for(names) - layout = _layout(args, size) - built = plan_mod.build_layout_plan(layout, facts, groups=layout.select(args.group), - max_relays=args.max_relays) - if args.json: - print(json.dumps(built.to_json(), indent=1)) - else: - print(plan_mod.render_text(built, facts, details=not args.brief)) - return 0 - site = Site.load(args.site) - marker = commands.MarkerConfig(args.marker) - if args.command in ("show", "facts", "marker"): - positions = _positions(args.sparks, site.size) - if args.command == "marker": - return _marker_command(site, positions, run, args, marker) - states = ops.gather(site, positions, run, marker) - if args.command == "facts": - problems = [p for state in states.values() for p in state.fact_problems(check_hostname=False)] - text = json.dumps(ops.facts_from(site, states).to_json(), indent=1) - if args.output: - args.output.write_text(text + "\n", encoding="utf-8") - else: - print(text) - for problem in problems: - print(f"problem: {problem}", file=sys.stderr) - return 3 if problems else 0 - print(report.render_show(states, marker)) - if args.raw: - for position, state in sorted(states.items()): - print(f"--- {state.name} raw ---") - for section, text in state.raw.items(): - print(f"@@{section}\n{text}") - return 0 if all(state.reachable for state in states.values()) else 1 - layout = _layout(args, site.size) - groups = layout.select(args.group) - positions = [position for group in groups for position in group.order] - states = ops.gather(site, positions, run, marker) - mode = "down" if args.command == "down" else "up" - outcome = ops.evaluate(site, layout, groups, states, mode=mode, marker=marker, adopt=args.adopt, - check_hostname=not args.skip_hostname_check, max_relays=args.max_relays) - if args.command == "diff": - _print_outcome(outcome, args, scripts=args.scripts) - if outcome.problems or not all(state.reachable for state in states.values()): - return 3 - if _route_check(outcome, site, run, installed_only=True): - return 3 - return 1 if outcome.host_changes else 0 - _print_outcome(outcome, args, scripts=not args.no_scripts) - if not args.apply: - print("dry run: nothing was changed; --apply runs the scripts above" - + (" (blockers must be resolved first)" if outcome.blocked else "")) - return 3 if outcome.blocked else 0 - return _apply(outcome, site, run, args, marker) - except (FabricError, SiteError, routes.RouteError, OSError, ValueError, KeyError) as error: - print(f"error: {error}", file=sys.stderr) - return 2 - - -if __name__ == "__main__": # pragma: no cover - sys.exit(main()) + importlib.import_module("sparkring_fabric.fabric.cli") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + +_ensure_sparkring_fabric() +sys.modules[__name__] = importlib.import_module("sparkring_fabric.fabric.cli") diff --git a/spark_transport/sircl/sparkring_sircl/fabric/commands.py b/spark_transport/sircl/sparkring_sircl/fabric/commands.py index 7abc900e..0687d59d 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/commands.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/commands.py @@ -1,278 +1,30 @@ -"""Shell commands the installer sends to a Spark. - -Every remote action is one ``bash -s`` script over SSH in batch mode, one -command per line, every interpolated value shell-quoted. The read script -(:func:`read_script`) uses read-only commands and needs no root: it is the -READ-ONLY REMOTE part of ``show``, ``diff`` and every dry run. Apply scripts -change host state through ``sudo -n`` (MUTATES HOST), stop at the first -failing command (``set -euo pipefail``) and first check the host's name -(:func:`guard`), so a wrong SSH target changes nothing. - -Ownership marks, by which ``down`` removes exactly the installer's objects: - -- routes and permanent neighbours carry routing protocol number 82 - (:data:`ROUTE_PROTOCOL`, ``proto 82``); -- relay filters occupy the reserved preferences 11 to 17 of chain 0 on the - ingress of the four fabric network devices (preference ``10 + k``, handle - ``k``, protocol ``TAG(k)``); -- marker processes run the marker executable, whose first 15 characters are - the process name ``pgrep -x`` matches; -- the record ``/run/sparkring-fabric/relay-state.json`` names the Spark's - group, layout, relay egress, plan digest and the ingress qdiscs the - installer added. ``/run`` is cleared at boot, like every object of the plan. - -Nothing else is changed: not the NetworkManager connections, addresses, links, -other routes, other neighbours, other filters, other qdiscs or other processes. -""" +"""Compatibility shim: canonical implementation lives in ``sparkring_fabric.fabric.commands``.""" from __future__ import annotations -import dataclasses -import ipaddress -import json -import posixpath -import re -import shlex -from collections.abc import Iterable, Mapping - -from .layouts import FabricError -from .plan import FABRIC_NETDEVS, RDMA_DEVICES, RelayFilter - -ROUTE_PROTOCOL = 82 -STATE_DIR = "/run/sparkring-fabric" -RECORD_PATH = f"{STATE_DIR}/relay-state.json" -RECORD_SCHEMA = "sparkring-fabric-relay-record/v1" -DEFAULT_MARKER_DIR = "/usr/local/libexec/sparkring" -DEFAULT_MARKER = f"{DEFAULT_MARKER_DIR}/ring8-mesh-marker" -SECTION = "@@" -HEADER = "set -euo pipefail" -SETTLE = "sleep 1.5" -_PATH = re.compile(r"^/[A-Za-z0-9_./+-]+$") -_MAC = re.compile(r"^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$") -_HOSTNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$") - - -def q(value: object) -> str: - return shlex.quote(str(value)) - +import importlib +import sys +from pathlib import Path -@dataclasses.dataclass(frozen=True) -class MarkerConfig: - """Where the marker executable lives on every Spark and where each marker logs.""" - path: str = DEFAULT_MARKER - log_dir: str = "/tmp" - expected_sha256: str | None = None - - def __post_init__(self) -> None: - for label, value in (("marker path", self.path), ("marker log directory", self.log_dir)): - if not _PATH.match(value) or "/../" in f"{value}/": - raise FabricError(f"{label} {value!r} must be an absolute path of letters, digits and _./+-") - if self.expected_sha256 is not None and not re.fullmatch(r"[0-9a-f]{64}", self.expected_sha256.lower()): - raise FabricError(f"expected marker sha256 {self.expected_sha256!r} must be 64 hex characters") - - @property - def name(self) -> str: - return posixpath.basename(self.path) - - @property - def digest_path(self) -> str: - return f"{self.path}.sha256" - - @property - def comm(self) -> str: - """The process name the kernel keeps for the executable (its first 15 characters).""" - return self.name[:15] - - def log(self, device: str) -> str: - return f"{self.log_dir}/{self.name}-{device}.log" - - -def _ipv4(value: str) -> str: +def _ensure_sparkring_fabric() -> None: try: - return str(ipaddress.IPv4Address(value)) - except ValueError: - raise FabricError(f"{value!r} is not an IPv4 address; apply needs the Sparks' facts, not placeholders") from None - - -def _mac(value: str) -> str: - if not _MAC.match(value.lower()): - raise FabricError(f"{value!r} is not a MAC address; apply needs the Sparks' facts, not placeholders") - return value.lower() - - -def _netdev(value: str) -> str: - if value not in FABRIC_NETDEVS: - raise FabricError(f"{value!r} is not a fabric network device") - return value - - -def _device(value: str) -> str: - if value not in RDMA_DEVICES: - raise FabricError(f"{value!r} is not a fabric RDMA device") - return value - - -# -- read script --------------------------------------------------------------------------- - - -def read_script(marker: MarkerConfig) -> str: - """Read-only facts and relay objects of one Spark, as ``@@
`` blocks.""" - lines = ["set -u"] - - def section(name: str, *commands: str) -> None: - lines.append(f"echo {SECTION}{name}") - lines.extend(commands) - - section("hostname", "hostname") - section("versions", "ip -V 2>&1 || true", "tc -V 2>&1 || true") - section("links", "ip -j addr show") - for device in RDMA_DEVICES: - section(f"rdma:{device}", f"ls /sys/class/infiniband/{device}/device/net 2>/dev/null || true") - section("routes", "ip -j -d route show table main") - section("neighbours", "ip -j neigh show nud permanent") - for netdev in FABRIC_NETDEVS: - section(f"qdisc:{netdev}", f"tc -j qdisc show dev {netdev} 2>/dev/null || true") - section(f"filters:{netdev}", f"tc -j filter show dev {netdev} ingress 2>/dev/null || true") - section("markers", f"pgrep -a -x {q(marker.comm)} || true") - section("marker-binary", f"sha256sum {q(marker.path)} 2>/dev/null || true") - section("marker-stat", f"stat -c '%u %g %a' {q(marker.path)} 2>/dev/null || true") - section("marker-sha256", f"cat {q(marker.digest_path)} 2>/dev/null || true") - for device in RDMA_DEVICES: - section(f"marker-log:{device}", f"head -c 4096 {q(marker.log(device))} 2>/dev/null || true") - section("record", f"cat {RECORD_PATH} 2>/dev/null || true") - lines.append(f"echo {SECTION}end") - return "\n".join(lines) + "\n" - - -def route_get_script(destinations: Iterable[str]) -> str: - """``ip -o route get`` of every destination (read-only), as ``@@route:
`` blocks. - - The ring harness and the vLLM launcher check origin routes the same way. - """ - lines = ["set -u"] - for destination in destinations: - address = _ipv4(destination) - lines += [f"echo {SECTION}route:{address}", f"ip -o route get {address} 2>&1 || true"] - lines.append(f"echo {SECTION}end") - return "\n".join(lines) + "\n" - - -# -- apply commands -------------------------------------------------------------------------- - - -def guard(hostname: str) -> str: - """Stop the script unless it runs on ``hostname``.""" - if not _HOSTNAME.match(hostname): - raise FabricError(f"host name {hostname!r} cannot be checked safely") - return (f'test "$(hostname)" = {q(hostname)} || ' - f'{{ echo {q("refusing: this host is not " + hostname)} >&2; exit 3; }}') - - -def qdisc_add(netdev: str) -> str: - return f"sudo -n tc qdisc add dev {_netdev(netdev)} ingress" - - -def qdisc_del(netdev: str) -> str: - return f"sudo -n tc qdisc del dev {_netdev(netdev)} ingress" - - -def filter_add(relay_filter: RelayFilter) -> str: - return (f"sudo -n tc filter add dev {_netdev(relay_filter.in_netdev)} ingress protocol " - f"0x{relay_filter.protocol:04x} pref {relay_filter.pref} handle {relay_filter.handle} flower skip_sw " - f"action pedit ex munge eth dst set {_mac(relay_filter.next_mac)} pipe " - f"action pedit ex munge eth type set 0x{relay_filter.new_type:04x} pipe " - f"action mirred egress redirect dev {_netdev(relay_filter.out_netdev)}") - - -def filter_del(netdev: str, pref: int, *, protocol: int | None = None, handle: int | None = None) -> str: - """Delete one filter (protocol and handle known) or every filter of a reserved preference.""" - if protocol is None or handle is None: - return f"sudo -n tc filter del dev {_netdev(netdev)} ingress pref {int(pref)}" - return (f"sudo -n tc filter del dev {_netdev(netdev)} ingress protocol 0x{int(protocol):04x} " - f"pref {int(pref)} handle {int(handle)} flower") - - -def neigh_replace(destination: str, mac: str, netdev: str) -> str: - return (f"sudo -n ip neigh replace {_ipv4(destination)} lladdr {_mac(mac)} dev {_netdev(netdev)} " - f"nud permanent proto {ROUTE_PROTOCOL}") - - -def neigh_del(destination: str, netdev: str) -> str: - return f"sudo -n ip neigh del {_ipv4(destination)} dev {_netdev(netdev)}" - - -def route_replace(destination: str, netdev: str, source: str) -> str: - return (f"sudo -n ip route replace {_ipv4(destination)}/32 dev {_netdev(netdev)} src {_ipv4(source)} " - f"scope link proto {ROUTE_PROTOCOL}") - - -def route_del(destination: str, netdev: str, *, protocol: int | None, metric: int = 0) -> str: - """Delete one /32 route; naming its protocol makes the kernel refuse any other route.""" - command = f"sudo -n ip route del {_ipv4(destination)}/32 dev {_netdev(netdev)}" - if protocol is not None: - command += f" proto {int(protocol)}" - if metric: - command += f" metric {int(metric)}" - return command - - -def marker_start(marker: MarkerConfig, device: str, rules: Iterable[tuple[str, int]]) -> str: - """Start one managed marker in its own session; it keeps its rules until SIGTERM.""" - rule_words = " ".join(f"--rule {_ipv4(destination)}=0x{int(value):04x}" for destination, value in rules) - if not rule_words: - raise FabricError(f"a marker for {device} needs at least one rule") - return (f"(sudo -n setsid {q(marker.path)} --device {_device(device)} {rule_words} --managed " - f"< /dev/null > {q(marker.log(device))} 2>&1 &)") - - -def marker_stop(marker: MarkerConfig, pid: int) -> tuple[str, str]: - """Signal one marker process (only while it still is one) and wait up to 5 s for it to exit. - - The marker removes its RDMA-TX rules when it exits. - """ - pid = int(pid) - return (f'[ "$(cat /proc/{pid}/comm 2>/dev/null)" != {q(marker.comm)} ] || sudo -n kill {pid}', - f"for i in $(seq 1 50); do [ -e /proc/{pid} ] || break; sleep 0.1; done; [ ! -e /proc/{pid} ]") - - -def record_text(record: Mapping[str, object]) -> str: - return json.dumps(record, sort_keys=True, separators=(",", ":")) - - -def record_write(record: Mapping[str, object]) -> tuple[str, str]: - return (f"sudo -n mkdir -p {STATE_DIR}", - f"printf '%s\\n' {q(record_text(record))} | sudo -n tee {RECORD_PATH} >/dev/null") - - -def record_remove() -> str: - return f"sudo -n rm -f {RECORD_PATH}" - - -# -- marker executable ----------------------------------------------------------------------- - -MARKER_SOURCE_END = "SPARKRING_MARKER_SOURCE_END" - - -def marker_build_script(hostname: str, marker: MarkerConfig, source: str) -> str: - """Compile the marker source on a Spark (rdma-core headers needed) and install it root-owned.""" - if any(line.strip() == MARKER_SOURCE_END for line in source.splitlines()): - raise FabricError("the marker source contains the here-document delimiter") - marker_dir = posixpath.dirname(marker.path) - digest_path = marker.digest_path - return "\n".join([ - HEADER, - guard(hostname), - "work=$(mktemp -d /var/tmp/sparkring-marker.XXXXXX)", - "trap 'rm -rf \"$work\"' EXIT", - f"cat > \"$work/mesh_marker.c\" <<'{MARKER_SOURCE_END}'", - source.rstrip("\n"), - MARKER_SOURCE_END, - "cc -O2 -Wall -Wextra \"$work/mesh_marker.c\" -o \"$work/marker\" -libverbs -lmlx5", - f"sudo -n install -d -o root -g root -m 0755 {q(marker_dir)}", - f"sudo -n install -o root -g root -m 0755 \"$work/marker\" {q(marker.path)}", - "rm -f \"$work/marker\"", - f"sha256sum {q(marker.path)} > \"$work/marker.sha256\"", - f"sudo -n install -o root -g root -m 0644 \"$work/marker.sha256\" {q(digest_path)}", - f"cat {q(digest_path)}", - ]) + "\n" + importlib.import_module("sparkring_fabric.fabric.commands") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + +_ensure_sparkring_fabric() +sys.modules[__name__] = importlib.import_module("sparkring_fabric.fabric.commands") diff --git a/spark_transport/sircl/sparkring_sircl/fabric/diff.py b/spark_transport/sircl/sparkring_sircl/fabric/diff.py index 67f6fccc..805a06c3 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/diff.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/diff.py @@ -1,366 +1,30 @@ -"""Comparison of one Spark's objects with its plan, and the script that reconciles them. - -:func:`compare_up` compares a Spark with its group's plan; :func:`compare_down` -lists everything ``down`` removes. Both return a :class:`SparkDiff`: the -changes (``add``, ``remove``, ``replace``; ``mark`` puts the ownership mark on -an unowned object equal to the plan; ``keep``; ``write`` and ``remove`` of -the record), the blockers that stop ``--apply``, notes, and the apply script. - -Rules: - -- a Spark whose record names another group is left alone: ``up`` and - ``down`` stop there, so one group's operation never changes another - group's objects; -- unowned relay routes and neighbours (no protocol 82) are changed or - removed only with ``--adopt``; without it, ``up`` and ``down`` stop on a - Spark that holds any, and ``diff`` reports what ``--adopt`` would do. A - route that is not a relay route but has a planned destination is a - conflict and is never touched; -- relay filters and marker processes are the installer's by their reserved - identifiers and are replaced when they differ from the plan; -- an ingress qdisc is added where filters need one; ``down`` removes only a - qdisc the record says the installer added, and only when no filter remains. - -Script order: qdiscs, relay filters, neighbours, routes, marker restarts, -removal of stale routes and neighbours, qdisc removal, record. A changed -filter or marker is deleted and re-created, which interrupts the lanes that -use it for well under a second; an unchanged object is not touched. -""" +"""Compatibility shim: canonical implementation lives in ``sparkring_fabric.fabric.diff``.""" from __future__ import annotations -import dataclasses -from collections.abc import Sequence - -from . import commands -from .plan import FABRIC_NETDEVS, RDMA_DEVICES, GroupPlan, SparkPlan -from .state import FilterEntry, HostState, NeighbourEntry, RouteEntry - -HOST_ACTIONS = ("add", "remove", "replace") - - -@dataclasses.dataclass(frozen=True) -class Change: - kind: str # route, neighbour, filter, qdisc, marker, record - action: str # add, remove, replace, mark, keep, write - key: str - detail: str - unowned: bool = False # acts on an object without the ownership mark - - @property - def host_change(self) -> bool: - """Whether the change alters forwarding state (marks and the record do not).""" - return self.kind != "record" and self.action in HOST_ACTIONS - - def text(self) -> str: - symbol = {"add": "+", "remove": "-", "replace": "~", "mark": "*", "keep": "=", "write": "+"}[self.action] - owner = " [unowned]" if self.unowned else "" - return f"{symbol} {self.action} {self.kind} {self.key}: {self.detail}{owner}" - - -@dataclasses.dataclass -class SparkDiff: - position: int - name: str - group: str - mode: str - changes: list[Change] = dataclasses.field(default_factory=list) - blockers: list[str] = dataclasses.field(default_factory=list) - notes: list[str] = dataclasses.field(default_factory=list) - commands: list[str] = dataclasses.field(default_factory=list) - needs_adopt: str | None = None # why --apply also needs --adopt (unowned objects would change) - - @property - def blocked(self) -> bool: - """Whether ``--apply`` must refuse this Spark.""" - return bool(self.blockers) or self.needs_adopt is not None - - def count(self, action: str) -> int: - return sum(1 for change in self.changes if change.action == action) - - @property - def host_changes(self) -> list[Change]: - return [change for change in self.changes if change.host_change] - - @property - def pending(self) -> list[Change]: - """Every change apply would make (anything but ``keep``).""" - return [change for change in self.changes if change.action != "keep"] - - @property - def script(self) -> str | None: - return "\n".join(self.commands) + "\n" if self.commands else None - - -@dataclasses.dataclass -class _Script: - qdisc_add: list[str] = dataclasses.field(default_factory=list) - filter_del: list[str] = dataclasses.field(default_factory=list) - filter_add: list[str] = dataclasses.field(default_factory=list) - neigh_set: list[str] = dataclasses.field(default_factory=list) - route_set: list[str] = dataclasses.field(default_factory=list) - marker_stop: list[str] = dataclasses.field(default_factory=list) - marker_start: list[str] = dataclasses.field(default_factory=list) - route_del: list[str] = dataclasses.field(default_factory=list) - neigh_del: list[str] = dataclasses.field(default_factory=list) - qdisc_del: list[str] = dataclasses.field(default_factory=list) - record: list[str] = dataclasses.field(default_factory=list) - - def lines(self, hostname: str) -> list[str]: - body = (self.qdisc_add + self.filter_del + self.filter_add + self.neigh_set + self.route_set - + self.marker_stop + self.marker_start + self.route_del + self.neigh_del + self.qdisc_del - + self.record) - if not body: - return [] - settle = [commands.SETTLE] if self.marker_start else [] - return [commands.HEADER, commands.guard(hostname), *body, *settle] - - -def _route_equal(entry: RouteEntry, destination: str, netdev: str, source: str) -> bool: - return (entry.dev == netdev and entry.source == source and entry.scope == "link" and not entry.gateway - and entry.metric == 0 and entry.kind == "unicast" and entry.destination == destination) - - -def _route_removal(entry: RouteEntry) -> str: - return commands.route_del(entry.destination, entry.dev, protocol=entry.protocol, metric=entry.metric) - - -def _filter_removal(entries: Sequence[FilterEntry]) -> list[str]: - if len(entries) == 1 and entries[0].protocol is not None and entries[0].handle is not None: - entry = entries[0] - return [commands.filter_del(entry.netdev, entry.pref, protocol=entry.protocol, handle=entry.handle)] - return [commands.filter_del(entries[0].netdev, entries[0].pref)] - - -def _common_blockers(diff: SparkDiff, state: HostState, *, check_hostname: bool) -> bool: - """Blockers that make the comparison meaningless; True when the Spark cannot be compared.""" - if not state.reachable: - diff.blockers.append(f"unreachable: {state.error}") - return True - if state.parse_problems: - diff.blockers.extend(f"read: {problem}" for problem in state.parse_problems) - if check_hostname and state.hostname != state.name: - diff.blockers.append(f"the host at {state.ssh} is named {state.hostname or 'nothing'}, the site lists " - f"{state.name} (--skip-hostname-check overrides)") - if state.record_problem: - diff.blockers.append(state.record_problem) - if state.record is not None and state.record.get("group") != diff.group: - diff.blockers.append(f"the Spark belongs to group {state.record.get('group')} (layout " - f"{state.record.get('layout')}); remove that group with `down` first") - return False - - -def _adopt_blocker(diff: SparkDiff, adopt: bool) -> None: - unowned = [change for change in diff.changes if change.unowned and change.action != "keep"] - if unowned and not adopt: - diff.needs_adopt = (f"{len(unowned)} relay route and neighbour change(s) act on objects without the " - "ownership mark (installed by other tooling); --adopt takes them over") - - -def _marker_changes(diff: SparkDiff, script: _Script, state: HostState, spark: SparkPlan | None, - marker: commands.MarkerConfig) -> None: - handled = set() - for device in RDMA_DEVICES: - planned = spark.marker(device) if spark is not None else None - wanted = frozenset(planned.rules) if planned is not None else frozenset() - present = [process for process in state.markers if process.device == device] - handled.update(process.pid for process in present) - rules_text = " ".join(f"{d}=0x{v:04x}" for d, v in (planned.rules if planned else ())) - if wanted and len(present) == 1 and present[0].rules == wanted and present[0].managed \ - and present[0].problem is None: - diff.changes.append(Change("marker", "keep", device, f"pid {present[0].pid}, {len(wanted)} rules")) - continue - for process in present: - script.marker_stop.extend(commands.marker_stop(marker, process.pid)) - if wanted: - script.marker_start.append(commands.marker_start(marker, device, planned.rules)) - before = "; ".join(process.text() for process in present) - diff.changes.append(Change("marker", "replace" if present else "add", device, - f"{before} -> {rules_text}" if present else rules_text)) - elif present: - diff.changes.append(Change("marker", "remove", device, "; ".join(p.text() for p in present))) - for process in state.markers: - if process.pid not in handled: - script.marker_stop.extend(commands.marker_stop(marker, process.pid)) - diff.changes.append(Change("marker", "remove", f"pid {process.pid}", process.text())) - if script.marker_start or (spark is not None and spark.markers): - diff.blockers.extend(state.marker_problems(marker.path, expected_sha256=marker.expected_sha256)) - - -def _record(spark: SparkPlan, plan: GroupPlan, layout_name: str, marker: commands.MarkerConfig, - qdiscs: Sequence[str], *, marker_sha256: str | None = None) -> dict[str, object]: - record: dict[str, object] = { - "schema": commands.RECORD_SCHEMA, "spark": spark.name, "position": spark.position, - "layout": layout_name, "group": plan.group.label, "members": list(plan.group.members), - "relay_egress": plan.relay_egress, "plan": plan.digest, "marker": marker.path, - "qdiscs": sorted(qdiscs), - } - if marker_sha256 is not None: - record["marker_sha256"] = marker_sha256 - return record - - -def compare_up(state: HostState, spark: SparkPlan, plan: GroupPlan, *, layout_name: str, - marker: commands.MarkerConfig, adopt: bool, check_hostname: bool = True) -> SparkDiff: - """What ``up`` changes on one Spark to install its group's plan.""" - diff = SparkDiff(spark.position, spark.name, plan.group.label, "up") - if _common_blockers(diff, state, check_hostname=check_hostname): - return diff - script = _Script() - removed_filters = {netdev: 0 for netdev in FABRIC_NETDEVS} - - # Relay filters (reserved preferences) and the ingress qdiscs they need. - added_qdiscs = [] - for netdev in FABRIC_NETDEVS: - planned = {relay_filter.pref: relay_filter for relay_filter in spark.filters if relay_filter.in_netdev == netdev} - present: dict[int, list[FilterEntry]] = {} - for entry in state.reserved_filters(netdev): - present.setdefault(entry.pref, []).append(entry) - if planned and state.ingress_qdisc.get(netdev) is None: - script.qdisc_add.append(commands.qdisc_add(netdev)) - added_qdiscs.append(netdev) - diff.changes.append(Change("qdisc", "add", netdev, "ingress")) - for pref, relay_filter in sorted(planned.items()): - entries = present.pop(pref, []) - wanted = (f"0x{relay_filter.protocol:04x} -> 0x{relay_filter.new_type:04x}, dst " - f"{relay_filter.next_mac}, out {relay_filter.out_netdev}") - if len(entries) == 1 and entries[0].matches(relay_filter): - diff.changes.append(Change("filter", "keep", f"{netdev} pref {pref}", wanted)) - continue - if entries: - script.filter_del.extend(_filter_removal(entries)) - removed_filters[netdev] += len(entries) - script.filter_add.append(commands.filter_add(relay_filter)) - before = "; ".join(entry.text() for entry in entries) - diff.changes.append(Change("filter", "replace" if entries else "add", f"{netdev} pref {pref}", - f"{before} -> {wanted}" if entries else wanted)) - for pref, entries in sorted(present.items()): - script.filter_del.extend(_filter_removal(entries)) - removed_filters[netdev] += len(entries) - diff.changes.append(Change("filter", "remove", f"{netdev} pref {pref}", - "; ".join(entry.text() for entry in entries))) - - # Origin routes and their permanent neighbours. - planned_routes = {route.destination: route for route in spark.routes} - host_routes: dict[str, list[RouteEntry]] = {} - for entry in state.routes: - if entry.prefixlen == 32: - host_routes.setdefault(entry.destination, []).append(entry) - for destination, route in planned_routes.items(): - entries = host_routes.get(destination, []) - candidates = [entry for entry in entries if entry.owned or state.is_relay_route(entry)] - foreign = [entry for entry in entries if entry not in candidates] - want = f"dev {route.netdev} src {route.source} -> position {route.peer} {route.peer_netdev}" - if foreign: - diff.blockers.append(f"route {destination}/32 is held by a route that is not a relay route " - f"({foreign[0].text()}); it is never touched") - continue - # `ip route replace` rewrites the metric-0 route in place; routes at other metrics are removed. - equal = next((entry for entry in candidates - if _route_equal(entry, destination, route.netdev, route.source)), None) - in_place = equal or next((entry for entry in candidates if entry.metric == 0), None) - for entry in candidates: - if entry is not in_place: - script.route_del.append(_route_removal(entry)) - diff.changes.append(Change("route", "remove", f"{destination}/32", entry.text(), not entry.owned)) - if equal is not None: - action = "keep" if equal.owned else "mark" - diff.changes.append(Change("route", action, f"{destination}/32", want, not equal.owned)) - if action == "mark": - script.route_set.append(commands.route_replace(destination, route.netdev, route.source)) - else: - script.route_set.append(commands.route_replace(destination, route.netdev, route.source)) - diff.changes.append(Change("route", "replace" if in_place else "add", f"{destination}/32", - f"{in_place.text()} -> {want}" if in_place else want, - bool(in_place and not in_place.owned))) - for entry in state.relay_routes(): - if entry.destination not in planned_routes: - script.route_del.append(_route_removal(entry)) - diff.changes.append(Change("route", "remove", f"{entry.destination}/32", entry.text(), not entry.owned)) - - planned_neighbours = {(route.destination, route.netdev): route.next_mac for route in spark.routes} - present_neighbours: dict[tuple[str, str], NeighbourEntry] = {} - for entry in state.relay_neighbours(): - present_neighbours[(entry.destination, entry.dev)] = entry - for (destination, netdev), mac in planned_neighbours.items(): - entry = present_neighbours.pop((destination, netdev), None) - if entry is not None and entry.mac == mac.lower(): - action = "keep" if entry.owned else "mark" - diff.changes.append(Change("neighbour", action, f"{destination} dev {netdev}", mac, not entry.owned)) - if action == "mark": - script.neigh_set.append(commands.neigh_replace(destination, mac, netdev)) - continue - script.neigh_set.append(commands.neigh_replace(destination, mac, netdev)) - diff.changes.append(Change("neighbour", "replace" if entry else "add", f"{destination} dev {netdev}", - f"{entry.mac} -> {mac}" if entry else mac, bool(entry and not entry.owned))) - for (destination, netdev), entry in sorted(present_neighbours.items()): - script.neigh_del.append(commands.neigh_del(destination, netdev)) - diff.changes.append(Change("neighbour", "remove", f"{destination} dev {netdev}", entry.text(), - not entry.owned)) - - _marker_changes(diff, script, state, spark, marker) - - # Qdiscs the record lists as added by the installer and that no filter needs any more. - record = state.record if state.record and state.record.get("group") == plan.group.label else None - recorded = set(record.get("qdiscs", [])) if record else set() - kept = set(added_qdiscs) | recorded - for netdev in sorted(recorded): - remaining = len(state.filters.get(netdev, [])) - removed_filters[netdev] - if netdev not in spark.filter_netdevs and remaining <= 0 and state.ingress_qdisc.get(netdev) == "ingress": - script.qdisc_del.append(commands.qdisc_del(netdev)) - kept.discard(netdev) - diff.changes.append(Change("qdisc", "remove", netdev, "ingress qdisc added by the installer")) - wanted_record = _record(spark, plan, layout_name, marker, sorted(kept), - marker_sha256=state.marker_binary if spark.markers else None) - if state.record != wanted_record: - script.record.extend(commands.record_write(wanted_record)) - before = (f"group {state.record.get('group')}, plan {state.record.get('plan')}" if state.record - else "none") - diff.changes.append(Change("record", "write", commands.RECORD_PATH, - f"{before} -> group {plan.group.label}, layout {layout_name}, plan {plan.digest}")) - for entry in state.foreign_tag_filters(): - diff.notes.append(f"a filter outside the reserved preferences matches relay tag 0x{entry.protocol:04x}: " - f"{entry.text()}") - _adopt_blocker(diff, adopt) - diff.commands = script.lines(spark.name) if diff.pending else [] - return diff - - -def compare_down(state: HostState, *, group: str, marker: commands.MarkerConfig, adopt: bool, - check_hostname: bool = True) -> SparkDiff: - """What ``down`` removes from one Spark of ``group``: every object the installer owns there.""" - diff = SparkDiff(state.position, state.name, group, "down") - if _common_blockers(diff, state, check_hostname=check_hostname): - return diff - script = _Script() - removed_filters = {netdev: 0 for netdev in FABRIC_NETDEVS} - for netdev in FABRIC_NETDEVS: - present: dict[int, list[FilterEntry]] = {} - for entry in state.reserved_filters(netdev): - present.setdefault(entry.pref, []).append(entry) - for pref, entries in sorted(present.items()): - script.filter_del.extend(_filter_removal(entries)) - removed_filters[netdev] += len(entries) - diff.changes.append(Change("filter", "remove", f"{netdev} pref {pref}", - "; ".join(entry.text() for entry in entries))) - for entry in state.relay_routes(): - script.route_del.append(_route_removal(entry)) - diff.changes.append(Change("route", "remove", f"{entry.destination}/32", entry.text(), not entry.owned)) - for entry in state.relay_neighbours(): - script.neigh_del.append(commands.neigh_del(entry.destination, entry.dev)) - diff.changes.append(Change("neighbour", "remove", f"{entry.destination} dev {entry.dev}", entry.text(), - not entry.owned)) - _marker_changes(diff, script, state, None, marker) - recorded = set(state.record.get("qdiscs", [])) if state.record else set() - for netdev in sorted(recorded): - remaining = len(state.filters.get(netdev, [])) - removed_filters.get(netdev, 0) - if remaining <= 0 and state.ingress_qdisc.get(netdev) == "ingress": - script.qdisc_del.append(commands.qdisc_del(netdev)) - diff.changes.append(Change("qdisc", "remove", netdev, "ingress qdisc added by the installer")) - if state.record is not None: - script.record.append(commands.record_remove()) - diff.changes.append(Change("record", "remove", commands.RECORD_PATH, - f"group {state.record.get('group')}, plan {state.record.get('plan')}")) - _adopt_blocker(diff, adopt) - diff.commands = script.lines(state.name) if diff.pending else [] - return diff +import importlib +import sys +from pathlib import Path + + +def _ensure_sparkring_fabric() -> None: + try: + importlib.import_module("sparkring_fabric.fabric.diff") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + +_ensure_sparkring_fabric() +sys.modules[__name__] = importlib.import_module("sparkring_fabric.fabric.diff") diff --git a/spark_transport/sircl/sparkring_sircl/fabric/plan.py b/spark_transport/sircl/sparkring_sircl/fabric/plan.py index bb603351..d5a14d94 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/plan.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/plan.py @@ -1,802 +1,30 @@ -"""The relay plan of a layout, derived from SIRCL's route module. - -Carried paths. For every ordered pair of members of a group the plan carries -every shortest path of the group's fabric (``routes.Fabric.shortest_paths``) -on both function classes. SIRCL's lanes (``routes.derive_routes``) are a -subset: lane 0 is the primary function and lane 1 the secondary function of -one of these paths. On a path of Sparks both sets are equal. On a ring of even -size the plan also carries the other function class of each opposite pair's -two paths, which makes the whole-ring plan the universal relay table: every -Spark reaches all four addresses of every Spark it shares no cable with. Every -lane of ``routes.derive_routes`` is checked to be carried, so this plan and -SIRCL's route maps cannot disagree. - -Objects, for a carried path with ``h >= 2`` hops from ``a`` to ``b`` on -function class ``c``: - -- an origin route at ``a``: ``b``'s address on the arrival function as a /32 - route, scope link, over ``a``'s network device of class ``c`` on the path's - first port, source ``a``'s address on that device, and a permanent - neighbour entry holding the adjacent Spark's MAC on that cable; -- a marker rule at ``a``: the RDMA device of that function rewrites the - EtherType of RoCE packets to that destination into ``TAG(h - 1)``; -- a relay filter at every intermediate Spark: on the ingress of the device - that receives the path (class ``c``), match ``TAG(k)`` (``k`` relays left), - set the next Spark's MAC of class ``c``, rewrite the tag to ``TAG(k - 1)`` - and redirect out of the other port (relay egress ``same`` or ``sibling``, - :mod:`.layouts`). - -``TAG(0)`` is IPv4 (0x0800) and ``TAG(k) = 0x88b4 + k``. Relay filters do not -depend on the sender: one per (Spark, ingress device, tag). - -Measured constraints that the plan states and applies: - -- a relay's hardware hairpin queue holds 512 KiB, the device maximum, and - cannot pause its sender, so frames beyond it are dropped. The plan lists - the SIRCL lanes through every queue, the relay load factor ``f`` and the - per-peer op bound ``0.75 * 512 KiB / f``; -- relay egress through the sibling Socket Direct function of the egress port - lowered burst loss to 0.06 % at 2 MiB (:mod:`.layouts`); -- queue pairs use flow label 0 and tags are chosen by destination address, - never by UDP port: the sender NIC computes the ICRC after the RDMA-TX - rewrite, so a rewritten UDP field would be covered by the ICRC and could not - be restored by a relay, and with flow label 0 the UDP source port does not - identify a lane. The EtherType lies outside the ICRC. - -Isolation: routes and tags exist only for destinations in the -same group and only on its members; a relay filter exists only on a member -that lies strictly inside a carried path, and both cables it forwards between -belong to the group. :func:`trace` follows every origin route through the -plan's objects over the physical ring and must reach the destination without -touching a Spark outside the group; :func:`isolation_problems` checks the -rules within and across the groups of a layout. - -Everything here is offline. Facts (addresses and MACs) come from the Sparks -(:mod:`.state`), from a facts file (schema ``sparkring-fabric-facts/v1``), or -as symbolic placeholders that make a plan reviewable without them. -""" +"""Compatibility shim: canonical implementation lives in ``sparkring_fabric.fabric.plan``.""" from __future__ import annotations -import dataclasses -import hashlib -import ipaddress -import json -import re -from collections.abc import Iterable, Mapping, Sequence - -from .. import routes -from .layouts import RELAY_EGRESS, FabricError, FabricLayout, Group - -ETH_P_IP = 0x0800 -TAG_BASE = 0x88B4 -MAX_TAG = 7 # tags TAG(1)..TAG(7); relay filter preferences 11..17 -FILTER_PREF_BASE = 10 -RESERVED_PREFS = range(FILTER_PREF_BASE + 1, FILTER_PREF_BASE + MAX_TAG + 1) -HAIRPIN_QUEUE_BYTES = routes.DEFAULT_HAIRPIN_QUEUE -RELAY_QUEUE_SHARE = routes.RELAY_QUEUE_SHARE -FABRIC_NETDEVS = tuple(role.netdev for role in routes.ROLES) -RDMA_DEVICES = tuple(role.device for role in routes.ROLES) -FACTS_SCHEMA = "sparkring-fabric-facts/v1" -PLAN_SCHEMA = "sparkring-fabric-plan/v1" -_ROLE_BY_NETDEV = {role.netdev: role for role in routes.ROLES} -_MAC = re.compile(r"^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$") - - -def tag(k: int) -> int: - """The EtherType of a frame with ``k`` relays left.""" - if not 0 <= k <= MAX_TAG: - raise FabricError(f"relay count {k} is outside the tags 0 to {MAX_TAG}") - return ETH_P_IP if k == 0 else TAG_BASE + k - - -def relays_left(ethertype: int) -> int | None: - """``k`` for ``TAG(k)``, or None for an EtherType that is not a relay tag.""" - if ethertype == ETH_P_IP: - return 0 - k = ethertype - TAG_BASE - return k if 1 <= k <= MAX_TAG else None - - -def role_of_netdev(netdev: str) -> routes.Role: - role = _ROLE_BY_NETDEV.get(netdev) - if role is None: - raise FabricError(f"{netdev} is not one of the fabric network devices {', '.join(FABRIC_NETDEVS)}") - return role - - -def class_name(secondary: bool) -> str: - return "secondary" if secondary else "primary" - - -def _address_key(text: str) -> tuple: - try: - return (0, int(ipaddress.IPv4Address(text))) - except ValueError: - return (1, text) - - -# -- facts -------------------------------------------------------------------------------- - - -@dataclasses.dataclass(frozen=True) -class Port: - """One fabric function's network device on one Spark: its MAC and IPv4 address.""" - - netdev: str - mac: str - address: str - prefixlen: int | None = None - - def network(self) -> ipaddress.IPv4Network | None: - if self.prefixlen is None: - return None - try: - return ipaddress.IPv4Interface(f"{self.address}/{self.prefixlen}").network - except ValueError: - return None - - def to_json(self) -> dict[str, object]: - address = self.address if self.prefixlen is None else f"{self.address}/{self.prefixlen}" - return {"mac": self.mac, "address": address} - - -@dataclasses.dataclass(frozen=True) -class SparkFacts: - position: int - name: str - ports: tuple[Port, ...] - - def port(self, netdev: str) -> Port | None: - for port in self.ports: - if port.netdev == netdev: - return port - return None +import importlib +import sys +from pathlib import Path -class Facts: - """Addresses and MACs of the fabric functions of the Sparks a plan uses.""" - - def __init__(self, sparks: Iterable[SparkFacts], *, symbolic: bool = False) -> None: - self.symbolic = symbolic - self._sparks = {spark.position: spark for spark in sparks} - self._addresses: dict[str, list[tuple[int, str]]] = {} - self._macs: dict[str, list[tuple[int, str]]] = {} - for spark in self._sparks.values(): - for port in spark.ports: - self._addresses.setdefault(port.address, []).append((spark.position, port.netdev)) - self._macs.setdefault(port.mac.lower(), []).append((spark.position, port.netdev)) - - @property - def positions(self) -> tuple[int, ...]: - return tuple(sorted(self._sparks)) - - def has(self, position: int) -> bool: - return position in self._sparks - - def spark(self, position: int) -> SparkFacts: - if position not in self._sparks: - raise FabricError(f"no facts for the Spark at ring position {position}") - return self._sparks[position] - - def name(self, position: int) -> str: - return self._sparks[position].name if position in self._sparks else f"position {position}" - - def port(self, position: int, netdev: str) -> Port: - port = self.spark(position).port(netdev) - if port is None: - raise FabricError(f"{self.name(position)} has no address or MAC for {netdev}") - return port - - def find_address(self, address: str) -> tuple[int, str] | None: - owners = self._addresses.get(address, []) - return owners[0] if len(owners) == 1 else None - - def find_mac(self, mac: str) -> tuple[int, str] | None: - owners = self._macs.get(mac.lower(), []) - return owners[0] if len(owners) == 1 else None - - def problems(self) -> list[str]: - """Addresses or MACs that more than one function holds.""" - found = [] - for label, table in (("address", self._addresses), ("MAC", self._macs)): - for value, owners in sorted(table.items()): - if len(owners) > 1: - holders = ", ".join(f"{self.name(position)} {netdev}" for position, netdev in owners) - found.append(f"{label} {value} is held by {holders}") - return found - - @classmethod - def symbolic_for(cls, names: Sequence[str]) -> "Facts": - """Placeholders ```` and ```` for every Spark of a ring.""" - return cls((SparkFacts(position, name, tuple(Port(netdev, f"<{name}:{netdev}:mac>", f"<{name}:{netdev}>") - for netdev in FABRIC_NETDEVS)) - for position, name in enumerate(names)), symbolic=True) - - @classmethod - def from_json(cls, document: Mapping[str, object]) -> "Facts": - if document.get("schema") != FACTS_SCHEMA: - raise FabricError(f"facts schema must be {FACTS_SCHEMA}") - sparks = [] - for entry in document.get("sparks", []): - position, name = int(entry["position"]), str(entry["name"]) - ports = [] - for netdev, values in sorted(dict(entry.get("ports", {})).items()): - role_of_netdev(netdev) - ports.append(port_from_text(netdev, str(values["mac"]), str(values["address"]), owner=name)) - sparks.append(SparkFacts(position, name, tuple(ports))) - return cls(sparks) - - def to_json(self) -> dict[str, object]: - return {"schema": FACTS_SCHEMA, "sparks": [ - {"position": spark.position, "name": spark.name, - "ports": {port.netdev: port.to_json() for port in spark.ports}} - for spark in sorted(self._sparks.values(), key=lambda s: s.position)]} - - -def port_from_text(netdev: str, mac: str, address: str, *, owner: str) -> Port: - """A validated :class:`Port` from a MAC and ``a.b.c.d`` or ``a.b.c.d/len``.""" - mac = mac.strip().lower() - if not _MAC.match(mac): - raise FabricError(f"{owner} {netdev}: {mac!r} is not a MAC address") +def _ensure_sparkring_fabric() -> None: try: - if "/" in address: - interface = ipaddress.IPv4Interface(address.strip()) - return Port(netdev, mac, str(interface.ip), interface.network.prefixlen) - return Port(netdev, mac, str(ipaddress.IPv4Address(address.strip()))) - except ValueError: - raise FabricError(f"{owner} {netdev}: {address!r} is not an IPv4 address") from None - - -# -- plan objects ----------------------------------------------------------------------------- - - -@dataclasses.dataclass(frozen=True) -class OriginRoute: - """A /32 route, its permanent neighbour and its marker rule at the Spark where a path starts.""" - - destination: str - netdev: str - device: str - source: str - next_mac: str - tag: int - peer: int - peer_netdev: str - hops: int - relays: tuple[int, ...] - cables: tuple[str, ...] # cables crossed, in the direction of travel - owned_cables: tuple[str, ...] # the same cables in canonical spelling - lanes: tuple[str, ...] = () # SIRCL lanes it carries: "rank r->p lane l" - - def to_json(self) -> dict[str, object]: - return {"destination": self.destination, "netdev": self.netdev, "device": self.device, - "source": self.source, "next_mac": self.next_mac, "tag": f"0x{self.tag:04x}", "peer": self.peer, - "peer_netdev": self.peer_netdev, "hops": self.hops, "relays": list(self.relays), - "cables": list(self.cables), "sircl_lanes": list(self.lanes)} - - -@dataclasses.dataclass(frozen=True) -class RelayFilter: - """A hardware ingress filter of a relay: ``TAG(k)`` in, ``TAG(k - 1)`` out of the other port.""" - - in_netdev: str - k: int - out_netdev: str - next_mac: str - next_position: int - next_netdev: str - direction: str # cw (out of port 0) or ccw (out of port 1) - lane_class: str # primary or secondary: the class of the lanes it relays - - @property - def pref(self) -> int: - return FILTER_PREF_BASE + self.k - - @property - def handle(self) -> int: - return self.k - - @property - def protocol(self) -> int: - return tag(self.k) - - @property - def new_type(self) -> int: - return tag(self.k - 1) - - def to_json(self) -> dict[str, object]: - return {"in_netdev": self.in_netdev, "k": self.k, "pref": self.pref, "protocol": f"0x{self.protocol:04x}", - "new_type": f"0x{self.new_type:04x}", "out_netdev": self.out_netdev, "next_mac": self.next_mac, - "next_position": self.next_position, "next_netdev": self.next_netdev, "direction": self.direction, - "lane_class": self.lane_class} - - -@dataclasses.dataclass(frozen=True) -class MarkerRules: - """The RDMA-TX tag rules of one RDMA device: (destination, EtherType) pairs.""" - - device: str - rules: tuple[tuple[str, int], ...] - - def to_json(self) -> dict[str, object]: - return {"device": self.device, "rules": {destination: f"0x{value:04x}" for destination, value in self.rules}} - - -@dataclasses.dataclass(frozen=True) -class SparkPlan: - position: int - name: str - group: str - routes: tuple[OriginRoute, ...] - filters: tuple[RelayFilter, ...] - - @property - def markers(self) -> tuple[MarkerRules, ...]: - by_device: dict[str, list[tuple[str, int]]] = {} - for route in self.routes: - by_device.setdefault(route.device, []).append((route.destination, route.tag)) - return tuple(MarkerRules(device, tuple(sorted(rules, key=lambda rule: _address_key(rule[0])))) - for device, rules in sorted(by_device.items(), key=lambda item: RDMA_DEVICES.index(item[0]))) - - def marker(self, device: str) -> MarkerRules | None: - for rules in self.markers: - if rules.device == device: - return rules - return None - - @property - def filter_netdevs(self) -> tuple[str, ...]: - return tuple(netdev for netdev in FABRIC_NETDEVS if any(f.in_netdev == netdev for f in self.filters)) - - def route_to(self, destination: str) -> OriginRoute | None: - for route in self.routes: - if route.destination == destination: - return route - return None - - def filter_for(self, netdev: str, k: int) -> RelayFilter | None: - for relay_filter in self.filters: - if relay_filter.in_netdev == netdev and relay_filter.k == k: - return relay_filter - return None - - def to_json(self) -> dict[str, object]: - return {"position": self.position, "name": self.name, "group": self.group, - "routes": [route.to_json() for route in self.routes], - "filters": [relay_filter.to_json() for relay_filter in self.filters], - "markers": [rules.to_json() for rules in self.markers]} - - -@dataclasses.dataclass(frozen=True) -class RelayQueue: - """One hairpin queue of a relay (ingress device to egress device) and the SIRCL lanes through it.""" - - position: int - in_netdev: str - out_netdev: str - lanes: tuple[str, ...] - - -@dataclasses.dataclass(frozen=True) -class GroupPlan: - group: Group - layout: routes.Layout - sircl: routes.GroupRoutes - relay_egress: str - max_relays: int - sparks: tuple[SparkPlan, ...] - queues: tuple[RelayQueue, ...] - busiest_queue: int - load_factor: float - digest: str - - @property - def per_peer_bytes(self) -> int | None: - """The largest per-peer op size that keeps the busiest relay queue at 75 %; None without relays.""" - if not self.load_factor: - return None - return int(RELAY_QUEUE_SHARE * HAIRPIN_QUEUE_BYTES / self.load_factor) - - def spark(self, position: int) -> SparkPlan | None: - for spark in self.sparks: - if spark.position == position: - return spark - return None - - def to_json(self) -> dict[str, object]: - return { - "group": self.group.label, "members": list(self.group.members), "cables": list(self.group.cables), - "relay_egress": self.relay_egress, "max_relays": self.max_relays, "digest": self.digest, - "route_maps": [self.sircl.route_text(rank) for rank in range(self.sircl.world)], - "relay_queues": [{"position": queue.position, "in": queue.in_netdev, "out": queue.out_netdev, - "sircl_lanes": list(queue.lanes)} for queue in self.queues], - "busiest_queue_lanes": self.busiest_queue, "load_factor": self.load_factor, - "per_peer_bytes": self.per_peer_bytes, "sparks": [spark.to_json() for spark in self.sparks], - } - - -@dataclasses.dataclass(frozen=True) -class LayoutPlan: - layout: FabricLayout - groups: tuple[GroupPlan, ...] - symbolic: bool - - def find(self, position: int) -> tuple[GroupPlan, SparkPlan] | None: - for group in self.groups: - spark = group.spark(position) - if spark is not None: - return group, spark - return None - - def to_json(self) -> dict[str, object]: - return {"schema": PLAN_SCHEMA, "layout": self.layout.name, "ring_size": self.layout.ring_size, - "relay_egress": self.layout.relay_egress, "symbolic_facts": self.symbolic, - "constraints": list(CONSTRAINTS), "groups": [group.to_json() for group in self.groups]} - - -CONSTRAINTS = ( - "relay hairpin queue: 512 KiB per (relay, ingress device, egress device), the device maximum; it cannot " - "pause its sender, so frames beyond it are dropped", - "relay egress: sibling Socket Direct function of the egress port lowered burst loss to 0.06 % at 2 MiB; " - "the whole-ring layout keeps same-function egress", - "queue pairs use flow label 0", - "tags are EtherTypes chosen by destination address, never by UDP port (the sender NIC computes the ICRC " - "after the RDMA-TX rewrite)", -) - - -# -- derivation --------------------------------------------------------------------------------- - - -def _carry(path: tuple[routes.Step, ...], secondary: bool, facts: Facts, relay_egress: str, - routes_at: dict[int, dict[str, OriginRoute]], filters_at: dict[int, dict[tuple[str, int], RelayFilter]], - label: str) -> None: - hops = len(path) - origin, target = path[0].src, path[-1].dst - local = routes.role_at(path[0].src_port, secondary) - remote = routes.role_at(path[-1].dst_port, secondary) - first = routes.role_at(path[0].dst_port, secondary) - route = OriginRoute( - destination=facts.port(target, remote.netdev).address, netdev=local.netdev, device=local.device, - source=facts.port(origin, local.netdev).address, next_mac=facts.port(path[0].dst, first.netdev).mac, - tag=tag(hops - 1), peer=target, peer_netdev=remote.netdev, hops=hops, - relays=tuple(step.dst for step in path[:-1]), cables=tuple(step.text for step in path), - owned_cables=tuple(step.cable.text for step in path)) - existing = routes_at[origin].get(route.destination) - if existing is not None and existing != route: - raise FabricError(f"group {label}: two paths from Spark {origin} reach {route.destination} differently") - routes_at[origin][route.destination] = route - for index in range(hops - 1): - arrive, leave = path[index], path[index + 1] - relay = arrive.dst - if leave.src != relay or leave.src_port != 1 - arrive.dst_port: - raise FabricError(f"group {label}: the path {route.cables} does not pass through Spark {relay}") - in_role = routes.role_at(arrive.dst_port, secondary) - out_role = routes.role_at(leave.src_port, secondary if relay_egress == "same" else not secondary) - next_role = routes.role_at(leave.dst_port, secondary) - relay_filter = RelayFilter( - in_netdev=in_role.netdev, k=hops - 1 - index, out_netdev=out_role.netdev, - next_mac=facts.port(leave.dst, next_role.netdev).mac, next_position=leave.dst, - next_netdev=next_role.netdev, direction="cw" if leave.src_port == 0 else "ccw", - lane_class=class_name(secondary)) - key = (relay_filter.in_netdev, relay_filter.k) - known = filters_at[relay].get(key) - if known is not None and known != relay_filter: - raise FabricError(f"group {label}: Spark {relay} would need two relay filters for TAG({relay_filter.k}) " - f"on {relay_filter.in_netdev}") - filters_at[relay][key] = relay_filter - - -def _digest(label: str, relay_egress: str, sparks: Sequence[SparkPlan]) -> str: - canonical = json.dumps({"group": label, "relay_egress": relay_egress, - "sparks": [spark.to_json() for spark in sparks]}, sort_keys=True) - return hashlib.sha256(canonical.encode()).hexdigest()[:16] - - -@dataclasses.dataclass(frozen=True) -class ChainGroup: - """An open chain/path group backed directly by its fabric cables (no closing ring cable).""" - - members: tuple[int, ...] - fabric: routes.Fabric - - def __post_init__(self) -> None: - members = tuple(int(member) for member in self.members) - object.__setattr__(self, "members", members) - if len(members) < 2 or len(set(members)) != len(members): - raise FabricError(f"chain group {members} needs at least two distinct Sparks") - if self.fabric.kind == "disconnected": - raise FabricError(f"chain group {members} fabric is disconnected") - self.layout() - - def layout(self) -> routes.Layout: - try: - return routes.Layout(self.fabric, self.members) - except routes.RouteError as error: - raise FabricError(str(error)) from None - - @property - def ring_size(self) -> int: - return len(self.fabric.positions) - - @property - def whole_ring(self) -> bool: - return False - - @property - def order(self) -> tuple[int, ...]: - return self.members - - @property - def kind(self) -> str: - return "pair" if len(self.members) == 2 else "path" - - @property - def label(self) -> str: - return f"{self.kind}:{'-'.join(str(position) for position in self.order)}" - - @property - def cables(self) -> tuple[str, ...]: - return tuple(cable.text for cable in self.fabric.cables) - - -def build_chain_plan( - positions: Sequence[int], - facts: Facts, - *, - fabric: routes.Fabric | None = None, - relay_egress: str = "sibling", - max_relays: int = routes.DEFAULT_MAX_RELAYS, -) -> GroupPlan: - """Build the relay plan of an open chain/path of Sparks without assuming a closed ring.""" - members = tuple(int(p) for p in positions) - if fabric is None: - try: - fabric = routes.Fabric.path(members) - except routes.RouteError as error: - raise FabricError(str(error)) from None - if fabric.kind != "path": - raise FabricError(f"open chain plan requires a connected path fabric, got {fabric.kind}") - return build_group_plan(ChainGroup(members, fabric), facts, relay_egress=relay_egress, max_relays=max_relays) - - -def build_group_plan(group: Group | ChainGroup, facts: Facts, *, relay_egress: str, - max_relays: int = routes.DEFAULT_MAX_RELAYS) -> GroupPlan: - """The relay plan of one group (module docstring), checked by :func:`trace` on every origin route.""" - if relay_egress not in RELAY_EGRESS: - raise FabricError(f"relay egress must be one of {', '.join(RELAY_EGRESS)}") - if not 0 <= max_relays <= MAX_TAG: - raise FabricError(f"the relay limit must be between 0 and {MAX_TAG} (one tag per relay count)") - layout = group.layout() - members = layout.positions - routes_at: dict[int, dict[str, OriginRoute]] = {position: {} for position in members} - filters_at: dict[int, dict[tuple[str, int], RelayFilter]] = {position: {} for position in members} - for origin in members: - for target in members: - if origin == target: - continue - for path in layout.fabric.shortest_paths(origin, target): - if len(path) < 2: - continue - if len(path) - 1 > max_relays: - raise FabricError( - f"group {group.label}: Spark {target} is {len(path)} cables from Spark {origin}, " - f"{len(path) - 1} relays; the qualified limit is {max_relays} (" - "--max-relays raises it, research-only)") - for secondary in (False, True): - _carry(path, secondary, facts, relay_egress, routes_at, filters_at, group.label) - sircl = routes.derive_routes(layout, 2) - lanes_of: dict[tuple[int, str], list[str]] = {} - for rank, peers in enumerate(sircl.ranks): - origin = layout.positions[rank] - for peer, lanes in sorted(peers.items()): - for lane in lanes: - if lane.hops < 2: - continue - destination = facts.port(layout.positions[peer], lane.remote.netdev).address - route = routes_at[origin].get(destination) - if (route is None or route.netdev != lane.local.netdev or route.cables != lane.cables - or route.tag != tag(len(lane.relays))): - raise FabricError(f"group {group.label}: SIRCL lane {lane.lane} from rank {rank} to rank {peer} " - f"({lane.local.device}, {lane.cables}) is not carried by the relay plan") - lanes_of.setdefault((origin, destination), []).append(f"rank {rank}->{peer} lane {lane.lane}") - sparks = [] - for position in group.order: - planned = sorted(routes_at[position].values(), - key=lambda r: (FABRIC_NETDEVS.index(r.netdev), r.hops, _address_key(r.destination))) - planned = [dataclasses.replace(route, lanes=tuple(lanes_of.get((position, route.destination), ()))) - for route in planned] - filters = sorted(filters_at[position].values(), key=lambda f: (FABRIC_NETDEVS.index(f.in_netdev), f.k)) - sparks.append(SparkPlan(position, facts.name(position), group.label, tuple(planned), tuple(filters))) - by_position = {spark.position: spark for spark in sparks} - for spark in sparks: - for route in spark.routes: - result = trace(by_position, facts, group.ring_size, spark.position, route.destination, - fabric=layout.fabric) - if result.outcome != "delivered" or result.hops[-1] != (route.peer, route.peer_netdev): - raise FabricError(f"group {group.label}: the route from {spark.name} to {route.destination} does " - f"not deliver through the plan's relays ({result.outcome}: {result.detail})") - outside = [position for position, _ in result.hops if position not in members] - if outside: - raise FabricError(f"group {group.label}: the route from {spark.name} to {route.destination} " - f"crosses Sparks {outside} outside the group") - maps = [sircl.route_map(rank) for rank in range(layout.world)] - queues = [] - for (relay, secondary, egress_port), members_of_queue in sorted(routes.relay_queues(layout, maps).items()): - in_role = routes.role_at(1 - egress_port, secondary) - out_role = routes.role_at(egress_port, secondary if relay_egress == "same" else not secondary) - queues.append(RelayQueue(relay, in_role.netdev, out_role.netdev, - tuple(f"rank {r}->{p} lane {lane}" for r, p, lane in members_of_queue))) - busiest, load = routes.relay_load(sircl) - return GroupPlan(group, layout, sircl, relay_egress, max_relays, tuple(sparks), tuple(queues), busiest, load, - _digest(group.label, relay_egress, sparks)) - - -def build_layout_plan(layout: FabricLayout, facts: Facts, *, groups: Sequence[Group] | None = None, - max_relays: int = routes.DEFAULT_MAX_RELAYS) -> LayoutPlan: - """Plans of the layout's groups (or of ``groups``), checked for isolation across the whole layout.""" - problems = layout_isolation_problems(layout) - chosen = tuple(groups) if groups is not None else layout.groups - plans = tuple(build_group_plan(group, facts, relay_egress=layout.relay_egress, max_relays=max_relays) - for group in chosen) - problems += isolation_problems(plans) - if problems: - raise FabricError("isolation: " + "; ".join(problems)) - return LayoutPlan(layout, plans, facts.symbolic) - - -# -- checks ---------------------------------------------------------------------------------------- - - -@dataclasses.dataclass(frozen=True) -class Trace: - """Where a frame sent on an origin route went: ``delivered``, ``dropped``, ``misdelivered``, - ``unrouted`` or ``looped``; ``hops`` lists the (position, receiving device) of every cable crossed.""" - - outcome: str - hops: tuple[tuple[int, str], ...] - detail: str = "" - - -def trace(sparks: Mapping[int, SparkPlan], facts: Facts, ring_size: int | None, origin: int, destination: str, - *, fabric: routes.Fabric | None = None, limit: int = 2 * MAX_TAG) -> Trace: - """Follow a frame from ``origin`` to ``destination`` through the plan's objects on the physical fabric. - - When ``fabric`` is provided, each hop follows its exact cable - (``fabric.cross``), so open chains/paths drop frames exiting an uncabled - endpoint port and arbitrary port pairings are traced faithfully. Otherwise, - falls back to a closed ring of ``ring_size`` Sparks where port 0 of - position ``i`` is cabled to port 1 of position ``(i + 1) % ring_size``. - """ - spark = sparks.get(origin) - route = spark.route_to(destination) if spark is not None else None - if route is None: - return Trace("unrouted", (), f"no origin route to {destination} at position {origin}") - mac, ethertype, here, out_netdev = route.next_mac, route.tag, origin, route.netdev - hops: list[tuple[int, str]] = [] - for _ in range(limit): - port = role_of_netdev(out_netdev).port - if fabric is not None: - step = fabric.cross(here, port) - if step is None: - return Trace("dropped", tuple(hops), - f"position {here} port {port} has no cable on this fabric") - there, expected_port = step.dst, step.dst_port - else: - if ring_size is None: - raise FabricError("trace requires either fabric or ring_size") - there = (here + 1) % ring_size if port == 0 else (here - 1) % ring_size - expected_port = 1 - port - receiver = facts.find_mac(mac) - if receiver is None or receiver[0] != there or role_of_netdev(receiver[1]).port != expected_port: - return Trace("misdelivered", tuple(hops), f"a frame for {mac} leaves position {here} port {port}; " - f"the cable ends at position {there} port {expected_port}") - hops.append(receiver) - netdev = receiver[1] - k = relays_left(ethertype) - if k == 0: - if facts.port(there, netdev).address == destination: - return Trace("delivered", tuple(hops)) - return Trace("misdelivered", tuple(hops), f"IPv4 frame for {destination} reached {netdev} at {there}") - relay = sparks.get(there) - relay_filter = relay.filter_for(netdev, k) if (relay is not None and k is not None) else None - if relay_filter is None: - return Trace("dropped", tuple(hops), f"no relay filter for EtherType 0x{ethertype:04x} on {netdev} " - f"at position {there}") - mac, ethertype, here, out_netdev = relay_filter.next_mac, tag(k - 1), there, relay_filter.out_netdev - return Trace("looped", tuple(hops), f"more than {limit} cables") - - -def isolation_problems(plans: Sequence[GroupPlan]) -> list[str]: - """Breaks of the group isolation rules within and across group plans; empty when isolated.""" - problems = [] - for plan in plans: - members = set(plan.group.members) - owned = set(plan.group.cables) - fabric = plan.layout.fabric - for spark in plan.sparks: - if spark.position not in members: - problems.append(f"{plan.group.label}: {spark.name} is not a member but has objects") - for route in spark.routes: - if route.peer not in members: - problems.append(f"{plan.group.label}: {spark.name} routes to {route.destination} of Spark " - f"{route.peer}, outside the group") - if not set(route.relays) <= members or not set(route.owned_cables) <= owned: - problems.append(f"{plan.group.label}: the route from {spark.name} to {route.destination} " - f"crosses {route.cables}, outside the group's cables {sorted(owned)}") - for relay_filter in spark.filters: - for netdev in (relay_filter.in_netdev, relay_filter.out_netdev): - port = role_of_netdev(netdev).port - if fabric.cable_at(spark.position, port) is None: - problems.append(f"{plan.group.label}: {spark.name} relays through {netdev} (port {port}), " - "whose cable the group does not own") - if relay_filter.next_position not in members: - problems.append(f"{plan.group.label}: {spark.name} relays toward Spark " - f"{relay_filter.next_position}, outside the group") - for first in range(len(plans)): - for second in range(first + 1, len(plans)): - a, b = plans[first], plans[second] - shared = set(a.group.members) & set(b.group.members) - if shared: - problems.append(f"{a.group.label} and {b.group.label} share Sparks {sorted(shared)}") - used_a = {cable for spark in a.sparks for route in spark.routes for cable in route.owned_cables} - used_b = {cable for spark in b.sparks for route in spark.routes for cable in route.owned_cables} - for cable in sorted((set(a.group.cables) | used_a) & (set(b.group.cables) | used_b)): - problems.append(f"{a.group.label} and {b.group.label} both use cable {cable}") - problems += routes.isolation_problems([plan.sircl for plan in plans]) - return problems - - -def layout_isolation_problems(layout: FabricLayout) -> list[str]: - """SIRCL's lane isolation check (``routes.isolation_problems``) over every group of a layout.""" - return routes.isolation_problems([routes.derive_routes(group.layout(), 2) for group in layout.groups]) - - -# -- rendering ---------------------------------------------------------------------------------------- - - -def render_text(plan: LayoutPlan, facts: Facts, *, details: bool = True) -> str: - layout = plan.layout - lines = [f"layout {layout.name} on a ring of {layout.ring_size}: {len(plan.groups)} group(s) planned of " - f"{len(layout.groups)}, relay egress {layout.relay_egress}" - + (" (symbolic facts: placeholders stand for addresses and MACs)" if plan.symbolic else "")] - for note in CONSTRAINTS: - lines.append(f" constraint: {note}") - for group in plan.groups: - counts = (sum(len(s.routes) for s in group.sparks), sum(len(s.filters) for s in group.sparks), - sum(len(s.markers) for s in group.sparks)) - lines.append(f"group {group.group.label}: Sparks {list(group.group.members)}, cables " - f"{list(group.group.cables) or 'none'}; {counts[0]} routes, {counts[1]} relay filters, " - f"{counts[2]} markers; plan {group.digest}") - if group.per_peer_bytes is None: - lines.append(" relay queues: none (no lane crosses a relay)") - else: - lines.append(f" relay queues: busiest {group.busiest_queue} SIRCL lanes, load factor " - f"{group.load_factor:g}; keep per-peer op sizes at or below {group.per_peer_bytes} bytes " - f"({RELAY_QUEUE_SHARE:.0%} of {HAIRPIN_QUEUE_BYTES >> 10} KiB / {group.load_factor:g})") - for rank in range(group.sircl.world): - lines.append(f" rank {rank} (position {group.layout.positions[rank]}): " - f"SIRCL_PEER_ROUTES={group.sircl.route_text(rank)}") - if not details: - continue - for queue in group.queues: - lines.append(f" queue {facts.name(queue.position)} {queue.in_netdev} -> {queue.out_netdev}: " - f"{len(queue.lanes)} SIRCL lanes") - for spark in group.sparks: - lines.append(f" {spark.name} (position {spark.position}): {len(spark.routes)} routes, " - f"{len(spark.filters)} relay filters, {len(spark.markers)} markers") - for route in spark.routes: - carried = f"; {', '.join(route.lanes)}" if route.lanes else "; not a SIRCL lane" - lines.append(f" route {route.destination}/32 dev {route.netdev} src {route.source} neighbour " - f"{route.next_mac} -> {facts.name(route.peer)} {route.peer_netdev}, {route.hops} hops " - f"through {list(route.relays)}, tag 0x{route.tag:04x}{carried}") - for rules in spark.markers: - lines.append(f" marker {rules.device}: " - + " ".join(f"{destination}=0x{value:04x}" for destination, value in rules.rules)) - for relay_filter in spark.filters: - lines.append(f" filter {relay_filter.in_netdev} pref {relay_filter.pref} " - f"0x{relay_filter.protocol:04x} -> 0x{relay_filter.new_type:04x}, dst {relay_filter.next_mac} " - f"({facts.name(relay_filter.next_position)} {relay_filter.next_netdev}), out " - f"{relay_filter.out_netdev} ({relay_filter.direction}, {relay_filter.lane_class} lanes)") - return "\n".join(lines) + importlib.import_module("sparkring_fabric.fabric.plan") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + +_ensure_sparkring_fabric() +sys.modules[__name__] = importlib.import_module("sparkring_fabric.fabric.plan") diff --git a/spark_transport/sircl/sparkring_sircl/fabric/state.py b/spark_transport/sircl/sparkring_sircl/fabric/state.py index 7c938e36..b0af0bcc 100644 --- a/spark_transport/sircl/sparkring_sircl/fabric/state.py +++ b/spark_transport/sircl/sparkring_sircl/fabric/state.py @@ -1,614 +1,30 @@ -"""What a Spark holds: the parsed output of the installer's read script. - -The read script (:func:`.commands.read_script`) prints ``@@
`` blocks: -the host name, the iproute2 versions, ``ip -j addr show``, the network device -of each RDMA device, ``ip -j -d route show table main``, -``ip -j neigh show nud permanent``, ``tc -j qdisc show`` and -``tc -j filter show ... ingress`` of the four fabric network devices, the -marker processes (``pgrep -a -x``), the marker executable's SHA-256, the head -of every marker log and the installer's record. :func:`parse` turns them into -a :class:`HostState`. - -Classification of what the host holds: - -- an *owned* route or neighbour carries routing protocol 82; -- a *relay* route is a /32 route, scope link, without gateway, over a fabric - network device to an address outside that device's own subnet, and a relay - neighbour is a permanent neighbour entry on a fabric device for such an - address. Relay objects without the mark are *unowned*: some other tooling - installed them. ``--adopt`` lets ``up`` and ``down`` take them over; -- relay filters are the filters at the reserved preferences 11 to 17 of chain - 0 on the ingress of a fabric device; marker processes are the processes - named after the marker executable. Both are the installer's by their - reserved identifiers. - -The parsers accept the JSON spellings of iproute2 releases 5.x and 6.x: a -filter protocol as a name, ``[decimal]`` or hexadecimal; a handle as a number -or ``0x`` string; pedit keys under either mask convention. -""" +"""Compatibility shim: canonical implementation lives in ``sparkring_fabric.fabric.state``.""" from __future__ import annotations -import dataclasses -import ipaddress -import json -from collections.abc import Mapping - -from . import commands -from .layouts import FabricError -from .plan import (ETH_P_IP, FABRIC_NETDEVS, RDMA_DEVICES, RESERVED_PREFS, Port, RelayFilter, port_from_text, - relays_left) - -_PROTOCOL_NAMES = { - "unspec": 0, "redirect": 1, "kernel": 2, "boot": 3, "static": 4, "gated": 8, "ra": 9, "mrt": 10, "zebra": 11, - "bird": 12, "dnrouted": 13, "xorp": 14, "ntk": 15, "dhcp": 16, "mrouted": 17, "keepalived": 18, "babel": 42, - "openr": 99, "bgp": 186, "isis": 187, "ospf": 188, "rip": 189, "eigrp": 192, -} -_ETHERTYPE_NAMES = {"ip": 0x0800, "ipv4": 0x0800, "arp": 0x0806, "rarp": 0x8035, "ipv6": 0x86DD, "802.1q": 0x8100, - "802.1ad": 0x88A8, "all": 0x0003, "lldp": 0x88CC, "mpls_uc": 0x8847, "mpls_mc": 0x8848} - - -def _int(value: object) -> int | None: - if isinstance(value, bool): - return None - if isinstance(value, int): - return value - if isinstance(value, str): - try: - return int(value.strip(), 0) - except ValueError: - return None - return None - - -def _hex(value: object) -> int | None: - if isinstance(value, int) and not isinstance(value, bool): - return value - if isinstance(value, str): - try: - return int(value.strip(), 16) - except ValueError: - return None - return None - - -def protocol_number(text: object) -> int | None: - """A routing protocol from iproute2's name or number; None for a name this table does not know.""" - if isinstance(text, int): - return text - if text is None: - return None - word = str(text).strip().lower() - if word.isdigit(): - return int(word) - return _PROTOCOL_NAMES.get(word) - - -def ethertype(text: object) -> int | None: - """A filter protocol as tc prints it: a name, ``[34997]``, ``0x88b5`` or a number.""" - if isinstance(text, int) and not isinstance(text, bool): - return text - if not isinstance(text, str): - return None - word = text.strip().lower() - if word.startswith("[") and word.endswith("]") and word[1:-1].isdigit(): - return int(word[1:-1]) - if word.startswith("0x"): - return _hex(word) - if word in _ETHERTYPE_NAMES: - return _ETHERTYPE_NAMES[word] - if word.isdigit(): - return int(word) - return None - - -def _key_ethertype(text: object) -> int | None: - """Flower's ``eth_type`` key: ``ipv4``, ``88b5`` (hexadecimal) and so on.""" - if isinstance(text, str) and len(text.strip()) == 4: - return _hex(text) - return ethertype(text) - - -# -- entries --------------------------------------------------------------------------------------- - - -@dataclasses.dataclass(frozen=True) -class Link: - name: str - mac: str - addresses: tuple[tuple[str, int], ...] # IPv4 (address, prefix length) - operstate: str - - def networks(self) -> tuple[ipaddress.IPv4Network, ...]: - return tuple(ipaddress.IPv4Interface(f"{address}/{length}").network for address, length in self.addresses) - - -@dataclasses.dataclass(frozen=True) -class RouteEntry: - destination: str - prefixlen: int - dev: str - source: str | None - scope: str - protocol: int | None - protocol_text: str - metric: int - gateway: str | None - kind: str - - @property - def owned(self) -> bool: - return self.protocol == commands.ROUTE_PROTOCOL - - def text(self) -> str: - parts = [f"{self.destination}/{self.prefixlen}"] - if self.gateway: - parts.append(f"via {self.gateway}") - parts.append(f"dev {self.dev}") - if self.source: - parts.append(f"src {self.source}") - parts.append(f"scope {self.scope} proto {self.protocol_text}") - if self.metric: - parts.append(f"metric {self.metric}") - return " ".join(parts) - - -@dataclasses.dataclass(frozen=True) -class NeighbourEntry: - destination: str - dev: str - mac: str - states: tuple[str, ...] - protocol: int | None - protocol_text: str - - @property - def owned(self) -> bool: - return self.protocol == commands.ROUTE_PROTOCOL - - @property - def permanent(self) -> bool: - return "PERMANENT" in self.states - - def text(self) -> str: - return (f"{self.destination} dev {self.dev} lladdr {self.mac or 'none'} {'/'.join(self.states)}" - + (f" proto {self.protocol_text}" if self.protocol_text else "")) - - -@dataclasses.dataclass(frozen=True) -class FilterEntry: - netdev: str - pref: int - chain: int - kind: str - protocol: int | None - handle: int | None - skip_sw: bool - in_hw: bool - dst_mac: str | None - new_type: int | None - out_dev: str | None - problem: str | None # why the actions are not a relay filter's - - @property - def reserved(self) -> bool: - return self.chain == 0 and self.pref in RESERVED_PREFS - - def matches(self, planned: RelayFilter) -> bool: - return (self.problem is None and self.kind == "flower" and self.chain == 0 and self.pref == planned.pref - and self.protocol == planned.protocol and self.handle == planned.handle and self.skip_sw - and self.dst_mac == planned.next_mac.lower() and self.new_type == planned.new_type - and self.out_dev == planned.out_netdev) - - def text(self) -> str: - protocol = f"0x{self.protocol:04x}" if self.protocol is not None else "unknown" - if self.problem: - body = f"not a relay filter ({self.problem})" - else: - new_type = f"0x{self.new_type:04x}" if self.new_type is not None else "?" - body = f"-> {new_type}, dst {self.dst_mac}, out {self.out_dev}" - flags = " ".join(flag for flag, on in (("skip_sw", self.skip_sw), ("in_hw", self.in_hw)) if on) - return f"{self.netdev} pref {self.pref} handle {self.handle} {protocol} {body} {flags}".rstrip() - - -@dataclasses.dataclass(frozen=True) -class MarkerProcess: - pid: int - argv: tuple[str, ...] - device: str | None - rules: frozenset[tuple[str, int]] - managed: bool - problem: str | None - - def text(self) -> str: - rules = " ".join(f"{d}=0x{v:04x}" for d, v in sorted(self.rules)) - return f"pid {self.pid} {self.device or '?'}: {rules}" + ("" if self.managed else " (not --managed)") - - -# -- decoders ---------------------------------------------------------------------------------------- +import importlib +import sys +from pathlib import Path -def _json_list(text: str, what: str, problems: list[str]) -> list: - text = text.strip() - if not text: - return [] +def _ensure_sparkring_fabric() -> None: try: - value = json.loads(text) - except json.JSONDecodeError as error: - problems.append(f"{what}: not JSON ({error.msg})") - return [] - if not isinstance(value, list): - problems.append(f"{what}: not a JSON list") - return [] - return [entry for entry in value if isinstance(entry, dict)] - - -def parse_links(text: str, problems: list[str]) -> dict[str, Link]: - links = {} - for entry in _json_list(text, "ip -j addr show", problems): - name = str(entry.get("ifname", "")) - addresses = tuple((str(info.get("local")), int(info.get("prefixlen", 32))) - for info in entry.get("addr_info", []) if isinstance(info, dict) - and info.get("family") == "inet" and info.get("local")) - links[name] = Link(name, str(entry.get("address", "")).lower(), addresses, str(entry.get("operstate", ""))) - return links - - -def parse_routes(text: str, problems: list[str]) -> list[RouteEntry]: - found = [] - for entry in _json_list(text, "ip -j -d route show", problems): - destination = str(entry.get("dst", "")) - if destination == "default": - address, length = "0.0.0.0", 0 - elif "/" in destination: - address, _, length_text = destination.partition("/") - length = int(length_text) if length_text.isdigit() else -1 - else: - address, length = destination, 32 - try: - ipaddress.IPv4Address(address) - except ValueError: - continue - protocol_text = str(entry.get("protocol", "boot")) - found.append(RouteEntry(address, length, str(entry.get("dev", "")), entry.get("prefsrc"), - str(entry.get("scope", "global")), protocol_number(protocol_text), protocol_text, - _int(entry.get("metric")) or 0, entry.get("gateway"), - str(entry.get("type", "unicast")))) - return found - - -def parse_neighbours(text: str, problems: list[str]) -> list[NeighbourEntry]: - found = [] - for entry in _json_list(text, "ip -j neigh show", problems): - states = entry.get("state", []) - states = tuple(states) if isinstance(states, list) else (str(states),) - protocol_text = str(entry.get("protocol", "")) if entry.get("protocol") is not None else "" - found.append(NeighbourEntry(str(entry.get("dst", "")), str(entry.get("dev", "")), - str(entry.get("lladdr", "")).lower(), states, - protocol_number(protocol_text) if protocol_text else None, protocol_text)) - return found - - -def parse_ingress_qdisc(text: str, problems: list[str], netdev: str) -> str | None: - for entry in _json_list(text, f"tc -j qdisc show dev {netdev}", problems): - if entry.get("kind") in ("ingress", "clsact"): - return str(entry["kind"]) - return None - - -def _header_bytes(keys: list, keep_mask: bool) -> dict[int, int] | None: - header: dict[int, int] = {} - for key in keys: - offset, value, mask = _int(key.get("offset")), _hex(key.get("val")), _hex(key.get("mask")) - if offset is None or value is None or mask is None or offset % 4 or offset < 0: - return None - for index in range(4): - shift = 24 - 8 * index - byte_mask = (mask >> shift) & 0xFF - written = byte_mask == 0 if keep_mask else byte_mask == 0xFF - if written: - header[offset + index] = (value >> shift) & 0xFF - elif byte_mask not in (0, 0xFF): - return None - return header - - -def decode_filter(netdev: str, entry: Mapping[str, object]) -> FilterEntry | None: - """One ``tc -j filter show`` entry; None for the per-preference summary entry without options.""" - options = entry.get("options") - if not isinstance(options, dict): - return None - pref = _int(entry.get("pref")) - chain = _int(entry.get("chain")) or 0 - kind = str(entry.get("kind", "")) - keys = options.get("keys") if isinstance(options.get("keys"), dict) else {} - protocol = ethertype(entry.get("protocol")) - if protocol is None: - protocol = _key_ethertype(keys.get("eth_type")) - actions = [action for action in options.get("actions", []) or [] if isinstance(action, dict)] - problem = None - pedit_keys = [] - for action in actions: - if action.get("kind") == "pedit": - for key in action.get("keys", []) or []: - if not isinstance(key, dict) or key.get("htype", "eth") != "eth" or key.get("cmd", "set") != "set": - problem = "a pedit key is not an Ethernet header set" - pedit_keys.append(key) - mirreds = [action for action in actions if action.get("kind") == "mirred"] - others = [action.get("kind") for action in actions if action.get("kind") not in ("pedit", "mirred")] - header = None - for keep_mask in (True, False): - candidate = _header_bytes(pedit_keys, keep_mask) if problem is None else None - if candidate is not None and set(candidate) == {0, 1, 2, 3, 4, 5, 12, 13}: - header = candidate - break - if problem is None and header is None: - problem = "the pedit actions do not set exactly the destination MAC and the EtherType" - if problem is None and others: - problem = f"other actions {others}" - out_dev = None - if problem is None: - if (len(mirreds) == 1 and actions[-1] is mirreds[0] and mirreds[0].get("mirred_action") == "redirect" - and mirreds[0].get("direction") == "egress"): - out_dev = str(mirreds[0].get("to_dev", "")) - else: - problem = "the last action is not one egress redirect" - dst_mac = ":".join(f"{header[index]:02x}" for index in range(6)) if header else None - new_type = (header[12] << 8) | header[13] if header else None - return FilterEntry(netdev, pref if pref is not None else -1, chain, kind, protocol, _int(options.get("handle")), - bool(options.get("skip_sw")), bool(options.get("in_hw")), dst_mac, new_type, out_dev, - problem) - - -def parse_filters(text: str, problems: list[str], netdev: str) -> list[FilterEntry]: - found = [] - for entry in _json_list(text, f"tc -j filter show dev {netdev} ingress", problems): - decoded = decode_filter(netdev, entry) - if decoded is not None: - found.append(decoded) - return found - - -def parse_markers(text: str) -> list[MarkerProcess]: - found = [] - for line in text.splitlines(): - words = line.split() - if len(words) < 2 or not words[0].isdigit(): - continue - argv = tuple(words[1:]) - device, rules, problem = None, set(), None - index = 1 - while index < len(argv): - word = argv[index] - if word == "--device" and index + 1 < len(argv): - device = argv[index + 1] - index += 2 - continue - if word == "--rule" and index + 1 < len(argv): - destination, _, value = argv[index + 1].partition("=") - number = _int(value) - if number is None: - problem = f"rule {argv[index + 1]!r} is not ADDRESS=ETHERTYPE" - else: - rules.add((destination, number)) - index += 2 - continue - index += 1 - found.append(MarkerProcess(int(words[0]), argv, device, frozenset(rules), "--managed" in argv, problem)) - return found - - -# -- host state --------------------------------------------------------------------------------------- - - -@dataclasses.dataclass -class HostState: - """Everything the read script found on one Spark.""" - - position: int - name: str - ssh: str - reachable: bool - error: str = "" - hostname: str = "" - versions: str = "" - links: dict[str, Link] = dataclasses.field(default_factory=dict) - rdma: dict[str, str] = dataclasses.field(default_factory=dict) - routes: list[RouteEntry] = dataclasses.field(default_factory=list) - neighbours: list[NeighbourEntry] = dataclasses.field(default_factory=list) - ingress_qdisc: dict[str, str | None] = dataclasses.field(default_factory=dict) - filters: dict[str, list[FilterEntry]] = dataclasses.field(default_factory=dict) - markers: list[MarkerProcess] = dataclasses.field(default_factory=list) - marker_binary: str | None = None - marker_uid: int | None = None - marker_gid: int | None = None - marker_mode: int | None = None - marker_expected_sha256: str | None = None - marker_logs: dict[str, dict | None] = dataclasses.field(default_factory=dict) - record: dict | None = None - record_problem: str | None = None - raw: dict[str, str] = dataclasses.field(default_factory=dict) - parse_problems: list[str] = dataclasses.field(default_factory=list) - - # -- facts -- - - def port(self, netdev: str) -> Port | None: - link = self.links.get(netdev) - if link is None or len(link.addresses) != 1 or not link.mac: - return None - address, length = link.addresses[0] - try: - return port_from_text(netdev, link.mac, f"{address}/{length}", owner=self.name) - except FabricError: - return None - - def ports(self) -> tuple[Port, ...]: - return tuple(port for port in (self.port(netdev) for netdev in FABRIC_NETDEVS) if port is not None) - - def fact_problems(self, *, check_hostname: bool = True) -> list[str]: - if not self.reachable: - return [f"{self.name}: unreachable ({self.error})"] - problems = [f"{self.name}: {problem}" for problem in self.parse_problems] - if check_hostname and self.hostname != self.name: - problems.append(f"{self.name}: the host at {self.ssh} is named {self.hostname or 'nothing'}, the site " - "lists it as " + self.name) - for device, netdev in zip(RDMA_DEVICES, FABRIC_NETDEVS): - if self.rdma.get(device) != netdev: - problems.append(f"{self.name}: RDMA device {device} belongs to network device " - f"{self.rdma.get(device) or 'none'}, expected {netdev}") - for netdev in FABRIC_NETDEVS: - link = self.links.get(netdev) - if link is None: - problems.append(f"{self.name}: network device {netdev} is missing") - elif len(link.addresses) != 1: - problems.append(f"{self.name}: {netdev} has {len(link.addresses)} IPv4 addresses; one is needed") - elif self.port(netdev) is None: - problems.append(f"{self.name}: {netdev} has no usable MAC or IPv4 address") - return problems - - # -- classification -- - - def on_link(self, netdev: str, address: str) -> bool: - link = self.links.get(netdev) - if link is None: - return False - try: - value = ipaddress.IPv4Address(address) - except ValueError: - return False - return any(value in network for network in link.networks()) - - def is_relay_route(self, route: RouteEntry) -> bool: - return (route.prefixlen == 32 and route.dev in FABRIC_NETDEVS and route.scope == "link" - and not route.gateway and route.kind == "unicast" and not self.on_link(route.dev, route.destination)) - - def relay_routes(self) -> list[RouteEntry]: - """Owned routes and unowned relay routes.""" - return [route for route in self.routes if route.owned or self.is_relay_route(route)] - - def is_relay_neighbour(self, neighbour: NeighbourEntry) -> bool: - return (neighbour.permanent and neighbour.dev in FABRIC_NETDEVS - and (neighbour.owned or not self.on_link(neighbour.dev, neighbour.destination))) - - def relay_neighbours(self) -> list[NeighbourEntry]: - return [neighbour for neighbour in self.neighbours if neighbour.owned or self.is_relay_neighbour(neighbour)] - - def reserved_filters(self, netdev: str) -> list[FilterEntry]: - return [entry for entry in self.filters.get(netdev, []) if entry.reserved] - - def foreign_tag_filters(self) -> list[FilterEntry]: - """Filters outside the reserved preferences that match a relay tag (they could take relayed frames).""" - return [entry for netdev in FABRIC_NETDEVS for entry in self.filters.get(netdev, []) - if not entry.reserved and entry.protocol is not None and entry.protocol != ETH_P_IP - and relays_left(entry.protocol)] - - def unowned_relay_objects(self) -> tuple[list[RouteEntry], list[NeighbourEntry]]: - return ([route for route in self.relay_routes() if not route.owned], - [neighbour for neighbour in self.relay_neighbours() if not neighbour.owned]) - - def marker_problems(self, path: str, *, expected_sha256: str | None = None) -> list[str]: - """Integrity problems that stop running ``path`` as root (empty when safe).""" - if self.marker_binary is None: - return [f"the marker executable {path} is missing; build it with the `marker` command"] - problems: list[str] = [] - if self.marker_uid is None or self.marker_mode is None: - problems.append(f"the marker executable {path} ownership and permissions could not be verified; " - "reinstall it with the `marker --rebuild --apply` command") - else: - if self.marker_uid != 0: - problems.append(f"the marker executable {path} is owned by uid {self.marker_uid}, expected root " - "(uid 0); reinstall it with the `marker --rebuild --apply` command") - if self.marker_mode & 0o022: - problems.append(f"the marker executable {path} has group/world-writable mode {self.marker_mode:04o}; " - "reinstall it with the `marker --rebuild --apply` command") - expected_sources: list[tuple[str, str]] = [] - if expected_sha256 is not None: - expected_sources.append(("configured", expected_sha256.lower())) - if self.marker_expected_sha256 is not None: - expected_sources.append(("recorded digest", self.marker_expected_sha256.lower())) - recorded = (self.record or {}).get("marker_sha256") - if isinstance(recorded, str) and len(recorded) == 64: - expected_sources.append(("state record", recorded.lower())) - actual = self.marker_binary.lower() - for label, expected in expected_sources: - if actual != expected: - problems.append(f"the marker executable {path} sha256 {actual} does not match {label} {expected}; " - "reinstall it with the `marker --rebuild --apply` command") - return problems - - -def parse_sections(stdout: str) -> dict[str, str]: - """``@@`` blocks of a script's output, by name.""" - sections: dict[str, list[str]] = {} - current = None - for line in stdout.splitlines(): - if line.startswith(commands.SECTION): - current = line[len(commands.SECTION):].strip() - sections[current] = [] - elif current is not None: - sections[current].append(line) - return {key: "\n".join(value) for key, value in sections.items()} - - -def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, stderr: str) -> HostState: - """The :class:`HostState` of one Spark from its read script's output.""" - state = HostState(position, name, ssh, reachable=True) - sections = parse_sections(stdout) - if "end" not in sections: - state.reachable = bool(sections) - detail = (stderr.strip().splitlines() or [f"exit code {returncode}"])[-1] - state.error = detail if not sections else f"the read script stopped early ({detail})" - if not state.reachable: - return state - state.parse_problems.append(state.error) - state.raw = sections - raw = state.raw - problems = state.parse_problems - state.hostname = raw.get("hostname", "").strip() - state.versions = " | ".join(line.strip() for line in raw.get("versions", "").splitlines() if line.strip()) - state.links = parse_links(raw.get("links", ""), problems) - for device in RDMA_DEVICES: - netdevs = raw.get(f"rdma:{device}", "").split() - state.rdma[device] = netdevs[0] if netdevs else "" - state.routes = parse_routes(raw.get("routes", ""), problems) - state.neighbours = parse_neighbours(raw.get("neighbours", ""), problems) - for netdev in FABRIC_NETDEVS: - state.ingress_qdisc[netdev] = parse_ingress_qdisc(raw.get(f"qdisc:{netdev}", ""), problems, netdev) - state.filters[netdev] = parse_filters(raw.get(f"filters:{netdev}", ""), problems, netdev) - state.markers = parse_markers(raw.get("markers", "")) - binary = raw.get("marker-binary", "").split() - state.marker_binary = (binary[0].lower() - if binary and len(binary[0]) == 64 and all(c in "0123456789abcdef" for c in binary[0].lower()) - else None) - meta = raw.get("marker-stat", "").split() - if len(meta) >= 3 and meta[0].isdigit() and meta[1].isdigit(): - try: - state.marker_uid = int(meta[0]) - state.marker_gid = int(meta[1]) - state.marker_mode = int(meta[2], 8) - except ValueError: - pass - expected = raw.get("marker-sha256", "").split() - state.marker_expected_sha256 = ( - expected[0].lower() - if expected and len(expected[0]) == 64 and all(c in "0123456789abcdef" for c in expected[0].lower()) - else None - ) - for device in RDMA_DEVICES: - text = raw.get(f"marker-log:{device}", "").strip() - first = text.splitlines()[0] if text else "" - try: - state.marker_logs[device] = json.loads(first) if first.startswith("{") else ( - {"error": text[:300]} if text else None) - except json.JSONDecodeError: - state.marker_logs[device] = {"error": text[:300]} - record_text = raw.get("record", "").strip() - if record_text: - try: - record = json.loads(record_text) - if not isinstance(record, dict) or record.get("schema") != commands.RECORD_SCHEMA: - raise ValueError(f"schema is not {commands.RECORD_SCHEMA}") - state.record = record - except (ValueError, json.JSONDecodeError) as error: - state.record_problem = f"the record {commands.RECORD_PATH} is unreadable: {error}" - return state + importlib.import_module("sparkring_fabric.fabric.state") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + +_ensure_sparkring_fabric() +sys.modules[__name__] = importlib.import_module("sparkring_fabric.fabric.state") diff --git a/spark_transport/sircl/sparkring_sircl/routes.py b/spark_transport/sircl/sparkring_sircl/routes.py index 2742dcd9..0f642a3e 100644 --- a/spark_transport/sircl/sparkring_sircl/routes.py +++ b/spark_transport/sircl/sparkring_sircl/routes.py @@ -1,935 +1,31 @@ -"""Fabric layouts and route maps of SIRCL ring sessions. - -Physical model. A DGX Spark has one ConnectX-7 with ports 0 and 1; each port -appears as a primary and a secondary PCIe function, each with its own RDMA -device. The repository names the four functions by role: - - cw_primary rocep1s0f0 port 0, primary - cw_secondary roceP2p1s0f0 port 0, secondary - ccw_primary rocep1s0f1 port 1, primary - ccw_secondary roceP2p1s0f1 port 1, secondary - -These are the names DGX OS gives the functions (:data:`DEFAULT_ROLES`). -When ``SIRCL_FABRIC_DOCUMENT`` names a fabric document (schema -``sparkring-fabric/v1``, written by SparkRing's setup), the devices and -network interfaces come from its port functions instead -(:func:`load_roles`); every Spark of the fabric must name them alike. - -A cable joins one port of one Spark to one port of another and carries two -links (the primary functions of its ends and the secondary functions). A -group's fabric is the set of cables it owns, written as -``".port

-.port"``; every Spark has two ports, so a -fabric is a path or a cycle. Ring cabling joins position ``i``'s port 0 to -position ``i+1``'s port 1. - -Route maps. A rank's route map names, for every other rank of its session, -the local RDMA devices of lanes ``0 .. L-1`` (``L`` is 1 or 2). Textual form -(``SIRCL_PEER_ROUTES``): ``=[/][,...]``. - -Derivation (:func:`derive_lanes`), for a lane set from position ``a`` to -position ``b``: take the shortest paths in the fabric (one, or two when the -two ends are opposite on an even cycle or joined by two cables). With one -path, lane 0 uses the primary and lane 1 the secondary function of the path's -first cable at ``a``. With two paths, path A is the one that leaves the end -with the smaller position through its port 0; lane 0 uses the primary function -on path A and lane 1 the secondary function on path B. A lane's remote device -is the function of the same class at the far end of its last cable. Subgroup -sessions use their parent group's fabric. - -Validation (:func:`validate_route_map`) checks one rank's map before setup; -:func:`check_complementary` checks every ordered pair of ranks against the -layout; :func:`relay_load` gives the relay queue load factor of a group. - -Status: implemented; checked against the reference route vectors of the -tests (``tests/data/routes.json``). -""" +"""Compatibility shim: canonical route planning now lives in ``sparkring_fabric.routes``.""" from __future__ import annotations -import dataclasses -import json -import os -import re -from collections import deque +import importlib +import sys from pathlib import Path -from collections.abc import Iterable, Mapping, Sequence - -from .protocol import MAX_DEVICES, MAX_LANES - -DEFAULT_MAX_RELAYS = 3 - - -class RouteError(ValueError): - """A route map or layout breaks a route rule (the message names the rank, entry and rule).""" - - -@dataclasses.dataclass(frozen=True) -class Role: - """One PCIe function of a Spark's ConnectX-7.""" - - name: str - device: str - netdev: str - port: int - secondary: bool - - @property - def label(self) -> str: - """The hyphenated spelling of the role, e.g. ``cw-primary``.""" - return self.name.replace("_", "-") -# The four functions under the names DGX OS gives a DGX Spark's ConnectX-7. -DEFAULT_ROLES = ( - Role("cw_primary", "rocep1s0f0", "enp1s0f0np0", 0, False), - Role("cw_secondary", "roceP2p1s0f0", "enP2p1s0f0np0", 0, True), - Role("ccw_primary", "rocep1s0f1", "enp1s0f1np1", 1, False), - Role("ccw_secondary", "roceP2p1s0f1", "enP2p1s0f1np1", 1, True), -) -FABRIC_DOCUMENT_SCHEMA = "sparkring-fabric/v1" -FABRIC_DOCUMENT_VARIABLE = "SIRCL_FABRIC_DOCUMENT" - - -def roles_from_fabric_document(document: Mapping[str, object]) -> tuple[Role, ...]: - """The four function roles a ``sparkring-fabric/v1`` document names. - - Every entry of ``positions`` names, under ``ports..functions.`` - (port ``"0"`` or ``"1"``, function ``primary`` or ``secondary``), the RDMA - device (``rdma``) and the network interface (``netdev``). A route map names - devices, and a lane's remote device is the function of the same role on the - far Spark, so every position must name each role alike; a document whose - positions differ is refused, naming the position and the role. - """ - if not isinstance(document, Mapping) or document.get("schema") != FABRIC_DOCUMENT_SCHEMA: - raise RouteError(f"the fabric document's schema is not {FABRIC_DOCUMENT_SCHEMA}") - positions = document.get("positions") - if not isinstance(positions, Sequence) or isinstance(positions, str) or not positions: - raise RouteError("the fabric document lists no positions") - roles: tuple[Role, ...] | None = None - for entry in positions: - position = entry.get("position") if isinstance(entry, Mapping) else None - named = [] - for default in DEFAULT_ROLES: - function = "secondary" if default.secondary else "primary" - try: - names = entry["ports"][str(default.port)]["functions"][function] - device, netdev = names["rdma"], names["netdev"] - except (KeyError, TypeError, IndexError): - raise RouteError(f"position {position} of the fabric document does not name the RDMA " - f"device and network interface of port {default.port} {function}") from None - if not (isinstance(device, str) and device and isinstance(netdev, str) and netdev): - raise RouteError(f"position {position} of the fabric document names an empty device or " - f"interface for port {default.port} {function}") - named.append(dataclasses.replace(default, device=device, netdev=netdev)) - if roles is None: - roles = tuple(named) - elif tuple(named) != roles: - differing = next(mine for mine, first in zip(named, roles) if mine != first) - raise RouteError(f"position {position} of the fabric document names port {differing.port} " - f"{'secondary' if differing.secondary else 'primary'} differently from the " - "first position; SIRCL needs every Spark of a fabric to name its functions " - "alike") - assert roles is not None - if len({role.device for role in roles}) != len(roles) or len({role.netdev for role in roles}) != len(roles): - raise RouteError("the fabric document names one device or interface for two functions") - return roles - - -def load_roles(environ: Mapping[str, str] | None = None) -> tuple[Role, ...]: - """The roles of the document ``SIRCL_FABRIC_DOCUMENT`` names, else :data:`DEFAULT_ROLES`.""" - environ = os.environ if environ is None else environ - path = (environ.get(FABRIC_DOCUMENT_VARIABLE) or "").strip() - if not path: - return DEFAULT_ROLES +def _ensure_sparkring_fabric() -> None: try: - document = json.loads(Path(path).read_text(encoding="utf-8")) - except (OSError, ValueError) as error: - raise RouteError(f"{FABRIC_DOCUMENT_VARIABLE}={path}: {error}") from None - return roles_from_fabric_document(document) - - -# The roles every derivation and check in this process uses, read once at import. -ROLES = load_roles() -_BY_DEVICE = {role.device: role for role in ROLES} -_BY_NAME = {role.name: role for role in ROLES} - - -def role_at(port: int, secondary: bool) -> Role: - for role in ROLES: - if role.port == port and role.secondary == secondary: - return role - raise RouteError(f"no function on port {port}") - - -def role_of(device: str, roles: Mapping[str, Role] | None = None) -> Role | None: - """The role of an RDMA device name (canonical names unless ``roles`` maps others).""" - if roles is not None and device in roles: - return roles[device] - return _BY_DEVICE.get(device) - - -# -- fabric -------------------------------------------------------------------- - -_CABLE = re.compile(r"^\s*(\d+)\.port([01])\s*-\s*(\d+)\.port([01])\s*$") - - -@dataclasses.dataclass(frozen=True) -class Cable: - a: int - a_port: int - b: int - b_port: int - - def __post_init__(self) -> None: - if self.a == self.b: - raise RouteError(f"cable {self.text} joins a Spark to itself") - - @property - def text(self) -> str: - return f"{self.a}.port{self.a_port}-{self.b}.port{self.b_port}" - - @classmethod - def parse(cls, text: str) -> "Cable": - match = _CABLE.match(text) - if match is None: - raise RouteError(f"cable {text!r} is not written .port<0|1>-.port<0|1>") - a, a_port, b, b_port = (int(group) for group in match.groups()) - return cls(a, a_port, b, b_port) - - def ends(self) -> tuple[tuple[int, int], tuple[int, int]]: - return (self.a, self.a_port), (self.b, self.b_port) - - -@dataclasses.dataclass(frozen=True) -class Step: - """One cable crossed from (``src``, ``src_port``) to (``dst``, ``dst_port``).""" - - cable: Cable - src: int - src_port: int - dst: int - dst_port: int - - @property - def text(self) -> str: - return f"{self.src}.port{self.src_port}-{self.dst}.port{self.dst_port}" - - -@dataclasses.dataclass(frozen=True) -class Fabric: - """The cables a group owns.""" - - cables: tuple[Cable, ...] - - def __post_init__(self) -> None: - seen: dict[tuple[int, int], Cable] = {} - for cable in self.cables: - for end in cable.ends(): - if end in seen: - raise RouteError(f"port {end[1]} of position {end[0]} has two cables") - seen[end] = cable - - @classmethod - def ring(cls, size: int) -> "Fabric": - """A ring of ``size`` Sparks: position ``i`` port 0 to position ``i+1`` port 1.""" - if size < 2: - raise RouteError("a ring needs at least two Sparks") - return cls(tuple(Cable(i, 0, (i + 1) % size, 1) for i in range(size))) - - @classmethod - def path(cls, positions: Sequence[int]) -> "Fabric": - """Consecutive Sparks of a ring, each cabled port 0 to the next one's port 1.""" - positions = tuple(positions) - if len(positions) < 2: - raise RouteError("a path needs at least two Sparks") - return cls(tuple(Cable(a, 0, b, 1) for a, b in zip(positions, positions[1:]))) - - @classmethod - def parse(cls, texts: Iterable[str]) -> "Fabric": - return cls(tuple(Cable.parse(text) for text in texts)) - - @property - def positions(self) -> tuple[int, ...]: - return tuple(sorted({end[0] for cable in self.cables for end in cable.ends()})) - - def connected(self) -> bool: - """Whether every position of the fabric is reachable from every other over its cables.""" - nodes = self.positions - if not nodes: - return False - adjacency: dict[int, list[int]] = {node: [] for node in nodes} - for cable in self.cables: - adjacency[cable.a].append(cable.b) - adjacency[cable.b].append(cable.a) - seen = {nodes[0]} - queue = deque([nodes[0]]) - while queue: - here = queue.popleft() - for nxt in adjacency[here]: - if nxt not in seen: - seen.add(nxt) - queue.append(nxt) - return len(seen) == len(nodes) - - @property - def kind(self) -> str: - """``cycle`` when every Spark has two cables closing one connected loop, - ``path`` for one connected open chain, else ``disconnected``.""" - degree: dict[int, int] = {} - for cable in self.cables: - for position, _ in cable.ends(): - degree[position] = degree.get(position, 0) + 1 - if not degree or not self.connected(): - return "disconnected" - if all(count == 2 for count in degree.values()) and len(self.cables) == len(degree): - return "cycle" - return "path" - - def cable_at(self, position: int, port: int) -> Cable | None: - for cable in self.cables: - if (position, port) in cable.ends(): - return cable - return None - - def cross(self, position: int, port: int) -> Step | None: - """Leave ``position`` through ``port``; None when that port has no cable in this fabric.""" - cable = self.cable_at(position, port) - if cable is None: - return None - if (cable.a, cable.a_port) == (position, port): - return Step(cable, position, port, cable.b, cable.b_port) - return Step(cable, position, port, cable.a, cable.a_port) - - def shortest_paths(self, a: int, b: int) -> tuple[tuple[Step, ...], ...]: - """Every shortest cable path from ``a`` to ``b``.""" - if a == b: - raise RouteError("a lane joins two different Sparks") - distance = {b: 0} - queue = deque([b]) - while queue: - here = queue.popleft() - for port in (0, 1): - step = self.cross(here, port) - if step is not None and step.dst not in distance: - distance[step.dst] = distance[here] + 1 - queue.append(step.dst) - if a not in distance: - return () - paths: list[tuple[Step, ...]] = [] - - def extend(here: int, steps: list[Step]) -> None: - if here == b: - paths.append(tuple(steps)) - return - for port in (0, 1): - step = self.cross(here, port) - if step is not None and distance.get(step.dst) == distance[here] - 1: - steps.append(step) - extend(step.dst, steps) - steps.pop() - - extend(a, []) - return tuple(paths) - - def walk(self, start: int, port: int, target: int, limit: int) -> tuple[Step, ...] | None: - """Follow the fabric from ``start`` out of ``port`` (relays leave through their other port). - - Returns the steps up to ``target``, or None when the walk leaves the - fabric or exceeds ``limit`` cables first. - """ - steps: list[Step] = [] - here, out = start, port - while len(steps) < limit: - step = self.cross(here, out) - if step is None: - return None - steps.append(step) - if step.dst == target: - return tuple(steps) - here, out = step.dst, 1 - step.dst_port - return None - - -@dataclasses.dataclass(frozen=True) -class Layout: - """A session's layout identity: its fabric and the fabric position of every rank.""" - - fabric: Fabric - positions: tuple[int, ...] - - def __post_init__(self) -> None: - if len(set(self.positions)) != len(self.positions): - raise RouteError("ranks need distinct fabric positions") - known = set(self.fabric.positions) - missing = [p for p in self.positions if p not in known] - if missing: - raise RouteError(f"positions {missing} are not on the fabric") - - @property - def world(self) -> int: - return len(self.positions) - - def identity(self) -> dict[str, object]: - return { - "kind": self.fabric.kind, - "size": len(self.fabric.positions), - "positions": list(self.positions), - "cables": [cable.text for cable in self.fabric.cables], - } - - @classmethod - def parse(cls, text: str) -> "Layout": - """``ring:[:]``, ``path:-[:]`` or - ``cables=,...;positions=

,...``.""" - text = text.strip() - try: - if text.startswith("cables="): - cables_part, _, positions_part = text.partition(";") - fabric = Fabric.parse(cables_part[len("cables="):].split(",")) - if not positions_part.startswith("positions="): - raise RouteError("an explicit layout names positions=

,...") - positions = tuple(int(p) for p in positions_part[len("positions="):].split(",")) - return cls(fabric, positions) - kind, _, rest = text.partition(":") - span, _, ranks = rest.partition(":") - if kind == "ring": - fabric = Fabric.ring(int(span)) - elif kind == "path": - first, _, last = span.partition("-") - fabric = Fabric.path(range(int(first), int(last) + 1)) - else: - raise RouteError(f"layout {text!r} is not ring:, path: or cables=") - positions = (tuple(int(p) for p in ranks.split(",")) if ranks - else fabric.positions) - return cls(fabric, positions) - except ValueError as error: - if isinstance(error, RouteError): - raise - raise RouteError(f"layout {text!r} is malformed: {error}") from None - - -# -- derivation ------------------------------------------------------------------- - - -@dataclasses.dataclass(frozen=True) -class LaneRoute: - """One lane from a rank toward a peer.""" - - lane: int - local: Role - remote: Role - steps: tuple[Step, ...] - - @property - def hops(self) -> int: - return len(self.steps) - - @property - def relays(self) -> tuple[int, ...]: - return tuple(step.dst for step in self.steps[:-1]) - - @property - def cables(self) -> tuple[str, ...]: - return tuple(step.text for step in self.steps) - - def to_json(self) -> dict[str, object]: - return { - "lane": self.lane, - "local": self.local.device, - "remote": self.remote.device, - "local_role": self.local.label, - "remote_role": self.remote.label, - "hops": self.hops, - "relays": list(self.relays), - "cables": list(self.cables), - } - - -def derive_lanes(fabric: Fabric, a: int, b: int, lanes: int = 2) -> tuple[LaneRoute, ...]: - """The lanes from position ``a`` to position ``b`` (derivation rules above).""" - if lanes not in (1, 2): - raise RouteError("a session has one or two lanes per peer") - paths = fabric.shortest_paths(a, b) - if not paths: - raise RouteError(f"position {b} cannot be reached from position {a} on this fabric") - if len(paths) == 1: - chosen = (paths[0], paths[0]) - elif len(paths) == 2: - smaller = min(a, b) - - def leaves_smaller_through_port0(path: tuple[Step, ...]) -> bool: - if smaller == a: - return path[0].src_port == 0 - return path[-1].dst_port == 0 - - path_a = [path for path in paths if leaves_smaller_through_port0(path)] - if len(path_a) != 1: - raise RouteError(f"cannot tell path A from path B between positions {a} and {b}") - path_b = next(path for path in paths if path is not path_a[0]) - chosen = (path_a[0], path_b) - else: - raise RouteError(f"{len(paths)} shortest paths between positions {a} and {b}") - result = [] - for lane in range(lanes): - path = chosen[lane] - secondary = lane == 1 - result.append(LaneRoute(lane, role_at(path[0].src_port, secondary), - role_at(path[-1].dst_port, secondary), path)) - return tuple(result) - - -@dataclasses.dataclass(frozen=True) -class GroupRoutes: - """Every rank's lanes for one session.""" - - layout: Layout - lanes: int - ranks: tuple[Mapping[int, tuple[LaneRoute, ...]], ...] - - @property - def world(self) -> int: - return self.layout.world - - def route_map(self, rank: int) -> dict[int, tuple[str, ...]]: - """Peer rank to lane device names.""" - return {peer: tuple(lane.local.device for lane in lanes) - for peer, lanes in sorted(self.ranks[rank].items())} - - def route_text(self, rank: int) -> str: - return format_peer_routes(self.route_map(rank)) - - def lanes_to(self, rank: int, peer: int) -> tuple[LaneRoute, ...]: - return self.ranks[rank][peer] - - def max_relays(self) -> int: - return max((len(lane.relays) for rank in self.ranks for lanes in rank.values() for lane in lanes), - default=0) - - -def _required_ring_peers(rank: int, world: int, layout: Layout | None) -> list[int]: - """The immediate neighbor peer ranks required for a sparse ``--ring-only`` route map.""" - if layout is not None: - rank_of = {pos: idx for idx, pos in enumerate(layout.positions)} - start = layout.positions[rank] - neighbors = sorted({ - rank_of[step.dst] - for port in (0, 1) - if (step := layout.fabric.cross(start, port)) is not None and step.dst in rank_of - } - {rank}) - if neighbors: - return neighbors - return sorted({(rank - 1) % world, (rank + 1) % world} - {rank}) - - -def derive_routes(layout: Layout, lanes: int = 2, *, ring_only: bool = False) -> GroupRoutes: - """Route maps of every rank of a session on ``layout``. - - With ``ring_only=True``, each rank includes only its immediate ring/chain neighbors. - """ - ranks = [] - world = layout.world - for rank, here in enumerate(layout.positions): - peers = _required_ring_peers(rank, world, layout) if ring_only else [ - peer for peer in range(world) if peer != rank - ] - ranks.append({peer: derive_lanes(layout.fabric, here, layout.positions[peer], lanes) - for peer in peers}) - return GroupRoutes(layout, lanes, tuple(ranks)) - - -# -- textual form ----------------------------------------------------------------- - - -def parse_peer_routes(text: str) -> dict[int, tuple[str, ...]]: - """Parse ``=[/],...``; duplicate peers raise.""" - routes: dict[int, tuple[str, ...]] = {} - if text is None or not text.strip(): - raise RouteError("the route map is empty") - for entry in text.split(","): - entry = entry.strip() - if not entry: - raise RouteError(f"route map {text!r} has an empty entry") - peer_text, separator, devices_text = entry.partition("=") - if not separator: - raise RouteError(f"route map entry {entry!r} is not =[/]") - try: - peer = int(peer_text.strip()) - except ValueError: - raise RouteError(f"route map entry {entry!r} names peer {peer_text.strip()!r}, not a rank") from None - if peer in routes: - raise RouteError(f"route map names rank {peer} twice") - routes[peer] = tuple(device.strip() for device in devices_text.split("/")) - return routes - - -def format_peer_routes(routes: Mapping[int, Sequence[str]]) -> str: - return ",".join(f"{peer}={'/'.join(devices)}" for peer, devices in sorted(routes.items())) - - -# -- validation ------------------------------------------------------------------- - - -def validate_route_map( - rank: int, - world: int, - routes: Mapping[int, Sequence[str]], - *, - layout: Layout | None = None, - max_relays: int = DEFAULT_MAX_RELAYS, - available_devices: Iterable[str] | None = None, - roles: Mapping[str, Role] | None = None, - ring_only: bool = False, -) -> int: - """Check one rank's route map; return its lane count ``L``. - - Rules: every required peer named exactly once (every other rank by default, - or immediate ring/chain neighbors when ``ring_only=True``) and the own rank - not at all; every entry with the same lane count, 1 or 2, of distinct - non-empty device names; 1 to 4 devices in all, each available when - ``available_devices`` is given; with a layout, every lane stays inside the - fabric and crosses at most ``max_relays`` relays. Errors name the rank, the - entry and the rule. - """ - if not 0 <= rank < world: - raise RouteError(f"rank {rank} is outside a session of {world}") - if rank in routes: - raise RouteError(f"rank {rank}'s route map names its own rank") - if layout is not None and layout.world != world: - raise RouteError(f"layout has {layout.world} ranks, the session {world}") - required = (_required_ring_peers(rank, world, layout) if ring_only - else [peer for peer in range(world) if peer != rank]) - missing = [peer for peer in required if peer not in routes] - if missing: - raise RouteError(f"rank {rank}'s route map has no entry for rank {missing[0]}") - if not routes: - raise RouteError(f"rank {rank}'s route map is empty") - extra = sorted(peer for peer in routes if not 0 <= peer < world) - if extra: - raise RouteError(f"rank {rank}'s route map names rank {extra[0]}, outside the session") - counts = {len(devices) for devices in routes.values()} - if len(counts) != 1: - raise RouteError(f"rank {rank}'s route map entries have different lane counts {sorted(counts)}") - lanes = counts.pop() - if not 1 <= lanes <= MAX_LANES: - raise RouteError(f"rank {rank}'s route map has {lanes} lanes per peer; one or two are supported") - for peer, devices in sorted(routes.items()): - if any(not device for device in devices): - raise RouteError(f"rank {rank}'s entry for rank {peer} has an empty device name") - if len(set(devices)) != len(devices): - raise RouteError(f"rank {rank}'s entry for rank {peer} names device {devices[0]} twice") - named = list(dict.fromkeys(device for _, devices in sorted(routes.items()) for device in devices)) - if not 1 <= len(named) <= MAX_DEVICES: - raise RouteError(f"rank {rank}'s route map names {len(named)} devices; 1 to {MAX_DEVICES} are supported") - if available_devices is not None: - available = set(available_devices) - for device in named: - if device not in available: - raise RouteError(f"rank {rank}'s route map names device {device}, which is not an active " - "RDMA device of this host") - if layout is not None: - start = layout.positions[rank] - for peer, devices in sorted(routes.items()): - for lane, device in enumerate(devices): - role = role_of(device, roles) - if role is None: - raise RouteError(f"rank {rank} lane {lane} toward rank {peer} uses device {device}, " - "whose port and function the layout check cannot tell") - steps = layout.fabric.walk(start, role.port, layout.positions[peer], - limit=len(layout.fabric.positions)) - if steps is None: - raise RouteError( - f"rank {rank} lane {lane} toward rank {peer} leaves through {device} (port " - f"{role.port}) and crosses a Spark outside the group's fabric") - if len(steps) - 1 > max_relays: - raise RouteError( - f"rank {rank} lane {lane} toward rank {peer} crosses {len(steps) - 1} relays; the " - f"qualified limit is {max_relays} (SIRCL_MAX_RELAYS raises it, research-only)") - return lanes - - -def check_complementary( - layout: Layout, - route_maps: Sequence[Mapping[int, Sequence[str]]], - *, - roles: Mapping[str, Role] | None = None, -) -> list[str]: - """Problems with the cross-rank pairing of lanes (empty when every lane pairs). - - Lane ``l`` of rank ``r`` toward ``p`` and lane ``l`` of ``p`` toward ``r`` - must cross the same cables in opposite directions with the same function - class: ``p``'s device must be the function of ``r``'s class on the port - where ``r``'s lane arrives. - """ - problems = [] - for rank, routes in enumerate(route_maps): - for peer, devices in sorted(routes.items()): - for lane, device in enumerate(devices): - mine = role_of(device, roles) - theirs_device = route_maps[peer][rank][lane] if lane < len(route_maps[peer].get(rank, ())) else None - if mine is None or theirs_device is None: - problems.append(f"lane {lane} between ranks {rank} and {peer} cannot be checked") - continue - steps = layout.fabric.walk(layout.positions[rank], mine.port, layout.positions[peer], - limit=len(layout.fabric.positions)) - if steps is None: - problems.append(f"lane {lane} of rank {rank} toward rank {peer} does not reach it") - continue - expected = role_at(steps[-1].dst_port, mine.secondary) - theirs = role_of(theirs_device, roles) - if theirs != expected: - problems.append( - f"lane {lane} of rank {rank} leaves through port {mine.port} and arrives on rank " - f"{peer}'s port {steps[-1].dst_port} ({expected.device}), but rank {peer} lists " - f"{theirs_device} for lane {lane}") - return problems - - -def relay_load(routes: GroupRoutes) -> tuple[int, float]: - """``(lanes through the busiest relay queue, load factor f)``. - - A relay queue is one (relay Spark, function class, direction). When every - rank sends ``b`` bytes to every peer, split over ``L`` lanes, the busiest - queue holds about ``f * b`` bytes with ``f`` = lanes / ``L``. - """ - load: dict[tuple[int, bool, int], int] = {} - for rank in routes.ranks: - for lanes in rank.values(): - for lane in lanes: - for step in lane.steps[:-1]: - # Arriving on port 1 continues clockwise (out of port 0). - key = (step.dst, lane.local.secondary, step.dst_port) - load[key] = load.get(key, 0) + 1 - busiest = max(load.values(), default=0) - return busiest, busiest / routes.lanes - - -DEFAULT_FORWARD_WINDOW = 131072 -DEFAULT_FORWARD_CHUNK = 32768 -DEFAULT_HAIRPIN_QUEUE = 524288 -RELAY_QUEUE_SHARE = 0.75 - - -def _lane_steps(layout: Layout, rank: int, peer: int, device: str, - roles: Mapping[str, Role] | None) -> tuple[Role, tuple[Step, ...]] | None: - role = role_of(device, roles) - if role is None: - return None - steps = layout.fabric.walk(layout.positions[rank], role.port, layout.positions[peer], - limit=len(layout.fabric.positions)) - return (role, steps) if steps is not None else None - - -def relay_queues( - layout: Layout, - route_maps: Sequence[Mapping[int, Sequence[str]]], - *, - roles: Mapping[str, Role] | None = None, -) -> dict[tuple[int, bool, int], list[tuple[int, int, int]]]: - """Lanes through every relay hairpin queue of a group. - - Key: (relay position, secondary function, egress port); value: the - ``(rank, peer, lane)`` of every lane whose packets that queue forwards. - """ - queues: dict[tuple[int, bool, int], list[tuple[int, int, int]]] = {} - for rank, routes in enumerate(route_maps): - for peer, devices in sorted(routes.items()): - for lane, device in enumerate(devices): - found = _lane_steps(layout, rank, peer, device, roles) - if found is None: - continue - role, steps = found - for step in steps[:-1]: - key = (step.dst, role.secondary, 1 - step.dst_port) - queues.setdefault(key, []).append((rank, peer, lane)) - return queues - - -def ring_queues( - layout: Layout, - route_maps: Sequence[Mapping[int, Sequence[str]]], - order: Sequence[int], - *, - roles: Mapping[str, Role] | None = None, -) -> dict[tuple[int, bool, int], list[tuple[int, int, int]]]: - """Lanes of the ring over ``order`` (rank ``order[i]`` to ``order[(i + 1) % W]``) through every - relay hairpin queue, keyed as in :func:`relay_queues`; empty when every ring edge is a cable.""" - queues: dict[tuple[int, bool, int], list[tuple[int, int, int]]] = {} - world = len(order) - for i, rank in enumerate(order): - peer = order[(i + 1) % world] - if peer == rank: - continue - for lane, device in enumerate(route_maps[rank].get(peer, ())): - found = _lane_steps(layout, rank, peer, device, roles) - if found is None: - continue - role, steps = found - for step in steps[:-1]: - key = (step.dst, role.secondary, 1 - step.dst_port) - queues.setdefault(key, []).append((rank, peer, lane)) - return queues - - -def ring_window( - layout: Layout, - route_maps: Sequence[Mapping[int, Sequence[str]]], - order: Sequence[int], - *, - chunk: int = DEFAULT_FORWARD_CHUNK, - queue_bytes: int = DEFAULT_HAIRPIN_QUEUE, - roles: Mapping[str, Role] | None = None, - subset_ring: bool = False, -) -> tuple[int, list[str]]: - """``(window, problems)`` of the ring over ``order``: the bytes each ring lane through relays - keeps unacknowledged (0 when every ring edge is a cable), and why the ring cannot run. - - During a ring op the ring's lanes are a group's only relayed traffic, so a relay hairpin queue - holds the bytes of the ring lanes through it; the window is the largest multiple of ``chunk`` - within ``RELAY_QUEUE_SHARE`` of a queue when every queue carries at most one ring lane (relays - forward each function's lanes through that function's own queue). A queue that carries two - ring lanes is a problem. Subset mode uses the smaller shared packet envelope - from subset.payload_budget instead of the legacy payload share. - """ - queues = ring_queues(layout, route_maps, order, roles=roles) - allowance = int(RELAY_QUEUE_SHARE * queue_bytes) - if subset_ring: - from . import subset - allowance = subset.payload_budget(layout, route_maps, queue_bytes=queue_bytes) - problems = [f"relay {key[0]} {'secondary' if key[1] else 'primary'} function toward port {key[2]} carries " - f"ring lanes {members}" for key, members in sorted(queues.items()) if len(members) > 1] - if not queues: - return 0, problems - window = allowance // chunk * chunk - if window < chunk: - problems.append(f"a relay queue of {queue_bytes} bytes holds less than one {chunk}-byte chunk") - return window, problems - - -def forward_windows( - layout: Layout, - route_maps: Sequence[Mapping[int, Sequence[str]]], - rank: int, - *, - max_window: int = DEFAULT_FORWARD_WINDOW, - chunk: int = DEFAULT_FORWARD_CHUNK, - queue_bytes: int = DEFAULT_HAIRPIN_QUEUE, - roles: Mapping[str, Role] | None = None, - subset_ring: bool = False, -) -> list[list[int]]: - """Forward window in bytes of every lane of ``rank`` (``[peer][lane]``; 0 for direct lanes). - - A lane through relays gets the largest multiple of ``chunk`` that is at - most ``max_window`` and, for every relay queue it crosses, at most - ``RELAY_QUEUE_SHARE * queue_bytes / n``, where ``n`` lanes share that queue; - never less than one chunk. A ``max_window`` of 0 disables windows. Subset - mode instead rejects disabled windows and shares smaller than a chunk. - """ - world = layout.world - lanes = max((len(devices) for devices in route_maps[rank].values()), default=0) - table = [[0] * lanes for _ in range(world)] - allowance = int(RELAY_QUEUE_SHARE * queue_bytes) - if subset_ring: - from . import subset - allowance = subset.payload_budget(layout, route_maps, queue_bytes=queue_bytes) - if max_window <= 0: - raise RouteError("subset ring requires forward windows") - if max_window <= 0: - return table - if chunk <= 0 or chunk % 16 or max_window < chunk: - raise RouteError(f"forward chunk {chunk} must be a positive multiple of 16 within the window {max_window}") - queues = relay_queues(layout, route_maps, roles=roles) - load: dict[tuple[int, int, int], int] = {} - for members in queues.values(): - for member in members: - load[member] = max(load.get(member, 0), len(members)) - for peer, devices in sorted(route_maps[rank].items()): - for lane in range(len(devices)): - sharing = load.get((rank, peer, lane), 0) - if sharing == 0: - continue - limit = min(max_window, allowance // sharing) - if subset_ring and limit < chunk: - raise RouteError(f"subset relay allowance {allowance} cannot hold {sharing} chunks of {chunk} bytes") - table[peer][lane] = max(chunk, limit // chunk * chunk) - return table - - -def chain_order( - layout: Layout, - route_maps: Sequence[Mapping[int, Sequence[str]]], - *, - roles: Mapping[str, Role] | None = None, - subset_ring: bool = False, -) -> tuple[int, ...] | None: - """The ranks in chain order when the group's ranks form a chain of cable neighbors, else None. - - Every Spark of the fabric must host a rank unless subset_ring admits a - bounded, isolated arc through subset.validate. On a path the chain starts at the - end with the smaller position; on a cycle it starts at rank 0 and follows - port 0, leaving the cable that closes the cycle unused. Every lane between - consecutive ranks of the chain, in both directions, must be a direct lane - (no relay). - """ - fabric = layout.fabric - if fabric.kind == "disconnected": - return None - if sorted(layout.positions) != list(fabric.positions): - if not subset_ring: - return None - from . import subset - return subset.validate(layout, route_maps) - rank_at = {position: rank for rank, position in enumerate(layout.positions)} - if fabric.kind == "path": - degree: dict[int, int] = {} - for cable in fabric.cables: - for position, _ in cable.ends(): - degree[position] = degree.get(position, 0) + 1 - start = min(position for position in fabric.positions if degree.get(position, 0) <= 1) - else: - start = layout.positions[0] - order = [start] - previous = None - while len(order) < len(fabric.positions): - here = order[-1] - steps = [fabric.cross(here, port) for port in (0, 1)] - candidates = [step.dst for step in steps if step is not None and step.dst != previous - and step.dst not in order] - if fabric.kind != "path" and len(order) == 1: - first = fabric.cross(here, 0) - candidates = [first.dst] if first is not None else [] - if not candidates: - return None - previous = here - order.append(candidates[0]) - ranks = tuple(rank_at[position] for position in order) - for a, b in zip(ranks, ranks[1:]): - for source, target in ((a, b), (b, a)): - devices = route_maps[source].get(target) - if not devices: - return None - for device in devices: - found = _lane_steps(layout, source, target, device, roles) - if found is None or len(found[1]) != 1: - return None - return ranks - - -def isolation_problems(groups: Sequence[GroupRoutes]) -> list[str]: - """Cables or relays shared by independent groups on one ring (must be empty).""" - problems = [] - for first in range(len(groups)): - for second in range(first + 1, len(groups)): - a, b = groups[first], groups[second] - cables_a = {step.cable for rank in a.ranks for lanes in rank.values() for lane in lanes - for step in lane.steps} - cables_b = {step.cable for rank in b.ranks for lanes in rank.values() for lane in lanes - for step in lane.steps} - for cable in sorted(cables_a & cables_b, key=lambda c: c.text): - problems.append(f"groups {first} and {second} both use cable {cable.text}") - sparks_a = set(a.layout.positions) | {relay for rank in a.ranks for lanes in rank.values() - for lane in lanes for relay in lane.relays} - sparks_b = set(b.layout.positions) | {relay for rank in b.ranks for lanes in rank.values() - for lane in lanes for relay in lane.relays} - for spark in sorted(sparks_a & sparks_b): - problems.append(f"groups {first} and {second} both use Spark {spark}") - return problems + importlib.import_module("sparkring_fabric.routes") + return + except ModuleNotFoundError: + pass + for parent in Path(__file__).resolve().parents: + pkg_root = parent / "sparkring_fabric" + if (pkg_root / "sparkring_fabric" / "__init__.py").is_file(): + pkg_str = str(pkg_root) + if pkg_str not in sys.path: + sys.path.insert(0, pkg_str) + existing = sys.modules.get("sparkring_fabric") + if existing is not None and getattr(existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() + return + + +_ensure_sparkring_fabric() +_canonical = importlib.import_module("sparkring_fabric.routes") +sys.modules[__name__] = _canonical diff --git a/sparkring_fabric/README.md b/sparkring_fabric/README.md new file mode 100644 index 00000000..51e5cc51 --- /dev/null +++ b/sparkring_fabric/README.md @@ -0,0 +1,83 @@ +# sparkring-fabric + +Standalone, zero-dependency Python package for RDMA fabric route planning and ConnectX hardware relay management on switchless rings, open chains, and adjacent pairs of DGX Sparks. + +`sparkring-fabric` depends only on the Python standard library — no vLLM, no PyTorch, no CUDA, and no CuTe-DSL — so any RDMA workload (vLLM, SGLang, Flare, PyTorch/NCCL, or `libsircl`) can derive route maps, forward windows, relay queue budgets, and hardware relay plans without pulling in inference or kernel stacks. + +## Install + +```bash +pip install ./sparkring_fabric +``` + +## Route Planning (Rings, Open Chains, and `--ring-only`) + +```python +from sparkring_fabric import routes + +# Full 8-node closed ring with 2 RDMA lanes per peer +ring8 = routes.Layout.parse("ring:8") +group = routes.derive_routes(ring8, lanes=2) +print(group.route_text(0)) + +# Neighbor-only ring routes (zero relays, zero diagonal queue pairs) +ring_only = routes.derive_routes(ring8, lanes=2, ring_only=True) +print(ring_only.route_text(0)) + +# Open chain (path) of 4 nodes without a closing cable +path4 = routes.Layout.parse("path:0-3") +chain_group = routes.derive_routes(path4, lanes=2) +maps = [chain_group.route_map(r) for r in range(path4.world)] +print("chain order:", routes.chain_order(path4, maps)) +print("rank 0 forward windows:", routes.forward_windows(path4, maps, rank=0)) +``` + +Multi-group isolation checks confirm that independent groups on one ring share neither cables nor intermediate relays: + +```python +g0 = routes.derive_routes(routes.Layout.parse("path:0-3"), lanes=2) +g1 = routes.derive_routes(routes.Layout.parse("path:4-7"), lanes=2) +assert routes.isolation_problems([g0, g1]) == [] +``` + +## Relay Hairpin Queue Budgeting + +`sparkring_fabric.budget` sizes point-to-point channel windows within each ConnectX-7 hairpin queue's 75% share (of 512 KiB) after reserving collective session windows: + +```python +from sparkring_fabric import budget, routes + +layout = routes.Layout.parse("path:0-3") +lane_set = budget.LaneSet.of("layout", layout, lanes=2) +reserved = budget.session_reservation(lane_set, budget.SessionSettings()) +allocation = budget.allocate( + [[lane_set]], + reserved=reserved, + max_window=budget.DEFAULT_P2P_WINDOW_BYTES, + chunk=budget.DEFAULT_P2P_CHUNK_BYTES, +) +print(allocation.table(lane_set, lane_count=2)) +``` + +## Hardware Relay Management CLI (`sparkring-fabric`) + +The `sparkring-fabric` CLI (also `python -m sparkring_fabric.fabric`) derives, inspects, diffs, installs, and removes per-Spark origin routes, permanent neighbours, hardware `tc flower` relay filters, and the root-owned RDMA-TX EtherType tag marker (`mesh_marker.c`): + +```bash +# Offline plan with symbolic placeholders or a facts file +sparkring-fabric plan --layout ring8 --brief +sparkring-fabric plan --layout 2xTP4 +sparkring-fabric plan --groups "0-3;4-7" + +# Read-only remote inspection and dry-run diff +sparkring-fabric facts --site site.json --output facts.json +sparkring-fabric show --site site.json +sparkring-fabric diff --site site.json --layout ring8 + +# Build/install the root-owned marker executable and apply a relay plan +sparkring-fabric marker --site site.json --apply +sparkring-fabric up --site site.json --layout ring8 --apply +sparkring-fabric down --site site.json --layout ring8 --apply +``` + +For open-chain fabrics without a closing cable, `sparkring_fabric.fabric.plan.build_chain_plan` derives the relay plan directly from the path's cables. diff --git a/sparkring_fabric/pyproject.toml b/sparkring_fabric/pyproject.toml new file mode 100644 index 00000000..58be212f --- /dev/null +++ b/sparkring_fabric/pyproject.toml @@ -0,0 +1,31 @@ +[build-system] +requires = ["setuptools>=68"] +build-backend = "setuptools.build_meta" + +[project] +name = "sparkring-fabric" +version = "0.1.0" +description = "Standalone RDMA fabric route planning and ConnectX relay management for switchless rings, chains and pairs" +readme = "README.md" +requires-python = ">=3.10" +license = "Apache-2.0" +# Pure Python standard library: zero vLLM, PyTorch, CUDA or CuTe-DSL dependencies. +dependencies = [] + +[project.optional-dependencies] +test = ["pytest>=8"] + +[project.scripts] +sparkring-fabric = "sparkring_fabric.fabric.cli:main" + +[tool.setuptools.packages.find] +include = ["sparkring_fabric*"] + +[tool.setuptools.package-data] +sparkring_fabric = [ + "fabric/*.c", +] + +[tool.pytest.ini_options] +testpaths = ["tests"] +addopts = "-p no:cacheprovider" diff --git a/sparkring_fabric/sparkring_fabric/__init__.py b/sparkring_fabric/sparkring_fabric/__init__.py new file mode 100644 index 00000000..2a2da223 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/__init__.py @@ -0,0 +1,19 @@ +"""Standalone RDMA fabric route planning and ConnectX relay management. + +Zero vLLM, PyTorch, CUDA, or CuTe-DSL dependencies — pure Python standard library. +""" + +from __future__ import annotations + +from . import budget, fabric, routes, site, subset + +__version__ = "0.1.0" + +__all__ = [ + "__version__", + "budget", + "fabric", + "routes", + "site", + "subset", +] diff --git a/sparkring_fabric/sparkring_fabric/budget.py b/sparkring_fabric/sparkring_fabric/budget.py new file mode 100644 index 00000000..3a66d5a9 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/budget.py @@ -0,0 +1,235 @@ +"""Forward windows of point-to-point lanes within the relay hairpin rule (stdlib-only). + +A relay forwards a lane's frames through one hairpin queue per (relay Spark, +function class, egress port), and the queue cannot pause its sender. SparkRing +keeps the bytes of every lane through one queue within ``RELAY_QUEUE_SHARE`` +(75 %) of its size (``SIRCL_HAIRPIN_QUEUE_BYTES``, 512 KiB). Collective +sessions take their share first; point-to-point lanes share what is left. + +:func:`session_reservation` gives the bytes a collective session's relayed +lanes may hold in each queue: its forward windows (``routes.forward_windows`` +with the session's settings), or, where a ``ring`` schedule is named, the +larger of those and its ring window (``routes.ring_window``); a session with +forward windows off reserves the whole share of every queue it uses. + +:func:`allocate` gives every relayed point-to-point lane its window, level by +level (PP groups before the channels of groups with a collective session): +each queue's remainder divided evenly among the level's lanes through it; a +lane's window is the smallest share over its queues, capped at the largest +window and rounded down to whole chunks. A lane left with less than one chunk +has no window; its channel is unavailable, and :class:`Allocation` names the +queue, its reservations and its lanes. + +Queues are keyed by physical position (``(relay position, secondary +function, egress port)``, as :func:`routes.relay_queues` keys them), so lanes +of groups on different layouts of one ring share a key when they share a +queue. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Iterable, Mapping, Sequence + +from . import routes as routes_mod + +DEFAULT_P2P_WINDOW_BYTES = 131072 +DEFAULT_P2P_CHUNK_BYTES = 32768 + +QueueKey = tuple[int, bool, int] +LaneKey = tuple[str, int, int, int] # (group name, rank, peer, lane) + + +class BudgetError(ValueError): + """Point-to-point lanes that the relay rule leaves without a window.""" + + +@dataclasses.dataclass(frozen=True) +class LaneSet: + """One group's lanes: its layout, every rank's full route map and the ordered pairs that carry traffic.""" + + name: str + layout: routes_mod.Layout + route_maps: tuple[Mapping[int, tuple[str, ...]], ...] + pairs: frozenset[tuple[int, int]] + + @classmethod + def of(cls, name: str, layout: routes_mod.Layout, lanes: int = 2, + pairs: Iterable[tuple[int, int]] | None = None) -> "LaneSet": + derived = routes_mod.derive_routes(layout, lanes) + maps = tuple(derived.route_map(rank) for rank in range(layout.world)) + every = {(a, b) for a in range(layout.world) for b in range(layout.world) if a != b} + return cls(name, layout, maps, frozenset(every if pairs is None else + {(int(a), int(b)) for a, b in pairs})) + + def filtered_maps(self) -> list[dict[int, tuple[str, ...]]]: + return [{peer: devices for peer, devices in routes.items() if (rank, peer) in self.pairs} + for rank, routes in enumerate(self.route_maps)] + + def queues(self) -> dict[QueueKey, list[tuple[int, int, int]]]: + """Every relay queue the set's pairs cross, with the (rank, peer, lane) of each lane through it.""" + return routes_mod.relay_queues(self.layout, self.filtered_maps()) + + +@dataclasses.dataclass(frozen=True) +class SessionSettings: + """The settings of a collective session that size its relayed lanes' share.""" + + forward_window: int = routes_mod.DEFAULT_FORWARD_WINDOW + forward_chunk: int = routes_mod.DEFAULT_FORWARD_CHUNK + ring_schedule: bool = False # a large, gather or scatter schedule is ``ring`` + subset_ring: bool = False + + @classmethod + def from_env(cls, environ: Mapping[str, str]) -> "SessionSettings": + def number(name: str, default: int) -> int: + raw = environ.get(name, "").strip() + return int(raw, 0) if raw else default + + ring = any(environ.get(name, "").strip() == "ring" + for name in ("SIRCL_LARGE_SCHEDULE", "SIRCL_GATHER_SCHEDULE", "SIRCL_SCATTER_SCHEDULE")) + from . import subset + return cls(number("SIRCL_FORWARD_WINDOW_BYTES", routes_mod.DEFAULT_FORWARD_WINDOW), + number("SIRCL_FORWARD_CHUNK_BYTES", routes_mod.DEFAULT_FORWARD_CHUNK), ring, subset.enabled(environ)) + + +def queue_share(queue_bytes: int) -> int: + return int(routes_mod.RELAY_QUEUE_SHARE * queue_bytes) + + +def session_reservation(lanes: LaneSet, settings: SessionSettings, *, + queue_bytes: int = routes_mod.DEFAULT_HAIRPIN_QUEUE) -> dict[QueueKey, int]: + """Bytes the collective session of ``lanes`` may hold in every relay queue its lanes cross.""" + queues = lanes.queues() + if not queues: + return {} + if settings.subset_ring and sorted(lanes.layout.positions) != list(lanes.layout.fabric.positions): + # Relayed P2P sessions have independent QPs and are outside the subset session proof. + from . import subset + subset.validate(lanes.layout, lanes.filtered_maps(), queue_bytes=queue_bytes) + return {key: queue_share(queue_bytes) for key in queues} + if settings.forward_window <= 0: + return {key: queue_share(queue_bytes) for key in queues} + maps = lanes.filtered_maps() + tables = [routes_mod.forward_windows(lanes.layout, maps, rank, max_window=settings.forward_window, + chunk=settings.forward_chunk, queue_bytes=queue_bytes) + for rank in range(lanes.layout.world)] + reserved = {key: sum(tables[rank][peer][lane] for rank, peer, lane in members) + for key, members in queues.items()} + if settings.ring_schedule: + order = routes_mod.chain_order(lanes.layout, maps) + if order is not None: + window, problems = routes_mod.ring_window(lanes.layout, maps, order, queue_bytes=queue_bytes) + if not problems: + for key, members in routes_mod.ring_queues(lanes.layout, maps, order).items(): + reserved[key] = max(reserved.get(key, 0), window * len(members)) + return reserved + + +@dataclasses.dataclass(frozen=True) +class Allocation: + """Windows of every relayed point-to-point lane, and the lanes left without one.""" + + windows: Mapping[LaneKey, int] + unavailable: Mapping[LaneKey, str] + reserved: Mapping[QueueKey, int] + + def table(self, lanes: LaneSet, lane_count: int) -> list[list[list[int]]]: + """``table[rank][peer][lane]`` of one group (0: a direct lane or no channel).""" + world = lanes.layout.world + table = [[[0] * lane_count for _ in range(world)] for _ in range(world)] + for (name, rank, peer, lane), window in self.windows.items(): + if name == lanes.name: + table[rank][peer][lane] = window + return table + + def unavailable_pairs(self, name: str) -> dict[tuple[int, int], str]: + """Ordered pairs of group ``name`` whose channel has a lane without a window, with the reason.""" + found: dict[tuple[int, int], str] = {} + for (group, rank, peer, _), reason in sorted(self.unavailable.items()): + if group == name: + found.setdefault((rank, peer), reason) + return found + + +def _describe(key: QueueKey) -> str: + return f"relay {key[0]} {'secondary' if key[1] else 'primary'} function toward port {key[2]}" + + +def allocate(levels: Sequence[Sequence[LaneSet]], *, reserved: Mapping[QueueKey, int] | None = None, + max_window: int, chunk: int, queue_bytes: int = routes_mod.DEFAULT_HAIRPIN_QUEUE) -> Allocation: + """Windows of the point-to-point lanes of every level, after ``reserved`` (see the module docstring).""" + if chunk <= 0 or chunk % 16: + raise BudgetError(f"forward chunk {chunk} must be a positive multiple of 16") + share = queue_share(queue_bytes) + used: dict[QueueKey, int] = dict(reserved or {}) + windows: dict[LaneKey, int] = {} + unavailable: dict[LaneKey, str] = {} + for level in levels: + through: dict[QueueKey, list[LaneKey]] = {} + for lanes in level: + for key, members in lanes.queues().items(): + through.setdefault(key, []).extend((lanes.name, rank, peer, lane) for rank, peer, lane in members) + lane_queues: dict[LaneKey, list[QueueKey]] = {} + for key, members in through.items(): + for member in members: + lane_queues.setdefault(member, []).append(key) + for member, keys in sorted(lane_queues.items()): + limit = max_window if max_window > 0 else 0 + reason = "" if max_window > 0 else "point-to-point windows are off (SIRCL_P2P_WINDOW_BYTES=0)" + for key in keys: + room = max(0, share - used.get(key, 0)) // len(through[key]) + if room < limit: + limit = room + if room < chunk: + reason = (f"{_describe(key)} has {max(0, share - used.get(key, 0))} of its {share} bytes " + f"left for {len(through[key])} point-to-point lanes " + f"({used.get(key, 0)} bytes reserved before them)") + window = limit // chunk * chunk + if window < chunk: + unavailable[member] = reason or f"its window is below one chunk of {chunk} bytes" + continue + windows[member] = window + for key, members in through.items(): + used[key] = used.get(key, 0) + sum(windows.get(member, 0) for member in members) + return Allocation(windows, unavailable, dict(reserved or {})) + + +def group_windows(lanes: LaneSet, lane_count: int, *, max_window: int, chunk: int, + queue_bytes: int = routes_mod.DEFAULT_HAIRPIN_QUEUE) -> tuple[list[list[list[int]]], dict]: + """Windows of one group's lanes when they are the only relayed traffic: ``(table, unavailable pairs)``.""" + allocation = allocate([[lanes]], max_window=max_window, chunk=chunk, queue_bytes=queue_bytes) + return allocation.table(lanes, lane_count), allocation.unavailable_pairs(lanes.name) + + +def pp_groups(world: int, *, tp: int, pp: int, pcp: int = 1, dp: int = 1) -> tuple[tuple[int, ...], ...]: + """Global ranks of every pipeline-parallel group (layout ExternalDP x DP x PP x PCP x TP).""" + if min(world, tp, pp, pcp, dp) < 1: + raise ValueError("group sizes must be positive") + inner = dp * pp * pcp * tp + if world % inner: + raise ValueError(f"world size {world} is not a multiple of DP*PP*PCP*TP = {inner}") + groups = [] + stage = pcp * tp + for outer in range(world // inner): + for data in range(dp): + base = (outer * dp + data) * pp * stage + for offset in range(stage): + groups.append(tuple(base + s * stage + offset for s in range(pp))) + return tuple(groups) + + +__all__ = [ + "Allocation", + "BudgetError", + "DEFAULT_P2P_CHUNK_BYTES", + "DEFAULT_P2P_WINDOW_BYTES", + "LaneSet", + "QueueKey", + "SessionSettings", + "allocate", + "group_windows", + "pp_groups", + "queue_share", + "session_reservation", +] diff --git a/sparkring_fabric/sparkring_fabric/fabric/__init__.py b/sparkring_fabric/sparkring_fabric/fabric/__init__.py new file mode 100644 index 00000000..64889163 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/__init__.py @@ -0,0 +1,33 @@ +"""Relay plan installer for RDMA sessions on a switchless ring or open chain of DGX Sparks. + +RDMA sessions read host networking but never configure it: members of a group +that share no cable reach each other through ConnectX-7 relays, and the relay +plan is installed by site tooling before a session starts. This subpackage is +that tooling. It derives a layout's plan from :mod:`sparkring_fabric.routes`, +so the lanes derived by route planners and the relays installed on the Sparks +cannot disagree, and it installs, compares and removes the plan over SSH. + +Per Spark the plan holds: + +- origin routes: a /32 route, scope link, over the lane's local network + device, with a permanent neighbour entry holding the adjacent Spark's MAC; +- relay count tags: one marker process per RDMA device (``mesh_marker.c``) + installs mlx5 RDMA-TX rules that rewrite the EtherType of RoCE packets to + each routed destination into ``TAG(k) = 0x88b4 + k``, ``k`` relays left; +- relay filters: on the ingress of the device that receives a relayed lane, a + hardware flower filter per tag that sets the next Spark's MAC, rewrites the + tag to ``TAG(k - 1)`` (``TAG(0)`` is IPv4) and redirects out of the other + port. + +Layouts (:mod:`.layouts`): ``ring8`` (the universal relay table), ``2xTP4``, +``4xTP2`` and custom groups of consecutive Sparks, wrap-around included. With +several groups on one ring, routes and tags exist only for same-group +destinations on that group's members, and relay filters only where a member +lies inside a carried path of its own group. + +Modules: :mod:`.layouts` (groups), :mod:`.plan` (derivation, isolation and +trace checks), :mod:`.commands` (shell commands and ownership marks), +:mod:`.state` (parsing what a Spark holds), :mod:`.diff` (comparison and +apply scripts), :mod:`.ops` (read, compare, apply), :mod:`.report` (text) and +:mod:`.cli` (``sparkring-fabric`` / ``python -m sparkring_fabric.fabric``). +""" diff --git a/sparkring_fabric/sparkring_fabric/fabric/__main__.py b/sparkring_fabric/sparkring_fabric/fabric/__main__.py new file mode 100644 index 00000000..dd8a8c90 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/__main__.py @@ -0,0 +1,5 @@ +import sys + +from .cli import main + +sys.exit(main()) diff --git a/sparkring_fabric/sparkring_fabric/fabric/cli.py b/sparkring_fabric/sparkring_fabric/fabric/cli.py new file mode 100644 index 00000000..3f287c01 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/cli.py @@ -0,0 +1,266 @@ +"""``sparkring-fabric `` (or ``python -m sparkring_fabric.fabric ``): the relay plan installer. + +Commands and their safety classes (``RUNBOOK.md``, section "Relay plan +installer"): + +- ``plan`` (OFFLINE): a layout's relay plan, from a facts file or with + placeholders for addresses and MACs; +- ``facts`` (READ-ONLY REMOTE): the Sparks' fabric addresses and MACs as a + facts file for ``plan``; +- ``show`` (READ-ONLY REMOTE): the relay objects every Spark holds: routes, + neighbours, marker processes and relay filters, labelled by group; +- ``diff`` (READ-ONLY REMOTE): the Sparks compared with a layout's plan; +- ``up`` and ``down``: without ``--apply`` a dry run (READ-ONLY REMOTE) that + prints every change and the exact script per Spark; with ``--apply`` + (MUTATES HOST) the scripts run on the selected groups' Sparks, which are + then read again and compared with the plan to verify; +- ``marker``: the marker executable on every Spark (READ-ONLY REMOTE); with + ``--apply`` it is compiled and installed where it is missing (MUTATES HOST). + +Exit codes: 0 done (``diff``: no host changes); 1 ``diff`` found host +changes, a Spark was unreachable, or applying or verifying failed; 2 invalid +input; 3 blockers stopped a dry run or ``--apply``, or a group cannot be +planned. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from .. import routes +from ..site import Site, SiteError +from . import commands, layouts, ops, report +from . import plan as plan_mod +from .commands import MARKER_SOURCE +from .layouts import FabricError + + +def _positions(text: str | None, size: int) -> list[int]: + if text is None or text.strip() == "all": + return list(range(size)) + return sorted({position for group in layouts.parse_groups(text, size) for position in group}) + + +def _layout(args, ring_size: int) -> layouts.FabricLayout: + return layouts.resolve(ring_size=ring_size, layout=args.layout, groups=args.groups, name=args.name, + relay_egress=args.relay_egress) + + +def _print_outcome(outcome: ops.Outcome, args, *, scripts: bool) -> None: + print(report.render_outcome(outcome, verbose=args.verbose, scripts=scripts)) + print(report.summary_line(outcome)) + + +def _route_check(outcome: ops.Outcome, site: Site, executor: ops.Executor, *, installed_only: bool) -> int: + """``ip route get`` of every lane destination on its origin Spark, as the harness and launcher check it.""" + if outcome.mode != "up" or not outcome.plans: + return 0 + problems = ops.check_lane_routes(site, outcome, executor, installed_only=installed_only) + checked = sum(len(found) for found in ops.lane_route_checks(outcome, installed_only=installed_only).values()) + for position, found in sorted(problems.items()): + for problem in found: + print(f"ROUTE CHECK {site.host(position).name}: {problem}") + count = sum(len(found) for found in problems.values()) + print(f"route check: {checked - count} of {checked} lane destination(s) resolve over their lane's device" + + (" (destinations whose origin route is still to be added are not checked)" if installed_only else "")) + return count + + +def _apply(outcome: ops.Outcome, site: Site, executor: ops.Executor, args, marker: commands.MarkerConfig) -> int: + if outcome.blocked: + print("apply refused: resolve the blockers above (nothing was changed)") + return 3 + if not outcome.pending: + print("nothing to apply: the Sparks already hold the plan") + return 0 + results = ops.apply(outcome, site, executor) + failed = False + for position, result in sorted(results.items()): + text = (result.stdout + result.stderr).strip() + print(f"{site.host(position).name}: exit {result.returncode}" + (f": {text[-1500:]}" if text else "")) + failed |= not result.ok + positions = [position for group in outcome.groups for position in group.order] + states = ops.gather(site, positions, executor, marker) + verify = ops.evaluate(site, outcome.layout, outcome.groups, states, mode=outcome.mode, marker=marker, + adopt=args.adopt, check_hostname=not args.skip_hostname_check, max_relays=args.max_relays) + leftovers = [(d, change) for d in verify.diffs for change in d.pending] + for d, change in leftovers: + print(f"after apply, {d.name} still differs: {change.text()}") + for d in verify.diffs: + for blocker in d.blockers: + print(f"after apply, {d.name}: {blocker}") + route_problems = _route_check(verify, site, executor, installed_only=False) + if failed or leftovers or verify.blocked or route_problems: + print("verification failed: run `diff` (or `show`) and inspect the Sparks named above") + return 1 + print(f"verified: {len(verify.diffs)} Spark(s) hold the {outcome.mode} state of " + + ", ".join(group.label for group in outcome.groups)) + return 0 + + +def _marker_command(site: Site, positions: list[int], executor: ops.Executor, args, + marker: commands.MarkerConfig) -> int: + states = ops.gather(site, positions, executor, marker) + print(report.render_marker_status(states, marker)) + targets = [p for p in positions if states[p].reachable and ( + args.rebuild or bool(states[p].marker_problems(marker.path, expected_sha256=marker.expected_sha256)))] + if not targets: + print("every reachable Spark has the marker executable") + return 0 if all(states[p].reachable for p in positions) else 1 + source = MARKER_SOURCE.read_text(encoding="utf-8") + scripts = {p: commands.marker_build_script(site.host(p).name, marker, source) for p in targets} + names = ", ".join(site.host(p).name for p in targets) + if not args.apply: + print(f"dry run: --apply compiles {MARKER_SOURCE.name} and installs {marker.path} on {names}") + if args.scripts: + print(scripts[targets[0]]) + return 0 + failed = False + for position in targets: + result = executor(site.host(position).ssh, scripts[position], ops.APPLY_TIMEOUT) + text = (result.stdout + result.stderr).strip() + print(f"{site.host(position).name}: exit {result.returncode}: {text[-800:]}") + failed |= not result.ok + return 1 if failed else 0 + + +def _parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(prog="sparkring-fabric", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + commands_parser = parser.add_subparsers(dest="command", required=True) + + def layout_options(sub: argparse.ArgumentParser) -> None: + sub.add_argument("--layout", help="ring8 (universal relay table), 2xTP4, 4xTP2, or ring") + sub.add_argument("--groups", help="custom groups instead of --layout: '0-3;4-7', '7,0,1,2' or '7-2'") + sub.add_argument("--name", help="name of a custom layout (recorded on the Sparks)") + sub.add_argument("--group", help="act on one group of the layout: index, label (path:4-5-6-7) or members") + sub.add_argument("--relay-egress", choices=layouts.RELAY_EGRESS, + help="relay egress function (default: same for the whole ring, sibling otherwise)") + sub.add_argument("--max-relays", type=int, default=routes.DEFAULT_MAX_RELAYS, + help=f"relay limit per lane (default {routes.DEFAULT_MAX_RELAYS}, the qualified limit; " + "higher values are research-only)") + + def remote_options(sub: argparse.ArgumentParser) -> None: + sub.add_argument("--site", required=True, type=Path, help="site file (sircl-ring-site/v1)") + sub.add_argument("--marker", default=commands.DEFAULT_MARKER, + help=f"marker executable on the Sparks (default {commands.DEFAULT_MARKER})") + sub.add_argument("--skip-hostname-check", action="store_true", + help="accept a host whose name differs from its site entry's name") + + plan_parser = commands_parser.add_parser("plan", help="print a layout's relay plan (OFFLINE)") + layout_options(plan_parser) + plan_parser.add_argument("--facts", type=Path, help="facts file (sparkring-fabric-facts/v1); else placeholders") + plan_parser.add_argument("--site", type=Path, help="site file, for Spark names and the ring size") + plan_parser.add_argument("--ring-size", type=int, help="ring size without a site or facts file (default 8)") + plan_parser.add_argument("--json", action="store_true") + plan_parser.add_argument("--brief", action="store_true", help="groups and route maps only") + + facts_parser = commands_parser.add_parser("facts", help="read the Sparks' fabric addresses and MACs") + remote_options(facts_parser) + facts_parser.add_argument("--sparks", help="positions to read (default all), e.g. '0-3'") + facts_parser.add_argument("--output", type=Path, help="write the facts file here instead of printing it") + + show_parser = commands_parser.add_parser("show", help="show every Spark's relay objects (READ-ONLY REMOTE)") + remote_options(show_parser) + show_parser.add_argument("--sparks", help="positions to read (default all), e.g. '0-3'") + show_parser.add_argument("--raw", action="store_true", help="also print the raw read-script output") + + for name, text in (("diff", "compare the Sparks with a layout's plan (READ-ONLY REMOTE)"), + ("up", "install a layout's plan: dry run unless --apply (MUTATES HOST)"), + ("down", "remove a layout's groups: dry run unless --apply (MUTATES HOST)")): + sub = commands_parser.add_parser(name, help=text) + remote_options(sub) + layout_options(sub) + sub.add_argument("--adopt", action="store_true", + help="take over relay routes and neighbours that lack the ownership mark") + sub.add_argument("--verbose", action="store_true", help="also list unchanged objects") + if name == "diff": + sub.add_argument("--scripts", action="store_true", help="print the scripts `up` would run") + else: + sub.add_argument("--apply", action="store_true", help="change the Sparks (MUTATES HOST)") + sub.add_argument("--no-scripts", action="store_true", help="omit the per-Spark scripts") + + marker_parser = commands_parser.add_parser("marker", help="the marker executable: status, or build with --apply") + remote_options(marker_parser) + marker_parser.add_argument("--sparks", help="positions (default all)") + marker_parser.add_argument("--apply", action="store_true", help="compile and install it (MUTATES HOST)") + marker_parser.add_argument("--rebuild", action="store_true", help="rebuild where it exists too") + marker_parser.add_argument("--scripts", action="store_true", help="print the build script") + return parser + + +def main(argv: list[str] | None = None, *, executor: ops.Executor | None = None) -> int: + args = _parser().parse_args(argv) + run = executor or ops.ssh_executor + try: + if args.command == "plan": + site = Site.load(args.site) if args.site else None + if args.facts: + facts = plan_mod.Facts.from_json(json.loads(args.facts.read_text(encoding="utf-8"))) + size = args.ring_size or (site.size if site else max(facts.positions) + 1) + else: + size = args.ring_size or (site.size if site else 8) + names = [host.name for host in site.ring] if site else [f"spark{i}" for i in range(size)] + facts = plan_mod.Facts.symbolic_for(names) + layout = _layout(args, size) + built = plan_mod.build_layout_plan(layout, facts, groups=layout.select(args.group), + max_relays=args.max_relays) + if args.json: + print(json.dumps(built.to_json(), indent=1)) + else: + print(plan_mod.render_text(built, facts, details=not args.brief)) + return 0 + site = Site.load(args.site) + marker = commands.MarkerConfig(args.marker) + if args.command in ("show", "facts", "marker"): + positions = _positions(args.sparks, site.size) + if args.command == "marker": + return _marker_command(site, positions, run, args, marker) + states = ops.gather(site, positions, run, marker) + if args.command == "facts": + problems = [p for state in states.values() for p in state.fact_problems(check_hostname=False)] + text = json.dumps(ops.facts_from(site, states).to_json(), indent=1) + if args.output: + args.output.write_text(text + "\n", encoding="utf-8") + else: + print(text) + for problem in problems: + print(f"problem: {problem}", file=sys.stderr) + return 3 if problems else 0 + print(report.render_show(states, marker)) + if args.raw: + for position, state in sorted(states.items()): + print(f"--- {state.name} raw ---") + for section, text in state.raw.items(): + print(f"@@{section}\n{text}") + return 0 if all(state.reachable for state in states.values()) else 1 + layout = _layout(args, site.size) + groups = layout.select(args.group) + positions = [position for group in groups for position in group.order] + states = ops.gather(site, positions, run, marker) + mode = "down" if args.command == "down" else "up" + outcome = ops.evaluate(site, layout, groups, states, mode=mode, marker=marker, adopt=args.adopt, + check_hostname=not args.skip_hostname_check, max_relays=args.max_relays) + if args.command == "diff": + _print_outcome(outcome, args, scripts=args.scripts) + if outcome.problems or not all(state.reachable for state in states.values()): + return 3 + if _route_check(outcome, site, run, installed_only=True): + return 3 + return 1 if outcome.host_changes else 0 + _print_outcome(outcome, args, scripts=not args.no_scripts) + if not args.apply: + print("dry run: nothing was changed; --apply runs the scripts above" + + (" (blockers must be resolved first)" if outcome.blocked else "")) + return 3 if outcome.blocked else 0 + return _apply(outcome, site, run, args, marker) + except (FabricError, SiteError, routes.RouteError, OSError, ValueError, KeyError) as error: + print(f"error: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": # pragma: no cover + sys.exit(main()) diff --git a/sparkring_fabric/sparkring_fabric/fabric/commands.py b/sparkring_fabric/sparkring_fabric/fabric/commands.py new file mode 100644 index 00000000..57fd719c --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/commands.py @@ -0,0 +1,283 @@ +"""Shell commands the installer sends to a Spark. + +Every remote action is one ``bash -s`` script over SSH in batch mode, one +command per line, every interpolated value shell-quoted. The read script +(:func:`read_script`) uses read-only commands and needs no root: it is the +READ-ONLY REMOTE part of ``show``, ``diff`` and every dry run. Apply scripts +change host state through ``sudo -n`` (MUTATES HOST), stop at the first +failing command (``set -euo pipefail``) and first check the host's name +(:func:`guard`), so a wrong SSH target changes nothing. + +Ownership marks, by which ``down`` removes exactly the installer's objects: + +- routes and permanent neighbours carry routing protocol number 82 + (:data:`ROUTE_PROTOCOL`, ``proto 82``); +- relay filters occupy the reserved preferences 11 to 17 of chain 0 on the + ingress of the four fabric network devices (preference ``10 + k``, handle + ``k``, protocol ``TAG(k)``); +- marker processes run the marker executable, whose first 15 characters are + the process name ``pgrep -x`` matches; +- the record ``/run/sparkring-fabric/relay-state.json`` names the Spark's + group, layout, relay egress, plan digest and the ingress qdiscs the + installer added. ``/run`` is cleared at boot, like every object of the plan. + +Nothing else is changed: not the NetworkManager connections, addresses, links, +other routes, other neighbours, other filters, other qdiscs or other processes. +""" + +from __future__ import annotations + +import dataclasses +import ipaddress +import json +import posixpath +import re +import shlex +from collections.abc import Iterable, Mapping +from pathlib import Path + +from .layouts import FabricError +from .plan import FABRIC_NETDEVS, RDMA_DEVICES, RelayFilter + +MARKER_SOURCE = Path(__file__).with_name("mesh_marker.c") + +ROUTE_PROTOCOL = 82 +STATE_DIR = "/run/sparkring-fabric" +RECORD_PATH = f"{STATE_DIR}/relay-state.json" +RECORD_SCHEMA = "sparkring-fabric-relay-record/v1" +DEFAULT_MARKER_DIR = "/usr/local/libexec/sparkring" +DEFAULT_MARKER = f"{DEFAULT_MARKER_DIR}/ring8-mesh-marker" +SECTION = "@@" +HEADER = "set -euo pipefail" +SETTLE = "sleep 1.5" +_PATH = re.compile(r"^/[A-Za-z0-9_./+-]+$") +_MAC = re.compile(r"^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$") +_HOSTNAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$") + + +def q(value: object) -> str: + return shlex.quote(str(value)) + + +@dataclasses.dataclass(frozen=True) +class MarkerConfig: + """Where the marker executable lives on every Spark and where each marker logs.""" + + path: str = DEFAULT_MARKER + log_dir: str = "/tmp" + expected_sha256: str | None = None + + def __post_init__(self) -> None: + for label, value in (("marker path", self.path), ("marker log directory", self.log_dir)): + if not _PATH.match(value) or "/../" in f"{value}/": + raise FabricError(f"{label} {value!r} must be an absolute path of letters, digits and _./+-") + if self.expected_sha256 is not None and not re.fullmatch(r"[0-9a-f]{64}", self.expected_sha256.lower()): + raise FabricError(f"expected marker sha256 {self.expected_sha256!r} must be 64 hex characters") + + @property + def name(self) -> str: + return posixpath.basename(self.path) + + @property + def digest_path(self) -> str: + return f"{self.path}.sha256" + + @property + def comm(self) -> str: + """The process name the kernel keeps for the executable (its first 15 characters).""" + return self.name[:15] + + def log(self, device: str) -> str: + return f"{self.log_dir}/{self.name}-{device}.log" + + +def _ipv4(value: str) -> str: + try: + return str(ipaddress.IPv4Address(value)) + except ValueError: + raise FabricError(f"{value!r} is not an IPv4 address; apply needs the Sparks' facts, not placeholders") from None + + +def _mac(value: str) -> str: + if not _MAC.match(value.lower()): + raise FabricError(f"{value!r} is not a MAC address; apply needs the Sparks' facts, not placeholders") + return value.lower() + + +def _netdev(value: str) -> str: + if value not in FABRIC_NETDEVS: + raise FabricError(f"{value!r} is not a fabric network device") + return value + + +def _device(value: str) -> str: + if value not in RDMA_DEVICES: + raise FabricError(f"{value!r} is not a fabric RDMA device") + return value + + +# -- read script --------------------------------------------------------------------------- + + +def read_script(marker: MarkerConfig) -> str: + """Read-only facts and relay objects of one Spark, as ``@@

`` blocks.""" + lines = ["set -u"] + + def section(name: str, *commands: str) -> None: + lines.append(f"echo {SECTION}{name}") + lines.extend(commands) + + section("hostname", "hostname") + section("versions", "ip -V 2>&1 || true", "tc -V 2>&1 || true") + section("links", "ip -j addr show") + for device in RDMA_DEVICES: + section(f"rdma:{device}", f"ls /sys/class/infiniband/{device}/device/net 2>/dev/null || true") + section("routes", "ip -j -d route show table main") + section("neighbours", "ip -j neigh show nud permanent") + for netdev in FABRIC_NETDEVS: + section(f"qdisc:{netdev}", f"tc -j qdisc show dev {netdev} 2>/dev/null || true") + section(f"filters:{netdev}", f"tc -j filter show dev {netdev} ingress 2>/dev/null || true") + section("markers", f"pgrep -a -x {q(marker.comm)} || true") + section("marker-binary", f"sha256sum {q(marker.path)} 2>/dev/null || true") + section("marker-stat", f"stat -c '%u %g %a' {q(marker.path)} 2>/dev/null || true") + section("marker-sha256", f"cat {q(marker.digest_path)} 2>/dev/null || true") + for device in RDMA_DEVICES: + section(f"marker-log:{device}", f"head -c 4096 {q(marker.log(device))} 2>/dev/null || true") + section("record", f"cat {RECORD_PATH} 2>/dev/null || true") + lines.append(f"echo {SECTION}end") + return "\n".join(lines) + "\n" + + +def route_get_script(destinations: Iterable[str]) -> str: + """``ip -o route get`` of every destination (read-only), as ``@@route:
`` blocks. + + The ring harness and the vLLM launcher check origin routes the same way. + """ + lines = ["set -u"] + for destination in destinations: + address = _ipv4(destination) + lines += [f"echo {SECTION}route:{address}", f"ip -o route get {address} 2>&1 || true"] + lines.append(f"echo {SECTION}end") + return "\n".join(lines) + "\n" + + +# -- apply commands -------------------------------------------------------------------------- + + +def guard(hostname: str) -> str: + """Stop the script unless it runs on ``hostname``.""" + if not _HOSTNAME.match(hostname): + raise FabricError(f"host name {hostname!r} cannot be checked safely") + return (f'test "$(hostname)" = {q(hostname)} || ' + f'{{ echo {q("refusing: this host is not " + hostname)} >&2; exit 3; }}') + + +def qdisc_add(netdev: str) -> str: + return f"sudo -n tc qdisc add dev {_netdev(netdev)} ingress" + + +def qdisc_del(netdev: str) -> str: + return f"sudo -n tc qdisc del dev {_netdev(netdev)} ingress" + + +def filter_add(relay_filter: RelayFilter) -> str: + return (f"sudo -n tc filter add dev {_netdev(relay_filter.in_netdev)} ingress protocol " + f"0x{relay_filter.protocol:04x} pref {relay_filter.pref} handle {relay_filter.handle} flower skip_sw " + f"action pedit ex munge eth dst set {_mac(relay_filter.next_mac)} pipe " + f"action pedit ex munge eth type set 0x{relay_filter.new_type:04x} pipe " + f"action mirred egress redirect dev {_netdev(relay_filter.out_netdev)}") + + +def filter_del(netdev: str, pref: int, *, protocol: int | None = None, handle: int | None = None) -> str: + """Delete one filter (protocol and handle known) or every filter of a reserved preference.""" + if protocol is None or handle is None: + return f"sudo -n tc filter del dev {_netdev(netdev)} ingress pref {int(pref)}" + return (f"sudo -n tc filter del dev {_netdev(netdev)} ingress protocol 0x{int(protocol):04x} " + f"pref {int(pref)} handle {int(handle)} flower") + + +def neigh_replace(destination: str, mac: str, netdev: str) -> str: + return (f"sudo -n ip neigh replace {_ipv4(destination)} lladdr {_mac(mac)} dev {_netdev(netdev)} " + f"nud permanent proto {ROUTE_PROTOCOL}") + + +def neigh_del(destination: str, netdev: str) -> str: + return f"sudo -n ip neigh del {_ipv4(destination)} dev {_netdev(netdev)}" + + +def route_replace(destination: str, netdev: str, source: str) -> str: + return (f"sudo -n ip route replace {_ipv4(destination)}/32 dev {_netdev(netdev)} src {_ipv4(source)} " + f"scope link proto {ROUTE_PROTOCOL}") + + +def route_del(destination: str, netdev: str, *, protocol: int | None, metric: int = 0) -> str: + """Delete one /32 route; naming its protocol makes the kernel refuse any other route.""" + command = f"sudo -n ip route del {_ipv4(destination)}/32 dev {_netdev(netdev)}" + if protocol is not None: + command += f" proto {int(protocol)}" + if metric: + command += f" metric {int(metric)}" + return command + + +def marker_start(marker: MarkerConfig, device: str, rules: Iterable[tuple[str, int]]) -> str: + """Start one managed marker in its own session; it keeps its rules until SIGTERM.""" + rule_words = " ".join(f"--rule {_ipv4(destination)}=0x{int(value):04x}" for destination, value in rules) + if not rule_words: + raise FabricError(f"a marker for {device} needs at least one rule") + return (f"(sudo -n setsid {q(marker.path)} --device {_device(device)} {rule_words} --managed " + f"< /dev/null > {q(marker.log(device))} 2>&1 &)") + + +def marker_stop(marker: MarkerConfig, pid: int) -> tuple[str, str]: + """Signal one marker process (only while it still is one) and wait up to 5 s for it to exit. + + The marker removes its RDMA-TX rules when it exits. + """ + pid = int(pid) + return (f'[ "$(cat /proc/{pid}/comm 2>/dev/null)" != {q(marker.comm)} ] || sudo -n kill {pid}', + f"for i in $(seq 1 50); do [ -e /proc/{pid} ] || break; sleep 0.1; done; [ ! -e /proc/{pid} ]") + + +def record_text(record: Mapping[str, object]) -> str: + return json.dumps(record, sort_keys=True, separators=(",", ":")) + + +def record_write(record: Mapping[str, object]) -> tuple[str, str]: + return (f"sudo -n mkdir -p {STATE_DIR}", + f"printf '%s\\n' {q(record_text(record))} | sudo -n tee {RECORD_PATH} >/dev/null") + + +def record_remove() -> str: + return f"sudo -n rm -f {RECORD_PATH}" + + +# -- marker executable ----------------------------------------------------------------------- + +MARKER_SOURCE_END = "SPARKRING_MARKER_SOURCE_END" + + +def marker_build_script(hostname: str, marker: MarkerConfig, source: str | None = None) -> str: + """Compile the marker source on a Spark (rdma-core headers needed) and install it root-owned.""" + if source is None: + source = MARKER_SOURCE.read_text(encoding="utf-8") + if any(line.strip() == MARKER_SOURCE_END for line in source.splitlines()): + raise FabricError("the marker source contains the here-document delimiter") + marker_dir = posixpath.dirname(marker.path) + digest_path = marker.digest_path + return "\n".join([ + HEADER, + guard(hostname), + "work=$(mktemp -d /var/tmp/sparkring-marker.XXXXXX)", + "trap 'rm -rf \"$work\"' EXIT", + f"cat > \"$work/mesh_marker.c\" <<'{MARKER_SOURCE_END}'", + source.rstrip("\n"), + MARKER_SOURCE_END, + "cc -O2 -Wall -Wextra \"$work/mesh_marker.c\" -o \"$work/marker\" -libverbs -lmlx5", + f"sudo -n install -d -o root -g root -m 0755 {q(marker_dir)}", + f"sudo -n install -o root -g root -m 0755 \"$work/marker\" {q(marker.path)}", + "rm -f \"$work/marker\"", + f"sha256sum {q(marker.path)} > \"$work/marker.sha256\"", + f"sudo -n install -o root -g root -m 0644 \"$work/marker.sha256\" {q(digest_path)}", + f"cat {q(digest_path)}", + ]) + "\n" diff --git a/sparkring_fabric/sparkring_fabric/fabric/diff.py b/sparkring_fabric/sparkring_fabric/fabric/diff.py new file mode 100644 index 00000000..67f6fccc --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/diff.py @@ -0,0 +1,366 @@ +"""Comparison of one Spark's objects with its plan, and the script that reconciles them. + +:func:`compare_up` compares a Spark with its group's plan; :func:`compare_down` +lists everything ``down`` removes. Both return a :class:`SparkDiff`: the +changes (``add``, ``remove``, ``replace``; ``mark`` puts the ownership mark on +an unowned object equal to the plan; ``keep``; ``write`` and ``remove`` of +the record), the blockers that stop ``--apply``, notes, and the apply script. + +Rules: + +- a Spark whose record names another group is left alone: ``up`` and + ``down`` stop there, so one group's operation never changes another + group's objects; +- unowned relay routes and neighbours (no protocol 82) are changed or + removed only with ``--adopt``; without it, ``up`` and ``down`` stop on a + Spark that holds any, and ``diff`` reports what ``--adopt`` would do. A + route that is not a relay route but has a planned destination is a + conflict and is never touched; +- relay filters and marker processes are the installer's by their reserved + identifiers and are replaced when they differ from the plan; +- an ingress qdisc is added where filters need one; ``down`` removes only a + qdisc the record says the installer added, and only when no filter remains. + +Script order: qdiscs, relay filters, neighbours, routes, marker restarts, +removal of stale routes and neighbours, qdisc removal, record. A changed +filter or marker is deleted and re-created, which interrupts the lanes that +use it for well under a second; an unchanged object is not touched. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Sequence + +from . import commands +from .plan import FABRIC_NETDEVS, RDMA_DEVICES, GroupPlan, SparkPlan +from .state import FilterEntry, HostState, NeighbourEntry, RouteEntry + +HOST_ACTIONS = ("add", "remove", "replace") + + +@dataclasses.dataclass(frozen=True) +class Change: + kind: str # route, neighbour, filter, qdisc, marker, record + action: str # add, remove, replace, mark, keep, write + key: str + detail: str + unowned: bool = False # acts on an object without the ownership mark + + @property + def host_change(self) -> bool: + """Whether the change alters forwarding state (marks and the record do not).""" + return self.kind != "record" and self.action in HOST_ACTIONS + + def text(self) -> str: + symbol = {"add": "+", "remove": "-", "replace": "~", "mark": "*", "keep": "=", "write": "+"}[self.action] + owner = " [unowned]" if self.unowned else "" + return f"{symbol} {self.action} {self.kind} {self.key}: {self.detail}{owner}" + + +@dataclasses.dataclass +class SparkDiff: + position: int + name: str + group: str + mode: str + changes: list[Change] = dataclasses.field(default_factory=list) + blockers: list[str] = dataclasses.field(default_factory=list) + notes: list[str] = dataclasses.field(default_factory=list) + commands: list[str] = dataclasses.field(default_factory=list) + needs_adopt: str | None = None # why --apply also needs --adopt (unowned objects would change) + + @property + def blocked(self) -> bool: + """Whether ``--apply`` must refuse this Spark.""" + return bool(self.blockers) or self.needs_adopt is not None + + def count(self, action: str) -> int: + return sum(1 for change in self.changes if change.action == action) + + @property + def host_changes(self) -> list[Change]: + return [change for change in self.changes if change.host_change] + + @property + def pending(self) -> list[Change]: + """Every change apply would make (anything but ``keep``).""" + return [change for change in self.changes if change.action != "keep"] + + @property + def script(self) -> str | None: + return "\n".join(self.commands) + "\n" if self.commands else None + + +@dataclasses.dataclass +class _Script: + qdisc_add: list[str] = dataclasses.field(default_factory=list) + filter_del: list[str] = dataclasses.field(default_factory=list) + filter_add: list[str] = dataclasses.field(default_factory=list) + neigh_set: list[str] = dataclasses.field(default_factory=list) + route_set: list[str] = dataclasses.field(default_factory=list) + marker_stop: list[str] = dataclasses.field(default_factory=list) + marker_start: list[str] = dataclasses.field(default_factory=list) + route_del: list[str] = dataclasses.field(default_factory=list) + neigh_del: list[str] = dataclasses.field(default_factory=list) + qdisc_del: list[str] = dataclasses.field(default_factory=list) + record: list[str] = dataclasses.field(default_factory=list) + + def lines(self, hostname: str) -> list[str]: + body = (self.qdisc_add + self.filter_del + self.filter_add + self.neigh_set + self.route_set + + self.marker_stop + self.marker_start + self.route_del + self.neigh_del + self.qdisc_del + + self.record) + if not body: + return [] + settle = [commands.SETTLE] if self.marker_start else [] + return [commands.HEADER, commands.guard(hostname), *body, *settle] + + +def _route_equal(entry: RouteEntry, destination: str, netdev: str, source: str) -> bool: + return (entry.dev == netdev and entry.source == source and entry.scope == "link" and not entry.gateway + and entry.metric == 0 and entry.kind == "unicast" and entry.destination == destination) + + +def _route_removal(entry: RouteEntry) -> str: + return commands.route_del(entry.destination, entry.dev, protocol=entry.protocol, metric=entry.metric) + + +def _filter_removal(entries: Sequence[FilterEntry]) -> list[str]: + if len(entries) == 1 and entries[0].protocol is not None and entries[0].handle is not None: + entry = entries[0] + return [commands.filter_del(entry.netdev, entry.pref, protocol=entry.protocol, handle=entry.handle)] + return [commands.filter_del(entries[0].netdev, entries[0].pref)] + + +def _common_blockers(diff: SparkDiff, state: HostState, *, check_hostname: bool) -> bool: + """Blockers that make the comparison meaningless; True when the Spark cannot be compared.""" + if not state.reachable: + diff.blockers.append(f"unreachable: {state.error}") + return True + if state.parse_problems: + diff.blockers.extend(f"read: {problem}" for problem in state.parse_problems) + if check_hostname and state.hostname != state.name: + diff.blockers.append(f"the host at {state.ssh} is named {state.hostname or 'nothing'}, the site lists " + f"{state.name} (--skip-hostname-check overrides)") + if state.record_problem: + diff.blockers.append(state.record_problem) + if state.record is not None and state.record.get("group") != diff.group: + diff.blockers.append(f"the Spark belongs to group {state.record.get('group')} (layout " + f"{state.record.get('layout')}); remove that group with `down` first") + return False + + +def _adopt_blocker(diff: SparkDiff, adopt: bool) -> None: + unowned = [change for change in diff.changes if change.unowned and change.action != "keep"] + if unowned and not adopt: + diff.needs_adopt = (f"{len(unowned)} relay route and neighbour change(s) act on objects without the " + "ownership mark (installed by other tooling); --adopt takes them over") + + +def _marker_changes(diff: SparkDiff, script: _Script, state: HostState, spark: SparkPlan | None, + marker: commands.MarkerConfig) -> None: + handled = set() + for device in RDMA_DEVICES: + planned = spark.marker(device) if spark is not None else None + wanted = frozenset(planned.rules) if planned is not None else frozenset() + present = [process for process in state.markers if process.device == device] + handled.update(process.pid for process in present) + rules_text = " ".join(f"{d}=0x{v:04x}" for d, v in (planned.rules if planned else ())) + if wanted and len(present) == 1 and present[0].rules == wanted and present[0].managed \ + and present[0].problem is None: + diff.changes.append(Change("marker", "keep", device, f"pid {present[0].pid}, {len(wanted)} rules")) + continue + for process in present: + script.marker_stop.extend(commands.marker_stop(marker, process.pid)) + if wanted: + script.marker_start.append(commands.marker_start(marker, device, planned.rules)) + before = "; ".join(process.text() for process in present) + diff.changes.append(Change("marker", "replace" if present else "add", device, + f"{before} -> {rules_text}" if present else rules_text)) + elif present: + diff.changes.append(Change("marker", "remove", device, "; ".join(p.text() for p in present))) + for process in state.markers: + if process.pid not in handled: + script.marker_stop.extend(commands.marker_stop(marker, process.pid)) + diff.changes.append(Change("marker", "remove", f"pid {process.pid}", process.text())) + if script.marker_start or (spark is not None and spark.markers): + diff.blockers.extend(state.marker_problems(marker.path, expected_sha256=marker.expected_sha256)) + + +def _record(spark: SparkPlan, plan: GroupPlan, layout_name: str, marker: commands.MarkerConfig, + qdiscs: Sequence[str], *, marker_sha256: str | None = None) -> dict[str, object]: + record: dict[str, object] = { + "schema": commands.RECORD_SCHEMA, "spark": spark.name, "position": spark.position, + "layout": layout_name, "group": plan.group.label, "members": list(plan.group.members), + "relay_egress": plan.relay_egress, "plan": plan.digest, "marker": marker.path, + "qdiscs": sorted(qdiscs), + } + if marker_sha256 is not None: + record["marker_sha256"] = marker_sha256 + return record + + +def compare_up(state: HostState, spark: SparkPlan, plan: GroupPlan, *, layout_name: str, + marker: commands.MarkerConfig, adopt: bool, check_hostname: bool = True) -> SparkDiff: + """What ``up`` changes on one Spark to install its group's plan.""" + diff = SparkDiff(spark.position, spark.name, plan.group.label, "up") + if _common_blockers(diff, state, check_hostname=check_hostname): + return diff + script = _Script() + removed_filters = {netdev: 0 for netdev in FABRIC_NETDEVS} + + # Relay filters (reserved preferences) and the ingress qdiscs they need. + added_qdiscs = [] + for netdev in FABRIC_NETDEVS: + planned = {relay_filter.pref: relay_filter for relay_filter in spark.filters if relay_filter.in_netdev == netdev} + present: dict[int, list[FilterEntry]] = {} + for entry in state.reserved_filters(netdev): + present.setdefault(entry.pref, []).append(entry) + if planned and state.ingress_qdisc.get(netdev) is None: + script.qdisc_add.append(commands.qdisc_add(netdev)) + added_qdiscs.append(netdev) + diff.changes.append(Change("qdisc", "add", netdev, "ingress")) + for pref, relay_filter in sorted(planned.items()): + entries = present.pop(pref, []) + wanted = (f"0x{relay_filter.protocol:04x} -> 0x{relay_filter.new_type:04x}, dst " + f"{relay_filter.next_mac}, out {relay_filter.out_netdev}") + if len(entries) == 1 and entries[0].matches(relay_filter): + diff.changes.append(Change("filter", "keep", f"{netdev} pref {pref}", wanted)) + continue + if entries: + script.filter_del.extend(_filter_removal(entries)) + removed_filters[netdev] += len(entries) + script.filter_add.append(commands.filter_add(relay_filter)) + before = "; ".join(entry.text() for entry in entries) + diff.changes.append(Change("filter", "replace" if entries else "add", f"{netdev} pref {pref}", + f"{before} -> {wanted}" if entries else wanted)) + for pref, entries in sorted(present.items()): + script.filter_del.extend(_filter_removal(entries)) + removed_filters[netdev] += len(entries) + diff.changes.append(Change("filter", "remove", f"{netdev} pref {pref}", + "; ".join(entry.text() for entry in entries))) + + # Origin routes and their permanent neighbours. + planned_routes = {route.destination: route for route in spark.routes} + host_routes: dict[str, list[RouteEntry]] = {} + for entry in state.routes: + if entry.prefixlen == 32: + host_routes.setdefault(entry.destination, []).append(entry) + for destination, route in planned_routes.items(): + entries = host_routes.get(destination, []) + candidates = [entry for entry in entries if entry.owned or state.is_relay_route(entry)] + foreign = [entry for entry in entries if entry not in candidates] + want = f"dev {route.netdev} src {route.source} -> position {route.peer} {route.peer_netdev}" + if foreign: + diff.blockers.append(f"route {destination}/32 is held by a route that is not a relay route " + f"({foreign[0].text()}); it is never touched") + continue + # `ip route replace` rewrites the metric-0 route in place; routes at other metrics are removed. + equal = next((entry for entry in candidates + if _route_equal(entry, destination, route.netdev, route.source)), None) + in_place = equal or next((entry for entry in candidates if entry.metric == 0), None) + for entry in candidates: + if entry is not in_place: + script.route_del.append(_route_removal(entry)) + diff.changes.append(Change("route", "remove", f"{destination}/32", entry.text(), not entry.owned)) + if equal is not None: + action = "keep" if equal.owned else "mark" + diff.changes.append(Change("route", action, f"{destination}/32", want, not equal.owned)) + if action == "mark": + script.route_set.append(commands.route_replace(destination, route.netdev, route.source)) + else: + script.route_set.append(commands.route_replace(destination, route.netdev, route.source)) + diff.changes.append(Change("route", "replace" if in_place else "add", f"{destination}/32", + f"{in_place.text()} -> {want}" if in_place else want, + bool(in_place and not in_place.owned))) + for entry in state.relay_routes(): + if entry.destination not in planned_routes: + script.route_del.append(_route_removal(entry)) + diff.changes.append(Change("route", "remove", f"{entry.destination}/32", entry.text(), not entry.owned)) + + planned_neighbours = {(route.destination, route.netdev): route.next_mac for route in spark.routes} + present_neighbours: dict[tuple[str, str], NeighbourEntry] = {} + for entry in state.relay_neighbours(): + present_neighbours[(entry.destination, entry.dev)] = entry + for (destination, netdev), mac in planned_neighbours.items(): + entry = present_neighbours.pop((destination, netdev), None) + if entry is not None and entry.mac == mac.lower(): + action = "keep" if entry.owned else "mark" + diff.changes.append(Change("neighbour", action, f"{destination} dev {netdev}", mac, not entry.owned)) + if action == "mark": + script.neigh_set.append(commands.neigh_replace(destination, mac, netdev)) + continue + script.neigh_set.append(commands.neigh_replace(destination, mac, netdev)) + diff.changes.append(Change("neighbour", "replace" if entry else "add", f"{destination} dev {netdev}", + f"{entry.mac} -> {mac}" if entry else mac, bool(entry and not entry.owned))) + for (destination, netdev), entry in sorted(present_neighbours.items()): + script.neigh_del.append(commands.neigh_del(destination, netdev)) + diff.changes.append(Change("neighbour", "remove", f"{destination} dev {netdev}", entry.text(), + not entry.owned)) + + _marker_changes(diff, script, state, spark, marker) + + # Qdiscs the record lists as added by the installer and that no filter needs any more. + record = state.record if state.record and state.record.get("group") == plan.group.label else None + recorded = set(record.get("qdiscs", [])) if record else set() + kept = set(added_qdiscs) | recorded + for netdev in sorted(recorded): + remaining = len(state.filters.get(netdev, [])) - removed_filters[netdev] + if netdev not in spark.filter_netdevs and remaining <= 0 and state.ingress_qdisc.get(netdev) == "ingress": + script.qdisc_del.append(commands.qdisc_del(netdev)) + kept.discard(netdev) + diff.changes.append(Change("qdisc", "remove", netdev, "ingress qdisc added by the installer")) + wanted_record = _record(spark, plan, layout_name, marker, sorted(kept), + marker_sha256=state.marker_binary if spark.markers else None) + if state.record != wanted_record: + script.record.extend(commands.record_write(wanted_record)) + before = (f"group {state.record.get('group')}, plan {state.record.get('plan')}" if state.record + else "none") + diff.changes.append(Change("record", "write", commands.RECORD_PATH, + f"{before} -> group {plan.group.label}, layout {layout_name}, plan {plan.digest}")) + for entry in state.foreign_tag_filters(): + diff.notes.append(f"a filter outside the reserved preferences matches relay tag 0x{entry.protocol:04x}: " + f"{entry.text()}") + _adopt_blocker(diff, adopt) + diff.commands = script.lines(spark.name) if diff.pending else [] + return diff + + +def compare_down(state: HostState, *, group: str, marker: commands.MarkerConfig, adopt: bool, + check_hostname: bool = True) -> SparkDiff: + """What ``down`` removes from one Spark of ``group``: every object the installer owns there.""" + diff = SparkDiff(state.position, state.name, group, "down") + if _common_blockers(diff, state, check_hostname=check_hostname): + return diff + script = _Script() + removed_filters = {netdev: 0 for netdev in FABRIC_NETDEVS} + for netdev in FABRIC_NETDEVS: + present: dict[int, list[FilterEntry]] = {} + for entry in state.reserved_filters(netdev): + present.setdefault(entry.pref, []).append(entry) + for pref, entries in sorted(present.items()): + script.filter_del.extend(_filter_removal(entries)) + removed_filters[netdev] += len(entries) + diff.changes.append(Change("filter", "remove", f"{netdev} pref {pref}", + "; ".join(entry.text() for entry in entries))) + for entry in state.relay_routes(): + script.route_del.append(_route_removal(entry)) + diff.changes.append(Change("route", "remove", f"{entry.destination}/32", entry.text(), not entry.owned)) + for entry in state.relay_neighbours(): + script.neigh_del.append(commands.neigh_del(entry.destination, entry.dev)) + diff.changes.append(Change("neighbour", "remove", f"{entry.destination} dev {entry.dev}", entry.text(), + not entry.owned)) + _marker_changes(diff, script, state, None, marker) + recorded = set(state.record.get("qdiscs", [])) if state.record else set() + for netdev in sorted(recorded): + remaining = len(state.filters.get(netdev, [])) - removed_filters.get(netdev, 0) + if remaining <= 0 and state.ingress_qdisc.get(netdev) == "ingress": + script.qdisc_del.append(commands.qdisc_del(netdev)) + diff.changes.append(Change("qdisc", "remove", netdev, "ingress qdisc added by the installer")) + if state.record is not None: + script.record.append(commands.record_remove()) + diff.changes.append(Change("record", "remove", commands.RECORD_PATH, + f"group {state.record.get('group')}, plan {state.record.get('plan')}")) + _adopt_blocker(diff, adopt) + diff.commands = script.lines(state.name) if diff.pending else [] + return diff diff --git a/sparkring_fabric/sparkring_fabric/fabric/layouts.py b/sparkring_fabric/sparkring_fabric/fabric/layouts.py new file mode 100644 index 00000000..66d78823 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/layouts.py @@ -0,0 +1,248 @@ +"""Layouts of the relay plan installer: which Sparks of a ring form which groups. + +A layout is a set of disjoint groups on one physical ring of DGX Sparks: ring +position ``i``'s port 0 is cabled to position ``i + 1``'s port 1, wrapping +around, in the order of the site file. A group is either the whole ring or +consecutive Sparks along it, including runs that wrap from the last position +to the first (``7,0,1,2``). A group owns the cables between its members and no +other cable. Its fabric is built by the ring harness's +:func:`sparkring_sircl.ring.plan.group_layout`, so this installer, the ring +harness and SIRCL sessions derive lanes from the same fabric. + +Built-in layouts of an eight-Spark ring: + +- ``ring8``: one group of all eight Sparks, the universal relay table; +- ``2xTP4``: two groups, Sparks 0-3 and Sparks 4-7; +- ``4xTP2``: four adjacent pairs, 0-1, 2-3, 4-5 and 6-7 (no relays). + +Custom layouts name their groups: ``0-3;4-7``, ``7,0,1,2``, or ``7-2`` (a range +whose end is smaller than its start wraps around the ring). + +Relay egress. A relay forwards a frame out of its other port, either through +the function of the lane's own class on that port (``same``) or through the +sibling Socket Direct function of the other class on that port (``sibling``). +Either way the relay writes the next Spark's MAC of the lane's class into the +frame, so the frame arrives on the same function. Measured on the ring: +relaying out of the sibling function lowered burst loss to 0.06 % at 2 MiB. +A layout whose only group is the whole ring uses ``same``: that is the +universal relay table ``ring8`` names, whose objects deployments built on the +table rely on. Every other layout uses ``sibling``. ``--relay-egress`` +overrides either default. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Sequence + +from .. import routes + +RELAY_EGRESS = ("same", "sibling") +BUILTIN_LAYOUTS = ("ring8", "2xTP4", "4xTP2") + + +class FabricError(ValueError): + """A layout, the facts of its Sparks or its relay plan breaks a rule of the installer.""" + + +def _cabled_group_layout(fabric: routes.Fabric, members: tuple[int, ...]) -> routes.Layout: + """A group on a site's own cables: the whole cycle, or each member joined to the next by a cable.""" + if fabric.kind == "cycle" and len(members) == len(fabric.positions): + if sorted(members) != list(fabric.positions): + raise FabricError("a whole-cycle group lists every Spark once") + return routes.Layout(fabric, members) + cables = [] + for a, b in zip(members, members[1:]): + joining = [cable for cable in fabric.cables if {cable.a, cable.b} == {a, b}] + if not joining: + raise FabricError(f"group {members} is not consecutive Sparks along the site's cables: Sparks {a} and " + f"{b} share no cable ({', '.join(cable.text for cable in fabric.cables)})") + cables.append(joining[0]) + return routes.Layout(routes.Fabric(tuple(cables)), members) + + +def group_layout(ring_size: int, members: Sequence[int], + fabric: routes.Fabric | None = None) -> routes.Layout: + """The group's fabric: the whole ring, or the cables between consecutive members.""" + members = tuple(members) + if len(members) < 2 or len(set(members)) != len(members): + raise FabricError(f"group {members} needs at least two distinct Sparks") + if any(not 0 <= member < ring_size for member in members): + raise FabricError(f"group {members} names a Spark outside the ring of {ring_size}") + if fabric is not None: + return _cabled_group_layout(fabric, members) + if len(members) == ring_size: + if sorted(members) != list(range(ring_size)): + raise FabricError("a whole-ring group lists every Spark once") + return routes.Layout(routes.Fabric.ring(ring_size), members) + for a, b in zip(members, members[1:]): + if b != (a + 1) % ring_size: + raise FabricError(f"group {members} is neither the whole ring nor consecutive Sparks along it") + path_fabric = routes.Fabric(tuple(routes.Cable(a, 0, b, 1) for a, b in zip(members, members[1:]))) + return routes.Layout(path_fabric, members) + + +@dataclasses.dataclass(frozen=True) +class Group: + """One group: its members (ring positions, in rank order) on a ring of ``ring_size`` Sparks.""" + + members: tuple[int, ...] + ring_size: int + + def __post_init__(self) -> None: + object.__setattr__(self, "members", tuple(int(member) for member in self.members)) + self.layout() + + def layout(self) -> routes.Layout: + """The group's fabric and rank positions.""" + try: + return group_layout(self.ring_size, self.members) + except routes.RouteError as error: + raise FabricError(str(error)) from None + + @property + def whole_ring(self) -> bool: + return len(self.members) == self.ring_size + + @property + def order(self) -> tuple[int, ...]: + """Members in fabric order: the whole ring from position 0, a path from its first member.""" + return tuple(range(self.ring_size)) if self.whole_ring else self.members + + @property + def kind(self) -> str: + if self.whole_ring: + return "cycle" + return "pair" if len(self.members) == 2 else "path" + + @property + def label(self) -> str: + """The group's identity, for example ``cycle:0-1-2-3-4-5-6-7`` or ``path:7-0-1-2``.""" + return f"{self.kind}:{'-'.join(str(position) for position in self.order)}" + + @property + def cables(self) -> tuple[str, ...]: + return tuple(cable.text for cable in self.layout().fabric.cables) + + +@dataclasses.dataclass(frozen=True) +class FabricLayout: + """Disjoint groups on one ring and the relay egress of their relays.""" + + name: str + ring_size: int + groups: tuple[Group, ...] + relay_egress: str + + def __post_init__(self) -> None: + if self.relay_egress not in RELAY_EGRESS: + raise FabricError(f"relay egress must be one of {', '.join(RELAY_EGRESS)}, got {self.relay_egress!r}") + if not self.groups: + raise FabricError(f"layout {self.name} has no groups") + seen: dict[int, str] = {} + cables: dict[str, str] = {} + for group in self.groups: + if group.ring_size != self.ring_size: + raise FabricError(f"group {group.label} is on a ring of {group.ring_size}, the layout on " + f"{self.ring_size}") + for member in group.members: + if member in seen: + raise FabricError(f"layout {self.name}: Spark {member} belongs to groups {seen[member]} and " + f"{group.label}; a Spark belongs to at most one group") + seen[member] = group.label + for cable in group.cables: + if cable in cables: + raise FabricError(f"layout {self.name}: cable {cable} is owned by {cables[cable]} and {group.label}") + cables[cable] = group.label + + @property + def positions(self) -> tuple[int, ...]: + return tuple(sorted(member for group in self.groups for member in group.members)) + + def select(self, selector: str | None) -> tuple[Group, ...]: + """The groups an operation acts on: all of them, or the one ``selector`` names. + + ``selector`` is a group index (``0``, ``1``, ...), a label + (``path:4-5-6-7``) or the group's members in the custom syntax (``4-7``). + """ + if selector is None: + return self.groups + text = selector.strip() + if text.isdigit() and int(text) < len(self.groups): + return (self.groups[int(text)],) + for group in self.groups: + if text == group.label: + return (group,) + try: + wanted = parse_groups(text, self.ring_size) + except FabricError: + wanted = () + for group in self.groups: + if len(wanted) == 1 and set(wanted[0]) == set(group.members): + return (group,) + raise FabricError(f"layout {self.name} has no group {selector!r}; its groups are " + + ", ".join(f"{index} ({group.label})" for index, group in enumerate(self.groups))) + + +def parse_groups(text: str, ring_size: int) -> tuple[tuple[int, ...], ...]: + """``0-3;4-7``, ``7,0,1,2`` or ``7-2``: groups separated by ``;``, members by ``,``. + + A range ``a-b`` lists ``a, a+1, ..., b`` along the ring; when ``b < a`` it + wraps from the last position to position 0. + """ + groups = [] + for part in text.split(";"): + members: list[int] = [] + for item in part.split(","): + item = item.strip() + if not item: + continue + first_text, _, last_text = item.partition("-") + try: + first = int(first_text) + last = int(last_text) if last_text else first + except ValueError: + raise FabricError(f"group {part.strip()!r} is not a list of Spark positions") from None + if not (0 <= first < ring_size and 0 <= last < ring_size): + raise FabricError(f"group {part.strip()!r} names a position outside the ring of {ring_size}") + span = (last - first) % ring_size + members.extend((first + step) % ring_size for step in range(span + 1)) + if members: + groups.append(tuple(members)) + if not groups: + raise FabricError("no groups given") + return tuple(groups) + + +def default_relay_egress(groups: Sequence[Group]) -> str: + """``same`` for a layout whose only group is the whole ring, ``sibling`` otherwise.""" + return "same" if len(groups) == 1 and groups[0].whole_ring else "sibling" + + +def builtin(name: str, ring_size: int) -> tuple[str, tuple[tuple[int, ...], ...]]: + """Canonical name and member lists of a built-in layout.""" + key = name.strip().lower() + if key in ("ring", f"ring{ring_size}"): + return f"ring{ring_size}", (tuple(range(ring_size)),) + if key in ("2xtp4", "4xtp2"): + if ring_size != 8: + raise FabricError(f"layout {name} is defined on a ring of 8 Sparks; the site lists {ring_size}") + if key == "2xtp4": + return "2xTP4", ((0, 1, 2, 3), (4, 5, 6, 7)) + return "4xTP2", ((0, 1), (2, 3), (4, 5), (6, 7)) + raise FabricError(f"unknown layout {name!r}; built-in layouts are {', '.join(BUILTIN_LAYOUTS)} " + "(ring for the whole ring of another size), or give --groups") + + +def resolve(*, ring_size: int, layout: str | None = None, groups: str | None = None, name: str | None = None, + relay_egress: str | None = None) -> FabricLayout: + """The layout of an operation: a built-in name, or custom groups (``groups``) with an optional name.""" + if (layout is None) == (groups is None): + raise FabricError("give exactly one of --layout and --groups") + if layout is not None: + canonical, member_lists = builtin(layout, ring_size) + else: + member_lists = parse_groups(groups, ring_size) + canonical = name or "custom" + built = tuple(Group(members, ring_size) for members in member_lists) + return FabricLayout(canonical, ring_size, built, relay_egress or default_relay_egress(built)) diff --git a/sparkring_fabric/sparkring_fabric/fabric/mesh_marker.c b/sparkring_fabric/sparkring_fabric/fabric/mesh_marker.c new file mode 100644 index 00000000..1ead5f79 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/mesh_marker.c @@ -0,0 +1,342 @@ +#define _DEFAULT_SOURCE +#define _POSIX_C_SOURCE 200809L + +/* + * Tag RoCE v2 packets by destination IPv4 address in the mlx5 RDMA transmit + * flow domain. + * + * One process owns one RDMA device. Each --rule ADDRESS=ETHERTYPE installs an + * RDMA-TX flow that matches outer EtherType 0x0800 and the exact outer + * destination IPv4 address and rewrites the outer EtherType to ETHERTYPE. + * Every RDMA queue pair on the device that sends to ADDRESS is tagged, + * whatever its flow label or UDP source port, so relays downstream can act + * on the tag. The rules stay installed until SIGINT/SIGTERM (--managed) or + * for --run-seconds; process exit removes them. + * + * Build: cc -O2 -Wall -Wextra mesh_marker.c -o ring8-mesh-marker -libverbs -lmlx5 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MATCH_PARAMETER_BYTES 0x180U +#define MLX5_MODIFICATION_TYPE_SET 0x1U +#define MLX5_MODIFICATION_FIELD_OUTER_ETHERTYPE 0x03U +#define MLX5_MATCH_CRITERIA_OUTER_HEADERS 0x1U +/* Byte offsets inside fte_match_set_lyr_2_4 (outer headers). */ +#define OUTER_ETHERTYPE_OFFSET 6U +#define OUTER_DST_IPV4_OFFSET 60U +#define MAX_RULES 64 +#define MAX_RUN_SECONDS 7200U +#define STOP_POLL_NANOSECONDS 100000000L + +static volatile sig_atomic_t stop_requested; + +static void request_stop(int signal_number) +{ + (void)signal_number; + stop_requested = 1; +} + +struct rule { + struct in_addr address; + uint16_t ethertype; + struct ibv_flow_action *action; + struct ibv_flow *flow; +}; + +struct options { + const char *device_name; + struct rule rules[MAX_RULES]; + int rule_count; + unsigned int run_seconds; + bool managed; +}; + +static void usage(const char *program) +{ + fprintf(stderr, + "usage: %s --device RDMA_DEVICE --rule IPV4=ETHERTYPE [--rule ...] " + "(--run-seconds SECONDS | --managed)\n", + program); +} + +static int parse_rule(const char *text, struct rule *rule) +{ + char address[INET_ADDRSTRLEN]; + const char *equals = strchr(text, '='); + char *end = NULL; + unsigned long value; + size_t length; + + if (equals == NULL) { + return -1; + } + length = (size_t)(equals - text); + if (length == 0 || length >= sizeof(address)) { + return -1; + } + memcpy(address, text, length); + address[length] = '\0'; + if (inet_pton(AF_INET, address, &rule->address) != 1) { + return -1; + } + errno = 0; + value = strtoul(equals + 1, &end, 0); + if (errno != 0 || end == equals + 1 || *end != '\0' || value == 0 || + value > UINT16_MAX || value == 0x0800U) { + return -1; + } + rule->ethertype = (uint16_t)value; + return 0; +} + +static int parse_options(int argc, char **argv, struct options *options) +{ + enum { OPT_DEVICE = 1000, OPT_RULE, OPT_RUN_SECONDS, OPT_MANAGED }; + static const struct option long_options[] = { + {"device", required_argument, NULL, OPT_DEVICE}, + {"rule", required_argument, NULL, OPT_RULE}, + {"run-seconds", required_argument, NULL, OPT_RUN_SECONDS}, + {"managed", no_argument, NULL, OPT_MANAGED}, + {"help", no_argument, NULL, 'h'}, + {NULL, 0, NULL, 0}, + }; + int option; + + memset(options, 0, sizeof(*options)); + while ((option = getopt_long(argc, argv, "h", long_options, NULL)) != -1) { + switch (option) { + case OPT_DEVICE: + options->device_name = optarg; + break; + case OPT_RULE: + if (options->rule_count >= MAX_RULES || + parse_rule(optarg, &options->rules[options->rule_count]) != 0) { + fprintf(stderr, "--rule must be IPV4=ETHERTYPE (not 0x0800), at most %d\n", + MAX_RULES); + return -1; + } + options->rule_count++; + break; + case OPT_RUN_SECONDS: { + char *end = NULL; + unsigned long value; + + errno = 0; + value = strtoul(optarg, &end, 10); + if (errno != 0 || end == optarg || *end != '\0' || value == 0 || + value > MAX_RUN_SECONDS) { + fprintf(stderr, "--run-seconds must be from 1 to %u\n", MAX_RUN_SECONDS); + return -1; + } + options->run_seconds = (unsigned int)value; + break; + } + case OPT_MANAGED: + options->managed = true; + break; + case 'h': + usage(argv[0]); + return 1; + default: + return -1; + } + } + if (options->device_name == NULL || options->rule_count == 0 || optind != argc || + options->managed == (options->run_seconds != 0)) { + usage(argv[0]); + return -1; + } + for (int i = 0; i < options->rule_count; ++i) { + for (int j = 0; j < i; ++j) { + if (options->rules[i].address.s_addr == options->rules[j].address.s_addr) { + fprintf(stderr, "duplicate --rule address\n"); + return -1; + } + } + } + return 0; +} + +static struct ibv_context *open_context(const char *name) +{ + struct ibv_device **devices; + struct ibv_context *context = NULL; + int count = 0; + + devices = ibv_get_device_list(&count); + if (devices == NULL) { + fprintf(stderr, "cannot enumerate RDMA devices: %s\n", strerror(errno)); + return NULL; + } + for (int index = 0; index < count; ++index) { + if (strcmp(ibv_get_device_name(devices[index]), name) == 0) { + context = ibv_open_device(devices[index]); + break; + } + } + ibv_free_device_list(devices); + if (context == NULL) { + fprintf(stderr, "cannot open RDMA device %s: %s\n", name, strerror(errno)); + } + return context; +} + +static int wait_for_stop(const struct options *options) +{ + struct timespec deadline; + + if (clock_gettime(CLOCK_MONOTONIC, &deadline) != 0) { + return -1; + } + deadline.tv_sec += (time_t)options->run_seconds; + while (!stop_requested) { + const struct timespec interval = {0, STOP_POLL_NANOSECONDS}; + struct timespec now; + + if (!options->managed) { + if (clock_gettime(CLOCK_MONOTONIC, &now) != 0) { + return -1; + } + if (now.tv_sec > deadline.tv_sec || + (now.tv_sec == deadline.tv_sec && now.tv_nsec >= deadline.tv_nsec)) { + return 0; + } + } + if (nanosleep(&interval, NULL) != 0 && errno != EINTR) { + return -1; + } + } + return 0; +} + +int main(int argc, char **argv) +{ + struct options options; + struct mlx5dv_flow_match_parameters *mask = NULL; + struct mlx5dv_flow_match_parameters *value = NULL; + struct mlx5dv_flow_matcher_attr matcher_attributes = {0}; + struct mlx5dv_flow_matcher *matcher = NULL; + struct ibv_context *context = NULL; + struct sigaction stop_action; + int parse_result; + int installed = 0; + int result = EXIT_FAILURE; + + parse_result = parse_options(argc, argv, &options); + if (parse_result != 0) { + return parse_result > 0 ? EXIT_SUCCESS : EXIT_FAILURE; + } + memset(&stop_action, 0, sizeof(stop_action)); + stop_action.sa_handler = request_stop; + if (sigemptyset(&stop_action.sa_mask) != 0 || sigaction(SIGINT, &stop_action, NULL) != 0 || + sigaction(SIGTERM, &stop_action, NULL) != 0) { + fprintf(stderr, "cannot install SIGINT/SIGTERM handlers: %s\n", strerror(errno)); + return EXIT_FAILURE; + } + context = open_context(options.device_name); + if (context == NULL) { + goto cleanup; + } + mask = calloc(1, sizeof(*mask) + MATCH_PARAMETER_BYTES); + value = calloc(1, sizeof(*value) + MATCH_PARAMETER_BYTES); + if (mask == NULL || value == NULL) { + fprintf(stderr, "cannot allocate mlx5 flow match parameters\n"); + goto cleanup; + } + mask->match_sz = MATCH_PARAMETER_BYTES; + value->match_sz = MATCH_PARAMETER_BYTES; + memset((uint8_t *)mask->match_buf + OUTER_ETHERTYPE_OFFSET, 0xff, 2); + memset((uint8_t *)mask->match_buf + OUTER_DST_IPV4_OFFSET, 0xff, 4); + matcher_attributes.type = IBV_FLOW_ATTR_NORMAL; + matcher_attributes.priority = 0; + matcher_attributes.match_criteria_enable = MLX5_MATCH_CRITERIA_OUTER_HEADERS; + matcher_attributes.match_mask = mask; + matcher_attributes.comp_mask = MLX5DV_FLOW_MATCHER_MASK_FT_TYPE; + matcher_attributes.ft_type = MLX5DV_FLOW_TABLE_TYPE_RDMA_TX; + matcher = mlx5dv_create_flow_matcher(context, &matcher_attributes); + if (matcher == NULL) { + fprintf(stderr, "RDMA-TX matcher creation failed: %s\n", strerror(errno)); + goto cleanup; + } + for (int i = 0; i < options.rule_count && !stop_requested; ++i) { + struct rule *rule = &options.rules[i]; + struct mlx5dv_flow_action_attr action = {0}; + const uint16_t ipv4_ethertype = htons(0x0800U); + uint32_t words[2]; + uint64_t action_word = 0; + + words[0] = htonl((MLX5_MODIFICATION_TYPE_SET << 28) | + ((uint32_t)MLX5_MODIFICATION_FIELD_OUTER_ETHERTYPE << 16) | 16U); + words[1] = htonl((uint32_t)rule->ethertype); + memcpy(&action_word, words, sizeof(action_word)); + rule->action = mlx5dv_create_flow_action_modify_header( + context, sizeof(action_word), &action_word, MLX5DV_FLOW_TABLE_TYPE_RDMA_TX); + if (rule->action == NULL) { + fprintf(stderr, "RDMA-TX EtherType rewrite action creation failed: %s\n", + strerror(errno)); + goto cleanup; + } + memset(value->match_buf, 0, MATCH_PARAMETER_BYTES); + memcpy((uint8_t *)value->match_buf + OUTER_ETHERTYPE_OFFSET, &ipv4_ethertype, 2); + memcpy((uint8_t *)value->match_buf + OUTER_DST_IPV4_OFFSET, &rule->address.s_addr, 4); + action.type = MLX5DV_FLOW_ACTION_IBV_FLOW_ACTION; + action.action = rule->action; + rule->flow = mlx5dv_create_flow(matcher, value, 1, &action); + if (rule->flow == NULL) { + fprintf(stderr, "RDMA-TX flow for %s failed: %s\n", inet_ntoa(rule->address), + strerror(errno)); + goto cleanup; + } + installed++; + } + printf("{\"device\":\"%s\",\"rules\":[", options.device_name); + for (int i = 0; i < options.rule_count; ++i) { + printf("%s{\"dst\":\"%s\",\"ethertype\":\"0x%04x\"}", i ? "," : "", + inet_ntoa(options.rules[i].address), options.rules[i].ethertype); + } + printf("],\"installed\":%d,\"managed\":%s,\"run_seconds\":%u}\n", installed, + options.managed ? "true" : "false", options.run_seconds); + fflush(stdout); + if (wait_for_stop(&options) != 0) { + fprintf(stderr, "wait failed: %s\n", strerror(errno)); + goto cleanup; + } + result = EXIT_SUCCESS; + +cleanup: + if (stop_requested) { + result = EXIT_SUCCESS; + } + for (int i = 0; i < options.rule_count; ++i) { + if (options.rules[i].flow != NULL && ibv_destroy_flow(options.rules[i].flow) != 0) { + result = EXIT_FAILURE; + } + if (options.rules[i].action != NULL && + ibv_destroy_flow_action(options.rules[i].action) != 0) { + result = EXIT_FAILURE; + } + } + if (matcher != NULL && mlx5dv_destroy_flow_matcher(matcher) != 0) { + result = EXIT_FAILURE; + } + free(value); + free(mask); + if (context != NULL && ibv_close_device(context) != 0) { + result = EXIT_FAILURE; + } + return result; +} diff --git a/sparkring_fabric/sparkring_fabric/fabric/ops.py b/sparkring_fabric/sparkring_fabric/fabric/ops.py new file mode 100644 index 00000000..028135b7 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/ops.py @@ -0,0 +1,216 @@ +"""Operations on the Sparks: read, plan, compare, apply and verify. + +Every Spark is reached through an *executor*: a function that runs one +``bash -s`` script on an SSH target and returns its exit code and output +(:func:`ssh_executor`; tests pass the host-command simulator's instead). The +Sparks of an operation are contacted in parallel. + +``evaluate`` reads nothing itself: it takes the states :func:`gather` read, +derives the facts of each group's members (addresses and MACs as the Sparks +report them), checks the cabling of each owned cable (both ends of each link +on one subnet), builds each group's plan and compares every member with it. +``apply`` runs the scripts of a comparison; callers read the Sparks again and +evaluate once more to verify. +""" + +from __future__ import annotations + +import concurrent.futures +import dataclasses +from collections.abc import Callable, Iterable, Sequence + +from .. import routes +from .. import site as site_mod +from ..site import Site +from . import diff as diff_mod +from . import plan as plan_mod +from . import state as state_mod +from .commands import MarkerConfig, read_script, route_get_script +from .layouts import FabricError, FabricLayout, Group + +Executor = Callable[[str, str, float], site_mod.Result] +READ_TIMEOUT = 60.0 +APPLY_TIMEOUT = 180.0 + + +def ssh_executor(target: str, script: str, timeout: float) -> site_mod.Result: + """Run ``script`` with ``bash -s`` on ``target`` (batch-mode SSH, deadline ``timeout``).""" + return site_mod.ssh(target, "bash -s", input_bytes=script.encode(), timeout=timeout) + + +def _parallel(jobs: Sequence[int], work: Callable[[int], object]) -> dict[int, object]: + if not jobs: + return {} + with concurrent.futures.ThreadPoolExecutor(max_workers=min(8, len(jobs))) as pool: + return dict(zip(jobs, pool.map(work, jobs))) + + +def gather(site: Site, positions: Iterable[int], executor: Executor, marker: MarkerConfig, + *, timeout: float = READ_TIMEOUT) -> dict[int, state_mod.HostState]: + """Read every listed Spark (READ-ONLY REMOTE).""" + script = read_script(marker) + + def read(position: int) -> state_mod.HostState: + host = site.host(position) + result = executor(host.ssh, script, timeout) + return state_mod.parse(position, host.name, host.ssh, returncode=result.returncode, stdout=result.stdout, + stderr=result.stderr) + + return _parallel(sorted(set(positions)), read) + + +def facts_from(site: Site, states: dict[int, state_mod.HostState]) -> plan_mod.Facts: + """The addresses and MACs the Sparks report (only usable ports are included).""" + return plan_mod.Facts(plan_mod.SparkFacts(position, site.host(position).name, state.ports()) + for position, state in sorted(states.items()) if state.reachable) + + +def cable_problems(group: Group, facts: plan_mod.Facts) -> list[str]: + """Each owned cable's two links must join one subnet: otherwise the site's ring order is not the cabling.""" + problems = [] + for cable in group.layout().fabric.cables: + for secondary in (False, True): + here = facts.port(cable.a, routes.role_at(cable.a_port, secondary).netdev) + there = facts.port(cable.b, routes.role_at(cable.b_port, secondary).netdev) + networks = (here.network(), there.network()) + if None in networks: + continue + if networks[0] != networks[1] or here.address == there.address: + problems.append(f"cable {cable.text} ({plan_mod.class_name(secondary)} link): {facts.name(cable.a)} " + f"{here.netdev} {here.address}/{here.prefixlen} and {facts.name(cable.b)} " + f"{there.netdev} {there.address}/{there.prefixlen} are not one subnet; the site's " + "ring order does not match the cabling") + return problems + + +@dataclasses.dataclass +class Outcome: + """A comparison of the selected groups' members with their plans (``up``) or their removal (``down``).""" + + layout: FabricLayout + mode: str + groups: tuple[Group, ...] + plans: dict[str, plan_mod.GroupPlan] = dataclasses.field(default_factory=dict) + diffs: list[diff_mod.SparkDiff] = dataclasses.field(default_factory=list) + problems: list[str] = dataclasses.field(default_factory=list) + facts: plan_mod.Facts | None = None + + @property + def blocked(self) -> bool: + return bool(self.problems) or any(d.blocked for d in self.diffs) + + @property + def pending(self) -> bool: + return any(d.pending for d in self.diffs) + + @property + def host_changes(self) -> int: + return sum(len(d.host_changes) for d in self.diffs) + + +def evaluate(site: Site, layout: FabricLayout, groups: Sequence[Group], states: dict[int, state_mod.HostState], + *, mode: str, marker: MarkerConfig, adopt: bool, check_hostname: bool = True, + max_relays: int = routes.DEFAULT_MAX_RELAYS) -> Outcome: + if mode not in ("up", "down"): + raise FabricError(f"mode must be up or down, got {mode!r}") + outcome = Outcome(layout, mode, tuple(groups)) + problems = plan_mod.layout_isolation_problems(layout) + if problems: + raise FabricError("isolation: " + "; ".join(problems)) + facts = facts_from(site, states) + outcome.facts = facts + for group in groups: + if mode == "down": + for position in group.order: + outcome.diffs.append(diff_mod.compare_down(states[position], group=group.label, marker=marker, + adopt=adopt, check_hostname=check_hostname)) + continue + problems = [problem for position in group.order + for problem in states[position].fact_problems(check_hostname=False)] + member_facts = plan_mod.Facts([facts.spark(p) for p in group.order if facts.has(p)]) + problems += member_facts.problems() + group_plan = None + if not problems: + try: + problems += cable_problems(group, facts) + if not problems: + group_plan = plan_mod.build_group_plan(group, facts, relay_egress=layout.relay_egress, + max_relays=max_relays) + except FabricError as error: + problems.append(str(error)) + if group_plan is None: + outcome.problems.extend(f"group {group.label}: {problem}" for problem in problems) + for position in group.order: + blocked = diff_mod.SparkDiff(position, site.host(position).name, group.label, mode) + blocked.blockers.append(f"group {group.label} cannot be planned (see the problems above)") + outcome.diffs.append(blocked) + continue + outcome.plans[group.label] = group_plan + for position in group.order: + outcome.diffs.append(diff_mod.compare_up(states[position], group_plan.spark(position), group_plan, + layout_name=layout.name, marker=marker, adopt=adopt, + check_hostname=check_hostname)) + return outcome + + +def lane_route_checks(outcome: Outcome, *, installed_only: bool) -> dict[int, dict[str, str]]: + """Destinations to resolve with ``ip route get`` per Spark, and the network device each must use. + + Every SIRCL lane of every planned group (direct lanes use the connected + route of their cable) and every other carried path. With + ``installed_only``, relayed destinations whose origin route the + comparison still has to add or replace are left out. + """ + checks: dict[int, dict[str, str]] = {} + for group_plan in outcome.plans.values(): + layout = group_plan.layout + pending = {(d.position, change.key.split("/")[0]) for d in outcome.diffs + for change in d.changes if change.kind == "route" and change.action in ("add", "replace")} + for spark in group_plan.sparks: + for route in spark.routes: + if not (installed_only and (spark.position, route.destination) in pending): + checks.setdefault(spark.position, {})[route.destination] = route.netdev + facts = outcome.facts + for rank, peers in enumerate(group_plan.sircl.ranks): + origin = layout.positions[rank] + for peer, lanes in peers.items(): + for lane in lanes: + if lane.hops == 1 and facts is not None and facts.has(layout.positions[peer]): + destination = facts.port(layout.positions[peer], lane.remote.netdev).address + checks.setdefault(origin, {})[destination] = lane.local.netdev + return checks + + +def check_lane_routes(site: Site, outcome: Outcome, executor: Executor, *, installed_only: bool, + timeout: float = READ_TIMEOUT) -> dict[int, list[str]]: + """Resolve every lane destination on its origin Spark (READ-ONLY REMOTE); problems per Spark.""" + checks = lane_route_checks(outcome, installed_only=installed_only) + + def resolve(position: int) -> list[str]: + wanted = checks[position] + result = executor(site.host(position).ssh, route_get_script(wanted), timeout) + answers = state_mod.parse_sections(result.stdout) + problems = [] + for destination, netdev in sorted(wanted.items()): + answer = answers.get(f"route:{destination}", "").strip() + words = answer.split() + device = words[words.index("dev") + 1] if "dev" in words[:-1] else None + if device != netdev: + problems.append(f"ip route get {destination} uses {device or 'no device'}, the lane needs {netdev} " + f"({answer.splitlines()[0] if answer else 'no answer'})") + return problems + + return {position: problems for position, problems in _parallel(sorted(checks), resolve).items() if problems} + + +def apply(outcome: Outcome, site: Site, executor: Executor, *, timeout: float = APPLY_TIMEOUT + ) -> dict[int, site_mod.Result]: + """Run every Spark's script of a comparison without blockers (MUTATES HOST).""" + if outcome.blocked: + raise FabricError("refusing to apply a comparison with blockers") + scripts = {d.position: d.script for d in outcome.diffs if d.script} + + def run(position: int) -> site_mod.Result: + return executor(site.host(position).ssh, scripts[position], timeout) + + return _parallel(sorted(scripts), run) diff --git a/sparkring_fabric/sparkring_fabric/fabric/plan.py b/sparkring_fabric/sparkring_fabric/fabric/plan.py new file mode 100644 index 00000000..bb603351 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/plan.py @@ -0,0 +1,802 @@ +"""The relay plan of a layout, derived from SIRCL's route module. + +Carried paths. For every ordered pair of members of a group the plan carries +every shortest path of the group's fabric (``routes.Fabric.shortest_paths``) +on both function classes. SIRCL's lanes (``routes.derive_routes``) are a +subset: lane 0 is the primary function and lane 1 the secondary function of +one of these paths. On a path of Sparks both sets are equal. On a ring of even +size the plan also carries the other function class of each opposite pair's +two paths, which makes the whole-ring plan the universal relay table: every +Spark reaches all four addresses of every Spark it shares no cable with. Every +lane of ``routes.derive_routes`` is checked to be carried, so this plan and +SIRCL's route maps cannot disagree. + +Objects, for a carried path with ``h >= 2`` hops from ``a`` to ``b`` on +function class ``c``: + +- an origin route at ``a``: ``b``'s address on the arrival function as a /32 + route, scope link, over ``a``'s network device of class ``c`` on the path's + first port, source ``a``'s address on that device, and a permanent + neighbour entry holding the adjacent Spark's MAC on that cable; +- a marker rule at ``a``: the RDMA device of that function rewrites the + EtherType of RoCE packets to that destination into ``TAG(h - 1)``; +- a relay filter at every intermediate Spark: on the ingress of the device + that receives the path (class ``c``), match ``TAG(k)`` (``k`` relays left), + set the next Spark's MAC of class ``c``, rewrite the tag to ``TAG(k - 1)`` + and redirect out of the other port (relay egress ``same`` or ``sibling``, + :mod:`.layouts`). + +``TAG(0)`` is IPv4 (0x0800) and ``TAG(k) = 0x88b4 + k``. Relay filters do not +depend on the sender: one per (Spark, ingress device, tag). + +Measured constraints that the plan states and applies: + +- a relay's hardware hairpin queue holds 512 KiB, the device maximum, and + cannot pause its sender, so frames beyond it are dropped. The plan lists + the SIRCL lanes through every queue, the relay load factor ``f`` and the + per-peer op bound ``0.75 * 512 KiB / f``; +- relay egress through the sibling Socket Direct function of the egress port + lowered burst loss to 0.06 % at 2 MiB (:mod:`.layouts`); +- queue pairs use flow label 0 and tags are chosen by destination address, + never by UDP port: the sender NIC computes the ICRC after the RDMA-TX + rewrite, so a rewritten UDP field would be covered by the ICRC and could not + be restored by a relay, and with flow label 0 the UDP source port does not + identify a lane. The EtherType lies outside the ICRC. + +Isolation: routes and tags exist only for destinations in the +same group and only on its members; a relay filter exists only on a member +that lies strictly inside a carried path, and both cables it forwards between +belong to the group. :func:`trace` follows every origin route through the +plan's objects over the physical ring and must reach the destination without +touching a Spark outside the group; :func:`isolation_problems` checks the +rules within and across the groups of a layout. + +Everything here is offline. Facts (addresses and MACs) come from the Sparks +(:mod:`.state`), from a facts file (schema ``sparkring-fabric-facts/v1``), or +as symbolic placeholders that make a plan reviewable without them. +""" + +from __future__ import annotations + +import dataclasses +import hashlib +import ipaddress +import json +import re +from collections.abc import Iterable, Mapping, Sequence + +from .. import routes +from .layouts import RELAY_EGRESS, FabricError, FabricLayout, Group + +ETH_P_IP = 0x0800 +TAG_BASE = 0x88B4 +MAX_TAG = 7 # tags TAG(1)..TAG(7); relay filter preferences 11..17 +FILTER_PREF_BASE = 10 +RESERVED_PREFS = range(FILTER_PREF_BASE + 1, FILTER_PREF_BASE + MAX_TAG + 1) +HAIRPIN_QUEUE_BYTES = routes.DEFAULT_HAIRPIN_QUEUE +RELAY_QUEUE_SHARE = routes.RELAY_QUEUE_SHARE +FABRIC_NETDEVS = tuple(role.netdev for role in routes.ROLES) +RDMA_DEVICES = tuple(role.device for role in routes.ROLES) +FACTS_SCHEMA = "sparkring-fabric-facts/v1" +PLAN_SCHEMA = "sparkring-fabric-plan/v1" +_ROLE_BY_NETDEV = {role.netdev: role for role in routes.ROLES} +_MAC = re.compile(r"^[0-9a-f]{2}(?::[0-9a-f]{2}){5}$") + + +def tag(k: int) -> int: + """The EtherType of a frame with ``k`` relays left.""" + if not 0 <= k <= MAX_TAG: + raise FabricError(f"relay count {k} is outside the tags 0 to {MAX_TAG}") + return ETH_P_IP if k == 0 else TAG_BASE + k + + +def relays_left(ethertype: int) -> int | None: + """``k`` for ``TAG(k)``, or None for an EtherType that is not a relay tag.""" + if ethertype == ETH_P_IP: + return 0 + k = ethertype - TAG_BASE + return k if 1 <= k <= MAX_TAG else None + + +def role_of_netdev(netdev: str) -> routes.Role: + role = _ROLE_BY_NETDEV.get(netdev) + if role is None: + raise FabricError(f"{netdev} is not one of the fabric network devices {', '.join(FABRIC_NETDEVS)}") + return role + + +def class_name(secondary: bool) -> str: + return "secondary" if secondary else "primary" + + +def _address_key(text: str) -> tuple: + try: + return (0, int(ipaddress.IPv4Address(text))) + except ValueError: + return (1, text) + + +# -- facts -------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class Port: + """One fabric function's network device on one Spark: its MAC and IPv4 address.""" + + netdev: str + mac: str + address: str + prefixlen: int | None = None + + def network(self) -> ipaddress.IPv4Network | None: + if self.prefixlen is None: + return None + try: + return ipaddress.IPv4Interface(f"{self.address}/{self.prefixlen}").network + except ValueError: + return None + + def to_json(self) -> dict[str, object]: + address = self.address if self.prefixlen is None else f"{self.address}/{self.prefixlen}" + return {"mac": self.mac, "address": address} + + +@dataclasses.dataclass(frozen=True) +class SparkFacts: + position: int + name: str + ports: tuple[Port, ...] + + def port(self, netdev: str) -> Port | None: + for port in self.ports: + if port.netdev == netdev: + return port + return None + + +class Facts: + """Addresses and MACs of the fabric functions of the Sparks a plan uses.""" + + def __init__(self, sparks: Iterable[SparkFacts], *, symbolic: bool = False) -> None: + self.symbolic = symbolic + self._sparks = {spark.position: spark for spark in sparks} + self._addresses: dict[str, list[tuple[int, str]]] = {} + self._macs: dict[str, list[tuple[int, str]]] = {} + for spark in self._sparks.values(): + for port in spark.ports: + self._addresses.setdefault(port.address, []).append((spark.position, port.netdev)) + self._macs.setdefault(port.mac.lower(), []).append((spark.position, port.netdev)) + + @property + def positions(self) -> tuple[int, ...]: + return tuple(sorted(self._sparks)) + + def has(self, position: int) -> bool: + return position in self._sparks + + def spark(self, position: int) -> SparkFacts: + if position not in self._sparks: + raise FabricError(f"no facts for the Spark at ring position {position}") + return self._sparks[position] + + def name(self, position: int) -> str: + return self._sparks[position].name if position in self._sparks else f"position {position}" + + def port(self, position: int, netdev: str) -> Port: + port = self.spark(position).port(netdev) + if port is None: + raise FabricError(f"{self.name(position)} has no address or MAC for {netdev}") + return port + + def find_address(self, address: str) -> tuple[int, str] | None: + owners = self._addresses.get(address, []) + return owners[0] if len(owners) == 1 else None + + def find_mac(self, mac: str) -> tuple[int, str] | None: + owners = self._macs.get(mac.lower(), []) + return owners[0] if len(owners) == 1 else None + + def problems(self) -> list[str]: + """Addresses or MACs that more than one function holds.""" + found = [] + for label, table in (("address", self._addresses), ("MAC", self._macs)): + for value, owners in sorted(table.items()): + if len(owners) > 1: + holders = ", ".join(f"{self.name(position)} {netdev}" for position, netdev in owners) + found.append(f"{label} {value} is held by {holders}") + return found + + @classmethod + def symbolic_for(cls, names: Sequence[str]) -> "Facts": + """Placeholders ```` and ```` for every Spark of a ring.""" + return cls((SparkFacts(position, name, tuple(Port(netdev, f"<{name}:{netdev}:mac>", f"<{name}:{netdev}>") + for netdev in FABRIC_NETDEVS)) + for position, name in enumerate(names)), symbolic=True) + + @classmethod + def from_json(cls, document: Mapping[str, object]) -> "Facts": + if document.get("schema") != FACTS_SCHEMA: + raise FabricError(f"facts schema must be {FACTS_SCHEMA}") + sparks = [] + for entry in document.get("sparks", []): + position, name = int(entry["position"]), str(entry["name"]) + ports = [] + for netdev, values in sorted(dict(entry.get("ports", {})).items()): + role_of_netdev(netdev) + ports.append(port_from_text(netdev, str(values["mac"]), str(values["address"]), owner=name)) + sparks.append(SparkFacts(position, name, tuple(ports))) + return cls(sparks) + + def to_json(self) -> dict[str, object]: + return {"schema": FACTS_SCHEMA, "sparks": [ + {"position": spark.position, "name": spark.name, + "ports": {port.netdev: port.to_json() for port in spark.ports}} + for spark in sorted(self._sparks.values(), key=lambda s: s.position)]} + + +def port_from_text(netdev: str, mac: str, address: str, *, owner: str) -> Port: + """A validated :class:`Port` from a MAC and ``a.b.c.d`` or ``a.b.c.d/len``.""" + mac = mac.strip().lower() + if not _MAC.match(mac): + raise FabricError(f"{owner} {netdev}: {mac!r} is not a MAC address") + try: + if "/" in address: + interface = ipaddress.IPv4Interface(address.strip()) + return Port(netdev, mac, str(interface.ip), interface.network.prefixlen) + return Port(netdev, mac, str(ipaddress.IPv4Address(address.strip()))) + except ValueError: + raise FabricError(f"{owner} {netdev}: {address!r} is not an IPv4 address") from None + + +# -- plan objects ----------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class OriginRoute: + """A /32 route, its permanent neighbour and its marker rule at the Spark where a path starts.""" + + destination: str + netdev: str + device: str + source: str + next_mac: str + tag: int + peer: int + peer_netdev: str + hops: int + relays: tuple[int, ...] + cables: tuple[str, ...] # cables crossed, in the direction of travel + owned_cables: tuple[str, ...] # the same cables in canonical spelling + lanes: tuple[str, ...] = () # SIRCL lanes it carries: "rank r->p lane l" + + def to_json(self) -> dict[str, object]: + return {"destination": self.destination, "netdev": self.netdev, "device": self.device, + "source": self.source, "next_mac": self.next_mac, "tag": f"0x{self.tag:04x}", "peer": self.peer, + "peer_netdev": self.peer_netdev, "hops": self.hops, "relays": list(self.relays), + "cables": list(self.cables), "sircl_lanes": list(self.lanes)} + + +@dataclasses.dataclass(frozen=True) +class RelayFilter: + """A hardware ingress filter of a relay: ``TAG(k)`` in, ``TAG(k - 1)`` out of the other port.""" + + in_netdev: str + k: int + out_netdev: str + next_mac: str + next_position: int + next_netdev: str + direction: str # cw (out of port 0) or ccw (out of port 1) + lane_class: str # primary or secondary: the class of the lanes it relays + + @property + def pref(self) -> int: + return FILTER_PREF_BASE + self.k + + @property + def handle(self) -> int: + return self.k + + @property + def protocol(self) -> int: + return tag(self.k) + + @property + def new_type(self) -> int: + return tag(self.k - 1) + + def to_json(self) -> dict[str, object]: + return {"in_netdev": self.in_netdev, "k": self.k, "pref": self.pref, "protocol": f"0x{self.protocol:04x}", + "new_type": f"0x{self.new_type:04x}", "out_netdev": self.out_netdev, "next_mac": self.next_mac, + "next_position": self.next_position, "next_netdev": self.next_netdev, "direction": self.direction, + "lane_class": self.lane_class} + + +@dataclasses.dataclass(frozen=True) +class MarkerRules: + """The RDMA-TX tag rules of one RDMA device: (destination, EtherType) pairs.""" + + device: str + rules: tuple[tuple[str, int], ...] + + def to_json(self) -> dict[str, object]: + return {"device": self.device, "rules": {destination: f"0x{value:04x}" for destination, value in self.rules}} + + +@dataclasses.dataclass(frozen=True) +class SparkPlan: + position: int + name: str + group: str + routes: tuple[OriginRoute, ...] + filters: tuple[RelayFilter, ...] + + @property + def markers(self) -> tuple[MarkerRules, ...]: + by_device: dict[str, list[tuple[str, int]]] = {} + for route in self.routes: + by_device.setdefault(route.device, []).append((route.destination, route.tag)) + return tuple(MarkerRules(device, tuple(sorted(rules, key=lambda rule: _address_key(rule[0])))) + for device, rules in sorted(by_device.items(), key=lambda item: RDMA_DEVICES.index(item[0]))) + + def marker(self, device: str) -> MarkerRules | None: + for rules in self.markers: + if rules.device == device: + return rules + return None + + @property + def filter_netdevs(self) -> tuple[str, ...]: + return tuple(netdev for netdev in FABRIC_NETDEVS if any(f.in_netdev == netdev for f in self.filters)) + + def route_to(self, destination: str) -> OriginRoute | None: + for route in self.routes: + if route.destination == destination: + return route + return None + + def filter_for(self, netdev: str, k: int) -> RelayFilter | None: + for relay_filter in self.filters: + if relay_filter.in_netdev == netdev and relay_filter.k == k: + return relay_filter + return None + + def to_json(self) -> dict[str, object]: + return {"position": self.position, "name": self.name, "group": self.group, + "routes": [route.to_json() for route in self.routes], + "filters": [relay_filter.to_json() for relay_filter in self.filters], + "markers": [rules.to_json() for rules in self.markers]} + + +@dataclasses.dataclass(frozen=True) +class RelayQueue: + """One hairpin queue of a relay (ingress device to egress device) and the SIRCL lanes through it.""" + + position: int + in_netdev: str + out_netdev: str + lanes: tuple[str, ...] + + +@dataclasses.dataclass(frozen=True) +class GroupPlan: + group: Group + layout: routes.Layout + sircl: routes.GroupRoutes + relay_egress: str + max_relays: int + sparks: tuple[SparkPlan, ...] + queues: tuple[RelayQueue, ...] + busiest_queue: int + load_factor: float + digest: str + + @property + def per_peer_bytes(self) -> int | None: + """The largest per-peer op size that keeps the busiest relay queue at 75 %; None without relays.""" + if not self.load_factor: + return None + return int(RELAY_QUEUE_SHARE * HAIRPIN_QUEUE_BYTES / self.load_factor) + + def spark(self, position: int) -> SparkPlan | None: + for spark in self.sparks: + if spark.position == position: + return spark + return None + + def to_json(self) -> dict[str, object]: + return { + "group": self.group.label, "members": list(self.group.members), "cables": list(self.group.cables), + "relay_egress": self.relay_egress, "max_relays": self.max_relays, "digest": self.digest, + "route_maps": [self.sircl.route_text(rank) for rank in range(self.sircl.world)], + "relay_queues": [{"position": queue.position, "in": queue.in_netdev, "out": queue.out_netdev, + "sircl_lanes": list(queue.lanes)} for queue in self.queues], + "busiest_queue_lanes": self.busiest_queue, "load_factor": self.load_factor, + "per_peer_bytes": self.per_peer_bytes, "sparks": [spark.to_json() for spark in self.sparks], + } + + +@dataclasses.dataclass(frozen=True) +class LayoutPlan: + layout: FabricLayout + groups: tuple[GroupPlan, ...] + symbolic: bool + + def find(self, position: int) -> tuple[GroupPlan, SparkPlan] | None: + for group in self.groups: + spark = group.spark(position) + if spark is not None: + return group, spark + return None + + def to_json(self) -> dict[str, object]: + return {"schema": PLAN_SCHEMA, "layout": self.layout.name, "ring_size": self.layout.ring_size, + "relay_egress": self.layout.relay_egress, "symbolic_facts": self.symbolic, + "constraints": list(CONSTRAINTS), "groups": [group.to_json() for group in self.groups]} + + +CONSTRAINTS = ( + "relay hairpin queue: 512 KiB per (relay, ingress device, egress device), the device maximum; it cannot " + "pause its sender, so frames beyond it are dropped", + "relay egress: sibling Socket Direct function of the egress port lowered burst loss to 0.06 % at 2 MiB; " + "the whole-ring layout keeps same-function egress", + "queue pairs use flow label 0", + "tags are EtherTypes chosen by destination address, never by UDP port (the sender NIC computes the ICRC " + "after the RDMA-TX rewrite)", +) + + +# -- derivation --------------------------------------------------------------------------------- + + +def _carry(path: tuple[routes.Step, ...], secondary: bool, facts: Facts, relay_egress: str, + routes_at: dict[int, dict[str, OriginRoute]], filters_at: dict[int, dict[tuple[str, int], RelayFilter]], + label: str) -> None: + hops = len(path) + origin, target = path[0].src, path[-1].dst + local = routes.role_at(path[0].src_port, secondary) + remote = routes.role_at(path[-1].dst_port, secondary) + first = routes.role_at(path[0].dst_port, secondary) + route = OriginRoute( + destination=facts.port(target, remote.netdev).address, netdev=local.netdev, device=local.device, + source=facts.port(origin, local.netdev).address, next_mac=facts.port(path[0].dst, first.netdev).mac, + tag=tag(hops - 1), peer=target, peer_netdev=remote.netdev, hops=hops, + relays=tuple(step.dst for step in path[:-1]), cables=tuple(step.text for step in path), + owned_cables=tuple(step.cable.text for step in path)) + existing = routes_at[origin].get(route.destination) + if existing is not None and existing != route: + raise FabricError(f"group {label}: two paths from Spark {origin} reach {route.destination} differently") + routes_at[origin][route.destination] = route + for index in range(hops - 1): + arrive, leave = path[index], path[index + 1] + relay = arrive.dst + if leave.src != relay or leave.src_port != 1 - arrive.dst_port: + raise FabricError(f"group {label}: the path {route.cables} does not pass through Spark {relay}") + in_role = routes.role_at(arrive.dst_port, secondary) + out_role = routes.role_at(leave.src_port, secondary if relay_egress == "same" else not secondary) + next_role = routes.role_at(leave.dst_port, secondary) + relay_filter = RelayFilter( + in_netdev=in_role.netdev, k=hops - 1 - index, out_netdev=out_role.netdev, + next_mac=facts.port(leave.dst, next_role.netdev).mac, next_position=leave.dst, + next_netdev=next_role.netdev, direction="cw" if leave.src_port == 0 else "ccw", + lane_class=class_name(secondary)) + key = (relay_filter.in_netdev, relay_filter.k) + known = filters_at[relay].get(key) + if known is not None and known != relay_filter: + raise FabricError(f"group {label}: Spark {relay} would need two relay filters for TAG({relay_filter.k}) " + f"on {relay_filter.in_netdev}") + filters_at[relay][key] = relay_filter + + +def _digest(label: str, relay_egress: str, sparks: Sequence[SparkPlan]) -> str: + canonical = json.dumps({"group": label, "relay_egress": relay_egress, + "sparks": [spark.to_json() for spark in sparks]}, sort_keys=True) + return hashlib.sha256(canonical.encode()).hexdigest()[:16] + + +@dataclasses.dataclass(frozen=True) +class ChainGroup: + """An open chain/path group backed directly by its fabric cables (no closing ring cable).""" + + members: tuple[int, ...] + fabric: routes.Fabric + + def __post_init__(self) -> None: + members = tuple(int(member) for member in self.members) + object.__setattr__(self, "members", members) + if len(members) < 2 or len(set(members)) != len(members): + raise FabricError(f"chain group {members} needs at least two distinct Sparks") + if self.fabric.kind == "disconnected": + raise FabricError(f"chain group {members} fabric is disconnected") + self.layout() + + def layout(self) -> routes.Layout: + try: + return routes.Layout(self.fabric, self.members) + except routes.RouteError as error: + raise FabricError(str(error)) from None + + @property + def ring_size(self) -> int: + return len(self.fabric.positions) + + @property + def whole_ring(self) -> bool: + return False + + @property + def order(self) -> tuple[int, ...]: + return self.members + + @property + def kind(self) -> str: + return "pair" if len(self.members) == 2 else "path" + + @property + def label(self) -> str: + return f"{self.kind}:{'-'.join(str(position) for position in self.order)}" + + @property + def cables(self) -> tuple[str, ...]: + return tuple(cable.text for cable in self.fabric.cables) + + +def build_chain_plan( + positions: Sequence[int], + facts: Facts, + *, + fabric: routes.Fabric | None = None, + relay_egress: str = "sibling", + max_relays: int = routes.DEFAULT_MAX_RELAYS, +) -> GroupPlan: + """Build the relay plan of an open chain/path of Sparks without assuming a closed ring.""" + members = tuple(int(p) for p in positions) + if fabric is None: + try: + fabric = routes.Fabric.path(members) + except routes.RouteError as error: + raise FabricError(str(error)) from None + if fabric.kind != "path": + raise FabricError(f"open chain plan requires a connected path fabric, got {fabric.kind}") + return build_group_plan(ChainGroup(members, fabric), facts, relay_egress=relay_egress, max_relays=max_relays) + + +def build_group_plan(group: Group | ChainGroup, facts: Facts, *, relay_egress: str, + max_relays: int = routes.DEFAULT_MAX_RELAYS) -> GroupPlan: + """The relay plan of one group (module docstring), checked by :func:`trace` on every origin route.""" + if relay_egress not in RELAY_EGRESS: + raise FabricError(f"relay egress must be one of {', '.join(RELAY_EGRESS)}") + if not 0 <= max_relays <= MAX_TAG: + raise FabricError(f"the relay limit must be between 0 and {MAX_TAG} (one tag per relay count)") + layout = group.layout() + members = layout.positions + routes_at: dict[int, dict[str, OriginRoute]] = {position: {} for position in members} + filters_at: dict[int, dict[tuple[str, int], RelayFilter]] = {position: {} for position in members} + for origin in members: + for target in members: + if origin == target: + continue + for path in layout.fabric.shortest_paths(origin, target): + if len(path) < 2: + continue + if len(path) - 1 > max_relays: + raise FabricError( + f"group {group.label}: Spark {target} is {len(path)} cables from Spark {origin}, " + f"{len(path) - 1} relays; the qualified limit is {max_relays} (" + "--max-relays raises it, research-only)") + for secondary in (False, True): + _carry(path, secondary, facts, relay_egress, routes_at, filters_at, group.label) + sircl = routes.derive_routes(layout, 2) + lanes_of: dict[tuple[int, str], list[str]] = {} + for rank, peers in enumerate(sircl.ranks): + origin = layout.positions[rank] + for peer, lanes in sorted(peers.items()): + for lane in lanes: + if lane.hops < 2: + continue + destination = facts.port(layout.positions[peer], lane.remote.netdev).address + route = routes_at[origin].get(destination) + if (route is None or route.netdev != lane.local.netdev or route.cables != lane.cables + or route.tag != tag(len(lane.relays))): + raise FabricError(f"group {group.label}: SIRCL lane {lane.lane} from rank {rank} to rank {peer} " + f"({lane.local.device}, {lane.cables}) is not carried by the relay plan") + lanes_of.setdefault((origin, destination), []).append(f"rank {rank}->{peer} lane {lane.lane}") + sparks = [] + for position in group.order: + planned = sorted(routes_at[position].values(), + key=lambda r: (FABRIC_NETDEVS.index(r.netdev), r.hops, _address_key(r.destination))) + planned = [dataclasses.replace(route, lanes=tuple(lanes_of.get((position, route.destination), ()))) + for route in planned] + filters = sorted(filters_at[position].values(), key=lambda f: (FABRIC_NETDEVS.index(f.in_netdev), f.k)) + sparks.append(SparkPlan(position, facts.name(position), group.label, tuple(planned), tuple(filters))) + by_position = {spark.position: spark for spark in sparks} + for spark in sparks: + for route in spark.routes: + result = trace(by_position, facts, group.ring_size, spark.position, route.destination, + fabric=layout.fabric) + if result.outcome != "delivered" or result.hops[-1] != (route.peer, route.peer_netdev): + raise FabricError(f"group {group.label}: the route from {spark.name} to {route.destination} does " + f"not deliver through the plan's relays ({result.outcome}: {result.detail})") + outside = [position for position, _ in result.hops if position not in members] + if outside: + raise FabricError(f"group {group.label}: the route from {spark.name} to {route.destination} " + f"crosses Sparks {outside} outside the group") + maps = [sircl.route_map(rank) for rank in range(layout.world)] + queues = [] + for (relay, secondary, egress_port), members_of_queue in sorted(routes.relay_queues(layout, maps).items()): + in_role = routes.role_at(1 - egress_port, secondary) + out_role = routes.role_at(egress_port, secondary if relay_egress == "same" else not secondary) + queues.append(RelayQueue(relay, in_role.netdev, out_role.netdev, + tuple(f"rank {r}->{p} lane {lane}" for r, p, lane in members_of_queue))) + busiest, load = routes.relay_load(sircl) + return GroupPlan(group, layout, sircl, relay_egress, max_relays, tuple(sparks), tuple(queues), busiest, load, + _digest(group.label, relay_egress, sparks)) + + +def build_layout_plan(layout: FabricLayout, facts: Facts, *, groups: Sequence[Group] | None = None, + max_relays: int = routes.DEFAULT_MAX_RELAYS) -> LayoutPlan: + """Plans of the layout's groups (or of ``groups``), checked for isolation across the whole layout.""" + problems = layout_isolation_problems(layout) + chosen = tuple(groups) if groups is not None else layout.groups + plans = tuple(build_group_plan(group, facts, relay_egress=layout.relay_egress, max_relays=max_relays) + for group in chosen) + problems += isolation_problems(plans) + if problems: + raise FabricError("isolation: " + "; ".join(problems)) + return LayoutPlan(layout, plans, facts.symbolic) + + +# -- checks ---------------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class Trace: + """Where a frame sent on an origin route went: ``delivered``, ``dropped``, ``misdelivered``, + ``unrouted`` or ``looped``; ``hops`` lists the (position, receiving device) of every cable crossed.""" + + outcome: str + hops: tuple[tuple[int, str], ...] + detail: str = "" + + +def trace(sparks: Mapping[int, SparkPlan], facts: Facts, ring_size: int | None, origin: int, destination: str, + *, fabric: routes.Fabric | None = None, limit: int = 2 * MAX_TAG) -> Trace: + """Follow a frame from ``origin`` to ``destination`` through the plan's objects on the physical fabric. + + When ``fabric`` is provided, each hop follows its exact cable + (``fabric.cross``), so open chains/paths drop frames exiting an uncabled + endpoint port and arbitrary port pairings are traced faithfully. Otherwise, + falls back to a closed ring of ``ring_size`` Sparks where port 0 of + position ``i`` is cabled to port 1 of position ``(i + 1) % ring_size``. + """ + spark = sparks.get(origin) + route = spark.route_to(destination) if spark is not None else None + if route is None: + return Trace("unrouted", (), f"no origin route to {destination} at position {origin}") + mac, ethertype, here, out_netdev = route.next_mac, route.tag, origin, route.netdev + hops: list[tuple[int, str]] = [] + for _ in range(limit): + port = role_of_netdev(out_netdev).port + if fabric is not None: + step = fabric.cross(here, port) + if step is None: + return Trace("dropped", tuple(hops), + f"position {here} port {port} has no cable on this fabric") + there, expected_port = step.dst, step.dst_port + else: + if ring_size is None: + raise FabricError("trace requires either fabric or ring_size") + there = (here + 1) % ring_size if port == 0 else (here - 1) % ring_size + expected_port = 1 - port + receiver = facts.find_mac(mac) + if receiver is None or receiver[0] != there or role_of_netdev(receiver[1]).port != expected_port: + return Trace("misdelivered", tuple(hops), f"a frame for {mac} leaves position {here} port {port}; " + f"the cable ends at position {there} port {expected_port}") + hops.append(receiver) + netdev = receiver[1] + k = relays_left(ethertype) + if k == 0: + if facts.port(there, netdev).address == destination: + return Trace("delivered", tuple(hops)) + return Trace("misdelivered", tuple(hops), f"IPv4 frame for {destination} reached {netdev} at {there}") + relay = sparks.get(there) + relay_filter = relay.filter_for(netdev, k) if (relay is not None and k is not None) else None + if relay_filter is None: + return Trace("dropped", tuple(hops), f"no relay filter for EtherType 0x{ethertype:04x} on {netdev} " + f"at position {there}") + mac, ethertype, here, out_netdev = relay_filter.next_mac, tag(k - 1), there, relay_filter.out_netdev + return Trace("looped", tuple(hops), f"more than {limit} cables") + + +def isolation_problems(plans: Sequence[GroupPlan]) -> list[str]: + """Breaks of the group isolation rules within and across group plans; empty when isolated.""" + problems = [] + for plan in plans: + members = set(plan.group.members) + owned = set(plan.group.cables) + fabric = plan.layout.fabric + for spark in plan.sparks: + if spark.position not in members: + problems.append(f"{plan.group.label}: {spark.name} is not a member but has objects") + for route in spark.routes: + if route.peer not in members: + problems.append(f"{plan.group.label}: {spark.name} routes to {route.destination} of Spark " + f"{route.peer}, outside the group") + if not set(route.relays) <= members or not set(route.owned_cables) <= owned: + problems.append(f"{plan.group.label}: the route from {spark.name} to {route.destination} " + f"crosses {route.cables}, outside the group's cables {sorted(owned)}") + for relay_filter in spark.filters: + for netdev in (relay_filter.in_netdev, relay_filter.out_netdev): + port = role_of_netdev(netdev).port + if fabric.cable_at(spark.position, port) is None: + problems.append(f"{plan.group.label}: {spark.name} relays through {netdev} (port {port}), " + "whose cable the group does not own") + if relay_filter.next_position not in members: + problems.append(f"{plan.group.label}: {spark.name} relays toward Spark " + f"{relay_filter.next_position}, outside the group") + for first in range(len(plans)): + for second in range(first + 1, len(plans)): + a, b = plans[first], plans[second] + shared = set(a.group.members) & set(b.group.members) + if shared: + problems.append(f"{a.group.label} and {b.group.label} share Sparks {sorted(shared)}") + used_a = {cable for spark in a.sparks for route in spark.routes for cable in route.owned_cables} + used_b = {cable for spark in b.sparks for route in spark.routes for cable in route.owned_cables} + for cable in sorted((set(a.group.cables) | used_a) & (set(b.group.cables) | used_b)): + problems.append(f"{a.group.label} and {b.group.label} both use cable {cable}") + problems += routes.isolation_problems([plan.sircl for plan in plans]) + return problems + + +def layout_isolation_problems(layout: FabricLayout) -> list[str]: + """SIRCL's lane isolation check (``routes.isolation_problems``) over every group of a layout.""" + return routes.isolation_problems([routes.derive_routes(group.layout(), 2) for group in layout.groups]) + + +# -- rendering ---------------------------------------------------------------------------------------- + + +def render_text(plan: LayoutPlan, facts: Facts, *, details: bool = True) -> str: + layout = plan.layout + lines = [f"layout {layout.name} on a ring of {layout.ring_size}: {len(plan.groups)} group(s) planned of " + f"{len(layout.groups)}, relay egress {layout.relay_egress}" + + (" (symbolic facts: placeholders stand for addresses and MACs)" if plan.symbolic else "")] + for note in CONSTRAINTS: + lines.append(f" constraint: {note}") + for group in plan.groups: + counts = (sum(len(s.routes) for s in group.sparks), sum(len(s.filters) for s in group.sparks), + sum(len(s.markers) for s in group.sparks)) + lines.append(f"group {group.group.label}: Sparks {list(group.group.members)}, cables " + f"{list(group.group.cables) or 'none'}; {counts[0]} routes, {counts[1]} relay filters, " + f"{counts[2]} markers; plan {group.digest}") + if group.per_peer_bytes is None: + lines.append(" relay queues: none (no lane crosses a relay)") + else: + lines.append(f" relay queues: busiest {group.busiest_queue} SIRCL lanes, load factor " + f"{group.load_factor:g}; keep per-peer op sizes at or below {group.per_peer_bytes} bytes " + f"({RELAY_QUEUE_SHARE:.0%} of {HAIRPIN_QUEUE_BYTES >> 10} KiB / {group.load_factor:g})") + for rank in range(group.sircl.world): + lines.append(f" rank {rank} (position {group.layout.positions[rank]}): " + f"SIRCL_PEER_ROUTES={group.sircl.route_text(rank)}") + if not details: + continue + for queue in group.queues: + lines.append(f" queue {facts.name(queue.position)} {queue.in_netdev} -> {queue.out_netdev}: " + f"{len(queue.lanes)} SIRCL lanes") + for spark in group.sparks: + lines.append(f" {spark.name} (position {spark.position}): {len(spark.routes)} routes, " + f"{len(spark.filters)} relay filters, {len(spark.markers)} markers") + for route in spark.routes: + carried = f"; {', '.join(route.lanes)}" if route.lanes else "; not a SIRCL lane" + lines.append(f" route {route.destination}/32 dev {route.netdev} src {route.source} neighbour " + f"{route.next_mac} -> {facts.name(route.peer)} {route.peer_netdev}, {route.hops} hops " + f"through {list(route.relays)}, tag 0x{route.tag:04x}{carried}") + for rules in spark.markers: + lines.append(f" marker {rules.device}: " + + " ".join(f"{destination}=0x{value:04x}" for destination, value in rules.rules)) + for relay_filter in spark.filters: + lines.append(f" filter {relay_filter.in_netdev} pref {relay_filter.pref} " + f"0x{relay_filter.protocol:04x} -> 0x{relay_filter.new_type:04x}, dst {relay_filter.next_mac} " + f"({facts.name(relay_filter.next_position)} {relay_filter.next_netdev}), out " + f"{relay_filter.out_netdev} ({relay_filter.direction}, {relay_filter.lane_class} lanes)") + return "\n".join(lines) diff --git a/sparkring_fabric/sparkring_fabric/fabric/report.py b/sparkring_fabric/sparkring_fabric/fabric/report.py new file mode 100644 index 00000000..58679831 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/report.py @@ -0,0 +1,194 @@ +"""Text reports of the installer: installed state per Spark, and comparisons with a plan. + +``show`` labels every relay object with its owner: the group named in the +Spark's record for objects that carry the installer's marks (protocol 82, +reserved filter preferences, marker processes), ``no record`` when they carry +the marks but the Spark has no record, and ``unowned`` for relay routes and +neighbours without protocol 82. Addresses and MACs are resolved to the Spark +and network device that hold them. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +from .commands import MarkerConfig +from .diff import SparkDiff +from .ops import Outcome +from .plan import FABRIC_NETDEVS, relays_left, role_of_netdev +from .state import HostState + + +def _lookups(states: Mapping[int, HostState]) -> tuple[dict[str, str], dict[str, str]]: + addresses, macs = {}, {} + for state in states.values(): + for name, link in state.links.items(): + if name not in FABRIC_NETDEVS: + continue + if link.mac: + macs[link.mac] = f"{state.name} {name}" + for address, _ in link.addresses: + addresses[address] = f"{state.name} {name}" + return addresses, macs + + +def render_show(states: Mapping[int, HostState], marker: MarkerConfig) -> str: + addresses, macs = _lookups(states) + lines = [] + for position, state in sorted(states.items()): + if not state.reachable: + lines.append(f"{state.name} (position {position}, {state.ssh}): unreachable: {state.error}") + continue + record = state.record + if record: + owner = f"group {record.get('group')}" + heading = (f"group {record.get('group')} (layout {record.get('layout')}, relay egress " + f"{record.get('relay_egress')}, plan {record.get('plan')})") + else: + owner = "no record" + heading = "no group record" + lines.append(f"{state.name} (position {position}, {state.ssh}): {heading}") + if state.hostname != state.name: + lines.append(f" host name: {state.hostname or 'unknown'} (the site lists {state.name})") + for problem in ([state.record_problem] if state.record_problem else []) + state.parse_problems: + lines.append(f" problem: {problem}") + ports = [] + for netdev in FABRIC_NETDEVS: + link = state.links.get(netdev) + if link is None: + ports.append(f"{netdev} missing") + else: + text = ",".join(f"{a}/{p}" for a, p in link.addresses) or "no IPv4" + ports.append(f"{netdev} {text} {link.mac} {link.operstate}") + lines.append(" fabric: " + "; ".join(ports)) + binary = f"sha256 {state.marker_binary[:16]}" if state.marker_binary else "missing" + lines.append(f" marker executable {marker.path}: {binary}") + tags = {} + for process in state.markers: + for destination, value in process.rules: + tags[(process.device, destination)] = value + relay_routes = state.relay_routes() + neighbours = {(n.destination, n.dev): n for n in state.relay_neighbours()} + lines.append(f" routes: {len(relay_routes)} relay routes " + f"({sum(1 for r in relay_routes if not r.owned)} unowned)") + for route in sorted(relay_routes, key=lambda r: (FABRIC_NETDEVS.index(r.dev) if r.dev in FABRIC_NETDEVS + else 9, r.destination)): + neighbour = neighbours.pop((route.destination, route.dev), None) + device = role_of_netdev(route.dev).device if route.dev in FABRIC_NETDEVS else None + value = tags.get((device, route.destination)) + tag_text = f"tag 0x{value:04x}" if value is not None else "no tag" + if neighbour is None: + next_text = "no permanent neighbour" + else: + next_text = (f"neighbour {neighbour.mac} ({macs.get(neighbour.mac, 'unknown')})" + + ("" if neighbour.owned == route.owned else + f" [{owner if neighbour.owned else 'unowned'}]")) + label = owner if route.owned else "unowned" + lines.append(f" {route.destination}/32 dev {route.dev} src {route.source} proto {route.protocol_text}" + f" -> {addresses.get(route.destination, 'unknown')}; {next_text}; {tag_text} [{label}]") + for (destination, dev), neighbour in sorted(neighbours.items()): + label = owner if neighbour.owned else "unowned" + lines.append(f" neighbour without route: {neighbour.text()} [{label}]") + lines.append(f" markers: {len(state.markers)}") + for process in sorted(state.markers, key=lambda p: (p.device or "", p.pid)): + log = state.marker_logs.get(process.device or "") or {} + installed = (f"installed {log.get('installed')}/{len(log.get('rules', []))}" if "installed" in log + else "no log") + lines.append(f" {process.text()}; {installed} [{owner}]") + filters = [entry for netdev in FABRIC_NETDEVS for entry in state.reserved_filters(netdev)] + lines.append(f" relay filters: {len(filters)}") + for entry in filters: + k = relays_left(entry.protocol) if entry.protocol is not None else None + k_text = f"k={k}" if k else "not a relay tag" + target = macs.get(entry.dst_mac or "", "unknown") if entry.dst_mac else "unknown" + lines.append(f" {entry.text()} ({k_text}; next {target}) [{owner}]") + qdiscs = [f"{netdev} {kind}" for netdev, kind in state.ingress_qdisc.items() if kind] + lines.append(f" ingress qdiscs: {', '.join(qdiscs) or 'none'}" + + (f" (added by the installer: {', '.join(record.get('qdiscs', []))})" + if record and record.get("qdiscs") else "")) + for entry in state.foreign_tag_filters(): + lines.append(f" note: filter outside the reserved preferences matches a relay tag: {entry.text()}") + return "\n".join(lines) + + +def _spark_lines(diff: SparkDiff, *, verbose: bool, scripts: bool) -> list[str]: + counts = {action: diff.count(action) for action in ("add", "remove", "replace", "mark", "keep", "write")} + pending = [f"{counts[action]} {action}" for action in ("add", "remove", "replace", "mark") if counts[action]] + if counts["write"]: + pending.append("record write") + lines = [f" {diff.name} (position {diff.position}): {', '.join(pending) or 'no changes'}; " + f"{counts['keep']} unchanged"] + for change in diff.changes: + # Unchanged objects and in-place ownership marks are counted above; --verbose lists them. + if change.action not in ("keep", "mark") or verbose: + lines.append(f" {change.text()}") + for blocker in diff.blockers: + lines.append(f" BLOCKER: {blocker}") + if diff.needs_adopt: + lines.append(f" NEEDS --adopt: {diff.needs_adopt}") + for note in diff.notes: + lines.append(f" note: {note}") + if scripts and diff.script: + lines.append(" script:") + lines.extend(f" {line}" for line in diff.commands) + return lines + + +def render_outcome(outcome: Outcome, *, verbose: bool = False, scripts: bool = False) -> str: + layout = outcome.layout + selected = ", ".join(group.label for group in outcome.groups) + lines = [f"layout {layout.name} ({len(layout.groups)} group(s), relay egress {layout.relay_egress}); " + f"{outcome.mode} for {selected}"] + for problem in outcome.problems: + lines.append(f"PROBLEM: {problem}") + for group in outcome.groups: + group_plan = outcome.plans.get(group.label) + if group_plan is not None: + bound = (f"per-peer op sizes at or below {group_plan.per_peer_bytes} bytes (busiest relay queue " + f"{group_plan.busiest_queue} SIRCL lanes, load factor {group_plan.load_factor:g})" + if group_plan.per_peer_bytes else "no relayed lanes") + lines.append(f"group {group.label}: plan {group_plan.digest}; {bound}") + else: + lines.append(f"group {group.label}") + for diff in outcome.diffs: + if diff.group == group.label: + lines.extend(_spark_lines(diff, verbose=verbose, scripts=scripts)) + return "\n".join(lines) + + +def summary_line(outcome: Outcome) -> str: + diffs = outcome.diffs + host = [change for d in diffs for change in d.host_changes] + marks = sum(d.count("mark") for d in diffs) + records = sum(1 for d in diffs for change in d.changes if change.kind == "record") + sparks = len({d.position for d in diffs if d.host_changes}) + blockers = sum(len(d.blockers) for d in diffs) + len(outcome.problems) + adopt = sum(1 for d in diffs if d.needs_adopt) + if host: + counts = {action: sum(1 for change in host if change.action == action) + for action in ("add", "remove", "replace")} + text = (f"{len(host)} host change(s) on {sparks} Spark(s): {counts['add']} to add, {counts['remove']} to " + f"remove, {counts['replace']} to replace") + else: + text = f"no host changes on {len(diffs)} Spark(s)" + if marks: + text += f"; {marks} unowned object(s) equal to the plan to mark in place (--adopt)" + if records: + text += f"; {records} record change(s)" + if adopt: + text += f"; --apply needs --adopt on {adopt} Spark(s)" + if blockers: + text += f"; {blockers} blocker(s)" + return f"{outcome.layout.name} {outcome.mode}: {text}" + + +def render_marker_status(states: Mapping[int, HostState], marker: MarkerConfig) -> str: + lines = [] + for position, state in sorted(states.items()): + if not state.reachable: + lines.append(f"{state.name}: unreachable: {state.error}") + continue + status = f"sha256 {state.marker_binary}" if state.marker_binary else "missing" + running = ", ".join(f"{p.device} pid {p.pid}" for p in state.markers) or "no marker running" + lines.append(f"{state.name}: {marker.path} {status}; {running}") + return "\n".join(lines) diff --git a/sparkring_fabric/sparkring_fabric/fabric/state.py b/sparkring_fabric/sparkring_fabric/fabric/state.py new file mode 100644 index 00000000..7c938e36 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/fabric/state.py @@ -0,0 +1,614 @@ +"""What a Spark holds: the parsed output of the installer's read script. + +The read script (:func:`.commands.read_script`) prints ``@@
`` blocks: +the host name, the iproute2 versions, ``ip -j addr show``, the network device +of each RDMA device, ``ip -j -d route show table main``, +``ip -j neigh show nud permanent``, ``tc -j qdisc show`` and +``tc -j filter show ... ingress`` of the four fabric network devices, the +marker processes (``pgrep -a -x``), the marker executable's SHA-256, the head +of every marker log and the installer's record. :func:`parse` turns them into +a :class:`HostState`. + +Classification of what the host holds: + +- an *owned* route or neighbour carries routing protocol 82; +- a *relay* route is a /32 route, scope link, without gateway, over a fabric + network device to an address outside that device's own subnet, and a relay + neighbour is a permanent neighbour entry on a fabric device for such an + address. Relay objects without the mark are *unowned*: some other tooling + installed them. ``--adopt`` lets ``up`` and ``down`` take them over; +- relay filters are the filters at the reserved preferences 11 to 17 of chain + 0 on the ingress of a fabric device; marker processes are the processes + named after the marker executable. Both are the installer's by their + reserved identifiers. + +The parsers accept the JSON spellings of iproute2 releases 5.x and 6.x: a +filter protocol as a name, ``[decimal]`` or hexadecimal; a handle as a number +or ``0x`` string; pedit keys under either mask convention. +""" + +from __future__ import annotations + +import dataclasses +import ipaddress +import json +from collections.abc import Mapping + +from . import commands +from .layouts import FabricError +from .plan import (ETH_P_IP, FABRIC_NETDEVS, RDMA_DEVICES, RESERVED_PREFS, Port, RelayFilter, port_from_text, + relays_left) + +_PROTOCOL_NAMES = { + "unspec": 0, "redirect": 1, "kernel": 2, "boot": 3, "static": 4, "gated": 8, "ra": 9, "mrt": 10, "zebra": 11, + "bird": 12, "dnrouted": 13, "xorp": 14, "ntk": 15, "dhcp": 16, "mrouted": 17, "keepalived": 18, "babel": 42, + "openr": 99, "bgp": 186, "isis": 187, "ospf": 188, "rip": 189, "eigrp": 192, +} +_ETHERTYPE_NAMES = {"ip": 0x0800, "ipv4": 0x0800, "arp": 0x0806, "rarp": 0x8035, "ipv6": 0x86DD, "802.1q": 0x8100, + "802.1ad": 0x88A8, "all": 0x0003, "lldp": 0x88CC, "mpls_uc": 0x8847, "mpls_mc": 0x8848} + + +def _int(value: object) -> int | None: + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, str): + try: + return int(value.strip(), 0) + except ValueError: + return None + return None + + +def _hex(value: object) -> int | None: + if isinstance(value, int) and not isinstance(value, bool): + return value + if isinstance(value, str): + try: + return int(value.strip(), 16) + except ValueError: + return None + return None + + +def protocol_number(text: object) -> int | None: + """A routing protocol from iproute2's name or number; None for a name this table does not know.""" + if isinstance(text, int): + return text + if text is None: + return None + word = str(text).strip().lower() + if word.isdigit(): + return int(word) + return _PROTOCOL_NAMES.get(word) + + +def ethertype(text: object) -> int | None: + """A filter protocol as tc prints it: a name, ``[34997]``, ``0x88b5`` or a number.""" + if isinstance(text, int) and not isinstance(text, bool): + return text + if not isinstance(text, str): + return None + word = text.strip().lower() + if word.startswith("[") and word.endswith("]") and word[1:-1].isdigit(): + return int(word[1:-1]) + if word.startswith("0x"): + return _hex(word) + if word in _ETHERTYPE_NAMES: + return _ETHERTYPE_NAMES[word] + if word.isdigit(): + return int(word) + return None + + +def _key_ethertype(text: object) -> int | None: + """Flower's ``eth_type`` key: ``ipv4``, ``88b5`` (hexadecimal) and so on.""" + if isinstance(text, str) and len(text.strip()) == 4: + return _hex(text) + return ethertype(text) + + +# -- entries --------------------------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class Link: + name: str + mac: str + addresses: tuple[tuple[str, int], ...] # IPv4 (address, prefix length) + operstate: str + + def networks(self) -> tuple[ipaddress.IPv4Network, ...]: + return tuple(ipaddress.IPv4Interface(f"{address}/{length}").network for address, length in self.addresses) + + +@dataclasses.dataclass(frozen=True) +class RouteEntry: + destination: str + prefixlen: int + dev: str + source: str | None + scope: str + protocol: int | None + protocol_text: str + metric: int + gateway: str | None + kind: str + + @property + def owned(self) -> bool: + return self.protocol == commands.ROUTE_PROTOCOL + + def text(self) -> str: + parts = [f"{self.destination}/{self.prefixlen}"] + if self.gateway: + parts.append(f"via {self.gateway}") + parts.append(f"dev {self.dev}") + if self.source: + parts.append(f"src {self.source}") + parts.append(f"scope {self.scope} proto {self.protocol_text}") + if self.metric: + parts.append(f"metric {self.metric}") + return " ".join(parts) + + +@dataclasses.dataclass(frozen=True) +class NeighbourEntry: + destination: str + dev: str + mac: str + states: tuple[str, ...] + protocol: int | None + protocol_text: str + + @property + def owned(self) -> bool: + return self.protocol == commands.ROUTE_PROTOCOL + + @property + def permanent(self) -> bool: + return "PERMANENT" in self.states + + def text(self) -> str: + return (f"{self.destination} dev {self.dev} lladdr {self.mac or 'none'} {'/'.join(self.states)}" + + (f" proto {self.protocol_text}" if self.protocol_text else "")) + + +@dataclasses.dataclass(frozen=True) +class FilterEntry: + netdev: str + pref: int + chain: int + kind: str + protocol: int | None + handle: int | None + skip_sw: bool + in_hw: bool + dst_mac: str | None + new_type: int | None + out_dev: str | None + problem: str | None # why the actions are not a relay filter's + + @property + def reserved(self) -> bool: + return self.chain == 0 and self.pref in RESERVED_PREFS + + def matches(self, planned: RelayFilter) -> bool: + return (self.problem is None and self.kind == "flower" and self.chain == 0 and self.pref == planned.pref + and self.protocol == planned.protocol and self.handle == planned.handle and self.skip_sw + and self.dst_mac == planned.next_mac.lower() and self.new_type == planned.new_type + and self.out_dev == planned.out_netdev) + + def text(self) -> str: + protocol = f"0x{self.protocol:04x}" if self.protocol is not None else "unknown" + if self.problem: + body = f"not a relay filter ({self.problem})" + else: + new_type = f"0x{self.new_type:04x}" if self.new_type is not None else "?" + body = f"-> {new_type}, dst {self.dst_mac}, out {self.out_dev}" + flags = " ".join(flag for flag, on in (("skip_sw", self.skip_sw), ("in_hw", self.in_hw)) if on) + return f"{self.netdev} pref {self.pref} handle {self.handle} {protocol} {body} {flags}".rstrip() + + +@dataclasses.dataclass(frozen=True) +class MarkerProcess: + pid: int + argv: tuple[str, ...] + device: str | None + rules: frozenset[tuple[str, int]] + managed: bool + problem: str | None + + def text(self) -> str: + rules = " ".join(f"{d}=0x{v:04x}" for d, v in sorted(self.rules)) + return f"pid {self.pid} {self.device or '?'}: {rules}" + ("" if self.managed else " (not --managed)") + + +# -- decoders ---------------------------------------------------------------------------------------- + + +def _json_list(text: str, what: str, problems: list[str]) -> list: + text = text.strip() + if not text: + return [] + try: + value = json.loads(text) + except json.JSONDecodeError as error: + problems.append(f"{what}: not JSON ({error.msg})") + return [] + if not isinstance(value, list): + problems.append(f"{what}: not a JSON list") + return [] + return [entry for entry in value if isinstance(entry, dict)] + + +def parse_links(text: str, problems: list[str]) -> dict[str, Link]: + links = {} + for entry in _json_list(text, "ip -j addr show", problems): + name = str(entry.get("ifname", "")) + addresses = tuple((str(info.get("local")), int(info.get("prefixlen", 32))) + for info in entry.get("addr_info", []) if isinstance(info, dict) + and info.get("family") == "inet" and info.get("local")) + links[name] = Link(name, str(entry.get("address", "")).lower(), addresses, str(entry.get("operstate", ""))) + return links + + +def parse_routes(text: str, problems: list[str]) -> list[RouteEntry]: + found = [] + for entry in _json_list(text, "ip -j -d route show", problems): + destination = str(entry.get("dst", "")) + if destination == "default": + address, length = "0.0.0.0", 0 + elif "/" in destination: + address, _, length_text = destination.partition("/") + length = int(length_text) if length_text.isdigit() else -1 + else: + address, length = destination, 32 + try: + ipaddress.IPv4Address(address) + except ValueError: + continue + protocol_text = str(entry.get("protocol", "boot")) + found.append(RouteEntry(address, length, str(entry.get("dev", "")), entry.get("prefsrc"), + str(entry.get("scope", "global")), protocol_number(protocol_text), protocol_text, + _int(entry.get("metric")) or 0, entry.get("gateway"), + str(entry.get("type", "unicast")))) + return found + + +def parse_neighbours(text: str, problems: list[str]) -> list[NeighbourEntry]: + found = [] + for entry in _json_list(text, "ip -j neigh show", problems): + states = entry.get("state", []) + states = tuple(states) if isinstance(states, list) else (str(states),) + protocol_text = str(entry.get("protocol", "")) if entry.get("protocol") is not None else "" + found.append(NeighbourEntry(str(entry.get("dst", "")), str(entry.get("dev", "")), + str(entry.get("lladdr", "")).lower(), states, + protocol_number(protocol_text) if protocol_text else None, protocol_text)) + return found + + +def parse_ingress_qdisc(text: str, problems: list[str], netdev: str) -> str | None: + for entry in _json_list(text, f"tc -j qdisc show dev {netdev}", problems): + if entry.get("kind") in ("ingress", "clsact"): + return str(entry["kind"]) + return None + + +def _header_bytes(keys: list, keep_mask: bool) -> dict[int, int] | None: + header: dict[int, int] = {} + for key in keys: + offset, value, mask = _int(key.get("offset")), _hex(key.get("val")), _hex(key.get("mask")) + if offset is None or value is None or mask is None or offset % 4 or offset < 0: + return None + for index in range(4): + shift = 24 - 8 * index + byte_mask = (mask >> shift) & 0xFF + written = byte_mask == 0 if keep_mask else byte_mask == 0xFF + if written: + header[offset + index] = (value >> shift) & 0xFF + elif byte_mask not in (0, 0xFF): + return None + return header + + +def decode_filter(netdev: str, entry: Mapping[str, object]) -> FilterEntry | None: + """One ``tc -j filter show`` entry; None for the per-preference summary entry without options.""" + options = entry.get("options") + if not isinstance(options, dict): + return None + pref = _int(entry.get("pref")) + chain = _int(entry.get("chain")) or 0 + kind = str(entry.get("kind", "")) + keys = options.get("keys") if isinstance(options.get("keys"), dict) else {} + protocol = ethertype(entry.get("protocol")) + if protocol is None: + protocol = _key_ethertype(keys.get("eth_type")) + actions = [action for action in options.get("actions", []) or [] if isinstance(action, dict)] + problem = None + pedit_keys = [] + for action in actions: + if action.get("kind") == "pedit": + for key in action.get("keys", []) or []: + if not isinstance(key, dict) or key.get("htype", "eth") != "eth" or key.get("cmd", "set") != "set": + problem = "a pedit key is not an Ethernet header set" + pedit_keys.append(key) + mirreds = [action for action in actions if action.get("kind") == "mirred"] + others = [action.get("kind") for action in actions if action.get("kind") not in ("pedit", "mirred")] + header = None + for keep_mask in (True, False): + candidate = _header_bytes(pedit_keys, keep_mask) if problem is None else None + if candidate is not None and set(candidate) == {0, 1, 2, 3, 4, 5, 12, 13}: + header = candidate + break + if problem is None and header is None: + problem = "the pedit actions do not set exactly the destination MAC and the EtherType" + if problem is None and others: + problem = f"other actions {others}" + out_dev = None + if problem is None: + if (len(mirreds) == 1 and actions[-1] is mirreds[0] and mirreds[0].get("mirred_action") == "redirect" + and mirreds[0].get("direction") == "egress"): + out_dev = str(mirreds[0].get("to_dev", "")) + else: + problem = "the last action is not one egress redirect" + dst_mac = ":".join(f"{header[index]:02x}" for index in range(6)) if header else None + new_type = (header[12] << 8) | header[13] if header else None + return FilterEntry(netdev, pref if pref is not None else -1, chain, kind, protocol, _int(options.get("handle")), + bool(options.get("skip_sw")), bool(options.get("in_hw")), dst_mac, new_type, out_dev, + problem) + + +def parse_filters(text: str, problems: list[str], netdev: str) -> list[FilterEntry]: + found = [] + for entry in _json_list(text, f"tc -j filter show dev {netdev} ingress", problems): + decoded = decode_filter(netdev, entry) + if decoded is not None: + found.append(decoded) + return found + + +def parse_markers(text: str) -> list[MarkerProcess]: + found = [] + for line in text.splitlines(): + words = line.split() + if len(words) < 2 or not words[0].isdigit(): + continue + argv = tuple(words[1:]) + device, rules, problem = None, set(), None + index = 1 + while index < len(argv): + word = argv[index] + if word == "--device" and index + 1 < len(argv): + device = argv[index + 1] + index += 2 + continue + if word == "--rule" and index + 1 < len(argv): + destination, _, value = argv[index + 1].partition("=") + number = _int(value) + if number is None: + problem = f"rule {argv[index + 1]!r} is not ADDRESS=ETHERTYPE" + else: + rules.add((destination, number)) + index += 2 + continue + index += 1 + found.append(MarkerProcess(int(words[0]), argv, device, frozenset(rules), "--managed" in argv, problem)) + return found + + +# -- host state --------------------------------------------------------------------------------------- + + +@dataclasses.dataclass +class HostState: + """Everything the read script found on one Spark.""" + + position: int + name: str + ssh: str + reachable: bool + error: str = "" + hostname: str = "" + versions: str = "" + links: dict[str, Link] = dataclasses.field(default_factory=dict) + rdma: dict[str, str] = dataclasses.field(default_factory=dict) + routes: list[RouteEntry] = dataclasses.field(default_factory=list) + neighbours: list[NeighbourEntry] = dataclasses.field(default_factory=list) + ingress_qdisc: dict[str, str | None] = dataclasses.field(default_factory=dict) + filters: dict[str, list[FilterEntry]] = dataclasses.field(default_factory=dict) + markers: list[MarkerProcess] = dataclasses.field(default_factory=list) + marker_binary: str | None = None + marker_uid: int | None = None + marker_gid: int | None = None + marker_mode: int | None = None + marker_expected_sha256: str | None = None + marker_logs: dict[str, dict | None] = dataclasses.field(default_factory=dict) + record: dict | None = None + record_problem: str | None = None + raw: dict[str, str] = dataclasses.field(default_factory=dict) + parse_problems: list[str] = dataclasses.field(default_factory=list) + + # -- facts -- + + def port(self, netdev: str) -> Port | None: + link = self.links.get(netdev) + if link is None or len(link.addresses) != 1 or not link.mac: + return None + address, length = link.addresses[0] + try: + return port_from_text(netdev, link.mac, f"{address}/{length}", owner=self.name) + except FabricError: + return None + + def ports(self) -> tuple[Port, ...]: + return tuple(port for port in (self.port(netdev) for netdev in FABRIC_NETDEVS) if port is not None) + + def fact_problems(self, *, check_hostname: bool = True) -> list[str]: + if not self.reachable: + return [f"{self.name}: unreachable ({self.error})"] + problems = [f"{self.name}: {problem}" for problem in self.parse_problems] + if check_hostname and self.hostname != self.name: + problems.append(f"{self.name}: the host at {self.ssh} is named {self.hostname or 'nothing'}, the site " + "lists it as " + self.name) + for device, netdev in zip(RDMA_DEVICES, FABRIC_NETDEVS): + if self.rdma.get(device) != netdev: + problems.append(f"{self.name}: RDMA device {device} belongs to network device " + f"{self.rdma.get(device) or 'none'}, expected {netdev}") + for netdev in FABRIC_NETDEVS: + link = self.links.get(netdev) + if link is None: + problems.append(f"{self.name}: network device {netdev} is missing") + elif len(link.addresses) != 1: + problems.append(f"{self.name}: {netdev} has {len(link.addresses)} IPv4 addresses; one is needed") + elif self.port(netdev) is None: + problems.append(f"{self.name}: {netdev} has no usable MAC or IPv4 address") + return problems + + # -- classification -- + + def on_link(self, netdev: str, address: str) -> bool: + link = self.links.get(netdev) + if link is None: + return False + try: + value = ipaddress.IPv4Address(address) + except ValueError: + return False + return any(value in network for network in link.networks()) + + def is_relay_route(self, route: RouteEntry) -> bool: + return (route.prefixlen == 32 and route.dev in FABRIC_NETDEVS and route.scope == "link" + and not route.gateway and route.kind == "unicast" and not self.on_link(route.dev, route.destination)) + + def relay_routes(self) -> list[RouteEntry]: + """Owned routes and unowned relay routes.""" + return [route for route in self.routes if route.owned or self.is_relay_route(route)] + + def is_relay_neighbour(self, neighbour: NeighbourEntry) -> bool: + return (neighbour.permanent and neighbour.dev in FABRIC_NETDEVS + and (neighbour.owned or not self.on_link(neighbour.dev, neighbour.destination))) + + def relay_neighbours(self) -> list[NeighbourEntry]: + return [neighbour for neighbour in self.neighbours if neighbour.owned or self.is_relay_neighbour(neighbour)] + + def reserved_filters(self, netdev: str) -> list[FilterEntry]: + return [entry for entry in self.filters.get(netdev, []) if entry.reserved] + + def foreign_tag_filters(self) -> list[FilterEntry]: + """Filters outside the reserved preferences that match a relay tag (they could take relayed frames).""" + return [entry for netdev in FABRIC_NETDEVS for entry in self.filters.get(netdev, []) + if not entry.reserved and entry.protocol is not None and entry.protocol != ETH_P_IP + and relays_left(entry.protocol)] + + def unowned_relay_objects(self) -> tuple[list[RouteEntry], list[NeighbourEntry]]: + return ([route for route in self.relay_routes() if not route.owned], + [neighbour for neighbour in self.relay_neighbours() if not neighbour.owned]) + + def marker_problems(self, path: str, *, expected_sha256: str | None = None) -> list[str]: + """Integrity problems that stop running ``path`` as root (empty when safe).""" + if self.marker_binary is None: + return [f"the marker executable {path} is missing; build it with the `marker` command"] + problems: list[str] = [] + if self.marker_uid is None or self.marker_mode is None: + problems.append(f"the marker executable {path} ownership and permissions could not be verified; " + "reinstall it with the `marker --rebuild --apply` command") + else: + if self.marker_uid != 0: + problems.append(f"the marker executable {path} is owned by uid {self.marker_uid}, expected root " + "(uid 0); reinstall it with the `marker --rebuild --apply` command") + if self.marker_mode & 0o022: + problems.append(f"the marker executable {path} has group/world-writable mode {self.marker_mode:04o}; " + "reinstall it with the `marker --rebuild --apply` command") + expected_sources: list[tuple[str, str]] = [] + if expected_sha256 is not None: + expected_sources.append(("configured", expected_sha256.lower())) + if self.marker_expected_sha256 is not None: + expected_sources.append(("recorded digest", self.marker_expected_sha256.lower())) + recorded = (self.record or {}).get("marker_sha256") + if isinstance(recorded, str) and len(recorded) == 64: + expected_sources.append(("state record", recorded.lower())) + actual = self.marker_binary.lower() + for label, expected in expected_sources: + if actual != expected: + problems.append(f"the marker executable {path} sha256 {actual} does not match {label} {expected}; " + "reinstall it with the `marker --rebuild --apply` command") + return problems + + +def parse_sections(stdout: str) -> dict[str, str]: + """``@@`` blocks of a script's output, by name.""" + sections: dict[str, list[str]] = {} + current = None + for line in stdout.splitlines(): + if line.startswith(commands.SECTION): + current = line[len(commands.SECTION):].strip() + sections[current] = [] + elif current is not None: + sections[current].append(line) + return {key: "\n".join(value) for key, value in sections.items()} + + +def parse(position: int, name: str, ssh: str, *, returncode: int, stdout: str, stderr: str) -> HostState: + """The :class:`HostState` of one Spark from its read script's output.""" + state = HostState(position, name, ssh, reachable=True) + sections = parse_sections(stdout) + if "end" not in sections: + state.reachable = bool(sections) + detail = (stderr.strip().splitlines() or [f"exit code {returncode}"])[-1] + state.error = detail if not sections else f"the read script stopped early ({detail})" + if not state.reachable: + return state + state.parse_problems.append(state.error) + state.raw = sections + raw = state.raw + problems = state.parse_problems + state.hostname = raw.get("hostname", "").strip() + state.versions = " | ".join(line.strip() for line in raw.get("versions", "").splitlines() if line.strip()) + state.links = parse_links(raw.get("links", ""), problems) + for device in RDMA_DEVICES: + netdevs = raw.get(f"rdma:{device}", "").split() + state.rdma[device] = netdevs[0] if netdevs else "" + state.routes = parse_routes(raw.get("routes", ""), problems) + state.neighbours = parse_neighbours(raw.get("neighbours", ""), problems) + for netdev in FABRIC_NETDEVS: + state.ingress_qdisc[netdev] = parse_ingress_qdisc(raw.get(f"qdisc:{netdev}", ""), problems, netdev) + state.filters[netdev] = parse_filters(raw.get(f"filters:{netdev}", ""), problems, netdev) + state.markers = parse_markers(raw.get("markers", "")) + binary = raw.get("marker-binary", "").split() + state.marker_binary = (binary[0].lower() + if binary and len(binary[0]) == 64 and all(c in "0123456789abcdef" for c in binary[0].lower()) + else None) + meta = raw.get("marker-stat", "").split() + if len(meta) >= 3 and meta[0].isdigit() and meta[1].isdigit(): + try: + state.marker_uid = int(meta[0]) + state.marker_gid = int(meta[1]) + state.marker_mode = int(meta[2], 8) + except ValueError: + pass + expected = raw.get("marker-sha256", "").split() + state.marker_expected_sha256 = ( + expected[0].lower() + if expected and len(expected[0]) == 64 and all(c in "0123456789abcdef" for c in expected[0].lower()) + else None + ) + for device in RDMA_DEVICES: + text = raw.get(f"marker-log:{device}", "").strip() + first = text.splitlines()[0] if text else "" + try: + state.marker_logs[device] = json.loads(first) if first.startswith("{") else ( + {"error": text[:300]} if text else None) + except json.JSONDecodeError: + state.marker_logs[device] = {"error": text[:300]} + record_text = raw.get("record", "").strip() + if record_text: + try: + record = json.loads(record_text) + if not isinstance(record, dict) or record.get("schema") != commands.RECORD_SCHEMA: + raise ValueError(f"schema is not {commands.RECORD_SCHEMA}") + state.record = record + except (ValueError, json.JSONDecodeError) as error: + state.record_problem = f"the record {commands.RECORD_PATH} is unreadable: {error}" + return state diff --git a/sparkring_fabric/sparkring_fabric/routes.py b/sparkring_fabric/sparkring_fabric/routes.py new file mode 100644 index 00000000..b3f0933d --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/routes.py @@ -0,0 +1,936 @@ +"""Fabric layouts and route maps of SIRCL ring sessions. + +Physical model. A DGX Spark has one ConnectX-7 with ports 0 and 1; each port +appears as a primary and a secondary PCIe function, each with its own RDMA +device. The repository names the four functions by role: + + cw_primary rocep1s0f0 port 0, primary + cw_secondary roceP2p1s0f0 port 0, secondary + ccw_primary rocep1s0f1 port 1, primary + ccw_secondary roceP2p1s0f1 port 1, secondary + +These are the names DGX OS gives the functions (:data:`DEFAULT_ROLES`). +When ``SIRCL_FABRIC_DOCUMENT`` names a fabric document (schema +``sparkring-fabric/v1``, written by SparkRing's setup), the devices and +network interfaces come from its port functions instead +(:func:`load_roles`); every Spark of the fabric must name them alike. + +A cable joins one port of one Spark to one port of another and carries two +links (the primary functions of its ends and the secondary functions). A +group's fabric is the set of cables it owns, written as +``".port

-.port"``; every Spark has two ports, so a +fabric is a path or a cycle. Ring cabling joins position ``i``'s port 0 to +position ``i+1``'s port 1. + +Route maps. A rank's route map names, for every other rank of its session, +the local RDMA devices of lanes ``0 .. L-1`` (``L`` is 1 or 2). Textual form +(``SIRCL_PEER_ROUTES``): ``=[/][,...]``. + +Derivation (:func:`derive_lanes`), for a lane set from position ``a`` to +position ``b``: take the shortest paths in the fabric (one, or two when the +two ends are opposite on an even cycle or joined by two cables). With one +path, lane 0 uses the primary and lane 1 the secondary function of the path's +first cable at ``a``. With two paths, path A is the one that leaves the end +with the smaller position through its port 0; lane 0 uses the primary function +on path A and lane 1 the secondary function on path B. A lane's remote device +is the function of the same class at the far end of its last cable. Subgroup +sessions use their parent group's fabric. + +Validation (:func:`validate_route_map`) checks one rank's map before setup; +:func:`check_complementary` checks every ordered pair of ranks against the +layout; :func:`relay_load` gives the relay queue load factor of a group. + +Status: implemented; checked against the reference route vectors of the +tests (``tests/data/routes.json``). +""" + +from __future__ import annotations + +import dataclasses +import json +import os +import re +from collections import deque +from pathlib import Path +from collections.abc import Iterable, Mapping, Sequence + +MAX_LANES = 2 +MAX_DEVICES = 4 +LINK_WINDOW_CHUNK = 32768 +DEFAULT_MAX_RELAYS = 3 + + +class RouteError(ValueError): + """A route map or layout breaks a route rule (the message names the rank, entry and rule).""" + + +@dataclasses.dataclass(frozen=True) +class Role: + """One PCIe function of a Spark's ConnectX-7.""" + + name: str + device: str + netdev: str + port: int + secondary: bool + + @property + def label(self) -> str: + """The hyphenated spelling of the role, e.g. ``cw-primary``.""" + return self.name.replace("_", "-") + + +# The four functions under the names DGX OS gives a DGX Spark's ConnectX-7. +DEFAULT_ROLES = ( + Role("cw_primary", "rocep1s0f0", "enp1s0f0np0", 0, False), + Role("cw_secondary", "roceP2p1s0f0", "enP2p1s0f0np0", 0, True), + Role("ccw_primary", "rocep1s0f1", "enp1s0f1np1", 1, False), + Role("ccw_secondary", "roceP2p1s0f1", "enP2p1s0f1np1", 1, True), +) +FABRIC_DOCUMENT_SCHEMA = "sparkring-fabric/v1" +FABRIC_DOCUMENT_VARIABLE = "SIRCL_FABRIC_DOCUMENT" + + +def roles_from_fabric_document(document: Mapping[str, object]) -> tuple[Role, ...]: + """The four function roles a ``sparkring-fabric/v1`` document names. + + Every entry of ``positions`` names, under ``ports..functions.`` + (port ``"0"`` or ``"1"``, function ``primary`` or ``secondary``), the RDMA + device (``rdma``) and the network interface (``netdev``). A route map names + devices, and a lane's remote device is the function of the same role on the + far Spark, so every position must name each role alike; a document whose + positions differ is refused, naming the position and the role. + """ + if not isinstance(document, Mapping) or document.get("schema") != FABRIC_DOCUMENT_SCHEMA: + raise RouteError(f"the fabric document's schema is not {FABRIC_DOCUMENT_SCHEMA}") + positions = document.get("positions") + if not isinstance(positions, Sequence) or isinstance(positions, str) or not positions: + raise RouteError("the fabric document lists no positions") + roles: tuple[Role, ...] | None = None + for entry in positions: + position = entry.get("position") if isinstance(entry, Mapping) else None + named = [] + for default in DEFAULT_ROLES: + function = "secondary" if default.secondary else "primary" + try: + names = entry["ports"][str(default.port)]["functions"][function] + device, netdev = names["rdma"], names["netdev"] + except (KeyError, TypeError, IndexError): + raise RouteError(f"position {position} of the fabric document does not name the RDMA " + f"device and network interface of port {default.port} {function}") from None + if not (isinstance(device, str) and device and isinstance(netdev, str) and netdev): + raise RouteError(f"position {position} of the fabric document names an empty device or " + f"interface for port {default.port} {function}") + named.append(dataclasses.replace(default, device=device, netdev=netdev)) + if roles is None: + roles = tuple(named) + elif tuple(named) != roles: + differing = next(mine for mine, first in zip(named, roles) if mine != first) + raise RouteError(f"position {position} of the fabric document names port {differing.port} " + f"{'secondary' if differing.secondary else 'primary'} differently from the " + "first position; SIRCL needs every Spark of a fabric to name its functions " + "alike") + assert roles is not None + if len({role.device for role in roles}) != len(roles) or len({role.netdev for role in roles}) != len(roles): + raise RouteError("the fabric document names one device or interface for two functions") + return roles + + +def load_roles(environ: Mapping[str, str] | None = None) -> tuple[Role, ...]: + """The roles of the document ``SIRCL_FABRIC_DOCUMENT`` names, else :data:`DEFAULT_ROLES`.""" + environ = os.environ if environ is None else environ + path = (environ.get(FABRIC_DOCUMENT_VARIABLE) or "").strip() + if not path: + return DEFAULT_ROLES + try: + document = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, ValueError) as error: + raise RouteError(f"{FABRIC_DOCUMENT_VARIABLE}={path}: {error}") from None + return roles_from_fabric_document(document) + + +# The roles every derivation and check in this process uses, read once at import. +ROLES = load_roles() +_BY_DEVICE = {role.device: role for role in ROLES} +_BY_NAME = {role.name: role for role in ROLES} + + +def role_at(port: int, secondary: bool) -> Role: + for role in ROLES: + if role.port == port and role.secondary == secondary: + return role + raise RouteError(f"no function on port {port}") + + +def role_of(device: str, roles: Mapping[str, Role] | None = None) -> Role | None: + """The role of an RDMA device name (canonical names unless ``roles`` maps others).""" + if roles is not None and device in roles: + return roles[device] + return _BY_DEVICE.get(device) + + +# -- fabric -------------------------------------------------------------------- + +_CABLE = re.compile(r"^\s*(\d+)\.port([01])\s*-\s*(\d+)\.port([01])\s*$") + + +@dataclasses.dataclass(frozen=True) +class Cable: + a: int + a_port: int + b: int + b_port: int + + def __post_init__(self) -> None: + if self.a == self.b: + raise RouteError(f"cable {self.text} joins a Spark to itself") + + @property + def text(self) -> str: + return f"{self.a}.port{self.a_port}-{self.b}.port{self.b_port}" + + @classmethod + def parse(cls, text: str) -> "Cable": + match = _CABLE.match(text) + if match is None: + raise RouteError(f"cable {text!r} is not written .port<0|1>-.port<0|1>") + a, a_port, b, b_port = (int(group) for group in match.groups()) + return cls(a, a_port, b, b_port) + + def ends(self) -> tuple[tuple[int, int], tuple[int, int]]: + return (self.a, self.a_port), (self.b, self.b_port) + + +@dataclasses.dataclass(frozen=True) +class Step: + """One cable crossed from (``src``, ``src_port``) to (``dst``, ``dst_port``).""" + + cable: Cable + src: int + src_port: int + dst: int + dst_port: int + + @property + def text(self) -> str: + return f"{self.src}.port{self.src_port}-{self.dst}.port{self.dst_port}" + + +@dataclasses.dataclass(frozen=True) +class Fabric: + """The cables a group owns.""" + + cables: tuple[Cable, ...] + + def __post_init__(self) -> None: + seen: dict[tuple[int, int], Cable] = {} + for cable in self.cables: + for end in cable.ends(): + if end in seen: + raise RouteError(f"port {end[1]} of position {end[0]} has two cables") + seen[end] = cable + + @classmethod + def ring(cls, size: int) -> "Fabric": + """A ring of ``size`` Sparks: position ``i`` port 0 to position ``i+1`` port 1.""" + if size < 2: + raise RouteError("a ring needs at least two Sparks") + return cls(tuple(Cable(i, 0, (i + 1) % size, 1) for i in range(size))) + + @classmethod + def path(cls, positions: Sequence[int]) -> "Fabric": + """Consecutive Sparks of a ring, each cabled port 0 to the next one's port 1.""" + positions = tuple(positions) + if len(positions) < 2: + raise RouteError("a path needs at least two Sparks") + return cls(tuple(Cable(a, 0, b, 1) for a, b in zip(positions, positions[1:]))) + + @classmethod + def parse(cls, texts: Iterable[str]) -> "Fabric": + return cls(tuple(Cable.parse(text) for text in texts)) + + @property + def positions(self) -> tuple[int, ...]: + return tuple(sorted({end[0] for cable in self.cables for end in cable.ends()})) + + def connected(self) -> bool: + """Whether every position of the fabric is reachable from every other over its cables.""" + nodes = self.positions + if not nodes: + return False + adjacency: dict[int, list[int]] = {node: [] for node in nodes} + for cable in self.cables: + adjacency[cable.a].append(cable.b) + adjacency[cable.b].append(cable.a) + seen = {nodes[0]} + queue = deque([nodes[0]]) + while queue: + here = queue.popleft() + for nxt in adjacency[here]: + if nxt not in seen: + seen.add(nxt) + queue.append(nxt) + return len(seen) == len(nodes) + + @property + def kind(self) -> str: + """``cycle`` when every Spark has two cables closing one connected loop, + ``path`` for one connected open chain, else ``disconnected``.""" + degree: dict[int, int] = {} + for cable in self.cables: + for position, _ in cable.ends(): + degree[position] = degree.get(position, 0) + 1 + if not degree or not self.connected(): + return "disconnected" + if all(count == 2 for count in degree.values()) and len(self.cables) == len(degree): + return "cycle" + return "path" + + def cable_at(self, position: int, port: int) -> Cable | None: + for cable in self.cables: + if (position, port) in cable.ends(): + return cable + return None + + def cross(self, position: int, port: int) -> Step | None: + """Leave ``position`` through ``port``; None when that port has no cable in this fabric.""" + cable = self.cable_at(position, port) + if cable is None: + return None + if (cable.a, cable.a_port) == (position, port): + return Step(cable, position, port, cable.b, cable.b_port) + return Step(cable, position, port, cable.a, cable.a_port) + + def shortest_paths(self, a: int, b: int) -> tuple[tuple[Step, ...], ...]: + """Every shortest cable path from ``a`` to ``b``.""" + if a == b: + raise RouteError("a lane joins two different Sparks") + distance = {b: 0} + queue = deque([b]) + while queue: + here = queue.popleft() + for port in (0, 1): + step = self.cross(here, port) + if step is not None and step.dst not in distance: + distance[step.dst] = distance[here] + 1 + queue.append(step.dst) + if a not in distance: + return () + paths: list[tuple[Step, ...]] = [] + + def extend(here: int, steps: list[Step]) -> None: + if here == b: + paths.append(tuple(steps)) + return + for port in (0, 1): + step = self.cross(here, port) + if step is not None and distance.get(step.dst) == distance[here] - 1: + steps.append(step) + extend(step.dst, steps) + steps.pop() + + extend(a, []) + return tuple(paths) + + def walk(self, start: int, port: int, target: int, limit: int) -> tuple[Step, ...] | None: + """Follow the fabric from ``start`` out of ``port`` (relays leave through their other port). + + Returns the steps up to ``target``, or None when the walk leaves the + fabric or exceeds ``limit`` cables first. + """ + steps: list[Step] = [] + here, out = start, port + while len(steps) < limit: + step = self.cross(here, out) + if step is None: + return None + steps.append(step) + if step.dst == target: + return tuple(steps) + here, out = step.dst, 1 - step.dst_port + return None + + +@dataclasses.dataclass(frozen=True) +class Layout: + """A session's layout identity: its fabric and the fabric position of every rank.""" + + fabric: Fabric + positions: tuple[int, ...] + + def __post_init__(self) -> None: + if len(set(self.positions)) != len(self.positions): + raise RouteError("ranks need distinct fabric positions") + known = set(self.fabric.positions) + missing = [p for p in self.positions if p not in known] + if missing: + raise RouteError(f"positions {missing} are not on the fabric") + + @property + def world(self) -> int: + return len(self.positions) + + def identity(self) -> dict[str, object]: + return { + "kind": self.fabric.kind, + "size": len(self.fabric.positions), + "positions": list(self.positions), + "cables": [cable.text for cable in self.fabric.cables], + } + + @classmethod + def parse(cls, text: str) -> "Layout": + """``ring:[:]``, ``path:-[:]`` or + ``cables=,...;positions=

,...``.""" + text = text.strip() + try: + if text.startswith("cables="): + cables_part, _, positions_part = text.partition(";") + fabric = Fabric.parse(cables_part[len("cables="):].split(",")) + if not positions_part.startswith("positions="): + raise RouteError("an explicit layout names positions=

,...") + positions = tuple(int(p) for p in positions_part[len("positions="):].split(",")) + return cls(fabric, positions) + kind, _, rest = text.partition(":") + span, _, ranks = rest.partition(":") + if kind == "ring": + fabric = Fabric.ring(int(span)) + elif kind == "path": + first, _, last = span.partition("-") + fabric = Fabric.path(range(int(first), int(last) + 1)) + else: + raise RouteError(f"layout {text!r} is not ring:, path: or cables=") + positions = (tuple(int(p) for p in ranks.split(",")) if ranks + else fabric.positions) + return cls(fabric, positions) + except ValueError as error: + if isinstance(error, RouteError): + raise + raise RouteError(f"layout {text!r} is malformed: {error}") from None + + +# -- derivation ------------------------------------------------------------------- + + +@dataclasses.dataclass(frozen=True) +class LaneRoute: + """One lane from a rank toward a peer.""" + + lane: int + local: Role + remote: Role + steps: tuple[Step, ...] + + @property + def hops(self) -> int: + return len(self.steps) + + @property + def relays(self) -> tuple[int, ...]: + return tuple(step.dst for step in self.steps[:-1]) + + @property + def cables(self) -> tuple[str, ...]: + return tuple(step.text for step in self.steps) + + def to_json(self) -> dict[str, object]: + return { + "lane": self.lane, + "local": self.local.device, + "remote": self.remote.device, + "local_role": self.local.label, + "remote_role": self.remote.label, + "hops": self.hops, + "relays": list(self.relays), + "cables": list(self.cables), + } + + +def derive_lanes(fabric: Fabric, a: int, b: int, lanes: int = 2) -> tuple[LaneRoute, ...]: + """The lanes from position ``a`` to position ``b`` (derivation rules above).""" + if lanes not in (1, 2): + raise RouteError("a session has one or two lanes per peer") + paths = fabric.shortest_paths(a, b) + if not paths: + raise RouteError(f"position {b} cannot be reached from position {a} on this fabric") + if len(paths) == 1: + chosen = (paths[0], paths[0]) + elif len(paths) == 2: + smaller = min(a, b) + + def leaves_smaller_through_port0(path: tuple[Step, ...]) -> bool: + if smaller == a: + return path[0].src_port == 0 + return path[-1].dst_port == 0 + + path_a = [path for path in paths if leaves_smaller_through_port0(path)] + if len(path_a) != 1: + raise RouteError(f"cannot tell path A from path B between positions {a} and {b}") + path_b = next(path for path in paths if path is not path_a[0]) + chosen = (path_a[0], path_b) + else: + raise RouteError(f"{len(paths)} shortest paths between positions {a} and {b}") + result = [] + for lane in range(lanes): + path = chosen[lane] + secondary = lane == 1 + result.append(LaneRoute(lane, role_at(path[0].src_port, secondary), + role_at(path[-1].dst_port, secondary), path)) + return tuple(result) + + +@dataclasses.dataclass(frozen=True) +class GroupRoutes: + """Every rank's lanes for one session.""" + + layout: Layout + lanes: int + ranks: tuple[Mapping[int, tuple[LaneRoute, ...]], ...] + + @property + def world(self) -> int: + return self.layout.world + + def route_map(self, rank: int) -> dict[int, tuple[str, ...]]: + """Peer rank to lane device names.""" + return {peer: tuple(lane.local.device for lane in lanes) + for peer, lanes in sorted(self.ranks[rank].items())} + + def route_text(self, rank: int) -> str: + return format_peer_routes(self.route_map(rank)) + + def lanes_to(self, rank: int, peer: int) -> tuple[LaneRoute, ...]: + return self.ranks[rank][peer] + + def max_relays(self) -> int: + return max((len(lane.relays) for rank in self.ranks for lanes in rank.values() for lane in lanes), + default=0) + + +def _required_ring_peers(rank: int, world: int, layout: Layout | None) -> list[int]: + """The immediate neighbor peer ranks required for a sparse ``--ring-only`` route map.""" + if layout is not None: + rank_of = {pos: idx for idx, pos in enumerate(layout.positions)} + start = layout.positions[rank] + neighbors = sorted({ + rank_of[step.dst] + for port in (0, 1) + if (step := layout.fabric.cross(start, port)) is not None and step.dst in rank_of + } - {rank}) + if neighbors: + return neighbors + return sorted({(rank - 1) % world, (rank + 1) % world} - {rank}) + + +def derive_routes(layout: Layout, lanes: int = 2, *, ring_only: bool = False) -> GroupRoutes: + """Route maps of every rank of a session on ``layout``. + + With ``ring_only=True``, each rank includes only its immediate ring/chain neighbors. + """ + ranks = [] + world = layout.world + for rank, here in enumerate(layout.positions): + peers = _required_ring_peers(rank, world, layout) if ring_only else [ + peer for peer in range(world) if peer != rank + ] + ranks.append({peer: derive_lanes(layout.fabric, here, layout.positions[peer], lanes) + for peer in peers}) + return GroupRoutes(layout, lanes, tuple(ranks)) + + +# -- textual form ----------------------------------------------------------------- + + +def parse_peer_routes(text: str) -> dict[int, tuple[str, ...]]: + """Parse ``=[/],...``; duplicate peers raise.""" + routes: dict[int, tuple[str, ...]] = {} + if text is None or not text.strip(): + raise RouteError("the route map is empty") + for entry in text.split(","): + entry = entry.strip() + if not entry: + raise RouteError(f"route map {text!r} has an empty entry") + peer_text, separator, devices_text = entry.partition("=") + if not separator: + raise RouteError(f"route map entry {entry!r} is not =[/]") + try: + peer = int(peer_text.strip()) + except ValueError: + raise RouteError(f"route map entry {entry!r} names peer {peer_text.strip()!r}, not a rank") from None + if peer in routes: + raise RouteError(f"route map names rank {peer} twice") + routes[peer] = tuple(device.strip() for device in devices_text.split("/")) + return routes + + +def format_peer_routes(routes: Mapping[int, Sequence[str]]) -> str: + return ",".join(f"{peer}={'/'.join(devices)}" for peer, devices in sorted(routes.items())) + + +# -- validation ------------------------------------------------------------------- + + +def validate_route_map( + rank: int, + world: int, + routes: Mapping[int, Sequence[str]], + *, + layout: Layout | None = None, + max_relays: int = DEFAULT_MAX_RELAYS, + available_devices: Iterable[str] | None = None, + roles: Mapping[str, Role] | None = None, + ring_only: bool = False, +) -> int: + """Check one rank's route map; return its lane count ``L``. + + Rules: every required peer named exactly once (every other rank by default, + or immediate ring/chain neighbors when ``ring_only=True``) and the own rank + not at all; every entry with the same lane count, 1 or 2, of distinct + non-empty device names; 1 to 4 devices in all, each available when + ``available_devices`` is given; with a layout, every lane stays inside the + fabric and crosses at most ``max_relays`` relays. Errors name the rank, the + entry and the rule. + """ + if not 0 <= rank < world: + raise RouteError(f"rank {rank} is outside a session of {world}") + if rank in routes: + raise RouteError(f"rank {rank}'s route map names its own rank") + if layout is not None and layout.world != world: + raise RouteError(f"layout has {layout.world} ranks, the session {world}") + required = (_required_ring_peers(rank, world, layout) if ring_only + else [peer for peer in range(world) if peer != rank]) + missing = [peer for peer in required if peer not in routes] + if missing: + raise RouteError(f"rank {rank}'s route map has no entry for rank {missing[0]}") + if not routes: + raise RouteError(f"rank {rank}'s route map is empty") + extra = sorted(peer for peer in routes if not 0 <= peer < world) + if extra: + raise RouteError(f"rank {rank}'s route map names rank {extra[0]}, outside the session") + counts = {len(devices) for devices in routes.values()} + if len(counts) != 1: + raise RouteError(f"rank {rank}'s route map entries have different lane counts {sorted(counts)}") + lanes = counts.pop() + if not 1 <= lanes <= MAX_LANES: + raise RouteError(f"rank {rank}'s route map has {lanes} lanes per peer; one or two are supported") + for peer, devices in sorted(routes.items()): + if any(not device for device in devices): + raise RouteError(f"rank {rank}'s entry for rank {peer} has an empty device name") + if len(set(devices)) != len(devices): + raise RouteError(f"rank {rank}'s entry for rank {peer} names device {devices[0]} twice") + named = list(dict.fromkeys(device for _, devices in sorted(routes.items()) for device in devices)) + if not 1 <= len(named) <= MAX_DEVICES: + raise RouteError(f"rank {rank}'s route map names {len(named)} devices; 1 to {MAX_DEVICES} are supported") + if available_devices is not None: + available = set(available_devices) + for device in named: + if device not in available: + raise RouteError(f"rank {rank}'s route map names device {device}, which is not an active " + "RDMA device of this host") + if layout is not None: + start = layout.positions[rank] + for peer, devices in sorted(routes.items()): + for lane, device in enumerate(devices): + role = role_of(device, roles) + if role is None: + raise RouteError(f"rank {rank} lane {lane} toward rank {peer} uses device {device}, " + "whose port and function the layout check cannot tell") + steps = layout.fabric.walk(start, role.port, layout.positions[peer], + limit=len(layout.fabric.positions)) + if steps is None: + raise RouteError( + f"rank {rank} lane {lane} toward rank {peer} leaves through {device} (port " + f"{role.port}) and crosses a Spark outside the group's fabric") + if len(steps) - 1 > max_relays: + raise RouteError( + f"rank {rank} lane {lane} toward rank {peer} crosses {len(steps) - 1} relays; the " + f"qualified limit is {max_relays} (SIRCL_MAX_RELAYS raises it, research-only)") + return lanes + + +def check_complementary( + layout: Layout, + route_maps: Sequence[Mapping[int, Sequence[str]]], + *, + roles: Mapping[str, Role] | None = None, +) -> list[str]: + """Problems with the cross-rank pairing of lanes (empty when every lane pairs). + + Lane ``l`` of rank ``r`` toward ``p`` and lane ``l`` of ``p`` toward ``r`` + must cross the same cables in opposite directions with the same function + class: ``p``'s device must be the function of ``r``'s class on the port + where ``r``'s lane arrives. + """ + problems = [] + for rank, routes in enumerate(route_maps): + for peer, devices in sorted(routes.items()): + for lane, device in enumerate(devices): + mine = role_of(device, roles) + theirs_device = route_maps[peer][rank][lane] if lane < len(route_maps[peer].get(rank, ())) else None + if mine is None or theirs_device is None: + problems.append(f"lane {lane} between ranks {rank} and {peer} cannot be checked") + continue + steps = layout.fabric.walk(layout.positions[rank], mine.port, layout.positions[peer], + limit=len(layout.fabric.positions)) + if steps is None: + problems.append(f"lane {lane} of rank {rank} toward rank {peer} does not reach it") + continue + expected = role_at(steps[-1].dst_port, mine.secondary) + theirs = role_of(theirs_device, roles) + if theirs != expected: + problems.append( + f"lane {lane} of rank {rank} leaves through port {mine.port} and arrives on rank " + f"{peer}'s port {steps[-1].dst_port} ({expected.device}), but rank {peer} lists " + f"{theirs_device} for lane {lane}") + return problems + + +def relay_load(routes: GroupRoutes) -> tuple[int, float]: + """``(lanes through the busiest relay queue, load factor f)``. + + A relay queue is one (relay Spark, function class, direction). When every + rank sends ``b`` bytes to every peer, split over ``L`` lanes, the busiest + queue holds about ``f * b`` bytes with ``f`` = lanes / ``L``. + """ + load: dict[tuple[int, bool, int], int] = {} + for rank in routes.ranks: + for lanes in rank.values(): + for lane in lanes: + for step in lane.steps[:-1]: + # Arriving on port 1 continues clockwise (out of port 0). + key = (step.dst, lane.local.secondary, step.dst_port) + load[key] = load.get(key, 0) + 1 + busiest = max(load.values(), default=0) + return busiest, busiest / routes.lanes + + +DEFAULT_FORWARD_WINDOW = 131072 +DEFAULT_FORWARD_CHUNK = 32768 +DEFAULT_HAIRPIN_QUEUE = 524288 +RELAY_QUEUE_SHARE = 0.75 + + +def _lane_steps(layout: Layout, rank: int, peer: int, device: str, + roles: Mapping[str, Role] | None) -> tuple[Role, tuple[Step, ...]] | None: + role = role_of(device, roles) + if role is None: + return None + steps = layout.fabric.walk(layout.positions[rank], role.port, layout.positions[peer], + limit=len(layout.fabric.positions)) + return (role, steps) if steps is not None else None + + +def relay_queues( + layout: Layout, + route_maps: Sequence[Mapping[int, Sequence[str]]], + *, + roles: Mapping[str, Role] | None = None, +) -> dict[tuple[int, bool, int], list[tuple[int, int, int]]]: + """Lanes through every relay hairpin queue of a group. + + Key: (relay position, secondary function, egress port); value: the + ``(rank, peer, lane)`` of every lane whose packets that queue forwards. + """ + queues: dict[tuple[int, bool, int], list[tuple[int, int, int]]] = {} + for rank, routes in enumerate(route_maps): + for peer, devices in sorted(routes.items()): + for lane, device in enumerate(devices): + found = _lane_steps(layout, rank, peer, device, roles) + if found is None: + continue + role, steps = found + for step in steps[:-1]: + key = (step.dst, role.secondary, 1 - step.dst_port) + queues.setdefault(key, []).append((rank, peer, lane)) + return queues + + +def ring_queues( + layout: Layout, + route_maps: Sequence[Mapping[int, Sequence[str]]], + order: Sequence[int], + *, + roles: Mapping[str, Role] | None = None, +) -> dict[tuple[int, bool, int], list[tuple[int, int, int]]]: + """Lanes of the ring over ``order`` (rank ``order[i]`` to ``order[(i + 1) % W]``) through every + relay hairpin queue, keyed as in :func:`relay_queues`; empty when every ring edge is a cable.""" + queues: dict[tuple[int, bool, int], list[tuple[int, int, int]]] = {} + world = len(order) + for i, rank in enumerate(order): + peer = order[(i + 1) % world] + if peer == rank: + continue + for lane, device in enumerate(route_maps[rank].get(peer, ())): + found = _lane_steps(layout, rank, peer, device, roles) + if found is None: + continue + role, steps = found + for step in steps[:-1]: + key = (step.dst, role.secondary, 1 - step.dst_port) + queues.setdefault(key, []).append((rank, peer, lane)) + return queues + + +def ring_window( + layout: Layout, + route_maps: Sequence[Mapping[int, Sequence[str]]], + order: Sequence[int], + *, + chunk: int = DEFAULT_FORWARD_CHUNK, + queue_bytes: int = DEFAULT_HAIRPIN_QUEUE, + roles: Mapping[str, Role] | None = None, + subset_ring: bool = False, +) -> tuple[int, list[str]]: + """``(window, problems)`` of the ring over ``order``: the bytes each ring lane through relays + keeps unacknowledged (0 when every ring edge is a cable), and why the ring cannot run. + + During a ring op the ring's lanes are a group's only relayed traffic, so a relay hairpin queue + holds the bytes of the ring lanes through it; the window is the largest multiple of ``chunk`` + within ``RELAY_QUEUE_SHARE`` of a queue when every queue carries at most one ring lane (relays + forward each function's lanes through that function's own queue). A queue that carries two + ring lanes is a problem. Subset mode uses the smaller shared packet envelope + from subset.payload_budget instead of the legacy payload share. + """ + queues = ring_queues(layout, route_maps, order, roles=roles) + allowance = int(RELAY_QUEUE_SHARE * queue_bytes) + if subset_ring: + from . import subset + allowance = subset.payload_budget(layout, route_maps, queue_bytes=queue_bytes) + problems = [f"relay {key[0]} {'secondary' if key[1] else 'primary'} function toward port {key[2]} carries " + f"ring lanes {members}" for key, members in sorted(queues.items()) if len(members) > 1] + if not queues: + return 0, problems + window = allowance // chunk * chunk + if window < chunk: + problems.append(f"a relay queue of {queue_bytes} bytes holds less than one {chunk}-byte chunk") + return window, problems + + +def forward_windows( + layout: Layout, + route_maps: Sequence[Mapping[int, Sequence[str]]], + rank: int, + *, + max_window: int = DEFAULT_FORWARD_WINDOW, + chunk: int = DEFAULT_FORWARD_CHUNK, + queue_bytes: int = DEFAULT_HAIRPIN_QUEUE, + roles: Mapping[str, Role] | None = None, + subset_ring: bool = False, +) -> list[list[int]]: + """Forward window in bytes of every lane of ``rank`` (``[peer][lane]``; 0 for direct lanes). + + A lane through relays gets the largest multiple of ``chunk`` that is at + most ``max_window`` and, for every relay queue it crosses, at most + ``RELAY_QUEUE_SHARE * queue_bytes / n``, where ``n`` lanes share that queue; + never less than one chunk. A ``max_window`` of 0 disables windows. Subset + mode instead rejects disabled windows and shares smaller than a chunk. + """ + world = layout.world + lanes = max((len(devices) for devices in route_maps[rank].values()), default=0) + table = [[0] * lanes for _ in range(world)] + allowance = int(RELAY_QUEUE_SHARE * queue_bytes) + if subset_ring: + from . import subset + allowance = subset.payload_budget(layout, route_maps, queue_bytes=queue_bytes) + if max_window <= 0: + raise RouteError("subset ring requires forward windows") + if max_window <= 0: + return table + if chunk <= 0 or chunk % 16 or max_window < chunk: + raise RouteError(f"forward chunk {chunk} must be a positive multiple of 16 within the window {max_window}") + queues = relay_queues(layout, route_maps, roles=roles) + load: dict[tuple[int, int, int], int] = {} + for members in queues.values(): + for member in members: + load[member] = max(load.get(member, 0), len(members)) + for peer, devices in sorted(route_maps[rank].items()): + for lane in range(len(devices)): + sharing = load.get((rank, peer, lane), 0) + if sharing == 0: + continue + limit = min(max_window, allowance // sharing) + if subset_ring and limit < chunk: + raise RouteError(f"subset relay allowance {allowance} cannot hold {sharing} chunks of {chunk} bytes") + table[peer][lane] = max(chunk, limit // chunk * chunk) + return table + + +def chain_order( + layout: Layout, + route_maps: Sequence[Mapping[int, Sequence[str]]], + *, + roles: Mapping[str, Role] | None = None, + subset_ring: bool = False, +) -> tuple[int, ...] | None: + """The ranks in chain order when the group's ranks form a chain of cable neighbors, else None. + + Every Spark of the fabric must host a rank unless subset_ring admits a + bounded, isolated arc through subset.validate. On a path the chain starts at the + end with the smaller position; on a cycle it starts at rank 0 and follows + port 0, leaving the cable that closes the cycle unused. Every lane between + consecutive ranks of the chain, in both directions, must be a direct lane + (no relay). + """ + fabric = layout.fabric + if fabric.kind == "disconnected": + return None + if sorted(layout.positions) != list(fabric.positions): + if not subset_ring: + return None + from . import subset + return subset.validate(layout, route_maps) + rank_at = {position: rank for rank, position in enumerate(layout.positions)} + if fabric.kind == "path": + degree: dict[int, int] = {} + for cable in fabric.cables: + for position, _ in cable.ends(): + degree[position] = degree.get(position, 0) + 1 + start = min(position for position in fabric.positions if degree.get(position, 0) <= 1) + else: + start = layout.positions[0] + order = [start] + previous = None + while len(order) < len(fabric.positions): + here = order[-1] + steps = [fabric.cross(here, port) for port in (0, 1)] + candidates = [step.dst for step in steps if step is not None and step.dst != previous + and step.dst not in order] + if fabric.kind != "path" and len(order) == 1: + first = fabric.cross(here, 0) + candidates = [first.dst] if first is not None else [] + if not candidates: + return None + previous = here + order.append(candidates[0]) + ranks = tuple(rank_at[position] for position in order) + for a, b in zip(ranks, ranks[1:]): + for source, target in ((a, b), (b, a)): + devices = route_maps[source].get(target) + if not devices: + return None + for device in devices: + found = _lane_steps(layout, source, target, device, roles) + if found is None or len(found[1]) != 1: + return None + return ranks + + +def isolation_problems(groups: Sequence[GroupRoutes]) -> list[str]: + """Cables or relays shared by independent groups on one ring (must be empty).""" + problems = [] + for first in range(len(groups)): + for second in range(first + 1, len(groups)): + a, b = groups[first], groups[second] + cables_a = {step.cable for rank in a.ranks for lanes in rank.values() for lane in lanes + for step in lane.steps} + cables_b = {step.cable for rank in b.ranks for lanes in rank.values() for lane in lanes + for step in lane.steps} + for cable in sorted(cables_a & cables_b, key=lambda c: c.text): + problems.append(f"groups {first} and {second} both use cable {cable.text}") + sparks_a = set(a.layout.positions) | {relay for rank in a.ranks for lanes in rank.values() + for lane in lanes for relay in lane.relays} + sparks_b = set(b.layout.positions) | {relay for rank in b.ranks for lanes in rank.values() + for lane in lanes for relay in lane.relays} + for spark in sorted(sparks_a & sparks_b): + problems.append(f"groups {first} and {second} both use Spark {spark}") + return problems diff --git a/sparkring_fabric/sparkring_fabric/site.py b/sparkring_fabric/sparkring_fabric/site.py new file mode 100644 index 00000000..923d3764 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/site.py @@ -0,0 +1,232 @@ +"""Site description (``sircl-ring-site/v1``) and batch-mode SSH runner for fabric tooling. + +Pure standard library + :mod:`sparkring_fabric.routes`. +""" + +from __future__ import annotations + +import dataclasses +import ipaddress +import json +import re +import subprocess +from collections.abc import Mapping, Sequence +from pathlib import Path + +from . import routes as routes_mod + +SCHEMA = "sircl-ring-site/v1" +DEFAULT_DOCKER = "docker" +CABLINGS = ("ring", "path", "cables") +SSH_OPTIONS = ("-o", "BatchMode=yes", "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=10", + "-o", "ServerAliveCountMax=3") +_PLACEHOLDER = re.compile(r"REPLACE|<|>") +_SAFE = re.compile(r"^[A-Za-z0-9_.@:/+-]+$") +_DOCKER_WORD = re.compile(r"^[A-Za-z0-9_.@:/+=-]+$") +_DOCKER_MAX_WORDS = 8 + + +class SiteError(ValueError): + """The site description is incomplete or inconsistent.""" + + +@dataclasses.dataclass(frozen=True) +class Result: + returncode: int + stdout: str + stderr: str + + @property + def ok(self) -> bool: + return self.returncode == 0 + + +def ssh(target: str, command: str, *, timeout: float = 60, input_bytes: bytes | None = None, + binary: str = "ssh") -> Result: + """Run ``command`` on ``target`` through ssh; a deadline returns code 124.""" + argv = [binary, *SSH_OPTIONS, target, command] + try: + process = subprocess.run(argv, input=input_bytes, capture_output=True, timeout=timeout) + except subprocess.TimeoutExpired: + return Result(124, "", f"ssh {target} timed out after {timeout:g} s") + except FileNotFoundError: + return Result(127, "", f"{binary} is not installed on this machine") + return Result(process.returncode, process.stdout.decode(errors="replace"), + process.stderr.decode(errors="replace")) + + +def docker_problem(value: object) -> str | None: + """Why ``value`` cannot be a Docker command prefix, or None when it can.""" + if not isinstance(value, str): + return 'must be a string such as "docker" or "sudo -n docker"' + words = value.split() + if not 1 <= len(words) <= _DOCKER_MAX_WORDS: + return f"must hold 1 to {_DOCKER_MAX_WORDS} words" + for word in words: + if _PLACEHOLDER.search(word) or not _DOCKER_WORD.match(word): + return f"has the word {word!r}, a placeholder or characters a shell would read" + if words[-1] != "docker" and not words[-1].endswith("/docker"): + return "must end with the Docker executable (docker, or a path ending in /docker)" + return None + + +def _docker_text(value: object) -> object: + return " ".join(value.split()) if isinstance(value, str) else value + + +def _cabling_of(value: object) -> tuple[str, tuple[str, ...]]: + if value is None or value == "ring": + return "ring", () + if value == "path": + return "path", () + if isinstance(value, Sequence) and not isinstance(value, str) and value \ + and all(isinstance(item, str) for item in value): + return "cables", tuple(" ".join(item.split()) for item in value) + raise SiteError('cabling must be "ring", "path" or a list of cables such as ["0.port0-1.port0"]') + + +@dataclasses.dataclass(frozen=True) +class Host: + name: str + ssh: str + lan_address: str + docker: str = DEFAULT_DOCKER + + +@dataclasses.dataclass(frozen=True) +class Site: + image: str + lan_interface: str + control_port: int + remote_dir: str + ring: tuple[Host, ...] + gid_index: int | None = None + docker: str = DEFAULT_DOCKER + cabling: str = "ring" + cables: tuple[str, ...] = () + + @property + def size(self) -> int: + return len(self.ring) + + def host(self, position: int) -> Host: + return self.ring[position] + + def fabric(self) -> routes_mod.Fabric: + """Every cable of the site between the listed Sparks (positions are entry indices).""" + if self.cabling == "ring": + return routes_mod.Fabric.ring(self.size) + if self.cabling == "path": + return routes_mod.Fabric.path(range(self.size)) + return routes_mod.Fabric.parse(self.cables) + + def cabled_ports(self, position: int) -> tuple[int, ...]: + """The ports of the Spark at ``position`` that hold a cable of the site.""" + fabric = self.fabric() + return tuple(port for port in (0, 1) if fabric.cable_at(position, port) is not None) + + def cabling_text(self) -> str: + """The cabling in words, for plans and errors.""" + if self.cabling == "ring": + return f"a ring of {self.size} (entry i port 0 to entry i + 1 port 1, wrapping around)" + if self.cabling == "path": + return f"a path of {self.size} (entry i port 0 to entry i + 1 port 1, the ends' outer ports free)" + return f"the cables {', '.join(self.cables)}" + + @classmethod + def from_json(cls, document: Mapping[str, object], *, cablings: Sequence[str] = ("ring",)) -> "Site": + """The site of ``document``; a cabling outside ``cablings`` is refused.""" + if document.get("schema") != SCHEMA: + raise SiteError(f"site schema must be {SCHEMA}") + try: + image = str(document["image"]) + interface = str(document["lan_interface"]) + port = int(document["control_port"]) + remote_dir = str(document.get("remote_dir", "/tmp/sircl-ring")) + entries = list(document["ring"]) + except (KeyError, TypeError, ValueError) as error: + raise SiteError(f"site file is missing or malforms a field: {error}") from None + gid = document.get("gid_index") + docker = _docker_text(document.get("docker", DEFAULT_DOCKER)) + cabling, cables = _cabling_of(document.get("cabling")) + hosts = [] + for index, entry in enumerate(entries): + if not isinstance(entry, Mapping): + raise SiteError(f"ring entry {index} is not an object") + hosts.append(Host(str(entry.get("name", f"spark{index}")), str(entry.get("ssh", "")), + str(entry.get("lan_address", "")), _docker_text(entry.get("docker", docker)))) + site = cls(image, interface, port, remote_dir, tuple(hosts), None if gid is None else int(gid), docker, + cabling, cables) + site.validate() + if site.cabling not in cablings: + raise SiteError(f"the site's Sparks are cabled as {site.cabling_text()} (cabling {site.cabling!r}); " + f"this command plans cabling {' or '.join(repr(name) for name in cablings)} only") + return site + + @classmethod + def load(cls, path: str | Path, *, cablings: Sequence[str] = ("ring",)) -> "Site": + return cls.from_json(json.loads(Path(path).read_text(encoding="utf-8")), cablings=cablings) + + def validate(self) -> None: + problems = [] + for field, value in (("image", self.image), ("lan_interface", self.lan_interface), + ("remote_dir", self.remote_dir)): + if not value or _PLACEHOLDER.search(value) or not _SAFE.match(value): + problems.append(f"{field} {value!r} is a placeholder or holds characters a shell would read") + problem = docker_problem(self.docker) + if problem: + problems.append(f"docker {self.docker!r} {problem}") + if not 1024 <= self.control_port <= 65000: + problems.append("control_port must be between 1024 and 65000") + if not self.remote_dir.startswith("/"): + problems.append("remote_dir must be an absolute path on the Sparks") + if not 2 <= self.size <= 16: + problems.append(f"the ring lists {self.size} Sparks; 2 to 16 are supported") + elif self.cabling == "cables": + problems.extend(self._cable_problems()) + seen_names, seen_addresses = set(), set() + for index, host in enumerate(self.ring): + if not host.ssh or _PLACEHOLDER.search(host.ssh) or not _SAFE.match(host.ssh): + problems.append(f"ring entry {index} ({host.name}) needs an SSH target") + problem = docker_problem(host.docker) + if problem: + problems.append(f"ring entry {index} ({host.name}) docker {host.docker!r} {problem}") + try: + address = ipaddress.IPv4Address(host.lan_address) + except ValueError: + problems.append(f"ring entry {index} ({host.name}) needs a wired-LAN IPv4 address") + continue + if address in seen_addresses: + problems.append(f"wired-LAN address {address} appears twice") + if host.name in seen_names: + problems.append(f"Spark name {host.name} appears twice") + seen_addresses.add(address) + seen_names.add(host.name) + if self.gid_index is not None and not 0 <= self.gid_index <= 255: + problems.append("gid_index must be in 0-255") + if problems: + raise SiteError("; ".join(problems)) + + def _cable_problems(self) -> list[str]: + try: + fabric = self.fabric() + except routes_mod.RouteError as error: + return [f"cabling: {error}"] + outside = sorted({p for p in fabric.positions if not 0 <= p < self.size}) + if outside: + return [f"cabling names positions {outside}; the ring lists positions 0 to {self.size - 1}"] + missing = sorted(set(range(self.size)) - set(fabric.positions)) + if missing: + return [f"cabling leaves positions {missing} without a cable"] + reached, frontier = {0}, [0] + while frontier: + here = frontier.pop() + for port in (0, 1): + step = fabric.cross(here, port) + if step is not None and step.dst not in reached: + reached.add(step.dst) + frontier.append(step.dst) + if len(reached) != self.size: + return [f"cabling splits the Sparks: positions {sorted(set(range(self.size)) - reached)} are not " + "reached from position 0"] + return [] diff --git a/sparkring_fabric/sparkring_fabric/subset.py b/sparkring_fabric/sparkring_fabric/subset.py new file mode 100644 index 00000000..fcb49010 --- /dev/null +++ b/sparkring_fabric/sparkring_fabric/subset.py @@ -0,0 +1,154 @@ +"""Admission and schedule policy for independent subset chain sessions. + +Only a cable-connected arc leaving at most two adjacent non-members is admitted. +Those non-members have no relayed traffic in the universal shortest-path table, +including when TP and DCP sessions run concurrently. No shared-queue reservation +protocol is implemented; larger complements are refused even when idle. +The conservative ring/arena budget helper is retained for isolated tests; +the active chain policy adds no relayed links and preserves OFF arena pacing. +""" + +from __future__ import annotations + +import os +from collections.abc import Mapping + +from . import routes + +VARIABLE = "SIRCL_SUBSET_RING" +FORWARD_CHUNK = 4096 +# Small flat gathers have no measured gain. Sizes are per-rank input bytes. +GATHER_MIN_BYTES = 4 << 20 +# RC's smallest path MTU is 256. Allow 128 bytes per packet for framing, +# transport headers, CRC and queue accounting. A signaled credit may cover +# two WRs; each QP has at most 64 such credits (_roce_proxy.c). +MIN_MTU = 256 +FRAME_ALLOWANCE = 128 +CONTROL_BYTES_PER_LANE = 64 * 2 * FRAME_ALLOWANCE + + +def enabled(environ: Mapping[str, str] | None = None) -> bool: + raw = (os.environ if environ is None else environ).get(VARIABLE, "0").strip() or "0" + if raw not in ("0", "1"): + raise routes.RouteError(f"{VARIABLE} must be 0 or 1, got {raw!r}") + return raw == "1" + + +def schedule(requested: str, collective: str) -> str: + """Subset links serve only flat all-gather; shape and size are checked by the runtime. + + A ring request becomes automatic chain selection, retaining the small-message + pieces fallback. Explicit pieces remains a way to disable chain all-gather. + """ + if collective != "gather": + return "pieces" + return "auto" if requested == "ring" else requested + + +def order(layout: routes.Layout) -> tuple[int, ...]: + """Admit a physical arc, including wrapping arcs and permuted rank order.""" + fabric = layout.fabric + members = set(layout.positions) + outside = set(fabric.positions) - members + if (fabric.kind != "cycle" or not 4 <= len(fabric.positions) <= 8 + or len(members) < 3 or not 1 <= len(outside) <= 2): + raise routes.RouteError("subset ring needs 3 or more ranks on a cycle of 4 to 8, leaving one or two " + "adjacent non-members; other subsets need coordinated relay reservations") + starts = [p for p in members if fabric.cross(p, 1).dst not in members] + if len(starts) != 1: + raise routes.RouteError("subset ring ranks must form one cable-connected arc") + positions = [starts[0]] + while len(positions) < len(members): + p = fabric.cross(positions[-1], 0).dst + if p not in members or p in positions: + raise routes.RouteError("subset ring ranks must form one cable-connected arc") + positions.append(p) + return tuple(layout.positions.index(p) for p in positions) + + +def validate(layout, maps, *, queue_bytes=routes.DEFAULT_HAIRPIN_QUEUE): + """Reject custom lanes and queue capacities outside the proved model.""" + result = order(layout) + if not 4096 <= queue_bytes <= routes.DEFAULT_HAIRPIN_QUEUE: + raise routes.RouteError("subset ring hairpin capacity must be between 4096 and 524288 bytes") + lanes = len(next(iter(maps[0].values()))) + derived = routes.derive_routes(layout, lanes) + + def roles(route_map): + return {peer: tuple(routes.role_of(device) for device in devices) + for peer, devices in route_map.items()} + + if [roles(m) for m in maps] != [roles(derived.route_map(rank)) for rank in range(layout.world)]: + raise routes.RouteError("subset ring requires the universal shortest-path lane maps") + return result + + +def payload_budget(layout, maps, *, queue_bytes=routes.DEFAULT_HAIRPIN_QUEUE) -> int: + """Retained, inactive ring/arena allowance for each direction of every relay queue. + + Let n count all session lanes through q and its reverse. Reserve n*16384 + bytes for short writes, short final packets and their ACKs. The remaining + bytes hold arena and ring payload simultaneously in both directions: + 2*B payload + 2*B/2 framing + 2*B/2 reverse ACKs = 4*B. + This is deliberately below the legacy 75-percent payload ceiling. + """ + validate(layout, maps, queue_bytes=queue_bytes) + queues = routes.relay_queues(layout, maps) + n = max((len(v) + len(queues.get((p, c, 1 - e), ())) + for (p, c, e), v in queues.items()), default=0) + return min(int(routes.RELAY_QUEUE_SHARE * queue_bytes), + max(0, (queue_bytes - n * CONTROL_BYTES_PER_LANE) // 4)) + + +def ring_packet_bound(layout, maps, *, chunk=32768, queue_bytes=routes.DEFAULT_HAIRPIN_QUEUE): + """Offline maximum common ring window with the conservative arena windows fixed. + + This is not an active runtime allowance. Completion-only credit release, + MTU >= 256, <= 128 bytes of overhead per packet, and no retained retry + copies are required. Arena and ring payload may overlap, but a native QP + shares one unacked counter: its payload is bounded by max(arena, ring), + not their sum. The reverse + queue's payload generates ACKs in this queue, including ACK-only queues. + Control credits are shared by arena and ring on each native QP. + """ + order_ranks = validate(layout, maps, queue_bytes=queue_bytes) + if chunk <= 0 or chunk % 16: + raise routes.RouteError("ring bound chunk must be a positive multiple of 16") + arena = routes.relay_queues(layout, maps) + ring = routes.ring_queues(layout, maps, order_ranks) + tables = [routes.forward_windows(layout, maps, rank, chunk=FORWARD_CHUNK, + queue_bytes=queue_bytes, subset_ring=True) + for rank in range(layout.world)] + keys = set(arena) | set(ring) + keys |= {(p, c, 1 - e) for p, c, e in keys.copy()} + rows = [] + for key in sorted(keys): + reverse = (*key[:2], 1 - key[2]) + a = sum(tables[r][p][lane] for r, p, lane in arena.get(key, ())) + b = sum(tables[r][p][lane] for r, p, lane in arena.get(reverse, ())) + controls = (len(arena.get(key, ())) + len(arena.get(reverse, ()))) * CONTROL_BYTES_PER_LANE + shared = [tables[r][p][lane] for r, p, lane in ring.get(key, ())] + back_shared = [tables[r][p][lane] for r, p, lane in ring.get(reverse, ())] + # Payload on QPs that do not carry the ring remains independently live. + fixed2 = 3 * (a - sum(shared)) + b - sum(back_shared) + 2 * controls + if 3 * a + b + 2 * controls > 2 * queue_bytes: + raise routes.RouteError("arena exceeds the packet envelope") + rows.append({"queue": list(key), "arena_bytes": a, "reverse_arena_bytes": b, + "control_bytes": controls, "fixed_twice_bytes": fixed2, + "ring_arena_windows": shared, "reverse_ring_arena_windows": back_shared}) + + def occupied2(row, window): + return (row["fixed_twice_bytes"] + 3 * sum(max(w, window) for w in row["ring_arena_windows"]) + + sum(max(w, window) for w in row["reverse_ring_arena_windows"])) + + # A monotone piecewise-linear bound; enumerate at most Q/chunk aligned values. + window = 0 + if ring: + for candidate in range(chunk, queue_bytes + 1, chunk): + if any(occupied2(row, candidate) > 2 * queue_bytes for row in rows): + break + window = candidate + for row in rows: + row["bound_bytes"] = (occupied2(row, window) + 1) // 2 + row["next_chunk_bound_bytes"] = (occupied2(row, window + chunk) + 1) // 2 + return window, rows diff --git a/sparkring_fabric/tests/conftest.py b/sparkring_fabric/tests/conftest.py new file mode 100644 index 00000000..0595e854 --- /dev/null +++ b/sparkring_fabric/tests/conftest.py @@ -0,0 +1,15 @@ +"""Ensure standalone ``sparkring_fabric`` resolves ahead of any repo-root namespace directory.""" + +from __future__ import annotations + +import importlib +import sys +from pathlib import Path + +PACKAGE_ROOT = str(Path(__file__).resolve().parents[1]) +if PACKAGE_ROOT not in sys.path: + sys.path.insert(0, PACKAGE_ROOT) +_existing = sys.modules.get("sparkring_fabric") +if _existing is not None and getattr(_existing, "__file__", None) is None: + del sys.modules["sparkring_fabric"] + importlib.invalidate_caches() diff --git a/sparkring_fabric/tests/test_import_boundary.py b/sparkring_fabric/tests/test_import_boundary.py new file mode 100644 index 00000000..ba2da8b9 --- /dev/null +++ b/sparkring_fabric/tests/test_import_boundary.py @@ -0,0 +1,163 @@ +"""Import-boundary and zero-dependency proofs for standalone ``sparkring_fabric``.""" + +from __future__ import annotations + +import ast +import subprocess +import sys +from pathlib import Path + +import pytest + +PACKAGE_PROJECT = Path(__file__).resolve().parents[1] +PACKAGE_DIR = PACKAGE_PROJECT / "sparkring_fabric" +REPO_ROOT = PACKAGE_PROJECT.parent + +FORBIDDEN_TOP_LEVELS = frozenset({ + "sparkring_sircl", + "vllm", + "torch", + "cutlass", + "cuda", + "runtime", + "integrations", + "experiments", + "spark_transport", + "numpy", + "yaml", +}) + + +def _imported_top_levels(path: Path) -> set[str]: + tree = ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path)) + found: set[str] = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + found.add(alias.name.split(".", 1)[0]) + elif isinstance(node, ast.ImportFrom): + if node.level == 0 and node.module: + found.add(node.module.split(".", 1)[0]) + return found + + +def test_ast_imports_are_stdlib_only_and_free_of_forbidden_packages(): + """Every module in ``sparkring_fabric`` imports only Python stdlib + relative package modules.""" + py_files = sorted(PACKAGE_DIR.rglob("*.py")) + assert py_files, "expected Python sources under sparkring_fabric/sparkring_fabric" + stdlib = sys.stdlib_module_names + for path in py_files: + top_levels = _imported_top_levels(path) + forbidden = top_levels & FORBIDDEN_TOP_LEVELS + assert not forbidden, f"{path.relative_to(PACKAGE_PROJECT)} imports forbidden modules: {sorted(forbidden)}" + non_stdlib = top_levels - stdlib - {"sparkring_fabric"} + assert not non_stdlib, ( + f"{path.relative_to(PACKAGE_PROJECT)} imports non-stdlib modules outside declared deps: {sorted(non_stdlib)}" + ) + + +def test_isolated_subprocess_imports_cleanly_with_forbidden_modules_blocked(): + """Importing every ``sparkring_fabric`` module succeeds in ``python -I`` with forbidden roots blocked.""" + code = ( + "import importlib, sys\n" + f"sys.path.insert(0, {str(PACKAGE_PROJECT)!r})\n" + f"FORBIDDEN = {sorted(FORBIDDEN_TOP_LEVELS)!r}\n" + "class BlockForbidden:\n" + " def find_spec(self, fullname, path, target=None):\n" + " root = fullname.split('.', 1)[0]\n" + " if root in FORBIDDEN:\n" + " raise AssertionError(f'forbidden import attempted: {fullname}')\n" + " return None\n" + "sys.meta_path.insert(0, BlockForbidden())\n" + "modules = [\n" + " 'sparkring_fabric',\n" + " 'sparkring_fabric.routes',\n" + " 'sparkring_fabric.subset',\n" + " 'sparkring_fabric.budget',\n" + " 'sparkring_fabric.site',\n" + " 'sparkring_fabric.fabric',\n" + " 'sparkring_fabric.fabric.layouts',\n" + " 'sparkring_fabric.fabric.plan',\n" + " 'sparkring_fabric.fabric.commands',\n" + " 'sparkring_fabric.fabric.state',\n" + " 'sparkring_fabric.fabric.diff',\n" + " 'sparkring_fabric.fabric.ops',\n" + " 'sparkring_fabric.fabric.report',\n" + " 'sparkring_fabric.fabric.cli',\n" + "]\n" + "for name in modules:\n" + " importlib.import_module(name)\n" + "for root in FORBIDDEN:\n" + " assert root not in sys.modules, f'unexpected module loaded: {root}'\n" + "print('OK', len(modules))\n" + ) + proc = subprocess.run([sys.executable, "-I", "-c", code], capture_output=True, text=True, timeout=60) + assert proc.returncode == 0, proc.stderr + assert proc.stdout.strip() == "OK 14" + + +def test_marker_source_located_relative_to_sparkring_fabric(): + from sparkring_fabric.fabric import cli, commands + + expected = (PACKAGE_DIR / "fabric" / "mesh_marker.c").resolve() + assert commands.MARKER_SOURCE.resolve() == expected + assert cli.MARKER_SOURCE.resolve() == expected + assert commands.MARKER_SOURCE.is_file() + script = commands.marker_build_script("spark0", commands.MarkerConfig()) + assert 'cat > "$work/mesh_marker.c"' in script + assert "mlx5dv_create_flow_matcher" in script + + +@pytest.mark.parametrize("mode", ["repo_root", "sircl_dir", "installed_tree"]) +def test_sircl_compatibility_shims_work_across_invocation_modes(tmp_path, mode): + """Thin shims in ``sparkring_sircl`` resolve to canonical ``sparkring_fabric`` modules in all 3 modes.""" + sircl_dir = REPO_ROOT / "spark_transport" / "sircl" + if mode == "repo_root": + paths = [str(REPO_ROOT)] + import_stmt = ( + "from spark_transport.sircl.sparkring_sircl import routes\n" + "from spark_transport.sircl.sparkring_sircl.fabric import cli, commands, diff, layouts, ops, plan, report, state\n" + ) + elif mode == "sircl_dir": + paths = [str(sircl_dir)] + import_stmt = ( + "from sparkring_sircl import routes\n" + "from sparkring_sircl.fabric import cli, commands, diff, layouts, ops, plan, report, state\n" + ) + else: + # Simulate an installed site-packages tree outside the repository checkout. + import shutil + + site_pkgs = tmp_path / "site-packages" + shutil.copytree(PACKAGE_DIR, site_pkgs / "sparkring_fabric") + shutil.copytree(sircl_dir / "sparkring_sircl", site_pkgs / "sparkring_sircl") + paths = [str(site_pkgs)] + import_stmt = ( + "from sparkring_sircl import routes\n" + "from sparkring_sircl.fabric import cli, commands, diff, layouts, ops, plan, report, state\n" + ) + + code = ( + "import sys\n" + f"sys.path[:0] = {paths!r}\n" + + import_stmt + + "import sparkring_fabric.routes as canon_routes\n" + "import sparkring_fabric.fabric.plan as canon_plan\n" + "import sparkring_fabric.fabric.layouts as canon_layouts\n" + "import sparkring_fabric.fabric.diff as canon_diff\n" + "import sparkring_fabric.fabric.state as canon_state\n" + "import sparkring_fabric.fabric.commands as canon_commands\n" + "import sparkring_fabric.fabric.cli as canon_cli\n" + "assert routes is canon_routes\n" + "assert plan is canon_plan\n" + "assert layouts is canon_layouts\n" + "assert diff is canon_diff\n" + "assert state is canon_state\n" + "assert commands is canon_commands\n" + "assert cli is canon_cli\n" + "assert cli.main(['plan', '--layout', '2xTP4', '--brief']) == 0\n" + ) + proc = subprocess.run([sys.executable, "-I", "-c", code], cwd=str(tmp_path), + capture_output=True, text=True, timeout=60) + assert proc.returncode == 0, proc.stderr + assert "group path:0-1-2-3" in proc.stdout diff --git a/sparkring_fabric/tests/test_routes_and_fabric.py b/sparkring_fabric/tests/test_routes_and_fabric.py new file mode 100644 index 00000000..045e41f1 --- /dev/null +++ b/sparkring_fabric/tests/test_routes_and_fabric.py @@ -0,0 +1,121 @@ +"""Standalone tests for ``sparkring_fabric`` routes, relay plans, budget, libsircl integration and packaging.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +from sparkring_fabric import budget, routes +from sparkring_fabric.fabric import cli, commands, layouts, plan + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +def test_ring_open_chain_and_ring_only_routes(): + ring8 = routes.Layout.parse("ring:8") + full = routes.derive_routes(ring8, lanes=2) + assert full.world == 8 + assert full.max_relays() == 3 + maps = [full.route_map(r) for r in range(8)] + assert routes.check_complementary(ring8, maps) == [] + assert routes.chain_order(ring8, maps) == (0, 1, 2, 3, 4, 5, 6, 7) + + sparse = routes.derive_routes(ring8, lanes=2, ring_only=True) + for r in range(8): + rmap = sparse.route_map(r) + assert sorted(rmap) == sorted([(r - 1) % 8, (r + 1) % 8]) + assert routes.validate_route_map(r, 8, rmap, layout=ring8, ring_only=True) == 2 + + path4 = routes.Layout.parse("path:0-3") + chain_routes = routes.derive_routes(path4, lanes=2) + chain_maps = [chain_routes.route_map(r) for r in range(4)] + assert routes.chain_order(path4, chain_maps) == (0, 1, 2, 3) + fw0 = routes.forward_windows(path4, chain_maps, 0) + assert fw0[1] == [0, 0] + assert fw0[2][0] > 0 and fw0[3][0] > 0 + + g0 = routes.derive_routes(routes.Layout.parse("path:0-3"), lanes=2) + g1 = routes.derive_routes(routes.Layout.parse("path:4-7"), lanes=2) + assert routes.isolation_problems([g0, g1]) == [] + + +def test_build_layout_and_open_chain_plans(): + names = [f"spark{i}" for i in range(8)] + facts = plan.Facts.symbolic_for(names) + layout = layouts.resolve(ring_size=8, layout="2xTP4") + built = plan.build_layout_plan(layout, facts) + assert len(built.groups) == 2 + assert built.layout.relay_egress == "sibling" + + chain_facts = plan.Facts.symbolic_for([f"spark{i}" for i in range(4)]) + chain_plan = plan.build_chain_plan((0, 1, 2, 3), chain_facts) + assert chain_plan.group.label == "path:0-1-2-3" + assert sum(len(s.filters) for s in chain_plan.sparks) == 12 + + +def test_cli_plan_command_offline(capsys): + assert cli.main(["plan", "--layout", "ring8", "--brief"]) == 0 + out = capsys.readouterr().out + assert "group cycle:0-1-2-3-4-5-6-7" in out + assert cli.main(["plan", "--groups", "0-3;4-7", "--json"]) == 0 + doc = json.loads(capsys.readouterr().out) + assert doc["schema"] == plan.PLAN_SCHEMA + assert len(doc["groups"]) == 2 + + +def test_budget_allocates_p2p_windows_on_path4(): + layout = routes.Layout.parse("path:0-3") + lane_set = budget.LaneSet.of("layout", layout, lanes=2) + reserved = budget.session_reservation(lane_set, budget.SessionSettings()) + allocation = budget.allocate( + [[lane_set]], + reserved=reserved, + max_window=budget.DEFAULT_P2P_WINDOW_BYTES, + chunk=budget.DEFAULT_P2P_CHUNK_BYTES, + ) + assert allocation.unavailable_pairs("layout") == {} + table = allocation.table(lane_set, 2) + assert table[0][3][0] >= budget.DEFAULT_P2P_CHUNK_BYTES + + +def test_libsircl_site_routes_runs_without_sircl_on_sys_path(): + """``spark_transport/libsircl/tools/site_routes.py`` works cleanly with ``spark_transport/sircl`` absent.""" + tool = REPO_ROOT / "spark_transport" / "libsircl" / "tools" / "site_routes.py" + if not tool.is_file(): + pytest.skip("libsircl site_routes.py not present") + env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "SIRCL_PACKAGE")} + env["PYTHONIOENCODING"] = "utf-8" + for args in (("--layout", "ring:8", "--lanes", "2", "--json"), + ("--layout", "ring:8", "--lanes", "2", "--ring-only", "--json"), + ("--layout", "path:0-3", "--lanes", "2", "--json")): + proc = subprocess.run([sys.executable, "-I", str(tool), *args], + env=env, capture_output=True, text=True, timeout=60) + assert proc.returncode == 0, proc.stderr + payload = json.loads(proc.stdout) + assert payload["ranks"], args + + +def test_deb_runtime_manifest_includes_sparkring_fabric(): + build_deb = REPO_ROOT / "scripts" / "build_deb.py" + if not build_deb.is_file(): + pytest.skip("scripts/build_deb.py not present") + if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + from scripts import build_deb as deb_mod + + assert deb_mod.is_runtime_manifest_path("sparkring_fabric/pyproject.toml") + assert deb_mod.is_runtime_manifest_path("sparkring_fabric/sparkring_fabric/routes.py") + assert deb_mod.is_runtime_manifest_path("sparkring_fabric/sparkring_fabric/fabric/mesh_marker.c") + + +def test_commands_default_marker_config_validates(): + cfg = commands.MarkerConfig() + assert cfg.path == commands.DEFAULT_MARKER + assert cfg.comm == "ring8-mesh-mark" + with pytest.raises(layouts.FabricError): + commands.MarkerConfig("relative/path")