Files
vpn-dns-gateway/delivery/bootstrap/enable-production-monitoring.py

80 lines
4.3 KiB
Python

"""Apply the reviewed production probe/panel only after production is healthy."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import urllib.request
parser = argparse.ArgumentParser()
parser.add_argument('--prometheus', required=True, type=Path)
parser.add_argument('--dashboard', required=True, type=Path)
parser.add_argument('--backup', required=True, type=Path)
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
live_prom = Path('/root/monitoring/prometheus/prometheus.yml')
live_dashboard = Path('/root/monitoring/grafana/dashboards/sre.json')
before = {live_prom:live_prom.read_bytes(), live_dashboard:live_dashboard.read_bytes()}
candidate_prom = args.prometheus.read_text().replace('\r\n','\n')
candidate_dashboard = args.dashboard.read_bytes()
addition = ' # Apply this addition only after Assignment 8 production is healthy.\n - https://app.yebilly.me/health\n'
assert candidate_prom.count(addition) == 1, 'Unexpected production probe'
assert candidate_prom.replace(addition,'').strip() == before[live_prom].decode().replace('\r\n','\n').strip(), 'Existing probes differ; inspect before changing'
old = json.loads(before[live_dashboard])
new = json.loads(candidate_dashboard)
assert old['uid'] == new['uid'] == 'group1-sre'
assert old['version'] == 1 and new['version'] == 2
panel = new['panels'][-1]
assert panel['id'] == 8 and panel['type'] == 'timeseries'
assert panel['targets'][0]['expr'] == 'probe_success{job="https",instance="https://app.yebilly.me/health"}'
comparison = dict(new, version=old['version'], panels=new['panels'][:-1])
assert comparison == old, 'Existing dashboard differs; inspect before changing'
with urllib.request.urlopen('https://app.yebilly.me/health',timeout=10) as response:
health = json.load(response)
assert response.status == 200 and health['status'] == 'ok' and health['version'] in {'v1','v2'}, 'Production must be healthy first'
stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
temporary = '/tmp/ssw590-production-probe-' + stamp + '.yml'
subprocess.run(['docker','cp',str(args.prometheus),'monitoring-prometheus-1:'+temporary],check=True,capture_output=True)
try:
validation = subprocess.check_output(['docker','exec','monitoring-prometheus-1','promtool','check','config',temporary],text=True)
if not args.apply:
print(validation + 'Validated only; no active file changed.')
raise SystemExit(0)
args.backup.mkdir(parents=True,mode=0o700,exist_ok=False)
for path in before:
shutil.copy2(path,args.backup / (path.name + '.before'))
inodes = {p:p.stat().st_ino for p in before}
def write(path,content):
with path.open('wb') as stream:
stream.write(content)
stream.flush()
os.fsync(stream.fileno())
assert path.stat().st_ino == inodes[path], 'Bind inode changed'
try:
write(live_prom,candidate_prom.encode())
write(live_dashboard,candidate_dashboard)
subprocess.run(['docker','kill','--signal','HUP','monitoring-prometheus-1'],check=True,capture_output=True)
except Exception:
for path,content in before.items():
write(path,content)
subprocess.run(['docker','kill','--signal','HUP','monitoring-prometheus-1'],check=True,capture_output=True)
raise
report = {'applied_at':datetime.now(timezone.utc).isoformat(),'production_health':health,
'validation':validation,'prior_probes_and_panels_preserved':True,
'files':[{'path':str(p),'before_sha256':hashlib.sha256(before[p]).hexdigest(),
'after_sha256':hashlib.sha256(p.read_bytes()).hexdigest(),
'inode_preserved':p.stat().st_ino == inodes[p]} for p in before],
'backup':str(args.backup),'reload':'Prometheus SIGHUP; Grafana file provisioning',
'result':'applied; runtime probe and panel verification still required'}
(args.backup / 'applied.json').write_text(json.dumps(report,indent=2))
print(json.dumps(report,indent=2))
finally:
# docker cp creates a root-owned file; the Prometheus service runs as nobody.
subprocess.run(['docker','exec','--user','0','monitoring-prometheus-1','rm','-f',temporary],check=True,capture_output=True)