feat(lab4): implement S3 attachments with fault tolerance

This commit is contained in:
sashadugina06
2026-11-06 18:15:53 +03:00
parent ec540a1a72
commit b4704b47b2
67 changed files with 3436 additions and 46 deletions
+41
View File
@@ -0,0 +1,41 @@
# Команды оператора
Из корня lab4:
```sh
python3 scripts/init-local.py
scripts/compose.sh up -d --build
scripts/compose.sh ps
BASE_URL=http://localhost:8084 make test
make test-persistence BASE_URL=http://localhost:8084 ACTION_SCRIPT=scripts/restart.sh
make test-failover BASE_URL=http://localhost:8084 ACTION_SCRIPT=scripts/stop-one.sh
scripts/compose.sh start api
scripts/cleanup.sh
```
`compose.sh` добавляет Docker Desktop credential helper в PATH на macOS.
`restart.sh` перезапускает все хранилища/API/LB/cleanup без удаления volumes;
сохраняет времена запуска до/после в evidence/restart-{before,after}.txt.
`stop-one.sh` сопоставляет TARGET_INSTANCE_ID ответу локального API внутри
контейнера и останавливает только найденную реплику. Возврат 1 означает,
что реплика не найдена; восстановление отдельно: `scripts/compose.sh start api`.
Полный проверочный прогон: `python3 scripts/verify.py`. Он намеренно выполняет
отказы и перезапуски только проекта lab4, создаёт синтетические данные,
сохраняет реальные exit codes/выводы в evidence. Пользовательские данные не удаляет.
Отдельные проверки (BASE_URL по умолчанию localhost:8084):
```sh
python3 student-tests/negative.py
python3 student-tests/faults.py
python3 student-tests/attachment-failover.py
python3 student-tests/upload-load.py
```
`faults.py` временно создаёт DB trigger для единственного случайного имени файла,
останавливает S3/БД, завершает API после PUT, проверяет очистку и восстанавливает
сервисы в finally. Проверка истечения grace использует часы тестового процесса +2h:
не меняет системное время, production-код grace или timestamps объектов.
Не запускайте fault/нагрузочные проверки одновременно друг с другом.
Проверки предназначены для отдельного локального учебного стенда.
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
./scripts/compose.sh exec -T api python -m src.cleanup
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
if [ -d /Applications/Docker.app/Contents/Resources/bin ]; then
export PATH="/Applications/Docker.app/Contents/Resources/bin:$PATH"
fi
exec docker compose --env-file .env "$@"
+21
View File
@@ -0,0 +1,21 @@
"""Generate local credentials once; never overwrite an existing secret."""
from pathlib import Path
import secrets
root = Path(__file__).resolve().parents[1]
directory = root / 'secrets'
directory.mkdir(mode=0o700, exist_ok=True)
values = {'postgres_password': secrets.token_hex(24), 's3_root_user': 'lab4root', 's3_root_password': secrets.token_hex(24), 's3_access_key_id': 'lab4api', 's3_secret_access_key': secrets.token_hex(24)}
for name, value in values.items():
path = directory / name
if not path.exists():
path.write_text(value + '\n')
path.chmod(0o600)
path = directory / 'database_url'
if not path.exists():
password = (directory / 'postgres_password').read_text().strip()
path.write_text(f'postgresql://messenger:{password}@postgres:5432/messenger\n')
path.chmod(0o600)
path = root / '.env'
if not path.exists():
path.write_text('COMPOSE_PROJECT_NAME=mtusi2026lab4\nPUBLIC_PORT=8084\n')
print('Local configuration ready (secret values suppressed)')
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p evidence
containers=$(./scripts/compose.sh ps -q postgres redis s3 api lb cleanup)
docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.State.Status}}' $containers > evidence/restart-before.txt
./scripts/compose.sh restart postgres redis s3 api lb cleanup
docker inspect --format '{{.Name}} {{.State.StartedAt}} {{.State.Status}}' $containers > evidence/restart-after.txt
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID required}"
for container in $(./scripts/compose.sh ps -q api); do
instance=$(docker exec "$container" python -c 'import urllib.request; print(urllib.request.urlopen("http://127.0.0.1:8080/health/live").headers["X-Instance-Id"])')
if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then
docker stop -t 2 "$container" >/dev/null
exit 0
fi
done
exit 1
+49
View File
@@ -0,0 +1,49 @@
"""Explicit full lab4 validation; includes lab4-only restarts and fault injection."""
import json
import os
from pathlib import Path
import subprocess
import sys
import time
root = Path(__file__).resolve().parents[1]
os.chdir(root)
env = dict(os.environ, BASE_URL='http://localhost:8084')
env['PATH'] = '/Applications/Docker.app/Contents/Resources/bin:' + env.get('PATH', '')
compose = ['docker', 'compose', '--env-file', '.env']
checks = [
('check', ['make', 'check']),
('validate', ['make', 'validate', 'PYTHON=.venv/bin/python']),
('image-pull', ['docker', 'pull', 'bitnamilegacy/minio:2025.7.23-debian-12-r5@sha256:6dabb4a2088c9a79908de3bc05f4586c23ad2182c8908e7e3acbf61c1467fb20']),
('compose-config', compose + ['config', '--quiet']),
('build', compose + ['up', '-d', '--build']),
('smoke', ['make', 'test', 'BASE_URL=http://localhost:8084']),
('persistence', ['make', 'test-persistence', 'BASE_URL=http://localhost:8084', 'ACTION_SCRIPT=scripts/restart.sh']),
('failover', ['make', 'test-failover', 'BASE_URL=http://localhost:8084', 'ACTION_SCRIPT=scripts/stop-one.sh']),
('restore-after-failover', compose + ['start', 'api']),
('negative', [sys.executable, 'student-tests/negative.py']),
('faults', [sys.executable, 'student-tests/faults.py']),
('attachment-failover', [sys.executable, 'student-tests/attachment-failover.py']),
('upload-load', [sys.executable, 'student-tests/upload-load.py']),
('cleanup', ['scripts/cleanup.sh']),
('cleanup-repeat', ['scripts/cleanup.sh']),
('storage-audit', [sys.executable, 'student-tests/audit-storage.py']),
]
results = []
try:
for name, command in checks:
print('RUN:', name, flush=True)
start = time.monotonic()
with (root / 'evidence' / (name + '.txt')).open('w') as output:
result = subprocess.run(command, env=env, stdout=output, stderr=subprocess.STDOUT)
record = {'check': name, 'command': command, 'exit_code': result.returncode, 'seconds': round(time.monotonic()-start, 3)}
results.append(record)
(root / 'evidence/verification.json').write_text(json.dumps(results, indent=2) + '\n')
print(('PASS:' if result.returncode == 0 else 'FAIL:'), name, 'seconds=', record['seconds'], flush=True)
if result.returncode:
print((root / 'evidence' / (name + '.txt')).read_text(), flush=True)
raise SystemExit(result.returncode)
if name in ('restore-after-failover', 'attachment-failover'):
time.sleep(4)
finally:
subprocess.run(compose + ['start', 'postgres', 's3', 'api'], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)