Выполнение лабораторной работы номер 7

This commit is contained in:
2026-12-04 18:15:18 +03:00
parent 20afc2c790
commit 2fae615742
77 changed files with 5212 additions and 64 deletions
+46
View File
@@ -0,0 +1,46 @@
"""Local Compose actions for the public resilience tests."""
import os
from pathlib import Path
import re
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
COMPOSE = ["docker", "compose", "--env-file", str(ROOT / ".env")]
def run(*args, capture=False):
return subprocess.run(args, cwd=ROOT, check=True, text=True,
capture_output=capture).stdout
def stop_one():
target = os.environ.get("TARGET_INSTANCE_ID", "")
if not re.fullmatch(r"[0-9a-f]{32}", target):
raise SystemExit("Invalid TARGET_INSTANCE_ID")
ids = run(*COMPOSE, "ps", "-q", "api", capture=True).splitlines()
matches = [cid for cid in ids if run("docker", "exec", cid, "python", "-c",
"import urllib.request;print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])",
capture=True).strip() == target]
if len(matches) != 1 or len(ids) < 2:
raise SystemExit("Expected one matching API and at least two running replicas")
print(f"Stopping API container {matches[0][:12]}", flush=True)
run("docker", "stop", "--time", "2", matches[0])
def restart():
# Keep postgres volume; Redis is a disposable cache. Never remove volumes.
run(*COMPOSE, "stop", "nginx", "api", "cleanup", "worker", "dispatcher")
run(*COMPOSE, "restart", "postgres", "redis", "minio", "broker", "openbao", "collector", "prometheus", "loki", "tempo", "grafana")
run(*COMPOSE, "restart", "broker-tls", "collector-tls", "collector-scrape-tls", "loki-tls", "tempo-query-tls", "tempo-ingest-tls")
run(sys.executable, str(ROOT / "scripts/bootstrap_bao.py"))
run(*COMPOSE, "up", "-d", "--wait", "--wait-timeout", "60")
if __name__ == "__main__":
if sys.argv[1:] == ["stop-one"]:
stop_one()
elif sys.argv[1:] == ["restart"]:
restart()
else:
raise SystemExit("Use stop-one or restart")
+76
View File
@@ -0,0 +1,76 @@
"""Operator-only, local OpenBao initialization and per-role certificate authentication."""
import json
import os
from pathlib import Path
import ssl
import time
import urllib.error
import urllib.request
from urllib.parse import quote
ROOT=Path(__file__).resolve().parents[1]
PKI=ROOT/'certs/private'
STATE=ROOT/'secrets/openbao-operator.json'
URL='https://127.0.0.1:8200/v1/'
context=ssl.create_default_context(cafile=str(PKI/'ca.crt'))
context.load_cert_chain(str(PKI/'operator-client/tls.crt'),str(PKI/'operator-client/tls.key'))
env={}
for line in (ROOT/'.env').read_text(encoding='utf-8').splitlines():
if '=' in line and not line.lstrip().startswith('#'):
k,v=line.split('=',1);env[k]=v
def request(path, body=None, token=None, method=None):
h={'Content-Type':'application/json'}
if token:
h['X-Vault-Token']=token
req=urllib.request.Request(URL+path,data=None if body is None else json.dumps(body).encode(),headers=h,method=method)
try:
with urllib.request.urlopen(req,context=context,timeout=15) as response:
data=response.read()
return json.loads(data) if data else {}
except urllib.error.HTTPError as exc:
raise RuntimeError(f'OpenBao operation {path} returned {exc.code}') from None
for attempt in range(30):
try:
initialized=request('sys/init')['initialized']
break
except (OSError,RuntimeError):
if attempt==29:raise
time.sleep(2)
if not initialized:
if STATE.exists():
raise SystemExit('Existing operator state: refuse to overwrite')
state=request('sys/init',{'secret_shares':1,'secret_threshold':1},method='PUT')
STATE.parent.mkdir(exist_ok=True)
STATE.write_text(json.dumps(state),encoding='utf-8')
os.chmod(STATE,0o600)
else:
state=json.loads(STATE.read_text(encoding='utf-8'))
if request('sys/seal-status')['sealed']:
request('sys/unseal',{'key':state['keys_base64'][0]},method='PUT')
token=state['root_token']
mounts=request('sys/mounts',token=token)
if 'kv/' not in mounts:
request('sys/mounts/kv',{'type':'kv','options':{'version':'2'}},token)
auth=request('sys/auth',token=token)
if 'cert/' not in auth:
request('sys/auth/cert',{'type':'cert'},token)
for role in ('api','worker','dispatcher','cleanup','migrate'):
db_user=env['POSTGRES_USER'] if role=='migrate' else 'messenger_'+role
db_password=env['POSTGRES_PASSWORD'] if role=='migrate' else env[role.upper()+'_DB_PASSWORD']
values={'DATABASE_URL':f"postgresql://{quote(db_user,safe='')}:{quote(db_password,safe='')}@postgres:5432/{env['POSTGRES_DB']}?sslmode=verify-full&sslrootcert=/ca/ca.crt"}
if role=='api':
values.update(REDIS_URL=f"rediss://:{quote(env['REDIS_PASSWORD'],safe='')}@redis:6379/0",S3_ACCESS_KEY=env['S3_ACCESS_KEY'],S3_SECRET_KEY=env['S3_SECRET_KEY'])
elif role in ('worker','cleanup'):
values.update(S3_ACCESS_KEY=env[role.upper()+'_S3_ACCESS_KEY'],S3_SECRET_KEY=env[role.upper()+'_S3_SECRET_KEY'])
if role in ('worker','dispatcher'):
broker_user='worker' if role=='worker' else 'dispatch'
values['BROKER_URL']=f"rediss://{broker_user}:{quote(env[role.upper()+'_BROKER_PASSWORD'],safe='')}@broker:6379/0"
request('kv/data/'+role,{'data':values},token)
request('sys/policies/acl/'+role,{'policy':f'path "kv/data/{role}" {{ capabilities = ["read"] }}'},token,method='PUT')
request('auth/cert/certs/'+role,{'certificate':(PKI/f'{role}-client/tls.crt').read_text(),
'token_policies':[role],'token_ttl':'15m','token_max_ttl':'30m','allowed_dns_sans':[role+'-client']},token)
print('OpenBao initialized/unsealed; per-service scoped secrets installed. Operator state kept locally.')
+126
View File
@@ -0,0 +1,126 @@
"""Generate local lab PKI. Never commit certs/private or secrets."""
from datetime import datetime, timedelta, timezone
import ipaddress
from pathlib import Path
import os
import argparse
import shutil
import hashlib
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
ROOT=Path(__file__).resolve().parents[1]
P=ROOT/'certs/private'
P.mkdir(parents=True,exist_ok=True)
parser=argparse.ArgumentParser()
parser.add_argument('--rotate',choices=['lb-client','api-client','worker-client','dispatcher-client','collector-client','grafana-client'])
args=parser.parse_args()
def key():
return rsa.generate_private_key(public_exponent=65537,key_size=2048)
def write(path,data):
path.parent.mkdir(parents=True,exist_ok=True)
path.write_bytes(data)
os.chmod(path,0o600)
def private(k):
return k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
def name(n):
return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,n)])
def builder(subject,issuer,k,days):
now=datetime.now(timezone.utc)
return (x509.CertificateBuilder().subject_name(name(subject)).issuer_name(issuer).public_key(k.public_key())
.serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=5))
.not_valid_after(now+timedelta(days=days)))
def has_extension(cert, extension):
try:
cert.extensions.get_extension_for_class(extension)
except x509.ExtensionNotFound:
return False
return True
if (P/'ca.key').exists():
ca_key=serialization.load_pem_private_key((P/'ca.key').read_bytes(),None)
ca=x509.load_pem_x509_certificate((P/'ca.crt').read_bytes())
else:
ca_key=key()
ca=None
write(P/'ca.key',private(ca_key))
if ca is None or not has_extension(ca,x509.SubjectKeyIdentifier):
ca=(builder('Messenger lab CA',name('Messenger lab CA'),ca_key,365)
.add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(ca_key.public_key()),critical=False)
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),critical=True)
.sign(ca_key,hashes.SHA256()))
write(P/'ca.crt',ca.public_bytes(serialization.Encoding.PEM))
def issue(identity,hosts,client=False):
d=P/identity
if (d/'tls.key').exists() and (d/'tls.crt').exists():
existing=x509.load_pem_x509_certificate((d/'tls.crt').read_bytes())
if args.rotate!=identity and has_extension(existing,x509.AuthorityKeyIdentifier):
return
if (d/'tls.key').exists() and (d/'tls.crt').exists() and args.rotate==identity:
backup=ROOT/'secrets'/'rotated'/identity
backup.mkdir(parents=True,exist_ok=True)
shutil.copy2(d/'tls.key',backup/'tls.key')
shutil.copy2(d/'tls.crt',backup/'tls.crt')
k=key()
san=[x509.DNSName(h) for h in hosts]
if 'localhost' in hosts:
san.append(x509.IPAddress(ipaddress.ip_address('127.0.0.1')))
usage=ExtendedKeyUsageOID.CLIENT_AUTH if client else ExtendedKeyUsageOID.SERVER_AUTH
cert=(builder(identity,ca.subject,k,30).add_extension(x509.SubjectAlternativeName(san),critical=False)
.add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),critical=False)
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()),critical=False)
.add_extension(x509.ExtendedKeyUsage([usage]),critical=False).sign(ca_key,hashes.SHA256()))
write(d/'tls.key',private(k));write(d/'tls.crt',cert.public_bytes(serialization.Encoding.PEM))
for identity,hosts in {'ingress':['localhost'],'api':['api'],'postgres':['postgres'],'minio':['minio'],
'redis':['redis'],'broker':['broker'],'collector':['collector'],'prometheus':['prometheus'],
'loki':['loki'],'tempo':['tempo'],'grafana':['localhost'],'openbao':['openbao','localhost']}.items():
issue(identity,hosts)
for role in ('lb-client','api-client','worker-client','dispatcher-client','cleanup-client','migrate-client','collector-client','grafana-client','prometheus-client','operator-client'):
issue(role,[role],client=True)
write(P/'public-pins'/f'{role}.crt',(P/role/'tls.crt').read_bytes())
# Grafana file provisioning supports PEM values in secureJsonData.
import json
provision=ROOT/'secrets/grafana-datasources'
provision.mkdir(parents=True,exist_ok=True)
pub=(P/'ca.crt').read_text()
cert=(P/'grafana-client/tls.crt').read_text()
priv=(P/'grafana-client/tls.key').read_text()
sources=[]
for typ,port in [('prometheus',9090),('loki',3101),('tempo',3201)]:
sources.append({'name':typ.title(),'uid':typ,'type':typ,'access':'proxy','url':f'https://{typ}:{port}',
'isDefault':typ=='prometheus','jsonData':{'tlsAuth':True,'tlsAuthWithCACert':True},
'secureJsonData':{'tlsCACert':pub,'tlsClientCert':cert,'tlsClientKey':priv}})
write(provision/'datasources.yaml',json.dumps({'apiVersion':1,'datasources':sources},indent=2).encode())
env={}
for line in (ROOT/'.env').read_text(encoding='utf-8').splitlines():
if '=' in line and not line.lstrip().startswith('#'):
k,v=line.split('=',1);env[k]=v
def digest(value):
return '#'+hashlib.sha256(value.encode()).hexdigest()
write(ROOT/'secrets/broker.acl', ('user default off\n'
f'user dispatch on {digest(env["DISPATCHER_BROKER_PASSWORD"])} ~attachment:jobs +ping +client|setinfo +xgroup +xadd\n'
f'user worker on {digest(env["WORKER_BROKER_PASSWORD"])} ~attachment:jobs +ping +client|setinfo +xgroup +xreadgroup +xautoclaim +xack +xdel\n').encode())
print('Local PKI created; CA: certs/private/ca.crt')
+3
View File
@@ -0,0 +1,3 @@
@echo off
python -X utf8 "%~dp0actions.py" restart
exit /b %errorlevel%
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
exec python3 "$(dirname "$0")/actions.py" restart
+3
View File
@@ -0,0 +1,3 @@
@echo off
python -X utf8 "%~dp0actions.py" stop-one
exit /b %errorlevel%
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
exec python3 "$(dirname "$0")/actions.py" stop-one