lab7: безопасность, mTLS, OpenBao и PKI lifecycle
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:-7} (operator TLS)"
|
||||
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
+38
@@ -0,0 +1,38 @@
|
||||
#!/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,}'),
|
||||
}
|
||||
|
||||
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()
|
||||
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
+151
@@ -0,0 +1,151 @@
|
||||
#!/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 https://localhost:8443
|
||||
"""
|
||||
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'))
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
|
||||
from client import Client # noqa: E402
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
from tests_helpers import compose # 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 = compose('ps', '-q', service).stdout.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=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
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, args.ca_file or CA_FILE, 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, 202, 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
+185
@@ -0,0 +1,185 @@
|
||||
#!/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 https://localhost:8443
|
||||
"""
|
||||
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
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
from tests_helpers import compose # noqa: E402
|
||||
|
||||
OUTPUT = ROOT / 'evidence/lab4/track1'
|
||||
|
||||
|
||||
def containers(service: str) -> list[str]:
|
||||
ids = compose('ps', '-q', service).stdout.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, 202, actor=actor, raw=content,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment',
|
||||
)
|
||||
|
||||
|
||||
def presign_upload(client: Client, actor: dict, chat: dict, content: bytes, ca_file=CA_FILE) -> None:
|
||||
prepared = presign(client, actor, chat, content)
|
||||
status = put(prepared['upload_url'], content, ca_file=ca_file)
|
||||
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=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--iterations', type=int, default=5)
|
||||
args = parser.parse_args()
|
||||
|
||||
client = Client(args.base_url, args.ca_file or CA_FILE, 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:
|
||||
if flow == 'presign':
|
||||
operation(client, alice, chat, content, ca_file=args.ca_file or CA_FILE)
|
||||
else:
|
||||
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
+167
@@ -0,0 +1,167 @@
|
||||
#!/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
|
||||
from lab7_http import BASE_URL, CA_FILE # 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=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
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, args.ca_file or CA_FILE)
|
||||
|
||||
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
+73
@@ -0,0 +1,73 @@
|
||||
#!/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
|
||||
|
||||
from lab7_http import open_url
|
||||
|
||||
|
||||
# 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'
|
||||
|
||||
|
||||
def get(url):
|
||||
with open_url(url, timeout=5, operator=True) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description='Poll Prometheus alerts')
|
||||
parser.add_argument('--prometheus', default='https://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,97 @@
|
||||
#!/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
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def query(expr):
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def alerts():
|
||||
with open_url('https://localhost:9090/api/v1/alerts', timeout=10, operator=True) 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 Environment().compose(*args, 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', BASE_URL,
|
||||
'--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','collector-tls','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','collector-tls').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
+186
@@ -0,0 +1,186 @@
|
||||
#!/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'))
|
||||
from lab7_http import BASE_URL, CA_FILE # noqa: E402
|
||||
|
||||
|
||||
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=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
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, args.ca_file or CA_FILE, 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, args.ca_file or CA_FILE, 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, args.ca_file or CA_FILE, 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,127 @@
|
||||
#!/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
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) 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 = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) 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 Environment().compose(*args, check=check)
|
||||
|
||||
|
||||
def cgroup_stats():
|
||||
ids = compose('ps', '-q', 'api', 'otel-collector').stdout.split()
|
||||
if not ids:
|
||||
return []
|
||||
output = subprocess.run(['docker','stats','--no-stream','--format','{{.Name}} {{.MemUsage}} {{.MemPerc}}', *ids],
|
||||
capture_output=True, text=True, check=True).stdout
|
||||
return output.splitlines()
|
||||
|
||||
|
||||
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', BASE_URL,
|
||||
'--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-tls','tempo-tls','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','loki-tls','tempo-tls')
|
||||
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','loki-tls','tempo-tls')
|
||||
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
+93
@@ -0,0 +1,93 @@
|
||||
#!/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
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL
|
||||
|
||||
# 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):
|
||||
return Environment().compose(*args, 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=BASE_URL)
|
||||
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
+394
@@ -0,0 +1,394 @@
|
||||
#!/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
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
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: {}
|
||||
|
||||
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 open_url(url, timeout=timeout, operator=True) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
return http_json(url).get('data', {}).get('result', [])
|
||||
|
||||
|
||||
def alerts():
|
||||
return http_json('https://localhost:9090/api/v1/alerts').get('data', {}).get('alerts', [])
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
result = Environment().compose(*args, 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 open_url(BASE_URL + '/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', BASE_URL, '--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,111 @@
|
||||
#!/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
|
||||
|
||||
from lab7_environment import Environment
|
||||
from lab7_http import BASE_URL, open_url
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def prom(expr):
|
||||
url = 'https://localhost:9090/api/v1/query?' + urllib.parse.urlencode({'query': expr})
|
||||
with open_url(url, timeout=10, operator=True) as response:
|
||||
result = json.loads(response.read()).get('data', {}).get('result', [])
|
||||
return result[0]['value'][1] if result else 'MISSING'
|
||||
|
||||
|
||||
def alerts():
|
||||
with open_url('https://localhost:9090/api/v1/alerts', timeout=10, operator=True) 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 Environment().compose(*args, 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 open_url('https://localhost:9090/api/v1/rules', timeout=10, operator=True) 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', BASE_URL,
|
||||
'--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
+309
@@ -0,0 +1,309 @@
|
||||
#!/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
|
||||
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url, grafana_password
|
||||
|
||||
# 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 open_url(req, timeout=timeout, operator=True) 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 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=BASE_URL)
|
||||
parser.add_argument('--ca-file', default=CA_FILE)
|
||||
parser.add_argument('--prometheus', default='https://localhost:9090')
|
||||
parser.add_argument('--loki', default='https://localhost:3100')
|
||||
parser.add_argument('--tempo', default='https://localhost:3200')
|
||||
parser.add_argument('--grafana', default='https://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, args.ca_file, 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 operator secret is missing (secrets/lab7/backends/credentials.json)')
|
||||
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
+302
@@ -0,0 +1,302 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure real password.Hash/Verify and optional real HTTPS login denials.
|
||||
|
||||
python3 scripts/lab7_auth_benchmark.py --concurrency 1 2 8 --operations 120 --output evidence/lab7/auth.json
|
||||
Optional: --api --ca-file <CA> --base-url https://localhost:8443
|
||||
|
||||
The temporary Go program imports this repository's password implementation,
|
||||
reads measured PHC m/t/p, and reports operation latency, busy denial and process
|
||||
peak RSS. It is deleted after execution; passwords, hashes and tokens never
|
||||
appear in output. Compiler memory/time are excluded from process RSS/latency.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'student-tests'))
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from lab7_helpers import ProbeFailure, command, require, Stand
|
||||
from client import Client, Failure
|
||||
|
||||
GO_PROGRAM = r'''package main
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"os"
|
||||
"runtime"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type sample struct {
|
||||
Operation string `json:"operation"`
|
||||
Seconds float64 `json:"seconds"`
|
||||
Result string `json:"result"`
|
||||
}
|
||||
|
||||
func fatal(classification string) {
|
||||
if err := json.NewEncoder(os.Stdout).Encode(map[string]string{"classification": classification}); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func main() {
|
||||
concurrency := flag.Int("concurrency", 1, "parallel callers")
|
||||
operations := flag.Int("operations", 120, "total operations")
|
||||
flag.Parse()
|
||||
if *concurrency < 1 || *operations < 1 {
|
||||
fatal("invalid_configuration")
|
||||
}
|
||||
plainBytes := make([]byte, 24)
|
||||
if _, err := rand.Read(plainBytes); err != nil {
|
||||
fatal("entropy_unavailable")
|
||||
}
|
||||
plain := hex.EncodeToString(plainBytes)
|
||||
encoded, err := password.Hash(plain)
|
||||
if err != nil {
|
||||
fatal("seed_hash_failed")
|
||||
}
|
||||
fields := strings.Split(encoded, "$")
|
||||
if len(fields) != 6 || fields[1] != "argon2id" {
|
||||
fatal("measured_hash_not_phc_argon2id")
|
||||
}
|
||||
params := map[string]int{}
|
||||
for _, item := range strings.Split(fields[3], ",") {
|
||||
pair := strings.SplitN(item, "=", 2)
|
||||
if len(pair) != 2 {
|
||||
fatal("measured_phc_parameters_invalid")
|
||||
}
|
||||
value, err := strconv.Atoi(pair[1])
|
||||
if err != nil {
|
||||
fatal("measured_phc_parameters_invalid")
|
||||
}
|
||||
params[pair[0]] = value
|
||||
}
|
||||
jobs := make(chan int)
|
||||
samples := make([]sample, *operations)
|
||||
var group sync.WaitGroup
|
||||
started := time.Now()
|
||||
for range *concurrency {
|
||||
group.Go(func() {
|
||||
for index := range jobs {
|
||||
began := time.Now()
|
||||
operation, result := "hash", "ok"
|
||||
switch index % 3 {
|
||||
case 0:
|
||||
_, err := password.Hash(plain)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
result = "busy_denied"
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
result = "hash_error"
|
||||
}
|
||||
case 1, 2:
|
||||
operation = "verify_correct"
|
||||
candidate := plain
|
||||
if index % 3 == 2 {
|
||||
operation = "verify_incorrect"
|
||||
candidate += "-incorrect"
|
||||
}
|
||||
verified, err := password.Verify(candidate, encoded)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
result = "busy_denied"
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
result = "verify_error"
|
||||
break
|
||||
}
|
||||
expectedMatch := index % 3 == 1
|
||||
if verified.Match != expectedMatch {
|
||||
result = "verification_mismatch"
|
||||
}
|
||||
}
|
||||
samples[index] = sample{
|
||||
Operation: operation,
|
||||
Seconds: time.Since(began).Seconds(),
|
||||
Result: result,
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
for index := range *operations {
|
||||
jobs <- index
|
||||
}
|
||||
close(jobs)
|
||||
group.Wait()
|
||||
elapsed := time.Since(started).Seconds()
|
||||
counts := map[string]int{}
|
||||
timings := map[string][]float64{}
|
||||
for _, value := range samples {
|
||||
counts[value.Result]++
|
||||
if value.Result == "ok" {
|
||||
timings[value.Operation] = append(timings[value.Operation], value.Seconds)
|
||||
}
|
||||
}
|
||||
latency := map[string]map[string]float64{}
|
||||
for operation, values := range timings {
|
||||
sort.Float64s(values)
|
||||
latency[operation] = map[string]float64{
|
||||
"p50_seconds": values[(len(values)-1)/2],
|
||||
"p95_seconds": values[(len(values)-1)*95/100],
|
||||
"max_seconds": values[len(values)-1],
|
||||
}
|
||||
}
|
||||
var usage syscall.Rusage
|
||||
if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err != nil {
|
||||
fatal("peak_rss_unavailable")
|
||||
}
|
||||
peakRSS := uint64(usage.Maxrss)
|
||||
if runtime.GOOS != "darwin" {
|
||||
peakRSS *= 1024
|
||||
}
|
||||
result := map[string]any{
|
||||
"classification": "measured",
|
||||
"algorithm": "argon2id",
|
||||
"parameters": params,
|
||||
"concurrency": *concurrency,
|
||||
"operations": *operations,
|
||||
"elapsed_seconds": elapsed,
|
||||
"successful_operations_per_second": float64(counts["ok"]) / elapsed,
|
||||
"busy_denied_rate": float64(counts["busy_denied"]) / float64(*operations),
|
||||
"counts": counts,
|
||||
"latency": latency,
|
||||
"peak_rss_bytes": peakRSS,
|
||||
"goos": runtime.GOOS,
|
||||
"gomaxprocs": runtime.GOMAXPROCS(0),
|
||||
"raw_samples": samples,
|
||||
}
|
||||
if err := json.NewEncoder(os.Stdout).Encode(result); err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
def hash_benchmark(concurrency, operations):
|
||||
# Internal package import is legal only under this module. No permanent
|
||||
# source or build artifact is created, and the module itself is not edited.
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-auth-bench-', dir=ROOT) as directory:
|
||||
source = Path(directory) / 'main.go'
|
||||
source.write_text(GO_PROGRAM)
|
||||
# Homebrew's default `go` can be older than go.mod's toolchain. Resolve
|
||||
# the cached toolchain GOROOT once, then pin that binary with local mode.
|
||||
go_bin = 'go'
|
||||
discovery = command(['go', 'env', 'GOROOT'], env={'GOTOOLCHAIN': 'auto'},
|
||||
check=False, timeout=30)
|
||||
candidate = Path(discovery.stdout.strip()) / 'bin' / 'go'
|
||||
if candidate.is_file():
|
||||
go_bin = str(candidate)
|
||||
result = command([go_bin, 'run', '-mod=readonly', str(source),
|
||||
'--concurrency', str(concurrency), '--operations', str(operations)],
|
||||
env={'GOPROXY': 'off', 'GOSUMDB': 'off', 'GOTOOLCHAIN': 'local'}, timeout=300)
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
raise ProbeFailure('hash_benchmark_invalid_json') from None
|
||||
require(payload.get('classification') == 'measured', 'hash_benchmark_not_measured')
|
||||
require(payload['counts'].get('hash_error', 0) == 0 and payload['counts'].get('verify_error', 0) == 0
|
||||
and payload['counts'].get('verification_mismatch', 0) == 0, 'real_hash_verification_failure')
|
||||
return payload
|
||||
|
||||
|
||||
def api_benchmark(args, concurrency):
|
||||
stand = Stand(base_url=args.base_url)
|
||||
client = Client(stand.base_url, args.ca_file, timeout=5)
|
||||
actor = client.user('authbench')
|
||||
credential = base64.b64encode((actor['registration']['username'] + ':incorrect-local-benchmark-password').encode()).decode()
|
||||
ids = [item['Id'] for item in stand.containers('api')]
|
||||
require(len(ids) == 2, 'auth_benchmark_requires_two_replicas')
|
||||
# cgroup v2 memory.peak measures actual API containers, not the Python or
|
||||
# compiler process. It can include a previous higher peak: report honestly.
|
||||
def peak_memory():
|
||||
peaks = []
|
||||
for container in ids:
|
||||
value = command(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.peak'], check=False, timeout=10)
|
||||
peaks.append(int(value.stdout.strip()) if value.returncode == 0 and value.stdout.strip().isdigit() else None)
|
||||
return peaks
|
||||
peaks_before = peak_memory()
|
||||
def one(index):
|
||||
began = time.monotonic()
|
||||
try:
|
||||
current = Client(stand.base_url, args.ca_file, timeout=5)
|
||||
response = current.call('POST', '/api/v1/auth/sessions', (401, 429), headers={'Authorization': 'Basic ' + credential})
|
||||
status = response['status']
|
||||
if status == 429:
|
||||
retry = response['headers'].get('Retry-After', '')
|
||||
require(retry.isdigit() and int(retry) > 0, 'api_busy_missing_retry_after')
|
||||
return {'index': index, 'status': status, 'latency_seconds': time.monotonic() - began,
|
||||
'instance': response['headers'].get('X-Instance-Id')}
|
||||
except (Failure, ProbeFailure):
|
||||
return {'index': index, 'status': None, 'classification': 'api_benchmark_request_failed',
|
||||
'latency_seconds': time.monotonic() - began}
|
||||
started = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
samples = list(pool.map(one, range(args.operations)))
|
||||
elapsed = time.monotonic() - started
|
||||
peaks_after = peak_memory()
|
||||
require(all(s['status'] in (401, 429) for s in samples), 'api_auth_benchmark_unexpected_failure')
|
||||
denied = sum(s['status'] == 429 for s in samples)
|
||||
latencies = sorted(s['latency_seconds'] for s in samples)
|
||||
latency = {'p50_seconds': latencies[(len(latencies) - 1) // 2],
|
||||
'p95_seconds': latencies[(len(latencies) - 1) * 95 // 100], 'max_seconds': latencies[-1]}
|
||||
return {'concurrency': concurrency, 'operations': args.operations, 'elapsed_seconds': elapsed,
|
||||
'requests_per_second': len(samples) / elapsed, 'admission_denied_rate': denied / len(samples),
|
||||
'incorrect_password_401': sum(s['status'] == 401 for s in samples),
|
||||
'api_cgroup_peak_bytes_before': peaks_before, 'api_cgroup_peak_bytes_after': peaks_after,
|
||||
'latency': latency, 'raw_samples': samples,
|
||||
'limitations': ['Cgroup memory.peak includes container lifetime history; account/shared/local rate limits all contribute to429.']}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--concurrency', type=int, nargs='+', default=[1, 2, 8])
|
||||
parser.add_argument('--operations', type=int, default=120)
|
||||
parser.add_argument('--api', action='store_true')
|
||||
parser.add_argument('--base-url', default='https://localhost:8443')
|
||||
parser.add_argument('--ca-file')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
require(all(0 < c <= 64 for c in args.concurrency) and args.operations >= 3, 'invalid_benchmark_configuration')
|
||||
require(not args.api or bool(args.ca_file), 'api_benchmark_ca_required')
|
||||
measured = [hash_benchmark(c, args.operations) for c in args.concurrency]
|
||||
result = {'study': 'lab7-auth-benchmark', 'timestamp': dt.datetime.now(dt.timezone.utc).isoformat(),
|
||||
'hash_verify': measured, 'api_auth': [api_benchmark(args, c) for c in args.concurrency] if args.api else [],
|
||||
'limitations': ['Native benchmark imports actual configured password implementation, not a reimplementation.',
|
||||
'Operation scheduling is closed-loop; memory includes Go runtime and seed hash, excludes compiler.',
|
||||
'Optional API benchmark uses one fresh account per concurrency level and real shared rejection paths.']}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
|
||||
print(json.dumps({'study': result['study'], 'classification': 'measured', 'output': str(args.output)}, sort_keys=True))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except ProbeFailure as exc:
|
||||
print(json.dumps({'classification': exc.classification, 'detail': exc.detail}))
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'classification': 'benchmark_exception', 'type': type(exc).__name__}))
|
||||
raise SystemExit(1)
|
||||
Executable
+246
@@ -0,0 +1,246 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-local environment and verified OpenBao transport for lab7."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ROLES = {
|
||||
'api': ['api', 'api-replica'],
|
||||
'worker': ['worker'],
|
||||
'relay': ['relay'],
|
||||
'lb': ['lb', 'localhost'],
|
||||
'postgres': ['postgres', 'localhost'],
|
||||
'redis': ['redis', 'localhost'],
|
||||
's3': ['s3', 'seaweedfs', 'localhost'],
|
||||
'broker': ['broker', 'localhost'],
|
||||
'collector': ['collector', 'otel-collector', 'localhost'],
|
||||
'prometheus': ['prometheus', 'localhost'],
|
||||
'loki': ['loki', 'localhost'],
|
||||
'tempo': ['tempo', 'localhost'],
|
||||
'grafana': ['grafana', 'localhost'],
|
||||
'openbao': ['openbao', 'localhost'],
|
||||
'operator': ['operator'],
|
||||
'rogue': ['rogue'],
|
||||
}
|
||||
ALPINE_IMAGE = 'alpine:3.22@sha256:49340b346798875b5592e5d420241f2f9cfba5f47e62ebb1446a1b34734e898f'
|
||||
|
||||
|
||||
class OperationError(RuntimeError):
|
||||
"""A sanitized failure; secret-bearing API bodies are never included."""
|
||||
|
||||
|
||||
def read_env(path: Path) -> dict[str, str]:
|
||||
values = {}
|
||||
if not path.exists():
|
||||
return values
|
||||
for line in path.read_text().splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith('#') and '=' in line:
|
||||
key, value = line.split('=', 1)
|
||||
values[key.strip()] = value.strip().strip('"').strip("'")
|
||||
return values
|
||||
|
||||
|
||||
def atomic_write(path: Path, content: str, mode: int = 0o600) -> None:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix='.' + path.name, dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
os.fchmod(stream.fileno(), mode)
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
|
||||
|
||||
class Environment:
|
||||
def __init__(self) -> None:
|
||||
self.config = read_env(ROOT / '.env')
|
||||
self.project = self.value('COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab6')
|
||||
if not re.fullmatch(r'[a-z0-9][a-z0-9_.-]*', self.project):
|
||||
raise OperationError('invalid local Compose project name')
|
||||
self.secrets = Path(self.value('LAB7_SECRETS_DIR', str(ROOT / 'secrets/lab7')))
|
||||
if not self.secrets.is_absolute():
|
||||
self.secrets = ROOT / self.secrets
|
||||
self.secrets = self.secrets.resolve()
|
||||
self.state = Path(self.value(
|
||||
'LAB7_OPERATOR_STATE',
|
||||
str(Path.home() / '.local/share/mtusi-lab7' / self.project),
|
||||
)).expanduser().resolve()
|
||||
self.secrets.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
self.state.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
os.chmod(self.secrets, 0o700)
|
||||
os.chmod(self.state, 0o700)
|
||||
self.redactions: set[str] = set()
|
||||
self.bao_url = 'https://localhost:' + self.value('BAO_PORT', '8200')
|
||||
self.base_url = 'https://localhost:' + self.value('PUBLIC_PORT', '8443')
|
||||
self.process_env = {
|
||||
**os.environ,
|
||||
'COMPOSE_PROJECT_NAME': self.project,
|
||||
'LAB7_SECRETS_DIR': str(self.secrets),
|
||||
'NO_PROXY': 'localhost,127.0.0.1,::1',
|
||||
'no_proxy': 'localhost,127.0.0.1,::1',
|
||||
}
|
||||
for key in ('HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'http_proxy', 'https_proxy', 'all_proxy'):
|
||||
self.process_env.pop(key, None)
|
||||
|
||||
def value(self, key: str, fallback: str) -> str:
|
||||
return os.environ.get(key, self.config.get(key, fallback))
|
||||
|
||||
def redact(self, value: str) -> str:
|
||||
for secret in self.redactions:
|
||||
if len(secret) >= 8:
|
||||
value = value.replace(secret, '[REDACTED]')
|
||||
return value
|
||||
|
||||
def run(self, command: list[str], *, data: str | None = None,
|
||||
check: bool = True, timeout: float = 180) -> subprocess.CompletedProcess:
|
||||
result = subprocess.run(command, cwd=ROOT, input=data, text=True,
|
||||
capture_output=True, timeout=timeout, env=self.process_env)
|
||||
if check and result.returncode:
|
||||
# SQL/bootstrap commands can echo a failed statement containing a password.
|
||||
detail = '' if data is not None else self.redact(result.stderr[-1800:])
|
||||
raise OperationError(f'{Path(command[0]).name} failed ({result.returncode}): {detail}')
|
||||
return result
|
||||
|
||||
def compose(self, *args: str, data: str | None = None,
|
||||
check: bool = True, timeout: float = 180) -> subprocess.CompletedProcess:
|
||||
env_file = ROOT / ('.env' if (ROOT / '.env').exists() else '.env.example')
|
||||
configured = self.process_env.get('COMPOSE_FILE', self.value('COMPOSE_FILE', str(ROOT / 'compose.yaml')))
|
||||
files = configured.split(os.pathsep)
|
||||
override = self.value('LAB7_COMPOSE_OVERRIDE', '')
|
||||
if override and override not in files:
|
||||
files.append(override)
|
||||
arguments = ['docker', 'compose', '--env-file', str(env_file)]
|
||||
for filename in files:
|
||||
path = Path(filename)
|
||||
if not path.is_absolute():
|
||||
path = ROOT / path
|
||||
arguments.extend(['-f', str(path)])
|
||||
return self.run([*arguments, *args], data=data, check=check, timeout=timeout)
|
||||
|
||||
def private_json(self, path: Path, value: dict) -> None:
|
||||
atomic_write(path, json.dumps(value, indent=2) + '\n')
|
||||
|
||||
def read_json(self, path: Path, fallback: dict | None = None) -> dict:
|
||||
if not path.exists():
|
||||
return {} if fallback is None else fallback
|
||||
return json.loads(path.read_text())
|
||||
|
||||
def identity(self, role: str) -> Path:
|
||||
return self.secrets / 'pki' / role / 'current'
|
||||
|
||||
def group_access(self, path: Path) -> None:
|
||||
# Operator-only helper: no network, no daemon socket, narrowly scoped mount.
|
||||
# DAC_OVERRIDE is needed to traverse operator-owned private directories;
|
||||
# CHOWN assigns the runtime group without making private keys world-readable.
|
||||
self.run(['docker', 'run', '--rm', '--network', 'none', '--user', '0:0',
|
||||
'--cap-drop', 'ALL', '--cap-add', 'CHOWN', '--cap-add', 'DAC_OVERRIDE',
|
||||
'--security-opt', 'no-new-privileges:true',
|
||||
'--mount', f'type=bind,source={path},target=/generated',
|
||||
ALPINE_IMAGE, 'chown', '-R', f'{os.getuid()}:10001', '/generated'])
|
||||
|
||||
def snapshot(self, role: str) -> dict[str, str]:
|
||||
directory = self.identity(role).resolve(strict=True)
|
||||
return {name: (directory / name).read_text()
|
||||
for name in ('tls.crt', 'tls.key', 'ca.crt', 'ca.crl')}
|
||||
|
||||
def publish(self, role: str, certificate: str, private_key: str,
|
||||
ca_bundle: str, crls: str) -> dict:
|
||||
if role not in ROLES and role not in ('wrong-identity', 'untrusted', 'next-lb'):
|
||||
raise OperationError('unknown service identity')
|
||||
certificate = certificate.rstrip() + '\n'
|
||||
private_key = private_key.rstrip() + '\n'
|
||||
public = self.run(['openssl', 'x509', '-pubkey', '-noout'], data=certificate).stdout
|
||||
key_public = self.run(['openssl', 'pkey', '-pubout'], data=private_key).stdout
|
||||
if public.strip() != key_public.strip():
|
||||
raise OperationError('certificate and private key do not match')
|
||||
directory = self.secrets / 'pki' / role
|
||||
version_name = str(time.time_ns()) + '-' + hashlib.sha256(certificate.encode()).hexdigest()[:12]
|
||||
version = directory / 'versions' / version_name
|
||||
version.mkdir(parents=True, mode=0o750)
|
||||
for parent in (directory, directory / 'versions'):
|
||||
os.chmod(parent, 0o750)
|
||||
for name, content in {
|
||||
'tls.crt': certificate, 'tls.key': private_key,
|
||||
'tls.pem': certificate + private_key, 'ca.crt': ca_bundle, 'ca.crl': crls,
|
||||
}.items():
|
||||
atomic_write(version / name, content, 0o640)
|
||||
self.group_access(directory if not (directory / 'current').exists() else version)
|
||||
temporary = directory / ('.current-' + version_name)
|
||||
temporary.symlink_to(Path('versions') / version_name)
|
||||
os.replace(temporary, directory / 'current')
|
||||
selector = directory / ('.current-version-' + version_name)
|
||||
atomic_write(selector, version_name + '\n', 0o640)
|
||||
self.group_access(selector)
|
||||
os.replace(selector, directory / 'current-version')
|
||||
description = self.run(['openssl', 'x509', '-noout', '-serial', '-enddate'],
|
||||
data=certificate).stdout.splitlines()
|
||||
serial = next(line.split('=', 1)[1].lower() for line in description if line.startswith('serial='))
|
||||
expiry = next(line.split('=', 1)[1] for line in description if line.startswith('notAfter='))
|
||||
return {'role': role, 'serial_number': serial, 'not_after': expiry}
|
||||
|
||||
|
||||
class BaoClient:
|
||||
def __init__(self, environment: Environment, role: str | None = 'operator') -> None:
|
||||
self.environment = environment
|
||||
self.role = role
|
||||
identity = environment.identity(role or 'operator')
|
||||
context = ssl.create_default_context(cafile=str(identity / 'ca.crt'))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if role is not None:
|
||||
context.load_cert_chain(str(identity / 'tls.crt'), str(identity / 'tls.key'))
|
||||
self.opener = urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}), urllib.request.HTTPSHandler(context=context))
|
||||
|
||||
def request(self, method: str, path: str, data: dict | None = None,
|
||||
token: str | None = None, raw: bool = False,
|
||||
allowed: tuple[int, ...] = (200, 204), timeout: float = 5):
|
||||
headers = {'Accept': 'application/json', 'Connection': 'close'}
|
||||
payload = None
|
||||
if data is not None:
|
||||
headers['Content-Type'] = 'application/json'
|
||||
payload = json.dumps(data).encode()
|
||||
if token:
|
||||
headers['X-Vault-Token'] = token
|
||||
self.environment.redactions.add(token)
|
||||
request = urllib.request.Request(self.environment.bao_url + '/v1/' + path.lstrip('/'),
|
||||
data=payload, method=method, headers=headers)
|
||||
try:
|
||||
with self.opener.open(request, timeout=timeout) as response:
|
||||
body = response.read(1024 * 1024 + 1)
|
||||
status = response.status
|
||||
except urllib.error.HTTPError as error:
|
||||
status = error.code
|
||||
body = error.read(1024 * 1024 + 1)
|
||||
except (urllib.error.URLError, TimeoutError) as error:
|
||||
raise OperationError('OpenBao verified TLS transport failed: ' + str(error)) from error
|
||||
if status not in allowed:
|
||||
raise OperationError(f'OpenBao {method} {path} rejected with HTTP {status}')
|
||||
if len(body) > 1024 * 1024:
|
||||
raise OperationError('OpenBao response exceeds one MiB')
|
||||
if raw:
|
||||
return body.decode()
|
||||
return json.loads(body) if body else {}
|
||||
|
||||
def login(self, role: str | None = None) -> str:
|
||||
response = self.request('POST', 'auth/cert/login', {'name': role or self.role})
|
||||
token = response.get('auth', {}).get('client_token')
|
||||
if not token:
|
||||
raise OperationError('OpenBao did not issue a scoped service token')
|
||||
self.environment.redactions.add(token)
|
||||
return token
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Verified local HTTPS transport shared by preserved lab1–6 operator tools."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from lab7_environment import ROOT, read_env
|
||||
|
||||
_SETTINGS = read_env(ROOT / '.env')
|
||||
|
||||
|
||||
def _value(name: str, fallback: str) -> str:
|
||||
return os.environ.get(name, _SETTINGS.get(name, fallback))
|
||||
|
||||
|
||||
def _path(value: str) -> Path:
|
||||
path = Path(value).expanduser()
|
||||
return path if path.is_absolute() else ROOT / path
|
||||
|
||||
|
||||
SECRETS_DIR = _path(_value('LAB7_SECRETS_DIR', 'secrets/lab7'))
|
||||
OPERATOR_IDENTITY = SECRETS_DIR / 'pki/operator/current'
|
||||
CA_FILE = str(_path(_value('CA_FILE', str(OPERATOR_IDENTITY / 'ca.crt'))))
|
||||
BASE_URL = _value('BASE_URL', 'https://localhost:' + _value('PUBLIC_PORT', '8443'))
|
||||
|
||||
|
||||
class _HTTPSOnly(urllib.request.HTTPHandler):
|
||||
def http_open(self, request):
|
||||
raise ValueError('legacy operator tools require a verified HTTPS URL')
|
||||
|
||||
|
||||
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, request, response, code, message, headers, new_url):
|
||||
return None
|
||||
|
||||
|
||||
def public_context(ca_file: str | None = CA_FILE) -> ssl.SSLContext:
|
||||
context = ssl.create_default_context(cafile=str(_path(ca_file or CA_FILE)))
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
return context
|
||||
|
||||
|
||||
def public_opener(ca_file: str | None = CA_FILE) -> urllib.request.OpenerDirector:
|
||||
return urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}),
|
||||
_HTTPSOnly(), _NoRedirect(),
|
||||
urllib.request.HTTPSHandler(context=public_context(ca_file)),
|
||||
)
|
||||
|
||||
|
||||
def operator_opener(ca_file: str | None = CA_FILE) -> urllib.request.OpenerDirector:
|
||||
# Resolve the immutable identity snapshot once so rotation cannot mix key/cert.
|
||||
identity = OPERATOR_IDENTITY.resolve(strict=True)
|
||||
ca_path = _path(ca_file or CA_FILE)
|
||||
if ca_path == OPERATOR_IDENTITY / 'ca.crt':
|
||||
ca_path = identity / 'ca.crt'
|
||||
context = public_context(str(ca_path))
|
||||
context.load_cert_chain(
|
||||
str(_path(_value('OPERATOR_CERT_FILE', str(identity / 'tls.crt')))),
|
||||
str(_path(_value('OPERATOR_KEY_FILE', str(identity / 'tls.key')))),
|
||||
)
|
||||
return urllib.request.build_opener(
|
||||
urllib.request.ProxyHandler({}), _HTTPSOnly(), _NoRedirect(),
|
||||
urllib.request.HTTPSHandler(context=context),
|
||||
)
|
||||
|
||||
|
||||
def open_url(url_or_request, timeout: float = 10, *, operator: bool = False,
|
||||
ca_file: str | None = CA_FILE):
|
||||
url = url_or_request.full_url if isinstance(url_or_request, urllib.request.Request) else url_or_request
|
||||
if urllib.parse.urlsplit(url).scheme != 'https':
|
||||
raise ValueError('legacy operator tools require a verified HTTPS URL')
|
||||
opener = operator_opener(ca_file) if operator else public_opener(ca_file)
|
||||
return opener.open(url_or_request, timeout=timeout)
|
||||
|
||||
|
||||
def grafana_password() -> str:
|
||||
credentials = json.loads((SECRETS_DIR / 'backends/credentials.json').read_text())
|
||||
password = credentials['grafana']['password']
|
||||
if not isinstance(password, str) or not password:
|
||||
raise ValueError('operator Grafana password is missing')
|
||||
return password
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run existing database/cache integration tests over verified local TLS.
|
||||
|
||||
Requires a bootstrapped stand (make up). Tests create isolated PostgreSQL
|
||||
fixture databases and use Redis DB7, never production cache DB0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from lab7_environment import OperationError, ROOT
|
||||
from securityctl import Controller
|
||||
|
||||
|
||||
def main() -> int:
|
||||
control = Controller()
|
||||
if not control.credentials_path.exists():
|
||||
raise OperationError('run make up before operator integration tests')
|
||||
values = control.credentials()
|
||||
environment = control.env.process_env.copy()
|
||||
environment['COMPOSE_FILE'] = str(ROOT / 'docker-compose.local.yaml')
|
||||
control.env.process_env.update(environment)
|
||||
control.env.config['COMPOSE_FILE'] = environment['COMPOSE_FILE']
|
||||
control.env.compose('up', '-d', '--no-build', 'postgres', 'redis', timeout=180)
|
||||
control.wait_stores()
|
||||
identity = control.env.identity('operator')
|
||||
environment.update({
|
||||
'TEST_POSTGRES_HOST': 'localhost',
|
||||
'TEST_POSTGRES_PORT': control.env.value('TEST_POSTGRES_PORT', '15432'),
|
||||
'TEST_POSTGRES_USER': values['postgres']['operator']['username'],
|
||||
'TEST_POSTGRES_PASSWORD': values['postgres']['operator']['password'],
|
||||
'TEST_POSTGRES_DATABASE': 'messenger',
|
||||
'TEST_POSTGRES_SSL_MODE': 'verify-full',
|
||||
'TEST_REDIS_HOST': 'localhost',
|
||||
'TEST_REDIS_PORT': control.env.value('TEST_REDIS_PORT', '16379'),
|
||||
'TEST_REDIS_USERNAME': 'operator',
|
||||
'TEST_REDIS_PASSWORD': values['redis']['operator']['password'],
|
||||
'TEST_REDIS_DB': '7',
|
||||
'TLS_CA_FILE': str(identity / 'ca.crt'),
|
||||
'TLS_CERT_FILE': str(identity / 'tls.crt'),
|
||||
'TLS_KEY_FILE': str(identity / 'tls.key'),
|
||||
'TLS_CRL_FILE': str(identity / 'ca.crl'),
|
||||
'TLS_VERSION_FILE': str(identity.parent / 'current-version'),
|
||||
})
|
||||
result = subprocess.run([
|
||||
os.environ.get('GO', 'go'), 'test', '-tags=integration', '-p', '1',
|
||||
'-count=1', '-timeout=15m', './internal/storage/postgres', './internal/storage/redis',
|
||||
], cwd=ROOT, env=environment, text=True, capture_output=True, timeout=1000)
|
||||
output = control.env.redact(result.stdout + result.stderr)
|
||||
destination = ROOT / 'evidence/lab7/integration.txt'
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(output)
|
||||
print(output, end='')
|
||||
return result.returncode
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OperationError, OSError, subprocess.TimeoutExpired) as error:
|
||||
print('FAIL: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Executable
+446
@@ -0,0 +1,446 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline root custody, OpenBao intermediate issuance and atomic leaf rotation."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import secrets
|
||||
import ssl
|
||||
import time
|
||||
|
||||
from lab7_environment import BaoClient, Environment, OperationError, ROLES, atomic_write
|
||||
|
||||
|
||||
class PKI:
|
||||
def __init__(self, environment: Environment) -> None:
|
||||
self.env = environment
|
||||
self.state_path = environment.state / 'pki-state.json'
|
||||
self.state = environment.read_json(self.state_path, {
|
||||
'active_root': 1, 'trust_roots': [1], 'issuers': {},
|
||||
})
|
||||
|
||||
def save(self) -> None:
|
||||
self.env.private_json(self.state_path, self.state)
|
||||
|
||||
def root_dir(self, generation: int | str) -> Path:
|
||||
return self.env.state / ('root-' + str(generation))
|
||||
|
||||
def create_root(self, generation: int | str) -> bool:
|
||||
directory = self.root_dir(generation)
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
if not (directory / 'ca.key').exists():
|
||||
self.env.run(['openssl', 'genpkey', '-algorithm', 'EC', '-pkeyopt',
|
||||
'ec_paramgen_curve:P-256', '-out', str(directory / 'ca.key')])
|
||||
os.chmod(directory / 'ca.key', 0o600)
|
||||
self.env.run(['openssl', 'req', '-new', '-x509', '-days', '3650',
|
||||
'-key', str(directory / 'ca.key'), '-out', str(directory / 'ca.crt'),
|
||||
'-subj', '/CN=MTUSI-Lab7-Root-' + str(generation),
|
||||
'-addext', 'basicConstraints=critical,CA:TRUE,pathlen:1',
|
||||
'-addext', 'keyUsage=critical,keyCertSign,cRLSign',
|
||||
'-addext', 'subjectKeyIdentifier=hash'])
|
||||
for name, initial in (('index.txt', ''), ('serial', secrets.token_hex(16) + '\n'),
|
||||
('crlnumber', secrets.token_hex(8) + '\n')):
|
||||
if not (directory / name).exists():
|
||||
atomic_write(directory / name, initial)
|
||||
(directory / 'newcerts').mkdir(exist_ok=True, mode=0o700)
|
||||
config = f'''[ca]
|
||||
default_ca = issuer
|
||||
[issuer]
|
||||
dir = {directory}
|
||||
database = $dir/index.txt
|
||||
new_certs_dir = $dir/newcerts
|
||||
certificate = $dir/ca.crt
|
||||
private_key = $dir/ca.key
|
||||
serial = $dir/serial
|
||||
crlnumber = $dir/crlnumber
|
||||
default_md = sha256
|
||||
default_days = 1
|
||||
default_crl_days = 3
|
||||
policy = names
|
||||
unique_subject = no
|
||||
copy_extensions = none
|
||||
[names]
|
||||
commonName = supplied
|
||||
'''
|
||||
atomic_write(directory / 'openssl.cnf', config)
|
||||
crl = directory / 'ca.crl'
|
||||
refresh = not crl.exists()
|
||||
if not refresh:
|
||||
result = self.env.run(['openssl', 'crl', '-in', str(crl), '-noout', '-nextupdate'])
|
||||
expires = ssl.cert_time_to_seconds(result.stdout.strip().split('=', 1)[1])
|
||||
refresh = expires <= time.time() + 86400
|
||||
if refresh:
|
||||
result = self.env.run(['openssl', 'ca', '-gencrl', '-config', str(directory / 'openssl.cnf')])
|
||||
atomic_write(crl, result.stdout)
|
||||
return refresh
|
||||
|
||||
def root_bundle(self) -> str:
|
||||
return ''.join((self.root_dir(generation) / 'ca.crt').read_text()
|
||||
for generation in self.state['trust_roots'])
|
||||
|
||||
def bundle(self) -> str:
|
||||
result = self.root_bundle()
|
||||
for generation in self.state['trust_roots']:
|
||||
path = self.root_dir(generation) / 'intermediate.crt'
|
||||
if path.exists():
|
||||
result += path.read_text()
|
||||
return result
|
||||
|
||||
def root_crls(self) -> str:
|
||||
return ''.join((self.root_dir(generation) / 'ca.crl').read_text()
|
||||
for generation in self.state['trust_roots'])
|
||||
|
||||
def cached_crls(self) -> str:
|
||||
result = self.root_crls()
|
||||
for generation in self.state['trust_roots']:
|
||||
path = self.root_dir(generation) / 'intermediate.crl'
|
||||
if path.exists():
|
||||
result += path.read_text()
|
||||
return result
|
||||
|
||||
def offline_leaf(self, role: str, generation: int | str, *,
|
||||
common_name: str | None = None, uri_role: str | None = None) -> tuple[str, str]:
|
||||
directory = self.env.state / 'offline-leaves' / role
|
||||
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
key = directory / 'tls.key'
|
||||
csr = directory / 'leaf.csr'
|
||||
certificate = directory / 'tls.crt'
|
||||
self.env.run(['openssl', 'genpkey', '-algorithm', 'EC', '-pkeyopt',
|
||||
'ec_paramgen_curve:P-256', '-out', str(key)])
|
||||
os.chmod(key, 0o600)
|
||||
cn = common_name or role
|
||||
self.env.run(['openssl', 'req', '-new', '-key', str(key), '-out', str(csr),
|
||||
'-subj', '/CN=' + cn])
|
||||
dns = ROLES.get(role, [cn])
|
||||
san = ','.join(['DNS:' + value for value in dns] + ['URI:spiffe://mtusi/' + (uri_role or role)])
|
||||
extensions = f'''[leaf]
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth,clientAuth
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
subjectAltName={san}
|
||||
'''
|
||||
atomic_write(directory / 'extensions.cnf', extensions)
|
||||
self.env.run(['openssl', 'ca', '-batch', '-notext', '-days', '1',
|
||||
'-config', str(self.root_dir(generation) / 'openssl.cnf'),
|
||||
'-extfile', str(directory / 'extensions.cnf'), '-extensions', 'leaf',
|
||||
'-in', str(csr), '-out', str(certificate)])
|
||||
return certificate.read_text(), key.read_text()
|
||||
|
||||
def prepare(self) -> None:
|
||||
refreshed = False
|
||||
for generation in self.state['trust_roots']:
|
||||
refreshed = self.create_root(generation) or refreshed
|
||||
for role in ROLES:
|
||||
if not self.env.identity(role).exists():
|
||||
certificate, key = self.offline_leaf(role, self.state['active_root'])
|
||||
self.env.publish(role, certificate, key, self.bundle(), self.cached_crls())
|
||||
elif refreshed or not (self.env.secrets / 'pki' / role / 'current-version').exists():
|
||||
snapshot = self.env.snapshot(role)
|
||||
self.env.publish(role, snapshot['tls.crt'], snapshot['tls.key'],
|
||||
self.bundle(), self.cached_crls())
|
||||
# Controlled wrong identity and wrong CA fixtures contain no root key.
|
||||
if not self.env.identity('wrong-identity').exists():
|
||||
certificate, key = self.offline_leaf('wrong-identity', self.state['active_root'],
|
||||
common_name='lb', uri_role='rogue')
|
||||
self.env.publish('wrong-identity', certificate, key, self.bundle(), self.cached_crls())
|
||||
if not self.env.identity('untrusted').exists():
|
||||
self.create_root('foreign')
|
||||
certificate, key = self.offline_leaf('untrusted', 'foreign', common_name='lb', uri_role='lb')
|
||||
self.env.publish('untrusted', certificate, key, self.bundle(), self.cached_crls())
|
||||
self.save()
|
||||
|
||||
def recover_transport(self) -> bool:
|
||||
restarted_listener = False
|
||||
for role in ('operator', 'openbao'):
|
||||
certificate = self.env.identity(role) / 'tls.crt'
|
||||
valid = self.env.run(['openssl', 'x509', '-checkend', '300', '-noout',
|
||||
'-in', str(certificate)], check=False).returncode == 0
|
||||
if valid:
|
||||
continue
|
||||
issued, key = self.offline_leaf(role, self.state['active_root'])
|
||||
self.env.publish(role, issued, key, self.bundle(), self.cached_crls())
|
||||
restarted_listener = restarted_listener or role == 'openbao'
|
||||
return restarted_listener
|
||||
|
||||
def create_intermediate(self, client: BaoClient, token: str, generation: int) -> str:
|
||||
known = self.state['issuers'].get(str(generation))
|
||||
if known:
|
||||
client.request('GET', 'pki/issuer/' + known, token=token)
|
||||
return known
|
||||
before = client.request('LIST', 'pki/issuers', token=token, allowed=(200, 404))
|
||||
previous = set(before.get('data', {}).get('keys', []))
|
||||
response = client.request('POST', 'pki/intermediate/generate/internal', {
|
||||
'common_name': 'MTUSI-Lab7-Intermediate-' + str(generation),
|
||||
'key_type': 'ec', 'key_bits': 256,
|
||||
}, token)
|
||||
csr = response.get('data', {}).get('csr')
|
||||
if not csr:
|
||||
raise OperationError('OpenBao did not return an intermediate CSR')
|
||||
directory = self.root_dir(generation)
|
||||
atomic_write(directory / 'intermediate.csr', csr)
|
||||
atomic_write(directory / 'intermediate.cnf', '''[intermediate]
|
||||
basicConstraints=critical,CA:TRUE,pathlen:0
|
||||
keyUsage=critical,keyCertSign,cRLSign
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
''')
|
||||
self.env.run(['openssl', 'ca', '-batch', '-notext', '-days', '365',
|
||||
'-config', str(directory / 'openssl.cnf'),
|
||||
'-extfile', str(directory / 'intermediate.cnf'), '-extensions', 'intermediate',
|
||||
'-in', str(directory / 'intermediate.csr'), '-out', str(directory / 'intermediate.crt')])
|
||||
imported = client.request('POST', 'pki/intermediate/set-signed', {
|
||||
'certificate': (directory / 'intermediate.crt').read_text() + (directory / 'ca.crt').read_text(),
|
||||
}, token)
|
||||
issuers = imported.get('data', {}).get('imported_issuers', [])
|
||||
if not issuers:
|
||||
after = client.request('LIST', 'pki/issuers', token=token)
|
||||
issuers = list(set(after['data']['keys']) - previous)
|
||||
expected = (directory / 'intermediate.crt').read_text().strip()
|
||||
matching = []
|
||||
for candidate in issuers:
|
||||
record = client.request('GET', 'pki/issuer/' + candidate, token=token)
|
||||
if record.get('data', {}).get('certificate', '').strip() == expected:
|
||||
matching.append(candidate)
|
||||
if len(matching) != 1:
|
||||
raise OperationError('cannot identify imported intermediate issuer')
|
||||
self.state['issuers'][str(generation)] = matching[0]
|
||||
self.save()
|
||||
return matching[0]
|
||||
|
||||
def provision(self, client: BaoClient, token: str) -> None:
|
||||
mounts = client.request('GET', 'sys/mounts', token=token)
|
||||
mounts = mounts.get('data', mounts)
|
||||
if 'pki/' not in mounts:
|
||||
client.request('POST', 'sys/mounts/pki', {
|
||||
'type': 'pki', 'config': {'max_lease_ttl': '8760h'},
|
||||
}, token)
|
||||
issuer = self.create_intermediate(client, token, self.state['active_root'])
|
||||
client.request('POST', 'pki/config/issuers', {'default': issuer}, token)
|
||||
client.request('POST', 'pki/config/urls', {
|
||||
'issuing_certificates': ['https://openbao:8200/v1/pki/ca'],
|
||||
'crl_distribution_points': ['https://openbao:8200/v1/pki/crl'],
|
||||
}, token)
|
||||
client.request('POST', 'pki/config/crl', {
|
||||
'expiry': '72h', 'auto_rebuild': True, 'auto_rebuild_grace_period': '24h',
|
||||
}, token, allowed=(200, 204, 404))
|
||||
for role, domains in ROLES.items():
|
||||
client.request('POST', 'pki/roles/' + role, {
|
||||
'allowed_domains': domains, 'allow_bare_domains': True,
|
||||
'allow_subdomains': False, 'allow_glob_domains': False,
|
||||
'allow_wildcard_certificates': False,
|
||||
'allow_localhost': 'localhost' in domains,
|
||||
'allow_ip_sans': False,
|
||||
'allowed_uri_sans': ['spiffe://mtusi/' + role],
|
||||
'key_type': 'ec', 'key_bits': 256, 'ttl': '1h', 'max_ttl': '1h',
|
||||
'server_flag': True, 'client_flag': True, 'issuer_ref': 'default',
|
||||
}, token)
|
||||
|
||||
def crl_remaining(self, crl: str) -> float:
|
||||
result = self.env.run(['openssl', 'crl', '-noout', '-nextupdate'], data=crl, check=False)
|
||||
if result.returncode:
|
||||
return -1
|
||||
try:
|
||||
stamp = result.stdout.strip().split('=', 1)[1]
|
||||
return ssl.cert_time_to_seconds(stamp) - time.time()
|
||||
except (IndexError, ValueError):
|
||||
return -1
|
||||
|
||||
def sync_crls(self, client: BaoClient, token: str) -> int:
|
||||
for generation in self.state['trust_roots']:
|
||||
self.create_root(generation)
|
||||
issuer = self.state['issuers'].get(str(generation))
|
||||
if issuer:
|
||||
crl = client.request('GET', 'pki/issuer/' + issuer + '/crl/pem',
|
||||
token=token, raw=True)
|
||||
if self.crl_remaining(crl) < 86400:
|
||||
client.request('POST', 'pki/issuer/' + issuer + '/crl/rotate', {},
|
||||
token=token, allowed=(200, 204, 403, 404, 405))
|
||||
crl = client.request('GET', 'pki/issuer/' + issuer + '/crl/pem',
|
||||
token=token, raw=True)
|
||||
if self.crl_remaining(crl) < 86400:
|
||||
raise OperationError('intermediate CRL remains inside its 24h margin')
|
||||
atomic_write(self.root_dir(generation) / 'intermediate.crl', crl)
|
||||
client.request('POST', 'auth/cert/crls/intermediate-' + str(generation),
|
||||
{'crl': crl}, token)
|
||||
root_crl = (self.root_dir(generation) / 'ca.crl').read_text()
|
||||
client.request('POST', 'auth/cert/crls/root-' + str(generation), {'crl': root_crl}, token)
|
||||
republished = 0
|
||||
for role in list(ROLES) + ['wrong-identity', 'untrusted', 'next-lb']:
|
||||
if self.env.identity(role).exists():
|
||||
snapshot = self.env.snapshot(role)
|
||||
self.env.publish(role, snapshot['tls.crt'], snapshot['tls.key'],
|
||||
self.bundle(), self.cached_crls())
|
||||
republished += 1
|
||||
return republished
|
||||
|
||||
def issue(self, role: str, ttl: str = '1h', *, service_auth: bool = False,
|
||||
issuer: str | None = None) -> dict:
|
||||
if role not in ROLES:
|
||||
raise OperationError('unknown PKI role')
|
||||
client = BaoClient(self.env, role if service_auth else 'operator')
|
||||
token = client.login()
|
||||
path = 'pki/issue/' + role
|
||||
if issuer:
|
||||
if service_auth:
|
||||
raise OperationError('service cannot override its allowed issuer path')
|
||||
path = 'pki/issuer/' + issuer + '/issue/' + role
|
||||
response = client.request('POST', path, {
|
||||
'common_name': role, 'alt_names': ','.join(ROLES[role][1:]),
|
||||
'uri_sans': 'spiffe://mtusi/' + role, 'ttl': ttl,
|
||||
}, token)
|
||||
data = response.get('data', {})
|
||||
certificate = data.get('certificate', '')
|
||||
private_key = data.get('private_key', '')
|
||||
if not certificate or not private_key:
|
||||
raise OperationError('OpenBao did not issue a complete leaf identity')
|
||||
chain = '\n'.join(part.strip() for part in [certificate, *data.get('ca_chain', [])]) + '\n'
|
||||
description = self.env.publish(role, chain, private_key,
|
||||
self.bundle(), self.cached_crls())
|
||||
archive = self.env.state / 'issued'
|
||||
archive.mkdir(exist_ok=True, mode=0o700)
|
||||
atomic_write(archive / (description['serial_number'] + '.crt'), certificate)
|
||||
return description
|
||||
|
||||
def renew_watch(self, role: str, ttl: str, interval: float, on_issued=None) -> None:
|
||||
if not 0 < interval <= 1:
|
||||
raise OperationError('leaf watchdog interval must be in (0, 1] seconds')
|
||||
result = self.issue(role, ttl, service_auth=True)
|
||||
if on_issued is not None:
|
||||
on_issued(role)
|
||||
print(json.dumps(result), flush=True)
|
||||
expiry = ssl.cert_time_to_seconds(result['not_after'])
|
||||
next_renewal = time.time() + max(1, (expiry - time.time()) / 2)
|
||||
while True:
|
||||
now = time.time()
|
||||
if now >= expiry - 1:
|
||||
raise OperationError('leaf renewal did not complete before certificate deadline')
|
||||
if now >= next_renewal:
|
||||
try:
|
||||
result = self.issue(role, ttl, service_auth=True)
|
||||
if on_issued is not None:
|
||||
on_issued(role)
|
||||
except OperationError as error:
|
||||
print(json.dumps({'role': role, 'renewal_error': str(error)}), flush=True)
|
||||
time.sleep(interval)
|
||||
continue
|
||||
print(json.dumps(result), flush=True)
|
||||
expiry = ssl.cert_time_to_seconds(result['not_after'])
|
||||
next_renewal = time.time() + max(1, (expiry - time.time()) / 2)
|
||||
time.sleep(interval)
|
||||
|
||||
def crl_contains_serial(self, bundle: str, normalized: str) -> bool:
|
||||
wanted = normalized.lstrip('0').lower()
|
||||
for block in re.findall(r'-----BEGIN X509 CRL-----.*?-----END X509 CRL-----', bundle, re.S):
|
||||
output = self.env.run(['openssl', 'crl', '-noout', '-text'], data=block,
|
||||
check=False).stdout
|
||||
for line in output.splitlines():
|
||||
if 'Serial Number:' not in line:
|
||||
continue
|
||||
value = line.split(':', 1)[1].strip().replace(':', '').lower().lstrip('0')
|
||||
if value == wanted:
|
||||
return True
|
||||
return False
|
||||
|
||||
def revoke(self, role: str, serial: str) -> dict:
|
||||
normalized = serial.replace(':', '').replace('-', '').lower()
|
||||
if not normalized or any(ch not in '0123456789abcdef' for ch in normalized):
|
||||
raise OperationError('invalid public certificate serial')
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
formatted = ':'.join(normalized[index:index + 2] for index in range(0, len(normalized), 2))
|
||||
client.request('POST', 'pki/revoke', {'serial_number': formatted}, token)
|
||||
# auto_rebuild only refreshes an expired CRL; a fresh revocation must
|
||||
# be published now, before the old identity can be retried. OpenBao
|
||||
# exposes rotation as GET /pki/crl/rotate (POST is 405 here).
|
||||
client.request('GET', 'pki/crl/rotate', token=token)
|
||||
self.sync_crls(client, token)
|
||||
if not self.crl_contains_serial(self.cached_crls(), normalized):
|
||||
raise OperationError('published CRL does not contain the revoked serial')
|
||||
return {'role': role, 'revoked_serial': normalized, 'crls_updated': True,
|
||||
'crl_rotated': True, 'crl_contains_serial': True}
|
||||
|
||||
def prepare_rollover(self) -> dict:
|
||||
if self.state.get('next_root'):
|
||||
return {'phase': 'prepare', 'next_root': self.state['next_root']}
|
||||
generation = self.state['active_root'] + 1
|
||||
self.create_root(generation)
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
self.create_intermediate(client, token, generation)
|
||||
self.state['next_root'] = generation
|
||||
self.state['trust_roots'].append(generation)
|
||||
self.save()
|
||||
# sync_crls publishes the overlap bundle to every role before issue:
|
||||
# clients and native services trust the next root before new leaves.
|
||||
republished = self.sync_crls(client, token)
|
||||
certificate, key = self.offline_leaf('next-lb', generation, common_name='lb', uri_role='lb')
|
||||
self.env.publish('next-lb', certificate, key, self.bundle(), self.cached_crls())
|
||||
return {'phase': 'prepare', 'next_root': generation, 'identities_republished': republished}
|
||||
|
||||
def switch_issuer(self) -> dict:
|
||||
generation = self.state.get('next_root')
|
||||
if not generation:
|
||||
raise OperationError('prepare CA overlap before switching issuance')
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
client.request('POST', 'pki/config/issuers', {
|
||||
'default': self.state['issuers'][str(generation)],
|
||||
}, token)
|
||||
self.state['previous_root'] = self.state['active_root']
|
||||
self.state['active_root'] = generation
|
||||
self.save()
|
||||
leaves = [self.issue(role) for role in ROLES]
|
||||
# Keep the same-CA rogue identity fixture meaningful after the switch:
|
||||
# otherwise it would be rejected as unknown CA instead of bad identity.
|
||||
if self.env.identity('wrong-identity').exists():
|
||||
certificate, key = self.offline_leaf('wrong-identity', generation,
|
||||
common_name='lb', uri_role='rogue')
|
||||
self.env.publish('wrong-identity', certificate, key, self.bundle(), self.cached_crls())
|
||||
return {'phase': 'issue', 'active_root': generation, 'leaves': leaves}
|
||||
|
||||
def certificate_name(self, path: Path, field: str) -> str:
|
||||
output = self.env.run(['openssl', 'x509', '-in', str(path), '-noout',
|
||||
'-' + field, '-nameopt', 'RFC2253']).stdout.strip()
|
||||
return output.split('=', 1)[1] if '=' in output else output
|
||||
|
||||
def retire_issuer(self) -> dict:
|
||||
previous = self.state.get('previous_root')
|
||||
if not previous:
|
||||
raise OperationError('switch issuance before retiring old CA')
|
||||
root_dir = self.root_dir(self.state['active_root'])
|
||||
active_issuers = {
|
||||
self.certificate_name(root_dir / 'intermediate.crt', 'subject'),
|
||||
self.certificate_name(root_dir / 'ca.crt', 'subject'),
|
||||
}
|
||||
for role in list(ROLES) + ['wrong-identity']:
|
||||
current = self.env.identity(role)
|
||||
if not current.exists():
|
||||
continue
|
||||
if self.certificate_name(current / 'tls.crt', 'issuer') not in active_issuers:
|
||||
raise OperationError('retire blocked: leaf is not from the active issuer: ' + role)
|
||||
verified = self.env.run(['openssl', 'verify',
|
||||
'-CAfile', str(root_dir / 'ca.crt'),
|
||||
'-untrusted', str(root_dir / 'intermediate.crt'),
|
||||
str(current / 'tls.crt')], check=False)
|
||||
if verified.returncode:
|
||||
raise OperationError('retire blocked: leaf chain does not verify: ' + role)
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
self.state['trust_roots'] = [self.state['active_root']]
|
||||
self.state.pop('next_root', None)
|
||||
self.save()
|
||||
# sync_crls re-publishes every identity with the retired trust set:
|
||||
# the leaf stays, but the old root and its CRL disappear from mounts.
|
||||
republished = self.sync_crls(client, token)
|
||||
# Old auth CRLs are removed to avoid stale/cross-issuer serial constraints.
|
||||
for name in ('root-' + str(previous), 'intermediate-' + str(previous)):
|
||||
client.request('DELETE', 'auth/cert/crls/' + name, token=token)
|
||||
old_issuer = self.state['issuers'].get(str(previous))
|
||||
if old_issuer:
|
||||
client.request('DELETE', 'pki/issuer/' + old_issuer, token=token)
|
||||
return {'phase': 'retire', 'retired_root': previous, 'active_root': self.state['active_root'],
|
||||
'identities_republished': republished}
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Renew short-lived role leaves and publish fresh CRLs on an interval.
|
||||
|
||||
The controller runs on the operator host next to `securityctl.py`: it needs the
|
||||
operator identity and the Docker CLI to reload native owners. It is not mounted
|
||||
into application containers. Run it under a supervisor (systemd/launchd) or as
|
||||
`make renewer` for a foreground lab session.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'scripts'))
|
||||
from lab7_environment import ROLES
|
||||
|
||||
SKIP = {'rogue'}
|
||||
|
||||
|
||||
def run(arguments: list[str]) -> tuple[bool, str]:
|
||||
result = subprocess.run([sys.executable, 'scripts/securityctl.py', *arguments],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=300)
|
||||
output = (result.stdout or result.stderr).strip()
|
||||
return result.returncode == 0, output[-600:]
|
||||
|
||||
|
||||
def cycle(ttl: str) -> dict:
|
||||
started = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
roles = {}
|
||||
for role in ROLES:
|
||||
if role in SKIP:
|
||||
continue
|
||||
ok, output = run(['renew', role, '--ttl', ttl])
|
||||
mode = 'renew'
|
||||
if not ok and 'expired' in output.lower():
|
||||
# Expiry is the only fallback: a revoked/disabled identity must
|
||||
# stay contained instead of being reissued by the operator.
|
||||
mode = 'issue'
|
||||
ok, output = run(['issue', role, '--ttl', ttl])
|
||||
roles[role] = {'ok': ok, 'mode': mode, 'output': output}
|
||||
crls_ok, crls_output = run(['sync-crls'])
|
||||
return {'timestamp': started, 'ttl': ttl, 'roles': roles,
|
||||
'crls': {'ok': crls_ok, 'output': crls_output},
|
||||
'passed': crls_ok and all(item['ok'] for item in roles.values())}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--interval', type=float, default=1800, help='seconds between cycles')
|
||||
parser.add_argument('--ttl', default='1h', help='leaf TTL requested from OpenBao')
|
||||
parser.add_argument('--once', action='store_true')
|
||||
parser.add_argument('--output', type=Path, default=None)
|
||||
args = parser.parse_args()
|
||||
while True:
|
||||
result = cycle(args.ttl)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
if args.output:
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
|
||||
if args.once:
|
||||
return 0 if result['passed'] else 1
|
||||
time.sleep(max(1, args.interval if result['passed'] else min(60, args.interval)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Executable
+108
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Pinned source/image vulnerability scans with no Docker socket in scanners."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
from lab7_environment import Environment, ROOT
|
||||
|
||||
TRIVY = 'aquasec/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb'
|
||||
GOVULNCHECK = 'golang.org/x/vuln/cmd/govulncheck@v1.9.0'
|
||||
|
||||
|
||||
def source_messages(text: str) -> list[dict]:
|
||||
"""govulncheck emits consecutive pretty-printed JSON objects, not JSONL."""
|
||||
decoder = json.JSONDecoder()
|
||||
messages, offset = [], 0
|
||||
while offset < len(text):
|
||||
while offset < len(text) and text[offset].isspace():
|
||||
offset += 1
|
||||
if offset == len(text):
|
||||
break
|
||||
message, offset = decoder.raw_decode(text, offset)
|
||||
messages.append(message)
|
||||
return messages
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--source-only', action='store_true')
|
||||
parser.add_argument('--output', type=Path, default=ROOT / 'evidence/lab7/scans')
|
||||
args = parser.parse_args()
|
||||
output = args.output.resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
cache = ROOT / '.cache/lab7-scans'
|
||||
cache.mkdir(parents=True, exist_ok=True)
|
||||
tool = ROOT / 'bin/govulncheck'
|
||||
if not tool.exists():
|
||||
subprocess.run(['go', 'install', GOVULNCHECK], cwd=ROOT,
|
||||
env={**os.environ, 'GOBIN': str(tool.parent)}, check=True)
|
||||
source = subprocess.run([str(tool), '-json', './...'], cwd=ROOT,
|
||||
capture_output=True, text=True, timeout=300)
|
||||
messages = source_messages(source.stdout)
|
||||
(output / 'govulncheck.json').write_text(json.dumps(messages, indent=2) + '\n')
|
||||
(output / 'govulncheck-status.txt').write_text('exit=' + str(source.returncode) + '\n' + source.stderr)
|
||||
advisories = {scope: set() for scope in ('symbol', 'package', 'module')}
|
||||
for message in messages:
|
||||
finding = message.get('finding')
|
||||
if finding:
|
||||
for scope, field in (('symbol', 'function'), ('package', 'package'), ('module', 'module')):
|
||||
if any(frame.get(field) for frame in finding.get('trace', [])):
|
||||
advisories[scope].add(finding['osv'])
|
||||
summary = {'govulncheck': {
|
||||
'exit': source.returncode, 'tool': GOVULNCHECK,
|
||||
'advisories': {'symbol': sorted(advisories['symbol']),
|
||||
'package_only': sorted(advisories['package'] - advisories['symbol']),
|
||||
'module_only': sorted(advisories['module'] - advisories['package'])},
|
||||
}, 'images': []}
|
||||
environment = Environment()
|
||||
if not args.source_only:
|
||||
images = sorted(set(environment.compose('config', '--images').stdout.split()))
|
||||
for index, image in enumerate(images):
|
||||
archive = cache / ('image-' + uuid.uuid4().hex + '.tar')
|
||||
subprocess.run(['docker', 'image', 'save', '--output', str(archive), image],
|
||||
cwd=ROOT, check=True, timeout=300)
|
||||
filename = f'image-{index:02d}.json'
|
||||
(output / filename).unlink(missing_ok=True)
|
||||
try:
|
||||
scan = subprocess.run([
|
||||
'docker', 'run', '--rm', '--cap-drop', 'ALL',
|
||||
'--security-opt', 'no-new-privileges:true',
|
||||
'--mount', f'type=bind,source={cache},target=/cache',
|
||||
'--mount', f'type=bind,source={output},target=/reports',
|
||||
TRIVY, 'image', '--input', '/cache/' + archive.name, '--cache-dir', '/cache/trivy',
|
||||
'--scanners', 'vuln', '--format', 'json', '--output', '/reports/' + filename,
|
||||
'--timeout', '5m',
|
||||
], cwd=ROOT, capture_output=True, text=True, timeout=330)
|
||||
(output / f'image-{index:02d}-status.txt').write_text(
|
||||
'exit=' + str(scan.returncode) + '\n' + scan.stdout + scan.stderr)
|
||||
counts = {}
|
||||
if scan.returncode == 0 and (output / filename).exists():
|
||||
report = json.loads((output / filename).read_text())
|
||||
for result in report.get('Results', []):
|
||||
for finding in result.get('Vulnerabilities') or []:
|
||||
severity = finding.get('Severity', 'UNKNOWN')
|
||||
counts[severity] = counts.get(severity, 0) + 1
|
||||
summary['images'].append({'image': image, 'exit': scan.returncode,
|
||||
'file': filename, 'counts': counts})
|
||||
print(json.dumps(summary['images'][-1]), flush=True)
|
||||
finally:
|
||||
archive.unlink(missing_ok=True)
|
||||
summary['trivy'] = TRIVY
|
||||
(output / 'summary.json').write_text(json.dumps(summary, indent=2) + '\n')
|
||||
print(json.dumps(summary), flush=True)
|
||||
return 0 if source.returncode in (0, 3) and all(item['exit'] == 0 for item in summary['images']) else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, subprocess.SubprocessError, json.JSONDecodeError) as error:
|
||||
print('SCAN FAILED: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Executable
+594
@@ -0,0 +1,594 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Repeatable destructive PKI study, restricted to fresh local synthetic projects.
|
||||
|
||||
python3 scripts/lab7_track2.py --reps 3 --duration 30 --output evidence/lab7/track2.json
|
||||
|
||||
Each repetition creates its own mtusi-lab7-track2-* Compose project, volumes,
|
||||
loopback ports and operator state outside checkout; cleanup removes only that
|
||||
project. Existing projects/volumes are never stopped or mutated. Images must
|
||||
already exist: all application recreation uses --no-build. One stable HTTPS
|
||||
client continuously POSTs messages; these total-expiry phases are NOT failover.
|
||||
Requires securityctl bootstrap/up/issue/renew --watch/revoke/rotate-secret/
|
||||
ca-rollover/audit-summary and automatic complete trust/CRL consumer reloads.
|
||||
"""
|
||||
import argparse
|
||||
import collections
|
||||
import concurrent.futures
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
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
|
||||
from lab7_helpers import Stand, ProbeFailure, command, require, http, temporary_directory
|
||||
from lab7_security import isolation
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
if not values:
|
||||
return None
|
||||
ordered = sorted(values)
|
||||
return ordered[min(len(ordered) - 1, int((len(ordered) - 1) * fraction))]
|
||||
|
||||
|
||||
def certificate(path):
|
||||
result = command(['openssl', 'x509', '-in', str(path), '-noout', '-serial', '-enddate', '-issuer'])
|
||||
fields = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
|
||||
require('serial' in fields and 'notAfter' in fields, 'certificate_metadata_missing')
|
||||
expires = dt.datetime.strptime(fields['notAfter'], '%b %d %H:%M:%S %Y %Z').replace(tzinfo=dt.timezone.utc)
|
||||
return {'serial_number': fields['serial'].upper(), 'not_after': expires.isoformat(),
|
||||
'expires_unix': expires.timestamp(), 'issuer': fields.get('issuer')}
|
||||
|
||||
|
||||
def current_api_certificate(stand):
|
||||
directory = stand.secrets / 'pki/api'
|
||||
version = (directory / 'current-version').read_text().strip()
|
||||
require(version and version not in ('.', '..') and Path(version).name == version,
|
||||
'invalid_api_version_selector')
|
||||
return certificate(directory / 'versions' / version / 'tls.crt')
|
||||
|
||||
|
||||
def snapshot(stand, role, directory):
|
||||
destination = Path(directory) / role
|
||||
destination.mkdir(mode=0o700)
|
||||
current = destination / 'current'
|
||||
current.mkdir(mode=0o700)
|
||||
for name in ('tls.crt', 'tls.key', 'ca.crt', 'ca.crl'):
|
||||
shutil.copyfile(stand.secrets / 'pki' / role / 'current' / name, current / name)
|
||||
(current / name).chmod(0o600)
|
||||
return destination
|
||||
|
||||
|
||||
def until(predicate, deadline=90, classification='recovery_deadline_exceeded'):
|
||||
end = time.monotonic() + deadline
|
||||
while time.monotonic() < end:
|
||||
try:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
except (ProbeFailure, Failure, OSError):
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
raise ProbeFailure(classification)
|
||||
|
||||
|
||||
class Load:
|
||||
"""A single bounded closed-loop HTTPS load client with stable actors."""
|
||||
def __init__(self, base, ca, actor, chat, rate, started=None):
|
||||
self.client = Client(base, str(ca), timeout=3)
|
||||
self.actor, self.chat, self.rate = actor, chat, rate
|
||||
self.stop = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.phase = 'baseline'
|
||||
self.started = started if started is not None else time.monotonic()
|
||||
self.samples = []
|
||||
self.thread = threading.Thread(target=self.run, daemon=True)
|
||||
|
||||
def set_phase(self, phase):
|
||||
with self.lock:
|
||||
self.phase = phase
|
||||
|
||||
def run(self):
|
||||
count = 0
|
||||
while not self.stop.is_set():
|
||||
started = time.monotonic()
|
||||
with self.lock:
|
||||
phase = self.phase
|
||||
try:
|
||||
result = self.client.message(self.actor, self.chat, 'lab7-load-' + str(count))
|
||||
status, error = result['status'], None
|
||||
except Failure as exc:
|
||||
# Client messages omit bodies/credentials; retain only status or
|
||||
# a fixed exception category, never arbitrary error text.
|
||||
text = str(exc)
|
||||
status = int(text.rsplit('received ', 1)[1]) if 'received ' in text and text.rsplit('received ', 1)[1].isdigit() else None
|
||||
error = 'http_' + str(status) if status else 'connection_or_tls'
|
||||
except Exception:
|
||||
status, error = None, 'client_exception'
|
||||
sample = {'at_seconds': round(started - self.started, 6), 'phase': phase,
|
||||
'latency_seconds': round(time.monotonic() - started, 6), 'status': status, 'error': error}
|
||||
with self.lock:
|
||||
self.samples.append(sample)
|
||||
count += 1
|
||||
self.stop.wait(max(0, 1 / self.rate - (time.monotonic() - started)))
|
||||
|
||||
def close(self):
|
||||
self.stop.set()
|
||||
self.thread.join(timeout=8)
|
||||
require(not self.thread.is_alive(), 'load_client_shutdown_timeout')
|
||||
|
||||
def refresh_trust(self, ca):
|
||||
# Only the load thread uses self.client; pointer swap retains actor/token
|
||||
# and creates a fresh CA-verified opener after trust-store publication.
|
||||
self.client = Client(self.client.base, str(ca), timeout=3)
|
||||
|
||||
def summary(self):
|
||||
with self.lock:
|
||||
samples = list(self.samples)
|
||||
phases = {}
|
||||
for name in dict.fromkeys(s['phase'] for s in samples):
|
||||
selected = [s for s in samples if s['phase'] == name]
|
||||
successes = [s for s in selected if s['status'] == 201]
|
||||
elapsed = max(0.001, selected[-1]['at_seconds'] + selected[-1]['latency_seconds'] - selected[0]['at_seconds'])
|
||||
failures = [s for s in selected if s['error']]
|
||||
phases[name] = {'requests': len(selected), 'successes': len(successes), 'errors': len(failures),
|
||||
'elapsed_seconds': elapsed, 'rps': len(successes) / elapsed,
|
||||
'p50_seconds': percentile([s['latency_seconds'] for s in successes], 0.50),
|
||||
'p95_seconds': percentile([s['latency_seconds'] for s in successes], 0.95),
|
||||
'errors_by_class': dict(collections.Counter(s['error'] for s in failures)),
|
||||
'failed_span_seconds': failures[-1]['at_seconds'] - failures[0]['at_seconds'] if failures else 0}
|
||||
outages = []
|
||||
began = None
|
||||
for sample in samples:
|
||||
if sample['error'] and began is None:
|
||||
began = sample
|
||||
if not sample['error'] and began is not None:
|
||||
outages.append({'phase_started': began['phase'], 'start_seconds': began['at_seconds'],
|
||||
'recovered_seconds': sample['at_seconds'],
|
||||
'observed_outage_seconds': sample['at_seconds'] - began['at_seconds'],
|
||||
'recovery_request_latency_seconds': sample['latency_seconds']})
|
||||
began = None
|
||||
if began is not None:
|
||||
outages.append({'phase_started': began['phase'], 'start_seconds': began['at_seconds'],
|
||||
'recovered_seconds': None, 'observed_outage_seconds': samples[-1]['at_seconds'] - began['at_seconds']})
|
||||
return {'phases': phases, 'raw_samples': samples, 'observed_outage_windows': outages,
|
||||
'outage_measurement': 'Failure-to-next-success sampling windows; resolution is the actual closed-loop request cadence.'}
|
||||
|
||||
|
||||
def free_ports(count):
|
||||
sockets = []
|
||||
try:
|
||||
for _ in range(count):
|
||||
sock = socket.socket()
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
sockets.append(sock)
|
||||
return [sock.getsockname()[1] for sock in sockets]
|
||||
finally:
|
||||
for sock in sockets:
|
||||
sock.close()
|
||||
|
||||
|
||||
def isolated_stand(directory, run_number):
|
||||
root = Path(directory)
|
||||
project = 'mtusi-lab7-track2-' + str(run_number) + '-' + uuid.uuid4().hex[:10]
|
||||
ingress, s3, bao, grafana, prometheus, loki, tempo, broker, stats = free_ports(9)
|
||||
env = {'OTEL_TRACES_SAMPLER': 'always_on', 'LAB7_OPERATOR_STATE': str(root / 'operator'),
|
||||
'BAO_PORT': str(bao), 'GRAFANA_PORT': str(grafana), 'PUBLIC_PORT': str(ingress), 'S3_PORT': str(s3),
|
||||
'PROMETHEUS_PORT': str(prometheus), 'LOKI_PORT': str(loki), 'TEMPO_PORT': str(tempo),
|
||||
'BROKER_MANAGEMENT_PORT': str(broker), 'LB_STATS_PORT': str(stats)}
|
||||
stand = Stand(project, root / 'secrets', 'https://localhost:' + str(ingress), env)
|
||||
override = root / 'compose-study.yaml'
|
||||
# Compose ports !override prevents the normal fixed loopback ports merging.
|
||||
# Namespace consumers do not receive ports; publication belongs to owners.
|
||||
owners = ('lb', 'seaweedfs', 'openbao', 'grafana', 'prometheus', 'loki', 'tempo', 'broker', 'otel-collector')
|
||||
mappings = {'lb': [f'127.0.0.1:{ingress}:8443'], 'seaweedfs': [f'127.0.0.1:{s3}:8333'],
|
||||
'openbao': [f'127.0.0.1:{bao}:8200'], 'grafana': [f'127.0.0.1:{grafana}:3000']}
|
||||
lines = ['services:']
|
||||
for owner in owners:
|
||||
lines += [' ' + owner + ':', ' ports: !override ' + json.dumps(mappings.get(owner, []))]
|
||||
for service in ('api', 'worker', 'relay'):
|
||||
lines += [' ' + service + ':', ' environment:', ' OTEL_TRACES_SAMPLER: "always_on"']
|
||||
override.write_text('\n'.join(lines) + '\n')
|
||||
stand.overrides.append(override)
|
||||
# securityctl subprocess Compose invocations must consume the same override.
|
||||
stand.env['LAB7_COMPOSE_OVERRIDE'] = str(override)
|
||||
return stand
|
||||
|
||||
|
||||
def server_serial(stand):
|
||||
result = stand.probe('tls', roles=('lb',), config={'host': 'api-replica', 'port': 8080, 'role': 'lb'})
|
||||
require(result.get('status') == 200 and result.get('serial'), 'fresh_api_tls_control_failed')
|
||||
return result['serial'].replace(':', '').upper()
|
||||
|
||||
|
||||
def api_ready(stand, ca):
|
||||
parsed = urllib.parse.urlsplit(stand.base_url)
|
||||
return http('localhost', parsed.port, 'GET', '/health/ready', ca=str(ca))['status'] == 200
|
||||
|
||||
|
||||
def retained(client, actor, chat, sentinel, attachment, content):
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
|
||||
found = False
|
||||
seen = set()
|
||||
for _ in range(100):
|
||||
page = client.call('GET', path, actor=actor, schema='MessagePage')['json']
|
||||
if any(m['id'] == sentinel['id'] and m['text'] == sentinel['text'] for m in page['items']):
|
||||
found = True
|
||||
break
|
||||
cursor = page['next_cursor']
|
||||
if cursor is None:
|
||||
break
|
||||
require(cursor not in seen, 'persisted_history_cursor_loop')
|
||||
seen.add(cursor)
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + urllib.parse.quote(cursor, safe='')
|
||||
require(found, 'persisted_message_sentinel_missing')
|
||||
got = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=actor)['bytes']
|
||||
require(hashlib.sha256(got).digest() == hashlib.sha256(content).digest(), 'persisted_attachment_sentinel_changed')
|
||||
return {'user_id': actor['id'], 'chat_id': chat['id'], 'message_id': sentinel['id'], 'attachment_id': attachment['id'],
|
||||
'attachment_sha256': hashlib.sha256(content).hexdigest()}
|
||||
|
||||
|
||||
def resume_negative(stand, identity, mutate, control_root, expect_detail=''):
|
||||
control = Path(control_root)
|
||||
control.mkdir(mode=0o700)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(stand.probe, 'session', roles=('operator',),
|
||||
config={'role': 'oldlb', 'host': 'api-replica', 'port': 8080, 'wait_seconds': 480},
|
||||
extra_mounts=((identity, '/pki/oldlb'),), control_dir=control, timeout=540)
|
||||
try:
|
||||
until(lambda: (control / 'armed').exists() or (future.done() and future.result()), deadline=45,
|
||||
classification='resumption_probe_not_armed')
|
||||
mutate()
|
||||
finally:
|
||||
(control / 'proceed').write_text('go')
|
||||
result = future.result(timeout=240)
|
||||
require(all(x['classification'] == 'tls_certificate_rejected' for x in result['after']),
|
||||
'old_identity_fresh_or_resumed_accepted')
|
||||
if expect_detail:
|
||||
require(all(expect_detail.upper() in (x.get('detail') or '').upper() for x in result['after']),
|
||||
'old_identity_rejected_for_unexpected_reason', expect_detail)
|
||||
return result
|
||||
|
||||
|
||||
def run_study(args, repetition, directory):
|
||||
stand = isolated_stand(directory, repetition)
|
||||
ca = stand.secrets / 'pki/operator/current/ca.crt'
|
||||
actions, errors = [], []
|
||||
load, watcher = None, None
|
||||
started = time.monotonic()
|
||||
started_at = dt.datetime.now(dt.timezone.utc).isoformat()
|
||||
stage = 'start'
|
||||
|
||||
def mark(name):
|
||||
nonlocal stage
|
||||
stage = name
|
||||
|
||||
def action(name, fn):
|
||||
nonlocal stage
|
||||
stage = name
|
||||
before = time.monotonic()
|
||||
if load:
|
||||
load.set_phase(name)
|
||||
result = fn()
|
||||
actions.append({'phase': name, 'at_seconds': before - started, 'seconds': time.monotonic() - before, 'result': result or {}})
|
||||
return result
|
||||
try:
|
||||
# No image build, and never bootstrap an existing project/namespace.
|
||||
require(not stand.containers(), 'isolated_project_already_exists')
|
||||
action('bootstrap', lambda: stand.security('bootstrap', timeout=300))
|
||||
action('startup', lambda: stand.security('up', timeout=360))
|
||||
stand.compose('up', '-d', '--no-build', '--scale', 'api=2', timeout=240)
|
||||
until(lambda: api_ready(stand, ca), deadline=120)
|
||||
client = Client(stand.base_url, str(ca), timeout=5)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
attachment = client.wait_ready(alice, attachment, wait_seconds=120)
|
||||
sentinel = client.message(alice, chat, 'lab7-persisted-' + uuid.uuid4().hex)['json']
|
||||
image_ids = sorted(c['Image'] for c in stand.containers('api') + stand.containers('worker'))
|
||||
action('initial_native_tls_control', lambda: {'serial_number': server_serial(stand)})
|
||||
action('initial_namespace_isolation', lambda: isolation(stand))
|
||||
load = Load(stand.base_url, ca, alice, chat, args.rate, started=started)
|
||||
load.thread.start()
|
||||
action('baseline', lambda: time.sleep(args.duration))
|
||||
baseline = load.summary()['phases'].get('baseline', {})
|
||||
require(baseline.get('successes', 0) > 0 and baseline.get('errors', 0) == 0, 'baseline_not_healthy')
|
||||
|
||||
def renewal():
|
||||
nonlocal watcher
|
||||
stand.security('issue', 'api', '--ttl', '20s')
|
||||
original = current_api_certificate(stand)
|
||||
old_expiry = original['expires_unix']
|
||||
until(lambda: server_serial(stand) == original['serial_number'], deadline=10)
|
||||
# Start independent cert-auth watcher at half of remaining lifetime.
|
||||
time.sleep(max(0, (old_expiry - time.time()) / 2))
|
||||
watcher = subprocess.Popen([sys.executable, 'scripts/securityctl.py', 'renew', 'api', '--ttl', '20s', '--watch', '--interval', '1'],
|
||||
cwd=ROOT, env={**os.environ, **stand.env}, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
seen = {original['serial_number']}
|
||||
records = [original]
|
||||
end = time.monotonic() + max(60, args.duration)
|
||||
while time.monotonic() < end:
|
||||
require(watcher.poll() is None, 'leaf_renew_watcher_exited')
|
||||
current = current_api_certificate(stand)
|
||||
if current['serial_number'] not in seen:
|
||||
# A polling timestamp is not the publication timestamp.
|
||||
# Prove adoption on fresh TLS and continuity past old expiry.
|
||||
until(lambda: server_serial(stand) == current['serial_number'],
|
||||
deadline=5, classification='published_leaf_not_used_on_fresh_tls')
|
||||
seen.add(current['serial_number'])
|
||||
records.append(current)
|
||||
time.sleep(0.5)
|
||||
require(len(seen) >= 3 and time.time() > old_expiry, 'renewal_not_repeated_before_old_expiry')
|
||||
require(api_ready(stand, ca), 'api_stopped_at_old_certificate_expiry')
|
||||
return {'original_expiry': original['not_after'], 'leaf_versions': records,
|
||||
'replacement_count': len(seen) - 1, 'old_expiry_survived': True}
|
||||
action('leaf_renewal', renewal)
|
||||
require(load.summary()['phases']['leaf_renewal']['errors'] == 0, 'renewal_load_interrupted')
|
||||
|
||||
def expiry():
|
||||
nonlocal watcher
|
||||
watcher.terminate()
|
||||
try:
|
||||
watcher.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
watcher.kill()
|
||||
watcher.wait(timeout=5)
|
||||
watcher = None
|
||||
last = current_api_certificate(stand)
|
||||
before = {c['Id']: c.get('RestartCount', 0) for c in stand.containers('api')}
|
||||
time.sleep(max(0, last['expires_unix'] - time.time() + 1))
|
||||
require(not api_ready(stand, ca), 'expired_api_remains_ready')
|
||||
# The process may be in restart policy after bounded drain. A
|
||||
# restart count is evidence of exit, not a fabricated state check.
|
||||
def exited():
|
||||
state = stand.containers('api')
|
||||
return state and all(not c['State']['Running'] or c.get('RestartCount', 0) > before.get(c['Id'], 0) for c in state)
|
||||
remaining = max(0.1, last['expires_unix'] + 29 - time.time())
|
||||
until(exited, deadline=remaining, classification='expired_api_did_not_exit_within_shutdown_bound')
|
||||
time.sleep(2)
|
||||
require(not api_ready(stand, ca), 'expired_api_reopened_admission')
|
||||
return {'expired_leaf': last, 'ready_closed': True, 'bounded_process_exit': True,
|
||||
'shutdown_deadline_unix': last['expires_unix'] + 29, 'total_outage_not_failover': True}
|
||||
action('intentional_expiry', expiry)
|
||||
require(load.summary()['phases']['intentional_expiry']['errors'] > 0, 'expiry_outage_not_exercised')
|
||||
|
||||
def recover():
|
||||
before = time.monotonic()
|
||||
stand.security('issue', 'api', '--ttl', '1h')
|
||||
stand.compose('up', '-d', '--no-build', '--no-deps', '--force-recreate', '--scale', 'api=2', 'api', timeout=150)
|
||||
until(lambda: api_ready(stand, ca), deadline=90)
|
||||
return {'recovery_seconds': time.monotonic() - before, 'retained': retained(client, alice, chat, sentinel, attachment, content)}
|
||||
action('expiry_recovery', recover)
|
||||
action('recovery_control', lambda: time.sleep(args.duration))
|
||||
|
||||
def sealed_bao():
|
||||
before = time.monotonic()
|
||||
stand.security('seal')
|
||||
until(lambda: not api_ready(stand, ca), deadline=65,
|
||||
classification='sealed_bao_did_not_close_admission')
|
||||
time.sleep(2)
|
||||
require(not api_ready(stand, ca), 'sealed_bao_reopened_admission')
|
||||
return {'admission_closed_seconds': time.monotonic() - before,
|
||||
'max_authorization_freshness_seconds': 60, 'ready_closed': True}
|
||||
action('sealed_bao', sealed_bao)
|
||||
require(load.summary()['phases']['sealed_bao']['errors'] > 0, 'sealed_bao_outage_not_exercised')
|
||||
|
||||
def unseal_recovery():
|
||||
before = time.monotonic()
|
||||
stand.security('unseal')
|
||||
stand.compose('up', '-d', '--no-build', '--no-deps', 'api', 'worker', 'relay', timeout=150)
|
||||
until(lambda: api_ready(stand, ca), deadline=90)
|
||||
return {'recovery_seconds': time.monotonic() - before,
|
||||
'retained': retained(client, alice, chat, sentinel, attachment, content)}
|
||||
action('sealed_bao_recovery', unseal_recovery)
|
||||
action('unsealed_recovery_control', lambda: time.sleep(args.duration))
|
||||
require(load.summary()['phases']['unsealed_recovery_control']['errors'] == 0,
|
||||
'unsealed_bao_not_recovered')
|
||||
|
||||
def revoke():
|
||||
old = snapshot(stand, 'lb', Path(directory) / 'revoke-private')
|
||||
metadata = certificate(old / 'current/tls.crt')
|
||||
def mutation():
|
||||
stand.security('issue', 'lb', '--ttl', '1h')
|
||||
stand.security('revoke', 'lb', '--serial', metadata['serial_number'])
|
||||
result = resume_negative(stand, old, mutation, Path(directory) / 'revoke-control')
|
||||
until(lambda: api_ready(stand, ca), deadline=90)
|
||||
return {'revoked_serial': metadata['serial_number'], 'old_identity': result, 'fresh_current_serial': server_serial(stand)}
|
||||
(Path(directory) / 'revoke-private').mkdir(mode=0o700)
|
||||
action('lb_leaf_rotate_revoke', revoke)
|
||||
|
||||
def rotate_secret():
|
||||
secret_path = stand.secrets / 'backends/credentials.json'
|
||||
old = json.loads(secret_path.read_text())
|
||||
# Old material lives only in private temporary operator state; not
|
||||
# stdout, argv, image, logs, or evidence. Only worker key is copied.
|
||||
oldfile = Path(directory) / 'old-worker-credentials.json'
|
||||
oldfile.write_text(json.dumps({'s3': {'worker': old['s3']['worker']}}))
|
||||
oldfile.chmod(0o600)
|
||||
key = 'attachments/lab7-rotation-missing-' + uuid.uuid4().hex
|
||||
control = stand.probe('s3', roles=('operator',), credentials=True,
|
||||
config={'single': True, 'role': 'worker', 'key': key})
|
||||
require(control.get('status') == 404, 'old_s3_credential_control_not_authorized')
|
||||
stand.security('rotate-secret', 'worker', timeout=180)
|
||||
denied = stand.probe('s3', roles=('operator',), extra_mounts=((oldfile, '/old-credentials.json'),),
|
||||
config={'credentials': '/old-credentials.json', 'single': True, 'role': 'worker', 'key': key})
|
||||
require(denied.get('status') == 403, 'old_worker_s3_credential_not_403')
|
||||
fresh, _ = client.attachment(alice, chat)
|
||||
fresh = client.wait_ready(alice, fresh, wait_seconds=120)
|
||||
oldfile.unlink()
|
||||
return {'old_credential_status': 403, 'new_worker_attachment_id': fresh['id'], 'status': fresh['status']}
|
||||
action('worker_s3_secret_rotation', rotate_secret)
|
||||
|
||||
def warm_pipeline(phase):
|
||||
# Every CA phase restarts stores and both application identities.
|
||||
# Retry only transport cold starts; a failed attachment is a real
|
||||
# pipeline defect and must fail the run immediately.
|
||||
started = time.monotonic()
|
||||
deadline = started + 180
|
||||
errors = []
|
||||
attempts = 0
|
||||
while time.monotonic() < deadline:
|
||||
attempts += 1
|
||||
try:
|
||||
probe = Client(stand.base_url, str(ca), timeout=15)
|
||||
ready, _ = probe.attachment(alice, chat)
|
||||
probe.wait_ready(alice, ready, wait_seconds=60)
|
||||
return {'phase': phase, 'attempts': attempts,
|
||||
'seconds': round(time.monotonic() - started, 3), 'errors': errors}
|
||||
except Failure as exc:
|
||||
text = str(exc)
|
||||
errors.append(text)
|
||||
if 'attachment reached failed' in text or 'incorrect upload status' in text:
|
||||
raise ProbeFailure('attachment_pipeline_failed', phase + ':' + text[:300]) from None
|
||||
if time.monotonic() >= deadline:
|
||||
raise ProbeFailure('attachment_pipeline_not_recovered',
|
||||
phase + ':' + str(attempts) + ':' + text[:240]) from None
|
||||
time.sleep(2)
|
||||
raise ProbeFailure('attachment_pipeline_not_recovered', phase + ':' + str(attempts))
|
||||
|
||||
def rollover():
|
||||
old = snapshot(stand, 'lb', Path(directory) / 'ca-private')
|
||||
metadata = certificate(old / 'current/tls.crt')
|
||||
warm_results = []
|
||||
mark('ca_prepare')
|
||||
prepare_result = stand.security('ca-rollover', '--phase', 'prepare', timeout=300)
|
||||
load.refresh_trust(ca)
|
||||
warm_results.append(warm_pipeline('prepare'))
|
||||
mark('ca_overlap_probe')
|
||||
old_control = stand.probe('tls', roles=('operator',), extra_mounts=((old, '/pki/oldlb'),),
|
||||
config={'role': 'oldlb', 'host': 'api-replica', 'port': 8080, 'ca': '/pki/operator/current/ca.crt'})
|
||||
require(old_control.get('status') == 200, 'overlap_old_identity_not_valid')
|
||||
mark('ca_issue')
|
||||
issue_result = stand.security('ca-rollover', '--phase', 'issue', timeout=360)
|
||||
warm_results.append(warm_pipeline('issue'))
|
||||
load.refresh_trust(ca)
|
||||
mark('ca_new_replica_probe')
|
||||
new_control = server_serial(stand)
|
||||
again = stand.probe('tls', roles=('operator',), extra_mounts=((old, '/pki/oldlb'),),
|
||||
config={'role': 'oldlb', 'host': 'api-replica', 'port': 8080, 'ca': '/pki/operator/current/ca.crt'})
|
||||
require(again.get('status') == 200, 'overlap_old_identity_lost_before_retire')
|
||||
mark('ca_retire')
|
||||
retire_result = {}
|
||||
|
||||
def retire():
|
||||
retire_result.update(stand.security('ca-rollover', '--phase', 'retire', timeout=360))
|
||||
|
||||
result = resume_negative(stand, old, retire, Path(directory) / 'ca-control',
|
||||
expect_detail='UNKNOWN_CA')
|
||||
load.refresh_trust(ca)
|
||||
mark('ca_retire_ready')
|
||||
until(lambda: api_ready(stand, ca), deadline=120)
|
||||
warm_results.append(warm_pipeline('retire'))
|
||||
mark('ca_attachment')
|
||||
current = Client(stand.base_url, str(ca), timeout=10)
|
||||
fresh, _ = current.attachment(alice, chat)
|
||||
fresh = current.wait_ready(alice, fresh, wait_seconds=120)
|
||||
mark('ca_backends')
|
||||
bao = stand.probe('bao', roles=('api',), config={'role': 'api'})
|
||||
redis = stand.probe('redis', roles=('api',), credentials=True, config={'role': 'api'})
|
||||
mark('ca_telemetry')
|
||||
telemetry = {}
|
||||
for name, host, port, role, method, path, body in (
|
||||
('api_otlp', 'otel-collector', 4318, 'api', 'POST', '/v1/traces', '{}'),
|
||||
('grafana_prometheus', 'prometheus', 9090, 'grafana', 'GET', '/api/v1/query?query=1', ''),
|
||||
('grafana_loki', 'loki', 3100, 'grafana', 'GET', '/loki/api/v1/query?query=vector%281%29', ''),
|
||||
('prometheus_collector_scrape', 'otel-collector', 8888, 'prometheus', 'GET', '/metrics', '')):
|
||||
response = stand.probe('tls', roles=(role,), config={'host': host, 'port': port, 'role': role,
|
||||
'method': method, 'path': path, 'body': body, 'headers': {'Content-Type': 'application/json'}}, network='observability')
|
||||
require(response.get('status') == 200, 'new_ca_telemetry_path_failed', name)
|
||||
telemetry[name] = response
|
||||
mark('ca_isolation')
|
||||
namespace = isolation(stand)
|
||||
mark('ca_retained')
|
||||
return {'old_leaf_serial': metadata['serial_number'], 'overlap_old': old_control, 'overlap_new_api_serial': new_control,
|
||||
'retired_old_identity': result, 'prepare': prepare_result, 'issue': issue_result,
|
||||
'retire': retire_result, 'warm_pipeline': warm_results,
|
||||
'new_pipeline_attachment_id': fresh['id'], 'new_bao_policy': bao,
|
||||
'new_redis_cache_path': redis, 'new_telemetry_paths': telemetry, 'new_namespace_isolation': namespace,
|
||||
'retained': retained(current, alice, chat, sentinel, attachment, content)}
|
||||
(Path(directory) / 'ca-private').mkdir(mode=0o700)
|
||||
action('ca_prepare_issue_retire', rollover)
|
||||
action('final_recovery_control', lambda: time.sleep(args.duration))
|
||||
require(load.summary()['phases']['final_recovery_control']['errors'] == 0, 'new_trust_paths_not_recovered')
|
||||
require(sorted(c['Image'] for c in stand.containers('api') + stand.containers('worker')) == image_ids, 'study_rebuilt_or_changed_application_image')
|
||||
action('bao_audit', lambda: stand.security('audit-summary'))
|
||||
except ProbeFailure as exc:
|
||||
errors.append({'classification': exc.classification, 'stage': stage, 'detail': exc.detail})
|
||||
except Failure as exc:
|
||||
# Public client errors deliberately omit credentials and query strings.
|
||||
errors.append({'classification': 'public_api_contract_failure', 'stage': stage, 'detail': str(exc)})
|
||||
except Exception as exc:
|
||||
errors.append({'classification': 'study_exception', 'type': type(exc).__name__})
|
||||
finally:
|
||||
if watcher and watcher.poll() is None:
|
||||
watcher.terminate()
|
||||
try:
|
||||
watcher.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
watcher.kill()
|
||||
watcher.wait(timeout=5)
|
||||
if load:
|
||||
try:
|
||||
load.close()
|
||||
except ProbeFailure as exc:
|
||||
errors.append({'classification': exc.classification})
|
||||
# Destructive cleanup is confined to this generated namespace; never
|
||||
# default stand, retained lab6 volumes, or user-supplied projects.
|
||||
require(stand.project.startswith('mtusi-lab7-track2-') and str(stand.secrets).startswith(str(Path(directory))), 'unsafe_cleanup_namespace')
|
||||
result = stand.compose('down', '--volumes', '--remove-orphans', timeout=180, check=False)
|
||||
if result.returncode:
|
||||
errors.append({'classification': 'isolated_project_cleanup_failed'})
|
||||
return {'repetition': repetition, 'project': stand.project, 'passed': not errors, 'seconds': time.monotonic() - started, 'started_at': started_at,
|
||||
'actions': actions, 'load': load.summary() if load else {'raw_samples': [], 'phases': {}}, 'errors': errors}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--reps', type=int, default=3)
|
||||
parser.add_argument('--duration', type=float, default=30, help='seconds per baseline/recovery control phase; renewal is at least60s')
|
||||
parser.add_argument('--rate', type=float, default=2, help='single-client offered messages per second')
|
||||
parser.add_argument('--output', type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
require(args.reps >= 3 and args.duration >= 5 and 0 < args.rate <= 10, 'invalid_repeatability_parameters')
|
||||
runs = []
|
||||
for repetition in range(1, args.reps + 1):
|
||||
with temporary_directory(prefix='mtusi-lab7-track2-private-') as directory:
|
||||
Path(directory).chmod(0o700)
|
||||
runs.append(run_study(args, repetition, directory))
|
||||
result = {'study': 'lab7-track2', 'timestamp': dt.datetime.now(dt.timezone.utc).isoformat(), 'runs': runs,
|
||||
'completed_repetitions': len(runs), 'required_repetitions': args.reps,
|
||||
'passed': len(runs) == args.reps and all(run['passed'] for run in runs),
|
||||
'configuration': {'offered_rate': args.rate, 'control_seconds': args.duration, 'renewal_ttl_seconds': 20,
|
||||
'load_clients': 1, 'api_replicas': 2, 'trace_sampler': 'always_on', 'request_counter_sampling': 'every attempt'},
|
||||
'limitations': ['Local synthetic stand; single-node Bao/PostgreSQL/S3/broker and Docker Desktop resource limits.',
|
||||
'Single closed-loop client is a lifecycle continuity probe, not a capacity or open-loop benchmark.',
|
||||
'Both API leaves intentionally expire: this measures total-outage fail-closed recovery, not A/B failover.',
|
||||
'Fresh connections and explicit resumption attempts tested; servers with tickets disabled cannot positively resume.',
|
||||
'Temporary old keys/credentials are deleted with private operator state and never written into evidence.']}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(result, indent=2, sort_keys=True) + '\n')
|
||||
print(json.dumps({'study': result['study'], 'passed': result['passed'], 'completed_repetitions': len(runs),
|
||||
'output': str(args.output), 'failed_repetitions': [r['repetition'] for r in runs if not r['passed']]}, sort_keys=True))
|
||||
return 0 if result['passed'] else 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except ProbeFailure as exc:
|
||||
print(json.dumps({'passed': False, 'classification': exc.classification, 'detail': exc.detail}))
|
||||
raise SystemExit(1)
|
||||
except Exception as exc:
|
||||
print(json.dumps({'passed': False, 'classification': 'driver_exception', 'type': type(exc).__name__}))
|
||||
raise SystemExit(1)
|
||||
Executable
+114
@@ -0,0 +1,114 @@
|
||||
#!/bin/sh
|
||||
# Verify LB exclusion of a live API whose native TLS PostgreSQL path has failed.
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
from collections import Counter
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
sys.path.insert(0, str(Path.cwd() / 'tests'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url
|
||||
from client import Client
|
||||
|
||||
environment = Environment()
|
||||
client = Client(BASE_URL, CA_FILE, timeout=5)
|
||||
output = Path(os.environ.get('OUT', 'evidence/lab5/lb-readiness-detail.txt'))
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
replicas = environment.compose('ps', '-q', 'api').stdout.split()
|
||||
if len(replicas) < 2:
|
||||
raise SystemExit('readiness exclusion needs two healthy Compose API replicas')
|
||||
networks = json.loads(environment.run(['docker', 'inspect', '--format',
|
||||
'{{json .NetworkSettings.Networks}}', replicas[0]]).stdout)
|
||||
if len(networks) != 1:
|
||||
raise SystemExit('expected exactly one API network for the isolated TLS tunnel')
|
||||
network = next(iter(networks))
|
||||
prefix = environment.project + '-readiness-' + uuid.uuid4().hex[:8]
|
||||
proxy, candidate = prefix + '-tunnel', prefix + '-api'
|
||||
stats_url = os.environ.get('STATS', 'https://localhost:' + environment.value('LB_STATS_PORT', '8404') + '/stats;csv')
|
||||
log = []
|
||||
|
||||
|
||||
def stats():
|
||||
with open_url(stats_url, operator=True) as response:
|
||||
rows = csv.DictReader(io.StringIO(response.read().decode().replace('# ', '', 1)))
|
||||
return {row['svname']: row['status'] for row in rows
|
||||
if row['pxname'].startswith('api') and row['svname'] not in ('BACKEND', 'FRONTEND')}
|
||||
|
||||
|
||||
def local_status():
|
||||
result = environment.run(['docker', 'exec', candidate, 'wget', '-qO-', '-S', '-T', '3',
|
||||
'http://127.0.0.1:8084/health/ready'], check=False)
|
||||
matches = re.findall(r'HTTP/\S+\s+(\d{3})', result.stderr)
|
||||
return int(matches[-1]) if matches else None
|
||||
|
||||
|
||||
def wait(predicate, description, seconds=60):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(description)
|
||||
|
||||
|
||||
def observed():
|
||||
return Counter(client.call('GET', '/health/live', schema='Health')['headers']['X-Instance-Id']
|
||||
for _ in range(int(os.environ.get('REQUESTS', '40'))))
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-readiness-') as temporary:
|
||||
try:
|
||||
baseline = stats()
|
||||
log.append('baseline instances: ' + json.dumps(observed()))
|
||||
# This network-only tunnel forwards encrypted PostgreSQL bytes unchanged.
|
||||
# It has no credentials, TLS termination, API listener or host-published ports.
|
||||
environment.run(['docker', 'run', '-d', '--name', proxy, '--network', network,
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true', '--read-only',
|
||||
'alpine/socat@sha256:fb3862c949af7c79996d0e514ee96128644d840835ed5368eeecb14a869de361',
|
||||
'tcp-listen:5432,fork,reuseaddr', 'tcp-connect:postgres:5432'])
|
||||
proxy_networks = json.loads(environment.run(['docker', 'inspect', '--format',
|
||||
'{{json .NetworkSettings.Networks}}', proxy]).stdout)
|
||||
proxy_ip = proxy_networks[network]['IPAddress']
|
||||
override = Path(temporary) / 'compose.json'
|
||||
# Preserve the real postgres hostname/SAN and Bao-supplied role credentials.
|
||||
override.write_text(json.dumps({'services': {'api': {'extra_hosts': ['postgres:' + proxy_ip]}}}))
|
||||
environment.compose('-f', str(override), 'run', '-d', '--no-deps', '--use-aliases',
|
||||
'--name', candidate, 'api')
|
||||
wait(lambda: local_status() == 200, 'candidate did not become ready')
|
||||
slot = wait(lambda: next((name for name, status in stats().items()
|
||||
if status.startswith('UP') and not baseline.get(name, '').startswith('UP')), None),
|
||||
'candidate did not enter the LB rotation')
|
||||
hostname = environment.run(['docker', 'inspect', '--format', '{{.Config.Hostname}}', candidate]).stdout.strip()
|
||||
log.append('candidate ready: instance=' + hostname + ' slot=' + slot)
|
||||
environment.run(['docker', 'stop', proxy])
|
||||
wait(lambda: local_status() == 503, 'candidate did not become not-ready')
|
||||
state = environment.run(['docker', 'inspect', '--format', '{{.State.Status}}', candidate]).stdout.strip()
|
||||
if state != 'running':
|
||||
raise RuntimeError('candidate stopped instead of reporting not-ready')
|
||||
wait(lambda: stats().get(slot, '').startswith('DOWN'), 'LB did not exclude the not-ready candidate')
|
||||
after = observed()
|
||||
if hostname in after:
|
||||
raise RuntimeError('LB routed a request to the not-ready candidate')
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
for index in range(10):
|
||||
client.message(alice, chat, 'readiness-exclusion-' + str(index))
|
||||
log += ['candidate alive/readiness503; LB slot DOWN', 'during outage instances: ' + json.dumps(after),
|
||||
'business writes through remaining replicas: 10']
|
||||
finally:
|
||||
environment.run(['docker', 'rm', '-f', candidate, proxy], check=False)
|
||||
output.write_text('\n'.join(log) + '\n')
|
||||
print('\n'.join(log))
|
||||
PY
|
||||
Executable
+65
@@ -0,0 +1,65 @@
|
||||
#!/bin/sh
|
||||
# Compare the same verified HTTPS load profile through host forwarding and LB namespace.
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE
|
||||
|
||||
environment = Environment()
|
||||
output = Path(os.environ.get('OUT', 'evidence/path-overhead')).resolve()
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
duration = os.environ.get('DURATION', '60')
|
||||
concurrency = os.environ.get('CONCURRENCY', '8')
|
||||
warmup = os.environ.get('WARMUP', '15')
|
||||
image = os.environ.get('CLIENT_IMAGE', 'python:3.12-alpine')
|
||||
lbs = environment.compose('ps', '-q', 'lb').stdout.split()
|
||||
if len(lbs) != 1:
|
||||
raise SystemExit('expected one running Compose LB')
|
||||
ca = Path(CA_FILE).resolve(strict=True)
|
||||
|
||||
|
||||
def run_profile(location, seconds, destination=None):
|
||||
if location == 'outside':
|
||||
command = [sys.executable, str(ROOT / 'tests/load.py'), '--base-url', BASE_URL,
|
||||
'--ca-file', str(ca)]
|
||||
else:
|
||||
# Only public tests, contract and CA are mounted; no operator private key.
|
||||
command = ['docker', 'run', '--rm', '--network', 'container:' + lbs[0],
|
||||
'--cap-drop', 'ALL', '--security-opt', 'no-new-privileges:true',
|
||||
'--read-only', '--tmpfs', '/tmp',
|
||||
'--mount', f'type=bind,source={ROOT / "tests"},target=/repo/tests,readonly',
|
||||
'--mount', f'type=bind,source={ROOT / "contracts"},target=/repo/contracts,readonly',
|
||||
'--mount', f'type=bind,source={ROOT / "lab.json"},target=/repo/lab.json,readonly',
|
||||
'--mount', f'type=bind,source={ca},target=/ca.crt,readonly',
|
||||
'--mount', f'type=bind,source={output},target=/out',
|
||||
'-e', 'NO_PROXY=localhost,127.0.0.1', '-e', 'PYTHONDONTWRITEBYTECODE=1',
|
||||
image, 'python', '/repo/tests/load.py', '--base-url', 'https://localhost:8443',
|
||||
'--ca-file', '/ca.crt']
|
||||
command += ['--duration', seconds, '--concurrency', concurrency]
|
||||
if destination:
|
||||
command += ['--output', str(output / destination) if location == 'outside' else '/out/' + destination]
|
||||
return subprocess.run(command, cwd=ROOT, env=environment.process_env,
|
||||
capture_output=True, text=True, check=True)
|
||||
|
||||
|
||||
summary = [time.strftime('# generated: %Y-%m-%dT%H:%M:%SZ', time.gmtime()),
|
||||
'host URL: ' + BASE_URL, 'inside URL: https://localhost:8443 (LB network namespace)',
|
||||
'client image: ' + image, 'VM generator shares the VM CPU budget with the stand']
|
||||
for location in ('outside', 'inside'):
|
||||
run_profile(location, warmup)
|
||||
result = run_profile(location, duration, 'load-' + location + '.json')
|
||||
(output / (location + '.txt')).write_text(result.stdout + result.stderr)
|
||||
summary.append(location + ': ' + json.dumps(json.loads((output / ('load-' + location + '.json')).read_text())))
|
||||
(output / 'summary.txt').write_text('\n'.join(summary) + '\n')
|
||||
print('\n'.join(summary))
|
||||
PY
|
||||
@@ -0,0 +1,135 @@
|
||||
#!/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
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'student-tests'))
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts'))
|
||||
from tests_helpers import compose as compose_operator, redis
|
||||
from lab7_http import BASE_URL, open_url
|
||||
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']
|
||||
|
||||
BUDGET_MS = int(os.environ.get('OUTAGE_BUDGET_MS', '2000'))
|
||||
PARALLEL = int(os.environ.get('OUTAGE_PARALLEL', '30'))
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return compose_operator(*args)
|
||||
|
||||
|
||||
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:
|
||||
with open_url(req, timeout=10) as resp:
|
||||
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)
|
||||
|
||||
cursor = '0'
|
||||
stuck = set()
|
||||
while True:
|
||||
rows = redis('SCAN', cursor, 'MATCH', 'lock:*', 'COUNT', '1000').splitlines()
|
||||
assert rows and rows[0].isdigit(), 'operator Redis SCAN returned an invalid cursor'
|
||||
cursor = rows[0]
|
||||
stuck.update(rows[1:])
|
||||
if cursor == '0':
|
||||
break
|
||||
for key in stuck:
|
||||
ttl = redis('ttl', key)
|
||||
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'):
|
||||
compose_operator(action, 'redis', check=False)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except AssertionError as exc:
|
||||
print('FAIL: %s' % exc)
|
||||
sys.exit(1)
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
|
||||
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
|
||||
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
|
||||
# Allow operator unseal if required in lab7; do not print credentials.
|
||||
# Exit 0 only after the intended action; test waits for API readiness separately.
|
||||
printf '%s
|
||||
' 'TODO: implement restart.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Operator restart preserves every data volume, unseals Bao from protected
|
||||
# operator-local state and recreates shared-namespace consumers explicitly.
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
exec python3 "$ROOT_DIR/scripts/securityctl.py" restart
|
||||
Executable
+121
@@ -0,0 +1,121 @@
|
||||
#!/bin/sh
|
||||
# Secure Compose surge rollout: inherited API identity/config/hardening, one replica at a time.
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec "${PYTHON:-python3}" - "$@" <<'PY'
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path.cwd() / 'scripts'))
|
||||
sys.path.insert(0, str(Path.cwd() / 'tests'))
|
||||
from lab7_environment import Environment, ROOT
|
||||
from lab7_http import BASE_URL, CA_FILE, open_url
|
||||
from client import Client
|
||||
|
||||
environment = Environment()
|
||||
output = Path(os.environ.get('OUT', 'evidence/rolling-update'))
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
image = os.environ.get('IMAGE', 'mtusi-messenger:lab7')
|
||||
stats_url = os.environ.get('STATS', 'https://localhost:' + environment.value('LB_STATS_PORT', '8404') + '/stats;csv')
|
||||
replicas = environment.compose('ps', '-q', 'api').stdout.split()
|
||||
if len(replicas) < 2:
|
||||
raise SystemExit('rolling update requires at least two running API replicas')
|
||||
environment.run(['docker', 'image', 'inspect', image])
|
||||
client = Client(BASE_URL, CA_FILE, timeout=5)
|
||||
log = []
|
||||
surge = []
|
||||
loader = None
|
||||
|
||||
def rows():
|
||||
with open_url(stats_url, operator=True, ca_file=CA_FILE) as response:
|
||||
content = response.read().decode()
|
||||
return list(csv.DictReader(io.StringIO(content.replace('# ', '', 1))))
|
||||
|
||||
def up_slots():
|
||||
return sum(row['pxname'] == 'api_backend' and row['svname'] not in ('BACKEND', 'FRONTEND')
|
||||
and row['status'].startswith('UP') for row in rows())
|
||||
|
||||
def wait_slots(expected):
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if up_slots() == expected:
|
||||
client.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError('LB did not converge to %d healthy business slots' % expected)
|
||||
|
||||
def wait_container(container):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
result = environment.run(['docker', 'exec', container, 'wget', '-qO-', '-T', '3',
|
||||
'http://127.0.0.1:8084/health/ready'], check=False)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError('surge replica did not become locally ready')
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='lab7-rollout-') as temporary:
|
||||
override = Path(temporary) / 'compose.json'
|
||||
override.write_text(json.dumps({'services': {'api': {'image': image}}}))
|
||||
try:
|
||||
wait_slots(len(replicas))
|
||||
old_images = [environment.run(['docker', 'inspect', '--format', '{{.Image}}', container]).stdout.strip()
|
||||
for container in replicas]
|
||||
log.append('old image digests: ' + ', '.join(old_images))
|
||||
with (output / 'load.txt').open('w') as load_log:
|
||||
loader = subprocess.Popen(
|
||||
[sys.executable, str(ROOT / 'student-tests/rolling_update_load.py'),
|
||||
'--base-url', BASE_URL, '--ca-file', CA_FILE,
|
||||
'--duration', os.environ.get('DURATION', '60'),
|
||||
'--concurrency', os.environ.get('CONCURRENCY', '8'),
|
||||
'--output', str(output / 'load.json')],
|
||||
cwd=ROOT, env=environment.process_env, stdout=load_log, stderr=subprocess.STDOUT)
|
||||
for old in replicas:
|
||||
name = environment.project + '-rollout-' + uuid.uuid4().hex[:8]
|
||||
environment.compose('-f', str(override), 'run', '-d', '--no-deps', '--use-aliases',
|
||||
'--name', name, 'api')
|
||||
surge.append(name)
|
||||
wait_container(name)
|
||||
wait_slots(len(replicas) + 1)
|
||||
environment.run(['docker', 'stop', old])
|
||||
environment.run(['docker', 'rm', old])
|
||||
wait_slots(len(replicas))
|
||||
log.append('ready surge %s replaced %s; healthy slots=%d' % (name, old, up_slots()))
|
||||
result = loader.wait()
|
||||
if result:
|
||||
raise RuntimeError('load generator failed; inspect load.txt/load.json')
|
||||
environment.compose('-f', str(override), 'up', '-d', '--no-deps', '--scale',
|
||||
'api=' + str(len(replicas)), 'api')
|
||||
wait_slots(len(replicas) + len(surge))
|
||||
while surge:
|
||||
name = surge[0]
|
||||
environment.run(['docker', 'stop', name])
|
||||
environment.run(['docker', 'rm', name])
|
||||
surge.pop(0)
|
||||
wait_slots(len(replicas) + len(surge))
|
||||
log.append('Compose control restored; healthy slots=%d' % up_slots())
|
||||
finally:
|
||||
if loader is not None and loader.poll() is None:
|
||||
loader.terminate()
|
||||
loader.wait()
|
||||
# Restore regular replicas before removing any surviving surge capacity.
|
||||
environment.compose('-f', str(override), 'up', '-d', '--no-deps', '--scale',
|
||||
'api=' + str(len(replicas)), 'api', check=False)
|
||||
if surge:
|
||||
for container in environment.compose('ps', '-q', 'api').stdout.split():
|
||||
wait_container(container)
|
||||
for name in surge:
|
||||
environment.run(['docker', 'stop', name], check=False)
|
||||
environment.run(['docker', 'rm', name], check=False)
|
||||
(output / 'rolling-update.txt').write_text('\n'.join(log) + '\n')
|
||||
print('\n'.join(log))
|
||||
PY
|
||||
Executable
+859
@@ -0,0 +1,859 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reproducible operator bootstrap/renewal/rotation for the local lab7 stand.
|
||||
|
||||
Private root/unseal state is outside this checkout. No secret values are printed.
|
||||
All OpenBao calls verify CA and hostname; app roles authenticate independently.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from lab7_environment import BaoClient, Environment, OperationError, ROOT, ROLES, atomic_write
|
||||
from lab7_pki import PKI
|
||||
|
||||
GATEWAY_PAIRS = {
|
||||
'seaweedfs': ['s3'],
|
||||
'broker': ['broker-admin-tls'],
|
||||
'otel-collector': ['collector-tls'],
|
||||
'prometheus': ['prometheus-tls'],
|
||||
'loki': ['loki-tls'],
|
||||
'tempo': ['tempo-tls'],
|
||||
'grafana': ['grafana-tls'],
|
||||
}
|
||||
STORES = ['postgres', 'redis', 'seaweedfs', 'broker']
|
||||
TELEMETRY = ['otel-collector', 'prometheus', 'loki', 'tempo', 'grafana']
|
||||
|
||||
|
||||
def password_hash(password: str) -> str:
|
||||
salt = secrets.token_bytes(4)
|
||||
return base64.b64encode(salt + hashlib.sha256(salt + password.encode()).digest()).decode()
|
||||
|
||||
|
||||
def scram_verifier(password: str, iterations: int = 4096) -> str:
|
||||
"""Build a SCRAM-SHA-256 verifier so plaintext never enters SQL/logs."""
|
||||
salt = secrets.token_bytes(16)
|
||||
salted = hashlib.pbkdf2_hmac('sha256', password.encode(), salt, iterations)
|
||||
client_key = hmac.new(salted, b'Client Key', hashlib.sha256).digest()
|
||||
stored_key = hashlib.sha256(client_key).digest()
|
||||
server_key = hmac.new(salted, b'Server Key', hashlib.sha256).digest()
|
||||
encode = lambda value: base64.b64encode(value).decode()
|
||||
return 'SCRAM-SHA-256$%d:%s$%s:%s' % (iterations, encode(salt), encode(stored_key), encode(server_key))
|
||||
|
||||
|
||||
def service_policy(role: str) -> str:
|
||||
rules = [f'''path "pki/issue/{role}" {{ capabilities = ["create", "update"] }}''',
|
||||
'''path "auth/token/lookup-self" { capabilities = ["read"] }
|
||||
path "auth/token/renew-self" { capabilities = ["update"] }
|
||||
path "auth/token/revoke-self" { capabilities = ["update"] }''']
|
||||
if role in ('api', 'worker', 'relay'):
|
||||
rules.append(f'''path "secret/data/{role}" {{ capabilities = ["read"] }}''')
|
||||
return '\n'.join(rules) + '\n'
|
||||
|
||||
|
||||
def operator_policy() -> str:
|
||||
paths = {
|
||||
'secret/data/*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'secret/metadata/*': ['read', 'list', 'delete'],
|
||||
'pki/*': ['create', 'read', 'update', 'delete', 'list', 'sudo'],
|
||||
'auth/cert/certs/*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'auth/cert/crls/*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'sys/policies/acl/lab7-*': ['create', 'read', 'update', 'delete', 'list'],
|
||||
'sys/mounts': ['read'], 'sys/mounts/pki': ['create', 'read', 'update', 'sudo'],
|
||||
'sys/mounts/secret': ['create', 'read', 'update', 'sudo'],
|
||||
'sys/auth': ['read'], 'sys/auth/cert': ['create', 'read', 'update', 'sudo'],
|
||||
'sys/audit': ['read', 'sudo'], 'sys/audit/file': ['read', 'sudo'],
|
||||
'sys/seal': ['update', 'sudo'], 'auth/token/lookup-self': ['read'],
|
||||
'auth/token/renew-self': ['update'], 'auth/token/revoke-self': ['update'],
|
||||
}
|
||||
return '\n'.join('path ' + json.dumps(path) + ' { capabilities = ' +
|
||||
json.dumps(capabilities) + ' }' for path, capabilities in paths.items()) + '\n'
|
||||
|
||||
|
||||
class Controller:
|
||||
def __init__(self) -> None:
|
||||
self.env = Environment()
|
||||
self.pki = PKI(self.env)
|
||||
self.credentials_path = self.env.secrets / 'backends/credentials.json'
|
||||
self.init_path = self.env.state / 'operator-unseal.json'
|
||||
|
||||
def credentials(self) -> dict:
|
||||
values = self.env.read_json(self.credentials_path)
|
||||
if not values:
|
||||
values = {
|
||||
'postgres': {
|
||||
'operator': {'username': 'lab_operator', 'password': secrets.token_hex(32)},
|
||||
**{role: {'username': 'messenger_' + role, 'password': secrets.token_hex(32)}
|
||||
for role in ('api', 'worker', 'relay')},
|
||||
},
|
||||
'redis': {role: {'username': role, 'password': secrets.token_hex(32)}
|
||||
for role in ('cache', 'operator', 'health')},
|
||||
's3': {role: {'access_key': 'lab7' + role + secrets.token_hex(8),
|
||||
'secret_key': secrets.token_hex(32)}
|
||||
for role in ('operator', 'api', 'worker')},
|
||||
'grafana': {'password': secrets.token_hex(32)},
|
||||
'broker': {'operator': {'password': secrets.token_hex(32)}},
|
||||
}
|
||||
self.env.private_json(self.credentials_path, values)
|
||||
for family in values.values():
|
||||
if isinstance(family, dict):
|
||||
for record in family.values():
|
||||
if isinstance(record, dict):
|
||||
self.env.redactions.update(str(value) for key, value in record.items()
|
||||
if key in ('password', 'secret_key', 'access_key'))
|
||||
self.env.redactions.add(values['grafana']['password'])
|
||||
return values
|
||||
|
||||
def write_file(self, relative: str, content: str) -> None:
|
||||
destination = self.env.secrets / relative
|
||||
destination.parent.mkdir(parents=True, exist_ok=True, mode=0o750)
|
||||
os.chmod(destination.parent, 0o750)
|
||||
atomic_write(destination, content, 0o640)
|
||||
|
||||
def backend_files(self) -> None:
|
||||
credentials = self.credentials()
|
||||
operator = credentials['postgres']['operator']
|
||||
self.write_file('bootstrap/migrate/postgres-password', operator['password'] + '\n')
|
||||
self.write_file('backends/postgres/operator-password', operator['password'] + '\n')
|
||||
for role, prefix in (('operator', 's3-admin'), ('api', 's3-app')):
|
||||
values = credentials['s3'][role]
|
||||
self.write_file('bootstrap/s3/' + prefix + '-access-key', values['access_key'] + '\n')
|
||||
self.write_file('bootstrap/s3/' + prefix + '-secret-key', values['secret_key'] + '\n')
|
||||
identity_config = json.loads((ROOT / 'infra/s3/s3.json').read_text())
|
||||
bucket = self.env.value('S3_BUCKET', 'messenger-attachments')
|
||||
for identity in identity_config['identities']:
|
||||
values = credentials['s3'][identity['name']]
|
||||
identity['credentials'] = [{'accessKey': values['access_key'], 'secretKey': values['secret_key']}]
|
||||
identity['actions'] = [action.replace('messenger-attachments', bucket)
|
||||
for action in identity['actions']]
|
||||
self.write_file('backends/s3/s3.json', json.dumps(identity_config, indent=2) + '\n')
|
||||
cache = credentials['redis']['cache']['password']
|
||||
operator_password = credentials['redis']['operator']['password']
|
||||
health = credentials['redis']['health']['password']
|
||||
acl = f'''user default off
|
||||
user cache on >{cache} ~chat_list:* ~lock:chat_list:* +get +set +del +ping +eval +evalsha +script|load
|
||||
user health on >{health} +ping
|
||||
user operator on >{operator_password} ~* &* +@all
|
||||
'''
|
||||
self.write_file('backends/redis/users.acl', acl)
|
||||
self.write_file('backends/redis/health-password', health + '\n')
|
||||
self.write_file('backends/redis/operator-password', operator_password + '\n')
|
||||
self.write_file('backends/grafana/admin-password', credentials['grafana']['password'] + '\n')
|
||||
users = [
|
||||
{'name': role, 'password_hash': password_hash(secrets.token_hex(32)),
|
||||
'hashing_algorithm': 'rabbit_password_hashing_sha256', 'tags': []}
|
||||
for role in ('worker', 'relay')
|
||||
]
|
||||
users.append({'name': 'operator',
|
||||
'password_hash': password_hash(credentials['broker']['operator']['password']),
|
||||
'hashing_algorithm': 'rabbit_password_hashing_sha256', 'tags': ['administrator']})
|
||||
definitions = {
|
||||
'users': users, 'vhosts': [{'name': 'messenger'}],
|
||||
'permissions': [
|
||||
{'user': 'relay', 'vhost': 'messenger', 'configure': '^$',
|
||||
'write': r'^attachments\.jobs$', 'read': '^$'},
|
||||
{'user': 'worker', 'vhost': 'messenger', 'configure': '^$',
|
||||
'write': '^$', 'read': r'^attachment\.process\.v1$'},
|
||||
{'user': 'operator', 'vhost': 'messenger', 'configure': '.*', 'write': '.*', 'read': '.*'},
|
||||
],
|
||||
'exchanges': [
|
||||
{'name': name, 'vhost': 'messenger', 'type': 'direct', 'durable': True,
|
||||
'auto_delete': False, 'internal': False, 'arguments': {}}
|
||||
for name in ('attachments.jobs', 'attachments.dlx')
|
||||
],
|
||||
'queues': [
|
||||
{'name': 'attachment.process.v1', 'vhost': 'messenger', 'durable': True,
|
||||
'auto_delete': False, 'arguments': {
|
||||
'x-queue-type': 'quorum', 'x-delivery-limit': 100,
|
||||
'x-delayed-retry-type': 'all', 'x-delayed-retry-min': 5000,
|
||||
'x-delayed-retry-max': 60000,
|
||||
'x-dead-letter-exchange': 'attachments.dlx',
|
||||
'x-dead-letter-routing-key': 'attachment.process.dead',
|
||||
'x-dead-letter-strategy': 'at-least-once',
|
||||
'x-overflow': 'reject-publish', 'x-max-length': 100000,
|
||||
'x-consumer-timeout': 300000,
|
||||
}},
|
||||
{'name': 'attachment.process.dead', 'vhost': 'messenger', 'durable': True,
|
||||
'auto_delete': False, 'arguments': {'x-queue-type': 'quorum', 'x-max-length': 100000,
|
||||
'x-overflow': 'reject-publish', 'x-message-ttl': 604800000}},
|
||||
],
|
||||
'bindings': [
|
||||
{'source': exchange, 'vhost': 'messenger', 'destination': queue,
|
||||
'destination_type': 'queue', 'routing_key': queue, 'arguments': {}}
|
||||
for exchange, queue in (('attachments.jobs', 'attachment.process.v1'),
|
||||
('attachments.dlx', 'attachment.process.dead'))
|
||||
],
|
||||
}
|
||||
self.write_file('backends/broker/definitions.json', json.dumps(definitions, indent=2) + '\n')
|
||||
self.env.group_access(self.env.secrets / 'backends')
|
||||
self.env.group_access(self.env.secrets / 'bootstrap')
|
||||
|
||||
def render_grafana(self) -> None:
|
||||
template = (ROOT / 'infra/grafana/provisioning/datasources/datasources.yaml').read_text()
|
||||
values = self.env.snapshot('grafana')
|
||||
replacements = {
|
||||
'__LAB7_CA_CERT__': values['ca.crt'],
|
||||
'__LAB7_CLIENT_CERT__': values['tls.crt'],
|
||||
'__LAB7_CLIENT_KEY__': values['tls.key'],
|
||||
}
|
||||
lines = []
|
||||
for line in template.splitlines():
|
||||
value = replacements.get(line.strip())
|
||||
if value is None:
|
||||
lines.append(line)
|
||||
else:
|
||||
indent = line[:len(line) - len(line.lstrip())]
|
||||
lines.extend(indent + item for item in value.rstrip().splitlines())
|
||||
self.write_file('backends/grafana/datasources/datasources.yaml', '\n'.join(lines) + '\n')
|
||||
self.write_file('backends/grafana/dashboards/dashboards.yaml',
|
||||
(ROOT / 'infra/grafana/provisioning/dashboards/dashboards.yaml').read_text())
|
||||
self.env.group_access(self.env.secrets / 'backends/grafana')
|
||||
|
||||
def prepare(self) -> dict:
|
||||
self.pki.prepare()
|
||||
self.backend_files()
|
||||
self.pki.recover_transport()
|
||||
self.render_grafana()
|
||||
metadata = {'project': self.env.project, 'pki_mount': 'pki',
|
||||
'api_replicas': int(self.env.value('API_REPLICAS', '2'))}
|
||||
self.env.private_json(self.env.secrets / 'metadata.json', metadata)
|
||||
return {'prepared': True, 'project': self.env.project}
|
||||
|
||||
def unseal(self) -> dict:
|
||||
deadline = time.monotonic() + 60
|
||||
client = BaoClient(self.env)
|
||||
while True:
|
||||
try:
|
||||
status = client.request('GET', 'sys/seal-status')
|
||||
break
|
||||
except OperationError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(1)
|
||||
if not status.get('initialized'):
|
||||
response = client.request('POST', 'sys/init', {'secret_shares': 3, 'secret_threshold': 2}, timeout=60)
|
||||
material = {'keys': response['keys_base64'], 'root_token': response['root_token']}
|
||||
self.env.private_json(self.init_path, material)
|
||||
status = client.request('GET', 'sys/seal-status')
|
||||
material = self.env.read_json(self.init_path)
|
||||
if status.get('sealed'):
|
||||
keys = material.get('keys', [])
|
||||
if len(keys) < 2:
|
||||
raise OperationError('operator unseal state is missing; it must never be recovered from the container')
|
||||
for key in keys[:2]:
|
||||
self.env.redactions.add(key)
|
||||
status = client.request('POST', 'sys/unseal', {'key': key}, timeout=30)
|
||||
if status.get('sealed'):
|
||||
raise OperationError('operator unseal did not complete')
|
||||
while True:
|
||||
health = client.request('GET', 'sys/health', allowed=(200, 429, 472, 473, 501, 503))
|
||||
if health.get('initialized') and not health.get('sealed') and not health.get('standby'):
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError('unsealed OpenBao did not become the active node')
|
||||
time.sleep(0.2)
|
||||
return {'unsealed': True, 'project': self.env.project}
|
||||
|
||||
def seal(self) -> dict:
|
||||
client = BaoClient(self.env)
|
||||
client.request('POST', 'sys/seal', {}, client.login())
|
||||
status = client.request('GET', 'sys/seal-status')
|
||||
if not status.get('sealed'):
|
||||
raise OperationError('operator seal did not close OpenBao')
|
||||
return {'sealed': True, 'project': self.env.project}
|
||||
|
||||
def configure_auth(self, client: BaoClient, token: str) -> None:
|
||||
methods = client.request('GET', 'sys/auth', token=token)
|
||||
methods = methods.get('data', methods)
|
||||
if 'cert/' not in methods:
|
||||
client.request('POST', 'sys/auth/cert', {'type': 'cert'}, token)
|
||||
for role in ROLES:
|
||||
policy = operator_policy() if role == 'operator' else service_policy(role)
|
||||
client.request('PUT', 'sys/policies/acl/lab7-' + role, {'policy': policy}, token)
|
||||
client.request('POST', 'auth/cert/certs/' + role, {
|
||||
'certificate': self.pki.root_bundle(),
|
||||
'allowed_common_names': [role], 'allowed_uri_sans': ['spiffe://mtusi/' + role],
|
||||
'token_policies': ['lab7-' + role], 'token_ttl': '60s',
|
||||
'token_max_ttl': '300s', 'token_explicit_max_ttl': '300s',
|
||||
'token_no_default_policy': True,
|
||||
}, token)
|
||||
|
||||
def configure_kv(self, client: BaoClient, token: str) -> None:
|
||||
mounts = client.request('GET', 'sys/mounts', token=token)
|
||||
mounts = mounts.get('data', mounts)
|
||||
if 'secret/' not in mounts:
|
||||
client.request('POST', 'sys/mounts/secret', {'type': 'kv', 'options': {'version': '2'}}, token)
|
||||
values = self.credentials()
|
||||
for role in ('api', 'worker', 'relay'):
|
||||
data = {'POSTGRES_PASSWORD': values['postgres'][role]['password']}
|
||||
if role != 'relay':
|
||||
data.update({'S3_ACCESS_KEY_ID': values['s3'][role]['access_key'],
|
||||
'S3_SECRET_ACCESS_KEY': values['s3'][role]['secret_key']})
|
||||
if role == 'api':
|
||||
data['REDIS_PASSWORD'] = values['redis']['cache']['password']
|
||||
client.request('POST', 'secret/data/' + role, {'data': data}, token)
|
||||
|
||||
def provision_bao(self) -> None:
|
||||
material = self.env.read_json(self.init_path)
|
||||
root_token = material.get('root_token')
|
||||
if root_token:
|
||||
self.env.redactions.add(root_token)
|
||||
client = BaoClient(self.env)
|
||||
token = root_token
|
||||
else:
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
audits = client.request('GET', 'sys/audit', token=token)
|
||||
audits = audits.get('data', audits)
|
||||
if 'file/' not in audits:
|
||||
raise OperationError('mandatory declarative audit device is not active')
|
||||
self.configure_auth(client, token)
|
||||
self.configure_kv(client, token)
|
||||
self.pki.provision(client, token)
|
||||
self.pki.sync_crls(client, token)
|
||||
if root_token:
|
||||
# Verify the separately scoped operator path before destroying initial root.
|
||||
operator = BaoClient(self.env)
|
||||
operator.login()
|
||||
client.request('POST', 'auth/token/revoke-self', {}, root_token)
|
||||
denied = client.request('GET', 'auth/token/lookup-self', token=root_token,
|
||||
allowed=(403,))
|
||||
if not denied.get('errors'):
|
||||
raise OperationError('root credential was not rejected after revocation')
|
||||
material.pop('root_token', None)
|
||||
material['root_token_revoked'] = True
|
||||
self.env.private_json(self.init_path, material)
|
||||
self.env.private_json(self.env.state / 'bootstrap-state.json', {'bao_provisioned': True})
|
||||
|
||||
def sql(self, sql: str, user: str = 'lab_operator', *, check: bool = True) -> str:
|
||||
result = self.env.compose('exec', '-T', 'postgres', 'psql', '-v', 'ON_ERROR_STOP=1',
|
||||
'-U', user, '-d', 'messenger', '-At', data=sql,
|
||||
check=check)
|
||||
return result.stdout if result.returncode == 0 else ''
|
||||
|
||||
def reconcile_roles(self) -> None:
|
||||
values = self.credentials()['postgres']
|
||||
existing = None
|
||||
for candidate in ('lab_operator', 'messenger', 'postgres'):
|
||||
if self.sql('SELECT current_user;\n', candidate, check=False).strip() == candidate:
|
||||
existing = candidate
|
||||
break
|
||||
if not existing:
|
||||
raise OperationError('no local operator database role is available')
|
||||
statements = []
|
||||
for role, record in values.items():
|
||||
name = record['username']
|
||||
statements.append(f"DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='{name}') "
|
||||
f'THEN CREATE ROLE "{name}"; END IF; END $$;')
|
||||
privilege = 'SUPERUSER CREATEDB CREATEROLE' if role == 'operator' else 'NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT'
|
||||
statements.append(f'ALTER ROLE "{name}" WITH LOGIN {privilege} '
|
||||
f"PASSWORD '{scram_verifier(record['password'])}' CONNECTION LIMIT 32;")
|
||||
self.sql('\n'.join(statements), existing)
|
||||
|
||||
def grants(self) -> None:
|
||||
sql = '''
|
||||
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
|
||||
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC;
|
||||
REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM PUBLIC;
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_relay;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker, messenger_relay;
|
||||
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM messenger_api, messenger_worker, messenger_relay;
|
||||
REVOKE ALL ON ALL SEQUENCES IN SCHEMA public FROM messenger_api, messenger_worker, messenger_relay;
|
||||
GRANT SELECT, INSERT, UPDATE ON users, chats, chat_members, messages, user_chat_versions,
|
||||
attachments, attachment_jobs, outbox_messages, attachment_job_events TO messenger_api;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON sessions, message_idempotency, login_limits TO messenger_api;
|
||||
GRANT SELECT ON attachment_variants TO messenger_api;
|
||||
GRANT SELECT, INSERT ON message_attachments TO messenger_api;
|
||||
GRANT DELETE ON attachments TO messenger_api;
|
||||
GRANT SELECT, INSERT, UPDATE ON attachments, attachment_jobs, attachment_variants,
|
||||
outbox_messages, attachment_job_events TO messenger_worker;
|
||||
GRANT DELETE ON attachments TO messenger_worker;
|
||||
GRANT SELECT, UPDATE ON attachments, attachment_jobs TO messenger_relay;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON outbox_messages TO messenger_relay;
|
||||
GRANT SELECT, INSERT ON attachment_job_events TO messenger_relay;
|
||||
GRANT USAGE, SELECT ON outbox_messages_id_seq, attachment_job_events_id_seq
|
||||
TO messenger_api, messenger_worker, messenger_relay;
|
||||
DO $$ DECLARE app_object record; object_type text; BEGIN
|
||||
IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger') THEN
|
||||
-- The initdb bootstrap principal owns pg_catalog objects that cannot be
|
||||
-- reassigned globally. Only the application's public objects move owners.
|
||||
FOR app_object IN
|
||||
SELECT c.relname, c.relkind FROM pg_class c
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace
|
||||
WHERE n.nspname = 'public'
|
||||
AND c.relowner = (SELECT oid FROM pg_roles WHERE rolname='messenger')
|
||||
AND c.relkind IN ('r', 'p', 'S', 'v', 'm')
|
||||
AND (c.relkind <> 'S' OR NOT EXISTS (
|
||||
SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_class'::regclass
|
||||
AND d.objid = c.oid AND d.deptype IN ('a', 'i')
|
||||
))
|
||||
LOOP
|
||||
object_type := CASE app_object.relkind
|
||||
WHEN 'S' THEN 'SEQUENCE' WHEN 'v' THEN 'VIEW'
|
||||
WHEN 'm' THEN 'MATERIALIZED VIEW' ELSE 'TABLE' END;
|
||||
EXECUTE format('ALTER %s public.%I OWNER TO lab_operator', object_type, app_object.relname);
|
||||
END LOOP;
|
||||
ALTER DATABASE messenger OWNER TO lab_operator;
|
||||
ALTER SCHEMA public OWNER TO lab_operator;
|
||||
-- PostgreSQL 18 requires the initdb bootstrap role to remain SUPERUSER.
|
||||
-- NOLOGIN plus removal of its password retires the legacy identity without
|
||||
-- rebuilding the cluster or changing user data.
|
||||
ALTER ROLE messenger NOLOGIN PASSWORD NULL NOCREATEDB NOCREATEROLE NOINHERIT;
|
||||
END IF;
|
||||
END $$;
|
||||
'''
|
||||
self.sql(sql)
|
||||
|
||||
def retire_broker_users(self) -> None:
|
||||
for user in ('messenger', 'guest'):
|
||||
self.env.compose('exec', '-T', 'broker', 'rabbitmqctl', 'delete_user', user, check=False)
|
||||
|
||||
def ensure_service_identities(self) -> dict:
|
||||
"""Reissue leafs that expired while the stand was stopped.
|
||||
|
||||
`prepare` only fills gaps and does not inspect leaf expiry. Recovery is
|
||||
operator-driven here; the running stand uses `make renewer`.
|
||||
"""
|
||||
replaced = self.pki.recover_transport()
|
||||
if replaced:
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
renewed = []
|
||||
for role in ROLES:
|
||||
certificate = self.env.identity(role) / 'tls.crt'
|
||||
if not certificate.exists():
|
||||
continue
|
||||
valid = self.env.run(['openssl', 'x509', '-checkend', '300', '-noout',
|
||||
'-in', str(certificate)], check=False).returncode == 0
|
||||
if not valid:
|
||||
self.pki.issue(role)
|
||||
renewed.append(role)
|
||||
reloaded, skipped = [], []
|
||||
for role in renewed:
|
||||
try:
|
||||
self.reload_identity(role)
|
||||
reloaded.append(role)
|
||||
except OperationError:
|
||||
# A stopped service will load the reissued leaf when compose starts it.
|
||||
skipped.append(role)
|
||||
return {'renewed': renewed, 'reloaded': reloaded, 'reload_skipped': skipped}
|
||||
|
||||
def bootstrap(self) -> dict:
|
||||
self.prepare()
|
||||
self.env.compose('up', '-d', '--no-build', 'volume-init', timeout=300)
|
||||
# volume-init is short-lived; consumers require successful completion.
|
||||
self.env.compose('up', '-d', '--no-build', 'openbao', timeout=300)
|
||||
self.unseal()
|
||||
self.provision_bao()
|
||||
# On the first successful bootstrap, transition from offline bootstrap
|
||||
# leaves to restricted OpenBao-issued, short-lived service identities.
|
||||
marker = self.env.state / 'service-leaves.json'
|
||||
if not marker.exists():
|
||||
leaves = [self.pki.issue(role) for role in ROLES if role != 'rogue']
|
||||
self.env.private_json(marker, {'issued': leaves})
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
recovered = self.ensure_service_identities()
|
||||
self.render_grafana()
|
||||
self.env.compose('up', '-d', '--no-build', *STORES, 's3', timeout=300)
|
||||
self.wait_stores()
|
||||
self.reconcile_roles()
|
||||
self.env.compose('run', '--rm', '--no-deps', 'migrate', timeout=180)
|
||||
self.grants()
|
||||
self.env.compose('run', '--rm', '--no-deps', 's3-init', timeout=180)
|
||||
self.retire_broker_users()
|
||||
return {'bootstrapped': True, 'project': self.env.project,
|
||||
'expired_identities_renewed': recovered.get('renewed', []),
|
||||
'expired_identities_reloaded': recovered.get('reloaded', []),
|
||||
'root_token_revoked': self.env.read_json(self.init_path).get('root_token_revoked', False)}
|
||||
|
||||
def wait_stores(self) -> None:
|
||||
deadline = time.monotonic() + 120
|
||||
for service in ('postgres', 'redis', 'broker', 'seaweedfs'):
|
||||
while True:
|
||||
result = self.env.compose('ps', '-q', service).stdout.strip()
|
||||
if result:
|
||||
state = self.env.run(['docker', 'inspect', '--format',
|
||||
'{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
|
||||
result]).stdout.strip()
|
||||
if state in ('healthy', 'running'):
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError(service + ' did not become ready')
|
||||
time.sleep(1)
|
||||
|
||||
def wait_s3(self, timeout: float = 120) -> None:
|
||||
"""Read old volume-backed bytes; never repair an established sentinel."""
|
||||
deadline = time.monotonic() + timeout
|
||||
marker = self.env.state / 's3-readiness.json'
|
||||
sentinel = self.env.read_json(marker)
|
||||
if not sentinel:
|
||||
sentinel = {'bucket': self.env.value('S3_BUCKET', 'messenger-attachments'),
|
||||
'key': 'operator-readiness/' + secrets.token_hex(16),
|
||||
'body': secrets.token_hex(32768), 'established': False}
|
||||
self.env.private_json(marker, sentinel)
|
||||
payload = sentinel['body'].encode()
|
||||
credential = self.credentials()['s3']['operator']
|
||||
host = 'localhost:' + self.env.value('S3_PORT', '8333')
|
||||
bucket_path = '/' + urllib.parse.quote(sentinel['bucket'], safe='')
|
||||
object_path = bucket_path + '/' + urllib.parse.quote(sentinel['key'], safe='/~')
|
||||
context = ssl.create_default_context(cafile=str(self.env.identity('operator') / 'ca.crt'))
|
||||
context.load_cert_chain(str(self.env.identity('operator') / 'tls.crt'),
|
||||
str(self.env.identity('operator') / 'tls.key'))
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect(),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
|
||||
def request(method: str, path: str, body: bytes = b'') -> bytes:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError()
|
||||
stamp = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime())
|
||||
day = stamp[:8]
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
headers = {'host': host, 'x-amz-content-sha256': digest, 'x-amz-date': stamp}
|
||||
signed = ';'.join(sorted(headers))
|
||||
canonical_headers = ''.join(name + ':' + headers[name] + '\n' for name in sorted(headers))
|
||||
canonical = '\n'.join((method, path, '', canonical_headers, signed, digest))
|
||||
scope = day + '/us-east-1/s3/aws4_request'
|
||||
to_sign = 'AWS4-HMAC-SHA256\n' + stamp + '\n' + scope + '\n' + hashlib.sha256(canonical.encode()).hexdigest()
|
||||
signing_key = ('AWS4' + credential['secret_key']).encode()
|
||||
for part in (day, 'us-east-1', 's3', 'aws4_request'):
|
||||
signing_key = hmac.new(signing_key, part.encode(), hashlib.sha256).digest()
|
||||
signature = hmac.new(signing_key, to_sign.encode(), hashlib.sha256).hexdigest()
|
||||
headers['Authorization'] = ('AWS4-HMAC-SHA256 Credential=' + credential['access_key'] +
|
||||
'/' + scope + ', SignedHeaders=' + signed + ', Signature=' + signature)
|
||||
req = urllib.request.Request('https://' + host + path, method=method, headers=headers,
|
||||
data=body if method == 'PUT' else None)
|
||||
with opener.open(req, timeout=min(5, remaining)) as response:
|
||||
chunks = bytearray()
|
||||
while len(chunks) <= len(payload):
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError()
|
||||
chunk = response.read1(min(8192, len(payload) + 1 - len(chunks)))
|
||||
if not chunk:
|
||||
break
|
||||
chunks.extend(chunk)
|
||||
return bytes(chunks)
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
if not sentinel['established']:
|
||||
# Only this operator-owned key is written on first initialization.
|
||||
request('PUT', object_path, payload)
|
||||
if request('GET', object_path) != payload:
|
||||
raise OperationError('persistent S3 readiness sentinel bytes changed')
|
||||
if not sentinel['established']:
|
||||
sentinel['established'] = True
|
||||
self.env.private_json(marker, sentinel)
|
||||
return
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code not in (404, 408, 429, 500, 502, 503, 504):
|
||||
raise OperationError('S3 readiness request rejected (HTTP ' + str(exc.code) + ')') from None
|
||||
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
||||
pass
|
||||
time.sleep(min(1, max(0, deadline - time.monotonic())))
|
||||
raise OperationError('CA-verified persistent S3 body readiness deadline exceeded')
|
||||
|
||||
def wait_ready(self, timeout: float = 120) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
self.wait_s3(timeout=timeout)
|
||||
context = ssl.create_default_context(cafile=str(self.env.identity('operator') / 'ca.crt'))
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with opener.open(self.env.base_url + '/health/ready', timeout=5) as response:
|
||||
if response.status == 200:
|
||||
return
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise OperationError('CA-verified public HTTPS readiness deadline exceeded')
|
||||
|
||||
def up(self) -> dict:
|
||||
result = self.bootstrap()
|
||||
self.env.compose('up', '-d', '--no-build', timeout=300)
|
||||
# Apply current credentials/trust/CRLs even when owners were reused.
|
||||
# Namespace consumers are recreated against the current owner ID.
|
||||
gateways = [child for children in GATEWAY_PAIRS.values()
|
||||
for child in children if child != 's3']
|
||||
self.env.compose('up', '-d', '--no-build', '--no-deps', '--force-recreate',
|
||||
*gateways, timeout=180)
|
||||
self.env.compose('restart', 'lb', timeout=60)
|
||||
self.wait_ready()
|
||||
self.reset_grafana_admin()
|
||||
return {**result, 'ready': True, 'base_url': self.env.base_url}
|
||||
|
||||
def wait_container_health(self, container: str, timeout: float = 120) -> None:
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
state = self.env.run(['docker', 'inspect', '--format',
|
||||
'{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}',
|
||||
container], check=False).stdout.strip()
|
||||
if state in ('healthy', 'running'):
|
||||
return
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError(container + ' did not become healthy after restart: ' + state)
|
||||
time.sleep(1)
|
||||
|
||||
def rolling_restart(self, service: str) -> None:
|
||||
containers = [item for item in self.env.compose('ps', '-q', service).stdout.split() if item]
|
||||
for container in containers:
|
||||
self.env.run(['docker', 'restart', container], timeout=120)
|
||||
self.wait_container_health(container)
|
||||
|
||||
def restart_consumers(self, *, stores: bool = True, apps: bool = True) -> None:
|
||||
if stores:
|
||||
# Establish/read the sentinel before stopping the old volume owner.
|
||||
self.wait_s3()
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
self.env.compose('restart', *STORES, *TELEMETRY, timeout=180)
|
||||
self.wait_stores()
|
||||
# A shared-network consumer is tied to a concrete owner container ID.
|
||||
# Recreate consumers explicitly even if an owner was replaced.
|
||||
consumers = [consumer for values in GATEWAY_PAIRS.values() for consumer in values]
|
||||
self.env.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps',
|
||||
*consumers, timeout=180)
|
||||
self.wait_s3()
|
||||
if apps:
|
||||
# One replica at a time: the surviving API serves while the peer
|
||||
# reloads the new leaf/trust bundle. LB is restarted last.
|
||||
for service in ('api', 'worker', 'relay'):
|
||||
self.rolling_restart(service)
|
||||
self.env.compose('restart', 'lb', timeout=60)
|
||||
self.wait_ready()
|
||||
|
||||
def rotate_secret(self, role: str) -> dict:
|
||||
if role not in ('api', 'worker'):
|
||||
raise OperationError('the completed secret rotation experiment targets an S3 application identity')
|
||||
values = self.credentials()
|
||||
old = values['s3'][role]
|
||||
self.env.private_json(self.env.state / ('retired-' + role + '-s3.json'), old)
|
||||
values['s3'][role] = {'access_key': 'lab7' + role + secrets.token_hex(8),
|
||||
'secret_key': secrets.token_hex(32)}
|
||||
self.env.private_json(self.credentials_path, values)
|
||||
self.backend_files()
|
||||
client = BaoClient(self.env)
|
||||
self.configure_kv(client, client.login())
|
||||
self.env.compose('restart', 's3', timeout=60)
|
||||
self.env.compose('restart', role, timeout=60)
|
||||
self.wait_ready()
|
||||
return {'role': role, 'secret_rotated': True, 'old_key_retired': True,
|
||||
'images_rebuilt': False}
|
||||
|
||||
def rollover(self, phase: str) -> dict:
|
||||
if phase == 'prepare':
|
||||
result = self.pki.prepare_rollover()
|
||||
elif phase == 'issue':
|
||||
result = self.pki.switch_issuer()
|
||||
else:
|
||||
result = self.pki.retire_issuer()
|
||||
client = BaoClient(self.env)
|
||||
self.configure_auth(client, client.login())
|
||||
self.render_grafana()
|
||||
# Go reloads leaves on new handshakes: during issue the trust bundle is
|
||||
# unchanged (overlap from prepare), so only native owners restart.
|
||||
# Prepare distributes trust and retire removes it; both need app reload.
|
||||
self.restart_consumers(apps=phase != 'issue')
|
||||
return {**result, 'all_consumers_reloaded': True, 'images_rebuilt': False,
|
||||
'application_reload': phase != 'issue'}
|
||||
|
||||
def reset_grafana_admin(self) -> None:
|
||||
context = ssl.create_default_context(cafile=str(self.env.identity('operator') / 'ca.crt'))
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
endpoint = 'https://localhost:' + self.env.value('GRAFANA_PORT', '3000') + '/api/health'
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
with opener.open(endpoint, timeout=5) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise OperationError('Grafana verified TLS health deadline exceeded')
|
||||
time.sleep(1)
|
||||
self.env.compose('exec', '-T', 'grafana', 'grafana', 'cli',
|
||||
'--homepath', '/usr/share/grafana', 'admin',
|
||||
'reset-admin-password', '--password-from-stdin',
|
||||
data=self.credentials()['grafana']['password'] + '\n')
|
||||
|
||||
def redis(self, arguments: list[str]) -> str:
|
||||
# Read the operator credential inside its own backend mount, never argv.
|
||||
result = self.env.compose('exec', '-T', 'redis', 'sh', '-ec',
|
||||
'export REDISCLI_AUTH="$(cat /run/backend/operator-password)"; '
|
||||
'exec redis-cli --tls --cacert /run/identity/current/ca.crt '
|
||||
'--user operator "$@"', '--', *arguments)
|
||||
return result.stdout
|
||||
|
||||
def jobctl(self, arguments: list[str]) -> str:
|
||||
return self.env.compose('run', '--rm', '--no-deps', 'jobctl', *arguments).stdout
|
||||
|
||||
def reload_identity(self, role: str) -> None:
|
||||
if role in ('api', 'operator', 'rogue'):
|
||||
# Go reloads complete versions on new handshakes; its manager notices
|
||||
# actual current leaf expiry independently of the token renewal.
|
||||
return
|
||||
if role == 'openbao':
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
return
|
||||
if role == 's3':
|
||||
self.env.compose('restart', 'seaweedfs', timeout=60)
|
||||
self.env.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps', 's3', timeout=90)
|
||||
return
|
||||
owner = 'otel-collector' if role == 'collector' else role
|
||||
if role == 'grafana':
|
||||
self.render_grafana()
|
||||
self.env.compose('restart', owner, timeout=90)
|
||||
children = GATEWAY_PAIRS.get(owner, [])
|
||||
if children:
|
||||
self.env.compose('up', '-d', '--no-build', '--force-recreate', '--no-deps', *children, timeout=90)
|
||||
|
||||
def revoke_identity(self, role: str, serial: str) -> dict:
|
||||
result = self.pki.revoke(role, serial)
|
||||
# Go reads current CRLs per handshake; native gateways hold startup
|
||||
# CRLs and must drain old sessions before revocation returns success.
|
||||
gateways = ['lb', *[child for children in GATEWAY_PAIRS.values()
|
||||
for child in children if child != 's3']]
|
||||
self.env.compose('restart', *gateways, timeout=180)
|
||||
return {**result, 'native_gateway_crls_reloaded': True,
|
||||
'native_gateway_restarts': True,
|
||||
'existing_application_pools_drained': False}
|
||||
|
||||
def recover_identity(self, role: str) -> dict:
|
||||
transport_replaced = self.pki.recover_transport()
|
||||
if transport_replaced or role == 'openbao':
|
||||
self.env.compose('restart', 'openbao', timeout=60)
|
||||
self.unseal()
|
||||
issued = self.pki.issue(role)
|
||||
self.reload_identity(role)
|
||||
if role in ('api', 'worker', 'relay'):
|
||||
self.env.compose('up', '-d', '--no-build', '--no-deps', role, timeout=90)
|
||||
return {**issued, 'recovered_by_operator': True}
|
||||
|
||||
def sync_crls(self) -> dict:
|
||||
client = BaoClient(self.env)
|
||||
token = client.login()
|
||||
republished = self.pki.sync_crls(client, token)
|
||||
return {'crls_updated': True, 'identities_republished': republished}
|
||||
|
||||
def audit_summary(self) -> dict:
|
||||
result = self.env.compose('exec', '-T', 'openbao', 'cat', '/openbao/audit/audit.log')
|
||||
counts = {}
|
||||
for line in result.stdout.splitlines():
|
||||
try:
|
||||
record = json.loads(line)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
request = record.get('request', {})
|
||||
path = request.get('path', '')
|
||||
operation = request.get('operation', '')
|
||||
if path.startswith(('pki/issue/', 'pki/revoke', 'auth/token/renew-self', 'auth/cert/login')):
|
||||
key = operation + ' ' + path
|
||||
counts[key] = counts.get(key, 0) + 1
|
||||
return {'audit_events': counts, 'raw_credentials_exported': False}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
commands = parser.add_subparsers(dest='command', required=True)
|
||||
for name in ('prepare', 'bootstrap', 'up', 'unseal', 'seal', 'restart', 'sync-crls', 'audit-summary', 'status'):
|
||||
commands.add_parser(name)
|
||||
for name in ('issue', 'renew'):
|
||||
sub = commands.add_parser(name)
|
||||
sub.add_argument('role', choices=ROLES)
|
||||
sub.add_argument('--ttl', default='1h')
|
||||
if name == 'renew':
|
||||
sub.add_argument('--watch', action='store_true')
|
||||
sub.add_argument('--interval', type=float, default=1)
|
||||
sub = commands.add_parser('revoke')
|
||||
sub.add_argument('role', choices=ROLES)
|
||||
sub.add_argument('--serial', required=True)
|
||||
sub = commands.add_parser('rotate-secret')
|
||||
sub.add_argument('role', choices=('api', 'worker'))
|
||||
sub = commands.add_parser('ca-rollover')
|
||||
sub.add_argument('--phase', choices=('prepare', 'issue', 'retire'), required=True)
|
||||
sub = commands.add_parser('recover')
|
||||
sub.add_argument('role', choices=ROLES)
|
||||
commands.add_parser('psql')
|
||||
for name in ('redis', 'jobctl'):
|
||||
command = commands.add_parser(name)
|
||||
command.add_argument('arguments', nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
control = Controller()
|
||||
if args.command == 'psql':
|
||||
print(control.sql(sys.stdin.read()), end='')
|
||||
return
|
||||
if args.command == 'redis':
|
||||
print(control.redis(args.arguments), end='')
|
||||
return
|
||||
if args.command == 'jobctl':
|
||||
print(control.jobctl(args.arguments), end='')
|
||||
return
|
||||
if args.command == 'prepare':
|
||||
result = control.prepare()
|
||||
elif args.command == 'bootstrap':
|
||||
result = control.bootstrap()
|
||||
elif args.command == 'up':
|
||||
result = control.up()
|
||||
elif args.command == 'unseal':
|
||||
result = control.unseal()
|
||||
elif args.command == 'seal':
|
||||
result = control.seal()
|
||||
elif args.command == 'restart':
|
||||
control.restart_consumers()
|
||||
result = {'restarted': True, 'volumes_preserved': True}
|
||||
elif args.command == 'sync-crls':
|
||||
result = control.sync_crls()
|
||||
elif args.command == 'issue':
|
||||
result = control.pki.issue(args.role, args.ttl)
|
||||
control.reload_identity(args.role)
|
||||
elif args.command == 'renew':
|
||||
if args.watch:
|
||||
control.pki.renew_watch(args.role, args.ttl, args.interval, control.reload_identity)
|
||||
return
|
||||
result = control.pki.issue(args.role, args.ttl, service_auth=True)
|
||||
control.reload_identity(args.role)
|
||||
elif args.command == 'recover':
|
||||
result = control.recover_identity(args.role)
|
||||
elif args.command == 'revoke':
|
||||
result = control.revoke_identity(args.role, args.serial)
|
||||
elif args.command == 'rotate-secret':
|
||||
result = control.rotate_secret(args.role)
|
||||
elif args.command == 'ca-rollover':
|
||||
result = control.rollover(args.phase)
|
||||
elif args.command == 'audit-summary':
|
||||
result = control.audit_summary()
|
||||
else:
|
||||
result = {'project': control.env.project, 'base_url': control.env.base_url,
|
||||
'pki': control.pki.state}
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except (OperationError, OSError, TimeoutError, subprocess.TimeoutExpired) as error:
|
||||
print('FAIL: ' + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec python3 student-tests/tests_helpers.py compose up -d --wait --no-deps broker broker-admin-tls
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec python3 student-tests/tests_helpers.py compose up -d --wait --no-deps worker
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
exec python3 student-tests/tests_helpers.py compose stop broker-admin-tls broker
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task.
|
||||
# Stop that instance and leave it stopped; no stop of DB/LB/volumes.
|
||||
# Return quickly (within 10 s); the test sends requests during this script.
|
||||
# Restore the replica explicitly after the test. Never print credentials.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
printf '%s
|
||||
' 'TODO: implement stop-one.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
ROOT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT_DIR"
|
||||
# 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=$(python3 student-tests/tests_helpers.py compose ps -q api)
|
||||
|
||||
if [ -z "$candidates" ]; then
|
||||
printf 'stop-one.sh: no api containers of project %s are running\n' "$PROJECT" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -- $candidates
|
||||
PROJECT=$(docker inspect --format '{{index .Config.Labels "com.docker.compose.project"}}' "$1")
|
||||
|
||||
# Matches the requested alias against every reasonable identifier of a replica:
|
||||
# container hostname (= X-Instance-Id), full/short container id, full container
|
||||
# name (project-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
+6
@@ -0,0 +1,6 @@
|
||||
#!/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"
|
||||
exec python3 student-tests/tests_helpers.py compose 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
+213
@@ -0,0 +1,213 @@
|
||||
#!/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 os
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
from lab7_environment import read_env
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_DIR = ROOT / 'evidence/track1'
|
||||
# Стенд трека 1 — только контейнеры своего проекта: параллельно поднятый стенд
|
||||
# другой лаборатории (тот же Docker-host) иначе попадал бы в те же колонки
|
||||
# (mtusi-messenger-lab2-postgres-1 -> postgres) и искажал бюджет и CPU.
|
||||
DEFAULT_PREFIX = os.environ.get('COMPOSE_PROJECT_NAME', read_env(ROOT / '.env').get(
|
||||
'COMPOSE_PROJECT_NAME', 'mtusi-messenger-lab6')) + '-'
|
||||
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
+322
@@ -0,0 +1,322 @@
|
||||
#!/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"
|
||||
|
||||
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=$("$PYTHON" -c 'import sys; sys.path.insert(0, "scripts"); from lab7_http import BASE_URL; print(BASE_URL)')
|
||||
CA_FILE=$("$PYTHON" -c 'import sys; sys.path.insert(0, "scripts"); from lab7_http import CA_FILE; print(CA_FILE)')
|
||||
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() {
|
||||
"$PYTHON" student-tests/tests_helpers.py compose "$@"
|
||||
}
|
||||
|
||||
wait_ready() {
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 90 ]; do
|
||||
if curl -fsS --noproxy '*' --cacert "$CA_FILE" -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"
|
||||
}
|
||||
|
||||
# The VM client shares the LB namespace but mounts only public tests and CA.
|
||||
lb_container() {
|
||||
container_of lb
|
||||
}
|
||||
|
||||
# $1 — длительность, $2 — путь к JSON-метрикам (необязательно).
|
||||
load_client() {
|
||||
if [ "$CLIENT" = vm ]; then
|
||||
lb=$(lb_container)
|
||||
ca=$("$PYTHON" -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).resolve(strict=True))' "$CA_FILE")
|
||||
out=$("$PYTHON" -c 'import pathlib,sys; print(pathlib.Path(sys.argv[1]).resolve())' "$OUT")
|
||||
set -- "$1" "$2"
|
||||
if [ -n "$2" ]; then
|
||||
destination="/out/$(basename "$2")"
|
||||
set -- "$1" --output "$destination"
|
||||
else
|
||||
set -- "$1"
|
||||
fi
|
||||
seconds=$1
|
||||
shift
|
||||
docker run --rm --network "container:$lb" \
|
||||
--cap-drop ALL --security-opt no-new-privileges:true --read-only --tmpfs /tmp \
|
||||
--mount "type=bind,source=$ROOT_DIR/tests,target=/repo/tests,readonly" \
|
||||
--mount "type=bind,source=$ROOT_DIR/contracts,target=/repo/contracts,readonly" \
|
||||
--mount "type=bind,source=$ROOT_DIR/lab.json,target=/repo/lab.json,readonly" \
|
||||
--mount "type=bind,source=$ca,target=/ca.crt,readonly" \
|
||||
--mount "type=bind,source=$out,target=/out" \
|
||||
-e NO_PROXY=localhost,127.0.0.1 -e PYTHONDONTWRITEBYTECODE=1 \
|
||||
"$CLIENT_IMAGE" python /repo/tests/load.py --base-url https://localhost:8443 \
|
||||
--ca-file /ca.crt --duration "$seconds" --concurrency "$CONCURRENCY" "$@"
|
||||
|
||||
return
|
||||
fi
|
||||
|
||||
if [ -n "$2" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" --ca-file "$CA_FILE" \
|
||||
--duration "$1" --concurrency "$CONCURRENCY" --output "$2"
|
||||
else
|
||||
# shellcheck disable=SC2086
|
||||
$NO_PROXY_ENV $PYTHON tests/load.py --base-url "$BASE_URL" --ca-file "$CA_FILE" \
|
||||
--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 printf 'SELECT 1;' | "$PYTHON" student-tests/tests_helpers.py psql >/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 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 --scale "api=$replicas" 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.
|
||||
printf '%s\n' "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;" \
|
||||
| "$PYTHON" student-tests/tests_helpers.py psql | 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