#!/usr/bin/env python3 """Jeannie-managed migration and refresh of the Debian monitoring backends.""" import argparse import base64 import configparser import fcntl import gzip import hashlib import ipaddress import json import os from pathlib import Path import shlex import shutil import re import sqlite3 import subprocess import sys import tarfile import tempfile import time import urllib.error import urllib.parse import urllib.request import yaml PROM = 'prometheus-stack-kube-prom-prometheus' ALERT = 'prometheus-stack-kube-prom-alertmanager' GRAFANA = 'prometheus-stack-grafana' PORTS = {PROM: 19090, ALERT: 19093, GRAFANA: 13000} def run(args, **kwargs): result = subprocess.run([str(a) for a in args], capture_output=True, **kwargs) if result.returncode: # Commands can contain secrets or tokens; never include argv/stdout. raise RuntimeError(f'{Path(str(args[0])).name} failed: ' + result.stderr.decode(errors='replace')[-1200:]) return result.stdout def write(path, content, mode=0o640): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + '.new') temporary.write_bytes(content.encode() if isinstance(content, str) else content) temporary.chmod(mode) temporary.replace(path) def external_config(config, api, services=None): """Retain Operator discovery/relabeling and rules; use external API auth.""" rendered = json.dumps(config).replace('$(SHARD)', '0').replace('$(POD_NAME)', 'debian-prometheus').replace('$(POD_NAMESPACE)', 'monitoring') if re.search(r'\$\([A-Z_]+\)', rendered): raise RuntimeError('Unknown Operator configuration substitution; refusing incomplete discovery') config = json.loads(rendered) for job in config.get('scrape_configs', []): for group in job.get('static_configs', []): group['targets'] = [service_url('http://' + target, services or {}).removeprefix('http://') for target in group.get('targets', [])] for sd in job.get('kubernetes_sd_configs', []): sd.update(api_server=api, authorization={'credentials_file': '/var/run/secrets/kubernetes.io/serviceaccount/token'}, tls_config={'ca_file': '/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'}) config.setdefault('alerting', {})['alertmanagers'] = [ {'static_configs': [{'targets': ['127.0.0.1:19093']}], 'api_version': 'v2'}] return config def service_url(url, services): parsed = urllib.parse.urlsplit(url) host = parsed.hostname or '' bits = host.split('.') if len(bits) >= 2 and (bits[0], bits[1]) in services: name, namespace = bits[:2] if name in PORTS: address, port = '127.0.0.1', PORTS[name] else: address, port = services[(name, namespace)], parsed.port if address and address != 'None': return urllib.parse.urlunsplit(parsed._replace(netloc=f'{address}:{port}' if port else address)) return url def validate_dex_client(config, secret, callback): clients = [c for c in config.get('staticClients', []) if c.get('id') == 'grafana'] if len(clients) != 1 or clients[0].get('secret') != secret or callback not in clients[0].get('redirectURIs', []): raise RuntimeError('Deployed Dex client secret or callback does not match Grafana') class Monitoring: def __init__(self, root): self.root = Path(root) self.settings = json.loads((self.root / 'settings.json').read_text()) self.k = ['kubectl', '--kubeconfig', self.settings['kubeconfig'], '--request-timeout=15s'] def get(self, resource, name=None, namespace='monitoring', labels=None): args = self.k + ['get', resource] + (['-A'] if namespace == '*' else ['-n', namespace] if namespace else []) if name: args.append(name) if labels: args += ['-l', labels] return json.loads(run(args + ['-o', 'json'])) def verify_identity(self): uid = self.get('namespace', 'kube-system', None)['metadata']['uid'] if uid != self.settings['cluster_uid']: raise RuntimeError('Selected cluster identity changed; refusing monitoring reconciliation') def compose(self, *args): return run(['sudo', '-n', 'docker', 'compose', '-f', self.root / 'compose.yaml', *args]) def routes(self): for network in self.settings['networks']: subnet = ipaddress.ip_network(network) if (not subnet.is_private or subnet.prefixlen < 8 or ipaddress.ip_address(self.settings['debian_ip']) in subnet or ipaddress.ip_address(self.settings['node_ip']) in subnet): raise RuntimeError('Refusing a cluster route that could replace host/LAN connectivity') for network in self.settings['networks']: run(['sudo', '-n', 'ip', 'route', 'replace', network, 'via', self.settings['node_ip']]) def refresh(self, reload=True): protected = [self.root / 'config/prometheus', self.root / 'config/alertmanager'] previous = {path: path.read_bytes() for directory in protected for path in directory.rglob('*') if path.is_file()} try: self._refresh(reload) except Exception: for directory in protected: for path in directory.rglob('*'): if path.is_file() and path not in previous: path.unlink() for path, content in previous.items(): write(path, content, 0o644) raise def _refresh(self, reload=True): self.verify_identity() self.routes() root = self.root / 'config' config_secret = self.get('secret', 'prometheus-' + PROM) services = {(s['metadata']['name'], s['metadata']['namespace']): s['spec'].get('clusterIP') for s in self.get('services', namespace='*')['items']} config = yaml.safe_load(gzip.decompress(base64.b64decode(config_secret['data']['prometheus.yaml.gz']))) config = external_config(config, self.settings['api'], services) token = run(self.k + ['-n', 'monitoring', 'create', 'token', PROM, '--duration=1h']).strip() write(root / 'k8s/token', token, 0o644) write(root / 'k8s/ca.crt', base64.b64decode(self.settings['ca']), 0o644) cms = self.get('configmaps')['items'] rule_count = 0 rule_files = set() for cm in cms: name = cm['metadata']['name'] if name.startswith('prometheus-' + PROM + '-rulefiles-'): for filename, value in cm.get('data', {}).items(): if Path(filename).name != filename: raise RuntimeError('Invalid rule filename') destination = root / 'prometheus/rules' / name / filename rule_files.add(destination) write(destination, value, 0o644) rule_count += 1 for stale in (root / 'prometheus/rules').rglob('*'): if stale.is_file() and stale not in rule_files: stale.unlink() write(root / 'prometheus/prometheus.yaml', yaml.safe_dump(config), 0o644) secret = self.get('secret', 'alertmanager-' + ALERT) write(root / 'alertmanager/alertmanager.yaml', base64.b64decode(secret['data']['alertmanager.yaml']), 0o644) datasource_count = 0 datasource_documents = [] datasource_files = set() for cm in cms: if cm['metadata'].get('labels', {}).get('grafana_datasource') != '1': continue for filename, value in cm.get('data', {}).items(): document = yaml.safe_load(value) for ds in document.get('datasources', []): if isinstance(ds.get('url'), str): ds['url'] = service_url(ds['url'], services) datasource_count += 1 datasource_documents.append(document) destination = root / 'grafana/provisioning/datasources' / (cm['metadata']['name'] + '-' + Path(filename).name) datasource_files.add(destination) write(destination, yaml.safe_dump(document), 0o644) for stale in (root / 'grafana/provisioning/datasources').glob('*'): if stale.is_file() and stale not in datasource_files: stale.unlink() dashboards = 0 dashboard_files = set() for cm in cms: if cm['metadata'].get('labels', {}).get('grafana_dashboard') != '1': continue folder = cm['metadata'].get('annotations', {}).get('grafana_folder', 'General') # A ConfigMap folder is display data, not a filesystem path. folder = folder.replace('/', '_').replace('..', '_') for filename, value in cm.get('data', {}).items(): json.loads(value) destination = root / 'grafana/dashboards' / folder / (cm['metadata']['name'] + '-' + Path(filename).name) dashboard_files.add(destination) write(destination, value, 0o644) dashboards += 1 for stale in (root / 'grafana/dashboards').rglob('*.json'): if stale not in dashboard_files: stale.unlink() write(root / 'grafana/provisioning/dashboards/jeannie.yaml', yaml.safe_dump({ 'apiVersion': 1, 'providers': [{'name': 'Jeannie', 'orgId': 1, 'type': 'file', 'disableDeletion': True, 'allowUiUpdates': True, 'updateIntervalSeconds': 30, 'options': {'path': '/etc/grafana/dashboards', 'foldersFromFilesStructure': True}}]}), 0o644) ini = self.get('configmap', GRAFANA)['data']['grafana.ini'] oauth = self.get('secret', 'grafana-dex-oauth')['data']['GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET'] parsed_ini = configparser.ConfigParser(interpolation=None) parsed_ini.read_string(ini) deployed_dex = yaml.safe_load(run(['sudo', '-n', 'cat', self.settings.get('dex_config', '/data/homelab-dex/config.yaml')])) validate_dex_client(deployed_dex, base64.b64decode(oauth).decode(), parsed_ini.get('server', 'root_url').rstrip('/') + '/login/generic_oauth') write(root / 'grafana/grafana.ini', ini, 0o644) fingerprint = hashlib.sha256((ini + oauth + json.dumps(datasource_documents, sort_keys=True)).encode()).hexdigest() fingerprint_path = self.root / '.grafana-config.sha256' previous_fingerprint = fingerprint_path.read_text() if fingerprint_path.exists() else '' write(root / 'grafana/secrets/client-secret', base64.b64decode(oauth), 0o600) run(['sudo', '-n', 'chown', '472:472', root / 'grafana/secrets/client-secret']) if not datasource_count or not dashboards or not rule_count: raise RuntimeError('Refusing empty dashboards, datasources or rules export') for directory in [root, *root.rglob('*')]: if directory.is_dir(): directory.chmod(0o755) self.compose('run', '--rm', '--no-deps', '--entrypoint', 'promtool', 'prometheus', 'check', 'config', '/etc/prometheus/prometheus.yaml') self.compose('run', '--rm', '--no-deps', '--entrypoint', 'amtool', 'alertmanager', 'check-config', '/etc/alertmanager/alertmanager.yaml') if reload: for port in (19090, 19093): self.http(f'http://127.0.0.1:{port}/-/reload', method='POST') if fingerprint != previous_fingerprint: self.compose('restart', 'grafana') write(fingerprint_path, fingerprint) print(json.dumps({'dashboards': dashboards, 'datasources': datasource_count, 'rule_files': rule_count})) @staticmethod def http(url, method='GET', headers=None): with urllib.request.urlopen(urllib.request.Request(url, method=method, headers=headers or {}), timeout=15) as response: return response.read() def dashboard_manifest(self): manifest = self.root / 'backup/grafana-dashboards.json' if not manifest.exists(): with tempfile.TemporaryDirectory(dir=self.root) as directory: with tarfile.open(self.root / 'backup/grafana.tar.gz') as archive: for member in archive: name = member.name.removeprefix('./') if name in ('grafana.db', 'grafana.db-wal', 'grafana.db-shm') and member.isfile(): with archive.extractfile(member) as source, (Path(directory) / name).open('wb') as target: shutil.copyfileobj(source, target) database = sqlite3.connect((Path(directory) / 'grafana.db').as_uri() + '?mode=ro', uri=True) original = [row[0] for row in database.execute('select uid from dashboard where is_folder=0')] database.close() write(manifest, json.dumps(original)) return set(json.loads(manifest.read_text())) def inventory_volumes(self): result = {} for pvc in self.get('pvc')['items']: name = pvc['metadata']['name'] role = ('grafana' if name == 'storage-' + GRAFANA + '-0' else 'prometheus' if name.startswith('prometheus-' + PROM + '-db-') else 'alertmanager' if name.startswith('alertmanager-' + ALERT + '-db-') else None) if not role: continue pv = self.get('pv', pvc['spec']['volumeName'], None) ref = pv['spec']['claimRef'] if ref['uid'] != pvc['metadata']['uid'] or ref['namespace'] != 'monitoring': raise RuntimeError('PVC/PV identity mismatch') path = pv['spec'].get('local', {}).get('path', '') if not path.startswith('/data/') or '..' in path.split('/'): raise RuntimeError('Only identified /data local volumes can be migrated') result[role] = {'pvc': name, 'uid': pvc['metadata']['uid'], 'pv': pv['metadata']['name'], 'path': path} if set(result) != {'grafana', 'prometheus', 'alertmanager'}: raise RuntimeError('Expected exactly the three existing monitoring volumes') return result def helm_external(self): values = {'prometheus': {'prometheusSpec': {'replicas': 0}}, 'alertmanager': {'alertmanagerSpec': {'replicas': 0}}, 'grafana': {'replicas': 0}} write(self.root / 'external-values.yaml', yaml.safe_dump(values)) release = json.loads(run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', 'list', '--filter', '^prometheus-stack$', '-o', 'json']))[0] version = release['chart'].removeprefix('kube-prometheus-stack-') for name in PORTS: service = self.get('service', name) if service['metadata'].get('annotations', {}).get('meta.helm.sh/release-name') != 'prometheus-stack': raise RuntimeError('Refusing to adopt endpoints of a service not owned by this Helm release') existing = run(self.k + ['-n', 'monitoring', 'get', 'endpoints', name, '--ignore-not-found', '-o', 'json']) if existing.strip(): run(self.k + ['-n', 'monitoring', 'annotate', 'endpoints', name, 'meta.helm.sh/release-name=prometheus-stack', 'meta.helm.sh/release-namespace=monitoring', '--overwrite']) run(self.k + ['-n', 'monitoring', 'label', 'endpoints', name, 'app.kubernetes.io/managed-by=Helm', '--overwrite']) renderer = str(self.root / 'postrender.py') environment = os.environ.copy() if run(['helm', 'version', '--short']).decode().startswith('v4.'): plugin = self.root / 'helm-plugins/jeannie-monitoring' write(plugin / 'plugin.yaml', yaml.safe_dump({'apiVersion': 'v1', 'type': 'postrenderer/v1', 'name': 'jeannie-monitoring', 'version': '1.0.0', 'runtime': 'subprocess', 'runtimeConfig': {'platformCommand': [{'command': renderer}]}})) environment['HELM_PLUGINS'] = str(plugin.parent) renderer = 'jeannie-monitoring' run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', 'upgrade', 'prometheus-stack', 'kube-prometheus-stack', '--repo', 'https://prometheus-community.github.io/helm-charts', '--version', version, '--reuse-values', '-f', self.root / 'external-values.yaml', '--post-renderer', renderer, '--post-renderer-args', self.settings['debian_ip'], '--timeout', '10m'], env=environment) def migrate(self): self.verify_identity() run(['sudo', '-n', 'install', '-d', '-m', '750', '-o', '472', '-g', '472', self.root / 'data/grafana-search']) if (self.root / 'migration-complete.json').exists(): self.compose('up', '-d') self.wait_for(self.http_ready) self.refresh() self.wait_for(self.validate) self.install_timer() return volumes = self.inventory_volumes() for role in volumes: (self.root / 'data' / role).mkdir(parents=True, exist_ok=True) backup = self.root / 'backup' backup.mkdir(exist_ok=True) write(backup / 'volumes.json', json.dumps(volumes, indent=2)) if not (backup / 'helm-values.yaml').exists(): write(backup / 'helm-values.yaml', run(['helm', '--kubeconfig', self.settings['kubeconfig'], '-n', 'monitoring', 'get', 'values', 'prometheus-stack', '-o', 'yaml'])) self.compose('pull') self.refresh(reload=False) print('Configuration validated. Stopping only the three in-cluster monitoring backends.', flush=True) self.helm_external() deadline = time.monotonic() + 180 while True: remaining = [p['metadata']['name'] for p in self.get('pods')['items'] if p['metadata']['name'] == GRAFANA + '-0' or p['metadata']['name'].startswith(('prometheus-' + PROM + '-', 'alertmanager-' + ALERT + '-'))] if not remaining: break if time.monotonic() > deadline: raise RuntimeError('Old monitoring pods did not stop normally; refusing data copy') time.sleep(3) for role, volume in volumes.items(): archive = backup / (role + '.tar.gz') if not archive.exists(): print('Backing up and transferring existing ' + role + ' data...', flush=True) remote = 'findmnt -rn -M /data -o OPTIONS | grep -q "^rw" && sudo -n tar -C ' + shlex.quote(volume['path']) + ' -czf - .' with archive.with_suffix('.partial').open('wb') as target: process = subprocess.run(['ssh', '-T', self.settings['node_ssh'], remote], stdout=target, stderr=subprocess.PIPE) if process.returncode: raise RuntimeError('Volume backup failed; partial archive retained') archive.with_suffix('.partial').replace(archive) destination = self.root / 'data' / role if not (backup / (role + '.copied')).exists(): destination.mkdir(parents=True, exist_ok=True) with tarfile.open(archive) as source: source.extractall(destination, filter='data') if role == 'grafana': database = destination / 'grafana.db' if not database.exists(): raise RuntimeError('Existing Grafana database missing; refusing an empty installation') original = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) copied = sqlite3.connect(str(database) + '.consistent') original.backup(copied) copied.close(); original.close() os.replace(str(database) + '.consistent', database) for suffix in ('-wal', '-shm'): Path(str(database) + suffix).unlink(missing_ok=True) connection = sqlite3.connect(database.as_uri() + '?mode=ro', uri=True) print('Preserved Grafana database dashboards:', connection.execute('select count(*) from dashboard').fetchone()[0]) connection.close() run(['sudo', '-n', 'chown', '-R', '472:472' if role == 'grafana' else '65534:65534', destination]) write(backup / (role + '.copied'), 'copied\n') self.compose('up', '-d', '--force-recreate') self.wait_for(self.validate) write(self.root / 'migration-complete.json', json.dumps({'volumes': volumes, 'cluster_uid': self.settings['cluster_uid']})) self.install_timer() @staticmethod def wait_for(check): deadline = time.monotonic() + 180 while True: try: check() break except (OSError, ValueError, RuntimeError, urllib.error.URLError): if time.monotonic() > deadline: raise time.sleep(4) def install_timer(self): user = self.settings['user'] service = (f'[Unit]\nDescription=Refresh external homelab monitoring configuration\nAfter=network-online.target docker.service\n' f'[Service]\nType=oneshot\nUser={user}\nEnvironment=HOME={self.settings["home"]}\n' f'ExecStart=/usr/bin/python3 {self.root}/manager.py refresh --root {self.root}\n') timer = '[Unit]\nDescription=Refresh monitoring discovery, rules and dashboards\n[Timer]\nOnBootSec=45\nOnUnitActiveSec=5min\n[Install]\nWantedBy=timers.target\n' for filename, content in (('homelab-monitoring-refresh.service', service), ('homelab-monitoring-refresh.timer', timer)): write(self.root / filename, content) run(['sudo', '-n', 'install', '-m', '644', self.root / filename, '/etc/systemd/system/' + filename]) run(['sudo', '-n', 'systemctl', 'daemon-reload']) run(['sudo', '-n', 'systemctl', 'enable', '--now', 'homelab-monitoring-refresh.timer']) def http_ready(self): for name, port, path in (('prometheus', 19090, '/-/ready'), ('alertmanager', 19093, '/-/ready'), ('grafana', 13000, '/api/health')): self.http(f'http://127.0.0.1:{port}{path}') def validate(self): self.verify_identity() self.http_ready() targets = json.loads(self.http('http://127.0.0.1:19090/api/v1/targets'))['data']['activeTargets'] print('Prometheus targets:', len(targets), 'up:', sum(t['health'] == 'up' for t in targets)) if not targets: raise RuntimeError('Prometheus discovered no scrape targets') if not any(t['health'] == 'up' and '/prometheus-stack-kube-state-metrics/' in t.get('scrapePool', '') for t in targets): raise RuntimeError('No healthy kube-state-metrics ServiceMonitor target; discovery/network validation failed') ini = configparser.ConfigParser(interpolation=None) ini.read(self.root / 'config/grafana/grafana.ini') if ini.get('auth.generic_oauth', 'client_id', fallback='') != 'grafana': raise RuntimeError('Grafana Dex client configuration missing') req = urllib.request.Request('http://127.0.0.1:13000/login/generic_oauth') class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None try: urllib.request.build_opener(NoRedirect()).open(req, timeout=10) raise RuntimeError('Grafana did not start an OAuth redirect') except urllib.error.HTTPError as error: location = error.headers.get('Location', '') if error.code != 302 or not location.startswith(ini.get('auth.generic_oauth', 'auth_url')): raise RuntimeError('Unexpected Grafana OAuth redirect') from None print('Dex OAuth authorization redirect: verified') deployed_dex = yaml.safe_load(run(['sudo', '-n', 'cat', self.settings.get('dex_config', '/data/homelab-dex/config.yaml')])) secret = run(['sudo', '-n', 'cat', self.root / 'config/grafana/secrets/client-secret']).decode() validate_dex_client(deployed_dex, secret, ini.get('server', 'root_url').rstrip('/') + '/login/generic_oauth') print('Deployed Dex client secret and callback: match') admin = self.get('secret', GRAFANA)['data'] auth = base64.b64encode(base64.b64decode(admin['admin-user']) + b':' + base64.b64decode(admin['admin-password'])).decode() headers = {'Authorization': 'Basic ' + auth} dashboards = json.loads(self.http('http://127.0.0.1:13000/api/search?type=dash-db&limit=1000', headers=headers)) expected = self.dashboard_manifest() for filename in (self.root / 'config/grafana/dashboards').rglob('*.json'): uid = json.loads(filename.read_text()).get('uid') if uid: expected.add(uid) if not expected: raise RuntimeError('No dashboard UID baseline available for preservation validation') if expected - {d['uid'] for d in dashboards}: raise RuntimeError('Grafana dashboard UIDs from the original database are missing') sources = json.loads(self.http('http://127.0.0.1:13000/api/datasources', headers=headers)) actual_sources = {s.get('uid'): s for s in sources} for filename in (self.root / 'config/grafana/provisioning/datasources').glob('*'): for desired in yaml.safe_load(filename.read_text()).get('datasources', []): uid = desired.get('uid') if uid and (uid not in actual_sources or actual_sources[uid].get('url', '').rstrip('/') != desired.get('url', '').rstrip('/')): raise RuntimeError('Expected datasource UID or backend URL was not preserved') print(f'Backup/provisioned dashboard UIDs verified: {len(expected)}; current dashboards: {len(dashboards)}') for name in ('prometheus', 'alertmanager', 'grafana'): print(name + ': ready') def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('action', choices=['migrate', 'apply', 'refresh', 'validate', 'status']) parser.add_argument('--root', default='/data/homelab-monitoring') args = parser.parse_args() os.umask(0o027) manager = Monitoring(args.root) with (manager.root / '.lock').open('w') as lock: fcntl.flock(lock, fcntl.LOCK_EX) if args.action in ('migrate', 'apply'): manager.migrate() elif args.action == 'refresh': manager.refresh() else: manager.validate() if __name__ == '__main__': try: main() except (OSError, ValueError, RuntimeError, urllib.error.URLError) as error: print('Monitoring: ' + str(error), file=sys.stderr) raise SystemExit(1)