diff --git a/infra/arr-stack/docker-compose.yml b/infra/arr-stack/docker-compose.yml index f9fa00c..4b2408e 100644 --- a/infra/arr-stack/docker-compose.yml +++ b/infra/arr-stack/docker-compose.yml @@ -14,6 +14,13 @@ services: image: ${FLARESOLVERR_IMAGE:-ghcr.io/flaresolverr/flaresolverr:latest} container_name: ${FLARESOLVERR_CONTAINER_NAME:-arr-flaresolverr} restart: unless-stopped + labels: + homelab.heimdall.enabled: "true" + homelab.heimdall.title: FlareSolverr + homelab.heimdall.url: "http://{debian.lan_ip}:${FLARESOLVERR_PORT:-8191}/" + homelab.heimdall.description: Browser challenge solver service for ARR automation + homelab.heimdall.colour: "#64748b" + homelab.heimdall.class: FlareSolverr dns: - ${ARR_DNS_PRIMARY:-1.1.1.1} - ${ARR_DNS_SECONDARY:-8.8.8.8} @@ -145,6 +152,13 @@ services: <<: *linuxserver-common image: ${JELLYFIN_IMAGE:-lscr.io/linuxserver/jellyfin:latest} container_name: ${JELLYFIN_CONTAINER_NAME:-arr-jellyfin} + labels: + homelab.heimdall.enabled: "true" + homelab.heimdall.title: Jellyfin + homelab.heimdall.url: "http://{debian.lan_ip}:${JELLYFIN_PORT:-8096}/" + homelab.heimdall.description: Media streaming server + homelab.heimdall.colour: "#7c3aed" + homelab.heimdall.class: Jellyfin dns: - ${ARR_DNS_PRIMARY:-1.1.1.1} - ${ARR_DNS_SECONDARY:-8.8.8.8} diff --git a/infra/heimdall/README.md b/infra/heimdall/README.md index 49ec0ba..255115a 100644 --- a/infra/heimdall/README.md +++ b/infra/heimdall/README.md @@ -15,6 +15,33 @@ under `/data/homelab-heimdall/data/config`, and the dashboard is published on port `8082` before the OCI edge proxy exposes it as `https://heimdall.lab2025.duckdns.org/`. -`links.json` is the repo-managed dashboard seed. The sidecar container reruns -`seed-heimdall.py` periodically and upserts links into Heimdall's SQLite -database without deleting manually added tiles. +`links.json` is generated by `scripts/generate-heimdall-links`. The generator +discovers public DuckDNS services from `homelab.yml`, Kubernetes Ingress hosts +from `apps/**/*.yaml`, and opt-in local services from Compose labels or +Kubernetes annotations. `./jeannie deploy-heimdall` refreshes the generated file +before copying the stack to the Debian host. + +For Docker Compose services that should appear on the dashboard, add labels next +to the service definition: + +```yaml +labels: + homelab.heimdall.enabled: "true" + homelab.heimdall.title: Jellyfin + homelab.heimdall.url: "http://{debian.lan_ip}:${JELLYFIN_PORT:-8096}/" + homelab.heimdall.description: Media streaming server +``` + +For local-only Kubernetes services, add matching annotations and provide the +URL explicitly: + +```yaml +metadata: + annotations: + homelab.heimdall/enabled: "true" + homelab.heimdall/title: Example App + homelab.heimdall/url: "http://192.168.100.240/example/" +``` + +The sidecar container reruns `seed-heimdall.py` periodically and upserts links +into Heimdall's SQLite database without deleting manually added tiles. diff --git a/infra/heimdall/links.json b/infra/heimdall/links.json index d16c82b..351cd02 100644 --- a/infra/heimdall/links.json +++ b/infra/heimdall/links.json @@ -14,32 +14,25 @@ "class": "Demos" }, { - "title": "Service Catalog", - "url": "https://demos.lab2025.duckdns.org/homelab-catalog/", - "description": "Generated host, service, route, and runbook map from homelab.yml", - "colour": "#0891b2", - "class": "Catalog" + "title": "Heimdall", + "url": "https://heimdall.lab2025.duckdns.org/", + "description": "Homelab service dashboard", + "colour": "#7c3aed", + "class": "Heimdall" }, { - "title": "Provisioning PXE", - "url": "http://192.168.100.73:8088/", - "description": "PXE, preseed, and worker provisioning HTTP files", - "colour": "#0d9488", - "class": "Provisioning" + "title": "Matrix", + "url": "https://matrix.lab2025.duckdns.org/", + "description": "Matrix Synapse homeserver", + "colour": "#0f172a", + "class": "Matrix" }, { - "title": "PXE Rescue", - "url": "http://192.168.100.73:8088/rescue/", - "description": "Browser rescue toolkit for manual repair paths", - "colour": "#0f766e", - "class": "Rescue" - }, - { - "title": "Gitea", - "url": "https://lab2025.duckdns.org/git/", - "description": "External Git service on the Debian host", - "colour": "#609926", - "class": "Gitea" + "title": "Element", + "url": "https://element.lab2025.duckdns.org/", + "description": "Matrix web client", + "colour": "#0ea5e9", + "class": "Element" }, { "title": "Grafana", @@ -62,13 +55,6 @@ "colour": "#b91c1c", "class": "Alertmanager" }, - { - "title": "Blockchain Explorer", - "url": "http://192.168.100.73:8089/", - "description": "Optional local Ethereum devnet explorer", - "colour": "#9333ea", - "class": "Blockchain" - }, { "title": "Argo CD", "url": "https://argocd.lab2025.duckdns.org/", @@ -76,34 +62,6 @@ "colour": "#0ea5e9", "class": "ArgoCD" }, - { - "title": "Container Registry", - "url": "http://100.77.80.72:30500/v2/_catalog", - "description": "Local image registry catalog endpoint", - "colour": "#334155", - "class": "Docker" - }, - { - "title": "Heimdall", - "url": "https://heimdall.lab2025.duckdns.org/", - "description": "Homelab service dashboard", - "colour": "#7c3aed", - "class": "Heimdall" - }, - { - "title": "Pi-hole", - "url": "http://192.168.100.89:8081/admin/", - "description": "LAN DNS and ad blocking on the Raspberry Pi", - "colour": "#dc2626", - "class": "PiHole" - }, - { - "title": "Uptime Kuma", - "url": "http://192.168.100.89:3001/", - "description": "Service uptime checks on the Raspberry Pi", - "colour": "#16a34a", - "class": "UptimeKuma" - }, { "title": "n8n", "url": "https://n8n.lab2025.duckdns.org/", @@ -160,11 +118,74 @@ "colour": "#14b8a6", "class": "Maintainerr" }, + { + "title": "Service Catalog", + "url": "https://demos.lab2025.duckdns.org/homelab-catalog/", + "description": "Generated host, service, route, and runbook map from homelab.yml", + "colour": "#0891b2", + "class": "Catalog" + }, + { + "title": "Provisioning PXE", + "url": "http://192.168.100.73:8088/", + "description": "PXE, preseed, and worker provisioning HTTP files", + "colour": "#0d9488", + "class": "Provisioning" + }, + { + "title": "PXE Rescue", + "url": "http://192.168.100.73:8088/rescue/", + "description": "Browser rescue toolkit for manual repair paths", + "colour": "#0f766e", + "class": "Rescue" + }, + { + "title": "Gitea", + "url": "https://lab2025.duckdns.org/git/", + "description": "External Git service on the Debian host", + "colour": "#609926", + "class": "Gitea" + }, + { + "title": "Container Registry", + "url": "http://192.168.100.73:30500/v2/_catalog", + "description": "Local image registry catalog endpoint", + "colour": "#334155", + "class": "Docker" + }, + { + "title": "Pi-hole", + "url": "http://192.168.100.89:8081/admin/", + "description": "LAN DNS and ad blocking on the Raspberry Pi", + "colour": "#dc2626", + "class": "PiHole" + }, + { + "title": "Uptime Kuma", + "url": "http://192.168.100.89:3001/", + "description": "Service uptime checks on the Raspberry Pi", + "colour": "#16a34a", + "class": "UptimeKuma" + }, + { + "title": "Blockchain Explorer", + "url": "http://192.168.100.73:8089/", + "description": "Optional local Ethereum devnet explorer", + "colour": "#9333ea", + "class": "Blockchain" + }, { "title": "FlareSolverr", - "url": "https://flaresolverr.lab2025.duckdns.org/", + "url": "http://192.168.100.73:8191/", "description": "Browser challenge solver service for ARR automation", "colour": "#64748b", "class": "FlareSolverr" + }, + { + "title": "Jellyfin", + "url": "http://192.168.100.73:8096/", + "description": "Media streaming server", + "colour": "#7c3aed", + "class": "Jellyfin" } ] diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index b8a40d4..33f312d 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -3876,6 +3876,7 @@ deploy_heimdall() { local network="${HEIMDALL_NETWORK:-homelab-heimdall}" local install_docker="${LAB_HEIMDALL_INSTALL_DOCKER:-false}" local source_dir="${REPO_ROOT}/infra/heimdall" + local link_generator="${REPO_ROOT}/scripts/generate-heimdall-links" local elapsed=0 local value_name local value @@ -3894,6 +3895,10 @@ deploy_heimdall() { fi done + if [[ -x "${link_generator}" ]]; then + "${link_generator}" + fi + if [[ ! -s "${source_dir}/docker-compose.yml" || ! -s "${source_dir}/links.json" || ! -s "${source_dir}/seed-heimdall.py" ]]; then echo "Missing Heimdall source files in ${source_dir}" >&2 exit 1 diff --git a/scripts/generate-heimdall-links b/scripts/generate-heimdall-links new file mode 100755 index 0000000..c4d487d --- /dev/null +++ b/scripts/generate-heimdall-links @@ -0,0 +1,365 @@ +#!/usr/bin/env python3 +"""Generate Heimdall dashboard links from repo service discovery metadata.""" + +from __future__ import annotations + +import argparse +import json +import os +import pathlib +import re +from typing import Any + +REPO_ROOT = pathlib.Path(__file__).resolve().parents[1] +INVENTORY = REPO_ROOT / "homelab.yml" +OUTPUT = REPO_ROOT / "infra" / "heimdall" / "links.json" + +DEFAULT_COLOUR = "#334155" + +HOST_METADATA = { + "lab2025": ("Website", "Public portfolio website", "#0f766e", "Website"), + "demos": ("Demo Apps", "Static browser-side demo catalog", "#2563eb", "Demos"), + "heimdall": ("Heimdall", "Homelab service dashboard", "#7c3aed", "Heimdall"), + "matrix": ("Matrix", "Matrix Synapse homeserver", "#0f172a", "Matrix"), + "element": ("Element", "Matrix web client", "#0ea5e9", "Element"), + "grafana": ("Grafana", "Monitoring dashboards", "#f97316", "Grafana"), + "prometheus": ("Prometheus", "Prometheus query UI", "#dc2626", "Prometheus"), + "alertmanager": ("Alertmanager", "Alert routing and silences", "#b91c1c", "Alertmanager"), + "argocd": ("Argo CD", "GitOps application sync status", "#0ea5e9", "ArgoCD"), + "n8n": ("n8n", "Workflow automation for translation jobs and homelab tasks", "#ea4b71", "N8N"), + "prowlarr": ("Prowlarr", "Indexer management for the media automation stack", "#2563eb", "Prowlarr"), + "sonarr": ("Sonarr", "TV library automation", "#22c55e", "Sonarr"), + "radarr": ("Radarr", "Movie library automation", "#f59e0b", "Radarr"), + "qbittorrent": ("qBittorrent", "Torrent download client", "#3b82f6", "Qbittorrent"), + "kapowarr": ("Kapowarr", "Comics library automation", "#ef4444", "Kapowarr"), + "suwayomi": ("Suwayomi", "Manga server and scraper engine", "#8b5cf6", "Suwayomi"), + "maintainerr": ("Maintainerr", "Media list maintenance automation", "#14b8a6", "Maintainerr"), + "flaresolverr": ("FlareSolverr", "Browser challenge solver service for ARR automation", "#64748b", "FlareSolverr"), +} + + +def parse_inventory(path: pathlib.Path) -> dict[str, Any]: + values: dict[str, Any] = {} + stack: list[tuple[int, str]] = [] + current_list_path: str | None = None + pattern = re.compile(r"^(\s*)([A-Za-z_][A-Za-z0-9_]*):(?:\s*(.*?))?\s*$") + + with path.open(encoding="utf-8") as handle: + for raw_line in handle: + stripped = raw_line.strip() + if not stripped or stripped.startswith("#"): + continue + if stripped.startswith("- "): + if current_list_path: + if not isinstance(values.get(current_list_path), list): + values[current_list_path] = [] + values[current_list_path].append(clean_value(stripped[2:])) + continue + + match = pattern.match(raw_line.rstrip("\n")) + if not match: + current_list_path = None + continue + + indent = len(match.group(1)) + key = match.group(2) + value = (match.group(3) or "").strip() + while stack and stack[-1][0] >= indent: + stack.pop() + path_key = ".".join([item[1] for item in stack] + [key]) + if value == "": + stack.append((indent, key)) + values.setdefault(path_key, {}) + current_list_path = path_key + continue + values[path_key] = clean_value(value) + current_list_path = None + return values + + +def clean_value(value: str) -> str: + if " #" in value: + value = value.split(" #", 1)[0] + return value.strip().strip('"\'') + + +def value(values: dict[str, Any], path: str, default: str = "") -> str: + raw_value = values.get(path, default) + if isinstance(raw_value, list): + return ", ".join(str(item) for item in raw_value) + if isinstance(raw_value, dict): + return default + return str(raw_value) + + +def list_value(values: dict[str, Any], path: str) -> list[str]: + raw_value = values.get(path, []) + if isinstance(raw_value, list): + return [str(item) for item in raw_value] + return [] + + +def host_ip(values: dict[str, Any], host_name: str, default: str = "") -> str: + return value(values, f"hosts.{host_name}.lan_ip", default) + + +def expand_placeholders(text: str, values: dict[str, Any], compose_dir: pathlib.Path) -> str: + host_defaults = { + "debian": host_ip(values, "debian"), + "rpi4": host_ip(values, "rpi4"), + "traefik": value(values, "network.metallb.traefik_ip"), + } + for host_name, ip in host_defaults.items(): + text = text.replace(f"${{{host_name}.lan_ip}}", ip) + text = text.replace(f"{{{host_name}.lan_ip}}", ip) + text = text.replace("${compose_dir}", str(compose_dir)) + text = text.replace("{compose_dir}", str(compose_dir)) + + def replace_env(match: re.Match[str]) -> str: + name = match.group(1) + default = match.group(2) or "" + return os.environ.get(name, default) + + text = re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}", replace_env, text) + return text + + +def title_from_host(hostname: str, base_domain: str) -> str: + if hostname == base_domain: + return HOST_METADATA["lab2025"][0] + prefix = hostname.removesuffix(f".{base_domain}").split(".")[-1] + return HOST_METADATA.get(prefix, (prefix.replace("-", " ").title(), "", DEFAULT_COLOUR, prefix.title()))[0] + + +def link(title: str, url: str, description: str = "", colour: str = DEFAULT_COLOUR, class_name: str = "") -> dict[str, str]: + item = { + "title": title, + "url": url, + "description": description, + "colour": colour, + "class": class_name or re.sub(r"[^A-Za-z0-9]", "", title), + } + return item + + +def public_links(values: dict[str, Any]) -> list[dict[str, str]]: + base_domain = value(values, "domain.base") + hosts = [base_domain, *list_value(values, "domain.subdomains")] + links: list[dict[str, str]] = [] + for hostname in hosts: + if not hostname: + continue + prefix = "lab2025" if hostname == base_domain else hostname.removesuffix(f".{base_domain}").split(".")[-1] + title, description, colour, class_name = HOST_METADATA.get( + prefix, + (title_from_host(hostname, base_domain), "Public service exposed through DuckDNS", DEFAULT_COLOUR, prefix.title()), + ) + links.append(link(title, f"https://{hostname}/", description, colour, class_name)) + return links + + +def inventory_links(values: dict[str, Any]) -> list[dict[str, str]]: + debian_ip = host_ip(values, "debian", "192.168.100.73") + rpi_ip = host_ip(values, "rpi4", "192.168.100.89") + registry = value(values, "services.local_registry.endpoint", f"{debian_ip}:30500") + return [ + link( + "Service Catalog", + f"https://demos.{value(values, 'domain.base')}/homelab-catalog/", + "Generated host, service, route, and runbook map from homelab.yml", + "#0891b2", + "Catalog", + ), + link( + "Provisioning PXE", + f"http://{debian_ip}:{value(values, 'services.provisioning.http_port', '8088')}/", + "PXE, preseed, and worker provisioning HTTP files", + "#0d9488", + "Provisioning", + ), + link( + "PXE Rescue", + value(values, "services.provisioning.rescue_url", f"http://{debian_ip}:8088/rescue/"), + "Browser rescue toolkit for manual repair paths", + "#0f766e", + "Rescue", + ), + link( + "Gitea", + value(values, "services.gitea.root_url"), + "External Git service on the Debian host", + "#609926", + "Gitea", + ), + link( + "Container Registry", + f"http://{registry}/v2/_catalog", + "Local image registry catalog endpoint", + "#334155", + "Docker", + ), + link( + "Pi-hole", + f"http://{rpi_ip}:{value(values, 'services.rpi_dns.pihole_web_port', '8081')}/admin/", + "LAN DNS and ad blocking on the Raspberry Pi", + "#dc2626", + "PiHole", + ), + link( + "Uptime Kuma", + f"http://{rpi_ip}:{value(values, 'services.rpi_dns.uptime_kuma_port', '3001')}/", + "Service uptime checks on the Raspberry Pi", + "#16a34a", + "UptimeKuma", + ), + link( + "Blockchain Explorer", + f"http://{debian_ip}:8089/", + "Optional local Ethereum devnet explorer", + "#9333ea", + "Blockchain", + ), + ] + + +def parse_labeled_block(block: str, prefix: str) -> dict[str, str]: + labels: dict[str, str] = {} + for raw_line in block.splitlines(): + line = raw_line.strip() + if line.startswith("-"): + line = line[1:].strip().strip('"\'') + if line.startswith(prefix) and "=" in line: + key, value_text = line.split("=", 1) + labels[key.removeprefix(prefix)] = clean_value(value_text) + continue + if line.startswith(prefix) and ":" in line: + key, value_text = line.split(":", 1) + labels[key.removeprefix(prefix)] = clean_value(value_text) + return labels + + +def compose_links(values: dict[str, Any]) -> list[dict[str, str]]: + links: list[dict[str, str]] = [] + for compose_path in sorted((REPO_ROOT / "infra").glob("*/docker-compose.yml")): + text = compose_path.read_text(encoding="utf-8") + for labels in find_compose_labels(text): + if labels.get("enabled", "false").lower() != "true": + continue + title = labels.get("title") + url = labels.get("url") + if not title or not url: + continue + links.append( + link( + title, + expand_placeholders(url, values, compose_path.parent), + labels.get("description", "Docker Compose service"), + labels.get("colour", DEFAULT_COLOUR), + labels.get("class", title), + ) + ) + return links + + +def find_compose_labels(text: str) -> list[dict[str, str]]: + labels: list[dict[str, str]] = [] + lines = text.splitlines() + service_indexes: list[int] = [] + for index, line_text in enumerate(lines): + if re.match(r"^ [A-Za-z0-9_.-]+:\s*$", line_text): + service_indexes.append(index) + service_indexes.append(len(lines)) + for start, end in zip(service_indexes, service_indexes[1:]): + block = "\n".join(lines[start:end]) + found = parse_labeled_block(block, "homelab.heimdall.") + if found: + labels.append(found) + return labels + + +def kubernetes_links(values: dict[str, Any]) -> list[dict[str, str]]: + links: list[dict[str, str]] = [] + base_domain = value(values, "domain.base") + for manifest_path in sorted((REPO_ROOT / "apps").glob("**/*.yaml")): + text = manifest_path.read_text(encoding="utf-8") + links.extend(annotated_manifest_links(text, values, manifest_path.parent)) + for hostname in re.findall(r"\bhost:\s*([A-Za-z0-9_.-]+)\s*", text): + prefix = hostname.removesuffix(f".{base_domain}").split(".")[-1] + title, description, colour, class_name = HOST_METADATA.get( + prefix, + (title_from_host(hostname, base_domain), "Kubernetes Ingress exposed through DuckDNS", DEFAULT_COLOUR, prefix.title()), + ) + links.append(link(title, f"https://{hostname}/", description, colour, class_name)) + return links + + +def annotated_manifest_links(text: str, values: dict[str, Any], manifest_dir: pathlib.Path) -> list[dict[str, str]]: + links: list[dict[str, str]] = [] + for document in re.split(r"^---\s*$", text, flags=re.MULTILINE): + labels = parse_labeled_block(document.replace("homelab.heimdall/", "homelab.heimdall."), "homelab.heimdall.") + if labels.get("enabled", "false").lower() != "true": + continue + title = labels.get("title") + url = labels.get("url") + if not title or not url: + continue + links.append( + link( + title, + expand_placeholders(url, values, manifest_dir), + labels.get("description", "Kubernetes service"), + labels.get("colour", DEFAULT_COLOUR), + labels.get("class", title), + ) + ) + return links + + +def merge_links(*groups: list[dict[str, str]]) -> list[dict[str, str]]: + merged: list[dict[str, str]] = [] + seen_urls: set[str] = set() + seen_titles: set[str] = set() + for group in groups: + for item in group: + title = item["title"].strip() + url = item["url"].strip() + if not title or not url or url in seen_urls or title.lower() in seen_titles: + continue + item["title"] = title + item["url"] = url + merged.append(item) + seen_urls.add(url) + seen_titles.add(title.lower()) + return merged + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=pathlib.Path, default=OUTPUT) + parser.add_argument("--check", action="store_true", help="fail if the output file is stale") + args = parser.parse_args() + + values = parse_inventory(INVENTORY) + generated = merge_links( + public_links(values), + inventory_links(values), + kubernetes_links(values), + compose_links(values), + ) + rendered = json.dumps(generated, indent=2) + "\n" + + if args.check: + current = args.output.read_text(encoding="utf-8") if args.output.exists() else "" + if current != rendered: + print(f"{args.output} is stale; run scripts/generate-heimdall-links", flush=True) + return 1 + return 0 + + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(rendered, encoding="utf-8") + print(f"Generated {args.output.relative_to(REPO_ROOT)} with {len(generated)} links") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())