ЛР 4 — БПИ2304 — Кирюпина — на 3

This commit is contained in:
SashaKirupina
2026-11-13 12:59:02 +03:00
parent ec540a1a72
commit 4c1109c93d
39 changed files with 3361 additions and 36 deletions
+75
View File
@@ -0,0 +1,75 @@
"""Explicit lab4-only lifecycle hooks. Never delete volumes or print credentials."""
import json
import os
from pathlib import Path
import subprocess
import sys
ROOT = Path(__file__).resolve().parents[1]
os.chdir(ROOT)
def docker(*args):
return subprocess.check_output(['docker', *args], text=True).strip()
def compose(*args):
return docker('compose', *args)
def snapshot():
result = []
containers = compose('ps', '-a', '-q').splitlines()
if not containers:
return result
# One bulk inspect keeps the stop hook well below its 10-second budget.
# Only these selected fields are written; Config/Env are never logged.
for container in json.loads(docker('inspect', *containers)):
service = container['Config']['Labels']['com.docker.compose.service']
if service not in ('lb', 'api1', 'api2', 'db', 's3'):
continue
state, mounts = container['State'], container['Mounts']
result.append({'service': service, 'container': container['Id'], 'running': state['Running'],
'started_at': state['StartedAt'], 'finished_at': state['FinishedAt'],
'volumes': [m['Name'] for m in mounts if m['Type'] == 'volume']})
return result
def save(name, value):
(ROOT / 'evidence').mkdir(exist_ok=True)
(ROOT / 'evidence' / name).write_text(json.dumps(value, indent=2) + '\n', encoding='utf-8')
def main():
action = sys.argv[1]
if action == 'restart':
before = snapshot()
compose('stop', 'lb', 'api1', 'api2', 'db', 's3')
compose('up', '-d', '--wait', '--wait-timeout', '30', 'db', 's3')
compose('run', '--rm', '--no-deps', 's3-init')
compose('run', '--rm', '--no-deps', 'migrate')
compose('up', '-d', '--no-deps', '--wait', '--wait-timeout', '30', 'api1', 'api2')
compose('up', '-d', '--no-deps', 'lb')
save('restart-scope.json', {'before': before, 'after': snapshot()})
elif action == 'stop-one':
target = os.environ.get('TARGET_INSTANCE_ID')
if not target:
raise RuntimeError('TARGET_INSTANCE_ID required')
before = snapshot()
selected = None
for service in ('api1', 'api2'):
code = "fetch('http://127.0.0.1:8080/health/live').then(r=>console.log(r.headers.get('x-instance-id'))).catch(()=>process.exit(1))"
instance = compose('exec', '-T', service, 'node', '-e', code)
if instance == target:
selected = service
break
if selected is None:
raise RuntimeError('Target is not a running API in this lab')
compose('stop', '-t', '2', selected)
after = snapshot()
assert not next(s for s in after if s['service'] == selected)['running']
assert all(s['running'] for s in after if s['service'] != selected)
save('stop-' + selected + '.json', {'target_instance': target, 'selected_service': selected, 'before': before, 'after': after})
elif action == 'restore':
compose('up', '-d', '--no-deps', '--wait', '--wait-timeout', '30', 'api1', 'api2')
else:
raise RuntimeError('Unknown action')
print('PASS: ' + action + ' completed for mtusi-lab4')
if __name__ == '__main__':
main()
+7
View File
@@ -0,0 +1,7 @@
@echo off
if defined LAB_PYTHON (
"%LAB_PYTHON%" -X utf8 "%~dp0control.py" restart
) else (
py -X utf8 "%~dp0control.py" restart
)
exit /b %errorlevel%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/control.py restart
+26
View File
@@ -0,0 +1,26 @@
"""Generate local credentials once; never print or rotate existing secrets."""
from pathlib import Path
import secrets
import shutil
root = Path(__file__).resolve().parents[1]
directory = root / 'secrets'
directory.mkdir(exist_ok=True)
password_file = directory / 'postgres_password'
url_file = directory / 'database_url'
if password_file.exists() != url_file.exists():
raise SystemExit('Incomplete secrets: restore the missing file; do not rotate an existing database password.')
if not password_file.exists():
password = secrets.token_hex(32)
password_file.write_text(password + '\n', encoding='utf-8')
url_file.write_text('postgresql://messenger:' + password + '@db:5432/messenger\n', encoding='utf-8')
password_file.chmod(0o600)
url_file.chmod(0o600)
for filename in ('s3_access_key_id', 's3_secret_access_key'):
destination = directory / filename
if not destination.exists():
destination.write_text(secrets.token_hex(10 if filename == 's3_access_key_id' else 24) + '\n', encoding='utf-8')
destination.chmod(0o600)
if not (root / '.env').exists():
shutil.copyfile(root / '.env.example', root / '.env')
print('Local .env and secrets ready; values are not printed. Existing credentials preserved.')
+7
View File
@@ -0,0 +1,7 @@
@echo off
if defined LAB_PYTHON (
"%LAB_PYTHON%" -X utf8 "%~dp0control.py" stop-one
) else (
py -X utf8 "%~dp0control.py" stop-one
)
exit /b %errorlevel%
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/control.py stop-one