Repository navigation
Expand file tree
/
Copy pathgen_kind_discover_params
More file actions
executable file
·128 lines (100 loc) · 5.45 KB
/
Copy pathgen_kind_discover_params
File metadata and controls
executable file
·128 lines (100 loc) · 5.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#!/usr/bin/env python3
"""Render the discovery execution parameters for the Kubernetes flavour (stdlib-only, run on the host).
Writes `generated/<scenario>/kind/discover-params.json`: the same document shape
`gen_clab_topology` commits for the containerlab flavour, but addressed at the
pods instead of the `lab-net` bridge. Only the addresses differ, so the device
set, the credentials and the layout all come from the existing generators
rather than from a second definition here.
A device's address in this flavour is its **Service ClusterIP**, which is why
this generator has to talk to the cluster at all: KIND assigns those IPs, and
assigns a fresh set every time the namespace is recreated, so they can be read
but never cached or committed. Two properties follow from them and are the
reason this file exists rather than a hand-written parameter file:
* **Every device is its own /32, and a summarising CIDR is forbidden.** The
ClusterIPs are scattered across the cluster's service range, so the only
prefix covering all ten would be the whole range. Discovery expands a CIDR
into one SSH probe per address, and the block's target guard is disabled —
a /16 would launch 65534 of them.
* **A `*.svc.cluster.local` name cannot be substituted for the address.** The
CMS stores a device's address in a Postgres `inet` column, which rejects a
hostname outright rather than resolving it. In-cluster DNS is how a human
reaches a device; discovery needs the literal IP.
The output is deterministic for a fixed cluster state: devices are emitted in
the topology's declaration order, not the order kubectl happens to list the
Services.
"""
from __future__ import annotations
import argparse
import json
import pathlib
import subprocess
import sys
import labscripts
DEFAULT_NAMESPACE = "neops-lab"
# A Service with no ClusterIP of its own (`clusterIP: None`) is headless; the
# API reports the absence as this string, not as a missing field.
HEADLESS = "None"
gen_kind_manifests = labscripts.load("gen_kind_manifests")
gen_clab_topology = labscripts.load("gen_clab_topology")
# The Kubernetes flavour renders FRR devices only; the same helper that decides
# which pods exist decides which addresses are asked for.
frr_devices = gen_kind_manifests.frr_devices
load_topology = gen_kind_manifests.gen_device_configs.load_topology
# The lab logins, scoped to their platform, and the committed compact layout.
_credentials = gen_clab_topology._credentials
_dump_discover_params = gen_clab_topology._dump_discover_params
def cluster_ips(namespace: str) -> dict:
"""Return `{service name: ClusterIP}` for every Service in a namespace."""
argv = ["kubectl", "-n", namespace, "get", "svc", "-o", "json"]
try:
result = subprocess.run(argv, capture_output=True, text=True, check=True)
except FileNotFoundError as exc:
raise SystemExit("kubectl not found in PATH") from exc
except subprocess.CalledProcessError as exc:
raise SystemExit(f"kubectl failed ({exc.returncode}): {(exc.stderr or '').strip()}") from exc
addresses = {}
for service in json.loads(result.stdout)["items"]:
address = service["spec"].get("clusterIP")
if address and address != HEADLESS:
addresses[service["metadata"]["name"]] = address
return addresses
def device_targets(devices: dict, addresses: dict) -> list:
"""Return one `/32` subnet entry per device, in declaration order."""
missing = [host for host in devices if host not in addresses]
if missing:
raise SystemExit(
"no Service ClusterIP for: "
+ ", ".join(missing)
+ "\nThe devices are not deployed in this namespace — run `make kind-lab-up` first."
)
return [{"cidr": f"{addresses[host]}/32", "platform": dev["vendor"]} for host, dev in devices.items()]
def render_discover_params(devices: dict, addresses: dict) -> dict:
"""Render the parameters document: per-host targets plus one login per vendor."""
return {"subnets": device_targets(devices, addresses), "credentials": _credentials(devices, scoped=True)}
def parse_args(argv: list) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Render the discovery parameters for the Kubernetes lab devices.")
parser.add_argument("--scenario", help="scenario to render; defaults to $SCENARIO")
parser.add_argument("--namespace", default=DEFAULT_NAMESPACE, help="lab namespace (default: %(default)s)")
parser.add_argument(
"--output",
type=pathlib.Path,
default=None,
help="parameters path (default: generated/<scenario>/kind/discover-params.json)",
)
return parser.parse_args(argv)
def main(argv: list | None = None) -> int:
args = parse_args(sys.argv[1:] if argv is None else argv)
resolver = gen_kind_manifests.gen_device_configs.resolve_scenario
scenario = resolver.scenario_name(args.scenario)
output = args.output or resolver.output_dir(scenario) / "kind" / "discover-params.json"
devices = frr_devices(load_topology(scenario))
if not devices:
print(f"scenario {scenario!r} has no frr devices to discover", file=sys.stderr)
return 1
params = render_discover_params(devices, cluster_ips(args.namespace))
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(_dump_discover_params(params))
print(f"generated {output}: {len(params['subnets'])} /32 targets from namespace {args.namespace}")
return 0
if __name__ == "__main__":
sys.exit(main())