This commit is contained in:
k00kzaAntonovaIra
2026-11-06 13:57:29 +03:00
parent ec540a1a72
commit 8d001712fe
194 changed files with 13448 additions and 203 deletions
+56 -32
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Offline structural checks; full schema validation is a separate target."""
import ast
import json
from pathlib import Path
@@ -7,48 +8,71 @@ import re
ROOT = Path(__file__).resolve().parents[1]
def main():
lab = json.loads((ROOT/'lab.json').read_text())['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
assert spec['openapi']=='3.1.0'
assert spec['info']['version']=='1.%d.0'%lab
lab = json.loads((ROOT / "lab.json").read_text())["number"]
spec = json.loads((ROOT / "contracts/openapi.json").read_text())
assert spec["openapi"] == "3.1.0"
assert spec["info"]["version"] == "1.%d.0" % lab
operation_ids = set()
def walk(value):
if isinstance(value,dict):
if '$ref' in value:
pointer = value['$ref']
assert pointer.startswith('#/'), 'unexpected external reference'
if isinstance(value, dict):
if "$ref" in value:
pointer = value["$ref"]
assert pointer.startswith("#/"), "unexpected external reference"
target = spec
for part in pointer[2:].split('/'):
target = target[part.replace('~1','/').replace('~0','~')]
for part in pointer[2:].split("/"):
target = target[part.replace("~1", "/").replace("~0", "~")]
for v in value.values():
walk(v)
elif isinstance(value,list):
elif isinstance(value, list):
for v in value:
walk(v)
walk(spec)
for route,methods in spec['paths'].items():
placeholders = set(re.findall(r'\{([^}]+)\}',route))
for method,op in methods.items():
assert op['operationId'] not in operation_ids, 'duplicate operationId'
operation_ids.add(op['operationId'])
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
assert placeholders==params, 'path parameter mismatch: '+route
for response in op['responses'].values():
assert 'X-Request-Id' in response['headers']
if lab>=3:
assert 'X-Instance-Id' in response['headers']
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
ast.parse(file.read_text(),filename=str(file))
for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
for route, methods in spec["paths"].items():
placeholders = set(re.findall(r"\{([^}]+)\}", route))
for method, op in methods.items():
assert op["operationId"] not in operation_ids, "duplicate operationId"
operation_ids.add(op["operationId"])
params = {
p["name"]
for p in op.get("parameters", [])
if p["in"] == "path" and p.get("required")
}
assert placeholders == params, "path parameter mismatch: " + route
for response in op["responses"].values():
assert "X-Request-Id" in response["headers"]
if lab >= 3:
assert "X-Instance-Id" in response["headers"]
assert ("/api/v1/auth/sessions" in spec["paths"]) == (lab >= 2)
assert ("/api/v1/attachments/{attachment_id}" in spec["paths"]) == (lab >= 4)
for file in list((ROOT / "tests").glob("*.py")) + list(
(ROOT / "scripts").glob("*.py")
):
ast.parse(file.read_text(encoding="utf-8"), filename=str(file))
for file in ROOT.rglob("*.json"):
if any(
part in {".git", ".venv", "node_modules", "vendor", "output"}
for part in file.parts
):
continue
json.loads(file.read_text())
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
for required in (
"README.md",
"COURSE.md",
"CONTRIBUTING.md",
"REPORT.md",
"contracts/README.md",
"tests/smoke.py",
"tests/README.md",
):
assert (ROOT / required).is_file(), "missing " + required
print(
"PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
)
if __name__=='__main__':
if __name__ == "__main__":
main()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Проверка срока жизни сессии, выхода и неверного пароля на запущенном API.
python scripts/check_expiry.py --base-url http://localhost:8081 --ttl 3
API должен работать с SESSION_TTL_SECONDS, равным --ttl.
"""
import argparse
import base64
import json
import sys
import time
import urllib.error
import urllib.request
import uuid
from datetime import datetime, timezone
def http(base, method, path, body=None, headers=None):
"""HTTP-запрос: (статус, заголовки, тело)."""
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(base + path, data=data, method=method, headers=dict(headers or {}))
if data is not None:
request.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(request, timeout=10) as reply:
return reply.status, reply.headers, reply.read()
except urllib.error.HTTPError as error:
return error.code, error.headers, error.read()
def step(text, ok):
"""Напечатать результат шага; при неудаче завершить с кодом 1."""
print(("OK " if ok else "FAIL ") + text, flush=True)
if not ok:
sys.exit(1)
def main():
"""Выполнить проверку."""
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8081")
parser.add_argument("--ttl", type=float, default=3)
args = parser.parse_args()
base = args.base_url.rstrip("/")
username, password = "ttl_" + uuid.uuid4().hex[:8], "Expiry-" + uuid.uuid4().hex
basic = {"Authorization": "Basic " + base64.b64encode((username + ":" + password).encode()).decode()}
status, _, _ = http(base, "POST", "/api/v1/users",
{"username": username, "display_name": "TTL", "password": password})
step("регистрация -> %d" % status, status == 201)
status, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers=basic)
session = json.loads(raw)
expires = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
left = (expires - datetime.now(timezone.utc)).total_seconds()
step("вход -> %d, expires_at через %.1f с (TTL=%g)" % (status, left, args.ttl),
status == 201 and 0 < left <= args.ttl + 1)
bearer = {"Authorization": "Bearer " + session["token"]}
for n in range(3):
status, _, _ = http(base, "GET", "/api/v1/users/me", headers=bearer)
step("GET /users/me #%d до истечения -> %d" % (n + 1, status), status == 200)
time.sleep(args.ttl + 1)
status, headers, raw = http(base, "GET", "/api/v1/users/me", headers=bearer)
step("GET /users/me после TTL+1 с -> %d, WWW-Authenticate: %s, code=%s"
% (status, headers.get("WWW-Authenticate"), json.loads(raw)["error"]["code"]),
status == 401 and headers.get("WWW-Authenticate") == 'Bearer realm="messenger"')
status, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers=basic)
bearer = {"Authorization": "Bearer " + json.loads(raw)["token"]}
step("новый вход -> %d" % status, status == 201)
status, _, _ = http(base, "DELETE", "/api/v1/auth/sessions/current", headers=bearer)
step("logout -> %d" % status, status == 204)
status, _, _ = http(base, "GET", "/api/v1/users/me", headers=bearer)
step("GET /users/me после logout -> %d" % status, status == 401)
status, _, _ = http(base, "DELETE", "/api/v1/auth/sessions/current", headers=bearer)
step("повторный logout -> %d" % status, status == 401)
wrong = {"Authorization": "Basic " + base64.b64encode((username + ":wrong-password-123").encode()).decode()}
status, headers, _ = http(base, "POST", "/api/v1/auth/sessions", headers=wrong)
step("вход с неверным паролем -> %d, WWW-Authenticate: %s" % (status, headers.get("WWW-Authenticate")),
status == 401 and headers.get("WWW-Authenticate", "").startswith("Basic"))
print("PASS: expiry (TTL=%g с), logout и неверный пароль на запущенном API" % args.ttl)
return 0
if __name__ == "__main__":
sys.exit(main())
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Статические ограничения стенда lab4; не заменяет docker compose config/nginx -t."""
import ast
import json
import os
from pathlib import Path
import shutil
import subprocess
import yaml
ROOT = Path(__file__).resolve().parents[1]
def main():
config = yaml.safe_load((ROOT / "compose.yaml").read_text(encoding="utf-8"))
services = config["services"]
assert {"api-a", "api-b", "migrate", "nginx", "db", "redis", "minio", "minio-init", "cleanup"} <= services.keys()
assert config["networks"]["data"]["internal"] is True
for name, service in services.items():
assert "container_name" not in service, name
assert float(service["cpus"]) > 0 and service["mem_limit"], name
if name != "nginx":
assert "ports" not in service, name
for name in ("api-a", "api-b"):
assert services[name]["depends_on"]["migrate"]["condition"] == "service_completed_successfully"
assert services[name]["stop_grace_period"] == "10s"
assert services["migrate"]["command"] == ["python", "-m", "app.migrate"]
assert services["nginx"]["image"] == "nginx:1.28.0-alpine"
assert services["nginx"]["networks"] == ["edge"]
assert {"pgdata", "miniodata"} <= config["volumes"].keys()
assert services["minio"]["environment"]["MINIO_BROWSER"] == "off"
assert "latest" not in services["minio"]["image"]
assert "MINIO_ROOT_PASSWORD" not in services["api-a"]["environment"]
assert "S3_SECRET_KEY" in services["api-a"]["environment"]
assert services["cleanup"]["command"] == ["python", "-m", "app.cleanup", "--loop"]
assert not any("docker.sock" in str(s) for s in services.values())
spec = json.loads((ROOT / "contracts/openapi.json").read_text(encoding="utf-8"))
operation = spec["paths"]["/api/v1/chats/{chat_id}/messages"]["post"]
assert any(p["name"] == "Idempotency-Key" and p["required"] for p in operation["parameters"])
for directory in ("app", "scripts", "student-tests", "unit-tests", "tests"):
for path in (ROOT / directory).rglob("*.py"):
ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
shell = shutil.which("sh")
if shell:
for path in list((ROOT / "scripts").glob("*.sh")) + list((ROOT / "infra").rglob("*.sh")):
subprocess.run([shell, "-n", str(path)], check=True)
else:
print("SKIP: shell syntax (sh unavailable); container entrypoint requires runtime verification.")
for filename in ("scripts/stop_one.py", "scripts/restart.py"):
path = ROOT / filename
assert path.is_file()
if os.name != "nt":
assert path.stat().st_mode & 0o111
print("PASS: lab4 static structure, resource/port isolation, contract, Python syntax; runtime NOT tested.")
if __name__ == "__main__":
main()
+428
View File
@@ -0,0 +1,428 @@
#!/usr/bin/env python3
"""Проверки кластера: останавливает и восстанавливает API, заменяет контейнеры."""
import argparse
import http.client
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import threading
import time
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
from resilience import history
from replicas import (
COMPOSE,
SERVICES,
compose,
inventory,
probe,
replace,
undrain,
wait_balanced,
wait_ready,
)
def save_json(path, value):
path.write_text(
json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
def record_command(out, name, command, env=None):
"""Записать реальный вывод команды; не запрашивать полный inspect или env."""
started = time.monotonic()
result = subprocess.run(
command,
cwd=ROOT,
text=True,
encoding="utf-8",
errors="replace",
capture_output=True,
env=env,
)
(out / (name + ".txt")).write_text(
"$ "
+ " ".join(command)
+ "\n"
+ result.stdout
+ result.stderr
+ f"\nexit_code={result.returncode}; elapsed_seconds={time.monotonic() - started:.3f}\n",
encoding="utf-8",
)
check(result.returncode == 0, name + " failed; inspect evidence file")
def observe(c, actor):
seen = set()
for _ in range(50):
try:
resp = c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
instance_id = resp["headers"].get("X-Instance-Id")
if instance_id:
seen.add(instance_id)
except Exception:
pass
if len(seen) >= 2:
break
time.sleep(0.1)
check(len(seen) >= 2, "one session must be accepted by at least two API processes")
return sorted(seen)
def concurrent_replay(base):
"""Одновременный один ключ через LB; один id, одна строка истории, обе реплики."""
c = Client(base)
alice, bob, eve, chat = c.bootstrap()
key = uuid.uuid4().hex
barrier = threading.Barrier(12)
def worker(_):
local = Client(base)
barrier.wait()
return local.message(alice, chat, "одновременный повтор", key=key)
with ThreadPoolExecutor(max_workers=12) as pool:
responses = list(pool.map(worker, range(12)))
ids = {r["json"]["id"] for r in responses}
instances = {r["headers"]["X-Instance-Id"] for r in responses}
check(len(ids) == 1, "concurrent replay created different messages")
check(len(instances) >= 2, "replay did not cross two API processes")
rows = history(c, bob, chat)
check(
len(rows) == 1 and rows[0] == responses[0]["json"],
"history must contain one exact response",
)
c.call(
"POST",
"/api/v1/chats/" + chat["id"] + "/messages",
409,
actor=alice,
body={"text": "другое тело"},
headers={"Idempotency-Key": key},
)
replay = c.message(alice, chat, "одновременный повтор", key=key)
check(replay["json"] == responses[0]["json"], "409 changed original result")
return {
"parallel_requests": 12,
"unique_message_ids": len(ids),
"history_rows": len(rows),
"instances": sorted(instances),
"conflict_status": 409,
}
def experiment(base, service, mode, duration):
"""Closed-loop чтение/запись во время stop или поочерёдной замены."""
c = Client(base, timeout=2)
alice, bob, eve, chat = c.bootstrap()
initial = c.message(alice, chat, "подтверждено до действия")["json"]
seen = observe(c, alice)
before = inventory()
target = probe(service)["instance_id"]
events, confirmed = [], [initial]
lock = threading.Lock()
halt = threading.Event()
started = time.monotonic()
def worker(number):
local = Client(base, timeout=2)
key, text = uuid.uuid4().hex, ""
while not halt.is_set():
if not text:
text = "load-" + key
for operation in ("write", "read"):
t0 = time.monotonic()
try:
response = (
local.message(alice, chat, text, key=key)
if operation == "write"
else local.call(
"GET",
"/api/v1/chats/" + chat["id"] + "/messages?limit=1",
actor=bob,
schema="MessagePage",
)
)
event = {
"start": t0,
"end": time.monotonic(),
"kind": operation,
"ok": True,
"instance": response["headers"]["X-Instance-Id"],
}
with lock:
if operation == "write":
confirmed.append(response["json"])
if operation == "write":
key, text = uuid.uuid4().hex, ""
except (Failure, OSError, http.client.HTTPException):
event = {
"start": t0,
"end": time.monotonic(),
"kind": operation,
"ok": False,
}
with lock:
events.append(event)
time.sleep(0.02)
with ThreadPoolExecutor(max_workers=2) as pool:
futures = [pool.submit(worker, n) for n in range(2)]
time.sleep(1)
action_started = time.monotonic()
try:
if mode == "stop":
env = {**os.environ, "TARGET_INSTANCE_ID": target}
# Вызываем replicas.py stop-target напрямую через текущий интерпретатор Python
result = subprocess.run(
[sys.executable, str(ROOT / "scripts/replicas.py"), "stop-target"],
cwd=ROOT,
env=env,
text=True,
encoding="utf-8",
errors="replace",
capture_output=True,
timeout=60,
)
check(result.returncode == 0, "stop hook failed")
action_detail = result.stdout
else:
action_detail = replace(service)
action_finished = time.monotonic()
after_action = inventory()
if mode == "stop":
stopped = next(row for row in after_action if row["service"] == service)
check(
stopped["state"] == "exited" and stopped["pid"] == 0,
"target process is still running",
)
deadline = max(action_started + duration, action_finished + 5)
while time.monotonic() < deadline:
time.sleep(0.1)
finally:
halt.set()
for future in futures:
future.result()
finished = time.monotonic()
rows = history(c, bob, chat)
by_id = {row["id"]: row for row in rows}
check(
all(by_id.get(message["id"]) == message for message in confirmed),
"confirmed data was lost",
)
texts = [row["text"] for row in rows]
check(len(texts) == len(set(texts)), "uncertain retry created duplicate text")
tail = [e for e in events if e["start"] >= action_finished]
check(any(e["ok"] and e["kind"] == "write" for e in tail), "no writes after action")
check(any(e["ok"] and e["kind"] == "read" for e in tail), "no reads after action")
if mode == "stop":
check(
all(e.get("instance") != target for e in tail if e["ok"]),
"stopped instance still responds",
)
for kind in ("write", "read"):
recovered = min(e["end"] for e in tail if e["ok"] and e["kind"] == kind)
check(recovered - action_started <= 10, kind + " recovery exceeded 10s")
def metrics(items, elapsed):
good = [e for e in items if e["ok"]]
failed = len(items) - len(good)
latencies = sorted((e["end"] - e["start"]) * 1000 for e in good)
def percentile(fraction):
return (
round(latencies[max(0, int(len(latencies) * fraction + 0.999) - 1)], 3)
if latencies
else None
)
return {
"elapsed_seconds": round(elapsed, 3),
"attempts": len(items),
"successes": len(good),
"errors": failed,
"error_ratio": round(failed / len(items), 6) if items else None,
"successful_rps": round(len(good) / elapsed, 3),
"successful_latency_ms": {
"p50": percentile(0.5),
"p95": percentile(0.95),
"p99": percentile(0.99),
},
}
result = {
"mode": mode,
"service": service,
"target_instance": target,
"observed_with_one_session": seen,
"before": before,
"after_action": after_action,
"action": action_detail,
"action_seconds": round(action_finished - action_started, 3),
"concurrency": 2,
"total": metrics(events, finished - started),
"during_and_after_action": metrics(
[e for e in events if e["start"] >= action_started],
finished - action_started,
),
"confirmed_responses": len(confirmed),
"history_messages": len(rows),
"duplicates": 0,
"existing_session_works": True,
}
for kind in ("write", "read"):
after = [e for e in tail if e["ok"] and e["kind"] == kind]
result["first_" + kind + "_after_action_seconds"] = round(
min(e["end"] for e in after) - action_started, 3
)
result[kind] = metrics(
[e for e in events if e["kind"] == kind], finished - started
)
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--output", default="evidence/cluster")
parser.add_argument("--duration", type=float, default=20)
args = parser.parse_args()
check(15 <= args.duration <= 120, "duration must be 15..120 seconds")
out = ROOT / args.output
out.mkdir(parents=True, exist_ok=True)
save_json(out / "result.json", {"status": "RUNNING"})
try:
os.environ["BASE_URL"] = args.base_url
save_json(
out / "00_environment.json",
{
"at_utc": datetime.now(timezone.utc).isoformat(),
"platform": platform.platform(),
"cpu_count": os.cpu_count(),
"python": platform.python_version(),
"duration": args.duration,
"workload": "2 closed-loop clients, POST+GET; uncertain POST retried with same key/body",
},
)
record_command(out, "01_docker", ["docker", "version"])
record_command(out, "02_compose_config", COMPOSE + ["config", "--quiet"])
wait_balanced()
save_json(out / "03_processes.json", inventory())
record_command(out, "03_limits", COMPOSE + ["ps", "-q"])
ids = compose("ps", "-q", capture=True).splitlines()
record_command(
out,
"03_container_limits",
[
"docker",
"inspect",
"--format",
"{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}} ports={{json .HostConfig.PortBindings}}",
*ids,
],
)
record_command(
out,
"04_smoke",
[sys.executable, "tests/smoke.py", "--base-url", args.base_url],
)
save_json(
out / "05_concurrent_idempotency.json", concurrent_replay(args.base_url)
)
try:
for service in SERVICES:
wait_balanced()
report = experiment(args.base_url, service, "stop", args.duration)
save_json(out / ("06_failover_" + service + ".json"), report)
compose("up", "-d", "--no-deps", service)
wait_balanced()
record_command(
out,
"07_public_failover",
[
sys.executable,
"tests/resilience.py",
"--mode",
"failover",
"--action-script",
"scripts/stop_one.py",
"--base-url",
args.base_url,
],
)
for service in SERVICES:
compose("up", "-d", "--no-deps", service)
wait_balanced()
for service in SERVICES:
save_json(
out / ("08_rolling_" + service + ".json"),
experiment(args.base_url, service, "replace", args.duration),
)
record_command(
out,
"09_persistence",
[
sys.executable,
"tests/resilience.py",
"--mode",
"persistence",
"--action-script",
"scripts/restart.py",
"--base-url",
args.base_url,
],
)
wait_balanced()
save_json(out / "10_processes_after.json", inventory())
record_command(
out,
"11_nginx",
COMPOSE
+ ["exec", "-T", "nginx", "nginx", "-T", "-c", "/opt/lb/nginx.conf"],
)
record_command(
out,
"12_student_tests",
COMPOSE + ["--profile", "test", "run", "--rm", "--build", "tests"],
)
save_json(
out / "result.json",
{"status": "PASS", "at_utc": datetime.now(timezone.utc).isoformat()},
)
except Exception:
save_json(
out / "result.json",
{
"status": "FAIL",
"note": "Inspect completed evidence files; failed runs are not evidence of passing.",
},
)
raise
finally:
for service in SERVICES:
compose("up", "-d", "--no-deps", service)
undrain(service)
print("PASS: evidence saved to " + str(out.relative_to(ROOT)))
except BaseException:
save_json(
out / "result.json",
{
"status": "FAIL",
"note": "Run did not finish successfully; inspect completed outputs.",
},
)
raise
if __name__ == "__main__":
main()
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/lab4_evidence.py "$@"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Сверить нормативные файлы с чистым clone без изменения эталона."""
import argparse
import ast
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FILES = (
'contracts/openapi.json', 'contracts/examples.json', 'contracts/infrastructure.json',
'contracts/README.md', 'tests/client.py', 'tests/smoke.py', 'tests/load.py',
'tests/image_probe.py', 'tests/fixtures/sample.png',
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--reference', type=Path, required=True)
parser.add_argument('--output', type=Path, default=ROOT / 'evidence/lab4/contract_comparison.json')
args = parser.parse_args()
rows = []
for filename in FILES:
reference = (args.reference / filename).read_bytes()
actual = (ROOT / filename).read_bytes()
rows.append({'file': filename, 'identical': reference == actual,
'sha256': hashlib.sha256(actual).hexdigest()})
original_tree = ast.parse((args.reference / 'tests/resilience.py').read_text(encoding='utf-8'))
actual_tree = ast.parse((ROOT / 'tests/resilience.py').read_text(encoding='utf-8'))
actual_tree.body = [node for node in actual_tree.body
if not (isinstance(node, ast.FunctionDef) and node.name == 'hook_command')
and not (isinstance(node, ast.Import) and len(node.names) == 1
and node.names[0].name in ('shutil', 'sys'))]
for node in ast.walk(actual_tree):
if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
and node.func.attr == 'Popen' and node.args
and isinstance(node.args[0], ast.Call)
and isinstance(node.args[0].func, ast.Name)
and node.args[0].func.id == 'hook_command'):
node.args[0] = ast.parse('[str(script)]', mode='eval').body
acceptance_identical = ast.dump(original_tree) == ast.dump(actual_tree)
result = {'resilience_acceptance_ast_identical': acceptance_identical, 'source': str(args.reference.resolve()), 'at_utc': datetime.now(timezone.utc).isoformat(),
'files': rows, 'resilience_difference': 'Only portable Python/shell hook interpreter resolution; acceptance assertions preserved.'}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')
for row in rows:
print(('PASS ' if row['identical'] else 'FAIL ') + row['file'])
print(('PASS ' if acceptance_identical else 'FAIL ') + 'resilience acceptance unchanged after interpreter adapter')
return int(not acceptance_identical or any(not row['identical'] for row in rows))
if __name__ == '__main__':
raise SystemExit(main())
+171
View File
@@ -0,0 +1,171 @@
"""Переносимые помощники экспериментов: stdin для секретов и cgroup RAM sampler."""
import json
import os
from pathlib import Path
import struct
import subprocess
import threading
import time
import zlib
from replicas import COMPOSE, ROOT
def save_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def record_command(out, name, command, *, timeout=600):
"""Записать только команды, не содержащие credentials или полные inspect/env."""
started = time.monotonic()
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
result = subprocess.run(command, cwd=ROOT, capture_output=True, env=env, timeout=timeout)
output = (result.stdout + result.stderr).decode("utf-8", errors="replace")
(out / (name + ".txt")).write_text(
"$ " + " ".join(map(str, command)) + "\n" + output
+ f"\nexit_code={result.returncode}; elapsed_seconds={time.monotonic() - started:.3f}\n",
encoding="utf-8",
)
if result.returncode:
raise RuntimeError(name + " failed; inspect the evidence file")
def exec_json(service, code, payload=None, *, timeout=90):
"""JSON передаётся через stdin, поэтому Bearer не появляется в argv или evidence."""
result = subprocess.run(
COMPOSE + ["exec", "-T", service, "python", "-c", code],
cwd=ROOT,
input=json.dumps(payload or {}).encode("utf-8"),
capture_output=True,
timeout=timeout,
)
if result.returncode:
# Не печатать stderr кода, который имеет доступ к credentials.
raise RuntimeError("in-container check failed in " + service)
try:
return json.loads(result.stdout)
except (ValueError, UnicodeError):
raise RuntimeError("in-container check returned invalid JSON") from None
def png_fixture(width=1024, height=683):
"""Настоящий RGB PNG >2 MiB, без Pillow и случайного содержимого на хосте."""
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(
">I", zlib.crc32(kind + data) & 0xffffffff
)
row = bytes(range(256)) * ((width * 3 + 255) // 256)
pixels = b"".join(b"\x00" + row[:width * 3] for _ in range(height))
return (
b"\x89PNG\r\n\x1a\n"
+ chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ chunk(b"IDAT", zlib.compress(pixels, level=0))
+ chunk(b"IEND", b"")
)
MEMORY_SAMPLER = r'''
import json, pathlib, sys, threading, time
stop = threading.Event()
threading.Thread(target=lambda: (sys.stdin.buffer.read(), stop.set()), daemon=True).start()
root = pathlib.Path('/sys/fs/cgroup')
if (root / 'memory.current').exists():
names = ('memory.current', 'memory.peak', 'memory.max')
version = 2
else:
root = root / 'memory'
names = ('memory.usage_in_bytes', 'memory.max_usage_in_bytes', 'memory.limit_in_bytes')
version = 1
started = time.monotonic()
def number(name):
try:
value = (root / name).read_text().strip()
return int(value) if value != 'max' else None
except (OSError, ValueError):
return None
def sample():
rss = None
try:
for line in pathlib.Path('/proc/1/status').read_text().splitlines():
if line.startswith('VmRSS:'):
rss = int(line.split()[1]) * 1024
except (OSError, ValueError):
pass
print(json.dumps({'seconds': round(time.monotonic() - started, 3),
'cgroup_version': version, 'memory_current_bytes': number(names[0]),
'container_lifetime_peak_bytes': number(names[1]), 'limit_bytes': number(names[2]),
'api_pid1_rss_bytes': rss}), flush=True)
sample()
while not stop.wait(0.2):
sample()
sample()
'''
class MemorySampler:
"""Один небольшой Python-процесс в API читает RAM каждые 200 мс."""
def __init__(self, service):
self.service = service
self.samples = []
self.ready = threading.Event()
self.process = None
def start(self):
self.process = subprocess.Popen(
COMPOSE + ["exec", "-T", self.service, "python", "-u", "-c", MEMORY_SAMPLER],
cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
def read():
for line in self.process.stdout:
try:
sample = json.loads(line)
self.samples.append(sample)
self.ready.set()
except (ValueError, UnicodeError):
pass
self.reader = threading.Thread(target=read, daemon=True)
self.reader.start()
if not self.ready.wait(timeout=10):
self.stop()
raise RuntimeError("memory sampler did not start in " + self.service)
if self.samples[0]["memory_current_bytes"] is None:
self.stop()
raise RuntimeError("cgroup memory counters unavailable in " + self.service)
return self
def stop(self):
if self.process is None:
return
self.process.stdin.close()
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait(timeout=5)
self.reader.join(timeout=5)
self.process.stdout.close()
self.process.stderr.close()
self.process = None
def report(self):
current = [s["memory_current_bytes"] for s in self.samples if s["memory_current_bytes"] is not None]
rss = [s["api_pid1_rss_bytes"] for s in self.samples if s["api_pid1_rss_bytes"] is not None]
lifetime = [s["container_lifetime_peak_bytes"] for s in self.samples if s["container_lifetime_peak_bytes"] is not None]
return {
"service": self.service,
"sampling_interval_seconds": 0.2,
"baseline_cgroup_bytes": current[0],
"sampled_cgroup_peak_bytes": max(current),
"sampled_growth_bytes": max(current) - current[0],
"sampled_api_pid1_rss_peak_bytes": max(rss) if rss else None,
"container_lifetime_peak_bytes": max(lifetime) if lifetime else None,
"limit_bytes": self.samples[0]["limit_bytes"],
"samples": self.samples,
"limitations": "cgroup includes file cache and sampler overhead; 200 ms samples may miss short spikes; lifetime peak may predate this experiment",
}
+70
View File
@@ -0,0 +1,70 @@
#!/usr/bin/env python3
"""Создать локальный .env для lab4 без вывода секретов; работает в PowerShell."""
import argparse
import os
from pathlib import Path
import secrets
ROOT = Path(__file__).resolve().parents[1]
def initialize(path: Path):
"""Сохранить существующие значения, заполнить отсутствующие настройки."""
lines = path.read_text(encoding="utf-8-sig").splitlines() if path.exists() else []
values = {}
positions = {}
for index, line in enumerate(lines):
if line.strip() and not line.lstrip().startswith("#") and "=" in line:
key, value = line.split("=", 1)
values[key.strip()] = value.strip()
positions.setdefault(key.strip(), []).append(index)
defaults = {
"POSTGRES_USER": "messenger",
"POSTGRES_PASSWORD": secrets.token_hex(24),
"POSTGRES_DB": "messenger",
"SESSION_TTL_SECONDS": "3600",
"CACHE_URL": "redis://redis:6379/0",
"LOG_LEVEL": "WARNING",
"API_IMAGE": "mtusi-messenger:lab4",
"MINIO_ROOT_USER": "minio-root",
"MINIO_ROOT_PASSWORD": secrets.token_hex(32),
"S3_BUCKET": "attachments",
"S3_ACCESS_KEY": "api_" + secrets.token_hex(8),
"S3_SECRET_KEY": secrets.token_hex(20),
}
changed = []
for key, default in defaults.items():
existing = values.get(key, "")
upgrade_image = key == "API_IMAGE" and existing == "mtusi-messenger:lab3"
if key in values and existing and not existing.startswith("CHANGE_ME") and not upgrade_image:
continue
# An explicitly empty CACHE_URL means the optional cache is disabled.
if key == "CACHE_URL" and key in values:
continue
if key in positions:
for index in positions[key]:
lines[index] = key + "=" + default
else:
lines.append(key + "=" + default)
changed.append(key)
if changed or not path.exists():
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
if os.name != "nt":
path.chmod(0o600)
return changed
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", type=Path, default=ROOT / ".env")
args = parser.parse_args()
changed = initialize(args.output)
print(".env: " + ("обновлены настройки " + ", ".join(changed) if changed else "уже настроен"))
print("Существующий пароль PostgreSQL сохранён; значения секретов не выводятся.")
if __name__ == "__main__":
main()
+389
View File
@@ -0,0 +1,389 @@
#!/usr/bin/env python3
"""Повторяемая проверка lab4: реальные отказы, приватный MinIO и 10 uploads с RAM."""
import argparse
import base64
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from urllib.parse import quote
from evidence_utils import MemorySampler, exec_json, png_fixture, record_command, save_json
from replicas import COMPOSE, ROOT, SERVICES, compose, inventory, wait_balanced
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check
from resilience import history
def upload(c, actor, chat, content, filename="sample.png"):
response = c.call(
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote(filename),
201, actor=actor, raw=content, headers={"Content-Type": "image/png"}, schema="Attachment",
)
att = response["json"]
check(att["status"] == "ready" and att["error_code"] is None, "upload must finish ready")
check(att["variants"] == [], "lab4 must return the original without variants")
check(att["size_bytes"] == len(content), "uploaded size mismatch")
check(att["sha256"] == hashlib.sha256(content).hexdigest(), "uploaded checksum mismatch")
check(att["chat_id"] == chat["id"] and att["owner_id"] == actor["id"], "upload ownership mismatch")
return response
def download(c, actor, att, content):
metadata = c.call("GET", "/api/v1/attachments/" + att["id"], actor=actor, schema="Attachment")
check(metadata["json"] == att, "attachment metadata changed")
response = c.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=actor)
check(response["bytes"] == content, "download differs byte-for-byte from original")
check(response["headers"].get_content_type() == "image/png", "download Content-Type mismatch")
return response
def attachment_contract(c, alice, bob, eve, chat, content):
response = upload(c, alice, chat, content)
att = response["json"]
attached = c.message(alice, chat, "", attachments=[att["id"]])["json"]
check(attached["attachment_ids"] == [att["id"]], "attachment-only message lost attachment")
check(attached in history(c, bob, chat), "second member cannot read attached message")
download(c, bob, att, content)
for suffix in ("", "/content"):
c.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=eve)
return {
"attachment_id": att["id"], "upload_instance": response["headers"]["X-Instance-Id"],
"sha256": att["sha256"], "size_bytes": len(content), "download_equal": True,
"attachment_only_message_visible": True, "outsider_metadata_status": 404,
"outsider_content_status": 404,
}, att, response["headers"]["X-Instance-Id"]
def uploader_failover(c, bob, att, content, target):
"""Остановить именно процесс, вернувший 201 на binary upload."""
before = inventory()
matches = [row for row in before if row.get("instance_id") == target]
check(len(matches) == 1, "upload must identify one current API process")
service = matches[0]["service"]
started = time.monotonic()
try:
env = dict(os.environ, TARGET_INSTANCE_ID=target, PYTHONUTF8="1")
result = subprocess.run(
[sys.executable, str(ROOT / "scripts/stop_one.py")], cwd=ROOT, env=env,
capture_output=True, timeout=15,
)
check(result.returncode == 0, "could not stop uploading API")
stopped = next(row for row in inventory() if row["service"] == service)
check(stopped["state"] == "exited" and stopped["pid"] == 0, "upload process still alive")
deadline = time.monotonic() + 10
while True:
try:
response = download(c, bob, att, content)
break
except Failure:
check(time.monotonic() < deadline, "download failed to recover after uploader stop")
time.sleep(0.2)
survivor = response["headers"]["X-Instance-Id"]
check(survivor != target, "download came from the stopped uploader")
return {
"upload_instance": target, "stopped_service": service,
"stopped_state": stopped["state"], "stopped_pid": stopped["pid"],
"download_instance": survivor, "sha256": hashlib.sha256(response["bytes"]).hexdigest(),
"download_equal": True, "seconds_from_stop_start": round(time.monotonic() - started, 3),
}
finally:
compose("up", "-d", "--no-deps", service)
wait_balanced(timeout=60)
def persistence(c, bob, chat, att, content, out):
before = inventory()
record_command(out, "04_restart_command", [sys.executable, "scripts/restart.py"], timeout=120)
after = inventory()
check({r["instance_id"] for r in before}.isdisjoint(r["instance_id"] for r in after),
"restart must replace both API processes")
response = download(c, bob, att, content)
check(any(att["id"] in message["attachment_ids"] for message in history(c, bob, chat)),
"attached message lost after restart")
return {
"before": before, "after": after, "existing_session_works": True,
"message_preserved": True, "metadata_equal": True, "download_equal": True,
"sha256": hashlib.sha256(response["bytes"]).hexdigest(),
"restart_scope": "all default Compose services, force recreated; named volumes retained",
}
DIRECT_PROBES = r'''
import base64, json, urllib.error, urllib.request, sys
p = json.load(sys.stdin)
result = {}
for name, method, path, body in (
('live', 'GET', '/health/live', None),
('ready', 'GET', '/health/ready', None),
('upload', 'POST', '/api/v1/chats/' + p['chat_id'] + '/attachments?filename=outage.png', base64.b64decode(p['png'])),
('content', 'GET', '/api/v1/attachments/' + p['attachment_id'] + '/content', None),
):
headers = {'Authorization': 'Bearer ' + p['token'], 'Content-Type': 'image/png'}
request = urllib.request.Request('http://127.0.0.1:8080' + path, method=method, headers=headers, data=body)
try:
response = urllib.request.urlopen(request, timeout=30)
except urllib.error.HTTPError as error:
response = error
with response:
data = response.read(16 * 1024 * 1024)
result[name] = {'status': response.status, 'instance_id': response.headers.get('X-Instance-Id'),
'request_id_present': bool(response.headers.get('X-Request-Id'))}
if response.status >= 400:
error = json.loads(data)['error']
result[name]['error_code'] = error['code']
result[name]['request_id_matches'] = error['request_id'] == response.headers.get('X-Request-Id')
print(json.dumps(result))
'''
def s3_outage(c, alice, bob, chat, att, content):
results = {}
public = None
try:
compose("stop", "--timeout", "10", "minio")
for service in SERVICES:
results[service] = exec_json(service, DIRECT_PROBES, {
"token": alice["token"], "chat_id": chat["id"], "attachment_id": att["id"],
"png": base64.b64encode(content).decode("ascii"),
}, timeout=120)
for name, status in (("live", 200), ("ready", 503), ("upload", 503), ("content", 503)):
actual = results[service][name]
check(actual["status"] == status, service + "/" + name + ": " + str(actual))
check(actual["request_id_present"] and actual["instance_id"], "missing API trace headers")
if status == 503:
check(actual["error_code"] == "unavailable" and actual["request_id_matches"],
"S3 outage must return a structured 503")
try:
reply = urllib.request.urlopen(c.base + "/health/ready", timeout=10)
except urllib.error.HTTPError as error:
reply = error
with reply:
payload = json.loads(reply.read())
public = {"status": reply.status, "error_code": payload["error"]["code"],
"request_id_matches": payload["error"]["request_id"] == reply.headers.get("X-Request-Id")}
check(public["status"] == 503 and public["request_id_matches"], "public readiness must return structured 503")
finally:
compose("start", "minio")
wait_balanced(timeout=60)
download(c, bob, att, content)
return {"direct_api_probes": results, "public_readiness": public, "restored_download_equal": True,
"method": "probe each API directly inside its container because LB excludes unready backends"}
PRIVATE_BUCKET = r'''
import asyncio, io, json, os, sys, uuid, urllib.error, urllib.request
import urllib.error
import urllib.request
from urllib.parse import quote, urlsplit
from minio import Minio
from minio.error import S3Error
from sqlalchemy import text
from app.config import Settings
from app.db import create_engine
p = json.load(sys.stdin)
async def key():
engine = create_engine(Settings.from_env())
try:
async with engine.connect() as connection:
return (await connection.execute(text('SELECT object_key FROM attachments WHERE id=:id'),
{'id': uuid.UUID(p['attachment_id'])})).scalar_one()
finally:
await engine.dispose()
object_key = asyncio.run(key())
endpoint = os.environ['S3_ENDPOINT_URL'].rstrip('/')
bucket = os.environ['S3_BUCKET']
url = endpoint + '/' + quote(bucket, safe='') + '/' + quote(object_key, safe='/')
try:
response = urllib.request.urlopen(url, timeout=5)
except urllib.error.HTTPError as error:
response = error
with response:
anonymous_status = response.status
parsed = urlsplit(endpoint)
client = Minio(parsed.netloc, access_key=os.environ['S3_ACCESS_KEY'], secret_key=os.environ['S3_SECRET_KEY'],
secure=parsed.scheme == 'https', region=os.environ.get('S3_REGION', 'us-east-1'))
new_bucket = 'forbidden-' + uuid.uuid4().hex
outside_key = 'forbidden/' + uuid.uuid4().hex
operations = {
'list_foreign_bucket': lambda: list(client.list_objects(new_bucket, recursive=True)),
'make_bucket': lambda: client.make_bucket(new_bucket),
'put_outside_prefix': lambda: client.put_object(bucket, outside_key, io.BytesIO(b'x'), 1),
}
# MinIO deliberately filters ListBuckets to buckets permitted by bucket-level IAM.
# Verify the names rather than incorrectly requiring HTTP 403 for this API.
visible_buckets = [item.name for item in client.list_buckets()]
outcomes = {}
for name, operation in operations.items():
try:
operation()
outcomes[name] = 'UNEXPECTED_SUCCESS'
except S3Error as error:
outcomes[name] = error.code
except Exception as error:
outcomes[name] = type(error).__name__
# Clean synthetic probes if an incorrect policy unexpectedly allowed them.
for action in (
(lambda: client.remove_bucket(new_bucket)) if outcomes['make_bucket'] == 'UNEXPECTED_SUCCESS' else None,
(lambda: client.remove_object(bucket, outside_key)) if outcomes['put_outside_prefix'] == 'UNEXPECTED_SUCCESS' else None,
):
if action:
try: action()
except Exception: pass
print(json.dumps({'anonymous_get_status': anonymous_status, 'restricted_operations': outcomes,
'visible_buckets': visible_buckets, 'visible_buckets_limited': set(visible_buckets) <= {bucket},
'root_credentials_absent_in_api': not any(name in os.environ for name in ('MINIO_ROOT_USER', 'MINIO_ROOT_PASSWORD')),
'server_assigned_original_prefix': object_key.startswith('originals/')}))
'''
def private_bucket(att, out):
# The same bootstrap is executed twice against an already populated bucket.
for number in (1, 2):
record_command(out, "06_bootstrap_repeat_" + str(number),
COMPOSE + ["run", "--rm", "--no-deps", "minio-init"], timeout=120)
result = exec_json("api-a", PRIVATE_BUCKET, {"attachment_id": att["id"]})
check(result["anonymous_get_status"] == 403, "private bucket anonymous GET: " + str(result))
check(all(value == "AccessDenied" for value in result["restricted_operations"].values()),
"API S3 privilege violation: " + str(result))
check(result["visible_buckets_limited"], "API can see an unrelated bucket")
check(result["root_credentials_absent_in_api"], "API must not receive root S3 credentials")
check(result["server_assigned_original_prefix"], "unexpected server object key prefix")
result["bootstrap_repeated_successfully"] = 2
return result
def concurrent_uploads(base, alice, bob, chat, concurrency):
content = png_fixture()
check(len(content) >= 2 * 1024 * 1024, "experiment fixture must be at least 2 MiB")
barrier = threading.Barrier(concurrency, timeout=30)
samplers = []
def send(number):
client = Client(base, timeout=90)
barrier.wait()
started = time.monotonic()
try:
response = upload(client, alice, chat, content, "parallel-%02d.png" % number)
return {"ok": True, "started": started, "finished": time.monotonic(),
"attachment": response["json"], "instance": response["headers"]["X-Instance-Id"]}
except Exception as error:
return {"ok": False, "started": started, "finished": time.monotonic(),
"error": str(error) if isinstance(error, Failure) else type(error).__name__}
try:
for service in SERVICES:
samplers.append(MemorySampler(service).start())
with ThreadPoolExecutor(max_workers=concurrency) as pool:
responses = list(pool.map(send, range(concurrency)))
finally:
for sampler in samplers:
sampler.stop()
good = [r for r in responses if r["ok"]]
elapsed = max(r["finished"] for r in responses) - min(r["started"] for r in responses)
memory = [sampler.report() for sampler in samplers]
result = {
"concurrency": concurrency, "barrier_synchronized": True, "requests": len(responses),
"successes": len(good), "failures": len(responses) - len(good),
"fixture_bytes": len(content), "fixture_dimensions": [1024, 683],
"fixture_sha256": hashlib.sha256(content).hexdigest(),
"elapsed_seconds": round(elapsed, 3), "successful_uploads_per_second": round(len(good) / elapsed, 3),
"successful_mib_per_second": round(len(good) * len(content) / (1024 * 1024 * elapsed), 3),
"instances": sorted({r["instance"] for r in good}), "memory": memory,
"latency_seconds": [round(r["finished"] - r["started"], 3) for r in responses],
"errors": [r["error"] for r in responses if not r["ok"]],
}
# Preserve measured results even when the experiment finds a failure.
result["all_downloads_equal"] = False
if len(good) != concurrency:
return result
check(len({r["attachment"]["id"] for r in good}) == concurrency, "uploads reused attachment IDs")
check(len(result["instances"]) == len(SERVICES), "concurrent uploads did not visit both API replicas")
for response in good:
download(Client(base, timeout=30), bob, response["attachment"], content)
result["all_downloads_equal"] = True
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--output", default="evidence/lab4")
parser.add_argument("--concurrency", type=int, default=10)
parser.add_argument("--skip-cluster", action="store_true", help="Run only lab4 experiments; record omitted cluster coverage")
parser.add_argument("--skip-student-tests", action="store_true", help="Repeat infrastructure experiments without rerunning the already completed suite; record NOT_RUN")
args = parser.parse_args()
check(10 <= args.concurrency <= 32, "concurrency must be 10..32")
out = ROOT / args.output
out.mkdir(parents=True, exist_ok=True)
save_json(out / "result.json", {"status": "RUNNING"})
os.environ["BASE_URL"] = args.base_url
def stage(name, action):
print("Running " + name, flush=True)
started = time.monotonic()
result = action()
save_json(out / (name + ".json"), result)
print("Completed " + name + " in %.2f seconds" % (time.monotonic() - started), flush=True)
return result
try:
save_json(out / "00_environment.json", {
"at_utc": datetime.now(timezone.utc).isoformat(), "platform": platform.platform(),
"python": platform.python_version(), "host_cpu_count": os.cpu_count(),
"cluster_checks": "NOT_RUN" if args.skip_cluster else "included",
"synthetic_data_only": True, "host_dependencies": "Python standard library + Docker Compose",
})
record_command(out, "00_docker", ["docker", "version"])
record_command(out, "00_compose_config", COMPOSE + ["config", "--quiet"])
if not args.skip_cluster:
print("Running preserved cluster checks", flush=True)
record_command(out, "01_cluster", [
sys.executable, "scripts/cluster_evidence.py", "--base-url", args.base_url,
"--output", str(out / "cluster"),
], timeout=900)
wait_balanced(timeout=60)
record_command(out, "01_public_smoke", [sys.executable, "tests/smoke.py", "--base-url", args.base_url])
c = Client(args.base_url, timeout=15)
alice, bob, eve, chat = c.bootstrap()
content = (ROOT / "tests/fixtures/sample.png").read_bytes()
contract, att, target = attachment_contract(c, alice, bob, eve, chat, content)
save_json(out / "02_attachment_contract.json", contract)
stage("03_uploader_failover", lambda: uploader_failover(c, bob, att, content, target))
stage("04_full_restart", lambda: persistence(c, bob, chat, att, content, out))
stage("05_s3_outage", lambda: s3_outage(c, alice, bob, chat, att, content))
stage("06_private_bucket", lambda: private_bucket(att, out))
result = stage("07_concurrent_uploads", lambda: concurrent_uploads(
args.base_url, alice, bob, chat, args.concurrency
))
check(result["failures"] == 0 and result["all_downloads_equal"], "concurrent uploads failed; see measured results")
record_command(out, "08_cleanup_dry_run", COMPOSE + ["exec", "-T", "api-a", "python", "-m", "app.cleanup", "--dry-run"])
if args.skip_student_tests:
save_json(out / "09_student_tests.json", {"status": "NOT_RUN", "reason": "explicit --skip-student-tests; consult full run"})
else:
record_command(out, "09_student_tests", COMPOSE + ["--profile", "test", "run", "--rm", "--build", "tests"], timeout=900)
save_json(out / "10_final_processes.json", inventory())
save_json(out / "result.json", {"status": "PASS", "at_utc": datetime.now(timezone.utc).isoformat(),
"cluster_checks": "NOT_RUN" if args.skip_cluster else "PASS",
"student_tests": "NOT_RUN" if args.skip_student_tests else "PASS"})
print("PASS: lab4 evidence saved to " + str(out), flush=True)
except BaseException as error:
save_json(out / "result.json", {"status": "FAIL", "at_utc": datetime.now(timezone.utc).isoformat(),
"error_type": type(error).__name__,
"note": "Inspect completed files; an incomplete run does not prove acceptance."})
raise
if __name__ == "__main__":
main()
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env python3
"""Сохранить только реально выполненные локальные проверки без запуска инфраструктуры."""
from datetime import datetime, timezone
import json
from pathlib import Path
import shutil
import subprocess
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
def main():
out = ROOT / "evidence/local"
out.mkdir(parents=True, exist_ok=True)
checks = [
("01_check", [sys.executable, "scripts/check_contract.py"]),
("02_openapi", [sys.executable, "scripts/validate_openapi.py"]),
("03_static_stack", [sys.executable, "scripts/check_stack.py"]),
("04_unit", [sys.executable, "-m", "pytest", "-q", "unit-tests", "-p", "no:cacheprovider"]),
("05_collection", [sys.executable, "-m", "pytest", "--collect-only", "-q", "-p", "no:cacheprovider"]),
("06_dependencies", [sys.executable, "-m", "pip", "check"]),
]
manifest = []
for name, command in checks:
started = time.monotonic()
run = subprocess.run(command, cwd=ROOT, text=True, capture_output=True)
(out / (name + ".txt")).write_text("$ " + " ".join(command) + "\n" + run.stdout + run.stderr + "\nexit_code=" + str(run.returncode) + "\n")
manifest.append({"name": name, "command": command, "exit_code": run.returncode,
"elapsed_seconds": round(time.monotonic() - started, 3)})
print(name, "PASS" if run.returncode == 0 else "FAIL", flush=True)
(out / "manifest.json").write_text(json.dumps({"at_utc": datetime.now(timezone.utc).isoformat(),
"python": sys.version.split()[0], "checks": manifest}, indent=2) + "\n")
(out / "runtime_status.json").write_text(json.dumps({
"docker_cli_available": shutil.which("docker") is not None,
"nginx_binary_available": shutil.which("nginx") is not None,
"compose_nginx_postgresql_redis_experiments": "NOT_RUN",
"reason": "This local checker does not run infrastructure; execute python scripts/lab4_evidence.py separately",
"required_command_on_docker_host": "python scripts/lab4_evidence.py",
}, indent=2) + "\n")
return int(any(check["exit_code"] != 0 for check in manifest))
if __name__ == "__main__":
sys.exit(main())
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Live HTTP negative checks and an actual client disconnect, without pytest."""
import argparse
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import socket
import sys
import time
from urllib.parse import urlsplit
import uuid
from evidence_utils import exec_json, save_json
from replicas import ROOT
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
INVENTORY = r'''
import asyncio,json,sys
from sqlalchemy import text
from app.config import Settings
from app.db import create_engine
from app.storage import MinioStorage
p=json.load(sys.stdin)
s=Settings.from_env()
async def count():
e=create_engine(s)
try:
async with e.connect() as c:
return (await c.execute(text('SELECT count(*) FROM attachments WHERE filename=:name'), {'name':p['filename']})).scalar_one()
finally:
await e.dispose()
storage=MinioStorage(s)
try:
print(json.dumps({'matching_metadata':asyncio.run(count()),'s3_objects':sum(1 for _ in storage.client.list_objects(storage.bucket,prefix='originals/',recursive=True))}))
finally:
storage.close()
'''
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--output', type=Path, default=ROOT / 'evidence/lab4/manual_http.json')
args = parser.parse_args()
c = Client(args.base_url, timeout=30)
alice, bob, eve, chat = c.bootstrap()
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=manual.png'
cases = [
('corrupt', data[:48], 'image/png', 415),
('mime_spoof', data, 'image/jpeg', 415),
('too_large', data + b'x' * (10 * 1024 * 1024), 'image/png', 413),
]
results = []
for label, raw, mime, status in cases:
reply = c.call('POST', path, status, actor=alice, raw=raw, headers={'Content-Type':mime})
results.append({'case':label, 'status':reply['status'], 'error_code':reply['json']['error']['code']})
attachment, content = c.attachment(alice, chat)
actual = c.call('GET','/api/v1/attachments/' + attachment['id'] + '/content',actor=bob)['bytes']
check(actual == content, 'manual download mismatch')
label = 'interrupted-' + uuid.uuid4().hex + '.png'
before = exec_json('api-a', INVENTORY, {'filename':label})
endpoint = urlsplit(args.base_url)
check(endpoint.scheme == 'http', 'disconnect probe requires isolated local HTTP stand')
host, port = endpoint.hostname, endpoint.port or 80
header = (
'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=' + label + ' HTTP/1.1\r\n'
'Host: ' + endpoint.netloc + '\r\n'
'Authorization: Bearer ' + alice['token'] + '\r\n'
'Content-Type: image/png\r\nContent-Length: ' + str(len(data)) + '\r\n'
'Connection: close\r\n\r\n'
).encode('ascii')
with socket.create_connection((host, port), timeout=5) as connection:
connection.sendall(header + data[:1024])
time.sleep(0.2)
# Close before declared Content-Length. The server must not publish an object.
time.sleep(1)
after = exec_json('api-a', INVENTORY, {'filename':label})
check(after['matching_metadata'] == 0, 'interrupted upload persisted metadata')
check(before['s3_objects'] == after['s3_objects'], 'interrupted upload left an S3 object')
result = {'status':'PASS','at_utc':datetime.now(timezone.utc).isoformat(), 'negative_cases':results,
'original_sha256':hashlib.sha256(actual).hexdigest(), 'download_equal':True,
'disconnect':{'actual_tcp_close':True,'metadata_rows_after':0,
's3_objects_before':before['s3_objects'],'s3_objects_after':after['s3_objects']}}
save_json(args.output,result)
print('PASS: live upload/download, negative files and interrupted TCP upload')
if __name__ == '__main__':
main()
+173
View File
@@ -0,0 +1,173 @@
#!/usr/bin/env python3
"""Управление двумя API без публичных backend-портов и без Docker socket в LB."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import time
ROOT = Path(__file__).resolve().parents[1]
SERVICES = ("api-a", "api-b")
COMPOSE = ["docker", "compose", "--env-file", ".env"]
PROBE = "import json,urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2); print(json.dumps({'status':r.status,'instance_id':r.headers['X-Instance-Id']}))"
def compose(*args, capture=False):
result = subprocess.run(
COMPOSE + list(args),
cwd=ROOT,
check=True,
text=True,
encoding="utf-8",
errors="replace",
stdout=subprocess.PIPE if capture else None,
stderr=subprocess.PIPE if capture else None,
)
return result.stdout.strip() if capture else ""
def probe(service):
"""Получить alias из реального контейнера; credentials не выводятся."""
return json.loads(
compose("exec", "-T", service, "python", "-c", PROBE, capture=True)
)
def wait_ready(service, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
return probe(service)
except (subprocess.CalledProcessError, ValueError):
time.sleep(0.5)
raise RuntimeError(service + " did not become ready")
def inventory():
"""ID контейнера, PID host, restart count, alias и состояние без env/secrets."""
rows = []
for service in SERVICES:
cid = compose("ps", "-a", "-q", service, capture=True)
if not cid:
rows.append({"service": service, "state": "absent"})
continue
raw = subprocess.run(
["docker", "inspect", "--format", "{{json .State}}", cid],
check=True,
text=True,
encoding="utf-8",
errors="replace",
capture_output=True,
)
state = json.loads(raw.stdout)
row = {
"service": service,
"container_id": cid,
"pid": state["Pid"],
"state": state["Status"],
"started_at": state["StartedAt"],
}
if state["Running"]:
row.update(probe(service))
rows.append(row)
return rows
def drain(service):
"""Исключить backend, дождаться обновления upstream и старых workers."""
compose("exec", "-T", "nginx", "touch", "/tmp/drain-" + service)
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
config = compose(
"exec", "-T", "nginx", "cat", "/tmp/backends.conf", capture=True
)
if service + ":8080" not in config:
time.sleep(5.2)
return
time.sleep(0.2)
raise RuntimeError("LB did not drain " + service)
def undrain(service):
compose("exec", "-T", "nginx", "rm", "-f", "/tmp/drain-" + service)
def replace(service):
"""Заменить одну реплику при заведомо готовой второй."""
other = next(s for s in SERVICES if s != service)
wait_ready(other)
before = probe(service)["instance_id"]
drain(service)
try:
compose("up", "-d", "--no-deps", "--force-recreate", service)
after = wait_ready(service)["instance_id"]
if before == after:
raise RuntimeError("process alias did not change")
finally:
undrain(service)
wait_balanced()
return {"service": service, "before": before, "after": after}
def wait_balanced(timeout=30):
"""Дождаться обеих текущих ready-реплик через LB, включая новую после replace."""
import urllib.request
deadline = time.monotonic() + timeout
expected = {
wait_ready(service, timeout=max(0, deadline - time.monotonic()))["instance_id"]
for service in SERVICES
}
if len(expected) != len(SERVICES):
raise RuntimeError("API processes must have distinct instance IDs")
observed = set()
base = os.environ.get("BASE_URL", "http://localhost:8080")
while time.monotonic() < deadline:
try:
req = urllib.request.Request(
base + "/health/ready", headers={"Connection": "close"}
)
with urllib.request.urlopen(req, timeout=2) as reply:
if reply.status == 200:
observed.add(reply.headers.get("X-Instance-Id"))
if expected <= observed:
return
except OSError:
pass
time.sleep(0.3)
raise RuntimeError("LB did not expose both current ready processes")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"action", choices=["status", "stop-target", "restore", "rolling"]
)
args = parser.parse_args()
if args.action == "status":
print(json.dumps(inventory(), indent=2))
elif args.action == "stop-target":
target = os.environ.get("TARGET_INSTANCE_ID", "")
if not target:
raise RuntimeError("TARGET_INSTANCE_ID is required")
matches = [s for s in SERVICES if probe(s)["instance_id"] == target]
if len(matches) != 1:
raise RuntimeError("target must identify exactly one live process")
service = matches[0]
compose("stop", "--timeout", "6", service)
print(json.dumps({"stopped_service": service, "instance_id": target}))
elif args.action == "restore":
for service in SERVICES:
compose("up", "-d", "--no-deps", service)
undrain(service)
wait_balanced()
print(json.dumps(inventory(), indent=2))
else:
for service in SERVICES:
print(json.dumps(replace(service)))
if __name__ == "__main__":
main()
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Пересоздать весь стенд с сохранением volumes; работает в Windows и Linux."""
from replicas import compose, wait_balanced
def main():
# Compose повторно запускает migrate и bootstrap согласно depends_on.
# Именованные тома PostgreSQL/MinIO остаются подключёнными к новым контейнерам.
compose("stop")
compose("up", "-d", "--force-recreate")
wait_balanced(timeout=60)
if __name__ == "__main__":
main()
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/restart.py "$@"
+64
View File
@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Выполнить команду и сохранить её вывод в файл вместе с датой, коммитом и кодом возврата.
python scripts/run_and_save.py evidence/01.txt -- python scripts/check_contract.py
"""
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
def git_commit(root: Path) -> str:
"""Короткий hash текущего коммита или пояснение, почему его нет."""
try:
out = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=str(root), capture_output=True,
text=True, timeout=5)
return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else "нет (git не используется)"
except Exception:
return "нет (git не найден)"
def main() -> int:
"""Выполнить команду после --, записать отчёт и вернуть её код возврата."""
argv = sys.argv[1:]
if len(argv) < 3 or argv[1] != "--":
print(__doc__)
return 2
target = Path(argv[0])
command = argv[2:]
root = Path(__file__).resolve().parents[1]
env = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1")
started = time.monotonic()
try:
done = subprocess.run(command, capture_output=True, env=env, cwd=str(root))
output = (done.stdout + done.stderr).decode("utf-8", errors="replace")
code = done.returncode
except FileNotFoundError:
output = "Команда не найдена: %s\n" % command[0]
code = 127
elapsed = time.monotonic() - started
text = "\n".join([
"# Дата (UTC): " + datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
"# Commit: " + git_commit(root),
"# Команда: " + " ".join(command),
"# ---------------------------------------- вывод ----------------------------------------",
output.rstrip(),
"# ---------------------------------------------------------------------------------------",
"# Код возврата: %d" % code,
"# Время выполнения: %.2f с" % elapsed,
"",
])
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
sys.stdout.buffer.write(text.encode("utf-8", errors="replace"))
print("\n[сохранено в %s]" % target)
return code
if __name__ == "__main__":
sys.exit(main())
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Один вход и несколько запросов через LB; секреты не выводятся."""
import argparse
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
from client import Client, check
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://localhost:8080")
args = parser.parse_args()
c = Client(args.base_url)
person = c.user("instances")
seen = []
for _ in range(20):
response = c.call("GET", "/api/v1/users/me", actor=person, schema="User")
check(response["json"] == person["user"], "same token returned another user")
seen.append(response["headers"]["X-Instance-Id"])
print(json.dumps({"login_count": 1, "user_id": person["id"], "request_instances": seen,
"distinct_instances": len(set(seen))}, indent=2))
check(len(set(seen)) >= 2, "less than two API processes observed")
if __name__ == "__main__":
main()
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec python3 scripts/replicas.py stop-target
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Остановить API по TARGET_INSTANCE_ID без зависимости от shell хоста."""
from pathlib import Path
import subprocess
import sys
if __name__ == "__main__":
raise SystemExit(subprocess.call([
sys.executable, str(Path(__file__).with_name("replicas.py")), "stop-target"
]))