75 lines
3.4 KiB
Python
75 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Probe host BTF and optionally label eligible Tetragon nodes."""
|
|
|
|
import argparse
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
|
|
import yaml
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
LABEL = "homelab.dev/kernel-btf"
|
|
|
|
|
|
def run(command):
|
|
return subprocess.run(command, check=True, text=True, capture_output=True, timeout=30).stdout.strip()
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--label-nodes", action="store_true")
|
|
args = parser.parse_args()
|
|
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
|
|
profile = os.environ.get("LAB_CLUSTER_PROFILE") or inventory["cluster"]["active_profile"]
|
|
control = inventory["cluster"]["profiles"][profile]["control_plane"]
|
|
spec = importlib.util.spec_from_file_location("tetragon_cluster_context", REPO / "scripts/cluster-context.py")
|
|
context = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(context)
|
|
ctx = context.Context(profile)
|
|
ctx.check()
|
|
credentials = {control["lan_ip"]: (control["user"], control["ssh_key_path"])}
|
|
for address in inventory["cluster"]["profiles"]["pimox"]["pimox"]["worker_static_ips"].split():
|
|
credentials.setdefault(address, (control["user"], control["ssh_key_path"]))
|
|
workers = REPO / ".lab/pimox-workers.tsv"
|
|
if workers.is_file() and profile != "k3s":
|
|
for line in workers.read_text().splitlines():
|
|
fields = line.split("\t")
|
|
if len(fields) == 5:
|
|
_, address, user, _, key = fields
|
|
credentials[address] = (user, key)
|
|
nodes = json.loads(run(ctx.client() + ["--request-timeout=15s", "get", "nodes", "-o", "json"]))["items"]
|
|
results = []
|
|
for node in nodes:
|
|
name = node["metadata"]["name"]
|
|
addresses = [a["address"] for a in node["status"]["addresses"] if a["type"] == "InternalIP" and a["address"] in credentials]
|
|
if len(addresses) != 1:
|
|
raise RuntimeError(f"{name}: no unique declared SSH target for kernel capability probe")
|
|
address = addresses[0]
|
|
user, key = credentials[address]
|
|
result = run(["ssh", "-T", "-i", key, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
|
|
"-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new", f"{user}@{address}",
|
|
"if test -s /sys/kernel/btf/vmlinux; then echo true; else echo false; fi"])
|
|
if result not in ("true", "false"):
|
|
raise RuntimeError(f"{name}: ambiguous BTF probe result")
|
|
results.append((node, result))
|
|
for node, result in results:
|
|
name = node["metadata"]["name"]
|
|
if args.label_nodes and node["metadata"].get("labels", {}).get(LABEL) != result:
|
|
run(ctx.client() + ["--request-timeout=15s", "label", "node", name, f"{LABEL}={result}", "--overwrite"])
|
|
print(f"Tetragon BTF capability: {name}={result}", file=sys.stderr)
|
|
enabled = any(result == "true" for _, result in results)
|
|
if not enabled:
|
|
print("Tetragon agent disabled: no cluster node exposes host kernel BTF. Runtime tracing is unavailable.", file=sys.stderr)
|
|
print("true" if enabled else "false")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (OSError, RuntimeError, KeyError, ValueError, subprocess.SubprocessError) as error:
|
|
raise SystemExit(f"Tetragon capability detection refused: {error}")
|