Проверить уровень 3, устойчивость и отрицательные сценарии, оформить отчёт

This commit is contained in:
2026-12-04 07:15:24 +03:00
parent d4f64bed85
commit 06459d3eed
54 changed files with 1934 additions and 126 deletions
+116
View File
@@ -0,0 +1,116 @@
"""Reproducible orchestration, scoped to this checkout and project."""
import argparse
import json
import os
from pathlib import Path
import ssl
import subprocess
import sys
import time
import urllib.request
ROOT=Path(__file__).resolve().parents[1]
os.chdir(ROOT)
def compose(*args, **kwargs):
return subprocess.run(['docker','compose',*args],check=True,**kwargs)
def python(script,*args):
subprocess.run([sys.executable,'-X','utf8',str(ROOT/script),*args],check=True)
def env():
return dict(line.split('=',1) for line in (ROOT/'.env').read_text().splitlines() if '=' in line)
def ready():
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/ca.crt'))
endpoint='https://localhost:'+env()['HTTPS_PORT']+'/health/ready'
deadline=time.monotonic()+120
while time.monotonic()<deadline:
try:
with urllib.request.urlopen(endpoint,context=ctx,timeout=3) as response:
assert response.status==200
print('HTTPS readiness: 200, CA and localhost SAN verified');return
except (OSError,AssertionError):
time.sleep(.5)
raise RuntimeError('HTTPS readiness exceeded 120 seconds')
def snapshot():
ids=subprocess.check_output(['docker','compose','ps','-aq'],text=True).split()
result=[]
objects=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)) if ids else []
for d in objects:
result.append({'service':d['Config']['Labels']['com.docker.compose.service'],'id':d['Id'][:12],
'started_at':d['State']['StartedAt'],'status':d['State']['Status']})
return result
def main():
parser=argparse.ArgumentParser()
parser.add_argument('action',choices=['start','restart','stop-one','ready'])
parser.add_argument('--initialize',action='store_true')
parser.add_argument('--unseal',action='store_true')
a=parser.parse_args()
assert env()['COMPOSE_PROJECT_NAME'].startswith('lyakhonov-lab7')
if a.action=='ready':
ready();return
if a.action=='start':
compose('build','api1','s3')
compose('up','-d','db','s3','broker','openbao','prometheus','loki','tempo','otel-collector')
# Health init endpoint works while sealed, and validates CA/hostname.
sys.path.insert(0,str(ROOT/'scripts'))
from bao import request
for _ in range(60):
try:
request('sys/init');break
except OSError:
time.sleep(.5)
else:
raise RuntimeError('OpenBao TLS listener not ready')
if a.initialize:
python('scripts/bao.py','init')
if a.unseal:
python('scripts/bao.py','unseal')
python('scripts/bao.py','configure')
for _ in range(60):
probe=subprocess.run(['docker','compose','exec','-T','db','pg_isready','-U','messenger','-d','messenger'],stdout=subprocess.DEVNULL)
if probe.returncode==0:break
time.sleep(.5)
compose('run','--rm','migrate')
compose('exec','-T','db','psql','-v','ON_ERROR_STOP=1','-U','messenger','-d','messenger',input=(ROOT/'infra/grants.sql').read_bytes())
compose('run','--rm','bucket-init')
compose('up','-d')
ready();return
before=snapshot()
if a.action=='restart':
compose('restart','api1','api2','worker','dispatcher','cleaner','db','s3','broker','openbao','prometheus','loki','tempo','grafana','otel-collector')
compose('restart','prometheus-tls','loki-tls','tempo-tls','tempo-tls-ingest')
if not a.unseal:
raise RuntimeError('Explicit --unseal operator action required after OpenBao restart')
# The key remains on the host. This hook is run by the operator, not app.
for _ in range(40):
result=subprocess.run([sys.executable,'-X','utf8','scripts/bao.py','unseal'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
if result.returncode==0:break
time.sleep(.5)
else:raise RuntimeError('Unseal failed')
ready()
else:
target=os.environ['TARGET_INSTANCE_ID']
found=[]
code="import urllib.request;print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])"
for service in ('api1','api2'):
current=subprocess.check_output(['docker','compose','exec','-T',service,'python','-c',code],text=True).strip()
if current==target:found.append(service)
assert len(found)==1,'Unknown or ambiguous process alias'
compose('stop','-t','1',found[0])
result={'action':a.action,'before':before,'after':snapshot()}
path=ROOT/'evidence'/('restart.json' if a.action=='restart' else 'stop-'+found[0]+'.json')
path.write_text(json.dumps(result,indent=2),encoding='utf-8')
if __name__=='__main__':
main()