forked from mtusi2026/mtusi2026lab7
База lab7: контракт 1.7.0 и реализация lab1–lab6
Перенесены cmd/internal/config, compose.yaml, Dockerfile, скрипты, student-tests и evidence из mtusi-messenger (master, lab6). Skeleton lab7 (openapi/infrastructure 1.7.0, trust-matrix.md, security/THREAT_MODEL.md, infra/openbao, tests/security.py) сохранён; make test-security добавлен в Makefile.
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
mkdir -p evidence/cache
|
||||
|
||||
{
|
||||
echo "# API cache performance experiment"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy \
|
||||
NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 \
|
||||
python3 student-tests/cache_api_performance.py
|
||||
} > evidence/cache/api-performance.txt 2>&1
|
||||
cat evidence/cache/api-performance.txt
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
OUT="$ROOT/evidence/cache"
|
||||
GO="${GO:-go}"
|
||||
|
||||
cd "$ROOT"
|
||||
mkdir -p "$OUT"
|
||||
|
||||
{
|
||||
echo "# Cache consistency evidence (track 1)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# redis: ${TEST_REDIS_HOST:-localhost}:${TEST_REDIS_PORT:-6379} db=${TEST_REDIS_DB:-1}"
|
||||
echo
|
||||
"$GO" test -tags=integration -count=1 -v -timeout=5m \
|
||||
-run 'TestChatRepositorySuite|TestSessionRepositorySuite' \
|
||||
./internal/storage/redis/...
|
||||
} | tee "$OUT/consistency.txt"
|
||||
|
||||
echo "wrote $OUT/consistency.txt"
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
mkdir -p evidence/cache
|
||||
|
||||
{
|
||||
echo "# Cache latency experiment"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
go version
|
||||
uname -sm
|
||||
go test -tags=integration -count=3 -timeout=5m -v \
|
||||
-run '^TestCacheLatencyExperiment$' ./internal/storage/postgres/...
|
||||
} > evidence/cache/latency.txt 2>&1
|
||||
cat evidence/cache/latency.txt
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
mkdir -p evidence/cache
|
||||
|
||||
{
|
||||
echo "# Cache performance experiment"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
go version
|
||||
uname -sm
|
||||
go test -tags=integration -count=3 -timeout=5m -v \
|
||||
-run '^TestCachePerformanceExperiment$' ./internal/storage/postgres/...
|
||||
} > evidence/cache/performance.txt 2>&1
|
||||
cat evidence/cache/performance.txt
|
||||
Executable
+46
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scan committed evidence for credentials, signed URLs and raw identifiers."""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PATTERNS = {
|
||||
'aws signature': re.compile(r'X-Amz-(?:Signature|Credential|Security-Token)='),
|
||||
'inline password': re.compile(r'(?i)(password|passwd|secret|token)\s*[=:]\s*["\']?[^\s"\']{6,}'),
|
||||
'url credentials': re.compile(r'://[^/\s:@]+:[^@\s]+@'),
|
||||
'private key': re.compile(r'BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY'),
|
||||
'bearer token': re.compile(r'Bearer\s+[A-Za-z0-9._-]{20,}'),
|
||||
}
|
||||
ALLOW = {
|
||||
'PASSWORD=messenger',
|
||||
'PASSWORD=messenger',
|
||||
'password: messenger',
|
||||
'POSTGRES_PASSWORD: messenger',
|
||||
}
|
||||
|
||||
def main():
|
||||
failures = []
|
||||
for path in (ROOT / 'evidence').rglob('*'):
|
||||
if not path.is_file() or path.suffix in {'.png', '.jpg', '.jpeg', '.webp'}:
|
||||
continue
|
||||
try:
|
||||
text = path.read_text(errors='replace')
|
||||
except OSError:
|
||||
continue
|
||||
for name, pattern in PATTERNS.items():
|
||||
for match in pattern.finditer(text):
|
||||
line = text[text.rfind('\n', 0, match.start()) + 1:text.find('\n', match.end())].strip()
|
||||
if any(allowed in line for allowed in ALLOW):
|
||||
continue
|
||||
failures.append(f'{path.relative_to(ROOT)}: {name}: {line[:160]}')
|
||||
if failures:
|
||||
print('FAIL: evidence scanner found possible secrets/signatures')
|
||||
for item in failures:
|
||||
print(' ', item)
|
||||
return 1
|
||||
print('PASS: evidence has no obvious secrets, signed URLs or bearer tokens')
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail when the SeaweedFS identities and the API environment disagree.
|
||||
|
||||
The stand keeps synthetic credentials in two places on purpose: the identities
|
||||
file is mounted into SeaweedFS, while the API receives the same values through
|
||||
the environment. This check keeps the copies from drifting.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
IDENTITIES = ROOT / "infra/s3/s3.json"
|
||||
|
||||
|
||||
def parse_env(path: Path) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
for raw in path.read_text().splitlines():
|
||||
line = raw.strip()
|
||||
if not line or line.startswith("#") or "=" not in line:
|
||||
continue
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip().strip('"').strip("'")
|
||||
return values
|
||||
|
||||
|
||||
def main() -> int:
|
||||
identities = json.loads(IDENTITIES.read_text())
|
||||
by_name = {item["name"]: item for item in identities.get("identities", [])}
|
||||
|
||||
source = ROOT / ".env"
|
||||
if not source.is_file():
|
||||
source = ROOT / ".env.example"
|
||||
env = parse_env(source)
|
||||
|
||||
expected = {
|
||||
"app": ("S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY"),
|
||||
}
|
||||
|
||||
failures: list[str] = []
|
||||
for name, (key_var, secret_var) in expected.items():
|
||||
identity = by_name.get(name)
|
||||
if identity is None:
|
||||
failures.append(f"{IDENTITIES}: identity {name!r} is missing")
|
||||
continue
|
||||
credentials = identity.get("credentials") or []
|
||||
if not credentials:
|
||||
failures.append(f"{IDENTITIES}: identity {name!r} has no credentials")
|
||||
continue
|
||||
access_key = credentials[0].get("accessKey")
|
||||
secret_key = credentials[0].get("secretKey")
|
||||
if env.get(key_var) != access_key:
|
||||
failures.append(f"{source.name}: {key_var} does not match identity {name!r}")
|
||||
if env.get(secret_var) != secret_key:
|
||||
failures.append(f"{source.name}: {secret_var} does not match identity {name!r}")
|
||||
|
||||
if failures:
|
||||
print("FAIL: S3 credentials are inconsistent")
|
||||
for failure in failures:
|
||||
print(" -", failure)
|
||||
return 1
|
||||
|
||||
if "admin" not in by_name:
|
||||
print("FAIL: infra/s3/s3.json has no admin identity for s3-init")
|
||||
return 1
|
||||
|
||||
print(f"PASS: S3 app identity matches {source.name}; admin stays in s3.json/s3-init")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
mkdir -p "$ROOT_DIR/secrets"
|
||||
if [ ! -s "$ROOT_DIR/secrets/grafana.env" ]; then
|
||||
(umask 077; printf 'GF_SECURITY_ADMIN_PASSWORD=%s\n' "$(openssl rand -hex 16)" > "$ROOT_DIR/secrets/grafana.env")
|
||||
echo "created secrets/grafana.env"
|
||||
fi
|
||||
Executable
+147
@@ -0,0 +1,147 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure API memory under concurrent 9 MiB uploads (lab4 level 4).
|
||||
|
||||
Run against a live stand. Writes raw CSV samples and a summary under
|
||||
evidence/lab4/memory/. The primary metric is cgroup anon memory: memory.current
|
||||
also includes page cache from the temporary spool files.
|
||||
|
||||
python3 scripts/lab4_memory_experiment.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client # noqa: E402
|
||||
|
||||
OUTPUT = ROOT / 'evidence/lab4/memory'
|
||||
|
||||
|
||||
def png_of_size(width: int, height: int, seed: int) -> bytes:
|
||||
"""Build a valid, poorly compressible PNG (random RGB scanlines)."""
|
||||
rng = __import__('random').Random(seed)
|
||||
raw = bytearray()
|
||||
for _ in range(height):
|
||||
raw.append(0) # filter: None
|
||||
raw.extend(rng.randbytes(width * 3))
|
||||
|
||||
def chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0)
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', zlib.compress(bytes(raw), 6)) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
output = os.popen(f'docker compose ps -q {service}').read().split()
|
||||
if not output:
|
||||
raise SystemExit(f'no running containers for service {service}')
|
||||
return output
|
||||
|
||||
|
||||
def read_number(container: str, path: str) -> int:
|
||||
output = os.popen(f'docker exec {container} cat {path} 2>/dev/null').read().strip()
|
||||
return int(output) if output.isdigit() else 0
|
||||
|
||||
|
||||
def memory_snapshot() -> dict[str, int]:
|
||||
api = containers('api')
|
||||
anon = current = 0
|
||||
for container in api:
|
||||
stats = os.popen(f'docker exec {container} cat /sys/fs/cgroup/memory.stat 2>/dev/null').read()
|
||||
for line in stats.splitlines():
|
||||
if line.startswith('anon '):
|
||||
anon += int(line.split()[1])
|
||||
current += read_number(container, '/sys/fs/cgroup/memory.current')
|
||||
return {'anon': anon, 'current': current}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--width', type=int, default=2100)
|
||||
parser.add_argument('--height', type=int, default=1500)
|
||||
parser.add_argument('--rounds', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
|
||||
content = png_of_size(args.width, args.height, 42)
|
||||
if len(content) > 10 * 1024 * 1024:
|
||||
raise SystemExit(f'generated PNG is {len(content)} bytes, above the 10 MiB contract limit')
|
||||
|
||||
client = Client(args.base_url, timeout=120)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
samples: list[dict[str, int | float | str]] = []
|
||||
stop = threading.Event()
|
||||
|
||||
def sample(phase: str = 'during') -> None:
|
||||
started = time.monotonic()
|
||||
while not stop.is_set():
|
||||
snapshot = memory_snapshot()
|
||||
samples.append({'elapsed': round(time.monotonic() - started, 3), 'phase': phase, **snapshot})
|
||||
time.sleep(0.2)
|
||||
|
||||
baseline = memory_snapshot()
|
||||
sampler = threading.Thread(target=sample, daemon=True)
|
||||
sampler.start()
|
||||
|
||||
def upload(_: int) -> None:
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=memory.png'
|
||||
client.call(
|
||||
'POST', path, 201, actor=alice, raw=content,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment',
|
||||
)
|
||||
|
||||
started = time.monotonic()
|
||||
for _ in range(args.rounds):
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
list(pool.map(upload, range(args.concurrency)))
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
stop.set()
|
||||
sampler.join(timeout=2)
|
||||
after = memory_snapshot()
|
||||
|
||||
peak_anon = max((int(item['anon']) for item in samples), default=after['anon'])
|
||||
peak_current = max((int(item['current']) for item in samples), default=after['current'])
|
||||
|
||||
csv_path = OUTPUT / 'samples.csv'
|
||||
with csv_path.open('w', newline='') as handle:
|
||||
writer = csv.DictWriter(handle, fieldnames=['elapsed', 'phase', 'anon', 'current'])
|
||||
writer.writeheader()
|
||||
writer.writerows(samples)
|
||||
|
||||
summary = OUTPUT / 'summary.txt'
|
||||
summary.write_text(
|
||||
'Lab4 memory experiment\n'
|
||||
f'concurrency: {args.concurrency}\n'
|
||||
f'file_size_bytes: {len(content)}\n'
|
||||
f'uploads: {args.concurrency * args.rounds}\n'
|
||||
f'rounds: {args.rounds}\n'
|
||||
f'elapsed_seconds: {elapsed:.3f}\n'
|
||||
f'baseline_anon_bytes: {baseline["anon"]}\n'
|
||||
f'peak_anon_bytes: {peak_anon}\n'
|
||||
f'anon_delta_bytes: {peak_anon - baseline["anon"]}\n'
|
||||
f'peak_memory_current_bytes: {peak_current}\n'
|
||||
'note: memory.current includes page cache from temporary spool files; anon is the primary metric\n'
|
||||
)
|
||||
|
||||
print(summary.read_text())
|
||||
print('CSV:', csv_path)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+179
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare proxy upload with presigned direct upload (lab4 track 1).
|
||||
|
||||
Measures client-facing LB traffic, API traffic, API anon memory and latency for
|
||||
two file sizes. Run against a live stand from the repository root.
|
||||
|
||||
python3 scripts/lab4_track1.py --base-url http://localhost:8080
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import os
|
||||
import statistics
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
|
||||
from client import Client # noqa: E402
|
||||
from presign_flow import complete, presign, put # noqa: E402
|
||||
from lab4_memory_experiment import png_of_size # noqa: E402
|
||||
|
||||
OUTPUT = ROOT / 'evidence/lab4/track1'
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
ids = os.popen(f'docker compose ps -q {service}').read().split()
|
||||
if not ids:
|
||||
raise SystemExit(f'no running containers for service {service}')
|
||||
return ids
|
||||
|
||||
|
||||
def read_net(service: str) -> tuple[int, int]:
|
||||
rx = tx = 0
|
||||
for container in containers(service):
|
||||
for direction, path in (('rx', 'rx_bytes'), ('tx', 'tx_bytes')):
|
||||
value = os.popen(
|
||||
f'docker exec {container} cat /sys/class/net/eth0/statistics/{path} 2>/dev/null'
|
||||
).read().strip()
|
||||
if value.isdigit():
|
||||
if direction == 'rx':
|
||||
rx += int(value)
|
||||
else:
|
||||
tx += int(value)
|
||||
return rx, tx
|
||||
|
||||
|
||||
def read_anon() -> int:
|
||||
total = 0
|
||||
for container in containers('api'):
|
||||
stats = os.popen(f'docker exec {container} cat /sys/fs/cgroup/memory.stat 2>/dev/null').read()
|
||||
for line in stats.splitlines():
|
||||
if line.startswith('anon '):
|
||||
total += int(line.split()[1])
|
||||
return total
|
||||
|
||||
|
||||
class Sampler:
|
||||
def __init__(self) -> None:
|
||||
self.stop = threading.Event()
|
||||
self.peak = 0
|
||||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||||
|
||||
def run(self) -> None:
|
||||
while not self.stop.is_set():
|
||||
self.peak = max(self.peak, read_anon())
|
||||
time.sleep(0.1)
|
||||
|
||||
def __enter__(self) -> 'Sampler':
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_args: object) -> None:
|
||||
self.stop.set()
|
||||
self.thread.join(timeout=2)
|
||||
|
||||
|
||||
def proxy_upload(client: Client, actor: dict, chat: dict, content: bytes) -> None:
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=track1.png'
|
||||
client.call(
|
||||
'POST', path, 201, actor=actor, raw=content,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment',
|
||||
)
|
||||
|
||||
|
||||
def presign_upload(client: Client, actor: dict, chat: dict, content: bytes) -> None:
|
||||
prepared = presign(client, actor, chat, content)
|
||||
status = put(prepared['upload_url'], content)
|
||||
if status != 200:
|
||||
raise SystemExit(f'presigned PUT failed with {status}')
|
||||
complete(client, actor, prepared['attachment_id'], prepared['sha256'])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--iterations', type=int, default=5)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, timeout=180)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
|
||||
files = {
|
||||
'~1MiB': png_of_size(700, 500, 11),
|
||||
'~9MiB': png_of_size(2100, 1500, 12),
|
||||
}
|
||||
|
||||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||||
rows: list[dict[str, object]] = []
|
||||
|
||||
for label, content in files.items():
|
||||
for flow, operation in (('proxy', proxy_upload), ('presign', presign_upload)):
|
||||
for iteration in range(args.iterations):
|
||||
lb_before, lb_tx_before = read_net('lb')
|
||||
api_before, api_tx_before = read_net('api')
|
||||
started = time.monotonic()
|
||||
|
||||
with Sampler() as sampler:
|
||||
operation(client, alice, chat, content)
|
||||
|
||||
latency = time.monotonic() - started
|
||||
lb_after, lb_tx_after = read_net('lb')
|
||||
api_after, api_tx_after = read_net('api')
|
||||
|
||||
rows.append({
|
||||
'size': label,
|
||||
'bytes': len(content),
|
||||
'flow': flow,
|
||||
'iteration': iteration,
|
||||
'latency_s': round(latency, 4),
|
||||
'lb_rx_bytes': lb_after - lb_before,
|
||||
'lb_tx_bytes': lb_tx_after - lb_tx_before,
|
||||
'api_rx_bytes': api_after - api_before,
|
||||
'api_tx_bytes': api_tx_after - api_tx_before,
|
||||
'api_anon_peak': sampler.peak,
|
||||
})
|
||||
|
||||
csv_path = OUTPUT / 'results.csv'
|
||||
with csv_path.open('w', newline='') as handle:
|
||||
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
lines = ['Lab4 track 1: proxy vs presigned upload', '']
|
||||
lines.append('| size | flow | median latency, s | p95 latency, s | LB rx, bytes | API rx, bytes | API anon peak, bytes |')
|
||||
lines.append('|---|---|---:|---:|---:|---:|---:|')
|
||||
for label in files:
|
||||
for flow in ('proxy', 'presign'):
|
||||
group = [row for row in rows if row['size'] == label and row['flow'] == flow]
|
||||
latencies = sorted(float(row['latency_s']) for row in group)
|
||||
median = statistics.median(latencies)
|
||||
p95 = latencies[min(len(latencies) - 1, int(round(0.95 * (len(latencies) - 1))))]
|
||||
lb_rx = sum(int(row['lb_rx_bytes']) for row in group) / len(group)
|
||||
api_rx = sum(int(row['api_rx_bytes']) for row in group) / len(group)
|
||||
peak = max(int(row['api_anon_peak']) for row in group)
|
||||
lines.append(
|
||||
f'| {label} | {flow} | {median:.3f} | {p95:.3f} | {lb_rx:.0f} | {api_rx:.0f} | {peak} |'
|
||||
)
|
||||
|
||||
lines += [
|
||||
'',
|
||||
'Note: presigned upload keeps the file body off the API request path and off the load balancer.',
|
||||
'Completion still streams the object from S3 once to verify its SHA-256, so api_rx stays close to',
|
||||
'the file size; the saving is in the client-facing LB leg and in not accepting/buffering the body.',
|
||||
'',
|
||||
]
|
||||
summary = OUTPUT / 'summary.txt'
|
||||
summary.write_text('\n'.join(lines))
|
||||
print(summary.read_text())
|
||||
print('CSV:', csv_path)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+165
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 2 evidence: versioned pipeline, duplicate delivery, stale-version guard.
|
||||
|
||||
Runs N repetitions against the live stand and writes raw CSV/Markdown evidence.
|
||||
This is a correctness harness, not a load test.
|
||||
|
||||
python3 scripts/lab5_track2.py --reps 5
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
from tests_helpers import compose, jobctl, psql # noqa: E402
|
||||
|
||||
FIXTURE = ROOT / 'tests/fixtures/sample.png'
|
||||
EVIDENCE = ROOT / 'evidence/lab5/track2'
|
||||
|
||||
|
||||
def wait_ready(client, actor, attachment, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
current = client.call('GET', '/api/v1/attachments/' + attachment['id'], actor=actor, schema='Attachment')['json']
|
||||
check(current['status'] != 'failed', 'attachment failed: ' + str(current.get('error_code')))
|
||||
if current['status'] == 'ready':
|
||||
return current
|
||||
time.sleep(0.2)
|
||||
raise Failure('attachment did not become ready')
|
||||
|
||||
|
||||
def wait_version(attachment_id, version, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
row = psql("select pipeline_version || '|' || status from attachments where id='%s'" % attachment_id)
|
||||
if row == str(version) + '|ready':
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise Failure('attachment did not reach pipeline version %d' % version)
|
||||
|
||||
|
||||
def variants_by_name(attachment):
|
||||
return {v['name']: v for v in attachment['variants']}
|
||||
|
||||
|
||||
def scenario_duplicate_before_effect(client, actor, chat):
|
||||
compose('stop', 'worker')
|
||||
try:
|
||||
attached, _ = client.attachment(actor, chat)
|
||||
time.sleep(1)
|
||||
job = psql("select job_id from attachment_jobs where attachment_id='%s'" % attached['id'])
|
||||
check(bool(job), 'job id missing')
|
||||
jobctl('duplicate', '-job', job)
|
||||
jobctl('duplicate', '-job', job)
|
||||
finally:
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
|
||||
ready = wait_ready(client, actor, attached)
|
||||
names = sorted(variants_by_name(ready))
|
||||
check(names == ['crop', 'optimized', 'thumbnail'], 'duplicate delivery changed the variant set')
|
||||
check(psql("select count(*) from attachment_variants where attachment_id='%s'" % attached['id']) == '3',
|
||||
'duplicate delivery created extra variant rows')
|
||||
|
||||
return 'duplicate_before_effect', True, 'attempts=' + psql(
|
||||
"select attempt from attachment_jobs where attachment_id='%s'" % attached['id'])
|
||||
|
||||
|
||||
def scenario_stale_version(client, actor, chat):
|
||||
attached, content = client.attachment(actor, chat)
|
||||
v1 = wait_ready(client, actor, attached)
|
||||
v1_variants = variants_by_name(v1)
|
||||
original_sha = hashlib.sha256(content).hexdigest()
|
||||
check(v1['sha256'] == original_sha, 'original checksum changed before reprocess')
|
||||
|
||||
v1_job = psql("select job_id from attachment_jobs where attachment_id='%s' and pipeline_version=1" % attached['id'])
|
||||
check(bool(v1_job), 'v1 job missing')
|
||||
|
||||
reprocess = jobctl('reprocess', '-attachment', attached['id'], '-pipeline', '2')
|
||||
check(reprocess.returncode == 0, 'reprocess failed: ' + reprocess.stderr)
|
||||
wait_version(attached['id'], 2)
|
||||
v2 = wait_ready(client, actor, attached)
|
||||
v2_variants = variants_by_name(v2)
|
||||
check(sorted(v2_variants) == ['crop', 'optimized', 'thumbnail'], 'v2 variant set incomplete')
|
||||
check(v2_variants['thumbnail']['sha256'] != v1_variants['thumbnail']['sha256'],
|
||||
'v2 bytes must differ from v1 (pipeline parameters changed)')
|
||||
check(v2['sha256'] == original_sha, 'original changed during reprocess')
|
||||
before = json.dumps(v2_variants, sort_keys=True)
|
||||
|
||||
# Deliver the old v1 message after v2 is published. It must be acknowledged
|
||||
# without touching the serving version or its artifacts.
|
||||
jobctl('duplicate', '-job', v1_job)
|
||||
time.sleep(2)
|
||||
|
||||
after_attachment = client.call('GET', '/api/v1/attachments/' + attached['id'], actor=actor, schema='Attachment')['json']
|
||||
after_variants = variants_by_name(after_attachment)
|
||||
check(json.dumps(after_variants, sort_keys=True) == before, 'stale v1 delivery overwrote v2 variants')
|
||||
check(psql("select pipeline_version from attachments where id='%s'" % attached['id']) == '2',
|
||||
'serving pipeline version regressed')
|
||||
check(psql("select status from attachment_jobs where job_id='%s'" % v1_job) == 'ready',
|
||||
'v1 job state changed unexpectedly')
|
||||
|
||||
return 'stale_version_after_v2', True, 'v1_job=' + v1_job
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Lab5 track 2 correctness harness')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--reps', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
|
||||
EVIDENCE.mkdir(parents=True, exist_ok=True)
|
||||
rows = []
|
||||
|
||||
client = Client(args.base_url, None)
|
||||
|
||||
for rep in range(1, args.reps + 1):
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
for scenario in (scenario_duplicate_before_effect, scenario_stale_version):
|
||||
name, passed, detail = scenario(client, alice, chat)
|
||||
rows.append({'scenario': name, 'rep': rep, 'pass': int(passed), 'detail': detail})
|
||||
print('D%s rep=%d: %s' % (name, rep, 'PASS' if passed else 'FAIL'))
|
||||
|
||||
with (EVIDENCE / 'runs.csv').open('w', newline='') as handle:
|
||||
writer = csv.DictWriter(handle, fieldnames=['scenario', 'rep', 'pass', 'detail'])
|
||||
writer.writeheader()
|
||||
writer.writerows(rows)
|
||||
|
||||
summary = [
|
||||
'# Track 2 — versioned pipeline and duplicate/stale delivery',
|
||||
'',
|
||||
'Hypothesis: with the effect key `(attachment_id, pipeline_version, variant)`,',
|
||||
'deterministic object keys, a serving version that changes only when all v2',
|
||||
'variants are committed, and stale-version acknowledgements, an at-least-once',
|
||||
'pipeline loses no accepted work and never overwrites a newer result with an',
|
||||
'older duplicate.',
|
||||
'',
|
||||
'Method: N=%d repetitions. Each repetition creates fresh users/chat and runs:' % args.reps,
|
||||
'- duplicate pipeline publication while the worker is stopped, followed by recovery;',
|
||||
'- v1 ready -> explicit reprocess to v2 -> old v1 message delivered after v2 ready.',
|
||||
'',
|
||||
'Invariants checked: unique variant rows per effect key; ready remains ready;',
|
||||
'serving pipeline version never regresses; original bytes/checksum unchanged;',
|
||||
'stale job state is not rewritten.',
|
||||
'',
|
||||
'Limitations: this harness covers duplicate and stale/reorder delivery. Crash',
|
||||
'windows (before/after side effect, before/after ack, outbox gap) and lease',
|
||||
'takeover are covered by student-tests/lab5_faults.py; both are single-node',
|
||||
'Compose evidence, not a production availability claim. Delivery is',
|
||||
'at-least-once; exactly-once is not claimed.',
|
||||
]
|
||||
(EVIDENCE / 'summary.md').write_text('\n'.join(summary) + '\n')
|
||||
|
||||
passed = sum(row['pass'] for row in rows)
|
||||
print('PASS: track2 %d/%d scenarios' % (passed, len(rows)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Summarize firing episodes and unfired pending alerts by Track 2 phase."""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
PAGE = {"APIErrorBudgetFastBurn", "TTRErrorBudgetFastBurn", "QueueOldestJobAgeCritical", "APISLIMissing"}
|
||||
TICKET = {"APIErrorBudgetSlowBurn", "TTRErrorBudgetSlowBurn"}
|
||||
|
||||
|
||||
def ts(value):
|
||||
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--alerts", default="evidence/lab6/track2/full/alerts.csv")
|
||||
parser.add_argument("--phases", default="evidence/lab6/track2/full/phases.json")
|
||||
parser.add_argument("--out", default="evidence/lab6/checks/alert-audit.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
phases = json.loads(Path(args.phases).read_text())
|
||||
rows = sorted(csv.DictReader(open(args.alerts)), key=lambda r: r["observed_utc"])
|
||||
by_alert = defaultdict(list)
|
||||
for row in rows:
|
||||
label = row.get("labels", "")
|
||||
key = row["alert"] if not label else row["alert"] + "|" + label
|
||||
by_alert[key].append(row)
|
||||
|
||||
result = []
|
||||
for phase in phases:
|
||||
start, end = ts(phase["started_utc"]), ts(phase["finished_utc"])
|
||||
firing = defaultdict(int)
|
||||
pending_not_fired = defaultdict(int)
|
||||
for key, events in by_alert.items():
|
||||
name = key.split("|", 1)[0]
|
||||
prev_state = None
|
||||
for row in events:
|
||||
if ts(row["observed_utc"]) < start:
|
||||
prev_state = row["state"]
|
||||
pending_in_phase = []
|
||||
for row in events:
|
||||
at = ts(row["observed_utc"])
|
||||
state = row["state"]
|
||||
if start <= at <= end:
|
||||
if state == "firing" and prev_state != "firing":
|
||||
firing[key] += 1
|
||||
if state == "pending":
|
||||
pending_in_phase.append(row)
|
||||
if state == "firing" and pending_in_phase:
|
||||
pending_in_phase.clear()
|
||||
if state == "resolved":
|
||||
pending_in_phase.clear()
|
||||
prev_state = state
|
||||
pending_not_fired[key] += len(pending_in_phase)
|
||||
entry = {
|
||||
"phase": phase["phase"],
|
||||
"started_utc": phase["started_utc"],
|
||||
"finished_utc": phase["finished_utc"],
|
||||
"firing": dict(sorted(firing.items())),
|
||||
"pending_not_fired": {k: v for k, v in sorted(pending_not_fired.items()) if v},
|
||||
}
|
||||
entry["page"] = sum(v for k, v in firing.items() if k.split("|", 1)[0] in PAGE)
|
||||
entry["ticket"] = sum(v for k, v in firing.items() if k.split("|", 1)[0] in TICKET)
|
||||
result.append(entry)
|
||||
|
||||
out = Path(args.out)
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(result, indent=2) + "\n")
|
||||
text = "# Alert episodes by phase\n\n| phase | page | ticket | firing | pending-not-fired |\n|---|---:|---:|---|---|\n"
|
||||
for x in result:
|
||||
text += f"| {x['phase']} | {x['page']} | {x['ticket']} | {x['firing']} | {x['pending_not_fired']} |\n"
|
||||
out.with_suffix(".md").write_text(text)
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Poll Prometheus alert state and write a firing/resolved timeline."""
|
||||
import argparse
|
||||
import os
|
||||
import csv
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
|
||||
def get(url):
|
||||
with urllib.request.urlopen(url, timeout=5) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Poll Prometheus alerts')
|
||||
parser.add_argument('--prometheus', default='http://localhost:9090')
|
||||
parser.add_argument('--duration', type=float, default=600)
|
||||
parser.add_argument('--interval', type=float, default=5)
|
||||
parser.add_argument('--output', default='evidence/lab6/alerts.csv')
|
||||
parser.add_argument('--injection-utc', default='')
|
||||
args = parser.parse_args()
|
||||
path = Path(args.output)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
started = time.time()
|
||||
active = set()
|
||||
had_error = False
|
||||
with path.open('w', newline='') as handle:
|
||||
writer = csv.writer(handle)
|
||||
writer.writerow(['observed_utc', 'alert', 'state', 'active_at', 'value', 'injection_utc'])
|
||||
while time.time() - started < args.duration:
|
||||
try:
|
||||
payload = get(args.prometheus.rstrip('/') + '/api/v1/alerts')
|
||||
current = set()
|
||||
for alert in payload.get('data', {}).get('alerts', []):
|
||||
name = alert.get('labels', {}).get('alertname', '')
|
||||
state = alert.get('state', '')
|
||||
current.add((name, state))
|
||||
if (name, state) not in active:
|
||||
writer.writerow([
|
||||
time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
name, state, alert.get('activeAt', ''),
|
||||
json.dumps(alert.get('value', ''), separators=(',', ':')), args.injection_utc,
|
||||
])
|
||||
for name, state in sorted(active - current):
|
||||
writer.writerow([
|
||||
time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
name, 'resolved', '', '', args.injection_utc,
|
||||
])
|
||||
active = current
|
||||
handle.flush()
|
||||
except Exception as exc:
|
||||
had_error = True
|
||||
print('WARN: alert poll failed:', exc)
|
||||
time.sleep(args.interval)
|
||||
print('alert timeline:', path)
|
||||
return 1 if had_error else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated collector outage under load with labeled probes and alert timeline."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
|
||||
def query(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def alerts():
|
||||
with OPENER.open('http://localhost:9090/api/v1/alerts', timeout=10) as response:
|
||||
data = json.loads(response.read()).get('data', {}).get('alerts', [])
|
||||
return [(a['labels'].get('alertname', ''), a['state']) for a in data]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def sample(label):
|
||||
print(label,
|
||||
'up=' + query('up{job="otel-collector"}'),
|
||||
'api_p99=' + query('histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))'),
|
||||
'api_error_5m=' + query('slo:api_error_ratio:5m'),
|
||||
'queue_logs=' + query('max(otelcol_exporter_queue_size{data_type="logs"})'),
|
||||
'queue_traces=' + query('max(otelcol_exporter_queue_size{data_type="traces"})'),
|
||||
'alerts=' + json.dumps(alerts()), flush=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--duration', type=int, default=300)
|
||||
args = parser.parse_args()
|
||||
print('UTC', time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), flush=True)
|
||||
print('HEAD', subprocess.run(['git','rev-parse','HEAD'], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip(), flush=True)
|
||||
print('pre_alerts=', json.dumps(alerts()), flush=True)
|
||||
load_path = ROOT/'evidence/lab6/checks/collector-down-load.json'
|
||||
load_path.unlink(missing_ok=True)
|
||||
load_duration = args.duration + 300 + 60
|
||||
load = subprocess.Popen([
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', 'http://localhost:8080',
|
||||
'--rate', '0.2', '--duration', str(load_duration), '--upload-ratio', '0.2',
|
||||
'--deadline', '60', '--output', str(load_path),
|
||||
], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
time.sleep(10)
|
||||
print('$ docker compose ps -a', flush=True)
|
||||
print(compose('ps','-a').stdout, flush=True)
|
||||
print('$ docker compose stop otel-collector', flush=True)
|
||||
print(compose('stop','otel-collector').stdout.strip(), flush=True)
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < args.duration:
|
||||
time.sleep(30)
|
||||
sample('down t=%ss' % int(time.monotonic() - started))
|
||||
print('$ docker compose ps -a (down)', flush=True)
|
||||
print(compose('ps','-a').stdout, flush=True)
|
||||
print('$ docker compose start otel-collector', flush=True)
|
||||
print(compose('start','otel-collector').stdout.strip(), flush=True)
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < 300:
|
||||
time.sleep(30)
|
||||
sample('recovery t=%ss' % int(time.monotonic() - started))
|
||||
current = alerts()
|
||||
if not any(name in ('TelemetryCollectorDown', 'CollectorDroppedTelemetry') for name, _ in current):
|
||||
print('telemetry alerts inactive', flush=True)
|
||||
break
|
||||
try:
|
||||
load.wait(timeout=load_duration + 120)
|
||||
except subprocess.TimeoutExpired:
|
||||
load.kill()
|
||||
load.wait()
|
||||
print('load_exit=', load.returncode, flush=True)
|
||||
if load_path.exists():
|
||||
data = json.loads(load_path.read_text())
|
||||
print('load_summary=', json.dumps({k: data.get(k) for k in ('counters','failures','failures_by_reason','duration_s')}), flush=True)
|
||||
print('$ docker compose ps -a (final)', flush=True)
|
||||
print(compose('ps','-a').stdout, flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+184
@@ -0,0 +1,184 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Open-loop lab6 load: fixed arrival rate, messages and attachment uploads.
|
||||
|
||||
Unlike tests/load.py this schedules arrivals instead of running a closed loop,
|
||||
so a degraded server cannot reduce the offered rate. It is intentionally small
|
||||
and standard-library only; use k6/wrk2 for capacity claims.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import os
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
rank = max(0, min(len(values) - 1, int(math.ceil(p / 100.0 * len(values))) - 1))
|
||||
return values[rank]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Open-loop lab6 load')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--rate', type=float, default=1.0, help='arrivals per second')
|
||||
parser.add_argument('--duration', type=float, default=60.0, help='seconds')
|
||||
parser.add_argument('--upload-ratio', type=float, default=0.25)
|
||||
parser.add_argument('--deadline', type=float, default=60.0)
|
||||
parser.add_argument('--workers', type=int, default=32)
|
||||
parser.add_argument('--output', default=None)
|
||||
parser.add_argument('--token-refresh-seconds', type=float, default=2400.0)
|
||||
args = parser.parse_args()
|
||||
|
||||
from client import Client, Failure
|
||||
bootstrap = Client(args.base_url, timeout=args.deadline)
|
||||
alice, _, _, chat = bootstrap.bootstrap()
|
||||
|
||||
lock = threading.Lock()
|
||||
token_lock = threading.Lock()
|
||||
last_refresh = [time.monotonic()]
|
||||
|
||||
def refresh_session():
|
||||
# Sessions live one hour; refresh well before expiry so a 70m warmup
|
||||
# does not turn into 401s halfway through.
|
||||
if time.monotonic() - last_refresh[0] < args.token_refresh_seconds:
|
||||
return
|
||||
with token_lock:
|
||||
if time.monotonic() - last_refresh[0] < args.token_refresh_seconds:
|
||||
return
|
||||
registration = alice['registration']
|
||||
credential = base64.b64encode(
|
||||
(registration['username'] + ':' + registration['password']).encode()).decode()
|
||||
refresher = Client(args.base_url, timeout=args.deadline)
|
||||
session = refresher.call(
|
||||
'POST', '/api/v1/auth/sessions', 201,
|
||||
headers={'Authorization': 'Basic ' + credential}, schema='Session')['json']
|
||||
alice['token'] = session['token']
|
||||
last_refresh[0] = time.monotonic()
|
||||
latencies, ttr, failures = [], [], []
|
||||
counters = {'accepted': 0, 'ready': 0, 'failed': 0, 'messages': 0, 'uploads': 0, 'dropped': 0}
|
||||
failures_by_reason = {}
|
||||
sem = threading.Semaphore(args.workers)
|
||||
|
||||
def failure_reason(detail):
|
||||
match = re.search(r'received (\d{3})', detail)
|
||||
if match:
|
||||
return 'http_' + match.group(1)
|
||||
return detail.split(':', 1)[0].strip() or 'unknown'
|
||||
|
||||
def record(kind, elapsed, ok, detail=''):
|
||||
with lock:
|
||||
if kind == 'message':
|
||||
counters['messages'] += 1
|
||||
if ok:
|
||||
latencies.append(elapsed)
|
||||
else:
|
||||
reason = failure_reason(detail)
|
||||
counters['failed'] += 1
|
||||
failures_by_reason[reason] = failures_by_reason.get(reason, 0) + 1
|
||||
failures.append(detail)
|
||||
else:
|
||||
if ok:
|
||||
counters['ready'] += 1
|
||||
ttr.append(elapsed)
|
||||
else:
|
||||
reason = failure_reason(detail)
|
||||
counters['failed'] += 1
|
||||
failures_by_reason[reason] = failures_by_reason.get(reason, 0) + 1
|
||||
failures.append(detail)
|
||||
|
||||
def run_one(kind, index):
|
||||
client = Client(args.base_url, timeout=args.deadline)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
refresh_session()
|
||||
if kind == 'message':
|
||||
client.message(alice, chat, 'lab6 load %d %s' % (index, uuid.uuid4().hex[:8]))
|
||||
record(kind, time.monotonic() - started, True)
|
||||
else:
|
||||
att, _ = client.attachment(alice, chat)
|
||||
with lock:
|
||||
counters['uploads'] += 1
|
||||
counters['accepted'] += 1
|
||||
try:
|
||||
client.wait_ready(alice, att, wait_seconds=args.deadline)
|
||||
record(kind, time.monotonic() - started, True)
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
reason = failure_reason(str(exc))
|
||||
counters['failed'] += 1
|
||||
failures_by_reason[reason] = failures_by_reason.get(reason, 0) + 1
|
||||
failures.append('ready: ' + type(exc).__name__ + ': ' + str(exc)[:120])
|
||||
except Exception as exc:
|
||||
record(kind, time.monotonic() - started, False, type(exc).__name__ + ': ' + str(exc)[:120])
|
||||
finally:
|
||||
sem.release()
|
||||
|
||||
total = max(0, int(args.rate * args.duration))
|
||||
started = time.monotonic()
|
||||
threads = []
|
||||
for index in range(total):
|
||||
target = started + index / max(args.rate, 0.001)
|
||||
delay = target - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
if not sem.acquire(blocking=False):
|
||||
with lock:
|
||||
counters['dropped'] += 1
|
||||
continue
|
||||
kind = 'upload' if ((index * 37) % 100) < int(args.upload_ratio * 100) else 'message'
|
||||
thread = threading.Thread(target=run_one, args=(kind, index), daemon=True)
|
||||
threads.append(thread)
|
||||
thread.start()
|
||||
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
summary = {
|
||||
'base_url': args.base_url,
|
||||
'rate': args.rate,
|
||||
'duration_s': round(time.monotonic() - started, 2),
|
||||
'scheduled': total,
|
||||
'counters': counters,
|
||||
'failures': len(failures),
|
||||
'failures_by_reason': dict(sorted(failures_by_reason.items())),
|
||||
'failure_samples': failures[:10],
|
||||
'latency_ms': {
|
||||
'p50': round(percentile(latencies, 50) * 1000, 1) if latencies else None,
|
||||
'p95': round(percentile(latencies, 95) * 1000, 1) if latencies else None,
|
||||
'p99': round(percentile(latencies, 99) * 1000, 1) if latencies else None,
|
||||
},
|
||||
'ttr_ms': {
|
||||
'p50': round(percentile(ttr, 50) * 1000, 1) if ttr else None,
|
||||
'p95': round(percentile(ttr, 95) * 1000, 1) if ttr else None,
|
||||
'p99': round(percentile(ttr, 99) * 1000, 1) if ttr else None,
|
||||
},
|
||||
}
|
||||
if args.output:
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(json.dumps(summary, indent=2) + '\n')
|
||||
print(json.dumps(summary, indent=2))
|
||||
return 0 if not failures else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated telemetry-storage outage under load, with baseline/recovery and cgroup data."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def labels(expr, label):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return [r['metric'].get(label, '') for r in result]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def cgroup_stats():
|
||||
output = subprocess.run(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}} {{.MemPerc}}',],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
return [line.strip() for line in output.splitlines() if any(s in line for s in ('api-','collector'))]
|
||||
|
||||
|
||||
def sample(phase):
|
||||
return {
|
||||
'phase': phase,
|
||||
'utc': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'api_memory': prom('max by (service_instance_id) (messenger_process_memory_usage_bytes{service_name="messenger-api"})'),
|
||||
'collector_rss': prom('max(otelcol_process_memory_rss)'),
|
||||
'collector_heap': prom('max(otelcol_process_runtime_heap_alloc_bytes)'),
|
||||
'queue_logs': prom('max(otelcol_exporter_queue_size{data_type="logs"})'),
|
||||
'queue_traces': prom('max(otelcol_exporter_queue_size{data_type="traces"})'),
|
||||
'sent_spans': prom('sum(rate(otelcol_exporter_sent_spans[5m]))'),
|
||||
'send_failed_spans': prom('sum(rate(otelcol_exporter_send_failed_spans[5m]))'),
|
||||
'enqueue_failed_spans': prom('sum(rate(otelcol_exporter_enqueue_failed_spans[5m]))'),
|
||||
'accepted_logs': prom('sum(rate(otelcol_receiver_accepted_log_records[5m]))'),
|
||||
'api_error_5m': prom('slo:api_error_ratio:5m'),
|
||||
'api_p99': prom('histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket[5m])))'),
|
||||
'api_instances': labels('messenger_process_memory_usage_bytes{service_name="messenger-api"}', 'service_instance_id'),
|
||||
'cgroup': cgroup_stats(),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--baseline', type=int, default=60)
|
||||
parser.add_argument('--duration', type=int, default=300)
|
||||
parser.add_argument('--recovery', type=int, default=300)
|
||||
parser.add_argument('--out', default='evidence/lab6/storage-down-series.json')
|
||||
args = parser.parse_args()
|
||||
load_path = ROOT/'evidence/lab6/checks/storage-down-load.json'
|
||||
load_path.unlink(missing_ok=True)
|
||||
load_duration = args.baseline + args.duration + args.recovery + 120
|
||||
load = subprocess.Popen([
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', 'http://localhost:8080',
|
||||
'--rate', '0.2', '--duration', str(load_duration),
|
||||
'--upload-ratio', '0.2', '--deadline', '60',
|
||||
'--output', str(load_path),
|
||||
], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
samples = []
|
||||
try:
|
||||
for _ in range(args.baseline // 10):
|
||||
time.sleep(10)
|
||||
samples.append(sample('baseline'))
|
||||
compose('stop','loki','tempo')
|
||||
samples.append(sample('down-start'))
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < args.duration:
|
||||
time.sleep(10)
|
||||
samples.append(sample('down'))
|
||||
compose('start','loki','tempo')
|
||||
samples.append(sample('recovery-start'))
|
||||
started = time.monotonic()
|
||||
zero_streak = 0
|
||||
while time.monotonic() - started < args.recovery:
|
||||
time.sleep(10)
|
||||
samples.append(sample('recovery'))
|
||||
logs_zero = prom('max(otelcol_exporter_queue_size{data_type="logs"})') in ('0','0.0')
|
||||
traces_zero = prom('max(otelcol_exporter_queue_size{data_type="traces"})') in ('0','0.0')
|
||||
if logs_zero and traces_zero:
|
||||
zero_streak += 1
|
||||
if zero_streak >= 2:
|
||||
break
|
||||
else:
|
||||
zero_streak = 0
|
||||
finally:
|
||||
compose('start','loki','tempo')
|
||||
try:
|
||||
load.wait(timeout=load_duration + 120)
|
||||
except subprocess.TimeoutExpired:
|
||||
load.kill()
|
||||
load.wait()
|
||||
print('load_exit=', load.returncode, flush=True)
|
||||
if load_path.exists():
|
||||
data = json.loads(load_path.read_text())
|
||||
print('load_summary=', json.dumps({k: data.get(k) for k in ('counters','failures','failures_by_reason','duration_s')}), flush=True)
|
||||
out = ROOT / args.out
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(samples, indent=2) + '\n')
|
||||
print(json.dumps(samples, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab6 track 2 scenario driver: burst, sustained outage and false-positive phases.
|
||||
|
||||
It starts the open-loop load, injects a PostgreSQL fault, records alert state and
|
||||
restores the stand. Use --quick for a short evidence run; the full 15-minute
|
||||
sustained phase is the graded scenario.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
command = ['docker', 'compose', '--env-file', '.env', '-f', 'compose.yaml', *args]
|
||||
return subprocess.run(command, cwd=ROOT, check=check)
|
||||
|
||||
|
||||
def stamp():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Lab6 track 2 scenarios')
|
||||
parser.add_argument('--scenario', choices=['burst', 'sustained', 'false-positive'], default='burst')
|
||||
parser.add_argument('--quick', action='store_true', help='short 20s phases')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--load-rate', type=float, default=0.5)
|
||||
parser.add_argument('--output-dir', default='evidence/lab6/track2')
|
||||
args = parser.parse_args()
|
||||
out = ROOT / args.output_dir
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
duration = 20 if args.quick else (120 if args.scenario == 'burst' else 900)
|
||||
if args.scenario == 'false-positive':
|
||||
duration = 20 if args.quick else 300
|
||||
|
||||
load = subprocess.Popen([
|
||||
sys.executable, str(ROOT / 'scripts/lab6_load.py'),
|
||||
'--base-url', args.base_url, '--rate', str(args.load_rate),
|
||||
'--duration', str(duration + 20), '--upload-ratio', '0.2',
|
||||
'--output', str(out / (args.scenario + '-load.json')),
|
||||
], cwd=ROOT)
|
||||
alerts = subprocess.Popen([
|
||||
sys.executable, str(ROOT / 'scripts/lab6_alerts.py'),
|
||||
'--duration', str(duration + 20), '--output', str(out / (args.scenario + '-alerts.csv')),
|
||||
], cwd=ROOT)
|
||||
|
||||
time.sleep(5)
|
||||
injection = stamp()
|
||||
try:
|
||||
if args.scenario == 'burst':
|
||||
compose('pause', 'postgres')
|
||||
elif args.scenario == 'sustained':
|
||||
compose('stop', 'worker')
|
||||
compose('stop', 'postgres')
|
||||
time.sleep(duration)
|
||||
finally:
|
||||
if args.scenario == 'burst':
|
||||
compose('unpause', 'postgres', check=False)
|
||||
elif args.scenario == 'sustained':
|
||||
compose('start', 'postgres', check=False)
|
||||
time.sleep(5)
|
||||
compose('up', '-d', '--no-deps', 'worker', check=False)
|
||||
restore = stamp()
|
||||
Path(out / (args.scenario + '-phases.json')).write_text(json.dumps({
|
||||
'scenario': args.scenario,
|
||||
'injection_utc': injection,
|
||||
'restore_utc': restore,
|
||||
'duration_seconds': duration,
|
||||
}, indent=2) + '\n')
|
||||
time.sleep(10)
|
||||
|
||||
load_rc = load.wait(timeout=duration + 60)
|
||||
alerts_rc = alerts.wait(timeout=duration + 60)
|
||||
print('track2 evidence:', out, 'load_rc=', load_rc, 'alerts_rc=', alerts_rc)
|
||||
return 1 if alerts_rc != 0 else 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+395
@@ -0,0 +1,395 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full Track 2 timeline with fail-fast, preflight and guaranteed restore.
|
||||
|
||||
Warmup >= 70m, baseline, 2m burst, 15m sustained outage, resolution, TTR and
|
||||
false-positive phases. The script records injection/restore timestamps, alert
|
||||
transitions and Prometheus snapshots before and after each fault.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
for _key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
# tests/client.py builds its own opener; make it ignore macOS system proxies too.
|
||||
urllib.request.getproxies = lambda: {}
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ACTIVE_LOAD = [None]
|
||||
|
||||
|
||||
def utc(ts=None):
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(ts if ts is not None else time.time()))
|
||||
|
||||
|
||||
def http_json(url, timeout=15):
|
||||
with OPENER.open(url, timeout=timeout) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
return http_json(url).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def alerts():
|
||||
return http_json('http://localhost:9090/api/v1/alerts').get('data', {}).get('alerts', [])
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
result = subprocess.run(
|
||||
['docker', 'compose', '--env-file', '.env', '-f', 'compose.yaml', *args],
|
||||
cwd=ROOT, capture_output=True, text=True, check=False,
|
||||
)
|
||||
(ROOT / 'evidence/lab6/track2').mkdir(parents=True, exist_ok=True)
|
||||
with (ROOT / 'evidence/lab6/track2/full-compose.log').open('a') as log:
|
||||
log.write(utc() + ' docker compose ' + ' '.join(args) + ' rc=' + str(result.returncode) + '\n')
|
||||
if result.stderr:
|
||||
log.write(result.stderr[-2000:] + '\n')
|
||||
if check and result.returncode != 0:
|
||||
raise RuntimeError('docker compose %s failed rc=%d: %s' % (' '.join(args), result.returncode, result.stderr[-500:]))
|
||||
return result
|
||||
|
||||
|
||||
def wait_ready(timeout=120):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
with OPENER.open('http://localhost:8080/health/ready', timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
return False
|
||||
|
||||
|
||||
class AlertTimeline:
|
||||
def __init__(self, path):
|
||||
self.path = path
|
||||
self.stop = threading.Event()
|
||||
self.active = {}
|
||||
self.changes = []
|
||||
self.injection = ''
|
||||
self.lock = threading.Lock()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self.handle = path.open('w', newline='')
|
||||
self.writer = csv.writer(self.handle)
|
||||
self.writer.writerow(['observed_utc', 'alert', 'state', 'active_at', 'value', 'injection_utc', 'labels'])
|
||||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
current = {}
|
||||
for alert in alerts():
|
||||
state = alert.get('state', '')
|
||||
if state not in ('pending', 'firing'):
|
||||
continue
|
||||
labels = alert.get('labels', {})
|
||||
name = labels.get('alertname', '')
|
||||
key = name + '|' + json.dumps(labels, sort_keys=True, separators=(',', ':'))
|
||||
current[key] = (name, state, alert.get('activeAt', ''), alert.get('value', ''), labels)
|
||||
for key, (name, state, active_at, value, labels) in current.items():
|
||||
previous = self.active.get(key)
|
||||
if previous is None or previous[1] != state:
|
||||
row = [utc(), name, state, active_at, value, self.injection, json.dumps(labels, sort_keys=True, separators=(',', ':'))]
|
||||
with self.lock:
|
||||
self.changes.append(row)
|
||||
self.writer.writerow(row)
|
||||
self.handle.flush()
|
||||
for key in sorted(set(self.active) - set(current)):
|
||||
name, state, _, _, labels = self.active[key]
|
||||
if state != 'firing':
|
||||
continue
|
||||
row = [utc(), name, 'resolved', '', '', self.injection, json.dumps(labels, sort_keys=True, separators=(',', ':'))]
|
||||
with self.lock:
|
||||
self.changes.append(row)
|
||||
self.writer.writerow(row)
|
||||
self.handle.flush()
|
||||
self.active = current
|
||||
except Exception as exc:
|
||||
with self.lock:
|
||||
self.writer.writerow([utc(), 'POLL_ERROR', str(exc)[:160], '', '', self.injection])
|
||||
self.handle.flush()
|
||||
self.stop.wait(5)
|
||||
|
||||
def finish(self):
|
||||
self.stop.set()
|
||||
self.thread.join(timeout=20)
|
||||
self.handle.close()
|
||||
return self.changes
|
||||
|
||||
|
||||
def snapshot(out, label):
|
||||
values = {}
|
||||
errors = []
|
||||
for name, expr in {
|
||||
'api_error_5m': 'slo:api_error_ratio:5m',
|
||||
'api_error_1h': 'slo:api_error_ratio:1h',
|
||||
'api_error_30m': 'slo:api_error_ratio:30m',
|
||||
'api_error_6h': 'slo:api_error_ratio:6h',
|
||||
'ttr_bad_5m': 'slo:job_ttr_bad_ratio:5m',
|
||||
'ttr_bad_1h': 'slo:job_ttr_bad_ratio:1h',
|
||||
'queue_oldest': 'max(messenger_queue_oldest_job_age_seconds)',
|
||||
'queue_depth': 'max(rabbitmq_queue_messages_ready{queue="attachment.process.v1"})',
|
||||
'jobs_overdue': 'max(messenger_jobs_overdue)',
|
||||
'worker_busy': 'max(messenger_worker_busy)',
|
||||
}.items():
|
||||
try:
|
||||
result = prom(expr)
|
||||
values[name] = result[0]['value'][1] if result else None
|
||||
except Exception as exc:
|
||||
values[name] = None
|
||||
errors.append(name + ': ' + str(exc)[:100])
|
||||
(out / 'snapshots').mkdir(parents=True, exist_ok=True)
|
||||
(out / 'snapshots' / (label + '-' + utc().replace(':', '-') + '.json')).write_text(json.dumps(values, indent=2) + '\n')
|
||||
if errors:
|
||||
raise RuntimeError('Prometheus snapshot failed: ' + '; '.join(errors))
|
||||
return values
|
||||
|
||||
|
||||
def run_load(out, label, duration, ratio=0.2, rate=0.2):
|
||||
log_path = out / (label + '-load.log')
|
||||
output_path = out / (label + '-load.json')
|
||||
cmd = [sys.executable, str(ROOT / 'scripts/lab6_load.py'),
|
||||
'--base-url', 'http://localhost:8080', '--rate', str(rate),
|
||||
'--duration', str(duration), '--upload-ratio', str(ratio),
|
||||
'--deadline', '60', '--output', str(output_path)]
|
||||
log = log_path.open('w')
|
||||
process = subprocess.Popen(cmd, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
|
||||
ACTIVE_LOAD[0] = (process, log, output_path)
|
||||
return process, log, output_path
|
||||
|
||||
|
||||
def finish_load(process, log, output_path, label, expected_s, allow_failures=False):
|
||||
try:
|
||||
rc = process.wait(timeout=expected_s + 300)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
rc = process.wait()
|
||||
log.close()
|
||||
ACTIVE_LOAD[0] = None
|
||||
if not output_path.exists():
|
||||
raise RuntimeError(label + ': load produced no JSON (rc=' + str(rc) + ')')
|
||||
summary = json.loads(output_path.read_text())
|
||||
minimum = 0.85 * expected_s if expected_s >= 30 else 0.5 * expected_s
|
||||
if summary.get('duration_s', 0) < minimum:
|
||||
raise RuntimeError(label + ': load ran only ' + str(summary.get('duration_s')) + 's, expected ~' + str(expected_s))
|
||||
if not allow_failures and (rc != 0 or summary.get('failures', 0)):
|
||||
raise RuntimeError(label + ': load failed rc=' + str(rc) + ' failures=' + str(summary.get('failures')))
|
||||
return summary
|
||||
|
||||
|
||||
def restore_stand():
|
||||
compose('unpause', 'postgres', check=False)
|
||||
compose('start', 'postgres', check=False)
|
||||
compose('up', '-d', '--wait', '--no-deps', 'worker', check=False)
|
||||
return wait_ready(120)
|
||||
|
||||
|
||||
def phase(out, phases, name, started, injection='', restore=''):
|
||||
value = {
|
||||
'phase': name,
|
||||
'started_utc': utc(started),
|
||||
'finished_utc': utc(),
|
||||
'duration_s': round(time.time() - started, 1),
|
||||
'injection_utc': injection,
|
||||
'restore_utc': restore,
|
||||
}
|
||||
phases.append(value)
|
||||
(out / 'phases.json').write_text(json.dumps(phases, indent=2) + '\n')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Full lab6 Track 2 timeline')
|
||||
parser.add_argument('--warmup', type=int, default=4200)
|
||||
parser.add_argument('--baseline', type=int, default=1200)
|
||||
parser.add_argument('--burst', type=int, default=120)
|
||||
parser.add_argument('--settle', type=int, default=600)
|
||||
parser.add_argument('--sustained', type=int, default=900)
|
||||
parser.add_argument('--resolution', type=int, default=3600)
|
||||
parser.add_argument('--ttr', type=int, default=900)
|
||||
parser.add_argument('--false-positive', type=int, default=1200)
|
||||
parser.add_argument('--out', default='evidence/lab6/track2/full')
|
||||
args = parser.parse_args()
|
||||
out = ROOT / args.out
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
phases = []
|
||||
timeline = AlertTimeline(out / 'alerts.csv')
|
||||
timeline.start()
|
||||
interrupted = False
|
||||
exit_code = 0
|
||||
try:
|
||||
def on_signal(signum, _frame):
|
||||
raise KeyboardInterrupt('signal %d' % signum)
|
||||
signal.signal(signal.SIGINT, on_signal)
|
||||
signal.signal(signal.SIGTERM, on_signal)
|
||||
|
||||
if not wait_ready(120):
|
||||
raise RuntimeError('preflight: /health/ready is not ready')
|
||||
preflight = run_load(out, 'preflight', 3, ratio=0.5, rate=1.0)
|
||||
finish_load(*preflight, 'preflight', 3, allow_failures=False)
|
||||
print(utc(), 'preflight OK; start full track', flush=True)
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'warmup', args.warmup)
|
||||
print(utc(), 'warmup started', flush=True)
|
||||
finish_load(*load, 'warmup', args.warmup)
|
||||
phase(out, phases, 'warmup', t)
|
||||
snapshot(out, 'warmup')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'baseline', args.baseline)
|
||||
print(utc(), 'baseline started', flush=True)
|
||||
finish_load(*load, 'baseline', args.baseline)
|
||||
phase(out, phases, 'baseline', t)
|
||||
(out / 'baseline.json').write_text(json.dumps(snapshot(out, 'baseline'), indent=2) + '\n')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'burst', args.burst + args.settle)
|
||||
time.sleep(10)
|
||||
injection = utc()
|
||||
timeline.injection = injection
|
||||
print(utc(), 'burst: pause postgres', flush=True)
|
||||
compose('pause', 'postgres')
|
||||
time.sleep(min(30, args.burst))
|
||||
burst_active = snapshot(out, 'burst-active')
|
||||
if args.burst > 30:
|
||||
time.sleep(args.burst - 30)
|
||||
compose('unpause', 'postgres')
|
||||
restore = utc()
|
||||
print(utc(), 'burst: unpause postgres', flush=True)
|
||||
finish_load(*load, 'burst', args.burst + args.settle, allow_failures=True)
|
||||
phase(out, phases, 'burst', t, injection, restore)
|
||||
burst_after = snapshot(out, 'burst-after')
|
||||
(out / 'burst.json').write_text(json.dumps({'active': burst_active, 'after': burst_after}, indent=2) + '\n')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'sustained', args.sustained + 300)
|
||||
time.sleep(10)
|
||||
injection = utc()
|
||||
timeline.injection = injection
|
||||
print(utc(), 'sustained: stop postgres', flush=True)
|
||||
compose('stop', 'postgres')
|
||||
time.sleep(min(30, args.sustained))
|
||||
sustained_active = snapshot(out, 'sustained-active')
|
||||
if args.sustained > 30:
|
||||
time.sleep(args.sustained - 30)
|
||||
compose('start', 'postgres')
|
||||
if not wait_ready(180):
|
||||
raise RuntimeError('sustained: readiness did not recover')
|
||||
restore = utc()
|
||||
print(utc(), 'sustained: postgres restored', flush=True)
|
||||
finish_load(*load, 'sustained', args.sustained + 300, allow_failures=True)
|
||||
drained = wait_queue_drain(300)
|
||||
phase(out, phases, 'sustained', t, injection, restore)
|
||||
sustained_after = snapshot(out, 'sustained-after')
|
||||
(out / 'sustained.json').write_text(json.dumps({'active': sustained_active, 'after': sustained_after, 'queue_drained': drained}, indent=2) + '\n')
|
||||
|
||||
print(utc(), 'resolution under normal load', flush=True)
|
||||
t = time.time()
|
||||
load = run_load(out, 'resolution', args.resolution)
|
||||
finish_load(*load, 'resolution', args.resolution)
|
||||
phase(out, phases, 'resolution_wait', t)
|
||||
snapshot(out, 'resolution')
|
||||
|
||||
t = time.time()
|
||||
compose('stop', 'worker')
|
||||
load = run_load(out, 'ttr', args.ttr, ratio=1.0)
|
||||
time.sleep(10)
|
||||
injection = utc()
|
||||
timeline.injection = injection
|
||||
print(utc(), 'ttr: worker stopped and uploads started', flush=True)
|
||||
time.sleep(args.ttr)
|
||||
compose('up', '-d', '--no-deps', 'worker')
|
||||
restore = utc()
|
||||
finish_load(*load, 'ttr', args.ttr, allow_failures=True)
|
||||
wait_queue_drain(300)
|
||||
phase(out, phases, 'ttr', t, injection, restore)
|
||||
snapshot(out, 'ttr-after')
|
||||
|
||||
t = time.time()
|
||||
load = run_load(out, 'false-positive', args.false_positive)
|
||||
print(utc(), 'false-positive phase started', flush=True)
|
||||
finish_load(*load, 'false-positive', args.false_positive)
|
||||
phase(out, phases, 'false-positive', t)
|
||||
final = snapshot(out, 'final')
|
||||
(out / 'final.json').write_text(json.dumps(final, indent=2) + '\n')
|
||||
|
||||
except BaseException as exc:
|
||||
interrupted = True
|
||||
(out / 'aborted.json').write_text(json.dumps({'aborted_utc': utc(), 'error': repr(exc)}, indent=2) + '\n')
|
||||
print(utc(), 'ABORT', repr(exc), flush=True)
|
||||
raise
|
||||
finally:
|
||||
if ACTIVE_LOAD[0] is not None:
|
||||
process, log, _ = ACTIVE_LOAD[0]
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
log.close()
|
||||
ACTIVE_LOAD[0] = None
|
||||
restored = restore_stand()
|
||||
if not restored and not interrupted:
|
||||
exit_code = 1
|
||||
changes = timeline.finish()
|
||||
(out / 'alerts.json').write_text(json.dumps(changes, indent=2) + '\n')
|
||||
try:
|
||||
final_summary = snapshot(out, 'final-summary')
|
||||
except Exception as exc:
|
||||
final_summary = {'error': str(exc)[:200]}
|
||||
(out / 'summary.md').write_text(
|
||||
'# Full Track 2 run\n\nPhases:\n```json\n' + json.dumps(phases, indent=2) +
|
||||
'\n```\n\nFinal snapshot:\n```json\n' + json.dumps(final_summary, indent=2) +
|
||||
'\n```\n\nAborted: ' + str(interrupted) + '\nRestored: ' + str(restored) + '\n')
|
||||
print(utc(), 'done; evidence', out, flush=True)
|
||||
return exit_code
|
||||
|
||||
|
||||
def wait_queue_drain(timeout=300):
|
||||
deadline = time.time() + timeout
|
||||
good = 0
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
oldest = prom('max(messenger_queue_oldest_job_age_seconds)')
|
||||
depth = prom('max(rabbitmq_queue_messages_ready{queue="attachment.process.v1"})')
|
||||
if not oldest or not depth:
|
||||
good = 0
|
||||
time.sleep(10)
|
||||
continue
|
||||
oldest_v = float(oldest[0]['value'][1])
|
||||
depth_v = float(depth[0]['value'][1])
|
||||
if oldest_v < 5 and depth_v < 5:
|
||||
good += 1
|
||||
if good >= 2:
|
||||
return True
|
||||
else:
|
||||
good = 0
|
||||
except Exception:
|
||||
good = 0
|
||||
time.sleep(10)
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Isolated 15-minute worker outage with TTR/queue/alert samples."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
for key in ('HTTP_PROXY','HTTPS_PROXY','ALL_PROXY','http_proxy','https_proxy','all_proxy'):
|
||||
os.environ.pop(key, None)
|
||||
OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'http://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with OPENER.open(url, timeout=10) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def alerts():
|
||||
with OPENER.open('http://localhost:9090/api/v1/alerts', timeout=10) as response:
|
||||
data = json.loads(response.read()).get('data', {}).get('alerts', [])
|
||||
return [(a['labels'].get('alertname', ''), a['state']) for a in data]
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(['docker','compose','--env-file','.env',*args], cwd=ROOT,
|
||||
capture_output=True, text=True, check=check)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--duration', type=int, default=930, help='sampling window seconds')
|
||||
parser.add_argument('--loads', type=int, default=1, help='initial load users')
|
||||
parser.add_argument('--spawn-every', type=int, default=90, help='start a new load user every N seconds')
|
||||
args = parser.parse_args()
|
||||
print('UTC', time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()), flush=True)
|
||||
print('HEAD', subprocess.run(['git','rev-parse','HEAD'], cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip(), flush=True)
|
||||
print('$ /api/v1/rules (contains or vector(0))', flush=True)
|
||||
with OPENER.open('http://localhost:9090/api/v1/rules', timeout=10) as response:
|
||||
rules = response.read().decode()
|
||||
print('or_vector_0=', 'or vector(0)' in rules, flush=True)
|
||||
print('json_len=', len(rules), flush=True)
|
||||
print('$ pre ALERTS', alerts(), flush=True)
|
||||
|
||||
loads = []
|
||||
|
||||
def start_load():
|
||||
index = len(loads)
|
||||
loads.append(subprocess.Popen([
|
||||
'python3', str(ROOT/'scripts/lab6_load.py'), '--base-url', 'http://localhost:8080',
|
||||
'--rate', '0.2', '--duration', '1000', '--upload-ratio', '1',
|
||||
'--deadline', '60', '--output', '/tmp/lab6-ttr-worker-load-%d.json' % index,
|
||||
], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL))
|
||||
|
||||
for _ in range(args.loads):
|
||||
start_load()
|
||||
time.sleep(5)
|
||||
print('$ stop worker', flush=True)
|
||||
print(compose('stop','worker').stdout.strip(), flush=True)
|
||||
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < args.duration:
|
||||
time.sleep(30)
|
||||
elapsed = int(time.monotonic() - started)
|
||||
if args.spawn_every > 0 and elapsed and elapsed % args.spawn_every == 0:
|
||||
start_load()
|
||||
print(
|
||||
't=%ss '%elapsed +
|
||||
'ratio5=' + prom('slo:job_ttr_bad_ratio:5m') +
|
||||
' ratio1h=' + prom('slo:job_ttr_bad_ratio:1h') +
|
||||
' missed_total=' + prom('sum(messenger_jobs_ttr_missed_total)') +
|
||||
' missed_inc5=' + prom('sum(increase(messenger_jobs_ttr_missed_total[5m]))') +
|
||||
' bucket_count=' + prom('count(messenger_job_time_to_ready_seconds_bucket)') +
|
||||
' overdue=' + prom('max(messenger_jobs_overdue)') +
|
||||
' oldest=' + prom('max(messenger_queue_oldest_job_age_seconds)') +
|
||||
' alerts=' + json.dumps(alerts()),
|
||||
flush=True,
|
||||
)
|
||||
|
||||
print('$ start worker', flush=True)
|
||||
print(compose('start','worker').stdout.strip(), flush=True)
|
||||
for elapsed in (30, 60, 120, 180, 240, 300):
|
||||
time.sleep(30 if elapsed == 30 else 30)
|
||||
print(
|
||||
'recovery t=%ss '%elapsed +
|
||||
'ratio5=' + prom('slo:job_ttr_bad_ratio:5m') +
|
||||
' ratio1h=' + prom('slo:job_ttr_bad_ratio:1h') +
|
||||
' missed_total=' + prom('sum(messenger_jobs_ttr_missed_total)') +
|
||||
' overdue=' + prom('max(messenger_jobs_overdue)') +
|
||||
' oldest=' + prom('max(messenger_queue_oldest_job_age_seconds)') +
|
||||
' alerts=' + json.dumps(alerts()),
|
||||
flush=True,
|
||||
)
|
||||
for load in loads:
|
||||
load.terminate()
|
||||
for load in loads:
|
||||
try:
|
||||
load.wait(timeout=15)
|
||||
except subprocess.TimeoutExpired:
|
||||
load.kill()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+314
@@ -0,0 +1,314 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Strict lab6 observability gate.
|
||||
|
||||
It creates a fresh message and attachment, waits for all three signals, checks
|
||||
route/template cardinality, Grafana provisioning and rules, and verifies that
|
||||
user content and credentials never reached Loki. A missing signal is a failure,
|
||||
not a warning.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
# The lab tools always target loopback; ignore ambient corporate proxies.
|
||||
for _proxy_key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(_proxy_key, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = 'localhost,127.0.0.1,::1'
|
||||
urllib.request.getproxies = lambda: {}
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
UUID_RE = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
|
||||
FORBIDDEN_LABELS = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'filename', 'request_id', 'object_key', 'path', 'query'}
|
||||
|
||||
|
||||
def request(url, auth=None, timeout=10):
|
||||
headers = {'Accept': 'application/json'}
|
||||
if auth:
|
||||
headers['Authorization'] = 'Basic ' + base64.b64encode(auth.encode()).decode()
|
||||
req = urllib.request.Request(url, headers=headers)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as response:
|
||||
return response.status, response.read()
|
||||
|
||||
|
||||
def prom(base, expr):
|
||||
url = base.rstrip('/') + '/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
_, raw = request(url)
|
||||
return json.loads(raw).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def prom_series(base, match):
|
||||
url = base.rstrip('/') + '/api/v1/series?' + urllib.parse.urlencode({'match[]': match})
|
||||
_, raw = request(url)
|
||||
return json.loads(raw).get('data', [])
|
||||
|
||||
|
||||
def loki_query(base, query, start_ns, end_ns, limit=20):
|
||||
params = urllib.parse.urlencode({'query': query, 'start': start_ns, 'end': end_ns, 'limit': limit})
|
||||
_, raw = request(base.rstrip('/') + '/loki/api/v1/query_range?' + params)
|
||||
return json.loads(raw).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def grafana_password():
|
||||
path = ROOT / 'secrets/grafana.env'
|
||||
if not path.exists():
|
||||
return None
|
||||
for line in path.read_text().splitlines():
|
||||
if '=' in line and line.split('=', 1)[0].strip() == 'GF_SECURITY_ADMIN_PASSWORD':
|
||||
return line.split('=', 1)[1].strip()
|
||||
return None
|
||||
|
||||
|
||||
def wait_for(fn, attempts=30, delay=2):
|
||||
last = None
|
||||
for _ in range(attempts):
|
||||
try:
|
||||
value = fn()
|
||||
if value:
|
||||
return value
|
||||
except Exception as exc: # noqa: BLE001 - retry the external endpoint
|
||||
last = exc
|
||||
time.sleep(delay)
|
||||
if last:
|
||||
raise last
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Strict lab6 telemetry gate')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--prometheus', default='http://localhost:9090')
|
||||
parser.add_argument('--loki', default='http://localhost:3100')
|
||||
parser.add_argument('--tempo', default='http://localhost:3200')
|
||||
parser.add_argument('--grafana', default='http://localhost:3000')
|
||||
parser.add_argument('--wait-seconds', type=int, default=60)
|
||||
args = parser.parse_args()
|
||||
failures = []
|
||||
notes = []
|
||||
|
||||
# 1. Generate a controlled request, a message and a job.
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client
|
||||
client = Client(args.base_url, timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
request_id = 'lab6-verify-' + uuid.uuid4().hex
|
||||
sentinel = 'SENTINEL-TELEMETRY-' + uuid.uuid4().hex
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
|
||||
body={'text': sentinel}, headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-ID': request_id})
|
||||
att, content = client.attachment(alice, chat)
|
||||
client.wait_ready(alice, att, wait_seconds=60)
|
||||
filename = 'sentinel-' + uuid.uuid4().hex + '.png'
|
||||
from urllib.parse import quote
|
||||
client.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + quote(filename), 202,
|
||||
actor=alice, raw=content, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
token = alice.get('token', '')
|
||||
notes.append('created request_id=' + request_id)
|
||||
|
||||
# 2. Required metric series. Counter/histogram series can take one export
|
||||
# and one scrape interval to appear.
|
||||
required = [
|
||||
('http_server_request_duration_seconds_count', 'HTTP request histogram count'),
|
||||
('http_server_request_duration_seconds_bucket', 'HTTP duration histogram'),
|
||||
('messenger_jobs_processed_total', 'job attempt counter'),
|
||||
('messenger_jobs_accepted_total', 'accepted jobs'),
|
||||
('messenger_jobs_ready_within_budget_total', 'ready-within-budget'),
|
||||
('messenger_job_duration_seconds_bucket', 'job duration histogram'),
|
||||
('messenger_job_time_to_ready_seconds_bucket', 'time-to-ready histogram'),
|
||||
('messenger_jobs_overdue', 'overdue jobs'),
|
||||
('messenger_worker_busy', 'worker saturation'),
|
||||
('messenger_db_pool_used', 'DB pool'),
|
||||
('messenger_queue_oldest_job_age_seconds', 'oldest job age'),
|
||||
('messenger_outbox_oldest_unpublished_age_seconds', 'outbox age'),
|
||||
('messenger_process_cpu_seconds_total', 'process CPU'),
|
||||
('rabbitmq_queue_messages_ready', 'RabbitMQ queue depth'),
|
||||
('otelcol_exporter_queue_size', 'collector queue self-metric'),
|
||||
]
|
||||
try:
|
||||
if not wait_for(lambda: prom(args.prometheus, 'sum(rate(messenger_job_time_to_ready_seconds_bucket{le="30.0"}[5m]))'), attempts=20, delay=3):
|
||||
failures.append('TTR good-event selector le="30.0" is empty')
|
||||
except Exception as exc:
|
||||
failures.append('TTR selector: ' + str(exc))
|
||||
|
||||
for metric, label in required:
|
||||
try:
|
||||
found = wait_for(lambda m=metric: prom(args.prometheus, 'count(' + m + ')'), attempts=max(1, args.wait_seconds // 3), delay=3)
|
||||
if not found:
|
||||
failures.append(label + ': no samples (' + metric + ')')
|
||||
except Exception as exc:
|
||||
failures.append(label + ': ' + str(exc))
|
||||
|
||||
try:
|
||||
up = prom(args.prometheus, 'up{job=~"otel-collector|haproxy|rabbitmq"} == 1')
|
||||
jobs = {item.get('metric', {}).get('job') for item in up}
|
||||
for job in ('otel-collector', 'haproxy', 'rabbitmq'):
|
||||
if job not in jobs:
|
||||
failures.append('Prometheus target is not up: ' + job)
|
||||
except Exception as exc:
|
||||
failures.append('Prometheus targets: ' + str(exc))
|
||||
|
||||
try:
|
||||
series = prom_series(args.prometheus, 'http_server_request_duration_seconds_count')
|
||||
routes = [item.get('http_route', '') for item in series]
|
||||
if not series:
|
||||
failures.append('HTTP metric has no series')
|
||||
for route in routes:
|
||||
if not route:
|
||||
failures.append('HTTP metric has an empty http_route label')
|
||||
if UUID_RE.search(route):
|
||||
failures.append('HTTP route label contains a UUID: ' + route)
|
||||
labels = {key for item in series for key in item}
|
||||
forbidden = labels & FORBIDDEN_LABELS
|
||||
if forbidden:
|
||||
failures.append('HTTP metric has forbidden labels: ' + ', '.join(sorted(forbidden)))
|
||||
methods = {item.get('http_request_method', '') for item in series}
|
||||
if len(methods) > 7:
|
||||
failures.append('HTTP method label cardinality is too high: ' + str(len(methods)))
|
||||
for method in methods:
|
||||
if method not in {'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'OTHER'}:
|
||||
failures.append('HTTP method is not normalized: ' + method)
|
||||
except Exception as exc:
|
||||
failures.append('HTTP label check: ' + str(exc))
|
||||
|
||||
# 3. Loki must contain the access log for the controlled request and must
|
||||
# not contain the message text, session token or file bytes.
|
||||
end = int(time.time() * 1e9)
|
||||
start = end - 15 * 60 * int(1e9)
|
||||
try:
|
||||
found = wait_for(lambda: loki_query(args.loki, '{service_name=~"messenger-api|messenger-worker|messenger-relay"} | request_id="' + request_id + '"', start, end), attempts=20, delay=2)
|
||||
if not found:
|
||||
failures.append('Loki: no log with the generated request_id (trace/log correlation)')
|
||||
for needle, label in ((sentinel, 'message text'), (token, 'session token'), (filename, 'filename')):
|
||||
if needle and loki_query(args.loki, '{service_name=~"messenger-api|messenger-worker|messenger-relay"} |= "' + needle + '"', start, end):
|
||||
failures.append('Loki contains forbidden ' + label)
|
||||
except Exception as exc:
|
||||
failures.append('Loki query: ' + str(exc))
|
||||
|
||||
# 4. Tempo must contain real application traces, including the worker span.
|
||||
# Tempo's search `name=` matches root spans only. job.process is a child of
|
||||
# the controlled API trace, so resolve its trace_id from the worker log and
|
||||
# fetch that trace directly.
|
||||
try:
|
||||
def tempo_search(tag):
|
||||
q = urllib.parse.quote(tag)
|
||||
_, raw = request(args.tempo.rstrip('/') + '/api/search?tags=' + q + '&limit=20')
|
||||
return json.loads(raw).get('traces', [])
|
||||
|
||||
def worker_job_trace():
|
||||
result = loki_query(
|
||||
args.loki,
|
||||
'{service_name="messenger-worker"} | event="attachment ready"',
|
||||
start, end, limit=50,
|
||||
)
|
||||
for stream in result:
|
||||
for _, line in stream.get('values', []):
|
||||
try:
|
||||
entry = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
entry = {}
|
||||
trace_id = entry.get('trace_id') or stream.get('stream', {}).get('trace_id', '')
|
||||
if not re.fullmatch(r'[0-9a-f]{32}', trace_id):
|
||||
continue
|
||||
try:
|
||||
_, raw = request(args.tempo.rstrip('/') + '/api/traces/' + trace_id)
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
spans = []
|
||||
for batch in payload.get('batches', []):
|
||||
for scope in batch.get('scopeSpans', []):
|
||||
spans.extend(scope.get('spans', []))
|
||||
publishes = [s for s in spans if s.get('name') == 'job.publish'
|
||||
and s.get('kind') == 'SPAN_KIND_PRODUCER']
|
||||
processes = [s for s in spans if s.get('name') == 'job.process'
|
||||
and s.get('kind') == 'SPAN_KIND_CONSUMER']
|
||||
if any(p.get('parentSpanId') == pub.get('spanId')
|
||||
for p in processes for pub in publishes):
|
||||
return trace_id
|
||||
return None
|
||||
|
||||
if not wait_for(lambda: tempo_search('service.name=messenger-api'), attempts=15, delay=2):
|
||||
failures.append('Tempo: no messenger-api traces')
|
||||
retry_path = ROOT / 'evidence/lab6/trace-retry.json'
|
||||
if retry_path.exists():
|
||||
retry = json.loads(retry_path.read_text())
|
||||
spans = []
|
||||
for batch in retry.get('batches', []):
|
||||
for scope in batch.get('scopeSpans', []):
|
||||
spans.extend(scope.get('spans', []))
|
||||
processes = [s for s in spans if s.get('name') == 'job.process']
|
||||
attempts = set()
|
||||
for span in processes:
|
||||
for attr in span.get('attributes', []):
|
||||
if attr.get('key') == 'job.attempt':
|
||||
value = attr.get('value', {})
|
||||
if 'intValue' in value:
|
||||
attempts.add(int(value['intValue']))
|
||||
outcomes = set()
|
||||
for span in processes:
|
||||
for attr in span.get('attributes', []):
|
||||
if attr.get('key') == 'job.outcome':
|
||||
value = attr.get('value', {}).get('stringValue')
|
||||
if value:
|
||||
outcomes.add(value)
|
||||
if (len(attempts) < 2 or 'retried' not in outcomes
|
||||
or not any(s.get('name') == 'job.requeue' for s in spans)):
|
||||
failures.append('Tempo: retry trace lacks two attempts, retried outcome or job.requeue')
|
||||
if not wait_for(worker_job_trace, attempts=20, delay=2):
|
||||
failures.append('Tempo: no worker job.process trace linked to worker log')
|
||||
except Exception as exc:
|
||||
failures.append('Tempo query: ' + str(exc))
|
||||
|
||||
# 5. Grafana provisioning and rules.
|
||||
try:
|
||||
password = grafana_password()
|
||||
if not password:
|
||||
failures.append('Grafana admin secret is missing (secrets/grafana.env)')
|
||||
else:
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/health')
|
||||
if json.loads(raw).get('database') != 'ok':
|
||||
failures.append('Grafana health is not ok')
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/datasources', auth='admin:' + password)
|
||||
names = {item.get('name') for item in json.loads(raw)}
|
||||
for required_name in ('Prometheus', 'Loki', 'Tempo'):
|
||||
if required_name not in names:
|
||||
failures.append('Grafana datasource missing: ' + required_name)
|
||||
for uid in ('lab6-overview', 'lab6-jobs', 'lab6-infra'):
|
||||
_, raw = request(args.grafana.rstrip('/') + '/api/dashboards/uid/' + uid, auth='admin:' + password)
|
||||
if json.loads(raw).get('dashboard', {}).get('uid') != uid:
|
||||
failures.append('Grafana dashboard missing: ' + uid)
|
||||
except Exception as exc:
|
||||
failures.append('Grafana: ' + str(exc))
|
||||
|
||||
try:
|
||||
_, raw = request(args.prometheus.rstrip('/') + '/api/v1/rules')
|
||||
rule_names = {r.get('name') for g in json.loads(raw).get('data', {}).get('groups', []) for r in g.get('rules', [])}
|
||||
for name in ('APIErrorBudgetFastBurn', 'APIErrorBudgetSlowBurn', 'QueueOldestJobAgeHigh', 'TTRErrorBudgetFastBurn'):
|
||||
if name not in rule_names:
|
||||
failures.append('Prometheus rule missing: ' + name)
|
||||
except Exception as exc:
|
||||
failures.append('Prometheus rules: ' + str(exc))
|
||||
|
||||
for note in notes:
|
||||
print('NOTE:', note)
|
||||
if failures:
|
||||
for item in failures:
|
||||
print('FAIL:', item)
|
||||
return 1
|
||||
print('PASS: lab6 strict telemetry gate (signals, trace/log correlation, labels, Grafana, rules, privacy sentinels)')
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+200
@@ -0,0 +1,200 @@
|
||||
#!/bin/sh
|
||||
# Проверка критерия «LB исключает неготовую реплику» (lab5).
|
||||
#
|
||||
# Рядом с рабочими репликами поднимается третья с тем же сетевым alias, но её
|
||||
# доступ к БД идёт через временный TCP-прокси. Пока прокси жив, реплика готова и
|
||||
# получает трафик через LB. После остановки прокси реплика остаётся доступной по
|
||||
# сети (процесс жив, порт открыт), но /health/ready отвечает 503 — и балансировщик
|
||||
# обязан убрать её из ротации и не отправлять ей ни одного запроса.
|
||||
#
|
||||
# scripts/lb_readiness_check.sh # стенд поднят (make up)
|
||||
# OUT=evidence/lb-readiness.txt scripts/lb_readiness_check.sh
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
# .env определяет, на каком порту публикуется LB (compose.yaml) и какие креды у
|
||||
# хранилищ, поэтому значения берём оттуда же, а не из окружения вызывающего.
|
||||
if [ -f .env ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
fi
|
||||
|
||||
OUT=${OUT:-evidence/lab5/lb-readiness-detail.txt}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
NET=${PROJECT}_default
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab6}
|
||||
STATS=${STATS:-http://127.0.0.1:${LB_STATS_PORT:-8404}/stats;csv}
|
||||
BASE_URL=${BASE_URL:-http://localhost:${SERVER_PORT:-8080}}
|
||||
CANDIDATE=lb-readiness-candidate
|
||||
PROXY=lb-readiness-pgproxy
|
||||
REQUESTS=${REQUESTS:-40}
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
cleanup() {
|
||||
docker rm -f "$CANDIDATE" "$PROXY" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
cleanup
|
||||
|
||||
instances() {
|
||||
tries=${1:-$REQUESTS}
|
||||
i=0
|
||||
|
||||
while [ "$i" -lt "$tries" ]; do
|
||||
curl -fsS --noproxy '*' -D - -o /dev/null "$BASE_URL/health/live" 2>/dev/null \
|
||||
| awk 'tolower($1) == "x-instance-id:" { print $2 }'
|
||||
i=$((i + 1))
|
||||
done | sort | uniq -c
|
||||
}
|
||||
|
||||
stats() {
|
||||
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ { printf "%s=%s ", $2, $18 }'
|
||||
}
|
||||
|
||||
readiness() {
|
||||
docker exec "$CANDIDATE" wget -qO- -S -T 3 http://127.0.0.1:8080/health/ready 2>&1 \
|
||||
| awk '/^ HTTP\//{print $2; exit}'
|
||||
}
|
||||
|
||||
wait_readiness() {
|
||||
want=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 30 ]; do
|
||||
[ "$(readiness)" = "$want" ] && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
up_slots() {
|
||||
curl -s --noproxy '*' "$STATS" | awk -F, '$1 ~ /^api/ && $18 ~ /^UP/ && $2 != "BACKEND" { printf "%s ", $2 }'
|
||||
}
|
||||
|
||||
wait_new_up_slot() {
|
||||
before=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 30 ]; do
|
||||
for slot in $(up_slots); do
|
||||
case " $before " in
|
||||
*" $slot "*) ;;
|
||||
*) echo "$slot"; return 0 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
wait_slot_status() {
|
||||
slot=$1
|
||||
want=$2
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
status=$(curl -s --noproxy '*' "$STATS" | awk -F, -v s="$slot" '$1 ~ /^api/ && $2 == s { print $18; exit }')
|
||||
|
||||
if [ "$status" = "$want" ]; then
|
||||
SWAIT_SECONDS=$((attempt / 2))
|
||||
return 0
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 0.5
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
{
|
||||
echo "# LB excludes a not-ready but reachable replica (lab5)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# lb: $(docker inspect -f '{{.Config.Image}}' "$(docker ps -q --filter label=com.docker.compose.service=lb)" 2>/dev/null)"
|
||||
echo
|
||||
echo "## 1. baseline: requests through LB by replica"
|
||||
instances
|
||||
baseline_slots=$(up_slots)
|
||||
echo " stats: $(stats)"
|
||||
echo
|
||||
echo "## 2. start a temporary TCP proxy to postgres and a candidate replica behind the same network alias"
|
||||
docker run -d --name "$PROXY" --network "$NET" alpine/socat@sha256:fb3862c949af7c79996d0e514ee96128644d840835ed5368eeecb14a869de361 \
|
||||
tcp-listen:5432,fork,reuseaddr tcp-connect:postgres:5432 >/dev/null
|
||||
docker run -d --name "$CANDIDATE" --network "$NET" --network-alias api-replica \
|
||||
-e APP_CONFIG=/etc/messenger/dev/config.yaml \
|
||||
-e POSTGRES_HOST="$PROXY" -e POSTGRES_PORT=5432 \
|
||||
-e POSTGRES_DATABASE="${POSTGRES_DATABASE:-messenger}" \
|
||||
-e POSTGRES_USER="${POSTGRES_USER:-messenger}" \
|
||||
-e POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-messenger}" -e POSTGRES_SSL_MODE=disable \
|
||||
-e REDIS_ENABLED=true -e REDIS_HOST=redis -e CACHE_ENABLED=true \
|
||||
-e S3_ENDPOINT=http://seaweedfs:8333 -e S3_REGION="${S3_REGION:-us-east-1}" \
|
||||
-e S3_BUCKET="${S3_BUCKET:-messenger-attachments}" \
|
||||
-e S3_ACCESS_KEY_ID="${S3_ACCESS_KEY_ID:-lab4app}" \
|
||||
-e S3_SECRET_ACCESS_KEY="${S3_SECRET_ACCESS_KEY:-lab4app-secret}" \
|
||||
-e S3_USE_PATH_STYLE=true \
|
||||
"$IMAGE" >/dev/null
|
||||
|
||||
if ! wait_readiness 200; then
|
||||
echo " candidate did not become ready" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " instance-id: $(docker inspect -f '{{.Config.Hostname}}' "$CANDIDATE"), readiness while its database is reachable: 200"
|
||||
|
||||
slot=$(wait_new_up_slot "$baseline_slots" || true)
|
||||
if [ -z "$slot" ]; then
|
||||
echo " candidate did not appear UP in the load balancer" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " load balancer slot for the candidate: $slot, stats: $(stats)"
|
||||
echo
|
||||
echo "## 3. cut the candidate's database access (stop only the TCP proxy)"
|
||||
docker stop "$PROXY" >/dev/null
|
||||
|
||||
if ! wait_readiness 503; then
|
||||
echo " candidate readiness did not become 503" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " candidate is still running: $(docker inspect -f '{{.State.Status}}' "$CANDIDATE"), readiness: 503"
|
||||
echo " waiting for the load balancer to mark $slot DOWN"
|
||||
|
||||
if wait_slot_status "$slot" DOWN; then
|
||||
echo " $slot went DOWN ${SWAIT_SECONDS}s after its database was cut (check: inter 2s fall 2)"
|
||||
else
|
||||
echo " FAIL: $slot is still not DOWN" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo " stats after failure: $(stats)"
|
||||
echo
|
||||
echo "## 4. ${REQUESTS} requests through LB while the candidate is not ready"
|
||||
instances
|
||||
echo " (the candidate must not appear above)"
|
||||
echo
|
||||
echo "## 5. business writes through LB during the exclusion"
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url "$BASE_URL" --duration 5 --concurrency 2 \
|
||||
| grep -E '"successful_rps"|"failed_requests"|"error_ratio"'
|
||||
echo
|
||||
echo "## 6. cleanup"
|
||||
cleanup
|
||||
sleep 5
|
||||
echo " stats after cleanup: $(stats)"
|
||||
} > "$OUT" 2>&1
|
||||
|
||||
cat "$OUT"
|
||||
printf 'lb_readiness_check.sh: evidence in %s\n' "$OUT"
|
||||
@@ -0,0 +1,271 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
|
||||
def request(base_url, method, path, body=None, user_id=None):
|
||||
payload = json.dumps(body, ensure_ascii=False).encode() if body is not None else None
|
||||
headers = {"Content-Type": "application/json"} if payload else {}
|
||||
if user_id:
|
||||
headers["X-User-Id"] = user_id
|
||||
request = urllib.request.Request(
|
||||
base_url + path,
|
||||
data=payload,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=3) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def wait_ready(base_url):
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
request(base_url, "GET", "/health/live")
|
||||
return
|
||||
except OSError:
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("container did not become ready")
|
||||
|
||||
|
||||
def process_alive(container):
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{.State.Running}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
return result.stdout.strip() == "true"
|
||||
|
||||
|
||||
def sample_stats(container, samples, stop):
|
||||
while not stop.is_set():
|
||||
result = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode == 0 and result.stdout.strip():
|
||||
try:
|
||||
value = json.loads(result.stdout)
|
||||
memory = value.get("MemUsage", "").split("/")[0].strip()
|
||||
if memory == "0B" or not process_alive(container):
|
||||
continue
|
||||
samples.append({
|
||||
"time_seconds": time.monotonic(),
|
||||
"memory": memory,
|
||||
"memory_mib": parse_memory(memory),
|
||||
})
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
stop.wait(0.1)
|
||||
|
||||
|
||||
def parse_memory(value):
|
||||
units = {"B": 1 / 1024 / 1024, "KiB": 1 / 1024, "MiB": 1, "GiB": 1024}
|
||||
for unit, factor in sorted(units.items(), key=lambda item: -len(item[0])):
|
||||
if value.endswith(unit):
|
||||
return float(value[:-len(unit)].strip()) * factor
|
||||
raise ValueError(value)
|
||||
|
||||
|
||||
def make_plot(data, output):
|
||||
samples = [sample for sample in data["memory_samples"] if sample["memory_mib"] > 0]
|
||||
start = samples[0]["time_seconds"] if samples else 0
|
||||
x = [sample["time_seconds"] - start for sample in samples]
|
||||
memory = [sample["memory_mib"] for sample in samples]
|
||||
|
||||
fig, memory_axis = plt.subplots(figsize=(11, 6))
|
||||
memory_axis.plot(x, memory, color="tab:red", label="RSS / container memory")
|
||||
memory_axis.axhline(data["memory_limit_mib"], color="black", linestyle="--", label="memory limit")
|
||||
memory_axis.set_xlabel("Time, seconds")
|
||||
memory_axis.set_ylabel("Memory, MiB")
|
||||
memory_axis.grid(True, alpha=0.25)
|
||||
|
||||
message_axis = memory_axis.twinx()
|
||||
message_axis.plot(
|
||||
data["message_points_x"],
|
||||
data["message_points_y"],
|
||||
color="tab:blue",
|
||||
label="successful messages",
|
||||
)
|
||||
message_axis.set_ylabel("Successful messages")
|
||||
|
||||
lines, labels = memory_axis.get_legend_handles_labels()
|
||||
other_lines, other_labels = message_axis.get_legend_handles_labels()
|
||||
memory_axis.legend(lines + other_lines, labels + other_labels, loc="upper left")
|
||||
memory_axis.set_title("In-memory messenger: memory exhaustion point")
|
||||
if data["oom_killed"] and data["failure_time_seconds"] is not None:
|
||||
memory_axis.axvline(
|
||||
data["failure_time_seconds"],
|
||||
color="tab:purple",
|
||||
linestyle=":",
|
||||
label="container OOMKilled",
|
||||
)
|
||||
memory_axis.annotate(
|
||||
"OOMKilled",
|
||||
(data["failure_time_seconds"], data["memory_limit_mib"]),
|
||||
xytext=(8, -18),
|
||||
textcoords="offset points",
|
||||
color="tab:purple",
|
||||
)
|
||||
fig.tight_layout()
|
||||
fig.savefig(output, dpi=160)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--image", required=True)
|
||||
parser.add_argument("--memory", default="32m")
|
||||
parser.add_argument("--output", default="evidence/memory-experiment.json")
|
||||
parser.add_argument("--plot", default="evidence/memory-experiment.png")
|
||||
parser.add_argument("--max-messages", type=int, default=100000)
|
||||
args = parser.parse_args()
|
||||
|
||||
container = "mtusi-memory-experiment-" + uuid.uuid4().hex[:8]
|
||||
port = 18081
|
||||
base_url = f"http://127.0.0.1:{port}"
|
||||
subprocess.run(
|
||||
[
|
||||
"docker", "run", "-d", "--name", container,
|
||||
"--memory", args.memory, "--memory-swap", args.memory,
|
||||
"-p", f"127.0.0.1:{port}:8080", args.image,
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
samples = []
|
||||
stop_sampling = threading.Event()
|
||||
sampler = threading.Thread(target=sample_stats, args=(container, samples, stop_sampling))
|
||||
successful = 0
|
||||
failures = 0
|
||||
fatal_error = None
|
||||
started = time.monotonic()
|
||||
message_points_x = []
|
||||
message_points_y = []
|
||||
failure_time = None
|
||||
oom_killed = False
|
||||
last_error = None
|
||||
last_state = {}
|
||||
logs = ""
|
||||
|
||||
try:
|
||||
wait_ready(base_url)
|
||||
user = request(base_url, "POST", "/api/v1/users", {
|
||||
"username": "memory_" + uuid.uuid4().hex[:16],
|
||||
"display_name": "Memory experiment",
|
||||
})
|
||||
chat = request(base_url, "POST", "/api/v1/chats", {
|
||||
"title": "Memory experiment",
|
||||
"member_ids": [user["id"]],
|
||||
}, user["id"])
|
||||
sampler.start()
|
||||
time.sleep(0.5)
|
||||
|
||||
body = "x" * 4000
|
||||
for index in range(args.max_messages):
|
||||
try:
|
||||
request(
|
||||
base_url,
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": body},
|
||||
user["id"],
|
||||
)
|
||||
successful += 1
|
||||
message_points_x.append(time.monotonic() - started)
|
||||
message_points_y.append(successful)
|
||||
except (OSError, urllib.error.HTTPError, ValueError) as exc:
|
||||
last_error = type(exc).__name__ + ": " + str(exc)
|
||||
failures += 1
|
||||
failure_time = time.monotonic() - started
|
||||
break
|
||||
|
||||
time.sleep(0.5)
|
||||
if not process_alive(container):
|
||||
failure_time = failure_time or (time.monotonic() - started)
|
||||
inspect = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(inspect.stdout) if inspect.stdout.strip() else {}
|
||||
if not state:
|
||||
state_result = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(state_result.stdout) if state_result.stdout.strip() else {}
|
||||
last_state = state
|
||||
logs_result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, check=False)
|
||||
logs = logs_result.stdout + logs_result.stderr
|
||||
oom_killed = bool(state.get("OOMKilled"))
|
||||
if failure_time is None and failures:
|
||||
failure_time = time.monotonic() - started
|
||||
except Exception as exc:
|
||||
fatal_error = type(exc).__name__ + ": " + str(exc)
|
||||
failure_time = failure_time or (time.monotonic() - started)
|
||||
finally:
|
||||
stop_sampling.set()
|
||||
if sampler.is_alive():
|
||||
sampler.join(timeout=2)
|
||||
|
||||
memory_limit_mib = float(args.memory.rstrip("mM")) if args.memory.lower().endswith("m") else 0
|
||||
if not oom_killed:
|
||||
inspect = subprocess.run(
|
||||
["docker", "inspect", "--format", "{{json .State}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
state = json.loads(inspect.stdout) if inspect.stdout.strip() else {}
|
||||
last_state = state
|
||||
oom_killed = bool(state.get("OOMKilled"))
|
||||
|
||||
result = {
|
||||
"image": args.image,
|
||||
"memory_limit": args.memory,
|
||||
"memory_limit_mib": memory_limit_mib,
|
||||
"successful_messages": successful,
|
||||
"failed_requests": failures,
|
||||
"oom_killed": oom_killed,
|
||||
"last_error": last_error,
|
||||
"fatal_error": fatal_error,
|
||||
"container_state": last_state,
|
||||
"container_logs_tail": logs[-20000:],
|
||||
"failure_time_seconds": failure_time,
|
||||
"memory_samples": samples,
|
||||
"message_points_x": message_points_x,
|
||||
"message_points_y": message_points_y,
|
||||
"reason": "process stopped after the container memory limit was reached" if oom_killed else "request processing did not reach the memory limit",
|
||||
}
|
||||
with open(args.output, "w", encoding="utf-8") as output:
|
||||
json.dump(result, output, ensure_ascii=False, indent=2)
|
||||
make_plot(result, args.plot)
|
||||
print(json.dumps({key: result[key] for key in (
|
||||
"memory_limit", "successful_messages", "failed_requests", "oom_killed", "failure_time_seconds", "reason",
|
||||
)}, ensure_ascii=False, indent=2))
|
||||
subprocess.run(["docker", "rm", "-f", container], capture_output=True, check=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/bin/sh
|
||||
# Контроль пути «хост -> Colima VM -> LB»: тот же генератор и тот же профиль
|
||||
# запускаются дважды — с хоста через опубликованный порт и изнутри VM, где
|
||||
# клиент говорит с балансировщиком напрямую по docker-сети. Разница показывает
|
||||
# вклад этого пути в потолок closed-loop профиля, а не приписывает его по
|
||||
# догадке. Стенд должен быть поднят (`make up`).
|
||||
#
|
||||
# scripts/path_overhead_check.sh
|
||||
#
|
||||
# Артефакт: evidence/path-overhead/{inside,outside}.txt + summary.txt
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
OUT=${OUT:-evidence/path-overhead}
|
||||
DURATION=${DURATION:-60}
|
||||
CONCURRENCY=${CONCURRENCY:-8}
|
||||
WARMUP=${WARMUP:-15}
|
||||
CLIENT_IMAGE=${CLIENT_IMAGE:-python:3.12-alpine}
|
||||
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
mkdir -p "$OUT"
|
||||
|
||||
network=$(docker inspect "$(compose ps -q api | head -1)" \
|
||||
--format '{{range $name, $network := .NetworkSettings.Networks}}{{$name}}{{end}}')
|
||||
|
||||
printf '# Контроль пути к балансировщику\n' > "$OUT/summary.txt"
|
||||
{
|
||||
printf '# generated: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
printf '# profile: tests/load.py duration=%s concurrency=%s warmup=%s\n' "$DURATION" "$CONCURRENCY" "$WARMUP"
|
||||
printf '# docker network: %s\n' "$network"
|
||||
printf '# клиент в VM: %s\n\n' "$CLIENT_IMAGE"
|
||||
} >> "$OUT/summary.txt"
|
||||
|
||||
# Клиент с хоста: путь «хост -> проброс порта -> VM -> LB».
|
||||
printf '=== извне: клиент на хосте, http://127.0.0.1:8080 ===\n' | tee -a "$OUT/summary.txt"
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url http://127.0.0.1:8080 \
|
||||
--duration "$WARMUP" --concurrency "$CONCURRENCY" >/dev/null
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV python3 tests/load.py --base-url http://127.0.0.1:8080 \
|
||||
--duration "$DURATION" --concurrency "$CONCURRENCY" \
|
||||
--output "$OUT/load-outside.json" | tee "$OUT/outside.txt" | tail -12
|
||||
|
||||
# Клиент внутри VM: тот же генератор и профиль, но без проброса порта и без
|
||||
# сетевого стека хоста. Генератор делит 2 vCPU VM со стендом, поэтому его
|
||||
# результат — нижняя оценка, а не потолок.
|
||||
printf '\n=== изнутри: клиент в VM, http://lb ===\n' | tee -a "$OUT/summary.txt"
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" -v "$ROOT_DIR/$OUT:/out" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$WARMUP" --concurrency "$CONCURRENCY" >/dev/null
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" -v "$ROOT_DIR/$OUT:/out" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$DURATION" --concurrency "$CONCURRENCY" \
|
||||
--output /out/load-inside.json | tee "$OUT/inside.txt" | tail -12
|
||||
|
||||
printf 'path_overhead_check.sh: артефакты в %s\n' "$OUT"
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproducible Redis-outage check: stop and pause, latency budget, create-during-outage.
|
||||
|
||||
Exit code is non-zero when any assertion fails. Always unpauses/starts Redis.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import base64
|
||||
|
||||
for proxy in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
os.environ.pop(proxy, None)
|
||||
os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1'
|
||||
os.environ['no_proxy'] = os.environ['NO_PROXY']
|
||||
|
||||
BASE_URL = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
COMPOSE = os.environ.get('COMPOSE_BIN', 'docker-compose')
|
||||
COMPOSE_FILE = 'docker-compose.local.yaml'
|
||||
BUDGET_MS = int(os.environ.get('OUTAGE_BUDGET_MS', '2000'))
|
||||
PARALLEL = int(os.environ.get('OUTAGE_PARALLEL', '30'))
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run([COMPOSE, '-f', COMPOSE_FILE, *args], check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {'Accept': 'application/json'}
|
||||
if body is not None:
|
||||
h['Content-Type'] = 'application/json'
|
||||
h.update(headers or {})
|
||||
req = urllib.request.Request(BASE_URL + path, data=data, headers=h, method=method)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
return resp.status, resp.read(), (time.monotonic() - started) * 1000
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, exc.read(), (time.monotonic() - started) * 1000
|
||||
|
||||
|
||||
def user(label):
|
||||
username = label + '_' + uuid.uuid4().hex[:8]
|
||||
password = 'T3st-' + uuid.uuid4().hex
|
||||
call('POST', '/api/v1/users', {'username': username, 'display_name': label, 'password': password})
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
_, body, _ = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
|
||||
return json.loads(body)
|
||||
|
||||
|
||||
def list_chats(actor):
|
||||
status, body, ms = call('GET', '/api/v1/chats?limit=50', headers={'Authorization': 'Bearer ' + actor['token']})
|
||||
assert status == 200, 'GET /chats expected 200, got %d' % status
|
||||
return json.loads(body)['items'], ms
|
||||
|
||||
|
||||
def assert_budget(label, samples):
|
||||
worst = max(samples)
|
||||
p95 = sorted(samples)[max(0, (len(samples) * 95 + 99) // 100 - 1)]
|
||||
print(' %s: n=%d max=%.0fms p95=%.0fms budget=%dms' % (label, len(samples), worst, p95, BUDGET_MS))
|
||||
assert worst <= BUDGET_MS, '%s exceeded budget: %.0fms > %dms' % (label, worst, BUDGET_MS)
|
||||
|
||||
|
||||
def main():
|
||||
alice = user('alice')
|
||||
bob = user('bob')
|
||||
ah = {'Authorization': 'Bearer ' + alice['token']}
|
||||
|
||||
try:
|
||||
_, ms = list_chats(alice)
|
||||
print('baseline: %.0fms' % ms)
|
||||
|
||||
compose('stop', 'redis')
|
||||
_, ms = list_chats(alice)
|
||||
print('after stop: %.0fms' % ms)
|
||||
assert_budget('stop', [ms])
|
||||
|
||||
compose('start', 'redis')
|
||||
time.sleep(2)
|
||||
compose('pause', 'redis')
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
||||
results = [f for f in pool.map(lambda _: list_chats(alice), range(PARALLEL))]
|
||||
assert_budget('pause parallel', [ms for _, ms in results])
|
||||
|
||||
title = 'during-outage-' + uuid.uuid4().hex[:8]
|
||||
status, _, _ = call('POST', '/api/v1/chats', {
|
||||
'title': title,
|
||||
'member_ids': [alice['user']['id'], bob['user']['id']],
|
||||
}, headers=ah)
|
||||
assert status == 201, 'chat create during pause expected 201, got %d' % status
|
||||
print('create during pause: 201')
|
||||
|
||||
compose('unpause', 'redis')
|
||||
time.sleep(2)
|
||||
|
||||
chats, ms = list_chats(alice)
|
||||
assert any(c['title'] == title for c in chats), 'new chat missing after recovery (stale cache)'
|
||||
print('after recovery: new chat visible, %.0fms' % ms)
|
||||
|
||||
stuck = subprocess.run(
|
||||
[COMPOSE, '-f', COMPOSE_FILE, 'exec', '-T', 'redis', 'redis-cli', '--scan', '--pattern', 'lock:*'],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout.split()
|
||||
for key in stuck:
|
||||
ttl = subprocess.run(
|
||||
[COMPOSE, '-f', COMPOSE_FILE, 'exec', '-T', 'redis', 'redis-cli', 'ttl', key],
|
||||
check=True, capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
assert ttl != '-1', 'stuck lock without TTL: %s' % key
|
||||
print('lock keys without TTL: 0')
|
||||
print('PASS: redis outage handled within budget')
|
||||
finally:
|
||||
for action in ('unpause', 'start'):
|
||||
subprocess.run([COMPOSE, '-f', COMPOSE_FILE, action, 'redis'],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL: %s' % exc)
|
||||
sys.exit(1)
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Restart hook: bounce API replicas, worker/relay and every state store of the lab5 stand.
|
||||
#
|
||||
# scripts/restart.sh
|
||||
#
|
||||
# Persistent volumes are kept: no `down -v`, no flush, no re-seed. The one-shot
|
||||
# `migrate` service is not re-run (schema stays as it is, data and sessions
|
||||
# survive). The script exits 0 only after /health/ready answers through the LB.
|
||||
# No credentials are printed.
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
# .env определяет, на каком порту публикуется LB (compose.yaml) и какие креды у
|
||||
# хранилищ, поэтому значения берём оттуда же, а не из окружения вызывающего.
|
||||
if [ -f .env ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
fi
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
PORT=${SERVER_PORT:-8080}
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
|
||||
# 1. State stores and broker: restart the running ones, then make sure they are
|
||||
# healthy. Volumes are attached as before, nothing is dropped or re-seeded.
|
||||
compose up -d --wait postgres redis seaweedfs broker
|
||||
compose restart postgres redis seaweedfs broker
|
||||
compose up -d --wait postgres redis seaweedfs broker
|
||||
|
||||
# 2. API replicas, worker and relay: restart in place and bring back any replica
|
||||
# stopped by a fault-injection hook. The worker reconnects to the broker.
|
||||
compose restart api worker relay
|
||||
compose up -d --wait --no-deps api worker relay
|
||||
|
||||
# 3. Load balancer keeps its upstream; re-resolve in case addresses changed.
|
||||
compose restart lb
|
||||
|
||||
# 4. Wait for readiness through the public entry point.
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
if curl -fsS --noproxy '*' -o /dev/null "http://127.0.0.1:${PORT}/health/ready"; then
|
||||
printf 'restart.sh: stack restarted, http://127.0.0.1:%s/health/ready is ready\n' "$PORT"
|
||||
exit 0
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'restart.sh: /health/ready did not become ready through the LB\n' >&2
|
||||
exit 1
|
||||
Executable
+231
@@ -0,0 +1,231 @@
|
||||
#!/bin/sh
|
||||
# Rolling update of the API replicas under load (lab3, level 4).
|
||||
#
|
||||
# Замена идёт «наплывом» и строго по одной реплике: сначала рядом поднимается
|
||||
# контейнер новой ревизии с тем же сетевым alias, затем снимается ОДИН старый.
|
||||
# Каждый шаг гейтится состоянием балансировщика: новый слот должен стать UP
|
||||
# (активная проверка /health/ready), снятый — перестать быть UP. Гейт по
|
||||
# статистике LB, а не по наблюдению X-Instance-Id в ответах, потому что HAProxy
|
||||
# переиспользует keepalive-соединения к уже работающим репликам и свежая реплика
|
||||
# может какое-то время не получать трафик, оставаясь при этом готовой.
|
||||
#
|
||||
# В конце стенд возвращается под управление compose: поднимаются штатные реплики
|
||||
# из новой ревизии, затем по одной снимаются временные контейнеры наплыва.
|
||||
#
|
||||
# scripts/rolling_update.sh # профиль лимитов берётся из .env/compose.yaml
|
||||
# DURATION=60 CONCURRENCY=8 scripts/rolling_update.sh
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
PYTHON=${PYTHON:-python3}
|
||||
DURATION=${DURATION:-60}
|
||||
CONCURRENCY=${CONCURRENCY:-8}
|
||||
BASE_URL=${BASE_URL:-http://localhost:8080}
|
||||
OUT=${OUT:-evidence/rolling-update}
|
||||
IMAGE=${IMAGE:-mtusi-messenger:lab4}
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab4}
|
||||
NET=${PROJECT}_default
|
||||
STATS=${STATS:-http://127.0.0.1:8404/stats;csv}
|
||||
PREFIX=lb-rollout
|
||||
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
mkdir -p "$OUT"
|
||||
rm -f "$OUT/load.json" "$OUT/load.txt"
|
||||
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
|
||||
api_containers() {
|
||||
docker ps -q \
|
||||
--filter "label=com.docker.compose.project=$PROJECT" \
|
||||
--filter 'label=com.docker.compose.service=api'
|
||||
}
|
||||
|
||||
rollout_containers() {
|
||||
docker ps -q --filter "name=^$PREFIX"
|
||||
}
|
||||
|
||||
restarts() {
|
||||
for container in $(api_containers) $(rollout_containers); do
|
||||
printf '%s=%s ' "$(docker inspect --format '{{.Name}}' "$container" | sed 's|^/||')" \
|
||||
"$(docker inspect --format '{{.RestartCount}}' "$container")"
|
||||
done
|
||||
}
|
||||
|
||||
stats_rows() {
|
||||
curl -s --noproxy '*' "$STATS"
|
||||
}
|
||||
|
||||
# В CSV-выгрузке HAProxy колонка addr приходит пустой, поэтому привязка слота к
|
||||
# конкретному контейнеру идёт по двум наблюдаемым фактам: контейнер отвечает на
|
||||
# /health/ready, а число UP-слотов соответствует ожидаемому.
|
||||
container_ready() {
|
||||
docker exec "$1" wget -qO- -T 3 http://127.0.0.1:8080/health/ready 2>/dev/null | grep -q '"status":"ok"'
|
||||
}
|
||||
|
||||
wait_container_ready() {
|
||||
name=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 45 ]; do
|
||||
container_ready "$name" && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
up_slots() {
|
||||
stats_rows | awk -F, '
|
||||
NR == 1 { for (i = 1; i <= NF; i++) if ($i == "status") s = i; next }
|
||||
$1 ~ /^api/ && $s == "UP" { count++ } END { print count + 0 }'
|
||||
}
|
||||
|
||||
wait_up_slots() {
|
||||
want=$1
|
||||
attempt=0
|
||||
|
||||
while [ "$attempt" -lt 45 ]; do
|
||||
[ "$(up_slots)" -ge "$want" ] && return 0
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
lb_5xx() {
|
||||
stats_rows | awk -F, '
|
||||
NR == 1 { for (i = 1; i <= NF; i++) if ($i == "hrsp_5xx") column = i; next }
|
||||
$1 == "http_front" && $2 == "FRONTEND" && column { print $column; exit }'
|
||||
}
|
||||
|
||||
{
|
||||
echo "# Rolling update under load (surge, one replica at a time)"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# load: tolerant loader, duration=${DURATION}s concurrency=${CONCURRENCY}"
|
||||
echo "# проверки готовности LB: httpchk /health/ready, inter 2s fall 2 rise 2, timeout check 1s"
|
||||
echo
|
||||
|
||||
# Сборка пишет много строк; в артефакт они не нужны.
|
||||
compose build api >/dev/null 2>&1 || compose build api
|
||||
|
||||
before_containers=$(api_containers)
|
||||
replicas=$(printf '%s\n' "$before_containers" | wc -l | tr -d ' ')
|
||||
[ "$replicas" -ge 2 ] || { echo "нужно не менее двух API-реплик" >&2; exit 1; }
|
||||
|
||||
old_image=$(docker inspect --format '{{.Image}}' "$(printf '%s\n' "$before_containers" | head -1)")
|
||||
new_image=$(docker image inspect --format '{{.Id}}' "$IMAGE")
|
||||
echo "реплик до обновления: ${replicas}"
|
||||
echo "образ старых реплик: ${old_image}"
|
||||
echo "образ новой ревизии: ${new_image}"
|
||||
echo "ревизия меняется: $([ "$old_image" = "$new_image" ] && echo 'нет (образ не изменился)' || echo 'да')"
|
||||
echo "слотов UP до: $(up_slots); restarts до: $(restarts)"
|
||||
echo
|
||||
|
||||
envfile=$(mktemp)
|
||||
trap 'rm -f "$envfile"; docker rm -f $(rollout_containers) >/dev/null 2>&1 || true' EXIT INT TERM
|
||||
docker inspect --format '{{range .Config.Env}}{{println .}}{{end}}' \
|
||||
"$(printf '%s\n' "$before_containers" | head -1)" > "$envfile"
|
||||
|
||||
# Перед измерением убеждаемся, что все ожидаемые реплики видит сам LB: после
|
||||
# экспериментов с отказом хранилищ слоты могут быть в переходном состоянии.
|
||||
if ! wait_up_slots "$replicas"; then
|
||||
echo "перед обновлением LB видит меньше ${replicas} реплик" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
five_before=$(lb_5xx)
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON student-tests/rolling_update_load.py --base-url "$BASE_URL" \
|
||||
--duration "$DURATION" --concurrency "$CONCURRENCY" \
|
||||
--output "$OUT/load.json" > "$OUT/load.txt" 2>&1 &
|
||||
load_pid=$!
|
||||
|
||||
step=0
|
||||
for container in $before_containers; do
|
||||
step=$((step + 1))
|
||||
name="$PREFIX-$step"
|
||||
old_instance=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
started=$(date -u +%Y-%m-%dT%H:%M:%SZ)
|
||||
|
||||
# 1. поднять реплику новой ревизии рядом со старыми; дождаться, что она
|
||||
# сама готова и что LB видит на один слот больше
|
||||
docker run -d --name "$name" --network "$NET" --network-alias api-replica \
|
||||
--env-file "$envfile" "$IMAGE" >/dev/null
|
||||
new_instance=$(docker inspect --format '{{.Config.Hostname}}' "$name")
|
||||
new_container_image=$(docker inspect --format '{{.Image}}' "$name")
|
||||
|
||||
if ! wait_container_ready "$name"; then
|
||||
echo " step ${step}: реплика ${name} не стала готова" >&2
|
||||
echo " diagnostics: status=$(docker inspect --format '{{.State.Status}}' "$name" 2>&1); stats: $(stats_rows | awk -F, '$1 ~ /^api/ { printf "%s=%s ", $2, $18 }')" >&2
|
||||
docker logs --tail 20 "$name" >&2 2>&1 || true
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! wait_up_slots "$((replicas + step))"; then
|
||||
echo " step ${step}: UP-слотов меньше ожидаемого ($(up_slots) вместо $((replicas + step)))" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. снять одну старую реплику и дождаться, что UP-слотов снова ровно
|
||||
# столько, сколько реплик должно остаться
|
||||
docker rm -f "$container" >/dev/null
|
||||
|
||||
if ! wait_up_slots "$((replicas + step - 1))"; then
|
||||
echo " step ${step}: после снятия UP-слотов больше ожидаемого" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf ' step %s: %s обслуживает (образ %s, instance %s), старый контейнер %s (%s) снят; UP-слотов %s; 5xx накоплено %s; старт шага %s\n' \
|
||||
"$step" "$name" "${new_container_image#sha256:}" "$new_instance" \
|
||||
"${container:0:12}" "$old_instance" "$(up_slots)" "$(lb_5xx)" "$started"
|
||||
done
|
||||
|
||||
wait "$load_pid" || true
|
||||
|
||||
five_after=$(lb_5xx)
|
||||
echo
|
||||
echo "load summary (tolerant generator):"
|
||||
cat "$OUT/load.txt"
|
||||
echo
|
||||
echo "5xx от LB за время обновления (hrsp_5xx frontend): $((${five_after:-0} - ${five_before:-0}))"
|
||||
echo "restarts после: $(restarts)"
|
||||
|
||||
# 3. вернуть стенд под управление compose и убрать временные контейнеры
|
||||
echo
|
||||
echo "возврат стенда под управление compose:"
|
||||
compose up -d --no-deps api
|
||||
wait_up_slots "$replicas" || true
|
||||
|
||||
remaining=$(printf '%s\n' $(rollout_containers) | wc -l | tr -d ' ')
|
||||
for container in $(rollout_containers); do
|
||||
docker rm -f "$container" >/dev/null
|
||||
remaining=$((remaining - 1))
|
||||
|
||||
if ! wait_up_slots "$((replicas + remaining))"; then
|
||||
echo " после снятия ${container} UP-слотов больше ожидаемого" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "снято временных контейнеров наплыва: проверено"
|
||||
|
||||
echo "UP-слотов после: $(up_slots); restarts в конце: $(restarts)"
|
||||
echo "API containers после обновления:"
|
||||
docker ps --format '{{.Names}} {{.Status}}' \
|
||||
--filter "label=com.docker.compose.project=$PROJECT" \
|
||||
--filter 'label=com.docker.compose.service=api'
|
||||
} > "$OUT/rolling-update.txt" 2>&1
|
||||
|
||||
cat "$OUT/rolling-update.txt"
|
||||
printf 'rolling_update.sh: evidence in %s\n' "$OUT"
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml up -d --wait --no-deps broker
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml up -d --wait --no-deps worker
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml stop broker
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Fault-injection hook: stop exactly ONE api replica of the lab5 stand.
|
||||
#
|
||||
# TARGET_INSTANCE_ID=<hostname|container name|short id> scripts/stop-one.sh
|
||||
#
|
||||
# The task value is the instance alias the API reports in X-Instance-Id, i.e.
|
||||
# the container hostname (docker's default = short container id). Container
|
||||
# names of the api service are matched too. The container is only stopped
|
||||
# (docker stop); databases, the load balancer and volumes are left untouched,
|
||||
# and the replica stays down until it is started again explicitly, e.g.
|
||||
# docker compose --env-file .env up -d --no-deps api
|
||||
# No credentials are printed.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
PROJECT=${COMPOSE_PROJECT_NAME:-mtusi-messenger-lab6}
|
||||
|
||||
candidates=$(docker ps -q \
|
||||
--filter "label=com.docker.compose.project=${PROJECT}" \
|
||||
--filter "label=com.docker.compose.service=api")
|
||||
|
||||
if [ -z "$candidates" ]; then
|
||||
printf 'stop-one.sh: no api containers of project %s are running\n' "$PROJECT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Matches the requested alias against every reasonable identifier of a replica:
|
||||
# container hostname (= X-Instance-Id), full/short container id, full container
|
||||
# name (mtusi-messenger-lab4-api-1) and the service-local suffix (api-1).
|
||||
match_replica() {
|
||||
target=$1
|
||||
full_id=$2
|
||||
short_id=$3
|
||||
name=$4
|
||||
hostname=$5
|
||||
suffix=${name#${PROJECT}-}
|
||||
|
||||
[ "$target" = "$hostname" ] && return 0
|
||||
[ "$target" = "$full_id" ] && return 0
|
||||
[ "$target" = "$short_id" ] && return 0
|
||||
[ "$target" = "$name" ] && return 0
|
||||
[ "$target" = "$suffix" ] && return 0
|
||||
return 1
|
||||
}
|
||||
|
||||
matched=""
|
||||
matched_names=""
|
||||
for id in $candidates; do
|
||||
info=$(docker inspect --format '{{.Id}} {{.Name}} {{.Config.Hostname}}' "$id")
|
||||
full_id=$(printf '%s' "$info" | cut -d' ' -f1)
|
||||
name=$(printf '%s' "$info" | cut -d' ' -f2 | sed 's|^/||')
|
||||
hostname=$(printf '%s' "$info" | cut -d' ' -f3)
|
||||
short_id=$(printf '%s' "$full_id" | cut -c1-12)
|
||||
|
||||
if match_replica "$TARGET_INSTANCE_ID" "$full_id" "$short_id" "$name" "$hostname"; then
|
||||
matched="$matched $id"
|
||||
matched_names="$matched_names $name"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$matched" ]; then
|
||||
printf 'stop-one.sh: no api replica matches TARGET_INSTANCE_ID=%s\n' "$TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Shut down cleanly (SIGTERM) but never hang the caller for long.
|
||||
for id in $matched; do
|
||||
docker stop --time 5 "$id" >/dev/null
|
||||
done
|
||||
|
||||
printf 'stop-one.sh: stopped api replica(s):%s\n' "$matched_names"
|
||||
exit 0
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Fault-injection hook: stop the lab5 worker and leave it stopped.
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml stop worker
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
# Контроль бюджетов БД и балансировщика, перемежённый с эталоном.
|
||||
#
|
||||
# По ходу серии пропускная способность дрейфует: таблица сообщений растёт
|
||||
# (~95 тыс. строк на профиль), а вместе с ней и стоимость записи. Поэтому
|
||||
# сравнивать профиль с бюджетом БД 1.00 CPU с эталоном, снятым четверть часа
|
||||
# назад, нельзя — разница бюджетов утонет в дрейфе. Здесь эталон (2 реплики,
|
||||
# PostgreSQL 0.50 CPU, LB 0.25 CPU) повторяется дважды, а каждая контролируемая
|
||||
# ручка меняется ровно в одном профиле рядом с эталоном:
|
||||
#
|
||||
# ctl1base -> ctl2pg (БД 1.00) -> ctl3base -> ctl4lb (LB 1.00)
|
||||
#
|
||||
# Пара ctl1base/ctl3base даёт масштаб дрейфа за два профиля.
|
||||
#
|
||||
# scripts/track1_controls.sh
|
||||
# rm evidence/track1/{load,stats,profile}-ctl*.{json,csv} # перемерить
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
SCALING=scripts/track1_scaling.sh
|
||||
OUT=${OUT:-evidence/track1}
|
||||
export OUT
|
||||
|
||||
export CLIENT=${CLIENT:-vm}
|
||||
export TOTAL_CPU=1.0 TOTAL_MEM_MB=768 DURATION=60 CONCURRENCY=8 WARMUP=15
|
||||
export POSTGRES_CPU_LIMIT=0.50 POSTGRES_MEM_LIMIT=384M POSTGRES_MAX_CONNS=10 LB_CPU_LIMIT=0.25
|
||||
|
||||
run() {
|
||||
label=$1
|
||||
shift
|
||||
|
||||
if [ -f "$OUT/profile-$label.json" ] && [ -f "$OUT/load-$label.json" ]; then
|
||||
printf 'track1_controls.sh: профиль %s пропущен — артефакты уже есть\n' "$label"
|
||||
|
||||
return 0
|
||||
fi
|
||||
|
||||
LABEL="$label" env "$@" "$SCALING"
|
||||
}
|
||||
|
||||
run ctl1base REPLICAS=2
|
||||
run ctl2pg REPLICAS=2 POSTGRES_CPU_LIMIT=1.00
|
||||
run ctl3base REPLICAS=2
|
||||
run ctl4lb REPLICAS=2 LB_CPU_LIMIT=1.00
|
||||
|
||||
printf 'track1_controls.sh: готово, сводка — python3 scripts/track1_report.py\n'
|
||||
Executable
+209
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Сводка трека 1: артефакты `evidence/track1/*` -> таблица и графики.
|
||||
|
||||
Читает `load-<label>.json` (tests/load.py) и `stats-<label>.csv` (docker stats)
|
||||
и печатает метрики профиля: успешный RPS, p50/p95/p99 успешных запросов, доля
|
||||
ошибок, суммарный CPU API, максимум памяти API, CPU PostgreSQL и LB.
|
||||
|
||||
.venv/bin/python scripts/track1_report.py
|
||||
|
||||
Графики (PNG) требуют matplotlib; без него печатается только таблица.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_DIR = ROOT / 'evidence/track1'
|
||||
# Стенд трека 1 — только контейнеры своего проекта: параллельно поднятый стенд
|
||||
# другой лаборатории (тот же Docker-host) иначе попадал бы в те же колонки
|
||||
# (mtusi-messenger-lab2-postgres-1 -> postgres) и искажал бюджет и CPU.
|
||||
DEFAULT_PREFIX = 'mtusi-messenger-lab3-'
|
||||
MEMORY_UNITS = {'B': 1 / 1024 / 1024, 'KiB': 1 / 1024, 'MiB': 1, 'GiB': 1024}
|
||||
|
||||
|
||||
def parse_cpu(value):
|
||||
return float(value.rstrip('%')) if value else 0.0
|
||||
|
||||
|
||||
def parse_memory(value):
|
||||
"""'123.4MiB / 256MiB' -> 123.4 MiB."""
|
||||
match = re.match(r'([\d.]+)\s*([KMG]?i?B)', value.strip())
|
||||
|
||||
if not match:
|
||||
return 0.0
|
||||
|
||||
return float(match.group(1)) * MEMORY_UNITS.get(match.group(2), 1)
|
||||
|
||||
|
||||
def service_of(container):
|
||||
"""mtusi-messenger-lab3-api-12 -> api"""
|
||||
return container.rsplit('-', 1)[0].split('-')[-1] if '-' in container else container
|
||||
|
||||
|
||||
def read_stats(path, prefix=''):
|
||||
"""Профиль -> агрегаты по сервисам.
|
||||
|
||||
Внутри одного timestamp значения всех контейнеров сервиса складываются: две-три
|
||||
реплики — это общий ресурс профиля, а не выборка. Затем CPU усредняется по
|
||||
timestamp'ам, а память берётся пиковой (сумма по репликам).
|
||||
"""
|
||||
samples = defaultdict(lambda: defaultdict(lambda: {'cpu': 0.0, 'mem': 0.0}))
|
||||
|
||||
with path.open() as handle:
|
||||
for row in csv.DictReader(handle):
|
||||
if prefix and not row['container'].startswith(prefix):
|
||||
continue
|
||||
|
||||
service = service_of(row['container'])
|
||||
bucket = samples[service][row['timestamp']]
|
||||
bucket['cpu'] += parse_cpu(row['cpu_percent'])
|
||||
bucket['mem'] += parse_memory(row['mem_usage'])
|
||||
|
||||
cpu = {service: [values['cpu'] for values in by_timestamp.values()] for service, by_timestamp in samples.items()}
|
||||
memory = {service: max(values['mem'] for values in by_timestamp.values()) for service, by_timestamp in samples.items()}
|
||||
|
||||
return cpu, memory
|
||||
|
||||
|
||||
def aggregate(label, directory, prefix=''):
|
||||
load_path = directory / f'load-{label}.json'
|
||||
stats_path = directory / f'stats-{label}.csv'
|
||||
profile_path = directory / f'profile-{label}.json'
|
||||
|
||||
if not load_path.is_file() or not stats_path.is_file():
|
||||
return None
|
||||
|
||||
report = json.loads(load_path.read_text())
|
||||
profile = json.loads(profile_path.read_text()) if profile_path.is_file() else {}
|
||||
cpu, memory = read_stats(stats_path, prefix)
|
||||
|
||||
api_cpu = cpu.get('api', [])
|
||||
api_memory = memory.get('api', 0.0)
|
||||
|
||||
def average(values):
|
||||
return round(sum(values) / len(values), 2) if values else None
|
||||
|
||||
sampled = max((len(values) for values in cpu.values()), default=0)
|
||||
|
||||
return {
|
||||
'label': label,
|
||||
'replicas': profile.get('replicas', 0),
|
||||
'total_cpu': profile.get('total_cpu'),
|
||||
'postgres_budget': '{}/{}'.format(
|
||||
profile.get('postgres_cpu_limit', '?'), profile.get('postgres_mem_limit', '?')
|
||||
),
|
||||
'postgres_max_conns': profile.get('postgres_max_conns', '?'),
|
||||
'lb_cpu_limit': profile.get('lb_cpu_limit', '?'),
|
||||
'cpu_per_replica': round(profile['total_cpu'] / max(1, profile['replicas']), 2)
|
||||
if profile.get('total_cpu') else None,
|
||||
'successful_rps': report['successful_rps'],
|
||||
'p50_ms': report['successful_latency_ms']['p50'],
|
||||
'p95_ms': report['successful_latency_ms']['p95'],
|
||||
'p99_ms': report['successful_latency_ms']['p99'],
|
||||
'errors': report['failed_requests'],
|
||||
'error_ratio': report['error_ratio'],
|
||||
'api_cpu_sum': average(api_cpu),
|
||||
'api_cpu_per_replica': round(average(api_cpu) / max(1, profile.get('replicas') or 1), 2)
|
||||
if api_cpu else None,
|
||||
'api_memory_max_sum_mib': round(api_memory, 1) if api_memory else None,
|
||||
'postgres_cpu': average(cpu.get('postgres', [])),
|
||||
'lb_cpu': average(cpu.get('lb', [])),
|
||||
'stats_samples': sampled,
|
||||
'load_seconds': report['elapsed_seconds'],
|
||||
}
|
||||
|
||||
|
||||
def markdown(rows):
|
||||
header = (
|
||||
'| профиль | реплик | бюджет CPU API | CPU/реплика | бюджет PG CPU/RAM | пул | LB CPU (лимит) | успешный RPS | '
|
||||
'p50 мс | p95 мс | p99 мс | ошибки | API CPU (сумма) | API RAM max (сумма, MiB) | PG CPU | LB CPU |\n'
|
||||
'| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |\n'
|
||||
)
|
||||
|
||||
lines = [
|
||||
'| {label} | {replicas} | {total_cpu} | {cpu_per_replica} | {postgres_budget} | {postgres_max_conns} | '
|
||||
'{lb_cpu_limit} | {successful_rps} | {p50_ms} | {p95_ms} | {p99_ms} | '
|
||||
'{errors} | {api_cpu_sum} | {api_memory_max_sum_mib} | {postgres_cpu} | {lb_cpu} |'.format(**row)
|
||||
for row in rows
|
||||
]
|
||||
|
||||
return header + '\n'.join(lines) + '\n'
|
||||
|
||||
|
||||
def plot(rows, directory):
|
||||
try:
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
except ImportError:
|
||||
print('matplotlib недоступен: графики не построены (pip install matplotlib)')
|
||||
return
|
||||
|
||||
series = {
|
||||
'fixed-budget': [row for row in rows if row['label'].startswith('r') and row['total_cpu']],
|
||||
'growth': [row for row in rows if row['label'].startswith('g') and row['total_cpu']],
|
||||
}
|
||||
|
||||
for name, points in series.items():
|
||||
if len(points) < 2:
|
||||
continue
|
||||
|
||||
axis = 'replicas' if name == 'fixed-budget' else 'total_cpu'
|
||||
points = sorted(points, key=lambda row: row[axis])
|
||||
ticks = [str(row[axis]) for row in points]
|
||||
|
||||
figure, (left, right) = plt.subplots(1, 2, figsize=(10, 4))
|
||||
|
||||
left.plot(ticks, [row['successful_rps'] for row in points], marker='o')
|
||||
left.set_xlabel('API реплик' if axis == 'replicas' else 'суммарный бюджет CPU')
|
||||
left.set_ylabel('успешный RPS')
|
||||
left.grid(True)
|
||||
left.set_title('Пропускная способность')
|
||||
|
||||
right.plot(ticks, [row['p95_ms'] for row in points], marker='o', color='tab:red')
|
||||
right.set_xlabel('API реплик' if axis == 'replicas' else 'суммарный бюджет CPU')
|
||||
right.set_ylabel('p95 успешных, мс')
|
||||
right.grid(True)
|
||||
right.set_title('Задержка p95')
|
||||
|
||||
figure.suptitle(('Фиксированный бюджет' if name == 'fixed-budget' else 'Рост ресурсов') + ' (трек 1)')
|
||||
figure.tight_layout()
|
||||
target = directory / ('scaling-' + name + '.png')
|
||||
figure.savefig(target, dpi=120)
|
||||
print('график:', target)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Сводка трека 1 по артефактам стенда')
|
||||
parser.add_argument('--dir', type=Path, default=DEFAULT_DIR)
|
||||
parser.add_argument('--prefix', default=DEFAULT_PREFIX, help='префикс контейнеров своего стенда')
|
||||
args = parser.parse_args()
|
||||
|
||||
labels = sorted(
|
||||
path.stem.removeprefix('load-') for path in args.dir.glob('load-*.json')
|
||||
)
|
||||
|
||||
rows = []
|
||||
for label in labels:
|
||||
row = aggregate(label, args.dir, args.prefix)
|
||||
if row is None:
|
||||
print('внимание: профиль ' + label + ' пропущен — нет load-*.json или stats-*.csv')
|
||||
continue
|
||||
rows.append(row)
|
||||
|
||||
if not rows:
|
||||
raise SystemExit('нет артефактов в ' + str(args.dir))
|
||||
|
||||
table = markdown(rows)
|
||||
print(table)
|
||||
(args.dir / 'summary.md').write_text('# Трек 1: цена масштабирования\n\n' + table)
|
||||
|
||||
plot(rows, args.dir)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+319
@@ -0,0 +1,319 @@
|
||||
#!/bin/sh
|
||||
# Track 1: the price of scaling. Runs one and the same closed-loop write profile
|
||||
# against 1/2/4 API replicas while the TOTAL API budget stays fixed, and records
|
||||
# raw metrics. The stand has to be built already (make up).
|
||||
#
|
||||
# scripts/track1_scaling.sh
|
||||
# REPLICAS="2 4" DURATION=30 CONCURRENCY=8 scripts/track1_scaling.sh
|
||||
#
|
||||
# Artifacts: evidence/track1/{load,stats}-r<N>.json|csv plus summary.txt
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
COMPOSE_BIN=${COMPOSE_BIN:-docker compose}
|
||||
PYTHON=${PYTHON:-python3}
|
||||
REPLICAS=${REPLICAS:-"1 2 4"}
|
||||
TOTAL_CPU=${TOTAL_CPU:-2.0}
|
||||
TOTAL_MEM_MB=${TOTAL_MEM_MB:-1024}
|
||||
DURATION=${DURATION:-60}
|
||||
CONCURRENCY=${CONCURRENCY:-16}
|
||||
WARMUP=${WARMUP:-15}
|
||||
BASE_URL=${BASE_URL:-http://localhost:8080}
|
||||
LABEL=${LABEL:-}
|
||||
OUT=${OUT:-evidence/track1}
|
||||
|
||||
# Бюджеты общих хранилищ фиксируются в профиле вместе с бюджетом API: без них
|
||||
# серию нельзя воспроизвести по артефактам.
|
||||
PG_CPU=${POSTGRES_CPU_LIMIT:-0.50}
|
||||
PG_MEM=${POSTGRES_MEM_LIMIT:-384M}
|
||||
PG_CONNS=${POSTGRES_MAX_CONNS:-10}
|
||||
LB_CPU=${LB_CPU_LIMIT:-0.25}
|
||||
# Где работает генератор нагрузки: `host` — на хосте через опубликованный порт,
|
||||
# `vm` — в контейнере внутри VM, где балансировщик доступен по docker-сети.
|
||||
# Вариант `host` упирается в проброс порта: под шквалом новых соединений
|
||||
# (клиент ходит без keep-alive) он отказывает, и отказы попадают в метрику
|
||||
# ошибок (см. `scripts/path_overhead_check.sh`).
|
||||
CLIENT=${CLIENT:-host}
|
||||
CLIENT_IMAGE=${CLIENT_IMAGE:-python:3.12-alpine}
|
||||
export POSTGRES_CPU_LIMIT="$PG_CPU" POSTGRES_MEM_LIMIT="$PG_MEM" POSTGRES_MAX_CONNS="$PG_CONNS"
|
||||
export LB_CPU_LIMIT="$LB_CPU"
|
||||
|
||||
# Бюджеты хранилищ compose применяет при создании контейнера. Это значения, к
|
||||
# которым стенд возвращается после контрольного профиля.
|
||||
PG_DEFAULT_CPU=${PG_DEFAULT_CPU:-0.50}
|
||||
PG_DEFAULT_MEM=${PG_DEFAULT_MEM:-384M}
|
||||
LB_DEFAULT_CPU=${LB_DEFAULT_CPU:-0.25}
|
||||
|
||||
# Приводим бюджет к тому виду, в котором он снимается с контейнера
|
||||
# (`docker inspect`): 1.0 -> 1.00, 1024M -> 1024M. Иначе проверка «применился ли
|
||||
# бюджет» сравнивала бы разные записи одного и того же значения.
|
||||
normalize_cpu() { awk -v value="$1" 'BEGIN{printf "%.2f", value}'; }
|
||||
|
||||
normalize_mem() {
|
||||
case $1 in
|
||||
*[Gg]) awk -v value="$1" 'BEGIN{printf "%.0fM", value * 1024}' ;;
|
||||
*[Mm]) awk -v value="$1" 'BEGIN{printf "%.0fM", value}' ;;
|
||||
*) printf '%s\n' "$1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
PG_CPU=$(normalize_cpu "$PG_CPU")
|
||||
PG_MEM=$(normalize_mem "$PG_MEM")
|
||||
PG_DEFAULT_CPU=$(normalize_cpu "$PG_DEFAULT_CPU")
|
||||
PG_DEFAULT_MEM=$(normalize_mem "$PG_DEFAULT_MEM")
|
||||
LB_CPU=$(normalize_cpu "$LB_CPU")
|
||||
LB_DEFAULT_CPU=$(normalize_cpu "$LB_DEFAULT_CPU")
|
||||
export POSTGRES_CPU_LIMIT="$PG_CPU" POSTGRES_MEM_LIMIT="$PG_MEM" LB_CPU_LIMIT="$LB_CPU"
|
||||
|
||||
# The author's shell exports HTTP(S)_PROXY, which breaks localhost clients.
|
||||
NO_PROXY_ENV="env -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY -u http_proxy -u https_proxy -u all_proxy"
|
||||
NO_PROXY_ENV="$NO_PROXY_ENV NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1"
|
||||
|
||||
mkdir -p "$OUT"
|
||||
|
||||
compose() {
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN --env-file .env -f compose.yaml "$@"
|
||||
}
|
||||
|
||||
wait_ready() {
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 90 ]; do
|
||||
if curl -fsS --noproxy '*' -o /dev/null "$BASE_URL/health/ready"; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'track1_scaling.sh: %s/health/ready did not become ready\n' "$BASE_URL" >&2
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
per_replica_cpu() {
|
||||
awk "BEGIN{printf \"%.2f\", $TOTAL_CPU/$1}"
|
||||
}
|
||||
|
||||
per_replica_mem() {
|
||||
awk "BEGIN{printf \"%.0fM\", $TOTAL_MEM_MB/$1}"
|
||||
}
|
||||
|
||||
container_of() {
|
||||
compose ps -q "$1"
|
||||
}
|
||||
|
||||
# Сеть стенда: клиент внутри VM обращается к балансировщику по ней, без проброса
|
||||
# порта и без сетевого стека хоста.
|
||||
stand_network() {
|
||||
docker inspect "$(container_of api | head -1)" \
|
||||
--format '{{range $name, $network := .NetworkSettings.Networks}}{{$name}}{{end}}'
|
||||
}
|
||||
|
||||
# $1 — длительность, $2 — путь к JSON-метрикам (необязательно).
|
||||
load_client() {
|
||||
if [ "$CLIENT" = vm ]; then
|
||||
network=$(stand_network)
|
||||
|
||||
if [ -n "$2" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" -v "$ROOT_DIR/$OUT:/out" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$1" --concurrency "$CONCURRENCY" --output "/out/$(basename "$2")"
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
docker run --rm -i --network "$network" -v "$ROOT_DIR:/repo:ro" \
|
||||
-e NO_PROXY='lb,localhost,127.0.0.1' -e no_proxy='lb,localhost,127.0.0.1' \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url http://lb \
|
||||
--duration "$1" --concurrency "$CONCURRENCY"
|
||||
fi
|
||||
|
||||
return
|
||||
fi
|
||||
|
||||
if [ -n "$2" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" \
|
||||
--duration "$1" --concurrency "$CONCURRENCY" --output "$2"
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" \
|
||||
--duration "$1" --concurrency "$CONCURRENCY"
|
||||
fi
|
||||
}
|
||||
|
||||
# Фактический бюджет контейнера, снятый с него самого: в профиль и в сводку
|
||||
# попадает измерение, а не переменная, с которой скрипт был запущен.
|
||||
container_cpu() {
|
||||
nano=$(docker inspect "$(container_of "$1")" --format '{{.HostConfig.NanoCpus}}')
|
||||
awk -v nano="$nano" 'BEGIN{printf "%.2f", nano/1000000000}'
|
||||
}
|
||||
|
||||
container_mem() {
|
||||
bytes=$(docker inspect "$(container_of "$1")" --format '{{.HostConfig.Memory}}')
|
||||
awk -v bytes="$bytes" 'BEGIN{printf "%.0fM", bytes/1024/1024}'
|
||||
}
|
||||
|
||||
wait_postgres_ready() {
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 90 ]; do
|
||||
if compose exec -T postgres pg_isready -U "${POSTGRES_USER:-messenger}" \
|
||||
-d "${POSTGRES_DB:-messenger}" >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
attempt=$((attempt + 1))
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'track1_scaling.sh: postgres did not become ready\n' >&2
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
# Лимиты общих хранилищ задаются при создании контейнера, поэтому одного
|
||||
# `up -d --no-deps api` для них мало: PostgreSQL и балансировщик приходится
|
||||
# пересоздавать, когда бюджет профиля отличается от действующего. Без этого
|
||||
# профиль записывал бы намерение, а измерение шло бы на прежнем лимите — именно
|
||||
# так контроль удвоения CPU БД перестал быть контролем.
|
||||
apply_store_limits() {
|
||||
applied_pg_cpu=$(container_cpu postgres)
|
||||
applied_pg_mem=$(container_mem postgres)
|
||||
applied_lb_cpu=$(container_cpu lb)
|
||||
|
||||
if [ "$applied_pg_cpu" != "$PG_CPU" ] || [ "$applied_pg_mem" != "$PG_MEM" ]; then
|
||||
printf '=== PostgreSQL: бюджет %s/%s -> %s/%s, пересоздаю контейнер ===\n' \
|
||||
"$applied_pg_cpu" "$applied_pg_mem" "$PG_CPU" "$PG_MEM" | tee -a "$SUMMARY"
|
||||
|
||||
POSTGRES_CPU_LIMIT="$PG_CPU" POSTGRES_MEM_LIMIT="$PG_MEM" \
|
||||
compose up -d --no-deps postgres >/dev/null
|
||||
|
||||
wait_postgres_ready
|
||||
fi
|
||||
|
||||
if [ "$applied_lb_cpu" != "$LB_CPU" ]; then
|
||||
printf '=== LB: бюджет CPU %s -> %s, пересоздаю контейнер ===\n' \
|
||||
"$applied_lb_cpu" "$LB_CPU" | tee -a "$SUMMARY"
|
||||
|
||||
LB_CPU_LIMIT="$LB_CPU" compose up -d --no-deps lb >/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
SUMMARY="$OUT/summary.txt"
|
||||
|
||||
if [ ! -f "$SUMMARY" ]; then
|
||||
{
|
||||
echo "# Track 1: the price of scaling"
|
||||
echo "# generated: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
|
||||
echo "# host: $(uname -sm)"
|
||||
echo "# cpu: $(sysctl -n machdep.cpu.brand_string 2>/dev/null || printf unknown)"
|
||||
echo "# ram bytes: $(sysctl -n hw.memsize 2>/dev/null || printf unknown)"
|
||||
echo "# load: tests/load.py closed loop; postgres/lb budgets are recreated and verified per profile"
|
||||
echo "# each profile line below records the budget it was run with"
|
||||
docker version --format 'docker engine {{.Server.Version}}'
|
||||
# shellcheck disable=SC2086
|
||||
$COMPOSE_BIN version
|
||||
echo
|
||||
} > "$SUMMARY"
|
||||
fi
|
||||
|
||||
{
|
||||
echo "=== invocation $(date -u +%Y-%m-%dT%H:%M:%SZ): REPLICAS=\"$REPLICAS\" TOTAL_CPU=$TOTAL_CPU TOTAL_MEM_MB=$TOTAL_MEM_MB DURATION=$DURATION CONCURRENCY=$CONCURRENCY WARMUP=$WARMUP ==="
|
||||
echo
|
||||
} >> "$SUMMARY"
|
||||
|
||||
for replicas in $REPLICAS; do
|
||||
cpu=$(per_replica_cpu "$replicas")
|
||||
mem=$(per_replica_mem "$replicas")
|
||||
label=${LABEL:-r$replicas}
|
||||
|
||||
printf '=== profile label=%s replicas=%s cpu=%s mem=%s postgres=%s/%s lb_cpu=%s max_conns=%s client=%s ===\n' \
|
||||
"$label" "$replicas" "$cpu" "$mem" "$PG_CPU" "$PG_MEM" "$LB_CPU" "$PG_CONNS" "$CLIENT" | tee -a "$SUMMARY"
|
||||
|
||||
apply_store_limits
|
||||
|
||||
API_REPLICAS="$replicas" API_CPU_LIMIT="$cpu" API_MEM_LIMIT="$mem" compose up -d --no-deps api
|
||||
wait_ready
|
||||
|
||||
# Warm up caches, connection pools and the JIT-free query plans; the warmup
|
||||
# data stays in the table, so every profile grows the same history shape.
|
||||
load_client "$WARMUP" "" >/dev/null
|
||||
|
||||
STATS="$OUT/stats-$label.csv"
|
||||
printf 'timestamp,container,cpu_percent,mem_usage\n' > "$STATS"
|
||||
|
||||
# В профиль попадают фактические лимиты, снятые с контейнеров: иначе профиль
|
||||
# описывал бы намерение, а не то, на чём действительно шло измерение.
|
||||
pg_cpu_applied=$(container_cpu postgres)
|
||||
pg_mem_applied=$(container_mem postgres)
|
||||
lb_cpu_applied=$(container_cpu lb)
|
||||
|
||||
if [ "$pg_cpu_applied" != "$PG_CPU" ] || [ "$pg_mem_applied" != "$PG_MEM" ] \
|
||||
|| [ "$lb_cpu_applied" != "$LB_CPU" ]; then
|
||||
printf 'track1_scaling.sh: лимиты не применились: postgres просили %s/%s, получили %s/%s; lb просили %s, получили %s\n' \
|
||||
"$PG_CPU" "$PG_MEM" "$pg_cpu_applied" "$pg_mem_applied" "$LB_CPU" "$lb_cpu_applied" >&2
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '=== applied label=%s replicas=%s postgres=%s/%s lb_cpu=%s (снято с контейнеров)\n' \
|
||||
"$label" "$replicas" "$pg_cpu_applied" "$pg_mem_applied" "$lb_cpu_applied" | tee -a "$SUMMARY"
|
||||
|
||||
PROFILE="$OUT/profile-$label.json"
|
||||
printf '{"label":"%s","replicas":%s,"total_cpu":%s,"total_mem_mb":%s,"duration":%s,"concurrency":%s,"warmup":%s,"postgres_cpu_limit":"%s","postgres_mem_limit":"%s","postgres_max_conns":%s,"lb_cpu_limit":"%s","client":"%s"}\n' \
|
||||
"$label" "$replicas" "$TOTAL_CPU" "$TOTAL_MEM_MB" "$DURATION" "$CONCURRENCY" "$WARMUP" \
|
||||
"$pg_cpu_applied" "$pg_mem_applied" "$PG_CONNS" "$lb_cpu_applied" "$CLIENT" > "$PROFILE"
|
||||
|
||||
(
|
||||
while :; do
|
||||
docker stats --no-stream \
|
||||
--format '{{.Name}},{{.CPUPerc}},{{.MemUsage}}' \
|
||||
| sed "s|^|$(date -u +%Y-%m-%dT%H:%M:%SZ),|" >> "$STATS"
|
||||
sleep 1
|
||||
done
|
||||
) &
|
||||
|
||||
sampler=$!
|
||||
trap 'kill "$sampler" 2>/dev/null || true' EXIT INT TERM
|
||||
|
||||
# shellcheck disable=SC2086
|
||||
load_client "$DURATION" "$OUT/load-$label.json" | tee -a "$SUMMARY"
|
||||
|
||||
kill "$sampler" 2>/dev/null || true
|
||||
wait "$sampler" 2>/dev/null || true
|
||||
trap - EXIT INT TERM
|
||||
|
||||
# Shared-dependency view right after the run: connections, pool pressure and
|
||||
# how much history the profile wrote into.
|
||||
compose exec -T postgres psql -U "${POSTGRES_USER:-messenger}" -d "${POSTGRES_DB:-messenger}" -Atc \
|
||||
"SELECT 'postgres_connections=' || count(*) FROM pg_stat_activity;
|
||||
SELECT 'postgres_max_connections=' || current_setting('max_connections');
|
||||
SELECT 'messages_rows=' || count(*) FROM messages;
|
||||
SELECT 'idempotency_rows=' || count(*) FROM message_idempotency;" | tee -a "$SUMMARY"
|
||||
|
||||
printf '\n' >> "$SUMMARY"
|
||||
done
|
||||
|
||||
# Контрольные профили меняют бюджет общих хранилищ; после серии стенд
|
||||
# возвращается к бюджетам compose, чтобы следующий сценарий шёл на них.
|
||||
if [ "$PG_CPU" != "$PG_DEFAULT_CPU" ] || [ "$PG_MEM" != "$PG_DEFAULT_MEM" ]; then
|
||||
printf '=== возвращаю PostgreSQL к бюджету %s/%s ===\n' \
|
||||
"$PG_DEFAULT_CPU" "$PG_DEFAULT_MEM" | tee -a "$SUMMARY"
|
||||
|
||||
POSTGRES_CPU_LIMIT="$PG_DEFAULT_CPU" POSTGRES_MEM_LIMIT="$PG_DEFAULT_MEM" \
|
||||
compose up -d --no-deps postgres >/dev/null
|
||||
|
||||
wait_postgres_ready
|
||||
fi
|
||||
|
||||
if [ "$LB_CPU" != "$LB_DEFAULT_CPU" ]; then
|
||||
printf '=== возвращаю LB к бюджету CPU %s ===\n' "$LB_DEFAULT_CPU" | tee -a "$SUMMARY"
|
||||
|
||||
LB_CPU_LIMIT="$LB_DEFAULT_CPU" compose up -d --no-deps lb >/dev/null
|
||||
fi
|
||||
|
||||
printf 'track1_scaling.sh: artifacts in %s\n' "$OUT"
|
||||
Executable
+69
@@ -0,0 +1,69 @@
|
||||
#!/bin/sh
|
||||
# Трек 1: вся серия профилей одной командой — так её и воспроизводят.
|
||||
#
|
||||
# scripts/track1_series.sh
|
||||
#
|
||||
# Серия 1: фиксированный суммарный бюджет API (1.0 CPU / 768 MiB) на 1, 2 и 4
|
||||
# репликах. Серия 2: рост бюджета API при 2 репликах (0.5, 1.0, 1.5 CPU).
|
||||
# Контрольные профили меняют одну ручку за раз: пул соединений (10 -> 5),
|
||||
# бюджет CPU PostgreSQL (0.50 -> 1.00) и бюджет CPU балансировщика (0.25 -> 1.00).
|
||||
#
|
||||
# Бюджеты общих хранилищ применяются к работающим контейнерам и проверяются по
|
||||
# `docker inspect` (см. scripts/track1_scaling.sh). Стенд должен быть поднят
|
||||
# (`make up`), артефакты ложатся в evidence/track1/.
|
||||
set -eu
|
||||
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
|
||||
SCALING=scripts/track1_scaling.sh
|
||||
|
||||
# Генератор работает внутри VM: проброс порта хоста под шквалом новых соединений
|
||||
# отказывает (см. evidence/path-overhead/), и отказы клиента маскировали бы
|
||||
# поведение стенда. Вариант CLIENT=host оставлен для сравнения путей.
|
||||
export CLIENT=${CLIENT:-vm}
|
||||
|
||||
# Общие параметры профиля: closed loop, 60 с нагрузки, 15 с прогрева, 8 клиентов.
|
||||
export TOTAL_CPU=1.0 TOTAL_MEM_MB=768 DURATION=60 CONCURRENCY=8 WARMUP=15
|
||||
|
||||
OUT=${OUT:-evidence/track1}
|
||||
export OUT
|
||||
|
||||
# Профиль с уже снятыми артефактами пропускается: серию можно продолжить после
|
||||
# обрыва (например, если Docker-host отвлёкся), не перемеряя начало.
|
||||
run_profile() {
|
||||
label=$1
|
||||
shift
|
||||
|
||||
if [ -f "$OUT/profile-$label.json" ] && [ -f "$OUT/load-$label.json" ]; then
|
||||
printf 'track1_series.sh: профиль %s пропущен — артефакты уже есть (удалите их, чтобы перемерить)\n' "$label"
|
||||
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Бюджеты профиля передаются именно как переменные окружения: `"$@"` с
|
||||
# присваиваниями превратил бы их в аргументы и профиль пошёл бы на дефолтах.
|
||||
LABEL="$label" env "$@" "$SCALING"
|
||||
}
|
||||
|
||||
# Серия 1: цена реплик при неизменном суммарном бюджете API.
|
||||
run_profile r1 REPLICAS=1
|
||||
run_profile r2 REPLICAS=2
|
||||
run_profile r4 REPLICAS=4
|
||||
|
||||
# Серия 2: рост бюджета API при двух репликах.
|
||||
run_profile g05 REPLICAS=2 TOTAL_CPU=0.5
|
||||
run_profile g10 REPLICAS=2 TOTAL_CPU=1.0
|
||||
run_profile g15 REPLICAS=2 TOTAL_CPU=1.5
|
||||
|
||||
# Контроль: пул соединений одной реплики 10 -> 5 при четырёх репликах.
|
||||
run_profile pool10 REPLICAS=4 POSTGRES_MAX_CONNS=10
|
||||
run_profile pool5 REPLICAS=4 POSTGRES_MAX_CONNS=5
|
||||
|
||||
# Контроль: удвоенный бюджет CPU PostgreSQL (1.00 вместо 0.50) при двух репликах.
|
||||
run_profile db1cpu REPLICAS=2 POSTGRES_CPU_LIMIT=1.00 POSTGRES_MEM_LIMIT=384M
|
||||
|
||||
# Контроль: четырехкратный бюджет CPU балансировщика (1.00 вместо 0.25).
|
||||
run_profile lb1cpu REPLICAS=2 LB_CPU_LIMIT=1.00
|
||||
|
||||
printf 'track1_series.sh: серия завершена, сводка — python3 scripts/track1_report.py\n'
|
||||
Reference in New Issue
Block a user