#!/usr/bin/env python3 """Generate the public blog diagram from a curated model and inventory.""" import argparse import html import json import subprocess import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent MODEL = ROOT / 'apps/website/architecture/model.json' OUTPUT = ROOT / 'apps/website/architecture/homelab.svg' def inventory(): path = ROOT / 'homelab.yml' try: import yaml except ImportError: try: result = subprocess.run(['ruby', '-ryaml', '-rjson', '-e', 'puts JSON.generate(YAML.safe_load_file(ARGV[0]))', str(path)], capture_output=True, text=True, check=True) return json.loads(result.stdout) except (OSError, subprocess.CalledProcessError, json.JSONDecodeError) as exc: raise ValueError('Install PyYAML to read homelab.yml') from exc return yaml.safe_load(path.read_text()) def lookup(data, path): for part in path.split('.'): if not isinstance(data, dict) or part not in data: raise ValueError(f'Inventory reference does not exist: {path}') data = data[part] return data def render(model, data): groups = model['groups'] if len(groups) != 3: raise ValueError('Diagram requires exactly three groups') declared_profiles = [] host_labels = {'debian': 'Debian host', 'rpi4': 'Raspberry Pi', 'opi5_pimox': 'Orange Pi host', 'kubernetes': 'Kubernetes'} for group in groups: if len(group['items']) > 4: raise ValueError('Each group can contain at most four items') for item in group['items']: if item.get('inventory'): value = lookup(data, item['inventory']) if item['inventory'].endswith('.host') and value not in host_labels: raise ValueError(f'Unknown public host label for {item["inventory"]}; review diagram') for ref in item.get('also_on_same_host', []): if lookup(data, ref) != value: raise ValueError(f'{ref} moved to a different host; review diagram') if item.get('profile'): profile = item['profile'] runtime = lookup(data, f'cluster.profiles.{profile}.runtime') if runtime != item['runtime']: raise ValueError(f'Profile {profile} runtime changed; review diagram') declared_profiles.append(profile) profiles = lookup(data, 'cluster.profiles') if not isinstance(profiles, dict) or sorted(declared_profiles) != sorted(profiles): raise ValueError('Cluster profiles changed; review the public architecture model') esc = lambda value: html.escape(str(value), quote=True) out = [f'', f'{esc(model["title"])}', f'{esc(model["description"])}', ''] for col, group in enumerate(groups): x = 24 + col * 392 out += [f'', f'{esc(group["title"])}'] if group.get('profile_group'): out.append(f'One profile active at a time') for row, item in enumerate(group['items']): y = 100 + row * 98 ref = item.get('inventory', '') detail = item['detail'] if ref.endswith('.host'): detail += ' ยท ' + host_labels[lookup(data, ref)] if len(detail) > 45: raise ValueError(f'Diagram detail is too long: {item["title"]}') out += [f'', f'{esc(item["title"])}', f'{esc(detail)}'] out.append('How the pieces connect') for i, flow in enumerate(model['flows']): out.append(f'{esc(flow)}') out.append('') return '\n'.join(out) + '\n' def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--check', action='store_true', help='fail if the committed SVG is stale') parser.add_argument('--output', type=Path, default=OUTPUT, help='write the generated SVG to this path') args = parser.parse_args() try: content = render(json.loads(MODEL.read_text()), inventory()) if args.check: if not args.output.exists() or args.output.read_text(encoding='utf-8') != content: raise ValueError('Architecture SVG is stale; run python3 scripts/render-website-architecture.py') print('Website architecture diagram is current.') else: args.output.write_text(content, encoding='utf-8') print(f'Wrote {args.output}') except (ValueError, KeyError, TypeError, OSError, json.JSONDecodeError) as exc: print(f'Architecture diagram: {exc}', file=sys.stderr) return 1 return 0 if __name__ == '__main__': sys.exit(main())