115 lines
5.5 KiB
Python
115 lines
5.5 KiB
Python
#!/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'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 720" role="img" aria-labelledby="title desc">',
|
|
f'<title id="title">{esc(model["title"])}</title>',
|
|
f'<desc id="desc">{esc(model["description"])}</desc>',
|
|
'<rect width="1200" height="720" rx="18" fill="#f8fafc"/>']
|
|
for col, group in enumerate(groups):
|
|
x = 24 + col * 392
|
|
out += [f'<rect x="{x}" y="24" width="368" height="500" rx="14" fill="#fff" stroke="#cbd5e1"/>',
|
|
f'<text x="{x+18}" y="58" fill="#102a43" font-size="20" font-weight="700" font-family="sans-serif">{esc(group["title"])}</text>']
|
|
if group.get('profile_group'):
|
|
out.append(f'<text x="{x+18}" y="82" fill="#52606d" font-size="13" font-family="sans-serif">One profile active at a time</text>')
|
|
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'<rect x="{x+16}" y="{y}" width="336" height="80" rx="9" fill="#f1f5f9" stroke="#cbd5e1"/>',
|
|
f'<text x="{x+30}" y="{y+30}" fill="#102a43" font-size="16" font-weight="700" font-family="sans-serif">{esc(item["title"])}</text>',
|
|
f'<text x="{x+30}" y="{y+55}" fill="#334155" font-size="13" font-family="sans-serif">{esc(detail)}</text>']
|
|
out.append('<text x="42" y="562" fill="#102a43" font-size="18" font-weight="700" font-family="sans-serif">How the pieces connect</text>')
|
|
for i, flow in enumerate(model['flows']):
|
|
out.append(f'<text x="42" y="{594+i*30}" fill="#334155" font-size="15" font-family="sans-serif">{esc(flow)}</text>')
|
|
out.append('</svg>')
|
|
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')
|
|
args = parser.parse_args()
|
|
try:
|
|
content = render(json.loads(MODEL.read_text()), inventory())
|
|
if args.check:
|
|
if not OUTPUT.exists() or OUTPUT.read_text() != content:
|
|
raise ValueError('Architecture SVG is stale; run python3 scripts/render-website-architecture.py')
|
|
print('Website architecture diagram is current.')
|
|
else:
|
|
OUTPUT.write_text(content)
|
|
print(f'Wrote {OUTPUT.relative_to(ROOT)}')
|
|
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())
|