forked from mtusi2026/mtusi2026lab4
ЛР4: MinIO, вложения и reconciler на оценку 5
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
"""Create local secrets once. Never print values or overwrite existing secrets."""
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
folder = root / 'secrets'
|
||||
folder.mkdir(exist_ok=True)
|
||||
folder.chmod(0o700)
|
||||
def put(name, value):
|
||||
path = folder / name
|
||||
if not path.exists():
|
||||
with path.open('x', encoding='utf-8', newline='\n') as f:
|
||||
f.write(value + '\n')
|
||||
# Parent directory is private; Compose mounts individual files for non-root services.
|
||||
path.chmod(0o644)
|
||||
return path.read_text(encoding='utf-8').strip()
|
||||
|
||||
pg = put('postgres_password', secrets.token_hex(32))
|
||||
vk = put('valkey_password', secrets.token_hex(32))
|
||||
put('database_url', f'postgres://messenger:{pg}@db:5432/messenger?sslmode=disable')
|
||||
put('cache_url', f'redis://:{vk}@valkey:6379/0')
|
||||
put('cursor_secret', secrets.token_hex(32))
|
||||
put('valkey.conf', '\n'.join(['bind 0.0.0.0', 'protected-mode yes', f'requirepass {vk}',
|
||||
'dir /data', 'appendonly yes', 'appendfsync always', 'maxmemory 128mb',
|
||||
'maxmemory-policy noeviction', 'save 60 1000']))
|
||||
if not (root / '.env').exists():
|
||||
(root / '.env').write_text((root / '.env.example').read_text(encoding='utf-8').replace('SESSION_STORE=postgres','SESSION_STORE=valkey'),encoding='utf-8')
|
||||
put('s3_root_user', 'admin_' + secrets.token_hex(8))
|
||||
put('s3_root_password', secrets.token_hex(32))
|
||||
put('s3_access_key_id', 'api_' + secrets.token_hex(8))
|
||||
put('s3_secret_access_key', secrets.token_hex(32))
|
||||
for name in ('restart.sh', 'stop-one.sh'):
|
||||
(root / 'scripts' / name).chmod(0o755)
|
||||
print('Local .env and secrets ready; existing values preserved.')
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Run the unchanged public make targets with executable Linux action hooks."""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument('target', choices=['check', 'validate', 'test', 'test-own', 'test-race', 'test-persistence', 'test-failover'])
|
||||
args = p.parse_args()
|
||||
command = ['docker', 'run', '--rm', '--network', 'mtusi-lab4_default',
|
||||
'--mount', 'type=bind,source='+str(root)+',target=/workspace']
|
||||
hooks = {'test-persistence': 'scripts/restart.sh', 'test-failover': 'scripts/stop-one.sh'}
|
||||
if args.target in hooks:
|
||||
command += ['--mount', 'type=bind,source=/var/run/docker.sock,target=/var/run/docker.sock']
|
||||
command += ['mtusi-messenger:lab4-tests', 'make', args.target, 'BASE_URL=http://lb:8080']
|
||||
if args.target in hooks:
|
||||
command += ['ACTION_SCRIPT='+hooks[args.target]]
|
||||
raise SystemExit(subprocess.call(command, cwd=root))
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Cross-platform operator commands for the local lab; never delete volumes."""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args, capture=False, env=None):
|
||||
result = subprocess.run(['docker', *args], cwd=ROOT, check=True,
|
||||
text=True, encoding='utf-8', capture_output=capture, env=env)
|
||||
return result.stdout.strip() if capture else None
|
||||
|
||||
|
||||
def replicas():
|
||||
ids = docker('compose', 'ps', '-q', 'api', capture=True).split()
|
||||
if not ids:
|
||||
return []
|
||||
# Only operational fields; never persist Env or secret values.
|
||||
raw = docker('inspect', '--format', '{{json .Config.Hostname}} {{json .Id}}', *ids, capture=True)
|
||||
return [dict(zip(('instance', 'id'), (json.loads(x) for x in line.split()))) for line in raw.splitlines()]
|
||||
|
||||
|
||||
def ready(count=2, base='http://127.0.0.1:8080'):
|
||||
deadline = time.monotonic()+90
|
||||
observed = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base+'/health/ready', timeout=2) as response:
|
||||
observed.add(response.headers['X-Instance-Id'])
|
||||
if len(observed) >= count:
|
||||
return
|
||||
except OSError:
|
||||
observed.clear()
|
||||
time.sleep(.2)
|
||||
raise RuntimeError('expected ready replicas did not appear through LB')
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('action', choices=['start','stop','restart','restore','status','stop-one','rolling'])
|
||||
p.add_argument('--instance')
|
||||
args = p.parse_args()
|
||||
if args.action == 'start':
|
||||
subprocess.run([sys.executable, '-X', 'utf8', 'scripts/bootstrap.py'], cwd=ROOT, check=True)
|
||||
docker('compose', 'up', '-d', '--build', '--wait')
|
||||
ready()
|
||||
elif args.action == 'stop':
|
||||
docker('compose', 'down')
|
||||
elif args.action == 'restart':
|
||||
docker('compose', 'restart', 'db', 'valkey', 's3', 'api', 'lb')
|
||||
ready()
|
||||
elif args.action == 'restore':
|
||||
docker('compose', 'up', '-d', '--no-deps', '--scale', 'api=2', 'api')
|
||||
ready()
|
||||
elif args.action == 'status':
|
||||
docker('compose', 'ps', '-a')
|
||||
print(json.dumps(replicas(), indent=2))
|
||||
ids = docker('compose','ps','-a','-q',capture=True).split()
|
||||
template = '[{{json .Id}},{{json .Name}},{{json .Config.Hostname}},{{json .State.Status}},{{json .State.StartedAt}},{{.HostConfig.NanoCpus}},{{.HostConfig.Memory}},{{json .NetworkSettings.Ports}},{{json .Config.Image}}]'
|
||||
containers = [dict(zip(('id','name','instance','state','started_at','nano_cpus','memory_bytes','ports','image'),json.loads(line)))
|
||||
for line in docker('inspect','--format',template,*ids,capture=True).splitlines()]
|
||||
query = "SELECT json_build_object('users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),'messages',(SELECT count(*) FROM messages),'idempotency_keys',(SELECT count(*) FROM message_keys),'database_bytes',pg_database_size(current_database()),'fsync',current_setting('fsync'),'synchronous_commit',current_setting('synchronous_commit'),'full_page_writes',current_setting('full_page_writes'))"
|
||||
counts = json.loads(docker('compose','exec','-T','db','psql','-U','messenger','-d','messenger','-At','-c',query,capture=True))
|
||||
engine = json.loads(docker('info','--format','[{{.NCPU}},{{.MemTotal}},{{json .OSType}},{{json .KernelVersion}},{{json .ServerVersion}},{{json .OperatingSystem}}]',capture=True))
|
||||
snapshot = {'timestamp_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'containers':containers,'database':counts,
|
||||
'docker_engine':dict(zip(('cpus','memory_bytes','os_type','kernel','version','operating_system'),engine))}
|
||||
folder = ROOT/'evidence'
|
||||
folder.mkdir(exist_ok=True)
|
||||
(folder/'infrastructure.json').write_text(json.dumps(snapshot,indent=2)+'\n',encoding='utf-8')
|
||||
elif args.action == 'stop-one':
|
||||
selected = [r for r in replicas() if r['instance']==args.instance]
|
||||
if len(selected) != 1:
|
||||
p.error('--instance must match exactly one running API hostname (see status)')
|
||||
docker('stop', '--time', '9', selected[0]['id'])
|
||||
else:
|
||||
original = replicas()
|
||||
if len(original) != 2:
|
||||
p.error('rolling replacement requires exactly two running replicas')
|
||||
for old in original:
|
||||
docker('compose', 'up', '-d', '--no-deps', '--scale', 'api=3', 'api')
|
||||
ready(3)
|
||||
docker('stop', '--time', '9', old['id'])
|
||||
docker('rm', old['id'])
|
||||
ready(2)
|
||||
print(json.dumps({'before':original, 'after':replicas()}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
ids=$(docker compose ps -q db valkey s3 api lb)
|
||||
docker inspect --format '{{.Id}} {{index .Config.Labels "com.docker.compose.service"}} {{.State.StartedAt}} {{.State.Status}}' $ids > evidence/restart-before.txt
|
||||
docker compose restart db valkey s3 api lb
|
||||
docker inspect --format '{{.Id}} {{index .Config.Labels "com.docker.compose.service"}} {{.State.StartedAt}} {{.State.Status}}' $ids > evidence/restart-after.txt
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
for id in $(docker compose ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
mkdir -p evidence
|
||||
docker inspect --format '{{.Id}} {{.State.Status}} {{.State.StartedAt}}' "$id" > evidence/stopped-before.txt
|
||||
docker stop --time 9 "$id" > /dev/null
|
||||
docker inspect --format '{{.Id}} {{.State.Status}} {{.State.FinishedAt}} {{.State.ExitCode}}' "$id" > evidence/stopped-after.txt
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo 'Target is not a running API container' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Render only measured evidence; never turn an unrun check into PASS."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
folder=ROOT/'evidence'
|
||||
def read(name):
|
||||
p=folder/name
|
||||
return json.loads(p.read_text(encoding='utf-8')) if p.exists() else None
|
||||
verification=read('verification.json') or {}
|
||||
lines=['# Фактические результаты lab4','',
|
||||
'Полный прогон завершён: **'+('да' if verification.get('complete') else 'нет')+'**.',
|
||||
'Контракт и публичные тесты неизменны: '+str(verification.get('protected_unchanged',False))+'.','',
|
||||
'| Проверка | Exit code | Время, с |','| --- | --- | --- |']
|
||||
lines += ['| '+c['name']+' | '+str(c['exit_code'])+' | '+str(c['seconds'])+' |' for c in verification.get('checks',[])]
|
||||
if verification.get('failure'):lines+=['','Остановка: '+verification['failure']]
|
||||
if verification.get('pending_revalidation'):
|
||||
lines+=['','Ожидает полного повторного прогона: настройка на пять загрузок на реплику и десять успешных параллельных запросов. Таблица выше относится к предыдущему прогону.']
|
||||
memory=read('upload-memory.json')
|
||||
if memory:
|
||||
lines+=['','## 10 одновременно стартующих uploads','',
|
||||
'| Bytes | Успех | 503 | RPS успешных | p95, мс | Σ cgroup peak, MiB |',
|
||||
'| --- | --- | --- | --- | --- | --- |']
|
||||
for c in memory['cases']:
|
||||
lines.append('| {} | {} | {} | {:.2f} | {:.2f} | {:.2f} |'.format(c['file_bytes'],c['success'],c['backpressure_503'],c['successful_rps'],c['p95_seconds']*1000,c['sum_cgroup_peaks_bytes']/1048576))
|
||||
lines+=['','Сумма отдельных kernel peaks — верхняя оценка одновременного общего пика. Startup включён.']
|
||||
research=read('research.json')
|
||||
if research:
|
||||
lines+=['','## Согласованность DB/S3','',
|
||||
'| Этап | Orphan | Missing | Удалено | Отмечено | Восстановлено |',
|
||||
'| --- | --- | --- | --- | --- | --- |']
|
||||
for name in ('dry_run','apply','repeat_apply','recovery'):
|
||||
c=research[name]
|
||||
lines.append('| {} | {} | {} | {} | {} | {} |'.format(name,c['old_orphans'],c['missing'],c['deleted'],c['marked_unavailable'],c['cleared_unavailable']))
|
||||
lines+=['','| Добавлено объектов | Объектов всего | Metadata rows | HEAD requests | Время обхода, мс (3 повтора) |',
|
||||
'| --- | --- | --- | --- | --- |']
|
||||
for case in research['scan_cost']:
|
||||
runs=case['runs'];c=runs[0]
|
||||
lines.append('| {} | {} | {} | {} | {} |'.format(case['added_objects'],c['objects_scanned'],c['metadata_scanned'],c['head_requests'],', '.join(str(x['elapsed_ms']) for x in runs)))
|
||||
lines+=['','Каждый PASS опирается на журнал соответствующей команды. Отсутствующие результаты не считаются выполненными.']
|
||||
(folder/'RESULTS.md').write_text('\n'.join(lines)+'\n',encoding='utf-8')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Complete, sequential verification on a disposable local Compose lab."""
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def protected():
|
||||
return {str(p.relative_to(ROOT)).replace('\\','/'):hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for folder in ('contracts','tests') for p in (ROOT/folder).rglob('*')
|
||||
if p.is_file() and '__pycache__' not in p.parts}
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--static-only',action='store_true')
|
||||
p.add_argument('--resume-integration',action='store_true',help='reuse successful local checks, rerun build and every integration check')
|
||||
args=p.parse_args()
|
||||
# Compose publishes IPv4 loopback. Avoid Windows localhost IPv6 fallback
|
||||
# and keep public/private child clients on the same operator-supplied URL.
|
||||
os.environ.setdefault('BASE_URL', 'http://127.0.0.1:8080')
|
||||
evidence=ROOT/'evidence';evidence.mkdir(exist_ok=True)
|
||||
result={'started_utc':dt.datetime.now(dt.timezone.utc).isoformat(),'complete':False,'checks':[]}
|
||||
if args.resume_integration:
|
||||
previous=json.loads((evidence/'verification.json').read_text(encoding='utf-8'))
|
||||
names={'contract','go-test','go-vet','student-unit','go-vuln','go-race'}
|
||||
successful={c['name']:c for c in previous['checks'] if c['name'] in names and c['exit_code']==0}
|
||||
if set(successful)!=names:
|
||||
raise RuntimeError('resume requires all local and race checks to have passed')
|
||||
cutoff=dt.datetime.fromisoformat(previous.get('local_checks_from_utc',previous['started_utc'])).timestamp()
|
||||
source=list(ROOT.glob('*.go'))+list((ROOT/'migrations').glob('*.sql'))+[ROOT/'go.mod',ROOT/'go.sum',ROOT/'Dockerfile']
|
||||
if any(path.stat().st_mtime>cutoff for path in source):
|
||||
raise RuntimeError('application sources changed; run the full verifier')
|
||||
result['checks']=[successful[name] for name in ('contract','go-test','go-vet','student-unit','go-vuln','go-race')]
|
||||
result['local_checks_from_utc']=previous.get('local_checks_from_utc',previous['started_utc'])
|
||||
manifest=evidence/'protected-files.json'
|
||||
original=json.loads(manifest.read_text(encoding='utf-8')) if manifest.exists() else protected()
|
||||
if protected()!=original:
|
||||
raise RuntimeError('protected files differ from the original SHA-256 manifest')
|
||||
def persist():
|
||||
result['protected_unchanged']=protected()==original
|
||||
(evidence/'verification.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8')
|
||||
subprocess.run([sys.executable,'-X','utf8','scripts/summarize.py'],cwd=ROOT,check=True)
|
||||
def run(name,command,timeout=1200):
|
||||
print('Running '+name,flush=True)
|
||||
start=time.monotonic()
|
||||
with (evidence/(name+'.txt')).open('w',encoding='utf-8') as output:
|
||||
completed=subprocess.run(command,cwd=ROOT,stdout=output,stderr=subprocess.STDOUT,
|
||||
encoding='utf-8',timeout=timeout)
|
||||
result['checks'].append({'name':name,'command':command,'exit_code':completed.returncode,'seconds':round(time.monotonic()-start,3)})
|
||||
persist()
|
||||
if completed.returncode:
|
||||
raise RuntimeError(name+' failed; see evidence/'+name+'.txt')
|
||||
py=[sys.executable,'-X','utf8']
|
||||
try:
|
||||
if not args.resume_integration:
|
||||
run('contract',py+['scripts/check_contract.py'])
|
||||
run('go-test',['go','test','./...'])
|
||||
run('go-vet',['go','vet','./...'])
|
||||
run('student-unit',py+['student-tests/unit.py'])
|
||||
run('go-vuln',['go','run','golang.org/x/vuln/cmd/govulncheck@v1.1.4','./...'])
|
||||
if args.static_only:
|
||||
result['static_complete']=True
|
||||
return
|
||||
run('bootstrap',py+['scripts/bootstrap.py'])
|
||||
run('compose-config',['docker','compose','config','--quiet'])
|
||||
run('start',py+['scripts/manage.py','start'],3600)
|
||||
run('build-tests',['docker','build','-f','Dockerfile.tests','-t','mtusi-messenger:lab4-tests','.'],1800)
|
||||
run('openapi',py+['scripts/linux_tests.py','validate'])
|
||||
if not args.resume_integration:
|
||||
run('go-race',['docker','run','--rm','--mount','type=bind,source='+str(ROOT)+',target=/workspace',
|
||||
'mtusi-messenger:lab4-tests','go','test','-race','./...'],1200)
|
||||
run('smoke',py+['tests/smoke.py'])
|
||||
run('attachments',py+['student-tests/attachments.py'])
|
||||
run('persistence',py+['scripts/linux_tests.py','test-persistence'])
|
||||
run('ready-before-failover',py+['scripts/manage.py','restore'])
|
||||
for i in range(2):
|
||||
run('failover-'+str(i+1),py+['scripts/linux_tests.py','test-failover'])
|
||||
run('restore-'+str(i+1),py+['scripts/manage.py','restore'])
|
||||
run('failures',py+['student-tests/failures.py'])
|
||||
run('memory',py+['student-tests/memory.py'])
|
||||
run('research',py+['student-tests/research.py'],1800)
|
||||
run('load',py+['tests/load.py','--duration','30','--concurrency','4','--output','evidence/load.json'])
|
||||
run('infrastructure',py+['scripts/manage.py','status'])
|
||||
result['complete']=True
|
||||
except (RuntimeError,subprocess.TimeoutExpired,FileNotFoundError) as exc:
|
||||
result['failure']=str(exc)
|
||||
print(str(exc),file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
finally:
|
||||
persist()
|
||||
if not result['protected_unchanged']:
|
||||
raise RuntimeError('protected files changed during verification')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user