Implement lab 7 transport security and worker containment
This commit is contained in:
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
|
||||
for role in api worker ops; do
|
||||
file="secrets/rabbitmq_${role}_password"
|
||||
[ -s "$file" ] || od -An -tx1 -N24 /dev/urandom | tr -d ' \n' >"$file"
|
||||
done
|
||||
|
||||
[ -s secrets/s3_worker_access_key_id ] || printf 'worker%s' "$(od -An -tx1 -N8 /dev/urandom | tr -d ' \n')" >secrets/s3_worker_access_key_id
|
||||
[ -s secrets/s3_worker_secret_access_key ] || od -An -tx1 -N32 /dev/urandom | tr -d ' \n' >secrets/s3_worker_secret_access_key
|
||||
|
||||
for role in api worker; do
|
||||
file="secrets/broker_url_${role}"
|
||||
[ -s "$file" ] || printf 'amqp://messenger-%s:%s@%s:5672/messenger' \
|
||||
"$role" "$(cat "secrets/rabbitmq_${role}_password")" "${BROKER_HOST:-broker}" >"$file"
|
||||
done
|
||||
|
||||
python3 - <<'PY'
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def user(role, tags):
|
||||
salt = os.urandom(4)
|
||||
with open("secrets/rabbitmq_%s_password" % role, "rb") as source:
|
||||
secret = source.read().strip()
|
||||
digest = hashlib.sha256(salt + secret).digest()
|
||||
return {
|
||||
"name": "messenger-" + role,
|
||||
"password_hash": base64.b64encode(salt + digest).decode(),
|
||||
"hashing_algorithm": "rabbit_password_hashing_sha256",
|
||||
"tags": tags,
|
||||
}
|
||||
|
||||
|
||||
def grant(role, configure, write, read):
|
||||
return {"user": "messenger-" + role, "vhost": "messenger", "configure": configure, "write": write, "read": read}
|
||||
|
||||
|
||||
definitions = {
|
||||
"users": [user("api", []), user("worker", []), user("ops", ["administrator"])],
|
||||
"permissions": [
|
||||
grant("api", "^$", "^attachments$", "^$"),
|
||||
grant("worker", "^$", "^$", "^attachments\\.process$"),
|
||||
grant("ops", ".*", ".*", ".*"),
|
||||
],
|
||||
}
|
||||
with open("secrets/rabbitmq_users.json", "w") as target:
|
||||
json.dump(definitions, target, indent=2)
|
||||
target.write("\n")
|
||||
PY
|
||||
chmod 700 secrets
|
||||
chmod 644 secrets/rabbitmq_users.json secrets/rabbitmq_ops_password secrets/broker_url_api secrets/broker_url_worker \
|
||||
secrets/s3_worker_access_key_id secrets/s3_worker_secret_access_key
|
||||
echo "broker and S3 worker secrets ready in secrets/ (values not printed)"
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE=${COMPOSE:-docker compose}
|
||||
service=${BROKER_SERVICE:-broker}
|
||||
dlq() {
|
||||
$COMPOSE exec -T "$service" sh -c 'RABBITMQADMIN_USERNAME=messenger-ops \
|
||||
RABBITMQADMIN_PASSWORD="$(cat /run/secrets/rabbitmq_ops_password)" \
|
||||
exec rabbitmqadmin --non-interactive -V messenger get messages \
|
||||
-q attachments.process.dlq -c "$1" -a ack_requeue_true' sh "${1:-10}"
|
||||
}
|
||||
queues() {
|
||||
$COMPOSE exec -T "$service" rabbitmqctl -q list_queues -p messenger \
|
||||
name type messages_ready messages_unacknowledged consumers
|
||||
}
|
||||
case "${1:-}" in
|
||||
restart) $COMPOSE restart -t 20 "$service" && $COMPOSE up -d --no-deps --no-recreate --wait --wait-timeout 90 "$service" ;;
|
||||
queues) queues ;;
|
||||
dlq) dlq "${2:-10}" ;;
|
||||
*) echo "usage: $0 restart|queues|dlq [count]" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,73 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SETTINGS = (
|
||||
"COMPOSE_PROJECT_NAME",
|
||||
"COMPOSE_FILE",
|
||||
"LB_HTTP_PORT",
|
||||
"LB_STATS_PORT",
|
||||
"BASE_URL",
|
||||
"EVIDENCE_DIR",
|
||||
"RECONCILE_EVIDENCE_DIR",
|
||||
"NO_PROXY",
|
||||
"S3_CPUS",
|
||||
"S3_MEMORY",
|
||||
"UPLOAD_GRACE_SECONDS",
|
||||
"API_IMAGE",
|
||||
"API_REPLICAS",
|
||||
"WEB_CONCURRENCY",
|
||||
"MALLOC_MMAP_THRESHOLD_",
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Capture a command without overwriting evidence")
|
||||
parser.add_argument("output", type=Path)
|
||||
parser.add_argument("command", nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
command = args.command[1:] if args.command[:1] == ["--"] else args.command
|
||||
if not command:
|
||||
parser.error("command is required")
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
|
||||
started = time.monotonic()
|
||||
with args.output.open("x") as output:
|
||||
|
||||
def write(line):
|
||||
line = line.replace(str(ROOT), "<repo>")
|
||||
output.write(line)
|
||||
output.flush()
|
||||
sys.stdout.write(line)
|
||||
sys.stdout.flush()
|
||||
|
||||
write(f"date: {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} commit: {commit}\n")
|
||||
write(
|
||||
"environment: "
|
||||
+ json.dumps({k: os.environ[k] for k in SETTINGS if k in os.environ})
|
||||
+ "\n"
|
||||
)
|
||||
write("$ " + shlex.join(command) + "\n")
|
||||
with subprocess.Popen(
|
||||
command,
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
errors="replace",
|
||||
) as process:
|
||||
for line in process.stdout:
|
||||
write(line)
|
||||
code = process.wait()
|
||||
write(f"exit_code: {code} elapsed_seconds: {time.monotonic() - started:.3f}\n")
|
||||
return code
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
repo=$PWD
|
||||
project="lab7-clean-$(date -u +%Y%m%d%H%M%S)"
|
||||
dir=$(mktemp -d /tmp/lab7-clean.XXXXXX)
|
||||
sha=$(git rev-parse HEAD)
|
||||
export COMPOSE_PROJECT_NAME="$project"
|
||||
export LAB7_OPERATOR_DIR="$HOME/.local/share/mtusi2026lab7/$project"
|
||||
export LB_HTTPS_PORT=19443 GRAFANA_HTTPS_PORT=28300 BAO_HTTPS_PORT=29200
|
||||
export BASE_URL=https://localhost:19443 BAO_OPERATOR_URL=https://localhost:29200
|
||||
export NO_PROXY=localhost,127.0.0.1,::1
|
||||
cleanup() {
|
||||
status=$?
|
||||
trap - EXIT HUP INT TERM
|
||||
if [ -f "$dir/compose.yaml" ]; then
|
||||
cd "$dir"
|
||||
docker compose --profile tools --profile reconcile down || status=1
|
||||
fi
|
||||
echo "exit_code=$status clone=$dir project=$project volumes retained"
|
||||
exit "$status"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
trap 'exit 130' HUP INT TERM
|
||||
echo "commit=$sha project=$project"
|
||||
git clone --quiet --no-hardlinks "$repo" "$dir"
|
||||
cd "$dir"
|
||||
git checkout --quiet --detach "$sha"
|
||||
printf 'COMPOSE_PROJECT_NAME=%s\n' "$project" > .env
|
||||
export CA_FILE="$dir/secrets/pki/operator/ca.crt"
|
||||
make install
|
||||
make check validate lint
|
||||
make up
|
||||
make test test-security
|
||||
docker compose run --rm --no-deps security-audit
|
||||
python3 scripts/security_inventory.py
|
||||
echo "PASS clean clone with fresh CA, operator state and persistent volumes"
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=${1:-evidence/detection}
|
||||
mkdir -p "$out"
|
||||
scripts/restore.sh
|
||||
replica() { docker compose ps -q "${API_SERVICE:-api}" | head -1; }
|
||||
detect() { python3 scripts/probe.py detect "$@"; }
|
||||
failed=0
|
||||
detect --max 1.5 --within-action --restore scripts/restore.sh --out "$out/sigterm.json" \
|
||||
-- docker stop -t "${STOP_TIMEOUT:-7}" "$(replica)" || failed=1
|
||||
detect --max 1.5 --restore scripts/restore.sh --out "$out/kill.json" \
|
||||
-- docker kill "$(replica)" || failed=1
|
||||
hung=$(replica)
|
||||
detect --max 3.5 --restore "docker unpause $hung && scripts/lb-wait.sh" --out "$out/pause.json" \
|
||||
-- docker pause "$hung" || failed=1
|
||||
db=$(docker compose ps -q postgres)
|
||||
detect --max 1.5 --until 0 --lb-status 503 --restore "docker start $db && scripts/lb-wait.sh" \
|
||||
--out "$out/postgres.json" -- docker stop "$db" || failed=1
|
||||
exit "$failed"
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
out=${1:?usage: docker-stats.sh <csv>}
|
||||
vm=$(dirname "$out")/vm_stat.csv
|
||||
cd "$(dirname "$0")/.."
|
||||
project=$(docker compose config | sed -n 's/^name: //p')
|
||||
echo 'ts,name,cpu_pct,mem_usage,mem_pct,net_io,block_io,pids' > "$out"
|
||||
echo 'ts,busy,total,cpus' > "$vm"
|
||||
while :; do
|
||||
ts=$(date +%s)
|
||||
docker compose exec -T valkey cat /proc/stat 2>/dev/null | awk -v ts="$ts" '/^cpu /{b=$2+$3+$4+$7+$8+$9; t=b+$5+$6} /^cpu[0-9]/{n++} END{if (t) print ts "," b "," t "," n}' >> "$vm" || true
|
||||
ids=$(docker ps -q --filter "label=com.docker.compose.project=$project")
|
||||
[ -z "$ids" ] || docker stats --no-stream --format "$ts,{{.Name}},{{.CPUPerc}},{{.MemUsage}},{{.MemPerc}},{{.NetIO}},{{.BlockIO}},{{.PIDs}}" $ids >> "$out" || true
|
||||
sleep "${INTERVAL:-1}"
|
||||
done
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=${EVIDENCE_DIR:-evidence}
|
||||
mkdir -p "$out"
|
||||
psql() { docker compose exec -T postgres psql -U messenger -d messenger -X -c "$1"; }
|
||||
value() { docker compose exec -T postgres psql -U messenger -d messenger -X -tA -c "$1"; }
|
||||
cli() { docker compose run --rm --no-deps -T s3-cli "$@"; }
|
||||
bucket=${S3_BUCKET:-messenger-attachments}
|
||||
{
|
||||
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD)"
|
||||
echo "\$ docker compose ps --format '{{.Service}} {{.Status}} {{.Ports}}'"
|
||||
docker compose ps -a --format '{{.Service}} {{.Status}} {{.Ports}}'
|
||||
for table in attachments message_attachments; do
|
||||
echo "\$ psql -c '\\d $table'"
|
||||
psql "\\d $table"
|
||||
done
|
||||
echo "\$ psql: столбцы bytea во всей схеме (хеши токенов и отпечатки, не файлы)"
|
||||
psql "SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = 'public' AND data_type = 'bytea' ORDER BY 1, 2"
|
||||
echo "\$ psql: вложения по статусу и максимальный размер строки attachments"
|
||||
psql "SELECT status, count(*), max(pg_column_size(a.*)) AS max_row_bytes FROM attachments a GROUP BY status"
|
||||
echo "\$ rc object list --recursive root/$bucket/attachments/ | count"
|
||||
cli object list --recursive "root/$bucket/attachments/" --json | grep -c '"key"' || true
|
||||
echo "\$ rc object list root/$bucket/ (первые 3 объекта, ключи назначены сервером)"
|
||||
cli object list --recursive "root/$bucket/attachments/" | head -3
|
||||
row=$(value "SELECT object_key || ' ' || sha256 || ' ' || size_bytes FROM attachments WHERE status = 'ready' ORDER BY created_at DESC LIMIT 1")
|
||||
key=${row%% *}
|
||||
echo "\$ сверка вне API: sha256 и размер последнего ready-вложения в PostgreSQL против байтов объекта в bucket"
|
||||
echo "postgres: ${row#* }"
|
||||
echo "s3: $(cli sh -c "rc object show root/$bucket/$key | sha256sum | cut -d' ' -f1") $(cli sh -c "rc object show root/$bucket/$key | wc -c" | tr -d ' ')"
|
||||
echo "\$ docker inspect api: ReadonlyRootfs, tmpfs, volumes/bind mounts"
|
||||
for id in $(docker compose ps -q api); do
|
||||
docker inspect -f '{{.Config.Hostname}} ro={{.HostConfig.ReadonlyRootfs}} tmpfs={{json .HostConfig.Tmpfs}} mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' "$id"
|
||||
done
|
||||
echo "\$ docker inspect s3: volume данных"
|
||||
docker inspect -f '{{range .Mounts}}{{.Type}}:{{.Name}}:{{.Destination}} {{end}}' "$(docker compose ps -q s3)"
|
||||
echo "\$ секреты сервисов: root-ключи S3 только у s3/s3-init/s3-cli"
|
||||
docker compose config --format json | python3 -c 'import json,sys
|
||||
for name, service in sorted(json.load(sys.stdin)["services"].items()):
|
||||
print(name, sorted(s["source"] for s in service.get("secrets", [])))'
|
||||
} > "$out"/storage-layout.txt
|
||||
cat "$out"/storage-layout.txt
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
cli() { docker compose exec -T valkey sh -c "REDISCLI_AUTH=\"\$(sed -n 's/^requirepass //p' /run/secrets/valkey.conf)\" valkey-cli $1"; }
|
||||
psql() { docker compose exec -T postgres psql -U messenger -d messenger -tA -c "$1"; }
|
||||
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse --short HEAD)"
|
||||
echo "\$ valkey-cli config get appendonly appendfsync maxmemory maxmemory-policy"
|
||||
cli "config get appendonly" ; cli "config get appendfsync"; cli "config get maxmemory"; cli "config get maxmemory-policy"
|
||||
echo "\$ valkey-cli info persistence | grep aof_enabled,aof_last_write_status"
|
||||
cli "info persistence" | grep -E '^aof_enabled|^aof_last_write_status'
|
||||
echo "\$ valkey-cli dbsize; info stats | grep keyspace"
|
||||
cli dbsize
|
||||
cli "info stats" | grep -E '^keyspace_(hits|misses)'
|
||||
echo "\$ valkey-cli --scan --pattern 'session:*' и вид значения (хеш сокращён, значения не печатаются)"
|
||||
revoked=0; cached=0; key=""; stored=""
|
||||
for k in $(cli "--scan --pattern session:* --count 1000"); do
|
||||
if [ "$(cli "get $k")" = "-" ]; then
|
||||
revoked=$((revoked + 1)); printf '%.16s… отметка отзыва "-"\n' "$k"; continue
|
||||
fi
|
||||
cached=$((cached + 1)); printf '%.16s… сессия\n' "$k"
|
||||
if [ -z "$key" ]; then
|
||||
stored=$(psql "SELECT (extract(epoch FROM expires_at) * 1000)::bigint FROM sessions WHERE token_hash = decode('${k#session:}', 'hex')")
|
||||
if [ -n "$stored" ]; then key=$k; fi
|
||||
fi
|
||||
done
|
||||
echo "tombstones: $revoked, cached sessions: $cached"
|
||||
if [ "$revoked" -eq 0 ] || [ -z "$key" ]; then
|
||||
echo "нужны закэшированная сессия из БД и отметка отзыва: сначала make test" >&2
|
||||
exit 1
|
||||
fi
|
||||
expires=$(cli "pexpiretime $key")
|
||||
echo "\$ срок ключа кэша против срока сессии для $(printf '%.16s' "$key")…"
|
||||
echo "valkey pexpiretime, ms: $expires"
|
||||
echo "postgres expires_at, ms: $stored"
|
||||
if [ "$expires" -le "$stored" ]; then echo "ключ не переживает сессию: да"; else echo "ключ не переживает сессию: НЕТ"; exit 1; fi
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=${EVIDENCE_DIR:-evidence}
|
||||
mkdir -p "$out"
|
||||
base=${1:-http://$(docker compose port lb 8080)}
|
||||
stats=http://$(docker compose port lb 8404)/stats\;csv
|
||||
header() { echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD)"; }
|
||||
{
|
||||
header
|
||||
echo "\$ docker compose --env-file .env config --quiet && echo valid"
|
||||
docker compose --env-file .env config --quiet && echo valid
|
||||
echo "\$ docker compose ps --format '{{.Service}} {{.Name}} {{.Status}} {{.Ports}}'"
|
||||
docker compose ps --format '{{.Service}} {{.Name}} {{.Status}} {{.Ports}}'
|
||||
echo "\$ docker compose config | grep -c container_name"
|
||||
docker compose config | grep -c container_name || true
|
||||
echo "\$ docker port <каждая реплика api> # реплики не публикуют порт"
|
||||
for id in $(docker compose ps -q api); do echo "$(docker inspect -f '{{.Config.Hostname}}' "$id"): [$(docker port "$id")]"; done
|
||||
echo "\$ docker inspect: hostname = X-Instance-Id, сети, лимиты CPU (nano) и памяти"
|
||||
for id in $(docker compose ps -q); do
|
||||
docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Config.Hostname}} {{.Name}} nets={{range $k, $v := .NetworkSettings.Networks}}{{$k}},{{end}} cpus={{.HostConfig.NanoCpus}} mem={{.HostConfig.Memory}} user={{.Config.User}} ro={{.HostConfig.ReadonlyRootfs}}' "$id"
|
||||
done | sort
|
||||
echo "\$ curl LB stats: backend api, server status check"
|
||||
curl -fsS "$stats" | python3 -c 'import csv,sys
|
||||
for r in csv.DictReader(sys.stdin.read().lstrip("# ").splitlines()):
|
||||
if r["pxname"] == "api" and r["status"] != "MAINT (resolution)":
|
||||
print(r["svname"], r["status"], r["check_status"], r["check_code"])'
|
||||
echo "\$ for i in 1..6: curl -D - $base/health/live | X-Instance-Id"
|
||||
for _ in 1 2 3 4 5 6; do curl -fsS -D - -o /dev/null "$base/health/live" | tr -d '\r' | grep -i '^x-instance-id'; done
|
||||
} > "$out"/stack.txt
|
||||
{
|
||||
header
|
||||
echo "host: $(sysctl -n machdep.cpu.brand_string 2>/dev/null || uname -m), $(sysctl -n hw.ncpu 2>/dev/null) CPU, $(($(sysctl -n hw.memsize 2>/dev/null || echo 0) / 1073741824)) GiB RAM, $(sw_vers -productName 2>/dev/null) $(sw_vers -productVersion 2>/dev/null)"
|
||||
echo "docker: $(docker version -f '{{.Server.Version}}'), VM: $(docker info -f '{{.NCPU}}') CPU, $(docker info -f '{{.MemTotal}}') bytes"
|
||||
echo "compose: $(docker compose version --short)"
|
||||
echo "images:"
|
||||
grep -h -E 'image:|@sha256' compose.yaml Dockerfile | sed 's/^ */ /'
|
||||
echo "python in image: $(docker exec "$(docker compose ps -q api | head -1)" python -V)"
|
||||
echo "haproxy: $(docker compose exec -T lb haproxy -v | head -1)"
|
||||
echo "rustfs: $(docker compose exec -T s3 rustfs --version 2>/dev/null | head -1)"
|
||||
echo "rabbitmq: $(docker compose exec -T broker rabbitmqctl -q version 2>/dev/null | head -1)"
|
||||
echo "packages (uv.lock):"
|
||||
for name in fastapi uvicorn uvicorn-worker gunicorn sqlalchemy alembic asyncpg argon2-cffi pydantic pydantic-settings dishka structlog redis aiobotocore botocore aiohttp pillow \
|
||||
faststream aio-pika aiormq dishka-faststream; do
|
||||
printf ' %s %s\n' "$name" "$(sed -n "/^name = \"$name\"$/{n;s/version = \"\(.*\)\"/\1/p;}" uv.lock)"
|
||||
done
|
||||
echo "process users (service uid command):"
|
||||
for id in $(docker compose ps -q); do
|
||||
service=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}}' "$id")
|
||||
docker top "$id" -eo pid,uid,comm | awk -v s="$service" 'NR > 1 {print " " s, $2, $3}'
|
||||
done | sort -u
|
||||
} > "$out"/environment.txt
|
||||
cat "$out"/stack.txt "$out"/environment.txt
|
||||
Executable
+47
@@ -0,0 +1,47 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=${EVIDENCE_DIR:-evidence}
|
||||
mkdir -p "$out"
|
||||
psql() { docker compose exec -T postgres psql -U messenger -d messenger -c "$1"; }
|
||||
header() { echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD)"; }
|
||||
counts="SELECT (SELECT count(*) FROM users) users, (SELECT count(*) FROM sessions) sessions, (SELECT count(*) FROM chats) chats, (SELECT count(*) FROM chat_members) members, (SELECT count(*) FROM messages) messages, (SELECT count(*) FROM idempotency_keys) keys, (SELECT count(*) FROM attachments) attachments, (SELECT count(*) FROM message_attachments) links, (SELECT count(*) FROM alembic_version) versions"
|
||||
kdf="SELECT substring(password_hash from '^[$]argon2id[$]v=[0-9]+[$]m=[0-9]+,t=[0-9]+,p=[0-9]+[$]') AS kdf_prefix, username = 'seed_author' AS seed_stub, count(*) AS users, min(length(password_hash)) AS min_length, max(length(password_hash)) AS max_length FROM users GROUP BY 1, 2 ORDER BY 2"
|
||||
tokens="SELECT octet_length(token_hash) AS stored_bytes, count(*) AS sessions FROM sessions GROUP BY 1"
|
||||
{
|
||||
header
|
||||
for table in users sessions chats chat_members messages idempotency_keys attachments message_attachments alembic_version; do
|
||||
echo "\$ psql -c '\\d+ $table'"
|
||||
psql "\\d+ $table"
|
||||
done
|
||||
echo "\$ psql -c 'SELECT version_num FROM alembic_version'"
|
||||
psql "SELECT version_num FROM alembic_version"
|
||||
} > "$out"/schema.txt
|
||||
{
|
||||
header
|
||||
echo "\$ psql -c \"$counts\""
|
||||
psql "$counts"
|
||||
echo "\$ make migrate"
|
||||
docker compose run --rm migrate 2>/dev/null
|
||||
echo "\$ psql -c \"$counts\""
|
||||
psql "$counts"
|
||||
} > "$out"/migrations.txt
|
||||
{
|
||||
header
|
||||
echo "\$ psql -c \"$kdf\""
|
||||
psql "$kdf"
|
||||
echo "\$ psql -c \"$tokens\""
|
||||
psql "$tokens"
|
||||
} > "$out"/kdf.txt
|
||||
{
|
||||
header
|
||||
echo "\$ git ls-files secrets .env backups volumes"
|
||||
git ls-files secrets .env backups volumes
|
||||
echo "(пусто: секретов, .env, дампов и volumes в Git нет)"
|
||||
echo "\$ git check-ignore -v secrets/database_url secrets/postgres_password secrets/s3_root_password secrets/s3_secret_access_key .env backups/"
|
||||
git check-ignore -v secrets/database_url secrets/postgres_password secrets/s3_root_password secrets/s3_secret_access_key .env backups/
|
||||
project=$(docker compose config --format json | python3 -c 'import json,sys; print(json.load(sys.stdin)["name"])')
|
||||
echo "\$ docker volume ls --filter label=com.docker.compose.project=$project"
|
||||
docker volume ls --filter "label=com.docker.compose.project=$project"
|
||||
} > "$out"/secrets.txt
|
||||
echo ""$out"/{schema,migrations,kdf,secrets}.txt обновлены"
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=${1:-evidence/failover-each}
|
||||
rm -rf "$out"
|
||||
mkdir -p "$out"
|
||||
scripts/restore.sh
|
||||
hosts=$(docker inspect -f '{{.Config.Hostname}}' $(docker compose ps -q "${API_SERVICE:-api}"))
|
||||
failed=0
|
||||
set --
|
||||
for host in $hosts; do
|
||||
TARGET_INSTANCE_ID=$host python3 scripts/probe.py load --expect dip --out "$out/$host" \
|
||||
-- sh -c "scripts/stop-one.sh && docker compose ps -a --format '{{.ID}} {{.Service}} {{.Status}}' ${API_SERVICE:-api} && { scripts/stand-usage.sh & sleep ${HOLD:-10}; wait; } && scripts/restore.sh" || failed=1
|
||||
scripts/restore.sh
|
||||
set -- "$@" "$out/$host/result.json"
|
||||
done
|
||||
python3 -c 'import json,sys; print(json.dumps([json.load(open(p)) for p in sys.argv[1:]], ensure_ascii=False, indent=2))' "$@" > "$out/summary.tmp"
|
||||
mv "$out/summary.tmp" "$out/summary.json"
|
||||
exit "$failed"
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
out=${EVIDENCE_DIR:-evidence}
|
||||
mkdir -p "$out"
|
||||
replicas() {
|
||||
docker inspect -f '{{.Config.Hostname}} {{.State.Status}} started={{.State.StartedAt}} finished={{.State.FinishedAt}}' $(docker compose ps -aq "${API_SERVICE:-api}")
|
||||
}
|
||||
url=${1:-http://localhost:8080}
|
||||
shift=0
|
||||
while [ "$shift" -lt "${2:-0}" ]; do curl -fsS -o /dev/null "$url/health/live"; shift=$((shift + 1)); done
|
||||
tmp="$out"/failover.tmp
|
||||
since=$(date -u +%FT%TZ)
|
||||
{
|
||||
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD)"
|
||||
echo "== before: api replicas (hostname = X-Instance-Id), state, StartedAt, FinishedAt"
|
||||
replicas
|
||||
echo "\$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh"
|
||||
make --no-print-directory test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL="$url"
|
||||
echo "== after: api replicas"
|
||||
replicas
|
||||
} > "$tmp" 2>&1
|
||||
stopped=$(replicas | awk '$2 == "exited" {print $1}')
|
||||
{
|
||||
echo "== stopped replica: $stopped; shutdown: signal, drain window with readiness 503, close, exit"
|
||||
docker logs --since "$since" "$stopped" 2>&1 | grep -E 'Handling signal|service.draining|"status":503|Shutting down|Waiting for conn|Finished server|service.stopped|SIGTERM' | tail -16
|
||||
echo "\$ scripts/restore.sh"
|
||||
scripts/restore.sh
|
||||
echo "== after restore"
|
||||
replicas
|
||||
} >> "$tmp" 2>&1
|
||||
mv "$tmp" "$out/failover-$stopped.txt"
|
||||
cat "$out/failover-$stopped.txt"
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
out=${1:?usage: k6.sh <output dir> [k6 run args]}
|
||||
shift
|
||||
mkdir -p "$out"
|
||||
out=$(cd "$out" && pwd)
|
||||
cd "$(dirname "$0")/.."
|
||||
exec docker compose --profile bench run --rm --no-deps -T -u "$(id -u):$(id -g)" -v "$out:/out" \
|
||||
-e RATE -e WARMUP -e DURATION -e USERS -e READ_RATIO -e VUS -e MAX_VUS -e RUN_ID \
|
||||
k6 run --quiet "$@" "/scripts/${K6_SCRIPT:-messages.js}"
|
||||
Executable
+263
@@ -0,0 +1,263 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
client = __import__("client")
|
||||
Client, Failure, check = client.Client, client.Failure, client.check
|
||||
FIXTURE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def compose(*args, stdin=None):
|
||||
cmd = ["docker", "compose", *args]
|
||||
return subprocess.run(cmd, cwd=ROOT, input=stdin, capture_output=True, text=True, check=False)
|
||||
|
||||
|
||||
def containers(service):
|
||||
ids = compose("ps", "-aq", service).stdout.split()
|
||||
fields = ("hostname", "status", "exit_code", "started_at", "finished_at")
|
||||
template = (
|
||||
"{{.Config.Hostname}} {{.State.Status}} {{.State.ExitCode}}"
|
||||
" {{.State.StartedAt}} {{.State.FinishedAt}}"
|
||||
)
|
||||
out = subprocess.run(
|
||||
["docker", "inspect", "-f", template, *ids], capture_output=True, text=True, check=False
|
||||
)
|
||||
return [dict(zip(fields, line.split())) for line in out.stdout.splitlines()]
|
||||
|
||||
|
||||
def upload(c, actor, chat, expected=202):
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png"
|
||||
schema = "Attachment" if expected == 202 else None
|
||||
return c.call(
|
||||
"POST",
|
||||
path,
|
||||
expected,
|
||||
actor=actor,
|
||||
raw=FIXTURE,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
|
||||
def content(c, actor, attachment, expected=200):
|
||||
return c.call("GET", f"/api/v1/attachments/{attachment['id']}/content", expected, actor=actor)
|
||||
|
||||
|
||||
def timed(fn):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = fn()
|
||||
except Failure as exc:
|
||||
return {
|
||||
"status": "failure",
|
||||
"seconds": round(time.monotonic() - started, 3),
|
||||
"error": str(exc),
|
||||
}
|
||||
seconds = round(time.monotonic() - started, 3)
|
||||
return {
|
||||
"status": response["status"],
|
||||
"seconds": seconds,
|
||||
"instance": response["headers"].get("X-Instance-Id"),
|
||||
}
|
||||
|
||||
|
||||
def wait(fn, seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
return fn()
|
||||
except Failure:
|
||||
if time.monotonic() > deadline:
|
||||
raise
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def failover_upload(c, args):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
sent = upload(c, alice, chat)
|
||||
att, target = sent["json"], sent["headers"]["X-Instance-Id"]
|
||||
c.wait_ready(bob, att)
|
||||
started = time.monotonic()
|
||||
hook = subprocess.run(
|
||||
[str(ROOT / "scripts/stop-one.sh")],
|
||||
cwd=ROOT,
|
||||
env=dict(os.environ, TARGET_INSTANCE_ID=target),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
check(hook.returncode == 0, f"stop-one.sh failed: {hook.stderr.strip()}")
|
||||
hook_seconds = time.monotonic() - started
|
||||
got = wait(lambda: content(c, bob, att), 15)
|
||||
recovered = time.monotonic() - started
|
||||
served = got["headers"].get("X-Instance-Id")
|
||||
check(served != target, "download served by the stopped replica")
|
||||
during = containers(args.service)
|
||||
states = {item["hostname"]: item["status"] for item in during}
|
||||
check(states.get(target) == "exited", f"target {target} is not exited: {states}")
|
||||
check(states.get(served) == "running", f"neighbour {served} is not running: {states}")
|
||||
digest = hashlib.sha256(got["bytes"]).hexdigest()
|
||||
check(
|
||||
digest == att["sha256"] == hashlib.sha256(FIXTURE).hexdigest(),
|
||||
"sha256 mismatch after failover",
|
||||
)
|
||||
if args.restore:
|
||||
compose("up", "-d", "--wait", "--no-recreate", "--no-deps", args.service)
|
||||
return {
|
||||
"scenario": "failover-upload",
|
||||
"upload_instance": target,
|
||||
"download_instance": served,
|
||||
"sha256_equal": True,
|
||||
"hook_seconds": round(hook_seconds, 3),
|
||||
"download_ok_after_seconds": round(recovered, 3),
|
||||
"replicas_at_download": during,
|
||||
"restored": args.restore,
|
||||
"replicas_after_restore": containers(args.service) if args.restore else None,
|
||||
}
|
||||
|
||||
|
||||
def s3_outage(c, args):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
att = c.wait_ready(bob, upload(c, alice, chat)["json"])
|
||||
check(
|
||||
compose("stop", "-t", "10", args.s3_service).returncode == 0, "docker compose stop failed"
|
||||
)
|
||||
try:
|
||||
during = {
|
||||
"upload": timed(lambda: upload(c, alice, chat, [503])),
|
||||
"metadata": timed(
|
||||
lambda: c.call("GET", f"/api/v1/attachments/{att['id']}", [200, 503], actor=bob)
|
||||
),
|
||||
"download": timed(lambda: content(c, bob, att, 503)),
|
||||
"text_message": timed(lambda: c.message(alice, chat, "S3 недоступен, текст работает")),
|
||||
"health_ready": timed(lambda: c.call("GET", "/health/ready", [200, 503])),
|
||||
}
|
||||
stopped = containers(args.s3_service)
|
||||
finally:
|
||||
started = time.monotonic()
|
||||
compose("up", "-d", "--wait", "--no-deps", "--no-recreate", args.s3_service)
|
||||
recovered = round(time.monotonic() - started, 3)
|
||||
got = wait(lambda: content(c, bob, att), 30)
|
||||
check(got["bytes"] == FIXTURE, "attachment changed across S3 outage")
|
||||
expected = {"upload": 503, "download": 503, "text_message": 201}
|
||||
check(all(during[k]["status"] == v for k, v in expected.items()), f"S3 outage: {during}")
|
||||
check(all(during[k]["seconds"] < 6 for k in ("upload", "download")), "S3 timeout exceeded")
|
||||
return {
|
||||
"scenario": "s3-outage",
|
||||
"s3_container_during_outage": stopped,
|
||||
"during_outage": during,
|
||||
"expected": expected,
|
||||
"as_expected": all(during[k]["status"] == v for k, v in expected.items()),
|
||||
"s3_back_healthy_seconds": recovered,
|
||||
"download_after_recovery": "sha256 equal",
|
||||
}
|
||||
|
||||
|
||||
def abort_upload(c, args):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
name = f"abort-{uuid.uuid4().hex}.png"
|
||||
parts = urlsplit(c.base)
|
||||
factory = http.client.HTTPSConnection if parts.scheme == "https" else http.client.HTTPConnection
|
||||
conn = factory(parts.netloc, timeout=10)
|
||||
conn.putrequest("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={name}")
|
||||
headers = {
|
||||
"Authorization": f"Bearer {alice['token']}",
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": str(args.declared),
|
||||
"Accept": "application/json",
|
||||
}
|
||||
for key, value in headers.items():
|
||||
conn.putheader(key, value)
|
||||
conn.endheaders()
|
||||
conn.send(FIXTURE[:8] + os.urandom(args.sent - 8))
|
||||
conn.close()
|
||||
time.sleep(args.settle)
|
||||
user, db = os.environ.get("PGUSER", "messenger"), os.environ.get("PGDATABASE", "messenger")
|
||||
sql = "SELECT status, count(*) FROM attachments WHERE filename = :'name' GROUP BY status;\n"
|
||||
out = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-qAt",
|
||||
"-F",
|
||||
" ",
|
||||
"-U",
|
||||
user,
|
||||
"-d",
|
||||
db,
|
||||
"-v",
|
||||
f"name={name}",
|
||||
stdin=sql,
|
||||
)
|
||||
rows = out.stdout.split()
|
||||
counts = dict(zip(rows[::2], (int(x) for x in rows[1::2])))
|
||||
check(out.returncode == 0, "cannot inspect aborted upload")
|
||||
check(counts.get("ready", 0) == 0, "aborted upload became ready")
|
||||
alive = c.call("GET", "/api/v1/users/me", actor=alice, schema="User")["status"]
|
||||
return {
|
||||
"scenario": "abort-upload",
|
||||
"declared_bytes": args.declared,
|
||||
"sent_bytes": args.sent,
|
||||
"settle_seconds": args.settle,
|
||||
"rows_by_status": counts,
|
||||
"ready_rows": counts.get("ready", 0),
|
||||
"api_still_serves": alive == 200,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(
|
||||
description="Lab4 failure scenarios over the public HTTP contract plus docker compose"
|
||||
)
|
||||
p.add_argument("scenario", choices=["failover-upload", "s3-outage", "abort-upload"])
|
||||
p.add_argument("--base-url", default=None)
|
||||
p.add_argument("--ca-file", default=None)
|
||||
p.add_argument("--timeout", type=float, default=15)
|
||||
p.add_argument("--service", default="api")
|
||||
p.add_argument("--s3-service", default="s3")
|
||||
p.add_argument(
|
||||
"--restore", action="store_true", help="failover-upload: start the stopped replica again"
|
||||
)
|
||||
p.add_argument("--declared", type=int, default=5 * 1024 * 1024)
|
||||
p.add_argument("--sent", type=int, default=256 * 1024)
|
||||
p.add_argument("--settle", type=float, default=3)
|
||||
p.add_argument("--output", metavar="FILE")
|
||||
args = p.parse_args()
|
||||
c = Client(args.base_url, args.ca_file, timeout=args.timeout)
|
||||
run = {
|
||||
"failover-upload": failover_upload,
|
||||
"s3-outage": s3_outage,
|
||||
"abort-upload": abort_upload,
|
||||
}[args.scenario]
|
||||
commit = subprocess.run(
|
||||
["git", "rev-parse", "HEAD"], cwd=ROOT, capture_output=True, check=False
|
||||
)
|
||||
stamp = {
|
||||
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"commit": commit.stdout.decode().strip(),
|
||||
}
|
||||
try:
|
||||
report = {"ok": True, **stamp, **run(c, args)}
|
||||
except Failure as exc:
|
||||
report = {"scenario": args.scenario, "ok": False, **stamp, "error": str(exc)}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + "\n")
|
||||
print(text)
|
||||
sys.exit(0 if report["ok"] else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+352
@@ -0,0 +1,352 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAX_UPLOAD = 10 * 1024 * 1024
|
||||
COLUMNS = (
|
||||
"id",
|
||||
"chat_id",
|
||||
"owner_id",
|
||||
"filename",
|
||||
"content_type",
|
||||
"size_bytes",
|
||||
"sha256",
|
||||
"width",
|
||||
"height",
|
||||
"object_key",
|
||||
"status",
|
||||
)
|
||||
|
||||
|
||||
def chunk(tag, data):
|
||||
return (
|
||||
struct.pack(">I", len(data))
|
||||
+ tag
|
||||
+ data
|
||||
+ struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
)
|
||||
|
||||
|
||||
def png(width, height):
|
||||
raw = b"".join(b"\x00" + os.urandom(width * 3) for _ in range(height))
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(raw, 1))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def sized_png(target):
|
||||
height = max(1, target // (1024 * 3 + 1))
|
||||
body = png(1024, height)
|
||||
while len(body) > min(target, MAX_UPLOAD) and height > 1:
|
||||
height -= max(1, (len(body) - target) // 3073 + 1)
|
||||
body = png(1024, height)
|
||||
return body
|
||||
|
||||
|
||||
def run(cmd, stdin=None):
|
||||
out = subprocess.run(cmd, cwd=ROOT, input=stdin, capture_output=True, check=False)
|
||||
if out.returncode:
|
||||
raise SystemExit(
|
||||
f"command failed: {' '.join(cmd[:6])}\n{out.stderr.decode(errors='replace')[-500:]}"
|
||||
)
|
||||
return out.stdout.decode()
|
||||
|
||||
|
||||
def psql(sql, stdin=None):
|
||||
user, db = os.environ.get("PGUSER", "messenger"), os.environ.get("PGDATABASE", "messenger")
|
||||
psql = [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-qAt",
|
||||
"-F",
|
||||
" ",
|
||||
]
|
||||
return run([*psql, "-U", user, "-d", db, "-c", sql], stdin)
|
||||
|
||||
|
||||
def direct(args):
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
prefix = os.environ.get("S3_PREFIX", "attachments/")
|
||||
if args.chat_id and args.owner_id:
|
||||
chat_id, owner_id = args.chat_id, args.owner_id
|
||||
else:
|
||||
found = psql(
|
||||
"SELECT chat_id, owner_id FROM attachments ORDER BY created_at LIMIT 1"
|
||||
).split()
|
||||
if len(found) != 2:
|
||||
raise SystemExit(
|
||||
"no attachment rows yet: upload one via API or pass --chat-id and --owner-id"
|
||||
)
|
||||
chat_id, owner_id = found
|
||||
rows = []
|
||||
started = time.monotonic()
|
||||
with tempfile.TemporaryDirectory(prefix="lab4-seed-") as tmp:
|
||||
Path(tmp).chmod(0o755)
|
||||
for i in range(args.count):
|
||||
aid = str(uuid.uuid4())
|
||||
body = png(8, 8)
|
||||
path = Path(tmp) / aid
|
||||
path.write_bytes(body)
|
||||
path.chmod(0o644)
|
||||
digest = hashlib.sha256(body).hexdigest()
|
||||
rows.append(
|
||||
f"{aid},{chat_id},{owner_id},seed-{i}.png,image/png,{len(body)},{digest},8,8,{prefix}{aid},ready"
|
||||
)
|
||||
generated = time.monotonic()
|
||||
cli = [
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"-v",
|
||||
f"{tmp}:/seed:ro",
|
||||
"s3-cli",
|
||||
]
|
||||
run([*cli, "put", "--recursive", "--no-progress", "/seed/", f"root/{bucket}/{prefix}"])
|
||||
uploaded = time.monotonic()
|
||||
columns = ", ".join(COLUMNS)
|
||||
psql(
|
||||
f"COPY attachments ({columns}) FROM STDIN WITH (FORMAT csv)",
|
||||
"".join(f"{r}\n" for r in rows).encode(),
|
||||
)
|
||||
seconds = {
|
||||
"generate": round(generated - started, 3),
|
||||
"s3_put": round(uploaded - generated, 3),
|
||||
"pg_copy": round(time.monotonic() - uploaded, 3),
|
||||
}
|
||||
return {"mode": "direct", "count": args.count, "seconds": seconds}
|
||||
|
||||
|
||||
class Http:
|
||||
def __init__(self, base, timeout):
|
||||
parts = urlsplit(base)
|
||||
self.cls = (
|
||||
http.client.HTTPSConnection if parts.scheme == "https" else http.client.HTTPConnection
|
||||
)
|
||||
self.host, self.timeout, self.local = parts.netloc, timeout, threading.local()
|
||||
|
||||
def call(self, method, path, body=None, headers=None, token=None):
|
||||
conn = getattr(self.local, "conn", None) or self.cls(self.host, timeout=self.timeout)
|
||||
self.local.conn = conn
|
||||
h = {"Accept": "application/json"}
|
||||
if token:
|
||||
h["Authorization"] = "Bearer " + token
|
||||
if isinstance(body, dict):
|
||||
body, h["Content-Type"] = json.dumps(body).encode(), "application/json"
|
||||
h.update(headers or {})
|
||||
try:
|
||||
conn.request(method, path, body=body, headers=h)
|
||||
response = conn.getresponse()
|
||||
data = response.read()
|
||||
except (OSError, http.client.HTTPException):
|
||||
conn.close()
|
||||
self.local.conn = None
|
||||
return 0, {}, b""
|
||||
return response.status, {k.lower(): v for k, v in response.getheaders()}, data
|
||||
|
||||
|
||||
def login(api, label):
|
||||
name = f"seed_{label}_{uuid.uuid4().hex[:12]}"
|
||||
password = "Seed-" + uuid.uuid4().hex
|
||||
body = {"username": name, "display_name": label, "password": password}
|
||||
status, _, data = api.call("POST", "/api/v1/users", body)
|
||||
if status != 201:
|
||||
raise SystemExit(f"user create failed: {status}")
|
||||
user = json.loads(data)
|
||||
basic = base64.b64encode(f"{name}:{password}".encode()).decode()
|
||||
status, _, data = api.call(
|
||||
"POST", "/api/v1/auth/sessions", headers={"Authorization": f"Basic {basic}"}
|
||||
)
|
||||
if status != 201:
|
||||
raise SystemExit(f"login failed: {status}")
|
||||
return user["id"], json.loads(data)["token"]
|
||||
|
||||
|
||||
def mib(text):
|
||||
m = re.match(r"([\d.]+)\s*([KMG]i?B)", text)
|
||||
if not m:
|
||||
return 0.0
|
||||
scale = {"KiB": 1 / 1024, "KB": 1 / 1024, "GiB": 1024, "GB": 1024}
|
||||
return float(m.group(1)) * scale.get(m.group(2), 1)
|
||||
|
||||
|
||||
def sampler(ids, peaks, stop):
|
||||
while not stop.is_set():
|
||||
cmd = ["docker", "stats", "--no-stream", "--format", "{{.ID}} {{.MemUsage}}", *ids]
|
||||
out = subprocess.run(cmd, capture_output=True, text=True, check=False).stdout
|
||||
for line in out.splitlines():
|
||||
cid, usage = line.split(" ", 1)
|
||||
peaks[cid] = max(peaks.get(cid, 0.0), mib(usage))
|
||||
|
||||
|
||||
def cgroup(cid, name):
|
||||
cmd = ["docker", "exec", cid, "cat", f"/sys/fs/cgroup/{name}"]
|
||||
return subprocess.run(cmd, capture_output=True, text=True, check=False).stdout.strip()
|
||||
|
||||
|
||||
def percentile(values, q):
|
||||
return (
|
||||
round(sorted(values)[min(len(values) - 1, int(q * len(values)))] * 1000, 1)
|
||||
if values
|
||||
else None
|
||||
)
|
||||
|
||||
|
||||
def over_http(args):
|
||||
api = Http(args.base_url, args.timeout)
|
||||
alice, token = login(api, "alice")
|
||||
bob, _ = login(api, "bob")
|
||||
status, _, data = api.call(
|
||||
"POST", "/api/v1/chats", {"title": "seed", "member_ids": [alice, bob]}, token=token
|
||||
)
|
||||
if status != 201:
|
||||
raise SystemExit(f"chat create failed: {status}")
|
||||
chat = json.loads(data)["id"]
|
||||
fixed = sized_png(args.size) if args.size else None
|
||||
counter, lock, results = iter(range(args.count)), threading.Lock(), []
|
||||
ids = run(["docker", "compose", "ps", "-q", args.service]).split() if args.sample else []
|
||||
idle = {cid: round(int(cgroup(cid, "memory.current") or 0) / 1048576, 1) for cid in ids}
|
||||
peaks, stop = {}, threading.Event()
|
||||
watcher = threading.Thread(target=sampler, args=(ids, peaks, stop), daemon=True)
|
||||
if ids:
|
||||
watcher.start()
|
||||
|
||||
def worker():
|
||||
while True:
|
||||
with lock:
|
||||
i = next(counter, None)
|
||||
if i is None:
|
||||
return
|
||||
body = fixed or png(8, 8)
|
||||
began = time.monotonic()
|
||||
path = f"/api/v1/chats/{chat}/attachments?filename=seed-{i}.png"
|
||||
status, headers, data = api.call(
|
||||
"POST", path, body, {"Content-Type": "image/png"}, token
|
||||
)
|
||||
created = json.loads(data)["id"] if status == 201 else None
|
||||
results.append(
|
||||
(status, time.monotonic() - began, headers.get("x-instance-id", ""), created)
|
||||
)
|
||||
|
||||
started = time.monotonic()
|
||||
threads = [threading.Thread(target=worker) for _ in range(args.concurrency)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
elapsed = time.monotonic() - started
|
||||
stop.set()
|
||||
if ids:
|
||||
watcher.join()
|
||||
created = [r[3] for r in results if r[3]]
|
||||
for start in range(0, min(args.link, len(created)), 10):
|
||||
body = {"text": "", "attachment_ids": created[start : min(start + 10, args.link)]}
|
||||
api.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat}/messages",
|
||||
body,
|
||||
{"Idempotency-Key": uuid.uuid4().hex},
|
||||
token,
|
||||
)
|
||||
if args.ids_out:
|
||||
Path(args.ids_out).write_text("".join(f"{i}\n" for i in created))
|
||||
codes, instances = {}, {}
|
||||
for status, _, instance, _ in results:
|
||||
codes[str(status)] = codes.get(str(status), 0) + 1
|
||||
instances[instance] = instances.get(instance, 0) + 1
|
||||
ok = [r[1] for r in results if r[0] == 201]
|
||||
memory = {}
|
||||
for cid in ids:
|
||||
peak = cgroup(cid, "memory.peak")
|
||||
events = dict(line.split() for line in cgroup(cid, "memory.events").splitlines())
|
||||
memory[cid[:12]] = {
|
||||
"idle_mib": idle[cid],
|
||||
"docker_stats_peak_mib": round(peaks.get(cid[:12], 0.0), 1),
|
||||
"cgroup_memory_peak_mib": round(int(peak) / 1048576, 1) if peak.isdigit() else None,
|
||||
"oom_kill": int(events.get("oom_kill", 0)),
|
||||
}
|
||||
return {
|
||||
"mode": "http",
|
||||
"count": args.count,
|
||||
"concurrency": args.concurrency,
|
||||
"body_bytes": len(fixed) if fixed else "~200 (unique 8x8 PNG)",
|
||||
"status_codes": codes,
|
||||
"instances": len([i for i in instances if i]),
|
||||
"linked_in_messages": min(args.link, len(created)),
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_rps": round(len(ok) / elapsed, 2) if elapsed else None,
|
||||
"latency_ms": {
|
||||
"p50": percentile(ok, 0.5),
|
||||
"p95": percentile(ok, 0.95),
|
||||
"p99": percentile(ok, 0.99),
|
||||
"max": percentile(ok, 1.0),
|
||||
},
|
||||
"memory": memory,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(
|
||||
description="Lab4 attachment volume generator: HTTP uploads or direct S3+PG seeding"
|
||||
)
|
||||
p.add_argument("--mode", choices=["http", "direct"], default="http")
|
||||
p.add_argument("--count", type=int, default=1000)
|
||||
p.add_argument("--concurrency", type=int, default=16)
|
||||
p.add_argument(
|
||||
"--size",
|
||||
type=int,
|
||||
default=0,
|
||||
help="http: bytes per upload (one PNG reused); 0 = unique 8x8 PNGs",
|
||||
)
|
||||
p.add_argument(
|
||||
"--link", type=int, default=0, help="http: reference the first N attachments from messages"
|
||||
)
|
||||
p.add_argument(
|
||||
"--sample",
|
||||
action="store_true",
|
||||
help="http: sample docker stats and memory.peak of API containers",
|
||||
)
|
||||
p.add_argument("--service", default="api")
|
||||
p.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
p.add_argument("--timeout", type=float, default=60)
|
||||
p.add_argument("--ids-out", metavar="FILE")
|
||||
p.add_argument("--chat-id")
|
||||
p.add_argument("--owner-id")
|
||||
p.add_argument("--output", metavar="FILE")
|
||||
args = p.parse_args()
|
||||
report = direct(args) if args.mode == "direct" else over_http(args)
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + "\n")
|
||||
print(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export COMPOSE_PROJECT_NAME=${COMPOSE_PROJECT_NAME:-mtusi2026lab6}
|
||||
export LB_HTTP_PORT=${LB_HTTP_PORT:-18086} LB_STATS_PORT=${LB_STATS_PORT:-26085}
|
||||
export BROKER_MANAGEMENT_PORT=${BROKER_MANAGEMENT_PORT:-26086}
|
||||
export PROMETHEUS_PORT=${PROMETHEUS_PORT:-26090} LOKI_PORT=${LOKI_PORT:-26310}
|
||||
export TEMPO_PORT=${TEMPO_PORT:-26320} GRAFANA_PORT=${GRAFANA_PORT:-26300}
|
||||
export BASE_URL=${BASE_URL:-http://127.0.0.1:$LB_HTTP_PORT}
|
||||
export PROMETHEUS_URL=http://127.0.0.1:$PROMETHEUS_PORT LOKI_URL=http://127.0.0.1:$LOKI_PORT
|
||||
export TEMPO_URL=http://127.0.0.1:$TEMPO_PORT GRAFANA_URL=http://127.0.0.1:$GRAFANA_PORT
|
||||
export NO_PROXY=localhost,127.0.0.1,::1
|
||||
exec "$@"
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export COMPOSE_PROJECT_NAME=mtusi2026lab7
|
||||
export BASE_URL=${BASE_URL:-https://localhost:18443}
|
||||
export CA_FILE=${CA_FILE:-$PWD/secrets/pki/operator/ca.crt}
|
||||
export NO_PROXY=localhost,127.0.0.1,::1
|
||||
exec "$@"
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
out=${1:?usage: lb-stats.sh <csv>}
|
||||
cd "$(dirname "$0")/.."
|
||||
url=${LB_STATS_URL:-http://$(docker compose port lb 8404)/stats;csv}
|
||||
curl -fsS "$url" | sed -n '1s/^# /ts,/p' > "$out"
|
||||
while :; do
|
||||
ts=$(date +%s)
|
||||
curl -fsS "$url" | grep -E '^(public|api),' | sed "s/^/$ts,/" >> "$out" || true
|
||||
sleep "${INTERVAL:-1}"
|
||||
done
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
want=${1:-2}
|
||||
deadline=$(($(date +%s) + ${WAIT_TIMEOUT:-90}))
|
||||
until [ "$(docker compose exec -T lb wget -qO- 'http://127.0.0.1:8404/stats;csv' | awk -F, '$1 == "api" && $2 != "BACKEND" && $18 == "UP"' | wc -l)" -ge "$want" ]; do
|
||||
[ "$(date +%s)" -lt "$deadline" ] || { echo "LB readiness timeout" >&2; exit 4; }
|
||||
sleep 1
|
||||
done
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
S3_CLIENT_SECRETS = [
|
||||
"s3_access_key_id",
|
||||
"s3_reconciler_access_key_id",
|
||||
"s3_reconciler_secret_access_key",
|
||||
"s3_worker_access_key_id",
|
||||
"s3_worker_secret_access_key",
|
||||
"s3_root_password",
|
||||
"s3_root_user",
|
||||
"s3_secret_access_key",
|
||||
]
|
||||
RECONCILER_SECRETS = [
|
||||
"database_url",
|
||||
"s3_reconciler_access_key_id",
|
||||
"s3_reconciler_secret_access_key",
|
||||
]
|
||||
OWN_USER = ("postgres", "valkey", "s3-init", "s3-cli")
|
||||
POLICY = {
|
||||
"lb": {"secrets": [], "volumes": [], "networks": ["backend", "edge"], "ports": True},
|
||||
"api": {
|
||||
"secrets": [
|
||||
"cache_url",
|
||||
"cursor_secret",
|
||||
"database_url",
|
||||
"s3_access_key_id",
|
||||
"s3_secret_access_key",
|
||||
],
|
||||
"volumes": [],
|
||||
"networks": ["backend"],
|
||||
},
|
||||
"migrate": {"secrets": ["database_url"], "volumes": [], "networks": ["backend"]},
|
||||
"reconciler": {
|
||||
"secrets": RECONCILER_SECRETS,
|
||||
"volumes": [],
|
||||
"networks": ["backend"],
|
||||
},
|
||||
"postgres": {"secrets": ["postgres_password"], "volumes": ["pgdata"], "networks": ["backend"]},
|
||||
"valkey": {"secrets": ["valkey.conf"], "volumes": ["valkeydata"], "networks": ["backend"]},
|
||||
"k6": {"secrets": [], "volumes": [], "networks": ["edge"]},
|
||||
"s3": {
|
||||
"secrets": ["s3_root_password", "s3_root_user"],
|
||||
"volumes": ["s3data"],
|
||||
"networks": ["backend"],
|
||||
},
|
||||
"s3-init": {"secrets": S3_CLIENT_SECRETS, "volumes": [], "networks": ["backend"]},
|
||||
"s3-cli": {"secrets": S3_CLIENT_SECRETS, "volumes": [], "networks": ["backend"]},
|
||||
"broker": {
|
||||
"secrets": ["rabbitmq_ops_password", "rabbitmq_users"],
|
||||
"volumes": ["broker-data"],
|
||||
"networks": ["backend", "edge"],
|
||||
"ports": True,
|
||||
},
|
||||
"relay": {
|
||||
"secrets": ["broker_url_api", "database_url", "s3_access_key_id", "s3_secret_access_key"],
|
||||
"volumes": [],
|
||||
"networks": ["backend"],
|
||||
},
|
||||
"worker": {
|
||||
"secrets": [
|
||||
"broker_url_worker",
|
||||
"database_url",
|
||||
"s3_worker_access_key_id",
|
||||
"s3_worker_secret_access_key",
|
||||
],
|
||||
"volumes": [],
|
||||
"networks": ["backend"],
|
||||
},
|
||||
}
|
||||
PUBLISHING = frozenset(name for name, rule in POLICY.items() if rule.get("ports"))
|
||||
|
||||
|
||||
def run(*command):
|
||||
done = subprocess.run(command, cwd=str(ROOT), capture_output=True, text=True, check=False)
|
||||
return done.returncode, done.stdout.strip()
|
||||
|
||||
|
||||
def declared(name, service, networks, problems):
|
||||
limits = service.get("deploy", {}).get("resources", {}).get("limits", {})
|
||||
secrets = sorted(s["source"] for s in service.get("secrets", []))
|
||||
volumes = sorted(v["source"] for v in service.get("volumes", []) if v["type"] == "volume")
|
||||
nets = sorted(service.get("networks", {}))
|
||||
ports = [
|
||||
f"{p.get('host_ip', '0.0.0.0')}:{p.get('published')}" for p in service.get("ports", [])
|
||||
]
|
||||
want = POLICY.get(name)
|
||||
if want is None:
|
||||
problems.append(f"{name}: service is not covered by the policy")
|
||||
want = {"secrets": [], "volumes": [], "networks": []}
|
||||
if not limits.get("cpus") or not limits.get("memory"):
|
||||
problems.append(f"{name}: no CPU or memory limit")
|
||||
if "container_name" in service:
|
||||
problems.append(f"{name}: container_name prevents scaling")
|
||||
for kind, actual in (("secrets", secrets), ("volumes", volumes), ("networks", nets)):
|
||||
if actual != want[kind]:
|
||||
problems.append(f"{name}: {kind} {actual}, policy {want[kind]}")
|
||||
if ports and not want.get("ports"):
|
||||
problems.append(f"{name}: publishes {ports} in bypass of the balancer")
|
||||
if any(not port.startswith("127.0.0.1:") for port in ports):
|
||||
problems.append(f"{name}: publishes {ports} beyond loopback")
|
||||
if name == "api" and not service.get("read_only"):
|
||||
problems.append("api: root filesystem is writable")
|
||||
user = str(service.get("user", ""))
|
||||
if name in OWN_USER and user.split(":", maxsplit=1)[0] in ("", "0", "root"):
|
||||
problems.append(f"{name}: runs as root")
|
||||
internal = [n for n in nets if networks.get(n, {}).get("internal")]
|
||||
return [
|
||||
name,
|
||||
f"{limits.get('cpus', '-')}/{int(limits.get('memory') or 0) >> 20}MiB",
|
||||
",".join(ports) or "-",
|
||||
",".join(secrets) or "-",
|
||||
",".join(volumes) or "-",
|
||||
",".join(f"{n}{'(internal)' if n in internal else ''}" for n in nets),
|
||||
str(service.get("read_only", False)).lower(),
|
||||
user or "image",
|
||||
]
|
||||
|
||||
|
||||
def running(problems):
|
||||
_, ids = run("docker", "compose", "ps", "-q")
|
||||
template = (
|
||||
'{{index .Config.Labels "com.docker.compose.service"}} {{.Config.Hostname}} '
|
||||
"{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}} {{json .HostConfig.PortBindings}}"
|
||||
)
|
||||
_, found = run("docker", "inspect", "-f", template, *ids.split())
|
||||
rows = []
|
||||
for line in found.splitlines():
|
||||
service, host, cpus, memory, bindings = line.split(" ", 4)
|
||||
published = [
|
||||
f"{b['HostIp']}:{b['HostPort']}->{port}"
|
||||
for port, items in (json.loads(bindings) or {}).items()
|
||||
for b in items or []
|
||||
]
|
||||
if int(cpus) <= 0 or int(memory) <= 0:
|
||||
problems.append(f"container {service}/{host}: no CPU or memory limit applied")
|
||||
if published and service not in PUBLISHING:
|
||||
problems.append(f"container {service}/{host}: publishes {published}")
|
||||
rows.append(
|
||||
[service, host, f"{int(cpus) / 1e9:g}", f"{int(memory) >> 20}MiB", ",".join(published)]
|
||||
)
|
||||
return sorted(rows)
|
||||
|
||||
|
||||
def table(header, rows):
|
||||
widths = [max(len(str(r[i])) for r in [header, *rows]) for i in range(len(header))]
|
||||
lines = [header, ["-" * w for w in widths], *rows]
|
||||
return [" ".join(str(c).ljust(w) for c, w in zip(r, widths)).rstrip() for r in lines]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="limits, ports, secrets, volumes and networks")
|
||||
parser.add_argument("--out", help="text report, written only after a complete check")
|
||||
args = parser.parse_args()
|
||||
problems = []
|
||||
_, raw = run(
|
||||
"docker",
|
||||
"compose",
|
||||
"--profile",
|
||||
"bench",
|
||||
"--profile",
|
||||
"tools",
|
||||
"--profile",
|
||||
"reconcile",
|
||||
"config",
|
||||
"--format",
|
||||
"json",
|
||||
)
|
||||
config = json.loads(raw)
|
||||
services = [
|
||||
declared(name, service, config.get("networks", {}), problems)
|
||||
for name, service in sorted(config["services"].items())
|
||||
]
|
||||
containers = running(problems)
|
||||
if not any(row[0] == "api" for row in containers):
|
||||
problems.append("no running api replicas to inspect")
|
||||
lines = [
|
||||
f"date: {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} "
|
||||
f"commit: {run('git', 'rev-parse', '--short', 'HEAD')[1]}",
|
||||
"$ docker compose --profile bench --profile tools --profile reconcile config --format json"
|
||||
" (declared)",
|
||||
*table(
|
||||
["service", "cpus/mem", "ports", "secrets", "volumes", "networks", "ro", "user"],
|
||||
services,
|
||||
),
|
||||
"",
|
||||
"$ docker inspect (running containers: hostname = X-Instance-Id, applied limits)",
|
||||
*table(["service", "hostname", "cpus", "memory", "published"], containers),
|
||||
"",
|
||||
*(f"FAIL: {p}" for p in problems),
|
||||
"PASS: limits, ports, secrets, volumes and networks match the policy"
|
||||
if not problems
|
||||
else f"FAIL: {len(problems)} violation(s)",
|
||||
]
|
||||
text = "\n".join(lines) + "\n"
|
||||
if args.out:
|
||||
Path(args.out).write_text(text)
|
||||
print(text, end="")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+62
@@ -0,0 +1,62 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
runs="${RUNS:-3}"
|
||||
pause="${PAUSE:-15}"
|
||||
project=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$(docker compose ps -q lb)")
|
||||
network="${project}_edge"
|
||||
image=$(sed -n 's/^FROM \(python:[^ ]*\) AS runtime$/\1/p' Dockerfile)
|
||||
name="$project-load-client"
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
out=${EVIDENCE_DIR:-evidence}
|
||||
mkdir -p "$out/load"
|
||||
[ -z "$(ls -A "$out/load")" ] || { echo "Choose an empty EVIDENCE_DIR/load" >&2; exit 2; }
|
||||
client() {
|
||||
docker run --rm --name "$name" --network "$network" --cpus 2 --memory 512m \
|
||||
--sysctl net.ipv4.tcp_tw_reuse=1 -v "$PWD/tests:/w/tests:ro" -v "$PWD/contracts:/w/contracts:ro" \
|
||||
-v "$PWD/lab.json:/w/lab.json:ro" -v "$PWD/$out/load:/out" "$image" python /w/tests/load.py "$@"
|
||||
}
|
||||
handled() {
|
||||
docker compose logs --no-log-prefix --since "$1" api | python3 -c 'import collections, json, sys
|
||||
seen = collections.Counter()
|
||||
for line in sys.stdin:
|
||||
if line.startswith("{"):
|
||||
event = json.loads(line)
|
||||
if event.get("event") == "request.handled":
|
||||
seen[(event["status"], event["method"], event["route"])] += 1
|
||||
for (status, method, route), count in sorted(seen.items()):
|
||||
print(status, method, route, count)'
|
||||
}
|
||||
{
|
||||
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD) network: $network"
|
||||
echo "# make load-evidence (scripts/load-evidence.sh): закрытый контур tests/load.py, 64 потока, 8 с, все записи"
|
||||
echo "# прогона в один новый чат, $runs повтора с паузой $pause с; клиент — одноразовый контейнер в сети <проект>_edge"
|
||||
echo "# стенда (2 CPU, 512 MiB, базовый образ API по digest, tests/, contracts/ и lab.json только для чтения,"
|
||||
echo "# tcp_tw_reuse=1), адрес http://lb:8080. На 4-й секунде — docker stats; после прогона — request.handled реплик."
|
||||
echo "\$ docker ps --format '{{.Names}}' | grep -v '^$project-' # чужие контейнеры на VM во время серии"
|
||||
docker ps --format '{{.Names}}' | grep -v "^$project-" || true
|
||||
echo "\$ client() { docker run --rm --name $name --network $network --cpus 2 --memory 512m --sysctl net.ipv4.tcp_tw_reuse=1 -v \"\$PWD/tests:/w/tests:ro\" -v \"\$PWD/contracts:/w/contracts:ro\" -v \"\$PWD/lab.json:/w/lab.json:ro\" -v \"\$PWD/$out/load:/out\" $image python /w/tests/load.py \"\$@\"; }"
|
||||
run=1
|
||||
while [ "$run" -le "$runs" ]; do
|
||||
since=$(date -u +%FT%TZ)
|
||||
echo "\$ client --base-url http://lb:8080 --duration 8 --concurrency 64 --output /out/run$run.json"
|
||||
client --base-url http://lb:8080 --duration 8 --concurrency 64 --output "/out/run$run.json" > "$work/out" 2>&1 &
|
||||
pid=$!
|
||||
sleep 4
|
||||
stats=$(docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' $(docker compose ps -q) "$name" | sed "s/^$project-//" | sort)
|
||||
if wait "$pid"; then code=0; else code=$?; fi
|
||||
echo "exit $code"
|
||||
cat "$work/out"
|
||||
echo "\$ docker stats --no-stream # 4-я секунда прогона: контейнер CPU% память"
|
||||
echo "$stats"
|
||||
echo "\$ docker compose logs --since $since api | request.handled: статус метод маршрут число"
|
||||
handled "$since"
|
||||
[ "$code" -eq 0 ] || { exit "$code"; }
|
||||
[ "$run" -lt "$runs" ] && sleep "$pause"
|
||||
run=$((run + 1))
|
||||
done
|
||||
echo "\$ docker compose exec -T postgres psql -c 'SELECT count(*) FROM messages'"
|
||||
docker compose exec -T postgres psql -U messenger -d messenger -qAt -c 'SELECT count(*) FROM messages'
|
||||
} > "$out/load.txt"
|
||||
cat "$out/load.txt"
|
||||
@@ -0,0 +1,354 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import struct
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAX_BYTES = 10485760
|
||||
MAX_PIXELS = 40000000
|
||||
REJECTED_OR_FAILED = {"upload": [202, 415], "final": "failed", "error_code": "invalid_image"}
|
||||
GIF = (
|
||||
b"GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00"
|
||||
b",\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"
|
||||
)
|
||||
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
|
||||
|
||||
|
||||
def png(width, height, rows, color_type=2, depth=8, *, extra=(), level=6):
|
||||
packer = zlib.compressobj(level)
|
||||
body = b"".join(packer.compress(b"\x00" + row) for row in rows) + packer.flush()
|
||||
header = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ b"".join(extra)
|
||||
+ chunk(b"IDAT", body)
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def ramp(value, size):
|
||||
return value * 255 // max(1, size - 1)
|
||||
|
||||
|
||||
def gradient(width, height, channels):
|
||||
for y in range(height):
|
||||
yield bytes(
|
||||
channel
|
||||
for x in range(width)
|
||||
for channel in (ramp(x, width), ramp(y, height), 160, ramp(x + y, width + height))[
|
||||
:channels
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
def blank(width, height, channels, depth=8):
|
||||
row = bytes(width * channels * depth // 8)
|
||||
for _ in range(height):
|
||||
yield row
|
||||
|
||||
|
||||
def padded(data, total):
|
||||
pad = total - len(data) - 12
|
||||
return data[:33] + chunk(b"paDd", bytes(pad)) + data[33:]
|
||||
|
||||
|
||||
class Bits:
|
||||
def __init__(self):
|
||||
self.out = bytearray()
|
||||
self.acc = 0
|
||||
self.size = 0
|
||||
|
||||
def put(self, value, length):
|
||||
self.acc = (self.acc << length) | value
|
||||
self.size += length
|
||||
while self.size >= 8:
|
||||
self.size -= 8
|
||||
byte = (self.acc >> self.size) & 0xFF
|
||||
self.out += b"\xff\x00" if byte == 0xFF else bytes((byte,))
|
||||
self.acc &= (1 << self.size) - 1
|
||||
|
||||
def zeros(self, count):
|
||||
head = min(count, (8 - self.size) % 8)
|
||||
self.put(0, head)
|
||||
count -= head
|
||||
self.out += bytes(count // 8)
|
||||
self.put(0, count % 8)
|
||||
|
||||
def flush(self):
|
||||
if self.size:
|
||||
self.put((1 << (8 - self.size)) - 1, 8 - self.size)
|
||||
return bytes(self.out)
|
||||
|
||||
|
||||
def segment(marker, payload):
|
||||
return b"\xff" + bytes((marker,)) + struct.pack(">H", len(payload) + 2) + payload
|
||||
|
||||
|
||||
def ycbcr(red, green, blue):
|
||||
return (
|
||||
0.299 * red + 0.587 * green + 0.114 * blue,
|
||||
128 - 0.168736 * red - 0.331264 * green + 0.5 * blue,
|
||||
128 + 0.5 * red - 0.418688 * green - 0.081312 * blue,
|
||||
)
|
||||
|
||||
|
||||
def exif(orientation):
|
||||
entry = struct.pack(">HHIHH", 0x0112, 3, 1, orientation, 0)
|
||||
tiff = b"MM\x00\x2a\x00\x00\x00\x08" + struct.pack(">H", 1) + entry + struct.pack(">I", 0)
|
||||
return segment(0xE1, b"Exif\x00\x00" + tiff)
|
||||
|
||||
|
||||
def jpeg(width, height, mode="rgb", orientation=None, uniform=False):
|
||||
components = {"gray": 1, "rgb": 3, "cmyk": 4}[mode]
|
||||
head = b"\xff\xd8" + (
|
||||
exif(orientation)
|
||||
if orientation
|
||||
else segment(0xE0, b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00")
|
||||
)
|
||||
if mode == "cmyk":
|
||||
head += segment(0xEE, b"Adobe\x00\x64\x00\x00\x00\x00\x00")
|
||||
head += segment(0xDB, b"\x00" + bytes([1] * 64))
|
||||
head += segment(
|
||||
0xC0,
|
||||
struct.pack(">BHHB", 8, height, width, components)
|
||||
+ b"".join(bytes((i + 1, 0x11, 0)) for i in range(components)),
|
||||
)
|
||||
head += segment(0xC4, b"\x00" + bytes([0, 0, 0, 12] + [0] * 12) + bytes(range(12)))
|
||||
head += segment(0xC4, b"\x10" + bytes([1] + [0] * 15) + b"\x00")
|
||||
head += segment(
|
||||
0xDA,
|
||||
bytes((components,))
|
||||
+ b"".join(bytes((i + 1, 0)) for i in range(components))
|
||||
+ b"\x00\x3f\x00",
|
||||
)
|
||||
columns, rows = (width + 7) // 8, (height + 7) // 8
|
||||
bits, previous = Bits(), [0] * components
|
||||
for block in range(1 if uniform else columns * rows):
|
||||
bx, by = block % columns, block // columns
|
||||
red, green, blue = ramp(bx, columns), ramp(by, rows), 160
|
||||
values = {"gray": (red,), "rgb": ycbcr(red, green, blue), "cmyk": (red, green, blue, 64)}[
|
||||
mode
|
||||
]
|
||||
for index, value in enumerate(values):
|
||||
dc = round(8 * (value - 128))
|
||||
diff, previous[index] = dc - previous[index], dc
|
||||
category = abs(diff).bit_length()
|
||||
bits.put(category, 4)
|
||||
if category:
|
||||
bits.put(diff if diff > 0 else diff + (1 << category) - 1, category)
|
||||
bits.put(0, 1)
|
||||
if uniform:
|
||||
bits.zeros((columns * rows - 1) * components * 5)
|
||||
return head + bits.flush() + b"\xff\xd9"
|
||||
|
||||
|
||||
def fit(width, height, box, upscale=False):
|
||||
if not upscale and max(width, height) <= box:
|
||||
return [width, height]
|
||||
if width >= height:
|
||||
return [box, max(1, height * box // width)]
|
||||
return [max(1, width * box // height), box]
|
||||
|
||||
|
||||
def ready(width, height, orientation=1):
|
||||
if orientation in (5, 6, 7, 8):
|
||||
width, height = height, width
|
||||
return {
|
||||
"upload": [202],
|
||||
"final": "ready",
|
||||
"variants": {
|
||||
"thumbnail": fit(width, height, 256),
|
||||
"crop": [128, 128],
|
||||
"optimized": fit(width, height, 1280),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def catalog(heavy):
|
||||
small = png(64, 64, gradient(64, 64, 3))
|
||||
truncated_png = png(320, 200, gradient(320, 200, 3))
|
||||
idat = truncated_png.index(b"IDAT")
|
||||
corrupt = bytearray(truncated_png)
|
||||
corrupt[idat + 40 : idat + 48] = b"\x00" * 8
|
||||
palette = bytes(channel for index in range(256) for channel in (index, 255 - index, 128))
|
||||
alpha = bytes(index for index in range(256))
|
||||
items = [
|
||||
(
|
||||
"png-rgb-320x200.png",
|
||||
"image/png",
|
||||
lambda: png(320, 200, gradient(320, 200, 3)),
|
||||
ready(320, 200),
|
||||
),
|
||||
(
|
||||
"png-rgba-300x300.png",
|
||||
"image/png",
|
||||
lambda: png(300, 300, gradient(300, 300, 4), 6),
|
||||
ready(300, 300),
|
||||
),
|
||||
(
|
||||
"png-palette-trns-200x100.png",
|
||||
"image/png",
|
||||
lambda: png(
|
||||
200,
|
||||
100,
|
||||
(bytes((x + y) % 256 for x in range(200)) for y in range(100)),
|
||||
3,
|
||||
extra=(chunk(b"PLTE", palette), chunk(b"tRNS", alpha)),
|
||||
),
|
||||
ready(200, 100),
|
||||
),
|
||||
(
|
||||
"png-gray-17x1000.png",
|
||||
"image/png",
|
||||
lambda: png(17, 1000, gradient(17, 1000, 1), 0),
|
||||
ready(17, 1000),
|
||||
),
|
||||
(
|
||||
"png-gray-alpha-640x480.png",
|
||||
"image/png",
|
||||
lambda: png(640, 480, gradient(640, 480, 2), 4),
|
||||
ready(640, 480),
|
||||
),
|
||||
(
|
||||
"png-gray16-300x200.png",
|
||||
"image/png",
|
||||
lambda: png(300, 200, gradient(600, 200, 1), 0, 16),
|
||||
ready(300, 200),
|
||||
),
|
||||
(
|
||||
"png-rgba16-64x64.png",
|
||||
"image/png",
|
||||
lambda: png(64, 64, gradient(512, 64, 1), 6, 16),
|
||||
ready(64, 64),
|
||||
),
|
||||
("png-1x1.png", "image/png", lambda: png(1, 1, gradient(1, 1, 3)), ready(1, 1)),
|
||||
(
|
||||
"png-wide-3000x2.png",
|
||||
"image/png",
|
||||
lambda: png(3000, 2, gradient(3000, 2, 3)),
|
||||
ready(3000, 2),
|
||||
),
|
||||
(
|
||||
"png-small-50x30.png",
|
||||
"image/png",
|
||||
lambda: png(50, 30, gradient(50, 30, 3)),
|
||||
ready(50, 30),
|
||||
),
|
||||
("jpeg-rgb-1000x750.jpg", "image/jpeg", lambda: jpeg(1000, 750), ready(1000, 750)),
|
||||
("jpeg-gray-801x601.jpg", "image/jpeg", lambda: jpeg(801, 601, "gray"), ready(801, 601)),
|
||||
("jpeg-cmyk-400x300.jpg", "image/jpeg", lambda: jpeg(400, 300, "cmyk"), ready(400, 300)),
|
||||
(
|
||||
"jpeg-exif6-400x200.jpg",
|
||||
"image/jpeg",
|
||||
lambda: jpeg(400, 200, orientation=6),
|
||||
ready(400, 200, 6),
|
||||
),
|
||||
(
|
||||
"jpeg-exif3-300x200.jpg",
|
||||
"image/jpeg",
|
||||
lambda: jpeg(300, 200, orientation=3),
|
||||
ready(300, 200, 3),
|
||||
),
|
||||
("jpeg-rgb-4000x3000.jpg", "image/jpeg", lambda: jpeg(4000, 3000), ready(4000, 3000)),
|
||||
("png-exactly-10mib.png", "image/png", lambda: padded(small, MAX_BYTES), ready(64, 64)),
|
||||
(
|
||||
"png-over-10mib.png",
|
||||
"image/png",
|
||||
lambda: padded(small, MAX_BYTES + 1),
|
||||
{"upload": [413]},
|
||||
),
|
||||
(
|
||||
"png-over-pixels-8001x5000.png",
|
||||
"image/png",
|
||||
lambda: png(8001, 5000, blank(8001, 5000, 3), level=9),
|
||||
{"upload": [413]},
|
||||
),
|
||||
(
|
||||
"jpeg-over-pixels-10000x5000.jpg",
|
||||
"image/jpeg",
|
||||
lambda: jpeg(10000, 5000, uniform=True),
|
||||
{"upload": [413]},
|
||||
),
|
||||
("png-truncated.png", "image/png", lambda: truncated_png[: idat + 600], REJECTED_OR_FAILED),
|
||||
("png-corrupt-idat.png", "image/png", lambda: bytes(corrupt), REJECTED_OR_FAILED),
|
||||
("jpeg-truncated.jpg", "image/jpeg", lambda: jpeg(1000, 750)[:3000], REJECTED_OR_FAILED),
|
||||
(
|
||||
"png-zero-width.png",
|
||||
"image/png",
|
||||
zero_width,
|
||||
{"upload": [400, 415]},
|
||||
),
|
||||
(
|
||||
"not-an-image.png",
|
||||
"image/png",
|
||||
lambda: b"plain text, not an image\n" * 8,
|
||||
{"upload": [415]},
|
||||
),
|
||||
("gif-declared-as-png.png", "image/png", lambda: GIF, {"upload": [415]}),
|
||||
]
|
||||
if heavy:
|
||||
items.append(
|
||||
(
|
||||
"png-at-pixel-limit-8000x5000.png",
|
||||
"image/png",
|
||||
lambda: png(8000, 5000, blank(8000, 5000, 3), level=9),
|
||||
ready(8000, 5000),
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def zero_width():
|
||||
header = struct.pack(">IIBBBBB", 0, 10, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(b""))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def build(out, heavy=False, only=None):
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
manifest = []
|
||||
for name, content_type, make, expect in catalog(heavy):
|
||||
if only and name not in only:
|
||||
continue
|
||||
data = make()
|
||||
(out / name).write_bytes(data)
|
||||
manifest.append(
|
||||
{"file": name, "content_type": content_type, "size_bytes": len(data), "expect": expect}
|
||||
)
|
||||
(out / "manifest.json").write_text(
|
||||
json.dumps(
|
||||
{"rules": {"max_bytes": MAX_BYTES, "max_pixels": MAX_PIXELS}, "images": manifest},
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
return manifest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generate lab5 test images and manifest.json with expected outcomes"
|
||||
)
|
||||
parser.add_argument("--out", default=str(ROOT / "build/lab5-images"))
|
||||
parser.add_argument(
|
||||
"--heavy", action="store_true", help="also write a 40 Mpx image at the pixel limit"
|
||||
)
|
||||
parser.add_argument("--only", default="", help="comma separated file names")
|
||||
args = parser.parse_args()
|
||||
manifest = build(Path(args.out), args.heavy, {x for x in args.only.split(",") if x})
|
||||
for item in manifest:
|
||||
print(f"{item['file']:36} {item['size_bytes']:>10} {item['expect']['upload']}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
otel=otel/opentelemetry-collector-contrib:0.163.2@sha256:7f22d2a6748110ffb6a59bc0df448bccbf501cdb667d610ede4c61d3863d5849
|
||||
prom=prom/prometheus:v3.15.1@sha256:fa3302279710be2f21a8301ec17a8b4f2301fd829bd113839b3b6b02b6f191a2
|
||||
loki=grafana/loki:3.7.9@sha256:0db216b630ae1f348a1584c67f3cead8b4c1fc839169a39501db664744158e28
|
||||
tempo=grafana/tempo:2.10.10@sha256:12b0820f13ffa10ce956b6e9acc3b03f3cffded99109be6cc09d106fe56e5d38
|
||||
docker run --rm --network none -v "$PWD/infra/otel:/etc/otelcol:ro" "$otel" validate --config=/etc/otelcol/collector.yaml
|
||||
echo "otelcol-contrib validate collector.yaml: OK"
|
||||
docker run --rm --network none --entrypoint promtool -v "$PWD/infra/prometheus:/etc/prometheus:ro" "$prom" check config /etc/prometheus/prometheus.yml
|
||||
docker run --rm --network none -v "$PWD/infra/loki/loki.yaml:/etc/loki/loki.yaml:ro" "$loki" -config.file=/etc/loki/loki.yaml -verify-config
|
||||
echo "loki -verify-config: OK"
|
||||
docker run --rm --network none -v "$PWD/infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro" "$tempo" -config.file=/etc/tempo/tempo.yaml -config.verify=true
|
||||
echo "tempo -config.verify: OK"
|
||||
for board in infra/grafana/dashboards/*.json; do
|
||||
python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); assert d["uid"] and d["panels"]' "$board"
|
||||
done
|
||||
echo "grafana dashboards: valid JSON with uid and panels"
|
||||
Executable
+498
@@ -0,0 +1,498 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROMQL_WORDS = {
|
||||
"sum", "min", "max", "avg", "count", "by", "without", "on", "ignoring", "group_left", "group_right", "and", "or",
|
||||
"unless", "offset", "bool", "rate", "irate", "increase", "delta", "deriv", "histogram_quantile", "label_replace",
|
||||
"label_join", "absent", "absent_over_time", "vector", "scalar", "clamp_min", "clamp_max", "topk", "bottomk",
|
||||
"max_over_time", "min_over_time", "avg_over_time", "sum_over_time", "count_over_time", "quantile_over_time",
|
||||
"time", "timestamp", "sort", "sort_desc", "round", "abs", "le", "inf", "nan", "predict_linear", "changes", "resets",
|
||||
}
|
||||
|
||||
|
||||
class Failure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def http(method, url, body=None, headers=None, timeout=10, expect=None):
|
||||
data = body if isinstance(body, (bytes, type(None))) else json.dumps(body).encode()
|
||||
head = {"Accept": "application/json"}
|
||||
if body is not None and not isinstance(body, bytes):
|
||||
head["Content-Type"] = "application/json"
|
||||
head.update(headers or {})
|
||||
request = urllib.request.Request(url, data=data, headers=head, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
status, raw, got = response.status, response.read(), dict(response.headers)
|
||||
except urllib.error.HTTPError as error:
|
||||
status, raw, got = error.code, error.read(), dict(error.headers)
|
||||
if expect is not None and status not in expect:
|
||||
raise Failure(f"{method} {url.split('?')[0]} -> {status}: {raw[:200]!r}")
|
||||
try:
|
||||
parsed = json.loads(raw) if raw else None
|
||||
except ValueError:
|
||||
parsed = None
|
||||
return status, parsed, got, raw
|
||||
|
||||
|
||||
def get_json(url, headers=None, params=None):
|
||||
if params:
|
||||
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(params)
|
||||
return http("GET", url, headers=headers, expect=(200,))[1]
|
||||
|
||||
|
||||
def wait_for(what, check, timeout, interval=2.0):
|
||||
deadline = time.monotonic() + timeout
|
||||
while True:
|
||||
try:
|
||||
result = check()
|
||||
if result:
|
||||
return result
|
||||
except (Failure, OSError):
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise Failure(f"timeout waiting for {what}")
|
||||
time.sleep(interval)
|
||||
|
||||
|
||||
class Backends:
|
||||
def __init__(self, args):
|
||||
self.prometheus = args.prometheus.rstrip("/")
|
||||
self.loki = args.loki.rstrip("/")
|
||||
self.tempo = args.tempo.rstrip("/")
|
||||
self.grafana = args.grafana.rstrip("/")
|
||||
self.grafana_password_file = args.grafana_password_file
|
||||
|
||||
def grafana_headers(self):
|
||||
password = Path(self.grafana_password_file).read_text().strip()
|
||||
token = base64.b64encode(f"admin:{password}".encode()).decode()
|
||||
return {"Authorization": "Basic " + token}
|
||||
|
||||
def promql(self, query, at=None, base=None):
|
||||
params = {"query": query}
|
||||
if at is not None:
|
||||
params["time"] = f"{at:.3f}"
|
||||
result = get_json((base or self.prometheus) + "/api/v1/query", params=params)
|
||||
if result.get("status") != "success":
|
||||
raise Failure(f"PromQL failed: {query}")
|
||||
return result["data"]["result"]
|
||||
|
||||
def logs(self, query, start, end, limit=100, base=None):
|
||||
params = {"query": query, "start": str(int(start * 1e9)), "end": str(int(end * 1e9)), "limit": str(limit),
|
||||
"direction": "backward"}
|
||||
result = get_json((base or self.loki) + "/loki/api/v1/query_range", params=params)
|
||||
return [(stream["stream"], line) for stream in result["data"]["result"] for _, line in stream["values"]]
|
||||
|
||||
def traceql(self, query, start, end, limit=20, base=None):
|
||||
params = {"q": query, "start": str(int(start)), "end": str(int(end) + 1), "limit": str(limit)}
|
||||
return get_json((base or self.tempo) + "/api/search", params=params).get("traces") or []
|
||||
|
||||
def trace(self, trace_id, base=None):
|
||||
status, body, _, raw = http("GET", (base or self.tempo) + f"/api/v2/traces/{trace_id}", expect=(200, 404))
|
||||
return (body, raw.decode("utf-8", "replace")) if status == 200 else (None, "")
|
||||
|
||||
|
||||
def otlp_attrs(values):
|
||||
return [{"key": k, "value": {"intValue": str(v)} if isinstance(v, int) else {"stringValue": str(v)}}
|
||||
for k, v in values.items()]
|
||||
|
||||
|
||||
def otlp_resource(service, instance):
|
||||
return {"attributes": otlp_attrs({"service.name": service, "service.version": "probe",
|
||||
"service.instance.id": instance, "deployment.environment.name": "lab"})}
|
||||
|
||||
|
||||
def tempo_spans(body):
|
||||
spans = []
|
||||
for batch in (body or {}).get("trace", {}).get("resourceSpans", []):
|
||||
service = next((a["value"].get("stringValue") for a in batch["resource"].get("attributes", [])
|
||||
if a["key"] == "service.name"), "?")
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for span in scope.get("spans", []):
|
||||
values = {a["key"]: next(iter(a["value"].values()), None) for a in span.get("attributes", [])}
|
||||
duration = (int(span["endTimeUnixNano"]) - int(span["startTimeUnixNano"])) / 1e6
|
||||
spans.append({"service": service, "name": span["name"], "kind": span.get("kind"),
|
||||
"status": span.get("status", {}).get("code", "STATUS_CODE_UNSET"),
|
||||
"span_id": span.get("spanId"), "parent_span_id": span.get("parentSpanId"),
|
||||
"duration_ms": round(duration, 3), "links": len(span.get("links", [])),
|
||||
"attributes": values})
|
||||
return spans
|
||||
|
||||
|
||||
def probe(args, b):
|
||||
leak = "probe-secret-" + secrets.token_hex(8)
|
||||
rid = uuid.uuid4().hex
|
||||
trace_id, server, producer, consumer = secrets.token_hex(16), secrets.token_hex(8), secrets.token_hex(8), secrets.token_hex(8)
|
||||
t0 = time.time()
|
||||
ns = time.time_ns()
|
||||
api, worker = args.service_name, args.service_name + "-worker"
|
||||
scope = {"name": "obs-check", "version": "1"}
|
||||
|
||||
def span(span_id, parent, name, kind, start_ms, end_ms, values, links=()):
|
||||
return {"traceId": trace_id, "spanId": span_id, "parentSpanId": parent, "name": name, "kind": kind,
|
||||
"startTimeUnixNano": str(ns + start_ms * 1_000_000), "endTimeUnixNano": str(ns + end_ms * 1_000_000),
|
||||
"attributes": otlp_attrs(values), "status": {"code": 1},
|
||||
"links": [{"traceId": trace_id, "spanId": s} for s in links]}
|
||||
|
||||
traces = {"resourceSpans": [
|
||||
{"resource": otlp_resource(api, api + "-1"), "scopeSpans": [{"scope": scope, "spans": [
|
||||
span(server, "", "POST /api/v1/probe", 2, 0, 40, {
|
||||
"http.request.method": "POST", "http.route": "/api/v1/probe", "http.response.status_code": 202,
|
||||
"messenger.request_id": rid, "http.request.header.authorization": "Bearer " + leak,
|
||||
"url.query": "filename=" + leak, "user.password": leak, "messenger.session.token": leak}),
|
||||
span(producer, server, "probe.jobs publish", 4, 30, 35, {"messaging.operation.type": "send"})]}]},
|
||||
{"resource": otlp_resource(worker, worker + "-1"), "scopeSpans": [{"scope": scope, "spans": [
|
||||
span(consumer, producer, "probe.jobs process", 5, 50, 90, {"messaging.operation.type": "process"}, [producer])]}]},
|
||||
]}
|
||||
logs = {"resourceLogs": [{"resource": otlp_resource(api, api + "-1"), "scopeLogs": [{"scope": scope, "logRecords": [{
|
||||
"timeUnixNano": str(ns), "observedTimeUnixNano": str(ns), "severityNumber": 9, "severityText": "INFO",
|
||||
"body": {"stringValue": "probe.request.completed"}, "traceId": trace_id, "spanId": server,
|
||||
"attributes": otlp_attrs({"event": "probe.request.completed", "request_id": rid, "authorization": "Bearer " + leak})}]}]}]}
|
||||
point = {"attributes": otlp_attrs({"probe.id": rid}), "startTimeUnixNano": str(ns - 10_000_000_000), "timeUnixNano": str(ns)}
|
||||
metrics = {"resourceMetrics": [{"resource": otlp_resource(api, api + "-1"), "scopeMetrics": [{"scope": scope, "metrics": [
|
||||
{"name": "obs.probe.heartbeat", "unit": "{probe}", "sum": {"aggregationTemporality": 2, "isMonotonic": True,
|
||||
"dataPoints": [dict(point, asInt="1")]}},
|
||||
{"name": "obs.probe.latency", "unit": "s", "histogram": {"aggregationTemporality": 2, "dataPoints": [dict(
|
||||
point, count="1", sum=0.04, bucketCounts=["0", "1", "0"], explicitBounds=[0.01, 0.1])]}},
|
||||
]}]}]}
|
||||
otlp = args.otlp.rstrip("/")
|
||||
for path, payload in (("/v1/traces", traces), ("/v1/logs", logs), ("/v1/metrics", metrics)):
|
||||
http("POST", otlp + path, payload, expect=(200,))
|
||||
report = {"probe_id": rid, "trace_id": trace_id, "service": api, "sent_at": now()}
|
||||
|
||||
def tempo_ok(base=None):
|
||||
body, raw = b.trace(trace_id, base)
|
||||
spans = tempo_spans(body)
|
||||
return {"spans": len(spans), "services": sorted({s["service"] for s in spans}), "raw": raw} if len(spans) == 3 else None
|
||||
|
||||
tempo = wait_for("trace in Tempo", tempo_ok, args.timeout)
|
||||
found = wait_for("TraceQL search", lambda: b.traceql(f'{{ span.messenger.request_id = "{rid}" }}', t0 - 60, time.time() + 60), args.timeout)
|
||||
loki_query = f'{{service_name="{api}"}} | request_id="{rid}"'
|
||||
lines = wait_for("log in Loki", lambda: b.logs(loki_query, t0 - 60, time.time() + 60), args.timeout)
|
||||
series = wait_for("metrics in Prometheus", lambda: (lambda r: r if len(r) == 2 else None)(b.promql(
|
||||
f'{{__name__=~"obs_probe_heartbeat_total|obs_probe_latency_seconds_count", probe_id="{rid}"}}')), args.timeout)
|
||||
labels = lines[0][0]
|
||||
raw_logs = json.dumps(lines)
|
||||
report.update({
|
||||
"tempo": {"spans": tempo["spans"], "services": tempo["services"], "traceql_hits": len(found)},
|
||||
"loki": {"lines": len(lines), "trace_id_matches": labels.get("trace_id") == trace_id,
|
||||
"indexed_labels": sorted(k for k in labels if k in {"service_name", "deployment_environment_name"})},
|
||||
"prometheus": {"series": sorted(s["metric"].get("__name__", "") for s in series),
|
||||
"job": series[0]["metric"].get("job")},
|
||||
"redaction": {"secret_in_tempo": leak in tempo["raw"], "secret_in_loki": leak in raw_logs,
|
||||
"masked_in_tempo": "****" in tempo["raw"]},
|
||||
})
|
||||
if not args.no_grafana:
|
||||
g = b.grafana + "/api/datasources/proxy/uid/"
|
||||
headers = b.grafana_headers()
|
||||
report["grafana"] = {
|
||||
"prometheus": len(get_json(g + "prometheus/api/v1/query", headers, {"query": f'obs_probe_heartbeat_total{{probe_id="{rid}"}}'})["data"]["result"]),
|
||||
"loki": len(get_json(g + "loki/loki/api/v1/query_range", headers, {"query": loki_query, "start": str(int((t0 - 60) * 1e9)), "end": str(int((time.time() + 60) * 1e9))})["data"]["result"]),
|
||||
"tempo": http("GET", g + f"tempo/api/v2/traces/{trace_id}", headers=headers)[0],
|
||||
}
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
ok = (report["tempo"]["spans"] == 3 and report["loki"]["trace_id_matches"] and len(series) == 2
|
||||
and not report["redaction"]["secret_in_tempo"] and not report["redaction"]["secret_in_loki"]
|
||||
and ("grafana" not in report or (report["grafana"]["prometheus"] and report["grafana"]["loki"] and report["grafana"]["tempo"] == 200)))
|
||||
if not ok:
|
||||
raise Failure("probe verification failed")
|
||||
|
||||
|
||||
class Api:
|
||||
def __init__(self, base):
|
||||
self.base = base.rstrip("/")
|
||||
|
||||
def call(self, method, path, body=None, headers=None, expect=(200,)):
|
||||
status, parsed, got, _ = http(method, self.base + path, body, headers, expect=expect)
|
||||
return parsed, got.get("X-Request-Id") or got.get("x-request-id")
|
||||
|
||||
def register(self):
|
||||
username = "u_obs_" + secrets.token_hex(6)
|
||||
password = "T3st-" + secrets.token_hex(16)
|
||||
user, rid = self.call("POST", "/api/v1/users", {"username": username, "display_name": "obs check", "password": password}, expect=(201,))
|
||||
return user, username, password, rid
|
||||
|
||||
def login(self, username, password):
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
session, _ = self.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}, expect=(201,))
|
||||
return {"Authorization": "Bearer " + session["token"]}, session["token"]
|
||||
|
||||
def chat(self, auth, user):
|
||||
chat, _ = self.call("POST", "/api/v1/chats", {"title": "obs", "member_ids": [user["id"]]}, auth, expect=(201,))
|
||||
return chat
|
||||
|
||||
def logout(self, auth):
|
||||
self.call("DELETE", "/api/v1/auth/sessions/current", headers=auth, expect=(204,))
|
||||
|
||||
|
||||
def request_check(args, b):
|
||||
api = Api(args.base_url)
|
||||
t0 = time.time()
|
||||
_, _, _, rid = api.register()
|
||||
query = f'{{service_name="{args.api_service}"}} | {args.log_request_id_key}="{rid}"'
|
||||
lines = wait_for("API log by request_id", lambda: b.logs(query, t0 - 30, time.time() + 30), args.timeout)
|
||||
labels, line = lines[0]
|
||||
trace_id = labels.get("trace_id")
|
||||
if not trace_id:
|
||||
raise Failure("log record has no trace_id")
|
||||
spans = wait_for("API trace in Tempo", lambda: tempo_spans(b.trace(trace_id)[0]), args.timeout)
|
||||
if not any(s["kind"] == "SPAN_KIND_SERVER" and s["service"] == args.api_service for s in spans):
|
||||
raise Failure("no real API server span")
|
||||
if not any(s["kind"] == "SPAN_KIND_CLIENT" and s["attributes"].get("db.system") == "postgresql" for s in spans):
|
||||
raise Failure("no PostgreSQL client span inside API trace")
|
||||
print(json.dumps({"checked_at": now(), "request_id": rid, "log": {"line": line[:200], "trace_id": trace_id,
|
||||
"span_id": labels.get("span_id"),
|
||||
"service_name": labels.get("service_name"),
|
||||
"severity": labels.get("severity_text") or labels.get("detected_level")},
|
||||
"trace": [{k: s[k] for k in ("service", "name", "kind", "status", "duration_ms")} for s in spans]},
|
||||
ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def job_check(args, b):
|
||||
api = Api(args.base_url)
|
||||
t0 = time.time()
|
||||
user, username, password, _ = api.register()
|
||||
auth, _ = api.login(username, password)
|
||||
chat = api.chat(auth, user)
|
||||
image = Path(args.image).read_bytes()
|
||||
headers = dict(auth, **{"Content-Type": "image/png"})
|
||||
attachment, rid = api.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=obs.png", image, headers, expect=(202,))
|
||||
ready = wait_for("attachment ready", lambda: (lambda a: a if a["status"] in ("ready", "failed") else None)(
|
||||
api.call("GET", f"/api/v1/attachments/{attachment['id']}", headers=auth)[0]), 60, 0.5)
|
||||
key = args.attachment_attr
|
||||
traces = wait_for("traces for attachment", lambda: b.traceql(f'{{ span.{key} = "{attachment["id"]}" }}', t0 - 30, time.time() + 30), args.timeout)
|
||||
chain = []
|
||||
for item in traces:
|
||||
for span in tempo_spans(b.trace(item["traceID"])[0]):
|
||||
chain.append(dict({k: span[k] for k in ("service", "name", "kind", "status", "duration_ms", "links")},
|
||||
trace_id=item["traceID"], attempt=span["attributes"].get(args.attempt_attr)))
|
||||
query = f'{{service_name="{args.worker_service}"}} | {args.log_attachment_key}="{attachment["id"]}"'
|
||||
worker_logs = wait_for("worker logs", lambda: b.logs(query, t0 - 30, time.time() + 30), args.timeout)
|
||||
api.logout(auth)
|
||||
if ready["status"] != "ready" or not any(s["kind"] == "SPAN_KIND_CONSUMER" and s["service"] == args.worker_service for s in chain):
|
||||
raise Failure("job is not ready or no real consumer span")
|
||||
if not any(labels.get("trace_id") and labels.get("span_id") for labels, _ in worker_logs):
|
||||
raise Failure("worker log is not correlated")
|
||||
print(json.dumps({"checked_at": now(), "upload_request_id": rid, "attachment_status": ready["status"],
|
||||
"traces": sorted({c["trace_id"] for c in chain}), "spans": chain,
|
||||
"worker_logs": [{"line": line[:200], "trace_id": labels.get("trace_id"), "span_id": labels.get("span_id")}
|
||||
for labels, line in worker_logs[:10]]}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
def leaks_check(args, b):
|
||||
api = Api(args.base_url)
|
||||
t0 = time.time()
|
||||
user, username, password, _ = api.register()
|
||||
auth, token = api.login(username, password)
|
||||
chat = api.chat(auth, user)
|
||||
text = "obs-leak-text-" + secrets.token_hex(8)
|
||||
filename = "obs-leak-file-" + secrets.token_hex(6) + ".png"
|
||||
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": text}, dict(auth, **{"Idempotency-Key": uuid.uuid4().hex}), expect=(201,))
|
||||
if Path(args.image).is_file():
|
||||
api.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=" + urllib.parse.quote(filename),
|
||||
Path(args.image).read_bytes(), dict(auth, **{"Content-Type": "image/png"}), expect=(202,))
|
||||
api.logout(auth)
|
||||
time.sleep(args.flush)
|
||||
needles = {"password": password, "token": token, "message_text": text, "filename": filename}
|
||||
end = time.time() + 5
|
||||
hits = {}
|
||||
for name, needle in needles.items():
|
||||
lines = b.logs(f'{{service_name=~"{args.service_regex}"}} |= `{needle}`', t0 - 30, end, limit=50)
|
||||
hits[name] = {"loki": len(lines)}
|
||||
traces = b.traceql(f'{{ resource.service.name =~ "{args.service_regex}" }}', t0 - 30, end, limit=500)
|
||||
raws = [b.trace(t["traceID"])[1] for t in traces]
|
||||
for name, needle in needles.items():
|
||||
hits[name]["tempo"] = sum(needle in raw for raw in raws)
|
||||
report = {"checked_at": now(), "window_seconds": round(end - t0), "traces_scanned": len(raws), "hits": hits}
|
||||
print(json.dumps(report, indent=2))
|
||||
if any(v["loki"] or v["tempo"] for v in hits.values()):
|
||||
raise Failure("secret or message body found in telemetry")
|
||||
|
||||
|
||||
def uploads_burst(args, b):
|
||||
api = Api(args.base_url)
|
||||
user, username, password, _ = api.register()
|
||||
auth, _ = api.login(username, password)
|
||||
chat = api.chat(auth, user)
|
||||
image = Path(args.image).read_bytes()
|
||||
accepted = []
|
||||
for index in range(args.count):
|
||||
attachment, rid = api.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=burst-{index}.png", image,
|
||||
dict(auth, **{"Content-Type": "image/png"}), expect=(202,))
|
||||
accepted.append({"attachment_id": attachment["id"], "request_id": rid, "status": attachment["status"]})
|
||||
time.sleep(args.interval)
|
||||
api.logout(auth)
|
||||
print(json.dumps({"ts": now(), "uploaded": accepted}, ensure_ascii=False))
|
||||
|
||||
|
||||
def query(args, b):
|
||||
results = {expr: [{"labels": {k: v for k, v in r["metric"].items() if k != "__name__"}, "value": r["value"][1]}
|
||||
for r in b.promql(expr)] for expr in args.expr}
|
||||
print(json.dumps({"ts": now(), "results": results}, ensure_ascii=False))
|
||||
|
||||
|
||||
def expand(expr):
|
||||
expr = re.sub(r"\$\{?__(rate_interval|interval|range)\}?", "1m", expr)
|
||||
return re.sub(r"\$\{?(\w+)(?::\w+)?\}?", ".*", expr)
|
||||
|
||||
|
||||
def metric_names(expr):
|
||||
stripped = re.sub(r'"[^"]*"|`[^`]*`|\{[^}]*\}|\b(by|without|on|ignoring|group_left|group_right)\s*\([^)]*\)', " ", expr)
|
||||
stripped = re.sub(r"\[[^\]]*\]", " ", stripped)
|
||||
return {t for t in re.findall(r"[a-zA-Z_:][a-zA-Z0-9_:]*", stripped) if ("_" in t or ":" in t) and t not in PROMQL_WORDS}
|
||||
|
||||
|
||||
def walk_panels(dashboard):
|
||||
for panel in dashboard.get("panels", []):
|
||||
yield panel
|
||||
yield from panel.get("panels", [])
|
||||
|
||||
|
||||
def dashboards_check(args, b):
|
||||
known = set(get_json(b.prometheus + "/api/v1/label/__name__/values")["data"])
|
||||
problems, report = [], []
|
||||
for path in sorted(Path(args.dir).glob("*.json")):
|
||||
dashboard = json.loads(path.read_text())
|
||||
for panel in walk_panels(dashboard):
|
||||
for target in panel.get("targets", []):
|
||||
uid = (target.get("datasource") or panel.get("datasource") or {}).get("uid")
|
||||
entry = {"dashboard": path.name, "panel": panel.get("title"), "datasource": uid}
|
||||
try:
|
||||
if uid == "prometheus":
|
||||
expr = expand(target["expr"])
|
||||
result = b.promql(expr)
|
||||
missing = sorted(metric_names(expr) - known)
|
||||
entry.update(series=len(result), missing_metrics=missing)
|
||||
if missing and args.strict:
|
||||
problems.append(f"{path.name}: {panel.get('title')}: missing {missing}")
|
||||
elif uid == "loki":
|
||||
entry["lines"] = len(b.logs(expand(target["expr"]), time.time() - 3600, time.time(), limit=5))
|
||||
elif uid == "tempo":
|
||||
entry["traces"] = len(b.traceql(expand(target["query"]), time.time() - 3600, time.time(), limit=5))
|
||||
except Failure as error:
|
||||
problems.append(f"{path.name}: {panel.get('title')}: {error}")
|
||||
report.append(entry)
|
||||
print(json.dumps({"checked_at": now(), "targets": report, "problems": problems}, ensure_ascii=False, indent=2))
|
||||
if problems:
|
||||
raise Failure(f"{len(problems)} dashboard queries failed")
|
||||
|
||||
|
||||
def grafana_check(args, b):
|
||||
headers = b.grafana_headers()
|
||||
health = get_json(b.grafana + "/api/health")
|
||||
sources = {}
|
||||
for uid in ("prometheus", "loki", "tempo"):
|
||||
status, body, _, _ = http("GET", b.grafana + f"/api/datasources/uid/{uid}/health", headers=headers)
|
||||
sources[uid] = {"http": status, "status": (body or {}).get("status"), "message": (body or {}).get("message")}
|
||||
found = get_json(b.grafana + "/api/search", headers, {"type": "dash-db"})
|
||||
boards = {}
|
||||
for item in found:
|
||||
status, body, _, _ = http("GET", b.grafana + f"/api/dashboards/uid/{item['uid']}", headers=headers)
|
||||
meta = (body or {}).get("meta", {})
|
||||
boards[item["uid"]] = {"title": item["title"], "http": status, "provisioned": meta.get("provisioned"),
|
||||
"folder": meta.get("folderTitle"), "panels": len(list(walk_panels((body or {}).get("dashboard", {}))))}
|
||||
expected = {json.loads(p.read_text())["uid"] for p in Path(args.dir).glob("*.json")}
|
||||
print(json.dumps({"checked_at": now(), "grafana": health.get("version"), "datasources": sources, "dashboards": boards,
|
||||
"missing_dashboards": sorted(expected - set(boards))}, ensure_ascii=False, indent=2))
|
||||
if expected - set(boards) or any(s["http"] != 200 or s["status"] != "OK" for s in sources.values()):
|
||||
raise Failure("grafana provisioning incomplete")
|
||||
|
||||
|
||||
def alerts_watch(args, b):
|
||||
want_state, _, wanted = args.until.partition(":") if args.until else ("", "", "")
|
||||
names = set(filter(None, wanted.split("|")))
|
||||
only = {n for value in args.only for n in value.split("|")}
|
||||
deadline = time.monotonic() + args.timeout
|
||||
last = None
|
||||
output = open(args.output, "a") if args.output else None
|
||||
while True:
|
||||
alerts = get_json(b.prometheus + "/api/v1/alerts")["data"]["alerts"]
|
||||
state = sorted((a["labels"]["alertname"], a["state"], a.get("activeAt", "")) for a in alerts
|
||||
if not only or a["labels"]["alertname"] in only)
|
||||
if state != last:
|
||||
line = json.dumps({"ts": now(), "alerts": [{"alertname": n, "state": s, "active_at": at} for n, s, at in state]}, ensure_ascii=False)
|
||||
print(line, flush=True)
|
||||
if output:
|
||||
output.write(line + "\n")
|
||||
output.flush()
|
||||
last = state
|
||||
current = {n: s for n, s, _ in state}
|
||||
firing = {n for n in names if current.get(n) == "firing"}
|
||||
if names and ((want_state == "firing" and firing) or (want_state == "resolved" and not firing)):
|
||||
return
|
||||
if time.monotonic() > deadline:
|
||||
raise Failure(f"timeout waiting for {args.until}")
|
||||
time.sleep(args.interval)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Telemetry checks through public HTTP APIs of the messenger and of the observability stack")
|
||||
parser.add_argument("--prometheus", default=os.environ.get("PROMETHEUS_URL", "http://127.0.0.1:9090"))
|
||||
parser.add_argument("--loki", default=os.environ.get("LOKI_URL", "http://127.0.0.1:3100"))
|
||||
parser.add_argument("--tempo", default=os.environ.get("TEMPO_URL", "http://127.0.0.1:3200"))
|
||||
parser.add_argument("--grafana", default=os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000"))
|
||||
parser.add_argument("--grafana-password-file", default=os.environ.get("GRAFANA_PASSWORD_FILE", str(ROOT / "secrets/grafana_admin_password")))
|
||||
parser.add_argument("--timeout", type=float, default=60)
|
||||
sub = parser.add_subparsers(dest="command", required=True)
|
||||
p = sub.add_parser("probe", help="send a synthetic OTLP trace, log and metric and find them in every backend and in Grafana")
|
||||
p.add_argument("--otlp", default=os.environ.get("OTLP_URL", "http://127.0.0.1:4318"))
|
||||
p.add_argument("--service-name", default="obs-probe")
|
||||
p.add_argument("--no-grafana", action="store_true")
|
||||
for name, fn in (("request", request_check), ("job", job_check), ("leaks", leaks_check), ("uploads", uploads_burst)):
|
||||
q = sub.add_parser(name)
|
||||
q.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
q.add_argument("--api-service", default="messenger-api")
|
||||
q.add_argument("--worker-service", default="messenger-worker")
|
||||
q.add_argument("--service-regex", default="messenger-.*")
|
||||
q.add_argument("--log-request-id-key", default="request_id")
|
||||
q.add_argument("--log-attachment-key", default="attachment_id")
|
||||
q.add_argument("--attachment-attr", default="messenger.attachment_id")
|
||||
q.add_argument("--attempt-attr", default="messenger.job.attempt")
|
||||
q.add_argument("--image", default=str(ROOT / "tests/fixtures/sample.png"))
|
||||
q.add_argument("--flush", type=float, default=15)
|
||||
q.add_argument("--count", type=int, default=10)
|
||||
q.add_argument("--interval", type=float, default=1)
|
||||
q.set_defaults(fn=fn)
|
||||
q = sub.add_parser("query", help="print instant PromQL results with a timestamp")
|
||||
q.add_argument("expr", nargs="+")
|
||||
q.set_defaults(fn=query)
|
||||
for name, fn in (("dashboards", dashboards_check), ("grafana", grafana_check)):
|
||||
q = sub.add_parser(name)
|
||||
q.add_argument("--dir", default=str(ROOT / "infra/grafana/dashboards"))
|
||||
q.add_argument("--strict", action="store_true", help="fail when a referenced metric does not exist yet")
|
||||
q.set_defaults(fn=fn)
|
||||
w = sub.add_parser("alerts", help="record alert state changes until firing:<a|b> or resolved:<a|b>")
|
||||
w.add_argument("--until", default="")
|
||||
w.add_argument("--only", nargs="*", default=[])
|
||||
w.add_argument("--interval", type=float, default=5)
|
||||
w.add_argument("--output", default="")
|
||||
p.set_defaults(fn=probe)
|
||||
w.set_defaults(fn=alerts_watch)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
args.fn(args, Backends(args))
|
||||
except (Failure, OSError, KeyError, ValueError) as error:
|
||||
print(f"FAIL: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,272 @@
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import closing
|
||||
from http.client import HTTPConnection
|
||||
from pathlib import Path
|
||||
|
||||
from obs_check import Api, http, now
|
||||
from obs_incidents import collector_metrics
|
||||
from obs_recovery import backends, compose
|
||||
|
||||
MODES = {
|
||||
"off": ("true", "1", "collector.yaml", "10000"),
|
||||
"on": ("false", "1", "collector.yaml", "10000"),
|
||||
"head": ("false", "0.1", "collector.yaml", "10000"),
|
||||
"tail": ("false", "1", "collector-tail.yaml", "10000"),
|
||||
"balanced": ("false", "1", "collector-balanced.yaml", "30000"),
|
||||
}
|
||||
|
||||
|
||||
def configure(mode):
|
||||
disabled, ratio, config, interval = MODES[mode]
|
||||
os.environ.update(
|
||||
OTEL_SDK_DISABLED=disabled,
|
||||
OTEL_TRACE_RATIO=ratio,
|
||||
OTEL_COLLECTOR_CONFIG=config,
|
||||
OTEL_METRIC_EXPORT_INTERVAL=interval,
|
||||
COST_EXPERIMENT="true",
|
||||
)
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--force-recreate",
|
||||
"--wait",
|
||||
"otel-collector",
|
||||
"api",
|
||||
"worker",
|
||||
"relay",
|
||||
)
|
||||
subprocess.run(["scripts/lb-wait.sh"], check=True, capture_output=True)
|
||||
|
||||
|
||||
class Engine(HTTPConnection):
|
||||
def __init__(self, path):
|
||||
super().__init__("localhost", timeout=10)
|
||||
self.path = path
|
||||
|
||||
def connect(self):
|
||||
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
self.sock.settimeout(self.timeout)
|
||||
self.sock.connect(self.path)
|
||||
|
||||
|
||||
def engine_read(path, route):
|
||||
with closing(Engine(path)) as connection:
|
||||
connection.request("GET", route)
|
||||
response = connection.getresponse()
|
||||
if response.status != 200:
|
||||
raise RuntimeError("Docker stats unavailable")
|
||||
return json.load(response)
|
||||
|
||||
|
||||
class Resources:
|
||||
def __init__(self):
|
||||
host = subprocess.check_output(
|
||||
["docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}"], text=True
|
||||
).strip()
|
||||
if not host.startswith("unix://"):
|
||||
raise RuntimeError("cost measurement requires a local Docker socket")
|
||||
self.path = host[7:]
|
||||
self.ids = compose("ps", "-q").splitlines()
|
||||
self.names = dict(
|
||||
zip(
|
||||
self.ids,
|
||||
subprocess.check_output(
|
||||
["docker", "inspect", "-f", "{{.Name}}", *self.ids], text=True
|
||||
).splitlines(),
|
||||
)
|
||||
)
|
||||
self.samples = []
|
||||
self.stop = threading.Event()
|
||||
self.thread = threading.Thread(target=self.poll)
|
||||
|
||||
def sample(self):
|
||||
rows = []
|
||||
for identity in self.ids:
|
||||
data = engine_read(
|
||||
self.path, f"/containers/{identity}/stats?stream=false&one-shot=true"
|
||||
)
|
||||
memory = data["memory_stats"]
|
||||
rows.append(
|
||||
{
|
||||
"id": identity[:12],
|
||||
"name": self.names[identity],
|
||||
"cpu_ns": data["cpu_stats"]["cpu_usage"]["total_usage"],
|
||||
"working_set_bytes": memory["usage"]
|
||||
- memory.get("stats", {}).get("inactive_file", 0),
|
||||
"memory_limit": memory["limit"],
|
||||
}
|
||||
)
|
||||
return {"at": time.time(), "containers": rows}
|
||||
|
||||
def poll(self):
|
||||
while not self.stop.wait(2):
|
||||
self.samples.append(self.sample())
|
||||
|
||||
def begin(self):
|
||||
self.samples.append(self.sample())
|
||||
self.thread.start()
|
||||
|
||||
def finish(self):
|
||||
self.stop.set()
|
||||
self.thread.join()
|
||||
self.samples.append(self.sample())
|
||||
return self.samples
|
||||
|
||||
|
||||
def counters(url, names):
|
||||
raw = http("GET", url + "/metrics", expect=(200,))[3].decode()
|
||||
result = {}
|
||||
for line in raw.splitlines():
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
name = line.split("{", 1)[0].split(" ", 1)[0]
|
||||
if name in names:
|
||||
result[name] = result.get(name, 0) + float(line.rsplit(" ", 1)[1])
|
||||
return result
|
||||
|
||||
|
||||
def accounting(b, hosts):
|
||||
metric = b.promql('sum(messenger_telemetry_spans_ended_total{instance=~"' + hosts + '"})')
|
||||
return {
|
||||
"collector": collector_metrics(),
|
||||
"sdk_ended_spans": float(metric[0]["value"][1]) if metric else 0,
|
||||
"tempo": counters(b.tempo, {"tempo_distributor_bytes_received_total"}),
|
||||
"loki": counters(b.loki, {"loki_distributor_bytes_received_total"}),
|
||||
"prometheus": counters(b.prometheus, {"prometheus_tsdb_head_samples_appended_total"}),
|
||||
}
|
||||
|
||||
|
||||
def run(mode, repeat, duration, rate, destination):
|
||||
configure(mode)
|
||||
b = backends()
|
||||
api = Api(os.environ["BASE_URL"])
|
||||
_, username, password, _ = api.register()
|
||||
auth, _ = api.login(username, password)
|
||||
for _ in range(20):
|
||||
api.call("GET", "/api/v1/users/me", headers=auth)
|
||||
time.sleep(35)
|
||||
hosts = "|".join(
|
||||
subprocess.check_output(
|
||||
["docker", "inspect", "-f", "{{.Config.Hostname}}", cid], text=True
|
||||
).strip()
|
||||
+ "-.*"
|
||||
for cid in compose("ps", "-q", "api", "worker", "relay").splitlines()
|
||||
)
|
||||
before = accounting(b, hosts)
|
||||
background = subprocess.check_output(
|
||||
["docker", "ps", "--format", '{{.Names}} {{.Label "com.docker.compose.project"}}'],
|
||||
text=True,
|
||||
).splitlines()
|
||||
resources = Resources()
|
||||
resources.begin()
|
||||
started = time.time()
|
||||
origin = time.perf_counter()
|
||||
prefix = "cost-" + uuid.uuid4().hex[:12]
|
||||
|
||||
def request(index):
|
||||
category = "error" if index % 50 == 0 else "slow" if index % 50 == 1 else "normal"
|
||||
rid = prefix + "-" + category + "-" + str(index)
|
||||
began = time.perf_counter()
|
||||
headers = dict(auth, **{"X-Request-Id": rid, "X-Lab-Cost": category})
|
||||
try:
|
||||
status = http("GET", api.base + "/api/v1/users/me", headers=headers)[0]
|
||||
except OSError:
|
||||
status = 0
|
||||
return {
|
||||
"id": rid,
|
||||
"category": category,
|
||||
"status": status,
|
||||
"latency_ms": (time.perf_counter() - began) * 1000,
|
||||
"schedule_lag_ms": (began - origin - index / rate) * 1000,
|
||||
}
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=64) as pool:
|
||||
futures = []
|
||||
for index in range(int(duration * rate)):
|
||||
time.sleep(max(0, origin + index / rate - time.perf_counter()))
|
||||
futures.append(pool.submit(request, index))
|
||||
requests = [future.result() for future in futures]
|
||||
finished = time.time()
|
||||
samples = resources.finish()
|
||||
time.sleep(35)
|
||||
after = accounting(b, hosts)
|
||||
retained = {}
|
||||
for category in ("normal", "error", "slow"):
|
||||
found = b.traceql(
|
||||
'{ span.messenger.request_id =~ "' + prefix + "-" + category + '-.*" }',
|
||||
started - 1,
|
||||
time.time() + 1,
|
||||
limit=5000,
|
||||
)
|
||||
retained[category] = sorted({t["traceID"] for t in found})
|
||||
api.logout(auth)
|
||||
unexpected = [r for r in requests if r["status"] != (503 if r["category"] == "error" else 200)]
|
||||
report = {
|
||||
"utc": now(),
|
||||
"sha": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
|
||||
"mode": mode,
|
||||
"repeat": repeat,
|
||||
"duration": duration,
|
||||
"rate": rate,
|
||||
"started": started,
|
||||
"finished": finished,
|
||||
"background": background,
|
||||
"requests": requests,
|
||||
"resources": samples,
|
||||
"before": before,
|
||||
"after": after,
|
||||
"retained_trace_ids": retained,
|
||||
"unexpected_responses": len(unexpected),
|
||||
"result": "PASS" if not unexpected else "FAIL",
|
||||
}
|
||||
destination.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"mode": mode,
|
||||
"repeat": repeat,
|
||||
"result": report["result"],
|
||||
"retained": {k: len(v) for k, v in retained.items()},
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
if unexpected:
|
||||
raise RuntimeError("unexpected benchmark responses; raw series saved")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--mode", choices=MODES)
|
||||
parser.add_argument("--repeat", type=int, default=1)
|
||||
parser.add_argument("--duration", type=int, default=40)
|
||||
parser.add_argument("--rate", type=int, default=20)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
if args.output.exists():
|
||||
raise RuntimeError("refusing to overwrite evidence")
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
run(args.mode, args.repeat, args.duration, args.rate, args.output)
|
||||
finally:
|
||||
os.environ.update(
|
||||
OTEL_SDK_DISABLED="false",
|
||||
OTEL_TRACE_RATIO="1",
|
||||
OTEL_COLLECTOR_CONFIG="collector.yaml",
|
||||
OTEL_METRIC_EXPORT_INTERVAL="10000",
|
||||
COST_EXPERIMENT="false",
|
||||
)
|
||||
compose("up", "-d", "--no-deps", "--wait", "otel-collector", "api", "worker", "relay")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,129 @@
|
||||
import argparse
|
||||
import json
|
||||
import statistics
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def percentile(values, fraction):
|
||||
ordered = sorted(values)
|
||||
return ordered[min(len(ordered) - 1, int((len(ordered) - 1) * fraction))]
|
||||
|
||||
|
||||
def total(counters, prefix):
|
||||
return sum(v for k, v in counters.items() if k.startswith(prefix + "{"))
|
||||
|
||||
|
||||
def summarize(path):
|
||||
run = json.loads(path.read_text())
|
||||
before, after = run["before"], run["after"]
|
||||
resources = run["resources"]
|
||||
elapsed = resources[-1]["at"] - resources[0]["at"]
|
||||
first = {r["id"]: r for r in resources[0]["containers"]}
|
||||
cpu = {}
|
||||
memory = {}
|
||||
membership = {}
|
||||
for row in resources[-1]["containers"]:
|
||||
name = row["name"]
|
||||
group = (
|
||||
"application"
|
||||
if any(part in name for part in ("-api-", "-relay-", "-worker-"))
|
||||
else "observability"
|
||||
if any(
|
||||
part in name
|
||||
for part in ("-otel-collector-", "-prometheus-", "-loki-", "-tempo-", "-grafana-")
|
||||
)
|
||||
else "business_stores_lb"
|
||||
)
|
||||
membership[row["id"]] = group
|
||||
cpu[group] = (
|
||||
cpu.get(group, 0) + (row["cpu_ns"] - first[row["id"]]["cpu_ns"]) / 1e9 / elapsed
|
||||
)
|
||||
memory[name] = max(
|
||||
r["working_set_bytes"]
|
||||
for sample in resources
|
||||
for r in sample["containers"]
|
||||
if r["id"] == row["id"]
|
||||
)
|
||||
latency = [r["latency_ms"] for r in run["requests"]]
|
||||
normal = [r["latency_ms"] for r in run["requests"] if r["category"] == "normal"]
|
||||
collector = {}
|
||||
for name in ("accepted", "sent", "failed"):
|
||||
prefix = {
|
||||
"accepted": "otelcol_receiver_accepted_spans_total",
|
||||
"sent": "otelcol_exporter_sent_spans_total",
|
||||
"failed": "otelcol_exporter_send_failed_spans_total",
|
||||
}[name]
|
||||
collector[name] = total(after["collector"], prefix) - total(before["collector"], prefix)
|
||||
ingest = {
|
||||
backend: {key: value - before[backend].get(key, 0) for key, value in after[backend].items()}
|
||||
for backend in ("tempo", "loki", "prometheus")
|
||||
}
|
||||
return {
|
||||
"file": path.name,
|
||||
"mode": run["mode"],
|
||||
"repeat": run["repeat"],
|
||||
"sha": run["sha"],
|
||||
"result": run["result"],
|
||||
"requests": len(latency),
|
||||
"unexpected_responses": run["unexpected_responses"],
|
||||
"p50_ms": percentile(latency, 0.5),
|
||||
"p95_ms": percentile(latency, 0.95),
|
||||
"p99_ms": percentile(latency, 0.99),
|
||||
"normal_p95_ms": percentile(normal, 0.95),
|
||||
"max_schedule_lag_ms": max(r["schedule_lag_ms"] for r in run["requests"]),
|
||||
"cpu_cores": cpu,
|
||||
"memory_peak_bytes": memory,
|
||||
"memory_peak_group_bytes": {
|
||||
group: max(
|
||||
sum(
|
||||
r["working_set_bytes"]
|
||||
for r in sample["containers"]
|
||||
if membership[r["id"]] == group
|
||||
)
|
||||
for sample in resources
|
||||
)
|
||||
for group in set(membership.values())
|
||||
},
|
||||
"achieved_rps": len(latency) / (run["finished"] - run["started"]),
|
||||
"resource_samples": len(resources),
|
||||
"ingest": ingest,
|
||||
"sdk_ended_spans": after["sdk_ended_spans"] - before["sdk_ended_spans"],
|
||||
"collector_spans": collector,
|
||||
"traces": {
|
||||
kind: {
|
||||
"expected": sum(r["category"] == kind for r in run["requests"]),
|
||||
"retained": len(ids),
|
||||
}
|
||||
for kind, ids in run["retained_trace_ids"].items()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("directory", type=Path)
|
||||
args = parser.parse_args()
|
||||
rows = [
|
||||
summarize(p)
|
||||
for p in sorted(args.directory.glob("*-*.json"))
|
||||
if p.name.split("-")[0] in {"off", "on", "head", "tail", "balanced"}
|
||||
]
|
||||
groups = {
|
||||
mode: {
|
||||
key: {
|
||||
"median": statistics.median(r[key] for r in rows if r["mode"] == mode),
|
||||
"min": min(r[key] for r in rows if r["mode"] == mode),
|
||||
"max": max(r[key] for r in rows if r["mode"] == mode),
|
||||
}
|
||||
for key in ("p50_ms", "p95_ms", "p99_ms", "normal_p95_ms")
|
||||
}
|
||||
for mode in sorted({r["mode"] for r in rows})
|
||||
}
|
||||
(args.directory / "comparison.json").write_text(
|
||||
json.dumps({"runs": rows, "latency_ranges": groups}, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps({"runs": len(rows), "modes": groups}, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,387 @@
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from obs_check import Api, Failure, get_json, http, now, tempo_spans, wait_for
|
||||
from obs_recovery import backends, compose
|
||||
|
||||
|
||||
def actor():
|
||||
api = Api(os.environ["BASE_URL"])
|
||||
user, username, password, _ = api.register()
|
||||
auth, _ = api.login(username, password)
|
||||
return api, auth, api.chat(auth, user)
|
||||
|
||||
|
||||
def upload(api, auth, chat):
|
||||
return api.call(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/attachments?filename=observation.png",
|
||||
Path("tests/fixtures/sample.png").read_bytes(),
|
||||
dict(auth, **{"Content-Type": "image/png"}),
|
||||
expect=(202,),
|
||||
)
|
||||
|
||||
|
||||
def ready(api, auth, attachment):
|
||||
def check():
|
||||
item = api.call("GET", "/api/v1/attachments/" + attachment["id"], headers=auth)[0]
|
||||
if item["status"] == "failed":
|
||||
raise RuntimeError("attachment failed")
|
||||
return item if item["status"] == "ready" else None
|
||||
|
||||
return wait_for("ready", check, 120, 1)
|
||||
|
||||
|
||||
def value(b, expression):
|
||||
result = b.promql(expression)
|
||||
return float(result[0]["value"][1]) if result else None
|
||||
|
||||
|
||||
def alert(b, name, firing):
|
||||
def check():
|
||||
alerts = get_json(b.prometheus + "/api/v1/alerts")["data"]["alerts"]
|
||||
found = [
|
||||
a for a in alerts if a["labels"].get("alertname") == name and a["state"] == "firing"
|
||||
]
|
||||
if bool(found) == firing:
|
||||
return {"utc": now(), "state": "firing" if firing else "resolved", "alerts": found}
|
||||
return None
|
||||
|
||||
return wait_for(name, check, 150)
|
||||
|
||||
|
||||
def chain(b, retry):
|
||||
api, auth, chat = actor()
|
||||
started = time.time()
|
||||
if retry:
|
||||
compose("stop", "worker")
|
||||
attachment, rid = upload(api, auth, chat)
|
||||
try:
|
||||
if retry:
|
||||
compose("stop", "s3")
|
||||
compose("up", "-d", "--no-deps", "--wait", "worker")
|
||||
query = (
|
||||
'{service_name="messenger-worker"} | attachment_id="'
|
||||
+ attachment["id"]
|
||||
+ '" | outcome="retry_scheduled"'
|
||||
)
|
||||
wait_for("real S3 retry", lambda: b.logs(query, started, time.time() + 1), 60)
|
||||
finally:
|
||||
if retry:
|
||||
compose("up", "-d", "--no-deps", "--wait", "s3", "worker")
|
||||
ready(api, auth, attachment)
|
||||
logs = wait_for(
|
||||
"upload log",
|
||||
lambda: b.logs(
|
||||
'{service_name="messenger-api"} | request_id="' + rid + '"',
|
||||
started - 1,
|
||||
time.time() + 1,
|
||||
),
|
||||
60,
|
||||
)
|
||||
trace_id = logs[0][0]["trace_id"]
|
||||
|
||||
def complete():
|
||||
spans = tempo_spans(b.trace(trace_id)[0])
|
||||
return (
|
||||
spans
|
||||
if any(s["attributes"].get("messenger.job.outcome") == "done" for s in spans)
|
||||
else None
|
||||
)
|
||||
|
||||
spans = wait_for("complete trace", complete, 90)
|
||||
roots = [
|
||||
s
|
||||
for s in spans
|
||||
if s["kind"] == "SPAN_KIND_SERVER" and s["attributes"].get("messenger.request_id") == rid
|
||||
]
|
||||
ids = {s["span_id"] for s in spans}
|
||||
producers = [s for s in spans if s["kind"] == "SPAN_KIND_PRODUCER"]
|
||||
consumers = [s for s in spans if s["kind"] == "SPAN_KIND_CONSUMER"]
|
||||
clients = [s for s in spans if s["kind"] == "SPAN_KIND_CLIENT"]
|
||||
if (
|
||||
not roots
|
||||
or not producers
|
||||
or not consumers
|
||||
or any(s["parent_span_id"] not in ids for s in producers + consumers)
|
||||
):
|
||||
raise Failure("broken distributed parent chain")
|
||||
if not any(s["attributes"].get("rpc.service") == "S3" for s in clients) or not any(
|
||||
s["attributes"].get("db.system") == "postgresql" for s in clients
|
||||
):
|
||||
raise Failure("missing dependency spans")
|
||||
outcomes = [s["attributes"].get("messenger.job.outcome") for s in consumers]
|
||||
if retry and "retry_scheduled" not in outcomes:
|
||||
raise Failure("retry left original trace")
|
||||
api.logout(auth)
|
||||
fields = ("service", "name", "kind", "status", "span_id", "parent_span_id", "duration_ms")
|
||||
return {
|
||||
"upload_request_id": rid,
|
||||
"trace_id": trace_id,
|
||||
"retry": retry,
|
||||
"outcomes": outcomes,
|
||||
"spans": [
|
||||
{**{k: s[k] for k in fields}, "attempt": s["attributes"].get("messenger.job.attempt")}
|
||||
for s in spans
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def worker(b):
|
||||
api, auth, chat = actor()
|
||||
compose("stop", "worker")
|
||||
stopped = now()
|
||||
try:
|
||||
items = [upload(api, auth, chat)[0] for _ in range(8)]
|
||||
firing = alert(b, "MessengerQueueLag", True)
|
||||
observed = {
|
||||
"depth": value(b, "max(messenger_queue_depth)"),
|
||||
"age_seconds": value(b, "max(messenger_queue_oldest_age_seconds)"),
|
||||
}
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--wait", "worker")
|
||||
restored = now()
|
||||
for item in items:
|
||||
ready(api, auth, item)
|
||||
resolved = alert(b, "MessengerQueueLag", False)
|
||||
api.logout(auth)
|
||||
return {
|
||||
"stopped": stopped,
|
||||
"restored": restored,
|
||||
"jobs": len(items),
|
||||
"backlog": observed,
|
||||
"firing": firing,
|
||||
"resolved": resolved,
|
||||
"depth_after": value(b, "max(messenger_queue_depth)"),
|
||||
}
|
||||
|
||||
|
||||
def database(b):
|
||||
api, auth, _ = actor()
|
||||
started = time.time()
|
||||
prefix = "db-incident-" + uuid.uuid4().hex[:12]
|
||||
|
||||
def request(index):
|
||||
rid = prefix + "-" + str(index)
|
||||
status = http(
|
||||
"GET", api.base + "/api/v1/users/me", headers=dict(auth, **{"X-Request-Id": rid})
|
||||
)[0]
|
||||
return {"request_id": rid, "status": status}
|
||||
|
||||
for index in range(10):
|
||||
request(index)
|
||||
time.sleep(12)
|
||||
psql = [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'exec psql -X -q -A -t -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" "$@"',
|
||||
"--",
|
||||
"-c",
|
||||
]
|
||||
lock_sql = (
|
||||
"SET application_name='lab6-db-lock'; BEGIN; "
|
||||
"LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(120); ROLLBACK;"
|
||||
)
|
||||
process = subprocess.Popen(
|
||||
[*psql, lock_sql], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
||||
)
|
||||
paused = now()
|
||||
responses = []
|
||||
try:
|
||||
time.sleep(1)
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
|
||||
for batch in range(20):
|
||||
responses.extend(pool.map(request, range(10 + batch * 12, 22 + batch * 12)))
|
||||
alerts = get_json(b.prometheus + "/api/v1/alerts")["data"]["alerts"]
|
||||
if any(
|
||||
a["labels"].get("alertname") == "MessengerHighErrorRate"
|
||||
and a["state"] == "firing"
|
||||
for a in alerts
|
||||
):
|
||||
break
|
||||
time.sleep(1)
|
||||
firing = alert(b, "MessengerHighErrorRate", True)
|
||||
signals = {
|
||||
"error_ratio": value(b, "messenger:http_errors:ratio_rate1m"),
|
||||
"pool_waiting": value(b, "max(max_over_time(messenger_db_pool_waiting[1m]))"),
|
||||
}
|
||||
finally:
|
||||
subprocess.run(
|
||||
[
|
||||
*psql,
|
||||
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
|
||||
"WHERE application_name='lab6-db-lock'",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
process.wait(timeout=10)
|
||||
restored = now()
|
||||
wait_for("database recovery", lambda: http("GET", api.base + "/health/ready")[0] == 200, 90)
|
||||
for index in range(34, 74):
|
||||
request(index)
|
||||
time.sleep(0.15)
|
||||
resolved = alert(b, "MessengerHighErrorRate", False)
|
||||
traces = b.traceql(
|
||||
'{ span.messenger.request_id =~ "' + prefix + '.*" }',
|
||||
started - 1,
|
||||
time.time() + 1,
|
||||
limit=100,
|
||||
)
|
||||
dependency = []
|
||||
for trace in traces:
|
||||
spans = tempo_spans(b.trace(trace["traceID"])[0])
|
||||
failed = [
|
||||
s
|
||||
for s in spans
|
||||
if s["attributes"].get("db.system") == "postgresql"
|
||||
and s["status"] == "STATUS_CODE_ERROR"
|
||||
]
|
||||
if failed:
|
||||
dependency.append(
|
||||
{
|
||||
"trace_id": trace["traceID"],
|
||||
"db_errors": [
|
||||
{k: s[k] for k in ("name", "kind", "status", "duration_ms")} for s in failed
|
||||
],
|
||||
}
|
||||
)
|
||||
if not dependency or not any(r["status"] == 503 for r in responses):
|
||||
raise Failure("database incident has no dependency failure trace")
|
||||
api.logout(auth)
|
||||
return {
|
||||
"paused": paused,
|
||||
"restored": restored,
|
||||
"requests": responses,
|
||||
"signals": signals,
|
||||
"firing": firing,
|
||||
"resolved": resolved,
|
||||
"dependency_traces": dependency,
|
||||
}
|
||||
|
||||
|
||||
def collector_metrics():
|
||||
source = 'import urllib.request; print(urllib.request.urlopen("http://otel-collector:8888/metrics").read().decode())'
|
||||
raw = compose("exec", "-T", "api", "python", "-c", source)
|
||||
return {
|
||||
line.rsplit(" ", 1)[0]: float(line.rsplit(" ", 1)[1])
|
||||
for line in raw.splitlines()
|
||||
if line.startswith(
|
||||
(
|
||||
"otelcol_receiver_accepted_",
|
||||
"otelcol_exporter_sent_",
|
||||
"otelcol_exporter_send_failed_",
|
||||
"otelcol_exporter_queue_",
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def memory():
|
||||
ids = compose("ps", "-q", "api", "relay", "worker", "otel-collector").splitlines()
|
||||
raw = subprocess.check_output(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", *ids], text=True
|
||||
)
|
||||
return [
|
||||
{k: row[k] for k in ("Name", "MemUsage", "MemPerc", "CPUPerc")}
|
||||
for row in map(json.loads, raw.splitlines())
|
||||
]
|
||||
|
||||
|
||||
def storage(b):
|
||||
api, auth, _ = actor()
|
||||
before = collector_metrics()
|
||||
samples = [{"utc": now(), "containers": memory()}]
|
||||
compose("stop", "prometheus", "loki", "tempo")
|
||||
stopped = now()
|
||||
requests = []
|
||||
try:
|
||||
result = subprocess.run(["make", "test"], capture_output=True, text=True, check=True)
|
||||
until = time.monotonic() + 85
|
||||
while time.monotonic() < until:
|
||||
rid = "storage-outage-" + uuid.uuid4().hex
|
||||
status = http(
|
||||
"GET",
|
||||
api.base + "/api/v1/users/me",
|
||||
headers=dict(auth, **{"X-Request-Id": rid}),
|
||||
expect=(200,),
|
||||
)[0]
|
||||
requests.append({"id": rid, "status": status})
|
||||
if len(requests) % 15 == 0:
|
||||
samples.append({"utc": now(), "containers": memory()})
|
||||
time.sleep(1)
|
||||
during = collector_metrics()
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--wait", "prometheus", "loki", "tempo")
|
||||
restored = now()
|
||||
time.sleep(20)
|
||||
after = collector_metrics()
|
||||
samples.append({"utc": now(), "containers": memory()})
|
||||
found = 0
|
||||
for item in requests:
|
||||
found += bool(
|
||||
b.traceql(
|
||||
'{ span.messenger.request_id = "' + item["id"] + '" }',
|
||||
time.time() - 300,
|
||||
time.time() + 1,
|
||||
)
|
||||
)
|
||||
peak_percent = max(
|
||||
float(row["MemPerc"].rstrip("%")) for sample in samples for row in sample["containers"]
|
||||
)
|
||||
if peak_percent >= 100:
|
||||
raise Failure("container memory limit reached")
|
||||
api.logout(auth)
|
||||
return {
|
||||
"stopped": stopped,
|
||||
"restored": restored,
|
||||
"peak_memory_percent_of_limit": peak_percent,
|
||||
"smoke": result.stdout,
|
||||
"successful_probes": len(requests),
|
||||
"stored_probe_traces": found,
|
||||
"lost_probe_traces": len(requests) - found,
|
||||
"memory_samples": samples,
|
||||
"collector_before": before,
|
||||
"collector_during": during,
|
||||
"collector_after": after,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("scenario", choices=("chain", "retry", "worker", "database", "storage"))
|
||||
args = parser.parse_args()
|
||||
b = backends()
|
||||
started = now()
|
||||
report = (
|
||||
chain(b, args.scenario == "retry")
|
||||
if args.scenario in ("chain", "retry")
|
||||
else {"worker": worker, "database": database, "storage": storage}[args.scenario](b)
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"started": started,
|
||||
"finished": now(),
|
||||
"result": "PASS",
|
||||
"scenario": args.scenario,
|
||||
"observations": report,
|
||||
},
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,98 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from obs_check import Api, Backends, get_json, http, now, tempo_spans, wait_for
|
||||
|
||||
|
||||
def backends():
|
||||
return Backends(
|
||||
argparse.Namespace(
|
||||
prometheus=os.environ["PROMETHEUS_URL"],
|
||||
loki=os.environ["LOKI_URL"],
|
||||
tempo=os.environ["TEMPO_URL"],
|
||||
grafana=os.environ["GRAFANA_URL"],
|
||||
grafana_password_file=os.environ.get(
|
||||
"GRAFANA_PASSWORD_FILE", "/".join(("secrets", "grafana_admin_password"))
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args], check=True, capture_output=True, text=True
|
||||
).stdout.strip()
|
||||
|
||||
|
||||
def history(b):
|
||||
started = time.time()
|
||||
_, _, _, rid = Api(os.environ["BASE_URL"]).register()
|
||||
query = '{service_name="messenger-api"} | request_id="' + rid + '"'
|
||||
logs = wait_for("log", lambda: b.logs(query, started - 1, time.time() + 1), 60)
|
||||
trace_id = logs[0][0]["trace_id"]
|
||||
spans = wait_for("trace", lambda: tempo_spans(b.trace(trace_id)[0]), 60)
|
||||
expr = 'sum(http_server_request_duration_seconds_count{job="messenger-api"})'
|
||||
before = wait_for("metrics", lambda: b.promql(expr), 60)
|
||||
at = before[0]["value"][0]
|
||||
compose("restart", "prometheus", "loki", "tempo", "grafana")
|
||||
wait_for("Grafana", lambda: get_json(b.grafana + "/api/health"), 90)
|
||||
after_logs = wait_for("retained log", lambda: b.logs(query, started - 1, time.time() + 1), 90)
|
||||
after_spans = wait_for("retained trace", lambda: tempo_spans(b.trace(trace_id)[0]), 90)
|
||||
after = wait_for("retained metric", lambda: b.promql(expr, at=at), 90)
|
||||
if before[0]["value"][1] != after[0]["value"][1] or len(after_spans) < len(spans):
|
||||
raise RuntimeError("telemetry history changed after restart")
|
||||
return {
|
||||
"request_id": rid,
|
||||
"trace_id": trace_id,
|
||||
"spans_before": len(spans),
|
||||
"spans_after": len(after_spans),
|
||||
"logs_after": len(after_logs),
|
||||
"metric_before": before,
|
||||
"metric_after": after,
|
||||
}
|
||||
|
||||
|
||||
def collector():
|
||||
compose("stop", "otel-collector")
|
||||
try:
|
||||
status = http("GET", os.environ["BASE_URL"] + "/health/ready")[0]
|
||||
result = subprocess.run(["make", "test"], capture_output=True, text=True, check=False)
|
||||
if status != 200 or result.returncode:
|
||||
raise RuntimeError("application failed without collector")
|
||||
replica = compose("ps", "-q", "api").splitlines()[0]
|
||||
started = time.monotonic()
|
||||
subprocess.run(["docker", "stop", "-t", "8", replica], check=True, capture_output=True)
|
||||
elapsed = time.monotonic() - started
|
||||
code = subprocess.check_output(
|
||||
["docker", "inspect", "-f", "{{.State.ExitCode}}", replica], text=True
|
||||
).strip()
|
||||
if code != "0" or elapsed > 8:
|
||||
raise RuntimeError("unbounded API shutdown")
|
||||
return {
|
||||
"ready": status,
|
||||
"smoke": result.stdout.strip(),
|
||||
"api_exit_code": code,
|
||||
"api_shutdown_seconds": round(elapsed, 3),
|
||||
}
|
||||
finally:
|
||||
compose("up", "-d", "--no-deps", "--wait", "api", "otel-collector")
|
||||
subprocess.run(["scripts/lb-wait.sh"], check=True)
|
||||
|
||||
|
||||
def main():
|
||||
b = backends()
|
||||
report = {
|
||||
"utc": now(),
|
||||
"sha": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
|
||||
}
|
||||
report["history"] = history(b)
|
||||
report["collector_down"] = collector()
|
||||
report["result"] = "PASS"
|
||||
print(json.dumps(report, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
limit="${WAIT_SECONDS:-1500}"
|
||||
out=${EVIDENCE_DIR:-evidence}
|
||||
mkdir -p "$out"
|
||||
sql() { docker compose exec -T postgres psql -U messenger -d messenger -X "$@"; }
|
||||
pending() { sql -tAc "SELECT count(*) FROM attachments WHERE status = 'pending'"; }
|
||||
statuses="SELECT status, count(*), min(created_at), max(created_at) FROM attachments GROUP BY status ORDER BY status"
|
||||
since=$(date -u +%FT%TZ)
|
||||
{
|
||||
echo "date: $since commit: $(git rev-parse HEAD)"
|
||||
echo "# make overload-leftovers (scripts/overload-leftovers.sh) после серии памяти: невидимые намерения от 503 по"
|
||||
echo "# таймауту видны сверке свежими, уборка API удаляет их после UPLOAD_GRACE_SECONDS; стенд тот же"
|
||||
echo "\$ make reconcile # dry-run"
|
||||
docker compose run --rm --no-deps -T reconciler 2>/dev/null
|
||||
echo "\$ psql -c \"$statuses\""
|
||||
sql -c "$statuses"
|
||||
echo "\$ until [ \"\$(psql -tAc \"SELECT count(*) FROM attachments WHERE status = 'pending'\")\" = 0 ]; do sleep 10; done"
|
||||
started=$(date +%s)
|
||||
until [ "$(pending)" = 0 ] || [ $(( $(date +%s) - started )) -gt "$limit" ]; do sleep 10; done
|
||||
echo "pending = $(pending) в $(date -u +%FT%TZ)"
|
||||
[ "$(pending)" = 0 ] || { echo "FAIL: pending cleanup timed out"; exit 1; }
|
||||
echo "\$ docker compose logs --since $since api | audit.attachment_discarded и attachments.swept"
|
||||
docker compose logs --no-log-prefix --since "$since" api | python3 -c 'import collections, json, sys
|
||||
reasons, swept, times = collections.Counter(), 0, []
|
||||
for line in sys.stdin:
|
||||
if not line.startswith("{"):
|
||||
continue
|
||||
event = json.loads(line)
|
||||
if event.get("event") == "audit.attachment_discarded":
|
||||
reasons[event["reason"]] += 1
|
||||
times.append(event["ts"][:19] + "Z")
|
||||
elif event.get("event") == "attachments.swept":
|
||||
swept += event["count"]
|
||||
print(dict(reasons), "swept", swept, "first", min(times, default="-"), "last", max(times, default="-"))'
|
||||
echo "\$ psql -c \"$statuses\""
|
||||
sql -c "$statuses"
|
||||
echo "\$ make reconcile # dry-run после уборки"
|
||||
docker compose run --rm --no-deps -T reconciler 2>/dev/null
|
||||
} > "$out/overload-leftovers.txt"
|
||||
cat "$out/overload-leftovers.txt"
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
started() {
|
||||
for id in $(docker compose ps -aq); do
|
||||
docker inspect --format '{{index .Config.Labels "com.docker.compose.service"}} {{.Config.Hostname}} {{.State.StartedAt}} {{.State.Status}}' "$id"
|
||||
done | sort
|
||||
}
|
||||
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD)"
|
||||
echo "== before: service hostname StartedAt status"
|
||||
started
|
||||
make --no-print-directory test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL="${1:-http://localhost:8080}"
|
||||
echo "== after: service hostname StartedAt status"
|
||||
started
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
mode=${1:?usage: pg-stats.sh activity <csv> | statements <csv> | size | reset}
|
||||
cd "$(dirname "$0")/.."
|
||||
psql() {
|
||||
docker compose exec -T postgres sh -c 'exec psql -X -q -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "${POSTGRES_DB:-$POSTGRES_USER}" "$@"' psql "$@"
|
||||
}
|
||||
case $mode in
|
||||
reset)
|
||||
psql -c 'set client_min_messages = warning' -c 'create extension if not exists pg_stat_statements' -c 'select pg_stat_statements_reset()' >/dev/null
|
||||
;;
|
||||
size)
|
||||
psql -At -F, -c "select pg_database_size(current_database()), coalesce((select n_live_tup from pg_stat_user_tables where relname = 'messages'), 0)"
|
||||
;;
|
||||
statements)
|
||||
psql -c "copy (select calls, round(total_exec_time::numeric, 3) as total_ms, round(mean_exec_time::numeric, 3) as mean_ms, rows, shared_blks_hit, shared_blks_read, left(regexp_replace(query, '\s+', ' ', 'g'), 200) as query from pg_stat_statements where dbid = (select oid from pg_database where datname = current_database()) and query not like '%pg_stat%' order by total_exec_time desc limit ${TOP:-20}) to stdout with csv header" > "${2:?csv}"
|
||||
;;
|
||||
activity)
|
||||
echo 'ts,state,wait_event_type,wait_event,backends,max_connections' > "${2:?csv}"
|
||||
while :; do
|
||||
ts=$(date +%s)
|
||||
psql -At -F, -c "select coalesce(state, ''), coalesce(wait_event_type, ''), coalesce(wait_event, ''), count(*), current_setting('max_connections') from pg_stat_activity where backend_type = 'client backend' and pid <> pg_backend_pid() group by 1, 2, 3" | sed "s/^/$ts,/" >> "$2" || true
|
||||
sleep "${INTERVAL:-1}"
|
||||
done
|
||||
;;
|
||||
*)
|
||||
echo "unknown mode $mode" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,110 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, check
|
||||
|
||||
COMPOSE = os.environ.get("COMPOSE", "docker compose").split()
|
||||
PEEK = (
|
||||
'RABBITMQADMIN_USERNAME=messenger-ops RABBITMQADMIN_PASSWORD="$(cat /run/secrets/'
|
||||
'rabbitmq_ops_password)" exec rabbitmqadmin -V messenger '
|
||||
"--table-style ascii get messages -q attachments.process -a ack_requeue_true"
|
||||
)
|
||||
QUEUES = "rabbitmqctl -q list_queues -p messenger name messages_ready messages_unacknowledged"
|
||||
|
||||
|
||||
def compose(*argv):
|
||||
done = subprocess.run(
|
||||
[*COMPOSE, *argv], cwd=ROOT, capture_output=True, text=True, timeout=180, check=False
|
||||
)
|
||||
check(done.returncode == 0, f"{' '.join(argv[:3])}: {done.stderr.strip()[-300:]}")
|
||||
return done.stdout
|
||||
|
||||
|
||||
def ready_messages():
|
||||
for line in compose("exec", "-T", "broker", *QUEUES.split()).splitlines():
|
||||
name, ready, _ = [*line.split("\t"), "", ""][:3]
|
||||
if name == "attachments.process":
|
||||
return int(ready)
|
||||
return 0
|
||||
|
||||
|
||||
def say(line):
|
||||
print(line, flush=True)
|
||||
|
||||
|
||||
def stop(service):
|
||||
began = time.monotonic()
|
||||
compose("stop", "-t", "10", service)
|
||||
seconds = time.monotonic() - began
|
||||
container = compose("ps", "-aq", service).split()[0]
|
||||
code = subprocess.run(
|
||||
["docker", "inspect", "-f", "{{.State.ExitCode}}", container],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.strip()
|
||||
say(f"$ docker compose stop -t 10 {service} -> {seconds:.1f} s, exit code {code}")
|
||||
say(
|
||||
compose(
|
||||
"ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}", service
|
||||
).rstrip()
|
||||
)
|
||||
check(seconds <= 10 and code == "0", f"{service} did not stop cleanly on SIGTERM")
|
||||
|
||||
|
||||
def start(service):
|
||||
compose("up", "-d", "--no-deps", "--wait", "--wait-timeout", "90", service)
|
||||
say(f"$ docker compose up -d --no-deps --wait {service} -> healthy")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Lab5 stand evidence: queue, message, SIGTERM")
|
||||
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
say(f"date: {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}")
|
||||
stop("worker")
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
say(f"upload -> 202 status={attachment['status']} id={attachment['id']}")
|
||||
path = f"/api/v1/attachments/{attachment['id']}"
|
||||
for variant in ("original", "thumbnail"):
|
||||
client.call("GET", f"{path}/content?variant={variant}", 409, actor=bob)
|
||||
say(f"GET content?variant={variant} while worker is stopped -> 409")
|
||||
deadline = time.monotonic() + 30
|
||||
while ready_messages() < 1:
|
||||
check(time.monotonic() < deadline, "the job did not reach the broker")
|
||||
time.sleep(0.5)
|
||||
say("$ rabbitmqctl list_queues -p messenger name messages_ready messages_unacknowledged")
|
||||
say(compose("exec", "-T", "broker", *QUEUES.split()).rstrip())
|
||||
say("$ rabbitmqadmin get messages -q attachments.process -a ack_requeue_true")
|
||||
peeked = compose("exec", "-T", "broker", "sh", "-c", PEEK)
|
||||
say(peeked.rstrip())
|
||||
body = json.loads(peeked[peeked.index('{"') : peeked.index("}", peeked.index('{"')) + 1])
|
||||
say(f"payload keys: {sorted(body)}")
|
||||
check(body["attachment_id"] == attachment["id"], "the queued job is for another attachment")
|
||||
stop("relay")
|
||||
start("relay")
|
||||
start("worker")
|
||||
ready = client.wait_ready(bob, attachment)
|
||||
names = [(v["name"], v["width"], v["height"]) for v in ready["variants"]]
|
||||
say(f"after worker start -> status={ready['status']} variants={names}")
|
||||
deadline = time.monotonic() + 30
|
||||
while ready_messages():
|
||||
check(time.monotonic() < deadline, "the queue did not drain")
|
||||
time.sleep(0.5)
|
||||
say(compose("exec", "-T", "broker", *QUEUES.split()).rstrip())
|
||||
say("PASS: pipeline stand evidence")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
+178
@@ -0,0 +1,178 @@
|
||||
import argparse
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROLES = (
|
||||
"lb",
|
||||
"api",
|
||||
"worker",
|
||||
"relay",
|
||||
"migrate",
|
||||
"reconciler",
|
||||
"postgres",
|
||||
"s3",
|
||||
"broker",
|
||||
"valkey",
|
||||
"otel-collector",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"grafana",
|
||||
"openbao",
|
||||
"operator",
|
||||
"outsider",
|
||||
)
|
||||
OPERATOR = Path(
|
||||
os.environ.get("LAB7_OPERATOR_DIR", str(Path.home() / ".local/share/mtusi2026lab7/operator"))
|
||||
)
|
||||
RUNTIME = Path("secrets/pki")
|
||||
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(
|
||||
["openssl", *map(str, args)], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE
|
||||
)
|
||||
|
||||
|
||||
def bootstrap():
|
||||
OPERATOR.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
OPERATOR.chmod(0o700)
|
||||
RUNTIME.mkdir(parents=True, exist_ok=True)
|
||||
if not (OPERATOR / "ca.key").exists():
|
||||
run(
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"rsa:3072",
|
||||
"-nodes",
|
||||
"-keyout",
|
||||
OPERATOR / "ca.key",
|
||||
"-out",
|
||||
OPERATOR / "ca.crt",
|
||||
"-days",
|
||||
"3650",
|
||||
"-subj",
|
||||
"/CN=Lab7 operator CA",
|
||||
"-addext",
|
||||
"basicConstraints=critical,CA:TRUE",
|
||||
"-addext",
|
||||
"keyUsage=critical,keyCertSign,cRLSign",
|
||||
)
|
||||
(OPERATOR / "ca.key").chmod(0o600)
|
||||
(OPERATOR / "index").touch(exist_ok=True)
|
||||
if not (OPERATOR / "crlnumber").exists():
|
||||
(OPERATOR / "crlnumber").write_text("1000\n")
|
||||
(OPERATOR / "ca.cnf").write_text(
|
||||
f"[ca]\ndefault_ca = authority\n[authority]\ndatabase = {OPERATOR}/index\n"
|
||||
f"certificate = {OPERATOR}/ca.crt\nprivate_key = {OPERATOR}/ca.key\n"
|
||||
f"crlnumber = {OPERATOR}/crlnumber\ndefault_md = sha256\ndefault_crl_days = 30\n"
|
||||
)
|
||||
run("ca", "-gencrl", "-config", OPERATOR / "ca.cnf", "-out", OPERATOR / "ca.crl")
|
||||
for role in ROLES:
|
||||
issue(role, replace=False)
|
||||
foreign = RUNTIME / "foreign"
|
||||
foreign.mkdir(exist_ok=True)
|
||||
if not (foreign / "tls.crt").exists():
|
||||
run(
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"rsa:2048",
|
||||
"-nodes",
|
||||
"-keyout",
|
||||
foreign / "tls.key",
|
||||
"-out",
|
||||
foreign / "tls.crt",
|
||||
"-days",
|
||||
"1",
|
||||
"-subj",
|
||||
"/CN=worker",
|
||||
)
|
||||
for file in foreign.iterdir():
|
||||
file.chmod(0o444)
|
||||
|
||||
|
||||
def issue(role, replace=True):
|
||||
target = RUNTIME / role
|
||||
target.mkdir(exist_ok=True)
|
||||
if replace or not (target / "tls.crt").exists():
|
||||
for file in target.iterdir():
|
||||
file.chmod(0o600)
|
||||
if (target / "tls.crt").exists():
|
||||
shutil.copyfile(target / "tls.crt", OPERATOR / f"{role}-previous.crt")
|
||||
run(
|
||||
"req",
|
||||
"-new",
|
||||
"-newkey",
|
||||
"rsa:2048",
|
||||
"-nodes",
|
||||
"-keyout",
|
||||
target / "tls.key",
|
||||
"-out",
|
||||
OPERATOR / f"{role}.csr",
|
||||
"-subj",
|
||||
f"/CN={role}",
|
||||
)
|
||||
ext = OPERATOR / f"{role}.ext"
|
||||
ext.write_text(
|
||||
f"subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always,issuer\n"
|
||||
f"basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=DNS:{role},DNS:localhost,IP:127.0.0.1\n"
|
||||
)
|
||||
run(
|
||||
"x509",
|
||||
"-req",
|
||||
"-in",
|
||||
OPERATOR / f"{role}.csr",
|
||||
"-CA",
|
||||
OPERATOR / "ca.crt",
|
||||
"-CAkey",
|
||||
OPERATOR / "ca.key",
|
||||
"-set_serial",
|
||||
str(int.from_bytes(os.urandom(16), "big")),
|
||||
"-days",
|
||||
"1",
|
||||
"-extfile",
|
||||
ext,
|
||||
"-out",
|
||||
target / "tls.crt",
|
||||
)
|
||||
(target / "tls.pem").write_bytes(
|
||||
(target / "tls.crt").read_bytes() + (target / "tls.key").read_bytes()
|
||||
)
|
||||
for name in ["ca.crt", "ca.crl"]:
|
||||
if (target / name).exists():
|
||||
(target / name).chmod(0o600)
|
||||
shutil.copyfile(OPERATOR / name, target / name)
|
||||
for file in target.iterdir():
|
||||
file.chmod(0o444)
|
||||
target.chmod(0o755)
|
||||
|
||||
|
||||
def revoke(role):
|
||||
cert = OPERATOR / f"{role}-previous.crt"
|
||||
if not cert.exists():
|
||||
cert = RUNTIME / role / "tls.crt"
|
||||
run("ca", "-revoke", cert, "-config", OPERATOR / "ca.cnf")
|
||||
run("ca", "-gencrl", "-config", OPERATOR / "ca.cnf", "-out", OPERATOR / "ca.crl")
|
||||
for directory in RUNTIME.iterdir():
|
||||
path = directory / "ca.crl"
|
||||
if path.exists():
|
||||
path.chmod(0o600)
|
||||
shutil.copyfile(OPERATOR / "ca.crl", path)
|
||||
path.chmod(0o444)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["bootstrap", "issue", "revoke"])
|
||||
parser.add_argument("role", nargs="?", choices=ROLES)
|
||||
args = parser.parse_args()
|
||||
if args.action == "bootstrap":
|
||||
bootstrap()
|
||||
elif args.role:
|
||||
(issue if args.action == "issue" else revoke)(args.role)
|
||||
else:
|
||||
parser.error("role required")
|
||||
print("PKI operation completed; private material not displayed.")
|
||||
@@ -0,0 +1,54 @@
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
|
||||
import aio_pika
|
||||
from security_probe import RESULTS, context, record, signed_s3
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
|
||||
async def compare(data):
|
||||
engine = create_async_engine(
|
||||
data["DATABASE_URL"].replace("postgresql://", "postgresql+asyncpg://"),
|
||||
connect_args={"ssl": context()},
|
||||
hide_parameters=True,
|
||||
)
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text("SELECT count(*) FROM users"))
|
||||
record("broad-db:users-readable", True)
|
||||
await connection.execute(text("CREATE TABLE security_comparison (id integer)"))
|
||||
await connection.rollback()
|
||||
record("broad-db:ddl-allowed", True)
|
||||
await engine.dispose()
|
||||
record(
|
||||
"broad-s3:private-write",
|
||||
signed_s3(data, "PUT", "private/security-comparison", b"probe", role="operator") == 200,
|
||||
)
|
||||
record(
|
||||
"broad-s3:private-delete",
|
||||
signed_s3(data, "DELETE", "private/security-comparison", role="operator") == 204,
|
||||
)
|
||||
parsed = urlsplit(data["BROKER_URL"])
|
||||
url = urlunsplit(
|
||||
("amqps", parsed.netloc.replace("127.0.0.1:5672", "broker:5671"), parsed.path, "", "")
|
||||
)
|
||||
async with await aio_pika.connect(
|
||||
url, ssl_context=context("operator"), timeout=5
|
||||
) as connection:
|
||||
channel = await connection.channel()
|
||||
queue = await channel.declare_queue("security-comparison", exclusive=True)
|
||||
await channel.default_exchange.publish(aio_pika.Message(b"probe"), routing_key=queue.name)
|
||||
message = await queue.get(timeout=5)
|
||||
await message.ack()
|
||||
await queue.delete()
|
||||
record("broad-queue:configure-publish-consume-delete", True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(compare(json.load(sys.stdin)))
|
||||
print(
|
||||
json.dumps({"checks": RESULTS, "passed": all(item["passed"] for item in RESULTS)}, indent=2)
|
||||
)
|
||||
raise SystemExit(0 if all(item["passed"] for item in RESULTS) else 1)
|
||||
Executable
+592
@@ -0,0 +1,592 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import collections
|
||||
import functools
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COUNTERS = ("wretr", "wredis", "econ", "eresp", "hrsp_5xx")
|
||||
PSQL = ["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger"]
|
||||
PSQL += ["-X", "-q", "-At"]
|
||||
|
||||
|
||||
@functools.cache
|
||||
def published(port, fallback):
|
||||
command = ["docker", "compose", "port", "lb", str(port)]
|
||||
found = subprocess.run(command, cwd=str(ROOT), capture_output=True, text=True, check=False)
|
||||
return found.stdout.strip() or fallback
|
||||
|
||||
|
||||
def base_url():
|
||||
return os.environ.get("BASE_URL") or "http://" + published(8080, "localhost:8080")
|
||||
|
||||
|
||||
def stats_url():
|
||||
return os.environ.get("LB_STATS_URL") or f"http://{published(8404, '127.0.0.1:8404')}/stats;csv"
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, timeout=2.0):
|
||||
data = None if body is None else json.dumps(body, ensure_ascii=False).encode()
|
||||
head = {"Accept": "application/json"}
|
||||
if data is not None:
|
||||
head["Content-Type"] = "application/json"
|
||||
head.update(headers or {})
|
||||
request = urllib.request.Request(
|
||||
base_url().rstrip("/") + path, data=data, headers=head, method=method
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
payload = json.loads(response.read() or b"null")
|
||||
return response.status, response.headers.get("X-Instance-Id", ""), payload
|
||||
except urllib.error.HTTPError as error:
|
||||
try:
|
||||
payload = json.loads(error.read() or b"null")
|
||||
except (OSError, ValueError):
|
||||
payload = None
|
||||
return error.code, error.headers.get("X-Instance-Id", ""), payload
|
||||
except (OSError, ValueError):
|
||||
return 0, "", None
|
||||
|
||||
|
||||
def emit(report, out=None):
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if out:
|
||||
Path(out).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(out).write_text(text + "\n")
|
||||
print(text)
|
||||
|
||||
|
||||
def created(result, what):
|
||||
if result[0] != 201:
|
||||
raise SystemExit(f"{what} failed: HTTP {result[0]}")
|
||||
return result[2]
|
||||
|
||||
|
||||
def actor(label):
|
||||
username = f"p_{label}_{uuid.uuid4().hex[:12]}"
|
||||
password = "Probe-" + uuid.uuid4().hex
|
||||
body = {"username": username, "display_name": "probe " + label, "password": password}
|
||||
user = created(call("POST", "/api/v1/users", body, timeout=10), "register")
|
||||
basic = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
login = call(
|
||||
"POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic}, timeout=10
|
||||
)
|
||||
return {
|
||||
"id": user["id"],
|
||||
"auth": {"Authorization": "Bearer " + created(login, "login")["token"]},
|
||||
}
|
||||
|
||||
|
||||
def chat_of(owner, other):
|
||||
body = {"title": "probe", "member_ids": [owner["id"], other["id"]]}
|
||||
return created(call("POST", "/api/v1/chats", body, owner["auth"], timeout=10), "chat")["id"]
|
||||
|
||||
|
||||
def send(owner, chat, text, key):
|
||||
headers = dict(owner["auth"], **{"Idempotency-Key": key})
|
||||
return call("POST", f"/api/v1/chats/{chat}/messages", {"text": text}, headers)
|
||||
|
||||
|
||||
def lb_rows(backend="api"):
|
||||
try:
|
||||
with urllib.request.urlopen(stats_url(), timeout=2) as response:
|
||||
lines = response.read().decode().splitlines()
|
||||
except OSError:
|
||||
return None
|
||||
header = lines[0].lstrip("# ").split(",")
|
||||
rows = [dict(zip(header, line.split(","))) for line in lines[1:] if line]
|
||||
return [r for r in rows if r["pxname"] == backend]
|
||||
|
||||
|
||||
def lb_up():
|
||||
rows = lb_rows()
|
||||
if rows is None:
|
||||
return None
|
||||
return sum(1 for r in rows if r["svname"] != "BACKEND" and r["status"].startswith("UP"))
|
||||
|
||||
|
||||
def lb_counters():
|
||||
row = next((r for r in lb_rows() or [] if r["svname"] == "BACKEND"), {})
|
||||
return {name: int(row.get(name) or 0) for name in COUNTERS}
|
||||
|
||||
|
||||
def run_k6(out, env, on_start=None):
|
||||
Path(out).mkdir(parents=True, exist_ok=True)
|
||||
started = []
|
||||
process = subprocess.Popen(
|
||||
[str(ROOT / "scripts/k6.sh"), str(out)],
|
||||
env=dict(os.environ, **env),
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
with (Path(out) / "k6.txt").open("w") as log:
|
||||
for line in process.stdout:
|
||||
log.write(line)
|
||||
if not started and "LOAD-START" in line:
|
||||
started.append(time.time())
|
||||
if on_start:
|
||||
on_start()
|
||||
return process.wait(), started[0] if started else None
|
||||
|
||||
|
||||
def k6_metrics(path, duration):
|
||||
metrics = json.loads(Path(path).read_text())["metrics"]
|
||||
|
||||
def value(name, field):
|
||||
return metrics.get(name + "{scenario:measure}", {}).get("values", {}).get(field, 0.0)
|
||||
|
||||
count = value("http_reqs", "count")
|
||||
return {
|
||||
"requests": int(count),
|
||||
"rps": round(count / duration, 2),
|
||||
"ok_rps": round(count * (1 - value("http_req_failed", "rate")) / duration, 2),
|
||||
"failed_ratio": round(value("http_req_failed", "rate"), 5),
|
||||
"dropped_iterations": int(value("dropped_iterations", "count")),
|
||||
"p50_ms": round(value("http_req_duration", "med"), 2),
|
||||
"p95_ms": round(value("http_req_duration", "p(95)"), 2),
|
||||
"p99_ms": round(value("http_req_duration", "p(99)"), 2),
|
||||
}
|
||||
|
||||
|
||||
def race(alice, chat, parallel):
|
||||
key, text = uuid.uuid4().hex, "same key " + uuid.uuid4().hex
|
||||
barrier, results = threading.Barrier(parallel), []
|
||||
|
||||
def worker():
|
||||
barrier.wait()
|
||||
results.append(send(alice, chat, text, key))
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(parallel)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
bodies = [r[2] for r in results if r[0] == 201]
|
||||
identical = bool(bodies) and all(b == bodies[0] for b in bodies)
|
||||
return text, results, identical, send(alice, chat, text + " changed", key)[0]
|
||||
|
||||
|
||||
def check(args):
|
||||
alice, bob = actor("alice"), actor("bob")
|
||||
chat = chat_of(alice, bob)
|
||||
seen = collections.Counter(
|
||||
call("GET", "/api/v1/users/me", headers=alice["auth"])[1] for _ in range(args.samples)
|
||||
)
|
||||
rounds = [race(alice, chat, args.parallel) for _ in range(min(args.rounds, 100))]
|
||||
page = call("GET", f"/api/v1/chats/{chat}/messages?limit=100", headers=bob["auth"])[2]
|
||||
copies = collections.Counter(m.get("text") for m in (page or {"items": []})["items"])
|
||||
statuses = collections.Counter(r[0] for _, results, _, _ in rounds for r in results)
|
||||
served = collections.Counter(r[1] for _, results, _, _ in rounds for r in results)
|
||||
same = {
|
||||
"rounds": len(rounds),
|
||||
"parallel": args.parallel,
|
||||
"statuses": dict(statuses),
|
||||
"instances": dict(served),
|
||||
"identical_bodies_rounds": sum(1 for _, _, identical, _ in rounds if identical),
|
||||
"single_copy_rounds": sum(1 for text, _, _, _ in rounds if copies[text] == 1),
|
||||
"conflict_rounds": sum(1 for _, _, _, other in rounds if other == 409),
|
||||
}
|
||||
passed = (
|
||||
len(seen) >= 2
|
||||
and statuses == {201: len(rounds) * args.parallel}
|
||||
and len(served) >= 2
|
||||
and same["identical_bodies_rounds"] == len(rounds)
|
||||
and same["single_copy_rounds"] == len(rounds)
|
||||
and same["conflict_rounds"] == len(rounds)
|
||||
)
|
||||
emit({"instances_one_token": dict(seen), "same_key": same, "pass": passed}, args.out)
|
||||
return 0 if passed else 1
|
||||
|
||||
|
||||
def output(*command):
|
||||
done = subprocess.run(command, cwd=str(ROOT), capture_output=True, text=True, check=False)
|
||||
return done.stdout + done.stderr
|
||||
|
||||
|
||||
def replicas():
|
||||
ids = output("docker", "compose", "ps", "-q", os.environ.get("API_SERVICE", "api")).split()
|
||||
form = "{{.Id}} {{.Config.Hostname}} {{range .NetworkSettings.Networks}}{{.IPAddress}} {{end}}"
|
||||
return [line.split() for line in output("docker", "inspect", "-f", form, *ids).splitlines()]
|
||||
|
||||
|
||||
def answered(container, request_id):
|
||||
for line in output("docker", "logs", container).splitlines():
|
||||
if request_id in line and "request.handled" in line:
|
||||
return json.loads(line).get("status")
|
||||
return None
|
||||
|
||||
|
||||
def lost(alice, bob, chat, kill, args):
|
||||
key, text = uuid.uuid4().hex, "lost " + uuid.uuid4().hex
|
||||
request_id = "lost-" + key[:12]
|
||||
lock = subprocess.Popen(
|
||||
PSQL, cwd=str(ROOT), stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True
|
||||
)
|
||||
lock.stdin.write(
|
||||
f"BEGIN;\nSELECT 'locked' FROM chats WHERE id = '{uuid.UUID(chat)}' FOR UPDATE;\n"
|
||||
f"SELECT pg_sleep({args.hold});\nCOMMIT;\n"
|
||||
)
|
||||
lock.stdin.flush()
|
||||
lock.stdout.readline()
|
||||
sent = time.time()
|
||||
headers = dict(alice["auth"], **{"Idempotency-Key": key, "X-Request-Id": request_id})
|
||||
path = f"/api/v1/chats/{chat}/messages"
|
||||
first = call("POST", path, {"text": text}, headers, args.timeout)[0]
|
||||
sql = "SELECT host(client_addr) FROM pg_stat_activity WHERE wait_event_type = 'Lock'"
|
||||
waiting = set(output(*PSQL, "-c", sql).split())
|
||||
holder = next((r for r in replicas() if waiting & set(r[2:])), [None, None])
|
||||
if kill and holder[0]:
|
||||
subprocess.call(["docker", "kill", holder[0]], stdout=subprocess.DEVNULL)
|
||||
lock.stdin.close()
|
||||
lock.wait()
|
||||
retried = time.time()
|
||||
attempts, (status, instance, body) = 1, send(alice, chat, text, key)
|
||||
while status != 201 and attempts < 20:
|
||||
time.sleep(0.2)
|
||||
attempts, (status, instance, body) = attempts + 1, send(alice, chat, text, key)
|
||||
page = call("GET", path + "?limit=100", headers=bob["auth"])[2] or {"items": []}
|
||||
copies = [m for m in page["items"] if m["text"] == text]
|
||||
stamp = copies[0]["created_at"].replace("Z", "+00:00") if copies else None
|
||||
report = {
|
||||
"variant": "kill" if kill else "timeout",
|
||||
"lost_attempt": {
|
||||
"status": first,
|
||||
"client_timeout_s": args.timeout,
|
||||
"chat_lock_held_s": args.hold,
|
||||
"replica": holder[1],
|
||||
"replica_killed": bool(kill and holder[0]),
|
||||
"replica_answered": answered(holder[0], request_id) if holder[0] else None,
|
||||
},
|
||||
"retry": {
|
||||
"after_s": round(retried - sent, 3),
|
||||
"status": status,
|
||||
"attempts": attempts,
|
||||
"replica": instance,
|
||||
},
|
||||
"copies_in_history": len(copies),
|
||||
"same_message": bool(copies) and copies[0]["id"] == (body or {}).get("id"),
|
||||
"written_by": None
|
||||
if stamp is None
|
||||
else ("lost attempt" if datetime.fromisoformat(stamp).timestamp() < retried else "retry"),
|
||||
}
|
||||
if kill and holder[0]:
|
||||
subprocess.call(
|
||||
[str(ROOT / "scripts/restore.sh")], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
|
||||
)
|
||||
report["pass"] = (
|
||||
first == 0
|
||||
and holder[0] is not None
|
||||
and status == 201
|
||||
and report["copies_in_history"] == 1
|
||||
and report["same_message"]
|
||||
and (kill or report["lost_attempt"]["replica_answered"] == 201)
|
||||
)
|
||||
return report
|
||||
|
||||
|
||||
def retry(args):
|
||||
alice, bob = actor("alice"), actor("bob")
|
||||
chat = chat_of(alice, bob)
|
||||
variants = [lost(alice, bob, chat, kill, args) for kill in (False, True)]
|
||||
passed = all(v["pass"] for v in variants)
|
||||
emit({"variants": variants, "pass": passed}, args.out)
|
||||
return 0 if passed else 1
|
||||
|
||||
|
||||
def record(stop, alice, chat):
|
||||
probes, trace, confirmed = [], [], []
|
||||
|
||||
def prober():
|
||||
key = uuid.uuid4().hex
|
||||
while not stop.is_set():
|
||||
started = time.time()
|
||||
status, instance, body = send(alice, chat, "probe " + key, key)
|
||||
probes.append((started, status, round(1000 * (time.time() - started), 1), instance))
|
||||
if status == 201:
|
||||
confirmed.append(body)
|
||||
key = uuid.uuid4().hex
|
||||
time.sleep(0.1)
|
||||
|
||||
def poller():
|
||||
while not stop.is_set():
|
||||
trace.append((time.time(), lb_up()))
|
||||
time.sleep(0.1)
|
||||
|
||||
threads = [threading.Thread(target=t, daemon=True) for t in (prober, poller)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
return probes, trace, threads, confirmed
|
||||
|
||||
|
||||
def history_check(reader, chat, confirmed):
|
||||
items, cursors = [], set()
|
||||
cursor = None
|
||||
for _ in range(len(confirmed) // 100 + 2):
|
||||
path = f"/api/v1/chats/{chat}/messages?limit=100"
|
||||
if cursor:
|
||||
path += "&cursor=" + urllib.parse.quote(cursor, safe="")
|
||||
status, _, page = call("GET", path, headers=reader["auth"])
|
||||
if status != 200 or not isinstance(page, dict):
|
||||
break
|
||||
items.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
same = sorted(items, key=lambda m: m["id"]) == sorted(confirmed, key=lambda m: m["id"])
|
||||
return {
|
||||
"confirmed": len(confirmed),
|
||||
"stored": len(items),
|
||||
"exact_match": bool(confirmed) and same,
|
||||
"unique": len({m["id"] for m in items}) == len(items),
|
||||
}
|
||||
if cursor in cursors:
|
||||
break
|
||||
cursors.add(cursor)
|
||||
return {
|
||||
"confirmed": len(confirmed),
|
||||
"stored": len(items),
|
||||
"exact_match": False,
|
||||
"unique": False,
|
||||
}
|
||||
|
||||
|
||||
def write_csv(path, header, rows):
|
||||
with path.open("w") as handle:
|
||||
handle.write(header + "\n")
|
||||
handle.writelines(",".join(str(v) for v in row) + "\n" for row in rows)
|
||||
|
||||
|
||||
def summarize(args, probes, trace, action, expected):
|
||||
t0, end = action["start"], action["end"]
|
||||
label = args.label or os.environ.get("TARGET_INSTANCE_ID", "action")
|
||||
failures = [t - t0 for t, s, _, _ in probes if s != 201 and t >= t0]
|
||||
successes = [(t, t + ms / 1000 - t0) for t, s, ms, _ in probes if s == 201 and t >= t0]
|
||||
recovery = (
|
||||
next((end for t, end in successes if t - t0 > failures[-1]), None) if failures else 0.0
|
||||
)
|
||||
down = [t for t, up in trace if t >= t0 and up is not None and up < expected]
|
||||
back = [t for t, up in trace if down and t > down[0] and up is not None and up >= expected]
|
||||
outage = [t for t in down if not back or t < back[0]] or [end]
|
||||
served = [(t, i) for t, s, _, i in probes if s == 201]
|
||||
before = collections.Counter(i for t, i in served if t < t0)
|
||||
during = collections.Counter(i for t, i in served if outage[0] <= t <= outage[-1])
|
||||
after = collections.Counter(i for t, i in served if t > end)
|
||||
return {
|
||||
"label": label,
|
||||
"action": args.command,
|
||||
"action_exit": action["exit"],
|
||||
"action_seconds": round(end - t0, 3),
|
||||
"action_finished_before_load_end": end < action["load_end"],
|
||||
"lb_up_before": expected,
|
||||
"lb_up_min": min((up for _, up in trace if up is not None), default=None),
|
||||
"lb_samples_missing": sum(up is None for _, up in trace),
|
||||
"detection_seconds": round(down[0] - t0, 3) if down else None,
|
||||
"rejoin_seconds": round(back[0] - t0, 3) if back else None,
|
||||
"probe": {
|
||||
"attempts": len(probes),
|
||||
"failed_attempts": sum(1 for _, s, _, _ in probes if s != 201),
|
||||
"first_failure_s": round(failures[0], 3) if failures else None,
|
||||
"first_success_s": round(successes[0][1], 3) if successes else None,
|
||||
"recovery_s": round(recovery, 3) if recovery is not None else None,
|
||||
"instances_before": dict(before),
|
||||
"instances_during_outage": dict(during),
|
||||
"instances_after": dict(after),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def verdict(args, result):
|
||||
probe, k6 = result["probe"], result["k6"]
|
||||
checks = {
|
||||
"action_ok": result["action_exit"] == 0 and result["action_finished_before_load_end"],
|
||||
"load_errors_ok": k6["exit"] == 0 and k6["failed_ratio"] <= args.max_failed_ratio,
|
||||
"load_delivered": k6["requests"] > 0 and k6["dropped_iterations"] == 0,
|
||||
"lb_observed": result["lb_up_before"] >= 2 and result["lb_samples_missing"] == 0,
|
||||
"write_recovery_ok": all(
|
||||
probe[k] is not None and probe[k] <= args.max_recovery
|
||||
for k in ("first_success_s", "recovery_s")
|
||||
),
|
||||
"history_preserved": result["history"]["exact_match"] and result["history"]["unique"],
|
||||
}
|
||||
if args.expect == "dip":
|
||||
checks["detected"] = result["detection_seconds"] is not None
|
||||
checks["target_excluded"] = probe["instances_during_outage"].get(result["label"], 0) == 0
|
||||
checks["rejoined"] = result["rejoin_seconds"] is not None and bool(
|
||||
probe["instances_after"].get(result["label"])
|
||||
)
|
||||
if args.expect == "replace":
|
||||
checks["capacity_kept"] = (result["lb_up_min"] or 0) >= result["lb_up_before"]
|
||||
old, new = set(probe["instances_before"]), set(probe["instances_after"])
|
||||
checks["all_replaced"] = bool(new) and not old & new
|
||||
return checks
|
||||
|
||||
|
||||
def load(args):
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
expected = lb_up() or 0
|
||||
alice, bob = actor("alice"), actor("bob")
|
||||
stop, action = threading.Event(), {}
|
||||
chat = chat_of(alice, bob)
|
||||
probes, trace, threads, confirmed = record(stop, alice, chat)
|
||||
|
||||
def act():
|
||||
time.sleep(args.warmup + args.lead)
|
||||
action["start"] = time.time()
|
||||
with (out / "action.txt").open("w") as log:
|
||||
action["exit"] = subprocess.call(
|
||||
args.command, cwd=str(ROOT), stdout=log, stderr=subprocess.STDOUT
|
||||
)
|
||||
action["end"] = time.time()
|
||||
|
||||
runner = threading.Thread(target=act)
|
||||
env = {"RATE": str(args.rate), "WARMUP": str(args.warmup), "DURATION": str(args.duration)}
|
||||
counters = lb_counters()
|
||||
code, load_start = run_k6(out / "k6", env, runner.start)
|
||||
if load_start is not None:
|
||||
runner.join()
|
||||
action["load_end"] = load_start + args.warmup + args.duration
|
||||
stop.set()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
if "start" not in action:
|
||||
raise SystemExit(f"k6 failed before the action (exit {code}), see {out / 'k6/k6.txt'}")
|
||||
t0 = action["start"]
|
||||
write_csv(
|
||||
out / "probe.csv",
|
||||
"t_rel_s,status,latency_ms,instance",
|
||||
((round(t - t0, 3), *r) for t, *r in probes),
|
||||
)
|
||||
write_csv(out / "lb_up.csv", "t_rel_s,up", ((round(t - t0, 3), up) for t, up in trace))
|
||||
result = summarize(args, probes, trace, action, expected)
|
||||
result["history"] = history_check(bob, chat, confirmed)
|
||||
result["lb_counters"] = {k: v - counters[k] for k, v in lb_counters().items()}
|
||||
result["k6"] = dict(
|
||||
k6_metrics(out / "k6/summary.json", args.duration), exit=code, rate=args.rate
|
||||
)
|
||||
result["checks"] = verdict(args, result)
|
||||
result["pass"] = all(result["checks"].values())
|
||||
(out / "result.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
return 0 if result["pass"] else 1
|
||||
|
||||
|
||||
def detect(args):
|
||||
before = lb_up() or 0
|
||||
until = before - 1 if args.until is None else args.until
|
||||
started = time.time()
|
||||
process = subprocess.Popen(args.command, cwd=str(ROOT))
|
||||
detected = acted = None
|
||||
missing = 0
|
||||
while time.time() - started < args.timeout and (detected is None or acted is None):
|
||||
if acted is None and process.poll() is not None:
|
||||
acted = time.time() - started
|
||||
up = lb_up()
|
||||
missing += up is None
|
||||
if detected is None and up is not None and up <= until:
|
||||
detected = time.time() - started
|
||||
time.sleep(0.05)
|
||||
code = process.wait()
|
||||
acted = time.time() - started if acted is None else acted
|
||||
status, instance, payload = call("GET", "/health/live")
|
||||
restored = None
|
||||
if args.restore:
|
||||
begun = time.time()
|
||||
subprocess.call(["sh", "-c", args.restore], cwd=str(ROOT))
|
||||
while (lb_up() or 0) < before and time.time() - begun < 3 * args.timeout:
|
||||
time.sleep(0.1)
|
||||
restored = round(time.time() - begun, 3) if (lb_up() or 0) >= before else None
|
||||
checks = {
|
||||
"action_ok": code == 0,
|
||||
"lb_observed": before >= 2 and missing == 0,
|
||||
"detected_in_time": detected is not None and detected <= args.max + args.slack,
|
||||
"lb_answer_ok": status == args.lb_status,
|
||||
}
|
||||
if args.within_action:
|
||||
checks["excluded_before_action_end"] = detected is not None and detected < acted
|
||||
if args.restore:
|
||||
checks["restored"] = restored is not None
|
||||
report = {
|
||||
"action": args.command,
|
||||
"action_exit": code,
|
||||
"action_seconds": round(acted, 3),
|
||||
"lb_up_before": before,
|
||||
"lb_samples_missing": missing,
|
||||
"lb_up_counted_as_detected": until,
|
||||
"detection_seconds": None if detected is None else round(detected, 3),
|
||||
"declared_max_seconds": args.max,
|
||||
"measurement_slack_seconds": args.slack,
|
||||
"lb_answer_after_detection": {
|
||||
"path": "/health/live",
|
||||
"status": status,
|
||||
"x_instance_id_present": bool(instance),
|
||||
"error_code": ((payload or {}).get("error") or {}).get("code"),
|
||||
},
|
||||
"restore": args.restore,
|
||||
"restore_seconds": restored,
|
||||
"lb_up_after_restore": lb_up(),
|
||||
"checks": checks,
|
||||
"pass": all(checks.values()),
|
||||
}
|
||||
emit(report, args.out)
|
||||
return 0 if report["pass"] else 1
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="LB probes over the public HTTP contract")
|
||||
sub = parser.add_subparsers(dest="mode", required=True)
|
||||
one = sub.add_parser("check", help="instances behind one token and same-key races")
|
||||
one.add_argument("--samples", type=int, default=40)
|
||||
one.add_argument("--parallel", type=int, default=8)
|
||||
one.add_argument("--rounds", type=int, default=1)
|
||||
one.add_argument("--out", help="JSON file, written only after a complete report")
|
||||
under = sub.add_parser("load", help="run an action under k6 load and measure recovery")
|
||||
under.add_argument("--out", required=True)
|
||||
under.add_argument("--label")
|
||||
under.add_argument("--expect", choices=("dip", "replace"), default="dip")
|
||||
under.add_argument("--rate", type=int, default=int(os.environ.get("RATE", "50")))
|
||||
under.add_argument("--warmup", type=int, default=10)
|
||||
under.add_argument("--duration", type=int, default=int(os.environ.get("DURATION", "60")))
|
||||
under.add_argument("--lead", type=int, default=15)
|
||||
under.add_argument("--max-failed-ratio", type=float, default=0.01)
|
||||
under.add_argument("--max-recovery", type=float, default=10.0)
|
||||
under.add_argument("command", nargs=argparse.REMAINDER)
|
||||
again = sub.add_parser("retry", help="retry a write whose answer was lost, same key")
|
||||
again.add_argument("--hold", type=float, default=1.5, help="chat row lock, s (< lock_timeout)")
|
||||
again.add_argument("--timeout", type=float, default=0.5, help="first attempt timeout, s")
|
||||
again.add_argument("--out", help="JSON file, written only after a complete report")
|
||||
watch = sub.add_parser("detect", help="time until the LB takes replicas out of rotation")
|
||||
watch.add_argument("--max", type=float, required=True, help="declared worst detection, s")
|
||||
watch.add_argument("--slack", type=float, default=0.25, help="docker CLI and polling, s")
|
||||
watch.add_argument("--until", type=int, help="UP servers counted as detected")
|
||||
watch.add_argument("--within-action", action="store_true")
|
||||
watch.add_argument("--lb-status", type=int, default=200)
|
||||
watch.add_argument("--restore", help="shell command that brings replicas back")
|
||||
watch.add_argument("--timeout", type=float, default=20)
|
||||
watch.add_argument("--out", help="JSON file, written only after a complete report")
|
||||
watch.add_argument("command", nargs=argparse.REMAINDER)
|
||||
args = parser.parse_args()
|
||||
if args.mode == "check":
|
||||
return check(args)
|
||||
if args.mode == "retry":
|
||||
return retry(args)
|
||||
args.command = [c for c in args.command if c != "--"]
|
||||
if not args.command:
|
||||
parser.error(f"{args.mode} needs an action command after --")
|
||||
return load(args) if args.mode == "load" else detect(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+37
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
kind="${1:?usage: reconcile-inject.sh orphan|missing|corrupt|bitflip|stale-pending|pending-object|multipart [count]}"
|
||||
count="${2:-1}"
|
||||
age="${INJECT_AGE_SECONDS:-7200}"
|
||||
prefix="${S3_PREFIX:-attachments/}"
|
||||
sql() { docker compose exec -T postgres psql -v ON_ERROR_STOP=1 -qAt -F ' ' -U "${PGUSER:-messenger}" -d "${PGDATABASE:-messenger}" -c "$1"; }
|
||||
s3() { docker compose run --rm --no-deps -T -e ROWS="$1" s3-cli sh -c "$2"; }
|
||||
ready() { sql "SELECT id, object_key, size_bytes FROM attachments WHERE status = 'ready' ${INJECT_IDS:+AND id = ANY('{$INJECT_IDS}'::uuid[])} ORDER BY random() LIMIT $count"; }
|
||||
pending() {
|
||||
sql "INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, width, height, object_key, status, created_at, updated_at)
|
||||
SELECT g.id, s.chat_id, s.owner_id, 'injected.png', 'image/png', 2048, repeat('0', 64), 1, 1, '$prefix' || g.id, 'pending',
|
||||
clock_timestamp() - make_interval(secs => $age), clock_timestamp() - make_interval(secs => $age)
|
||||
FROM (SELECT chat_id, owner_id FROM attachments ORDER BY created_at LIMIT 1) s,
|
||||
(SELECT gen_random_uuid() AS id FROM generate_series(1, $count)) g
|
||||
RETURNING id, object_key"
|
||||
}
|
||||
fresh() { sql "SELECT g, '$prefix' || g FROM (SELECT gen_random_uuid() AS g FROM generate_series(1, $count)) s"; }
|
||||
put_random='printf "%s\n" "$ROWS" | while read -r id key size; do [ -n "$key" ] || continue; head -c "${size:-2048}" /dev/urandom | rc pipe "root/$S3_BUCKET/$key" >/dev/null; echo "$id $key"; done'
|
||||
case "$kind" in
|
||||
orphan) rows=$(fresh); s3 "$rows" "$put_random" | sed "s/^/orphan /" ;;
|
||||
missing) rows=$(ready); s3 "$rows" 'printf "%s\n" "$ROWS" | while read -r id key size; do [ -n "$key" ] || continue; rc object remove --force "root/$S3_BUCKET/$key" >/dev/null; echo "$id $key"; done' | sed "s/^/missing /" ;;
|
||||
corrupt) rows=$(ready | awk '{print $1, $2, int($3 / 2) + 1}'); s3 "$rows" "$put_random" | sed "s/^/corrupt /" ;;
|
||||
bitflip) rows=$(ready); s3 "$rows" "$put_random" | sed "s/^/bitflip /" ;;
|
||||
stale-pending) pending | sed "s/^/stale-pending /" ;;
|
||||
pending-object) rows=$(pending); s3 "$rows" "$put_random" | sed "s/^/pending-object /" ;;
|
||||
multipart)
|
||||
fresh | while read -r _ key; do
|
||||
docker compose exec -T -e KEY="$key" -e S3_BUCKET="${S3_BUCKET:-messenger-attachments}" s3 sh -c 'u="http://127.0.0.1:9000/$S3_BUCKET/$KEY"; a="$(cat /run/secrets/s3_root_user):$(cat /run/secrets/s3_root_password)"; s="aws:amz:${RUSTFS_REGION:-us-east-1}:s3"
|
||||
upload=$(curl -fsS --aws-sigv4 "$s" --user "$a" -X POST "$u?uploads" | sed -n "s:.*<UploadId>\(.*\)</UploadId>.*:\1:p")
|
||||
head -c 4096 /dev/urandom | curl -fsS --aws-sigv4 "$s" --user "$a" -X PUT --data-binary @- "$u?partNumber=1&uploadId=$upload" -o /dev/null' </dev/null
|
||||
echo "multipart - $key"
|
||||
done
|
||||
;;
|
||||
*) echo "unknown kind: $kind" >&2; exit 2 ;;
|
||||
esac
|
||||
Executable
+199
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SQL = (
|
||||
"SELECT a.id, a.object_key, a.status, a.size_bytes, a.sha256,"
|
||||
" floor(extract(epoch FROM clock_timestamp() - a.created_at))::bigint,"
|
||||
" EXISTS (SELECT 1 FROM message_attachments m WHERE m.attachment_id = a.id),"
|
||||
" (to_jsonb(a) ->> 'quarantined_at') IS NOT NULL"
|
||||
" FROM attachments a ORDER BY a.object_key"
|
||||
)
|
||||
HASH = (
|
||||
'while read -r k; do printf "%s %s\\n" "$k" '
|
||||
'"$(rc object show "root/$S3_BUCKET/$k" | sha256sum | cut -c1-64)"; done'
|
||||
)
|
||||
CLASSES = (
|
||||
"orphan_stale",
|
||||
"orphan_fresh",
|
||||
"missing_referenced",
|
||||
"missing_unreferenced",
|
||||
"size_mismatch",
|
||||
"sha_mismatch",
|
||||
"pending_stale_with_object",
|
||||
"pending_stale_without_object",
|
||||
"pending_fresh",
|
||||
"quarantined",
|
||||
"incomplete_stale",
|
||||
"incomplete_fresh",
|
||||
"lost_ready",
|
||||
)
|
||||
TOLERATED = {"orphan_fresh", "pending_fresh", "incomplete_fresh", "quarantined"}
|
||||
BROKEN = (
|
||||
"missing_referenced",
|
||||
"missing_unreferenced",
|
||||
"size_mismatch",
|
||||
"sha_mismatch",
|
||||
"quarantined",
|
||||
)
|
||||
|
||||
|
||||
def timed(cmd, stdin=None):
|
||||
started = time.monotonic()
|
||||
out = subprocess.run(cmd, cwd=ROOT, input=stdin, capture_output=True, text=True, check=False)
|
||||
if out.returncode:
|
||||
raise SystemExit(f"command failed: {' '.join(cmd[:6])}\n{out.stderr[-500:]}")
|
||||
return out.stdout, round(time.monotonic() - started, 3)
|
||||
|
||||
|
||||
def s3(*args, stdin=None):
|
||||
return timed(["docker", "compose", "run", "--rm", "--no-deps", "-T", "s3-cli", *args], stdin)
|
||||
|
||||
|
||||
def age(stamp, now):
|
||||
return now - dt.datetime.fromisoformat(stamp[:19] + "+00:00").timestamp()
|
||||
|
||||
|
||||
def load(bucket, prefix, deep):
|
||||
listing, list_seconds = s3("object", "list", "--recursive", "--json", f"root/{bucket}/{prefix}")
|
||||
uploads, uploads_seconds = s3(
|
||||
"object", "list", "--incomplete", "--recursive", "--json", f"root/{bucket}"
|
||||
)
|
||||
user, db = os.environ.get("PGUSER", "messenger"), os.environ.get("PGDATABASE", "messenger")
|
||||
psql = ["docker", "compose", "exec", "-T", "postgres", "psql", "-v", "ON_ERROR_STOP=1", "-qAt"]
|
||||
rows_raw, pg_seconds = timed([*psql, "-F", "\t", "-U", user, "-d", db, "-c", SQL])
|
||||
objects = {}
|
||||
for item in json.loads(listing).get("items", []):
|
||||
key = item["key"] if item["key"].startswith(prefix) else prefix + item["key"]
|
||||
objects[key] = item
|
||||
rows = {}
|
||||
for line in rows_raw.splitlines():
|
||||
rid, key, status, size, sha, row_age, referenced, quarantined = line.split("\t")
|
||||
rows[key] = {
|
||||
"id": rid,
|
||||
"status": status,
|
||||
"size": int(size),
|
||||
"sha256": sha,
|
||||
"age": int(row_age),
|
||||
"referenced": referenced == "t",
|
||||
"quarantined": quarantined == "t",
|
||||
}
|
||||
hashes, deep_seconds = {}, 0.0
|
||||
if deep:
|
||||
present = "".join(
|
||||
f"{k}\n" for k, r in rows.items() if r["status"] == "ready" and k in objects
|
||||
)
|
||||
out, deep_seconds = s3("sh", "-c", HASH, stdin=present)
|
||||
hashes = dict(line.split(" ", 1) for line in out.splitlines() if " " in line)
|
||||
seconds = {
|
||||
"s3_list": list_seconds,
|
||||
"s3_incomplete": uploads_seconds,
|
||||
"pg_query": pg_seconds,
|
||||
"deep_hash": deep_seconds,
|
||||
}
|
||||
return objects, rows, hashes, json.loads(uploads).get("data", {}).get("items", []), seconds
|
||||
|
||||
|
||||
def row_class(key, row, objects, hashes, grace):
|
||||
if row["quarantined"]:
|
||||
return "quarantined"
|
||||
if row["status"] == "pending":
|
||||
stale = "pending_stale_with_object" if key in objects else "pending_stale_without_object"
|
||||
return "pending_fresh" if row["age"] <= grace else stale
|
||||
if key not in objects:
|
||||
return "missing_referenced" if row["referenced"] else "missing_unreferenced"
|
||||
if objects[key]["size_bytes"] != row["size"]:
|
||||
return "size_mismatch"
|
||||
return "sha_mismatch" if hashes and hashes.get(key) != row["sha256"] else None
|
||||
|
||||
|
||||
def classify(objects, rows, hashes, uploads, grace):
|
||||
now = time.time()
|
||||
classes = {name: [] for name in CLASSES}
|
||||
for key, item in objects.items():
|
||||
if key not in rows:
|
||||
classes[
|
||||
"orphan_stale" if age(item["last_modified"], now) > grace else "orphan_fresh"
|
||||
].append(key)
|
||||
for key, row in rows.items():
|
||||
name = row_class(key, row, objects, hashes, grace)
|
||||
if name:
|
||||
classes[name].append(key if name.startswith("orphan") else row["id"])
|
||||
for item in uploads:
|
||||
classes[
|
||||
"incomplete_stale" if age(item["initiated"], now) > grace else "incomplete_fresh"
|
||||
].append(item["key"])
|
||||
return classes
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(
|
||||
description="Independent PG <-> S3 invariant check for lab4 attachments"
|
||||
)
|
||||
p.add_argument(
|
||||
"--grace", type=int, default=int(os.environ.get("RECONCILE_GRACE_SECONDS", "3600"))
|
||||
)
|
||||
p.add_argument(
|
||||
"--deep", action="store_true", help="stream every present object and compare sha256"
|
||||
)
|
||||
p.add_argument(
|
||||
"--save-ready", metavar="FILE", help="store ids and sha256 of healthy ready attachments"
|
||||
)
|
||||
p.add_argument(
|
||||
"--expect-ready",
|
||||
metavar="FILE",
|
||||
help="fail if any attachment from FILE is no longer healthy",
|
||||
)
|
||||
p.add_argument("--limit", type=int, default=20, help="max ids per class in the report")
|
||||
p.add_argument("--output", metavar="FILE")
|
||||
args = p.parse_args()
|
||||
started = time.monotonic()
|
||||
prefix = os.environ.get("S3_PREFIX", "attachments/")
|
||||
objects, rows, hashes, uploads, seconds = load(
|
||||
os.environ.get("S3_BUCKET", "messenger-attachments"), prefix, args.deep
|
||||
)
|
||||
classes = classify(objects, rows, hashes, uploads, args.grace)
|
||||
bad = {i for c in BROKEN for i in classes[c]}
|
||||
healthy = {
|
||||
r["id"]: r["sha256"]
|
||||
for k, r in rows.items()
|
||||
if r["status"] == "ready" and k in objects and r["id"] not in bad
|
||||
}
|
||||
if args.expect_ready:
|
||||
expected = json.loads(Path(args.expect_ready).read_text())
|
||||
classes["lost_ready"] = sorted(i for i, sha in expected.items() if healthy.get(i) != sha)
|
||||
if args.save_ready:
|
||||
Path(args.save_ready).write_text(json.dumps(healthy, sort_keys=True))
|
||||
violations = [c for c in CLASSES if classes[c] and c not in TOLERATED]
|
||||
seconds["total"] = round(time.monotonic() - started, 3)
|
||||
report = {
|
||||
"checked_at": dt.datetime.now(dt.timezone.utc)
|
||||
.isoformat(timespec="seconds")
|
||||
.replace("+00:00", "Z"),
|
||||
"grace_seconds": args.grace,
|
||||
"deep": args.deep,
|
||||
"objects": len(objects),
|
||||
"rows": len(rows),
|
||||
"ready_healthy": len(healthy),
|
||||
"counts": {c: len(v) for c, v in classes.items()},
|
||||
"samples": {c: sorted(v)[: args.limit] for c, v in classes.items() if v},
|
||||
"seconds": seconds,
|
||||
"violations": violations,
|
||||
"ok": not violations,
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=2)
|
||||
if args.output:
|
||||
Path(args.output).write_text(text + "\n")
|
||||
print(text)
|
||||
sys.exit(0 if report["ok"] else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,823 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
client = __import__("client")
|
||||
FIXTURE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
GRACE = 60
|
||||
FLAGS = ("--grace", str(GRACE), "--skew", "0")
|
||||
INTENT_AGE = 300
|
||||
LOCK_KEY = 20260004
|
||||
FIXABLE = ("orphan_stale", "missing", "size_mismatch", "sha_mismatch", "pending_stale")
|
||||
USER_HZ = 100
|
||||
BUSY = (0, 1, 2, 5, 6, 7)
|
||||
|
||||
|
||||
def run(cmd, env=None, stdin=None):
|
||||
started = time.monotonic()
|
||||
done = subprocess.run(
|
||||
cmd,
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
check=False,
|
||||
env=dict(os.environ, **(env or {})),
|
||||
)
|
||||
out, err = done.stdout.decode(errors="replace"), done.stderr.decode(errors="replace")
|
||||
return done.returncode, out, err, round(time.monotonic() - started, 3)
|
||||
|
||||
|
||||
def must(cmd, env=None, stdin=None):
|
||||
code, out, err, _ = run(cmd, env, stdin)
|
||||
if code:
|
||||
raise SystemExit(f"failed: {' '.join(cmd[:7])}\n{err[-800:]}")
|
||||
return out
|
||||
|
||||
|
||||
def compose(*args, env=None, stdin=None):
|
||||
return must(["docker", "compose", *args], env, stdin)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-qAt",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-c",
|
||||
sql,
|
||||
).strip()
|
||||
|
||||
|
||||
def reconcile(*flags, env=None):
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "-T", "reconciler", *flags]
|
||||
code, out, err, wall = run(cmd, env)
|
||||
if code not in (0, 1) or not out.strip():
|
||||
raise SystemExit(f"reconciler failed ({code}):\n{err[-800:]}")
|
||||
report = json.loads(out)
|
||||
audit = [json.loads(line) for line in err.splitlines() if '"audit.' in line]
|
||||
report.update(exit_code=code, wall_seconds=wall, audit=audit)
|
||||
return report
|
||||
|
||||
|
||||
def oracle(*flags):
|
||||
code, out, err, _ = run([sys.executable, "scripts/reconcile_check.py", *flags])
|
||||
if not out.strip():
|
||||
raise SystemExit(f"reconcile_check failed ({code}):\n{err[-800:]}")
|
||||
return json.loads(out)
|
||||
|
||||
|
||||
def inject(kind, count, ids=(), age=None):
|
||||
env = {"INJECT_IDS": ",".join(ids)} if ids else {}
|
||||
if age is not None:
|
||||
env["INJECT_AGE_SECONDS"] = str(age)
|
||||
out = must(["sh", "scripts/reconcile-inject.sh", kind, str(count)], env)
|
||||
return [line.split()[1] for line in out.splitlines() if line.strip()]
|
||||
|
||||
|
||||
def head():
|
||||
return must(["git", "rev-parse", "HEAD"]).strip()
|
||||
|
||||
|
||||
def evidence_root():
|
||||
return ROOT / os.environ.get("RECONCILE_EVIDENCE_DIR", "evidence/reconcile")
|
||||
|
||||
|
||||
def save(name, data, *, stamp=True):
|
||||
path = evidence_root() / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
stamped = {"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "commit": head(), **data}
|
||||
path.write_text(json.dumps(stamped if stamp else data, ensure_ascii=False, indent=2) + "\n")
|
||||
return path
|
||||
|
||||
|
||||
class Checks:
|
||||
def __init__(self):
|
||||
self.items = []
|
||||
|
||||
def __call__(self, name, ok, **detail):
|
||||
self.items.append(dict(name=name, ok=bool(ok), **detail))
|
||||
sys.stderr.write(("PASS " if ok else "FAIL ") + name + "\n")
|
||||
|
||||
@property
|
||||
def ok(self):
|
||||
return all(item["ok"] for item in self.items)
|
||||
|
||||
|
||||
def chunk(tag, data):
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data))
|
||||
|
||||
|
||||
def tiny_png():
|
||||
raw = b"".join(b"\x00" + os.urandom(24) for _ in range(8))
|
||||
header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", header)
|
||||
+ chunk(b"IDAT", zlib.compress(raw))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def pick(found, names):
|
||||
return {name: found.get(name, 0) for name in names}
|
||||
|
||||
|
||||
def faults(c, check, pre):
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
ids = [c.attachment(alice, chat)[0]["id"] for _ in range(18)]
|
||||
linked = ids[:6]
|
||||
for part in (linked[:3], linked[3:]):
|
||||
c.message(alice, chat, "", attachments=part)
|
||||
targets = {
|
||||
"missing": [linked[0], linked[1], ids[6]],
|
||||
"corrupt": [linked[2], ids[7], ids[8]],
|
||||
"bitflip": [linked[3], ids[9], ids[10]],
|
||||
}
|
||||
damaged = {i for group in targets.values() for i in group}
|
||||
ready = evidence_root() / "ready-before.json"
|
||||
oracle("--grace", str(GRACE), "--deep", "--save-ready", str(ready))
|
||||
untouched = {k: v for k, v in json.loads(ready.read_text()).items() if k not in damaged}
|
||||
save("ready-untouched.json", untouched, stamp=False)
|
||||
started = time.monotonic()
|
||||
injected = {
|
||||
"orphan_stale": inject("orphan", 3),
|
||||
"missing": inject("missing", 3, targets["missing"]),
|
||||
"size_mismatch": inject("corrupt", 3, targets["corrupt"]),
|
||||
"sha_mismatch": inject("bitflip", 3, targets["bitflip"]),
|
||||
"pending_stale": inject("stale-pending", 3, age=INTENT_AGE)
|
||||
+ inject("pending-object", 3, age=INTENT_AGE),
|
||||
}
|
||||
time.sleep(max(0.0, GRACE + 5 - (time.monotonic() - started)))
|
||||
injected["orphan_fresh"] = inject("orphan", 2)
|
||||
injected["pending_fresh"] = inject("stale-pending", 2, age=0)
|
||||
expected = {name: len(keys) for name, keys in injected.items()}
|
||||
expected.update(quarantined=pre["counts"]["quarantined"])
|
||||
before = oracle(
|
||||
"--grace", str(GRACE), "--deep", "--output", str(evidence_root() / "check-before.json")
|
||||
)
|
||||
dry = reconcile("--dry-run", "--deep", *FLAGS)
|
||||
save("dry-run.json", dry)
|
||||
after_dry = oracle("--grace", str(GRACE), "--deep")
|
||||
named = {k: sorted(s.rsplit("/", 1)[-1] for s in dry["samples"].get(k, [])) for k in injected}
|
||||
check(
|
||||
"dry-run находит каждый внедрённый класс, и найдено ровно внедрённое",
|
||||
pick(dry["found"], expected) == expected
|
||||
and named == {name: sorted(ids) for name, ids in injected.items()},
|
||||
expected=expected,
|
||||
found=dry["found"],
|
||||
)
|
||||
check(
|
||||
"dry-run ничего не меняет",
|
||||
not any(dry["fixed"].values())
|
||||
and after_dry["counts"] == before["counts"]
|
||||
and (after_dry["objects"], after_dry["rows"]) == (before["objects"], before["rows"]),
|
||||
objects=[before["objects"], after_dry["objects"]],
|
||||
rows=[before["rows"], after_dry["rows"]],
|
||||
)
|
||||
first = reconcile("--apply", "--deep", *FLAGS)
|
||||
save("apply-1.json", first)
|
||||
discarded = sorted(e["attachment_id"] for e in first["audit"] if e["reason"] == "reconcile")
|
||||
check(
|
||||
"apply исправляет ровно найденное dry-run, удаление намерений — в журнале аудита",
|
||||
pick(first["fixed"], FIXABLE) == pick(dry["found"], FIXABLE)
|
||||
and not first["errors"]
|
||||
and discarded == sorted(injected["pending_stale"]),
|
||||
dry_run=pick(dry["found"], FIXABLE),
|
||||
fixed=pick(first["fixed"], FIXABLE),
|
||||
audit_discarded=len(discarded),
|
||||
)
|
||||
second = reconcile("--apply", "--deep", *FLAGS)
|
||||
save("apply-2.json", second)
|
||||
check(
|
||||
"повторный apply — 0 действий",
|
||||
not any(second["fixed"].values()),
|
||||
fixed=second["fixed"],
|
||||
found=second["found"],
|
||||
)
|
||||
after = oracle(
|
||||
"--grace",
|
||||
str(GRACE),
|
||||
"--deep",
|
||||
"--expect-ready",
|
||||
str(evidence_root() / "ready-untouched.json"),
|
||||
"--output",
|
||||
str(evidence_root() / "check-after.json"),
|
||||
)
|
||||
tolerated = ("orphan_fresh", "pending_fresh")
|
||||
check(
|
||||
"независимая проверка после apply: нарушений нет, готовые не потеряны",
|
||||
after["ok"]
|
||||
and not after["counts"]["lost_ready"]
|
||||
and pick(after["counts"], tolerated) == pick(before["counts"], tolerated)
|
||||
and after["counts"]["quarantined"] == pre["counts"]["quarantined"] + 9,
|
||||
counts=after["counts"],
|
||||
)
|
||||
marks = dict(
|
||||
line.split("|") for line in psql("SELECT id, quarantine_reason FROM attachments").split()
|
||||
)
|
||||
links = psql("SELECT attachment_id FROM message_attachments").split()
|
||||
kept = {i: marks.get(i) for i in sorted(damaged)}
|
||||
check(
|
||||
"строки с расхождениями и ссылки сообщений сохранены",
|
||||
all(kept.values()) and sum(i in linked for i in links) == len(linked),
|
||||
quarantine=kept,
|
||||
message_links=sum(i in linked for i in links),
|
||||
)
|
||||
meta = c.call("GET", f"/api/v1/attachments/{linked[0]}", 200, actor=bob, schema="Attachment")
|
||||
blocked = c.call("GET", f"/api/v1/attachments/{linked[2]}/content", 404, actor=bob)
|
||||
intact = c.call("GET", f"/api/v1/attachments/{linked[4]}/content", 200, actor=bob)
|
||||
check(
|
||||
"карантин: метаданные 200, /content 404; нетронутое скачивается",
|
||||
meta["status"] == 200 and blocked["status"] == 404 and intact["bytes"] == FIXTURE,
|
||||
)
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
for attachment, data in ((linked[0], FIXTURE), (linked[1], os.urandom(len(FIXTURE)))):
|
||||
compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"s3-cli",
|
||||
"pipe",
|
||||
f"root/{bucket}/attachments/{attachment}",
|
||||
stdin=data,
|
||||
)
|
||||
healed = reconcile("--apply", *FLAGS)
|
||||
save("healed.json", healed)
|
||||
restored = c.call("GET", f"/api/v1/attachments/{linked[0]}/content", 200, actor=bob)
|
||||
foreign = c.call("GET", f"/api/v1/attachments/{linked[1]}/content", 404, actor=bob)
|
||||
check(
|
||||
"вернули те же байты — карантин снят; другие байты той же длины — остался",
|
||||
healed["fixed"]["healed"] == 1
|
||||
and healed["samples"].get("healed") == [linked[0]]
|
||||
and linked[1] in healed["samples"].get("quarantined", [])
|
||||
and restored["bytes"] == FIXTURE
|
||||
and foreign["status"] == 404,
|
||||
fixed=healed["fixed"],
|
||||
s3_get=healed["cost"]["requests"]["s3_get"],
|
||||
)
|
||||
return {"injected": injected, "targets": targets, "linked": linked}
|
||||
|
||||
|
||||
def single(check):
|
||||
holder = subprocess.Popen(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-c",
|
||||
f"SELECT pg_advisory_lock({LOCK_KEY}), pg_sleep(15)",
|
||||
],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
try:
|
||||
time.sleep(3)
|
||||
busy = reconcile("--apply", *FLAGS)
|
||||
finally:
|
||||
holder.wait()
|
||||
save("lock-busy.json", busy)
|
||||
check(
|
||||
"второй одновременный проход пропущен",
|
||||
busy["skipped"] and busy["exit_code"] == 0 and not any(busy["fixed"].values()),
|
||||
)
|
||||
|
||||
|
||||
def healthy(service, seconds=90):
|
||||
container = compose("ps", "-q", service).strip()
|
||||
probe = ["docker", "inspect", "-f", "{{.State.Health.Status}}", container]
|
||||
deadline = time.monotonic() + seconds
|
||||
while must(probe).strip() != "healthy":
|
||||
if time.monotonic() > deadline:
|
||||
raise SystemExit(f"{service} is not healthy after {seconds} s")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def interrupt(check):
|
||||
name = f"hlpipe-lab6-reconcile-sigterm-{os.getpid()}"
|
||||
compose("pause", "s3")
|
||||
try:
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "-T", "--name", name, "reconciler"]
|
||||
runner = subprocess.Popen(
|
||||
[*cmd, "--apply", *FLAGS],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
time.sleep(4)
|
||||
state = must(["docker", "inspect", "-f", "{{.State.Status}} {{.HostConfig.Init}}", name])
|
||||
started = time.monotonic()
|
||||
must(["docker", "stop", name])
|
||||
stopped = round(time.monotonic() - started, 2)
|
||||
code = runner.wait(timeout=60)
|
||||
finally:
|
||||
compose("unpause", "s3")
|
||||
healthy("s3")
|
||||
after = reconcile("--dry-run", *FLAGS)
|
||||
status, init = state.split()
|
||||
report = {
|
||||
"s3": "paused",
|
||||
"state_before_stop": status,
|
||||
"init": init,
|
||||
"stop_seconds": stopped,
|
||||
"exit_code": code,
|
||||
"next_pass_skipped": after["skipped"],
|
||||
}
|
||||
save("sigterm.json", report)
|
||||
check(
|
||||
"SIGTERM: идущий проход останавливается за секунды, блокировка освобождена",
|
||||
status == "running" and code == 143 and stopped < 5 and not after["skipped"],
|
||||
**report,
|
||||
)
|
||||
|
||||
|
||||
def outage(check):
|
||||
before = oracle("--grace", str(GRACE))
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
cmd = ["docker", "compose", "run", "--rm", "--no-deps", "-T", "reconciler", "--apply"]
|
||||
code, out, err, wall = run([*cmd, *FLAGS])
|
||||
finally:
|
||||
compose("up", "-d", "--wait", "--no-deps", "s3")
|
||||
after = oracle("--grace", str(GRACE))
|
||||
log = [line for line in err.splitlines() if "reconcile." in line]
|
||||
same = all(after[k] == before[k] for k in ("objects", "rows", "counts"))
|
||||
save("s3-down.json", {"exit_code": code, "wall_seconds": wall, "stdout": out, "log": log})
|
||||
check(
|
||||
"S3 остановлен: код 1 за ограниченное время, состояние не изменилось",
|
||||
code == 1 and wall < 30 and not out.strip() and same,
|
||||
exit_code=code,
|
||||
wall_seconds=wall,
|
||||
)
|
||||
|
||||
|
||||
def uploader(base, token, chat, *, deadline, results, lock):
|
||||
host = urlsplit(base).netloc
|
||||
conn = http.client.HTTPConnection(host, timeout=30)
|
||||
headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
|
||||
sent = 0
|
||||
while time.monotonic() < deadline:
|
||||
path = f"/api/v1/chats/{chat}/attachments?filename=load.png"
|
||||
try:
|
||||
conn.request("POST", path, tiny_png(), {**headers, "Content-Type": "image/png"})
|
||||
response = conn.getresponse()
|
||||
status, data = response.status, response.read()
|
||||
if status == 201 and sent % 10 == 0:
|
||||
body = json.dumps({"text": "", "attachment_ids": [json.loads(data)["id"]]})
|
||||
extra = {"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex}
|
||||
conn.request("POST", f"/api/v1/chats/{chat}/messages", body, {**headers, **extra})
|
||||
linked = conn.getresponse()
|
||||
linked.read()
|
||||
status = 201 if linked.status == 201 else -linked.status
|
||||
except (OSError, http.client.HTTPException):
|
||||
conn.close()
|
||||
conn = http.client.HTTPConnection(host, timeout=30)
|
||||
status, data = 0, b""
|
||||
with lock:
|
||||
results.append((status, json.loads(data) if status == 201 else None))
|
||||
sent += 1
|
||||
time.sleep(0.05)
|
||||
|
||||
|
||||
def under_load(c, check, base, seconds, threads):
|
||||
alice, _, _, chat = c.bootstrap()
|
||||
ready = evidence_root() / "ready-load.json"
|
||||
left = oracle("--grace", str(GRACE), "--save-ready", str(ready))["counts"]
|
||||
leftover = {
|
||||
"orphan_stale": left["orphan_fresh"] + left["orphan_stale"],
|
||||
"pending_stale": left["pending_fresh"]
|
||||
+ left["pending_stale_with_object"]
|
||||
+ left["pending_stale_without_object"],
|
||||
}
|
||||
orphans = inject("orphan", 3)
|
||||
intents = inject("stale-pending", 3, age=INTENT_AGE)
|
||||
results, lock = [], threading.Lock()
|
||||
deadline = time.monotonic() + seconds
|
||||
workers = [
|
||||
threading.Thread(
|
||||
target=uploader,
|
||||
args=(base, alice["token"], chat["id"]),
|
||||
kwargs={"deadline": deadline, "results": results, "lock": lock},
|
||||
)
|
||||
for _ in range(threads)
|
||||
]
|
||||
for worker in workers:
|
||||
worker.start()
|
||||
runs = []
|
||||
while time.monotonic() < deadline:
|
||||
runs.append(reconcile("--apply", *FLAGS))
|
||||
for worker in workers:
|
||||
worker.join()
|
||||
runs.append(reconcile("--apply", *FLAGS))
|
||||
created = {att["id"]: att["sha256"] for status, att in results if att}
|
||||
expected = dict(json.loads(ready.read_text()), **created)
|
||||
save("ready-load.json", expected, stamp=False)
|
||||
after = oracle(
|
||||
"--grace",
|
||||
str(GRACE),
|
||||
"--deep",
|
||||
"--expect-ready",
|
||||
str(ready),
|
||||
"--output",
|
||||
str(evidence_root() / "check-under-load.json"),
|
||||
)
|
||||
statuses = {}
|
||||
for status, _ in results:
|
||||
statuses[str(status)] = statuses.get(str(status), 0) + 1
|
||||
fixed = {name: sum(r["fixed"][name] for r in runs) for name in FIXABLE}
|
||||
rechecked = {}
|
||||
for r in runs:
|
||||
for name, count in r["rechecked"].items():
|
||||
rechecked[name] = rechecked.get(name, 0) + count
|
||||
seen = {name: sum(r["found"][name] for r in runs) for name in ("orphan_fresh", "pending_fresh")}
|
||||
summary = {
|
||||
"seconds": seconds,
|
||||
"upload_threads": threads,
|
||||
"uploads": statuses,
|
||||
"created": len(created),
|
||||
"linked_every": 10,
|
||||
"reconciler_runs": len(runs),
|
||||
"run_seconds": [r["cost"]["seconds"] for r in runs],
|
||||
"fixed_total": fixed,
|
||||
"fresh_seen_total": seen,
|
||||
"rechecked_total": rechecked,
|
||||
"errors": sum(r["errors"] for r in runs),
|
||||
"skipped": sum(1 for r in runs if r["skipped"]),
|
||||
"injected_before_load": {"orphan": len(orphans), "pending_stale": len(intents)},
|
||||
"left_from_faults": leftover,
|
||||
"check_after": {k: after[k] for k in ("objects", "rows", "ready_healthy", "counts", "ok")},
|
||||
}
|
||||
save("under-load.json", summary)
|
||||
check(
|
||||
"под нагрузкой: исправлены только внедрённые, ошибок нет",
|
||||
fixed
|
||||
== {
|
||||
**dict.fromkeys(FIXABLE, 0),
|
||||
"orphan_stale": leftover["orphan_stale"] + len(orphans),
|
||||
"pending_stale": leftover["pending_stale"] + len(intents),
|
||||
}
|
||||
and not summary["errors"]
|
||||
and not summary["skipped"],
|
||||
fixed=fixed,
|
||||
runs=len(runs),
|
||||
)
|
||||
check(
|
||||
"под нагрузкой: все 201 готовы и совпадают по SHA-256, потерь 0",
|
||||
after["ok"] and not after["counts"]["lost_ready"] and set(statuses) == {"201"},
|
||||
uploads=statuses,
|
||||
lost_ready=after["counts"]["lost_ready"],
|
||||
)
|
||||
|
||||
|
||||
def demo(args):
|
||||
evidence_root().mkdir(parents=True, exist_ok=False)
|
||||
c = client.Client(args.base_url, timeout=30)
|
||||
check = Checks()
|
||||
pre = oracle("--grace", str(GRACE))
|
||||
dirty = {k: v for k, v in pre["counts"].items() if v and k != "quarantined"}
|
||||
if dirty:
|
||||
raise SystemExit(f"стенд не в исходном состоянии {dirty}: make reconcile ARGS=--apply")
|
||||
started = time.monotonic()
|
||||
result = {"started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "commit": head()}
|
||||
result["faults"] = faults(c, check, pre)
|
||||
single(check)
|
||||
interrupt(check)
|
||||
outage(check)
|
||||
under_load(c, check, args.base_url, args.load_seconds, args.load_threads)
|
||||
result.update(seconds=round(time.monotonic() - started, 1), checks=check.items, ok=check.ok)
|
||||
save("demo.json", result)
|
||||
print(json.dumps({"ok": check.ok, "checks": len(check.items)}, ensure_ascii=False))
|
||||
sys.exit(0 if check.ok else 1)
|
||||
|
||||
|
||||
def pins(args):
|
||||
cpus = int(must(["docker", "info", "--format", "{{.NCPU}}"]).strip())
|
||||
sized = {"S3_CPUS": "2", "S3_MEMORY": args.s3_memory}
|
||||
if args.no_pin or cpus < 8:
|
||||
return sized
|
||||
return dict(
|
||||
sized,
|
||||
S3_CPUSET=f"{cpus - 5}-{cpus - 4}",
|
||||
PG_CPUSET=f"{cpus - 3}-{cpus - 2}",
|
||||
RECONCILE_CPUSET=str(cpus - 1),
|
||||
)
|
||||
|
||||
|
||||
def cpu_set(env):
|
||||
cpus = set()
|
||||
for name in ("S3_CPUSET", "PG_CPUSET", "RECONCILE_CPUSET"):
|
||||
for part in filter(None, env.get(name, "").split(",")):
|
||||
low, _, high = part.partition("-")
|
||||
cpus.update(range(int(low), int(high or low) + 1))
|
||||
return cpus
|
||||
|
||||
|
||||
def limits():
|
||||
ids = compose("ps", "-q", "s3", "postgres").split()
|
||||
fmt = (
|
||||
"{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}}"
|
||||
" cpuset={{.HostConfig.CpusetCpus}}"
|
||||
)
|
||||
return must(["docker", "inspect", "-f", fmt, *ids]).strip().splitlines()
|
||||
|
||||
|
||||
def host(title):
|
||||
stats = must(
|
||||
[
|
||||
"docker",
|
||||
"stats",
|
||||
"--no-stream",
|
||||
"--all",
|
||||
"--format",
|
||||
"table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}\t{{.PIDs}}",
|
||||
]
|
||||
)
|
||||
running = must(["docker", "ps", "--format", "{{.Names}} {{.Image}} {{.Status}}"])
|
||||
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
load = " ".join(f"{v:.2f}" for v in os.getloadavg())
|
||||
return (
|
||||
f"== {title} date: {stamp} commit: {head()} host loadavg: {load}\n"
|
||||
f"$ docker stats --no-stream --all\n{stats}\n$ docker ps\n{running}\n"
|
||||
)
|
||||
|
||||
|
||||
def usage(text):
|
||||
return int(re.search(r"^usage_usec (\d+)$", text, re.M).group(1)) / 1e6
|
||||
|
||||
|
||||
def sample():
|
||||
vm = compose(
|
||||
"exec", "-T", "postgres", "cat", "/proc/uptime", "/proc/stat", "/sys/fs/cgroup/cpu.stat"
|
||||
)
|
||||
s3 = compose("exec", "-T", "s3", "cat", "/sys/fs/cgroup/cpu.stat")
|
||||
busy = {}
|
||||
for line in vm.splitlines()[1:]:
|
||||
name, *values = line.split() or [""]
|
||||
if name.startswith("cpu") and name[3:].isdigit():
|
||||
busy[int(name[3:])] = sum(int(values[i]) for i in BUSY) / USER_HZ
|
||||
return float(vm.split()[0]), busy, usage(vm) + usage(s3)
|
||||
|
||||
|
||||
def screen(first, last, own, pinned, args, *, started=True):
|
||||
window = max(last[0] - first[0], 0.01)
|
||||
busy = {cpu: spent - first[1].get(cpu, 0.0) for cpu, spent in last[1].items()}
|
||||
ours = last[2] - first[2] + own
|
||||
other = sum(busy.values()) - ours - args.start_other * started
|
||||
on_pinned = sum(busy.get(cpu, 0.0) for cpu in pinned) - ours - args.start_pinned * started
|
||||
other, on_pinned = max(0.0, other / window), max(0.0, on_pinned / window) if pinned else 0.0
|
||||
return {
|
||||
"window_seconds": round(window, 2),
|
||||
"ours_cores": round(ours / window, 2),
|
||||
"other_cores": round(other, 2),
|
||||
"other_on_pinned_cores": round(on_pinned, 2),
|
||||
"host_loadavg_1m": round(os.getloadavg()[0], 2),
|
||||
"disturbed": other > args.max_other or on_pinned > args.max_pinned,
|
||||
}
|
||||
|
||||
|
||||
def wait_quiet(args, pinned):
|
||||
deadline, calm = time.monotonic() + args.quiet_timeout, 0
|
||||
while calm < 3 and time.monotonic() < deadline:
|
||||
first = sample()
|
||||
time.sleep(5)
|
||||
quiet = screen(first, sample(), 0.0, pinned, args, started=False)
|
||||
calm = 0 if quiet["disturbed"] else calm + 1
|
||||
sys.stderr.write(f"waiting for quiet: {json.dumps(quiet)}\n")
|
||||
return calm == 3
|
||||
|
||||
|
||||
def measure(flags, env, args, pinned):
|
||||
rejected = []
|
||||
for attempt in range(args.retries + 1):
|
||||
first = sample()
|
||||
report = reconcile(*flags, "--samples", "3", env=env)
|
||||
report["screen"] = screen(first, sample(), report["cost"]["cpu_seconds"], pinned, args)
|
||||
if not report["screen"]["disturbed"]:
|
||||
return report, rejected
|
||||
rejected.append(report)
|
||||
if attempt < args.retries and not wait_quiet(args, pinned):
|
||||
break
|
||||
return None, rejected
|
||||
|
||||
|
||||
def seed(count, env):
|
||||
if count <= 0:
|
||||
return {"added": 0}
|
||||
env = dict(env, API_CPUS="4", API_MEMORY="512m")
|
||||
tools = f"{ROOT / 'student-tests' / 'tools'}:/tools:ro"
|
||||
out = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"-v",
|
||||
tools,
|
||||
"--entrypoint",
|
||||
"python",
|
||||
"api",
|
||||
"/tools/seed_storage.py",
|
||||
"--count",
|
||||
str(count),
|
||||
"--concurrency",
|
||||
"4",
|
||||
env=env,
|
||||
)
|
||||
records = [json.loads(line) for line in out.strip().splitlines()]
|
||||
return {**records[-1], "progress": records[:-1]}
|
||||
|
||||
|
||||
def median(runs, path):
|
||||
values = []
|
||||
for r in runs:
|
||||
value = r
|
||||
for key in path:
|
||||
value = value[key]
|
||||
values.append(value)
|
||||
return statistics.median(values)
|
||||
|
||||
|
||||
def summarize(results, rejected):
|
||||
rows = []
|
||||
for (n, mode), runs in sorted(results.items()):
|
||||
seconds = median(runs, ("cost", "seconds"))
|
||||
rows.append(
|
||||
{
|
||||
"objects": n,
|
||||
"mode": mode,
|
||||
"runs": len(runs),
|
||||
"seconds_median": seconds,
|
||||
"seconds_all": [r["cost"]["seconds"] for r in runs],
|
||||
"wall_seconds_median": median(runs, ("wall_seconds",)),
|
||||
"us_per_object": round(seconds / n * 1e6, 1),
|
||||
"cpu_seconds_median": median(runs, ("cost", "cpu_seconds")),
|
||||
"s3_list_wait_median": median(runs, ("cost", "waited_seconds", "s3_list")),
|
||||
"sql_wait_median": median(runs, ("cost", "waited_seconds", "sql")),
|
||||
"requests": runs[0]["cost"]["requests"],
|
||||
"max_rss_mib_median": median(runs, ("cost", "max_rss_mib")),
|
||||
"other_cores_max": max(r["screen"]["other_cores"] for r in runs),
|
||||
"other_on_pinned_cores_max": max(
|
||||
r["screen"]["other_on_pinned_cores"] for r in runs
|
||||
),
|
||||
"disturbed_kept": sum(r["screen"]["disturbed"] for r in runs),
|
||||
"rejected": rejected.get((n, mode), 0),
|
||||
"scanned": runs[0]["scanned"],
|
||||
"found_nonzero": {k: v for k, v in runs[0]["found"].items() if v},
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def table(rows):
|
||||
head = (
|
||||
"objects mode runs t_med,s wall,s us/obj cpu,s list,s sql,s lists sqls"
|
||||
" gets rss,MiB other pinned rejected"
|
||||
)
|
||||
lines = [head]
|
||||
for r in rows:
|
||||
q = r["requests"]
|
||||
lines.append(
|
||||
f"{r['objects']:>7} {r['mode']:<9} {r['runs']:>4} {r['seconds_median']:>7.3f} "
|
||||
f"{r['wall_seconds_median']:>6.2f} {r['us_per_object']:>6.1f} "
|
||||
f"{r['cpu_seconds_median']:>5.2f} {r['s3_list_wait_median']:>6.3f} "
|
||||
f"{r['sql_wait_median']:>5.3f} {q['s3_list']:>5} {q['sql']:>4} {q['s3_get']:>5} "
|
||||
f"{r['max_rss_mib_median']:>7.1f} {r['other_cores_max']:>5.2f} "
|
||||
f"{r['other_on_pinned_cores_max']:>6.2f} {r['rejected']:>8}"
|
||||
)
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def cost(args):
|
||||
out = evidence_root() / "cost"
|
||||
out.mkdir(parents=True, exist_ok=False)
|
||||
(out / "disturbed").mkdir()
|
||||
rows = int(psql("SELECT count(*) FROM attachments"))
|
||||
if rows > args.sizes[0]:
|
||||
raise SystemExit(f"на стенде уже {rows} вложений: используйте новый отдельный project")
|
||||
snapshot = out / "host-docker-stats.txt"
|
||||
snapshot.write_text(host("before the series"))
|
||||
env = pins(args)
|
||||
pinned = cpu_set(env)
|
||||
compose("up", "-d", "--wait", "--no-deps", "s3", "postgres", env=env)
|
||||
stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
plan = {"date": stamp, "commit": head(), "pins": env, "limits": limits(), "seeds": []}
|
||||
plan["screen"] = {
|
||||
"max_other_cores": args.max_other,
|
||||
"max_other_on_pinned_cores": args.max_pinned,
|
||||
"start_allowance_core_seconds": {"vm": args.start_other, "pinned": args.start_pinned},
|
||||
"retries": args.retries,
|
||||
}
|
||||
results, rejected = {}, {}
|
||||
try:
|
||||
for n in args.sizes:
|
||||
plan["seeds"].append(dict(seed(n - rows, env), target=n))
|
||||
rows = n
|
||||
time.sleep(args.settle)
|
||||
save("cost/plan.json", plan)
|
||||
if not wait_quiet(args, pinned):
|
||||
raise SystemExit("no quiet measurement window before timeout")
|
||||
modes = [("shallow", ["--dry-run"])]
|
||||
if n <= args.deep_max:
|
||||
modes.append(("deep", ["--dry-run", "--deep"]))
|
||||
if n == args.page_compare:
|
||||
modes.append(("page100", ["--dry-run", "--page-size", "100"]))
|
||||
for mode, flags in modes:
|
||||
for attempt in range(1, args.repeats + 1):
|
||||
report, dropped = measure(flags, env, args, pinned)
|
||||
name = f"n{n}-{mode}-{attempt}"
|
||||
for number, bad in enumerate(dropped, 1):
|
||||
save(f"cost/disturbed/{name}-try{number}.json", bad)
|
||||
rejected[(n, mode)] = rejected.get((n, mode), 0) + len(dropped)
|
||||
if report is None:
|
||||
raise SystemExit(f"{name}: no clean run after retries; rejected preserved")
|
||||
if (
|
||||
report["exit_code"]
|
||||
or report["errors"]
|
||||
or report["skipped"]
|
||||
or report["scanned"] != {"objects": n, "rows": n}
|
||||
or any(report["found"].values())
|
||||
):
|
||||
save(f"cost/invalid/{name}.json", report)
|
||||
raise SystemExit(f"{name}: inconsistent dataset or failed pass")
|
||||
save(f"cost/{name}.json", report)
|
||||
results.setdefault((n, mode), []).append(report)
|
||||
save("cost/summary.json", {**plan, "results": summarize(results, rejected)})
|
||||
sys.stderr.write(f"{name}: {report['cost']['seconds']} s {report['screen']}\n")
|
||||
finally:
|
||||
save("cost/summary.json", {**plan, "results": summarize(results, rejected)})
|
||||
compose("up", "-d", "--wait", "--no-deps", "s3", "postgres")
|
||||
with snapshot.open("a") as handle:
|
||||
handle.write("\n" + host("after the series"))
|
||||
summary = summarize(results, rejected)
|
||||
save("cost/summary.json", {**plan, "results": summary})
|
||||
(out / "summary.txt").write_text(
|
||||
f"date: {stamp} commit: {plan['commit']} pins: {env}\n" + table(summary)
|
||||
)
|
||||
sys.stdout.write(table(summary))
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Lab4 track 2: reconciler demo and cost of a pass")
|
||||
sub = p.add_subparsers(dest="command", required=True)
|
||||
d = sub.add_parser("demo", help="fault injection, dry-run/apply/repeat, safety, under load")
|
||||
d.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
d.add_argument("--load-seconds", type=int, default=75)
|
||||
d.add_argument("--load-threads", type=int, default=3)
|
||||
k = sub.add_parser("cost", help="cost of a pass for N objects, repeated")
|
||||
k.add_argument("--sizes", type=int, nargs="+", default=[1000, 10000, 30000, 100000])
|
||||
k.add_argument("--repeats", type=int, default=3)
|
||||
k.add_argument("--deep-max", type=int, default=100000)
|
||||
k.add_argument("--page-compare", type=int, default=10000)
|
||||
k.add_argument("--settle", type=float, default=10)
|
||||
k.add_argument("--s3-memory", default="3g")
|
||||
k.add_argument("--no-pin", action="store_true")
|
||||
k.add_argument("--max-other", type=float, default=2.0, help="foreign CPU in the VM, cores")
|
||||
k.add_argument("--max-pinned", type=float, default=0.25, help="foreign CPU on pinned cores")
|
||||
k.add_argument("--start-other", type=float, default=1.5, help="container start, core-s")
|
||||
k.add_argument("--start-pinned", type=float, default=0.5, help="the same on pinned cores")
|
||||
k.add_argument("--retries", type=int, default=3, help="reruns of a disturbed run")
|
||||
k.add_argument("--quiet-timeout", type=float, default=900.0)
|
||||
for command in (d, k):
|
||||
command.add_argument(
|
||||
"--out", default=os.environ.get("RECONCILE_EVIDENCE_DIR", "evidence/reconcile")
|
||||
)
|
||||
args = p.parse_args()
|
||||
os.environ["RECONCILE_EVIDENCE_DIR"] = args.out
|
||||
if args.command == "demo":
|
||||
demo(args)
|
||||
else:
|
||||
cost(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop lb api relay worker
|
||||
docker compose restart postgres valkey s3 broker
|
||||
docker compose up -d --force-recreate --no-deps s3-tls valkey-tls broker-tls
|
||||
docker compose up -d --no-deps api relay worker lb
|
||||
scripts/lb-wait.sh
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose up -d --no-deps --no-recreate --wait --wait-timeout "${WAIT_TIMEOUT:-60}" "${API_SERVICE:-api}"
|
||||
scripts/lb-wait.sh
|
||||
Executable
+22
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
service=${API_SERVICE:-api}
|
||||
show() { docker inspect -f '{{.Config.Hostname}} image={{.Config.Image}}@{{slice .Image 7 19}}' "$1"; }
|
||||
scripts/stand-usage.sh &
|
||||
echo "$(date -u +%T) migrate once before the first replacement"
|
||||
docker compose run --rm --no-deps -T migrate 2>&1
|
||||
old=$(docker compose ps -q "$service")
|
||||
count=$(printf '%s\n' "$old" | grep -c .)
|
||||
for id in $old; do
|
||||
running=$(docker compose ps -q "$service")
|
||||
docker compose up -d --no-deps --no-recreate --wait --wait-timeout "${WAIT_TIMEOUT:-90}" --scale "$service=$((count + 1))" "$service" 2>&1
|
||||
scripts/lb-wait.sh $((count + 1))
|
||||
new=$(docker compose ps -q "$service" | grep -v -F "$running")
|
||||
echo "$(date -u +%T) replace $(show "$id") -> $(show "$new")"
|
||||
docker stop -t "${STOP_TIMEOUT:-7}" "$id" >/dev/null
|
||||
docker rm "$id" >/dev/null
|
||||
done
|
||||
scripts/lb-wait.sh "$count"
|
||||
wait
|
||||
echo "$(date -u +%T) done: $count replicas replaced"
|
||||
Executable
+89
@@ -0,0 +1,89 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
cli() { docker compose run --rm --no-deps -T s3-cli "$@"; }
|
||||
undated() {
|
||||
python3 -c 'import json, sys
|
||||
def clean(value):
|
||||
if isinstance(value, dict):
|
||||
return {k: clean(v) for k, v in value.items() if not k.endswith("_date")}
|
||||
return [clean(v) for v in value] if isinstance(value, list) else value
|
||||
text, decoder, at = sys.stdin.read(), json.JSONDecoder(), 0
|
||||
while text[at:].strip():
|
||||
at += len(text[at:]) - len(text[at:].lstrip())
|
||||
value, at = decoder.raw_decode(text, at)
|
||||
print(json.dumps(clean(value), indent=2, ensure_ascii=False))'
|
||||
}
|
||||
snapshot() {
|
||||
cli sh -s <<'EOF' | undated
|
||||
ak=$(cat /run/secrets/s3_access_key_id)
|
||||
rk=$(cat /run/secrets/s3_reconciler_access_key_id)
|
||||
for c in "bucket list root" "bucket anonymous get root/$S3_BUCKET" "admin policy info root messenger-api" "admin policy info root messenger-reconciler" "admin user info root $ak" "admin user info root $rk" "bucket lifecycle rule export root/$S3_BUCKET"; do
|
||||
rc $c --json
|
||||
done | sed "s/$ak/<api-key>/g; s/$rk/<reconciler-key>/g"
|
||||
EOF
|
||||
}
|
||||
failed=0
|
||||
verdict() { if [ "$2" = "$3" ]; then echo "PASS $1: $3"; else echo "FAIL $1: ожидалось $2, получено $3"; failed=1; fi; }
|
||||
echo "date: $(date -u +%FT%TZ) commit: $(git rev-parse HEAD) == S3 privacy and bootstrap checks"
|
||||
verdict "s3: опубликованные host-порты" "нет" "$(docker inspect -f '{{json .NetworkSettings.Ports}}' "$(docker compose ps -q s3)" | grep -q HostPort && echo есть || echo нет)"
|
||||
verdict "s3: консоль :9001 внутри контейнера" "000" "$(docker compose exec -T s3 curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:9001/ || true)"
|
||||
before=$(snapshot)
|
||||
first=$(docker compose run --rm --no-deps -T s3-init >/dev/null 2>&1 && echo 0 || echo 1)
|
||||
second=$(docker compose run --rm --no-deps -T s3-init 2>/dev/null || echo FAILED)
|
||||
after=$(snapshot)
|
||||
verdict "s3-init: повторный запуск 1" "0" "$first"
|
||||
verdict "s3-init: повторный запуск 2" "0" "$(echo "$second" | grep -q '^s3-init:' && echo 0 || echo 1)"
|
||||
verdict "s3-init: состояние IAM/bucket не изменилось" "same" "$([ "$before" = "$after" ] && echo same || echo changed)"
|
||||
cli sh -s <<'EOF' || failed=1
|
||||
b=$S3_BUCKET
|
||||
key="attachments/s3-check-$(date +%s)-$$"
|
||||
spare="$key-reconciler"
|
||||
other="s3-check-$(date +%s)-$$"
|
||||
head -c 4096 /dev/urandom > /tmp/probe
|
||||
result=0
|
||||
expect() {
|
||||
want=$1; name=$2; shift 2
|
||||
if "$@" >/tmp/out 2>&1; then got=allow; elif grep -qE '403|AccessDenied|set_bucket_policy: service error|check bucket: Network error: service error' /tmp/out; then got=deny; else got=error; fi
|
||||
if [ "$got" = "$want" ]; then echo "PASS $name: $got"; else echo "FAIL $name: ожидалось $want, получено $got"; result=1; fi
|
||||
}
|
||||
expect allow "api: PutObject" rc put /tmp/probe "api/$b/$key"
|
||||
expect allow "api: HeadObject" rc object stat "api/$b/$key"
|
||||
expect allow "api: GetObject" rc object show "api/$b/$key"
|
||||
expect deny "api: ListBucket" rc object list "api/$b/attachments/"
|
||||
rc put /tmp/probe "api/$b/$spare" >/dev/null
|
||||
expect allow "reconciler: ListBucket" rc object list "reconciler/$b/attachments/"
|
||||
expect allow "reconciler: HeadObject" rc object stat "reconciler/$b/$key"
|
||||
expect allow "reconciler: GetObject" rc object show "reconciler/$b/$key"
|
||||
expect deny "reconciler: PutObject" rc put /tmp/probe "reconciler/$b/$key-put"
|
||||
expect allow "reconciler: DeleteObject" rc object remove --force "reconciler/$b/$spare"
|
||||
expect deny "reconciler: CreateBucket" rc bucket create "reconciler/$other"
|
||||
expect deny "reconciler: PutBucketPolicy (public)" rc bucket anonymous set public "reconciler/$b"
|
||||
expect deny "reconciler: admin ListUsers" rc admin user list reconciler
|
||||
expect deny "api: CreateBucket" rc bucket create "api/$other"
|
||||
expect deny "api: DeleteBucket" rc bucket remove "api/$b"
|
||||
expect deny "api: PutBucketPolicy (public)" rc bucket anonymous set public "api/$b"
|
||||
expect deny "api: PutBucketLifecycle (HeadBucket уже 403)" rc bucket lifecycle rule import "api/$b" /s3/lifecycle.json
|
||||
expect deny "api: admin ListUsers" rc admin user list api
|
||||
rc bucket create --ignore-existing "root/$other" >/dev/null
|
||||
expect deny "api: PutObject в чужой bucket" rc put /tmp/probe "api/$other/x"
|
||||
expect deny "api: ListBucket чужого bucket" rc object list "api/$other"
|
||||
rc bucket remove "root/$other" >/dev/null
|
||||
expect deny "anonymous: HeadObject" rc object stat "anon/$b/$key"
|
||||
expect deny "anonymous: ListBucket" rc object list "anon/$b"
|
||||
expect deny "anonymous: PutObject" rc put /tmp/probe "anon/$b/attachments/anonymous"
|
||||
status=$(wget -S -O /dev/null "$S3_ENDPOINT/$b/$key" 2>&1 | sed -n 's/^ *HTTP\/[0-9.]* \([0-9]*\).*/\1/p' | head -n 1)
|
||||
if [ "$status" = 403 ]; then echo "PASS anonymous: прямой HTTP GET объекта из отдельного контейнера: $status"; else echo "FAIL anonymous: прямой HTTP GET: $status"; result=1; fi
|
||||
permission=$(rc bucket anonymous get "root/$b" --json | sed -n 's/.*"permission": *"\([a-z]*\)".*/\1/p')
|
||||
if [ "$permission" = private ]; then echo "PASS bucket: anonymous policy: $permission"; else echo "FAIL bucket: anonymous policy: $permission"; result=1; fi
|
||||
expect allow "api: DeleteObject" rc object remove --force "api/$b/$key"
|
||||
host=$(echo "$S3_ENDPOINT" | sed 's#^[a-z]*://##; s#:.*##')
|
||||
if wget -T 2 -O /dev/null "http://$host:9001/" >/tmp/out 2>&1; then echo "FAIL s3: консоль :9001 отвечает из сети стенда"; result=1
|
||||
elif grep -q refused /tmp/out; then echo "PASS s3: консоль :9001 из отдельного контейнера сети стенда: connection refused"
|
||||
else echo "FAIL s3: консоль :9001 из сети стенда: $(tail -n 1 /tmp/out)"; result=1; fi
|
||||
exit $result
|
||||
EOF
|
||||
echo "== IAM/bucket snapshot (без секретов)"
|
||||
echo "$after"
|
||||
if [ "$failed" != 0 ]; then echo "RESULT: FAIL"; exit 1; fi
|
||||
echo "RESULT: PASS"
|
||||
Executable
+524
@@ -0,0 +1,524 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import collections
|
||||
import contextlib
|
||||
import csv
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from probe import ROOT, k6_metrics, lb_up, run_k6
|
||||
|
||||
SCRIPTS = ROOT / "scripts"
|
||||
UNITS = {"B": 1, "KIB": 2**10, "MIB": 2**20, "GIB": 2**30, "KB": 10**3, "MB": 10**6, "GB": 10**9}
|
||||
PINNED = {
|
||||
"PG_CPUSET": "0-1",
|
||||
"LB_CPUSET": "2",
|
||||
"VALKEY_CPUSET": "3",
|
||||
"K6_CPUSET": "4-6",
|
||||
"K6_CPUS": "3",
|
||||
"K6_MEMORY": "1g",
|
||||
}
|
||||
API_FIRST_CPU = 7
|
||||
FIELDS = [
|
||||
"raw_dir",
|
||||
"variant",
|
||||
"config",
|
||||
"replicas",
|
||||
"cpus",
|
||||
"memory_mb",
|
||||
"workers",
|
||||
"pool",
|
||||
"maxconn",
|
||||
"api_cpuset",
|
||||
"rate",
|
||||
"repeat",
|
||||
"started",
|
||||
"db_mb",
|
||||
"messages",
|
||||
"k6_exit",
|
||||
"saturated",
|
||||
"requests",
|
||||
"rps",
|
||||
"ok_rps",
|
||||
"failed_ratio",
|
||||
"dropped_iterations",
|
||||
"p50_ms",
|
||||
"p95_ms",
|
||||
"p99_ms",
|
||||
"p95_post_ms",
|
||||
"p95_get_ms",
|
||||
"cpu_api",
|
||||
"cpu_postgres",
|
||||
"cpu_lb",
|
||||
"cpu_valkey",
|
||||
"cpu_k6",
|
||||
"mem_api_mb",
|
||||
"mem_postgres_mb",
|
||||
"mem_k6_mb",
|
||||
"pg_backends_max",
|
||||
"pg_active_avg",
|
||||
"pg_active_max",
|
||||
"pg_idle_avg",
|
||||
"pg_idle_tx_avg",
|
||||
"pg_lock_avg",
|
||||
"pg_lock_max",
|
||||
"pg_lwlock_avg",
|
||||
"pg_io_avg",
|
||||
"lb_scur_max",
|
||||
"lb_qcur_max",
|
||||
"lb_qtime_max_ms",
|
||||
"lb_rtime_avg_ms",
|
||||
"cpu_vm",
|
||||
"cpu_other",
|
||||
"gap_s",
|
||||
"wall_s",
|
||||
"disturbed",
|
||||
]
|
||||
|
||||
|
||||
def compose(*args, env=None):
|
||||
command = ["docker", "compose", *args]
|
||||
return subprocess.run(
|
||||
command, cwd=str(ROOT), env=env, check=True, capture_output=True, text=True
|
||||
).stdout
|
||||
|
||||
|
||||
def size(text):
|
||||
match = re.match(r"([\d.]+)\s*([A-Za-z]+)", text.strip())
|
||||
return float(match.group(1)) * UNITS.get(match.group(2).upper(), 1) if match else 0.0
|
||||
|
||||
|
||||
def rows(path, start, end):
|
||||
with path.open() as handle:
|
||||
return [r for r in csv.DictReader(handle) if r["ts"] and start <= float(r["ts"]) <= end]
|
||||
|
||||
|
||||
def mean(values):
|
||||
return round(statistics.mean(values), 2) if values else 0.0
|
||||
|
||||
|
||||
def docker_usage(path, project, start, end):
|
||||
ticks = collections.defaultdict(collections.Counter)
|
||||
memory = collections.Counter()
|
||||
for r in rows(path, start, end):
|
||||
name = re.sub(r"(-run-[0-9a-f]+|-\d+)$", "", r["name"][len(project) + 1 :])
|
||||
ticks[r["ts"]][name] += float(r["cpu_pct"].rstrip("%") or 0)
|
||||
memory[name] = max(memory[name], size(r["mem_usage"].split("/")[0]) / 2**20)
|
||||
cpu = {
|
||||
name: mean([t[name] for t in ticks.values() if name in t])
|
||||
for name in ("api", "postgres", "lb", "valkey", "k6")
|
||||
}
|
||||
usage = {f"cpu_{name}": value for name, value in cpu.items()}
|
||||
usage.update({f"mem_{name}_mb": round(memory[name], 1) for name in ("api", "postgres", "k6")})
|
||||
return usage
|
||||
|
||||
|
||||
def vm_usage(path, start, end):
|
||||
samples = [(int(r["busy"]), int(r["total"]), int(r["cpus"])) for r in rows(path, start, end)]
|
||||
if len(samples) < 2 or samples[-1][1] == samples[0][1]:
|
||||
return 0.0
|
||||
first, last = samples[0], samples[-1]
|
||||
return round(100 * last[2] * (last[0] - first[0]) / (last[1] - first[1]), 1)
|
||||
|
||||
|
||||
def gap(path, start, end):
|
||||
ticks = sorted({float(r["ts"]) for r in rows(path, start - 5, end + 5)})
|
||||
edges = [start, *[t for t in ticks if start <= t <= end], end]
|
||||
return max(b - a for a, b in zip(edges, edges[1:]))
|
||||
|
||||
|
||||
def vm_counters():
|
||||
lines = compose("exec", "-T", "valkey", "cat", "/proc/stat").splitlines()
|
||||
values = [int(v) for v in lines[0].split()[1:]]
|
||||
cpus = sum(1 for line in lines if re.match(r"cpu\d", line))
|
||||
return sum(values) - values[3] - values[4], sum(values), cpus
|
||||
|
||||
|
||||
def wait_quiet(args):
|
||||
deadline, calm = time.monotonic() + args.quiet_timeout, 0
|
||||
while calm < 3 and time.monotonic() < deadline:
|
||||
first = vm_counters()
|
||||
time.sleep(5)
|
||||
last = vm_counters()
|
||||
busy = 100 * last[2] * (last[0] - first[0]) / max(1, last[1] - first[1])
|
||||
calm = calm + 1 if busy < args.max_other else 0
|
||||
print(json.dumps({"waiting_for_quiet_vm_cpu": round(busy, 1)}), flush=True)
|
||||
|
||||
|
||||
def pg_usage(path, start, end):
|
||||
ticks = collections.defaultdict(collections.Counter)
|
||||
for r in rows(path, start, end):
|
||||
count, state, wait = int(r["backends"]), r["state"], r["wait_event_type"]
|
||||
tick = ticks[r["ts"]]
|
||||
tick["backends"] += count
|
||||
tick["active"] += count * (state == "active")
|
||||
tick["idle"] += count * (state == "idle")
|
||||
tick["idle_tx"] += count * state.startswith("idle in transaction")
|
||||
tick["lock"] += count * (wait == "Lock")
|
||||
tick["lwlock"] += count * (wait == "LWLock")
|
||||
tick["io"] += count * (wait == "IO")
|
||||
series = list(ticks.values())
|
||||
return {
|
||||
"pg_backends_max": max((t["backends"] for t in series), default=0),
|
||||
"pg_active_avg": mean([t["active"] for t in series]),
|
||||
"pg_active_max": max((t["active"] for t in series), default=0),
|
||||
"pg_idle_avg": mean([t["idle"] for t in series]),
|
||||
"pg_idle_tx_avg": mean([t["idle_tx"] for t in series]),
|
||||
"pg_lock_avg": mean([t["lock"] for t in series]),
|
||||
"pg_lock_max": max((t["lock"] for t in series), default=0),
|
||||
"pg_lwlock_avg": mean([t["lwlock"] for t in series]),
|
||||
"pg_io_avg": mean([t["io"] for t in series]),
|
||||
}
|
||||
|
||||
|
||||
def lb_usage(path, start, end):
|
||||
backend = [
|
||||
r for r in rows(path, start, end) if r["pxname"] == "api" and r["svname"] == "BACKEND"
|
||||
]
|
||||
|
||||
def numbers(field):
|
||||
return [int(r[field] or 0) for r in backend]
|
||||
|
||||
return {
|
||||
"lb_scur_max": max(numbers("scur"), default=0),
|
||||
"lb_qcur_max": max(numbers("qcur"), default=0),
|
||||
"lb_qtime_max_ms": max(numbers("qtime"), default=0),
|
||||
"lb_rtime_avg_ms": mean(numbers("rtime")),
|
||||
}
|
||||
|
||||
|
||||
def trend(path, name):
|
||||
metrics = json.loads(Path(path).read_text())["metrics"]
|
||||
found = metrics.get(f"http_req_duration{{scenario:measure,name:{name}}}", {})
|
||||
return round(found.get("values", {}).get("p(95)", 0.0), 2)
|
||||
|
||||
|
||||
def sampler(*command):
|
||||
return subprocess.Popen([str(SCRIPTS / command[0]), *command[1:]], start_new_session=True)
|
||||
|
||||
|
||||
def stop(process):
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
return
|
||||
process.wait()
|
||||
|
||||
|
||||
def wait_lb(expected, timeout=120):
|
||||
deadline, stable = time.monotonic() + timeout, 0
|
||||
while stable < 4:
|
||||
if time.monotonic() > deadline:
|
||||
raise SystemExit(f"LB does not settle on {expected} UP servers (now {lb_up()})")
|
||||
stable = stable + 1 if lb_up() == expected else 0
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def layout(config, args, variant):
|
||||
name, _, extra = variant.partition(":")
|
||||
replicas, cpus = (float(v) for v in config.split("x"))
|
||||
replicas = int(replicas)
|
||||
workers = args.workers or max(1, int(cpus))
|
||||
width = max(1, math.ceil(replicas * cpus))
|
||||
cpuset = str(API_FIRST_CPU) + (f"-{API_FIRST_CPU + width - 1}" if width > 1 else "")
|
||||
memory = args.api_memory or args.api_memory_total // replicas
|
||||
settings = {
|
||||
"API_REPLICAS": str(replicas),
|
||||
"API_CPUS": f"{cpus:g}",
|
||||
"API_MEMORY": f"{memory}m",
|
||||
"WEB_CONCURRENCY": str(workers),
|
||||
"DB_POOL_MAX_SIZE": str(args.pool),
|
||||
"API_SERVER_MAXCONN": str(args.conn_per_worker * workers),
|
||||
"API_CPUSET": cpuset if args.pin else "",
|
||||
}
|
||||
settings.update(dict(kv.split("=", 1) for kv in [*args.env, *filter(None, extra.split(","))]))
|
||||
base = {
|
||||
"variant": name,
|
||||
"config": config,
|
||||
"replicas": replicas,
|
||||
"cpus": cpus,
|
||||
"memory_mb": memory,
|
||||
"workers": int(settings["WEB_CONCURRENCY"]),
|
||||
"pool": int(settings["DB_POOL_MAX_SIZE"]),
|
||||
"maxconn": int(settings["API_SERVER_MAXCONN"]),
|
||||
"api_cpuset": settings["API_CPUSET"],
|
||||
}
|
||||
return base, settings
|
||||
|
||||
|
||||
def apply(base, settings, env, out):
|
||||
env = dict(env, **settings)
|
||||
for attempt in range(3):
|
||||
try:
|
||||
compose("up", "-d", "--wait", "--wait-timeout", "180", env=env)
|
||||
break
|
||||
except subprocess.CalledProcessError as error:
|
||||
log = Path(out) / "compose-up-failed.txt"
|
||||
with log.open("a") as handle:
|
||||
stamp = time.strftime("%FT%TZ", time.gmtime())
|
||||
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||
handle.write(f"date: {stamp} commit: {commit}\n")
|
||||
handle.write(f"== {stamp} {base} attempt {attempt + 1}\n")
|
||||
handle.write(error.stdout + error.stderr + "\n")
|
||||
print(json.dumps({"compose_up_failed": attempt + 1, "log": str(log)}))
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(30)
|
||||
wait_lb(base["replicas"])
|
||||
return env
|
||||
|
||||
|
||||
def deployment(env):
|
||||
ids = compose("ps", "-q", env=env).split()
|
||||
template = "{{json .Name}} {{json .Image}} {{json .HostConfig}}"
|
||||
result = subprocess.run(
|
||||
["docker", "inspect", "--format", template, *ids],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
containers = []
|
||||
for line in result.stdout.splitlines():
|
||||
name, image, config = line.split(" ", 2)
|
||||
limits = json.loads(config)
|
||||
containers.append(
|
||||
dict(
|
||||
name=json.loads(name),
|
||||
image=json.loads(image),
|
||||
**{k: limits[k] for k in ("NanoCpus", "Memory", "CpusetCpus", "PortBindings")},
|
||||
)
|
||||
)
|
||||
return containers
|
||||
|
||||
|
||||
def provenance(folder, args, env):
|
||||
stamp = time.strftime("%FT%TZ", time.gmtime())
|
||||
metadata = {
|
||||
"date": stamp,
|
||||
"commit": args.commit,
|
||||
"project": args.project,
|
||||
"command": sys.argv,
|
||||
"api_image": env.get("API_IMAGE", "compose default"),
|
||||
"warmup_seconds": args.warmup,
|
||||
"duration_seconds": args.duration,
|
||||
"containers": args.deployment,
|
||||
}
|
||||
(folder / "metadata.json").write_text(json.dumps(metadata, ensure_ascii=False) + "\n")
|
||||
for path in folder.rglob("*"):
|
||||
if path.suffix in {".csv", ".txt"}:
|
||||
path.write_text(f"# date: {stamp} commit: {args.commit}\n" + path.read_text())
|
||||
elif path.name == "summary.json":
|
||||
data = dict(date=stamp, commit=args.commit, **json.loads(path.read_text()))
|
||||
path.write_text(json.dumps(data) + "\n")
|
||||
|
||||
|
||||
def attempt_folder(out, base, rate, repeat):
|
||||
name = f"{base['variant']}-{base['config']}_rate{rate}_rep{repeat}"
|
||||
attempt = 1
|
||||
while (Path(out) / f"{name}_attempt{attempt}").exists():
|
||||
attempt += 1
|
||||
folder = Path(out) / f"{name}_attempt{attempt}"
|
||||
folder.mkdir(parents=True)
|
||||
return folder
|
||||
|
||||
|
||||
def measure(folder, args, rate, env):
|
||||
subprocess.run([str(SCRIPTS / "pg-stats.sh"), "reset"], check=True)
|
||||
database = subprocess.run(
|
||||
[str(SCRIPTS / "pg-stats.sh"), "size"], check=True, capture_output=True, text=True
|
||||
).stdout.split(",")
|
||||
samplers = [
|
||||
sampler("docker-stats.sh", str(folder / "docker_stats.csv")),
|
||||
sampler("lb-stats.sh", str(folder / "lb_stats.csv")),
|
||||
sampler("pg-stats.sh", "activity", str(folder / "pg_activity.csv")),
|
||||
]
|
||||
load = dict(env, RATE=str(rate), WARMUP=str(args.warmup), DURATION=str(args.duration))
|
||||
began = time.time()
|
||||
try:
|
||||
code, started = run_k6(folder / "k6", load)
|
||||
finally:
|
||||
wall = time.time() - began
|
||||
for process in samplers:
|
||||
stop(process)
|
||||
subprocess.run(
|
||||
[str(SCRIPTS / "pg-stats.sh"), "statements", str(folder / "pg_statements.csv")], check=True
|
||||
)
|
||||
if started is None:
|
||||
raise SystemExit(f"k6 failed in setup, see {folder / 'k6/k6.txt'}")
|
||||
return code, started + args.warmup, database, wall
|
||||
|
||||
|
||||
def step(base, rate, repeat, args, env):
|
||||
folder = attempt_folder(args.out, base, rate, repeat)
|
||||
code, start, database, wall = measure(folder, args, rate, env)
|
||||
end = start + args.duration
|
||||
summary = folder / "k6/summary.json"
|
||||
metrics = k6_metrics(summary, args.duration)
|
||||
saturated = (
|
||||
metrics["failed_ratio"] > args.max_error_ratio
|
||||
or metrics["dropped_iterations"] > args.max_error_ratio * rate * args.duration
|
||||
or metrics["p95_ms"] > args.slo_p95_ms
|
||||
)
|
||||
row = dict(
|
||||
base,
|
||||
raw_dir=folder.name,
|
||||
rate=rate,
|
||||
repeat=repeat,
|
||||
k6_exit=code,
|
||||
saturated=saturated,
|
||||
**metrics,
|
||||
)
|
||||
row["started"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(start))
|
||||
row["db_mb"] = round(int(database[0]) / 2**20, 1)
|
||||
row["messages"] = int(database[1])
|
||||
row["p95_post_ms"] = trend(summary, "post_message")
|
||||
row["p95_get_ms"] = trend(summary, "get_history")
|
||||
row.update(docker_usage(folder / "docker_stats.csv", args.project, start, end))
|
||||
row.update(pg_usage(folder / "pg_activity.csv", start, end))
|
||||
row.update(lb_usage(folder / "lb_stats.csv", start, end))
|
||||
row["cpu_vm"] = vm_usage(folder / "vm_stat.csv", start, end)
|
||||
own = sum(row[f"cpu_{name}"] for name in ("api", "postgres", "lb", "valkey", "k6"))
|
||||
row["cpu_other"] = round(row["cpu_vm"] - own, 1)
|
||||
row["gap_s"] = round(gap(folder / "docker_stats.csv", start, end), 1)
|
||||
row["wall_s"] = round(wall, 1)
|
||||
row["disturbed"] = (
|
||||
row["cpu_other"] > args.max_other
|
||||
or row["gap_s"] > args.max_gap
|
||||
or wall > args.warmup + args.duration + args.max_overhead
|
||||
or row["cpu_k6"] >= 95 * float(env.get("K6_CPUS", "2"))
|
||||
or any(row[f"cpu_{name}"] <= 0 for name in ("vm", "api", "postgres", "k6"))
|
||||
or not rows(folder / "pg_activity.csv", start, end)
|
||||
or not rows(folder / "lb_stats.csv", start, end)
|
||||
)
|
||||
provenance(folder, args, env)
|
||||
if code or not metrics["requests"]:
|
||||
raise SystemExit(f"invalid k6 run: {folder}")
|
||||
print(json.dumps({k: row[k] for k in FIELDS}, ensure_ascii=False), flush=True)
|
||||
return row
|
||||
|
||||
|
||||
def rates(args, base):
|
||||
if args.rates:
|
||||
return [int(r) for r in args.rates.split(",")]
|
||||
factor, top = (float(v) for v in args.search.split(":"))
|
||||
value, values = args.start_per_cpu * base["replicas"] * base["cpus"], []
|
||||
while value <= top:
|
||||
values.append(int(round(value, -1)))
|
||||
value *= factor
|
||||
return values
|
||||
|
||||
|
||||
def arguments():
|
||||
parser = argparse.ArgumentParser(description="Track 1: replicas against throughput")
|
||||
parser.add_argument("--out", required=True)
|
||||
parser.add_argument("--configs", default="1x4,2x2,4x1", help="replicas x cpus per replica")
|
||||
parser.add_argument(
|
||||
"--variant",
|
||||
dest="variants",
|
||||
action="append",
|
||||
help="NAME[:KEY=VALUE,...]; several variants alternate per repeat",
|
||||
)
|
||||
parser.add_argument("--api-memory-total", type=int, default=2048, help="MiB for all replicas")
|
||||
parser.add_argument("--api-memory", type=int, default=0, help="MiB per replica")
|
||||
parser.add_argument("--workers", type=int, default=0, help="gunicorn workers, default = cpus")
|
||||
parser.add_argument("--pool", type=int, default=8, help="DB pool per worker")
|
||||
parser.add_argument("--conn-per-worker", type=int, default=32, help="LB maxconn per worker")
|
||||
parser.add_argument("--env", action="append", default=[], help="extra compose KEY=VALUE")
|
||||
parser.add_argument("--no-pin", dest="pin", action="store_false", help="do not pin CPUs")
|
||||
parser.add_argument("--rates", help="comma separated offered rates, rps")
|
||||
parser.add_argument("--search", default="1.5:8000", help="factor:max, from start-per-cpu")
|
||||
parser.add_argument("--start-per-cpu", type=float, default=100.0)
|
||||
parser.add_argument("--repeats", type=int, default=3)
|
||||
parser.add_argument("--first-repeat", type=int, default=1, help="number of the first repeat")
|
||||
parser.add_argument("--warmup", type=int, default=10)
|
||||
parser.add_argument("--duration", type=int, default=30)
|
||||
parser.add_argument("--pause", type=float, default=5.0)
|
||||
parser.add_argument("--slo-p95-ms", type=float, default=500.0)
|
||||
parser.add_argument("--max-error-ratio", type=float, default=0.01)
|
||||
parser.add_argument("--keep", action="store_true", help="leave the last layout running")
|
||||
parser.add_argument("--max-other", type=float, default=100.0, help="foreign VM CPU, %% core")
|
||||
parser.add_argument("--max-gap", type=float, default=10.0, help="sampling gap, s")
|
||||
parser.add_argument("--max-overhead", type=float, default=90.0, help="k6 run beyond load, s")
|
||||
parser.add_argument("--retries", type=int, default=3, help="reruns of a disturbed step")
|
||||
parser.add_argument("--quiet-timeout", type=float, default=1200.0)
|
||||
args = parser.parse_args()
|
||||
args.variants = args.variants or ["base"]
|
||||
if len(args.variants) > 1 and not args.rates:
|
||||
parser.error("several variants need explicit --rates")
|
||||
return args
|
||||
|
||||
|
||||
def block(args, output, config, variant, repeats):
|
||||
base, settings = layout(config, args, variant)
|
||||
current, streak = apply(base, settings, args.base_env, args.out), 0
|
||||
args.deployment = deployment(current)
|
||||
for rate in rates(args, base):
|
||||
results = []
|
||||
for repeat in repeats:
|
||||
for _ in range(args.retries + 1):
|
||||
row = step(base, rate, repeat, args, current)
|
||||
time.sleep(args.pause)
|
||||
if not row["disturbed"]:
|
||||
break
|
||||
args.rejected.writerow(row)
|
||||
wait_quiet(args)
|
||||
else:
|
||||
raise SystemExit(f"disturbed step exhausted retries: {row['raw_dir']}")
|
||||
results.append(row)
|
||||
output.writerows(results)
|
||||
streak = streak + 1 if not args.rates and all(r["saturated"] for r in results) else 0
|
||||
if streak == 2:
|
||||
break
|
||||
|
||||
|
||||
def series(args, output):
|
||||
every = range(args.first_repeat, args.first_repeat + args.repeats)
|
||||
configs = args.configs.split(",")
|
||||
if not args.rates:
|
||||
for config in configs:
|
||||
block(args, output, config, args.variants[0], every)
|
||||
return
|
||||
for repeat in every:
|
||||
for config in configs:
|
||||
for variant in args.variants:
|
||||
block(args, output, config, variant, [repeat])
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def table(path):
|
||||
fresh = not path.exists()
|
||||
with path.open("a", newline="", buffering=1) as handle:
|
||||
writer = csv.DictWriter(handle, fieldnames=FIELDS, extrasaction="ignore")
|
||||
if fresh:
|
||||
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||
handle.write(f"# date: {time.strftime('%FT%TZ', time.gmtime())} commit: {commit}\n")
|
||||
writer.writeheader()
|
||||
yield writer
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments()
|
||||
out = Path(args.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
args.project = json.loads(compose("config", "--format", "json"))["name"]
|
||||
args.commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
|
||||
args.base_env = dict(os.environ, **(PINNED if args.pin else {}))
|
||||
try:
|
||||
with table(out / "summary.csv") as writer, table(out / "disturbed.csv") as args.rejected:
|
||||
series(args, writer)
|
||||
finally:
|
||||
if not args.keep:
|
||||
compose("up", "-d", "--wait", "--wait-timeout", "180")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
[ -s secrets/grafana_admin_password ] || od -An -N24 -tx1 /dev/urandom | tr -d ' \n' > secrets/grafana_admin_password
|
||||
chmod 644 secrets/grafana_admin_password
|
||||
echo "secrets/grafana_admin_password is ready (value not printed)"
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
random() { od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; }
|
||||
put() {
|
||||
if [ ! -s "secrets/$1" ]; then
|
||||
printf '%s' "$2" > "secrets/$1"
|
||||
chmod 644 "secrets/$1"
|
||||
echo "создан secrets/$1"
|
||||
fi
|
||||
}
|
||||
put postgres_password "$(random)"
|
||||
put database_url "postgresql://messenger:$(cat secrets/postgres_password)@postgres:5432/messenger"
|
||||
put cursor_secret "$(random)"
|
||||
put valkey_password "$(random)"
|
||||
put valkey.conf "requirepass $(cat secrets/valkey_password)"
|
||||
put cache_url "redis://:$(cat secrets/valkey_password)@valkey:6379/0"
|
||||
put s3_root_user "root$(random | cut -c1-16)"
|
||||
put s3_root_password "$(random)"
|
||||
put s3_access_key_id "api$(random | cut -c1-16)"
|
||||
put s3_secret_access_key "$(random)"
|
||||
put s3_reconciler_access_key_id "rec$(random | cut -c1-16)"
|
||||
put s3_reconciler_secret_access_key "$(random)"
|
||||
[ -f .env ] || { cp .env.example .env; echo "создан .env из .env.example"; }
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
export COMPOSE_PROJECT_NAME=${COMPOSE_PROJECT_NAME:-mtusi2026lab7} NO_PROXY=localhost,127.0.0.1,::1
|
||||
make security-bootstrap
|
||||
mkdir -p evidence/security
|
||||
docker compose build api
|
||||
docker compose up -d postgres valkey s3 broker openbao healthtools prometheus loki tempo grafana otel-collector
|
||||
docker compose up -d s3-tls broker-tls valkey-tls prometheus-tls loki-tls tempo-tls grafana-tls otel-collector-tls
|
||||
python3 scripts/security_operator.py ensure
|
||||
docker compose run --rm --no-deps migrate
|
||||
python3 scripts/security_operator.py roles
|
||||
docker compose run --rm --no-deps s3-init
|
||||
docker compose up -d --no-deps api relay worker lb
|
||||
scripts/lb-wait.sh
|
||||
@@ -0,0 +1,107 @@
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
|
||||
STOP = Event()
|
||||
KEYS = {
|
||||
"DATABASE_URL",
|
||||
"CACHE_URL",
|
||||
"CURSOR_SECRET",
|
||||
"S3_ACCESS_KEY_ID",
|
||||
"S3_SECRET_ACCESS_KEY",
|
||||
"BROKER_URL",
|
||||
}
|
||||
|
||||
|
||||
def stopping(_signum, _frame):
|
||||
STOP.set()
|
||||
|
||||
|
||||
def request(path, payload=None, token=None):
|
||||
context = ssl.create_default_context(cafile="/run/pki/ca.crt")
|
||||
context.load_cert_chain("/run/pki/tls.crt", "/run/pki/tls.key")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
data = json.dumps(payload).encode() if payload is not None else None
|
||||
req = urllib.request.Request(os.environ["BAO_ADDR"] + "/v1/" + path, data=data, headers=headers)
|
||||
with urllib.request.urlopen(req, context=context, timeout=3) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def configuration():
|
||||
role = os.environ["SERVICE_ROLE"]
|
||||
auth = request("auth/cert/login", {"name": role})["auth"]
|
||||
data = request("secret/data/" + role, token=auth["client_token"])["data"]["data"]
|
||||
if not data or set(data) - KEYS or any(not isinstance(v, str) for v in data.values()):
|
||||
raise ValueError("Invalid scoped configuration")
|
||||
return data, time.monotonic() + min(auth["lease_duration"], 300)
|
||||
|
||||
|
||||
def terminate(process):
|
||||
if process and process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
try:
|
||||
process.wait(timeout=8)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
|
||||
|
||||
def main():
|
||||
signal.signal(signal.SIGTERM, stopping)
|
||||
signal.signal(signal.SIGINT, stopping)
|
||||
proxy = None
|
||||
child = None
|
||||
deadline = 0
|
||||
config = None
|
||||
next_refresh = 0
|
||||
bootstrap_deadline = time.monotonic() + 60
|
||||
try:
|
||||
cfg = "/etc/security/" + os.environ["SERVICE_ROLE"] + ".cfg"
|
||||
if Path(cfg).exists():
|
||||
proxy = subprocess.Popen(["haproxy", "-W", "-db", "-f", cfg], start_new_session=True)
|
||||
while not STOP.is_set():
|
||||
now = time.monotonic()
|
||||
if proxy and proxy.poll() is not None:
|
||||
return 1
|
||||
if now >= next_refresh:
|
||||
try:
|
||||
updated, deadline = configuration()
|
||||
if updated != config or child is None:
|
||||
terminate(child)
|
||||
env = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if k not in {name + "_FILE" for name in KEYS}
|
||||
}
|
||||
child = subprocess.Popen(
|
||||
sys.argv[1:], env={**env, **updated}, start_new_session=True
|
||||
)
|
||||
config = updated
|
||||
print("security.configuration.accepted", flush=True)
|
||||
except (OSError, ValueError, KeyError):
|
||||
print("security.configuration.unavailable", flush=True)
|
||||
next_refresh = now + 10
|
||||
if child and child.poll() is not None:
|
||||
return child.returncode
|
||||
if (child and now >= deadline) or (child is None and now >= bootstrap_deadline):
|
||||
print("security.authorization.expired", flush=True)
|
||||
return 1
|
||||
time.sleep(0.2)
|
||||
finally:
|
||||
terminate(child)
|
||||
terminate(proxy)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
import concurrent.futures
|
||||
import json
|
||||
import resource
|
||||
import secrets
|
||||
import statistics
|
||||
import time
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
password = secrets.token_urlsafe(24)
|
||||
encoded = hasher.hash(password)
|
||||
|
||||
|
||||
def measure(_):
|
||||
start = time.perf_counter()
|
||||
hasher.verify(encoded, password)
|
||||
return (time.perf_counter() - start) * 1000
|
||||
|
||||
|
||||
results = []
|
||||
for concurrency in [1, 2, 4]:
|
||||
start = time.perf_counter()
|
||||
cpu = time.process_time()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency) as pool:
|
||||
samples = sorted(pool.map(measure, range(100)))
|
||||
results.append(
|
||||
{
|
||||
"concurrency": concurrency,
|
||||
"samples": len(samples),
|
||||
"median_ms": round(statistics.median(samples), 3),
|
||||
"p95_ms": round(samples[94], 3),
|
||||
"cpu_ms_per_verify": round((time.process_time() - cpu) * 10, 3),
|
||||
"wall_seconds": round(time.perf_counter() - start, 3),
|
||||
"peak_rss_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
|
||||
}
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{"memory_kib": 19456, "iterations": 2, "parallelism": 1, "results": results}, indent=2
|
||||
)
|
||||
)
|
||||
@@ -0,0 +1,91 @@
|
||||
import importlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import security_operator as operator
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
Client = importlib.import_module("client").Client
|
||||
|
||||
|
||||
def execute(*args, data=None):
|
||||
result = subprocess.run(args, input=data, check=True, capture_output=True, text=True)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def comparison():
|
||||
data = operator.configuration("migrate")
|
||||
data.update(
|
||||
S3_ACCESS_KEY_ID=operator.secret("s3_root_user"),
|
||||
S3_SECRET_ACCESS_KEY=operator.secret("s3_root_password"),
|
||||
BROKER_URL="amqp://messenger-ops:"
|
||||
+ operator.secret("rabbitmq_ops_password")
|
||||
+ "@127.0.0.1:5672/messenger",
|
||||
)
|
||||
result = execute(
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"--entrypoint",
|
||||
"python",
|
||||
"security-audit",
|
||||
"/audit/privilege_compare.py",
|
||||
data=json.dumps(data),
|
||||
)
|
||||
(ROOT / "evidence/security/broad-rights.json").write_text(result)
|
||||
|
||||
|
||||
def leakage():
|
||||
client = Client("https://localhost:18443", str(ROOT / "secrets/pki/operator/ca.crt"))
|
||||
actor = client.user("leakcheck")
|
||||
material = [actor["token"], actor["registration"]["password"]]
|
||||
identities = []
|
||||
for path in (ROOT / "secrets").iterdir():
|
||||
if path.is_file():
|
||||
value = path.read_text().strip()
|
||||
if len(value) >= 12 and "\n" not in value:
|
||||
if path.name.endswith("_access_key_id") or path.name == "s3_root_user":
|
||||
identities.append(value)
|
||||
else:
|
||||
material.append(value)
|
||||
init = json.loads((operator.OPERATOR / "init.json").read_text())
|
||||
material.extend([init["root_token"], *init["keys_base64"]])
|
||||
time.sleep(12)
|
||||
logs = execute("docker", "compose", "logs", "--no-color")
|
||||
raw = execute(
|
||||
"docker", "compose", "run", "--rm", "--no-deps", "security-audit", "telemetry-dump"
|
||||
)
|
||||
telemetry = json.loads(raw)
|
||||
metrics = telemetry["metrics"]["data"]["result"]
|
||||
streams = telemetry["logs"]["data"]["result"]
|
||||
traces = telemetry["traces"].get("traces", [])
|
||||
leaks = sum(value in logs or value in raw for value in material)
|
||||
output = {
|
||||
"known_secret_values_checked": len(material),
|
||||
"nonsecret_s3_identity_matches": sum(value in logs or value in raw for value in identities),
|
||||
"compose_log_bytes": len(logs),
|
||||
"telemetry_bytes": len(raw),
|
||||
"metric_series": len(metrics),
|
||||
"log_streams": len(streams),
|
||||
"traces": len(traces),
|
||||
"exact_secret_matches": leaks,
|
||||
"passed": leaks == 0 and bool(metrics) and bool(streams) and bool(traces),
|
||||
}
|
||||
(ROOT / "evidence/security/telemetry-secrets.json").write_text(
|
||||
json.dumps(output, indent=2) + "\n"
|
||||
)
|
||||
if not output["passed"]:
|
||||
raise RuntimeError("Telemetry presence/leakage audit failed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
comparison()
|
||||
leakage()
|
||||
print("Broad permissions and telemetry leakage checks passed.")
|
||||
@@ -0,0 +1,72 @@
|
||||
import importlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
Client = importlib.import_module("client").Client
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.run(args, check=True, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
client = Client("https://localhost:18443", str(ROOT / "secrets/pki/operator/ca.crt"))
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
containers = json.loads(
|
||||
command("docker", "inspect", *command("docker", "compose", "ps", "-q", "api").split())
|
||||
)
|
||||
results = []
|
||||
for item in containers:
|
||||
target = item["Config"]["Hostname"]
|
||||
attachment, content = client.attachment(alice, chat)
|
||||
client.wait_ready(alice, attachment)
|
||||
before = client.message(alice, chat, "Before replica stop")["json"]
|
||||
started = time.monotonic()
|
||||
failures = 0
|
||||
success = 0
|
||||
instances = set()
|
||||
try:
|
||||
command("docker", "stop", "-t", "7", item["Id"])
|
||||
deadline = time.monotonic() + 20
|
||||
first = None
|
||||
while success < 30 and time.monotonic() < deadline:
|
||||
try:
|
||||
response = client.message(alice, chat, "After replica stop")
|
||||
success += 1
|
||||
instances.add(response["headers"]["X-Instance-Id"])
|
||||
first = first or time.monotonic() - started
|
||||
except AssertionError:
|
||||
failures += 1
|
||||
time.sleep(0.2)
|
||||
if success != 30 or target in instances or len(instances) != 1:
|
||||
raise RuntimeError("Replica failover did not isolate stopped instance")
|
||||
data = client.call(
|
||||
"GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=alice, schema="MessagePage"
|
||||
)["json"]
|
||||
if before["id"] not in [row["id"] for row in data["items"]]:
|
||||
raise RuntimeError("Confirmed message lost")
|
||||
if (
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=alice)[
|
||||
"bytes"
|
||||
]
|
||||
!= content
|
||||
):
|
||||
raise RuntimeError("Attachment changed")
|
||||
results.append(
|
||||
{
|
||||
"target": target,
|
||||
"successful_writes": success,
|
||||
"failed_attempts": failures,
|
||||
"first_recovery_seconds": round(first, 3),
|
||||
"message_attachment_session_preserved": True,
|
||||
}
|
||||
)
|
||||
finally:
|
||||
command("docker", "start", item["Id"])
|
||||
command("scripts/lb-wait.sh")
|
||||
print(json.dumps(results, indent=2))
|
||||
(ROOT / "evidence/security/failover-each.json").write_text(json.dumps(results, indent=2) + "\n")
|
||||
@@ -0,0 +1,56 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.run(args, capture_output=True, text=True, check=True).stdout
|
||||
|
||||
|
||||
def inventory():
|
||||
identifiers = command("docker", "compose", "ps", "-q").split()
|
||||
containers = json.loads(command("docker", "inspect", *identifiers))
|
||||
rows = []
|
||||
for item in containers:
|
||||
config, host = item["Config"], item["HostConfig"]
|
||||
service = config["Labels"]["com.docker.compose.service"]
|
||||
mounts = item["Mounts"]
|
||||
base = (
|
||||
not host["Privileged"]
|
||||
and host["NetworkMode"] != "host"
|
||||
and not any("docker.sock" in mount["Source"] for mount in mounts)
|
||||
)
|
||||
app = service in ["api", "relay", "worker"]
|
||||
restricted = not app or (
|
||||
config["User"] == "10001:10001"
|
||||
and host["ReadonlyRootfs"]
|
||||
and "ALL" in host["CapDrop"]
|
||||
and "no-new-privileges:true" in host["SecurityOpt"]
|
||||
and host["Memory"] > 0
|
||||
and host["NanoCpus"] > 0
|
||||
)
|
||||
own_keys = not app or all(
|
||||
"/secrets/pki/" + service in mount["Source"]
|
||||
for mount in mounts
|
||||
if "/secrets/" in mount["Source"]
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"service": service,
|
||||
"user": config["User"],
|
||||
"readonly": host["ReadonlyRootfs"],
|
||||
"memory_bytes": host["Memory"],
|
||||
"cpu_quota": host["NanoCpus"] / 1e9,
|
||||
"only_own_keys": own_keys,
|
||||
"passed": base and restricted and own_keys,
|
||||
}
|
||||
)
|
||||
return {"containers": rows, "passed": all(row["passed"] for row in rows)}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = inventory()
|
||||
print(json.dumps(result, indent=2))
|
||||
raise SystemExit(0 if result["passed"] else 1)
|
||||
@@ -0,0 +1,105 @@
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import security_operator as operator
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
Client = importlib.import_module("client").Client
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args], capture_output=True, text=True, check=True
|
||||
).stdout
|
||||
|
||||
|
||||
def lifecycle():
|
||||
client = Client("https://localhost:18443", str(ROOT / "secrets/pki/operator/ca.crt"))
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
original = client.message(alice, chat, "Persist through sealed Bao")["json"]
|
||||
start = time.monotonic()
|
||||
operator.call("sys/seal", {}, operator.operator_token())
|
||||
deadline = start + 85
|
||||
stopped = False
|
||||
try:
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
except AssertionError:
|
||||
stopped = True
|
||||
break
|
||||
time.sleep(1)
|
||||
if not stopped:
|
||||
raise RuntimeError("API continued after bounded authorization expired")
|
||||
outage = time.monotonic() - start
|
||||
compose("restart", "openbao")
|
||||
time.sleep(3)
|
||||
if not operator.call("sys/seal-status")["sealed"]:
|
||||
raise RuntimeError("Bao automatically unsealed after restart")
|
||||
recovery = time.monotonic()
|
||||
finally:
|
||||
operator.unseal()
|
||||
subprocess.run(["scripts/lb-wait.sh"], check=True, capture_output=True)
|
||||
client.message(alice, chat, "Existing session after unseal")
|
||||
messages = client.call(
|
||||
"GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=alice, schema="MessagePage"
|
||||
)["json"]
|
||||
if original["id"] not in [item["id"] for item in messages["items"]]:
|
||||
raise RuntimeError("Data lost after OpenBao restart")
|
||||
return {
|
||||
"sealed_api_stop_seconds": round(outage, 3),
|
||||
"unseal_recovery_seconds": round(time.monotonic() - recovery, 3),
|
||||
"bao_restart_stays_sealed": True,
|
||||
"persistent_configuration": True,
|
||||
"session_and_message_preserved": True,
|
||||
}
|
||||
|
||||
|
||||
def login_limit():
|
||||
operator.sql("DELETE FROM login_budget;")
|
||||
|
||||
def attempt(_):
|
||||
client = Client("https://localhost:18443", str(ROOT / "secrets/pki/operator/ca.crt"))
|
||||
return client.call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
expected=[401, 429],
|
||||
headers={
|
||||
"Authorization": "Basic " + base64.b64encode(b"nonexistent:incorrect").decode()
|
||||
},
|
||||
)
|
||||
|
||||
while time.time() % 10 > 2:
|
||||
time.sleep(0.1)
|
||||
start = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=30) as pool:
|
||||
responses = list(pool.map(attempt, range(30)))
|
||||
statuses = [item["status"] for item in responses]
|
||||
instances = {item["headers"]["X-Instance-Id"] for item in responses}
|
||||
if statuses.count(401) != 20 or statuses.count(429) != 10 or len(instances) != 2:
|
||||
raise RuntimeError("Shared login budget did not match configured limit")
|
||||
if not all(item["headers"].get("Retry-After") for item in responses if item["status"] == 429):
|
||||
raise RuntimeError("Retry-After missing")
|
||||
return {
|
||||
"attempts": 30,
|
||||
"kdf_admitted": 20,
|
||||
"rate_limited": 10,
|
||||
"instances": len(instances),
|
||||
"retry_after_present": True,
|
||||
"elapsed_seconds": round(time.monotonic() - start, 3),
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.chdir(ROOT)
|
||||
result = {"lifecycle": lifecycle(), "login_limit": login_limit()}
|
||||
print(json.dumps(result, indent=2))
|
||||
(ROOT / "evidence/security/lifecycle.json").write_text(json.dumps(result, indent=2) + "\n")
|
||||
@@ -0,0 +1,260 @@
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OPERATOR = Path(
|
||||
os.environ.get("LAB7_OPERATOR_DIR", str(Path.home() / ".local/share/mtusi2026lab7/operator"))
|
||||
)
|
||||
ROLES = ("api", "worker", "relay", "migrate", "reconciler")
|
||||
|
||||
|
||||
def secret(name):
|
||||
return (ROOT / "secrets" / name).read_text().strip()
|
||||
|
||||
|
||||
def call(path, data=None, token=None, method=None):
|
||||
ctx = ssl.create_default_context(cafile=str(ROOT / "secrets/pki/operator/ca.crt"))
|
||||
ctx.load_cert_chain(
|
||||
ROOT / "secrets/pki/operator/tls.crt", ROOT / "secrets/pki/operator/tls.key"
|
||||
)
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = urllib.request.Request(
|
||||
os.environ.get("BAO_OPERATOR_URL", "https://localhost:28200") + "/v1/" + path,
|
||||
data=json.dumps(data).encode() if data is not None else None,
|
||||
headers=headers,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=ctx, timeout=10) as response:
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def operator_token():
|
||||
return json.loads((OPERATOR / "init.json").read_text())["root_token"]
|
||||
|
||||
|
||||
def unseal():
|
||||
data = json.loads((OPERATOR / "init.json").read_text())
|
||||
for key in data["keys_base64"][:2]:
|
||||
call("sys/unseal", {"key": key})
|
||||
print("OpenBao unsealed by operator; shares not displayed.")
|
||||
|
||||
|
||||
def ensure():
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
initialized = call("sys/init")["initialized"]
|
||||
break
|
||||
except OSError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(1)
|
||||
if not initialized:
|
||||
initialize()
|
||||
elif call("sys/seal-status")["sealed"]:
|
||||
raise SystemExit("OpenBao sealed: operator must run make security-unseal.")
|
||||
|
||||
|
||||
def initialize():
|
||||
if not call("sys/init")["initialized"]:
|
||||
data = call("sys/init", {"secret_shares": 3, "secret_threshold": 2})
|
||||
path = OPERATOR / "init.json"
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "w") as file:
|
||||
json.dump(data, file)
|
||||
unseal()
|
||||
token = operator_token()
|
||||
for path, payload in [
|
||||
("sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}),
|
||||
("sys/auth/cert", {"type": "cert"}),
|
||||
("sys/audit/file", {"type": "file", "options": {"file_path": "/bao/data/audit.json"}}),
|
||||
]:
|
||||
try:
|
||||
call(path, payload, token)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 400:
|
||||
raise
|
||||
for role in ROLES:
|
||||
configure(role)
|
||||
|
||||
|
||||
def configuration(role):
|
||||
dbrole = "messenger" if role == "migrate" else "messenger_" + role
|
||||
password = secret("postgres_password" if role == "migrate" else "db_" + role)
|
||||
data = {"DATABASE_URL": f"postgresql://{dbrole}:{password}@postgres:5432/messenger"}
|
||||
if role == "api":
|
||||
data.update(
|
||||
CACHE_URL="redis://api:" + secret("valkey_password") + "@127.0.0.1:6379/0",
|
||||
CURSOR_SECRET=secret("cursor_secret"),
|
||||
)
|
||||
if role != "migrate":
|
||||
keyrole = {"worker": "worker_", "relay": "relay_", "reconciler": "reconciler_"}.get(
|
||||
role, ""
|
||||
)
|
||||
data.update(
|
||||
S3_ACCESS_KEY_ID=secret("s3_" + keyrole + "access_key_id"),
|
||||
S3_SECRET_ACCESS_KEY=secret("s3_" + keyrole + "secret_access_key"),
|
||||
)
|
||||
if role in ["worker", "relay"]:
|
||||
brokerrole = "worker" if role == "worker" else "api"
|
||||
data["BROKER_URL"] = (
|
||||
"amqp://messenger-"
|
||||
+ brokerrole
|
||||
+ ":"
|
||||
+ secret("rabbitmq_" + brokerrole + "_password")
|
||||
+ "@127.0.0.1:5672/messenger"
|
||||
)
|
||||
return data
|
||||
|
||||
|
||||
def configure(role):
|
||||
token = operator_token()
|
||||
policy = f'path "secret/data/{role}" {{ capabilities = ["read"] }}\n'
|
||||
(ROOT / f"infra/openbao/{role}.hcl").write_text(policy)
|
||||
call("sys/policies/acl/" + role, {"policy": policy}, token)
|
||||
call(
|
||||
"auth/cert/certs/" + role,
|
||||
{
|
||||
"certificate": (ROOT / f"secrets/pki/{role}/tls.crt").read_text(),
|
||||
"allowed_common_names": [role],
|
||||
"token_policies": [role],
|
||||
"token_no_default_policy": True,
|
||||
"token_ttl": 60,
|
||||
"token_max_ttl": 300,
|
||||
},
|
||||
token,
|
||||
)
|
||||
call("secret/data/" + role, {"data": configuration(role)}, token)
|
||||
|
||||
|
||||
def passwords():
|
||||
for suffix in ["access_key_id", "secret_access_key"]:
|
||||
path = ROOT / "secrets" / ("s3_relay_" + suffix)
|
||||
if not path.exists():
|
||||
path.write_text("relay" + secrets.token_hex(16))
|
||||
path.chmod(0o644)
|
||||
for role in ROLES:
|
||||
if role == "migrate":
|
||||
continue
|
||||
path = ROOT / "secrets" / ("db_" + role)
|
||||
if not path.exists():
|
||||
path.write_text(secrets.token_hex(24))
|
||||
path.chmod(0o600)
|
||||
(ROOT / "secrets/valkey.conf").write_text(
|
||||
"user default off\nuser api on >"
|
||||
+ secret("valkey_password")
|
||||
+ " ~session:* ~revoked:* +ping +get +set +del +exists +ttl +pttl +expire +pexpire"
|
||||
" +eval +evalsha +script|load\n"
|
||||
)
|
||||
(ROOT / "secrets/valkey.conf").chmod(0o644)
|
||||
|
||||
|
||||
def sql(text):
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
"-q",
|
||||
],
|
||||
input=text.encode(),
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def rotate_worker(password):
|
||||
if len(password) != 48 or any(char not in "0123456789abcdef" for char in password):
|
||||
raise ValueError("Expected generated 24-byte hex password")
|
||||
statement = f"ALTER ROLE messenger_worker PASSWORD '{password}'"
|
||||
sql(statement)
|
||||
sql(
|
||||
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
|
||||
"WHERE usename='messenger_worker' AND pid <> pg_backend_pid();"
|
||||
)
|
||||
|
||||
|
||||
def roles():
|
||||
for role in ROLES:
|
||||
if role == "migrate":
|
||||
continue
|
||||
name = "messenger_" + role
|
||||
sql(
|
||||
"DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='"
|
||||
+ name
|
||||
+ "') THEN CREATE ROLE "
|
||||
+ name
|
||||
+ " LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION;"
|
||||
" END IF; END $$; ALTER ROLE "
|
||||
+ name
|
||||
+ " PASSWORD '"
|
||||
+ secret("db_" + role)
|
||||
+ "'; GRANT CONNECT ON DATABASE messenger TO "
|
||||
+ name
|
||||
+ "; GRANT USAGE ON SCHEMA public TO "
|
||||
+ name
|
||||
+ ";"
|
||||
)
|
||||
sql(
|
||||
"REVOKE CREATE ON SCHEMA public FROM PUBLIC;"
|
||||
" REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC;"
|
||||
" GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO messenger_api;"
|
||||
)
|
||||
for role in ["worker", "relay"]:
|
||||
sql(
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON attachments, "
|
||||
"attachment_variants, jobs, outbox, "
|
||||
"job_events TO messenger_" + role + ";"
|
||||
)
|
||||
sql(
|
||||
"GRANT SELECT ON ALL TABLES IN SCHEMA public TO messenger_reconciler;"
|
||||
" GRANT UPDATE, DELETE ON attachments TO messenger_reconciler;"
|
||||
)
|
||||
print("Scoped database roles applied.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"action",
|
||||
choices=["init", "unseal", "configure", "passwords", "roles", "seal", "revoke", "ensure"],
|
||||
)
|
||||
parser.add_argument("--role", choices=ROLES, default="worker")
|
||||
args = parser.parse_args()
|
||||
os.chdir(ROOT)
|
||||
if args.action == "ensure":
|
||||
ensure()
|
||||
elif args.action == "init":
|
||||
initialize()
|
||||
elif args.action == "unseal":
|
||||
unseal()
|
||||
elif args.action == "configure":
|
||||
configure(args.role)
|
||||
elif args.action == "passwords":
|
||||
passwords()
|
||||
elif args.action == "roles":
|
||||
roles()
|
||||
elif args.action == "seal":
|
||||
call("sys/seal", {}, operator_token())
|
||||
elif args.action == "revoke":
|
||||
call("auth/cert/certs/" + args.role, token=operator_token(), method="DELETE")
|
||||
@@ -0,0 +1,348 @@
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlencode, urlsplit, urlunsplit
|
||||
|
||||
import aio_pika
|
||||
import redis.asyncio as redis
|
||||
from botocore.auth import S3SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
PKI = Path("/audit-pki")
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def record(name, passed, **details):
|
||||
RESULTS.append({"test": name, "passed": bool(passed), **details})
|
||||
|
||||
|
||||
def context(role=None, trusted=True):
|
||||
ctx = ssl.create_default_context(cafile=str(PKI / "operator/ca.crt") if trusted else None)
|
||||
if role:
|
||||
ctx.load_cert_chain(PKI / role / "tls.crt", PKI / role / "tls.key")
|
||||
return ctx
|
||||
|
||||
|
||||
def tls(host, port, role, payload, *, hostname=None, trusted=True):
|
||||
try:
|
||||
with (
|
||||
socket.create_connection((host, port), timeout=3) as raw,
|
||||
context(role, trusted).wrap_socket(raw, server_hostname=hostname or host) as stream,
|
||||
):
|
||||
stream.sendall(payload)
|
||||
return bool(stream.recv(2048))
|
||||
except (OSError, ssl.SSLError):
|
||||
return False
|
||||
|
||||
|
||||
def http(role, url, payload=None, token=None, *, method=None, headers=None):
|
||||
head = {"Content-Type": "application/json", **(headers or {})}
|
||||
if token:
|
||||
head["X-Vault-Token"] = token
|
||||
data = json.dumps(payload).encode() if isinstance(payload, dict) else payload
|
||||
req = urllib.request.Request(url, data=data, headers=head, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(req, context=context(role), timeout=5) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
|
||||
|
||||
def credentials(role):
|
||||
status, body = http(role, "https://openbao:8200/v1/auth/cert/login", {"name": role})
|
||||
if status != 200:
|
||||
raise RuntimeError("Service authentication failed")
|
||||
token = json.loads(body)["auth"]["client_token"]
|
||||
status, body = http(role, "https://openbao:8200/v1/secret/data/" + role, token=token)
|
||||
if status != 200:
|
||||
raise RuntimeError("Scoped configuration unavailable")
|
||||
return token, json.loads(body)["data"]["data"]
|
||||
|
||||
|
||||
def transport_matrix():
|
||||
targets = [
|
||||
("api", 8443, "lb"),
|
||||
("s3", 9443, "api"),
|
||||
("broker", 5671, "worker"),
|
||||
("otel-collector", 44318, "api"),
|
||||
("prometheus", 9443, "grafana"),
|
||||
("loki", 9443, "grafana"),
|
||||
("tempo", 9443, "grafana"),
|
||||
("tempo", 44318, "otel-collector"),
|
||||
("grafana", 9443, "operator"),
|
||||
("valkey", 6380, "api"),
|
||||
]
|
||||
for host, port, role in targets:
|
||||
payload = (
|
||||
b"AMQP\x00\x00\x09\x01"
|
||||
if host == "broker"
|
||||
else b"*1\r\n$4\r\nPING\r\n"
|
||||
if host == "valkey"
|
||||
else b"GET / HTTP/1.1\r\nHost: " + host.encode() + b"\r\nConnection: close\r\n\r\n"
|
||||
)
|
||||
for identity, expected in [
|
||||
(role, True),
|
||||
(None, False),
|
||||
("outsider", False),
|
||||
("foreign", False),
|
||||
]:
|
||||
observed = tls(host, port, identity, payload)
|
||||
record(f"mtls:{host}:{port}:{identity}", observed == expected)
|
||||
record(
|
||||
f"hostname:{host}:{port}",
|
||||
not tls(host, port, role, payload, hostname="incorrect.invalid"),
|
||||
)
|
||||
for host, port in [
|
||||
("api", 8080),
|
||||
("s3", 9000),
|
||||
("broker", 5672),
|
||||
("broker", 15672),
|
||||
("broker", 15692),
|
||||
("broker", 25672),
|
||||
("broker", 4369),
|
||||
("valkey", 6379),
|
||||
("otel-collector", 4318),
|
||||
("otel-collector", 8888),
|
||||
("otel-collector", 13133),
|
||||
("prometheus", 9090),
|
||||
("loki", 3100),
|
||||
("loki", 9096),
|
||||
("tempo", 3200),
|
||||
("tempo", 4318),
|
||||
("tempo", 9095),
|
||||
("grafana", 3000),
|
||||
]:
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=1):
|
||||
accessible = True
|
||||
except OSError:
|
||||
accessible = False
|
||||
record(f"plaintext-closed:{host}:{port}", not accessible)
|
||||
for role in ["api", "worker", "relay"]:
|
||||
token, _ = credentials(role)
|
||||
own = http(role, "https://openbao:8200/v1/secret/data/" + role, token=token)[0]
|
||||
other = http(role, "https://openbao:8200/v1/secret/data/migrate", token=token)[0]
|
||||
admin = http(
|
||||
role,
|
||||
"https://openbao:8200/v1/sys/policies/acl/forbidden",
|
||||
{"policy": 'path "*" { capabilities=["sudo"] }'},
|
||||
token,
|
||||
)[0]
|
||||
record(
|
||||
"bao-scope:" + role,
|
||||
own == 200 and other == 403 and admin == 403,
|
||||
own=own,
|
||||
foreign=other,
|
||||
admin=admin,
|
||||
)
|
||||
|
||||
|
||||
def signed_s3(data, method, key, body=b"", *, role="worker"):
|
||||
url = "https://s3:9443/messenger-attachments/" + key
|
||||
request = AWSRequest(method=method, url=url, data=body)
|
||||
S3SigV4Auth(
|
||||
Credentials(data["S3_ACCESS_KEY_ID"], data["S3_SECRET_ACCESS_KEY"]), "s3", "us-east-1"
|
||||
).add_auth(request)
|
||||
return http(role, url, body, method=method, headers=dict(request.headers))[0]
|
||||
|
||||
|
||||
async def worker_scope():
|
||||
_, data = credentials("worker")
|
||||
dsn = data["DATABASE_URL"].replace("postgresql://", "postgresql+asyncpg://")
|
||||
engine = create_async_engine(dsn, connect_args={"ssl": context()}, hide_parameters=True)
|
||||
probes = [
|
||||
("jobs-readable", "SELECT count(*) FROM jobs", True),
|
||||
("users-denied", "SELECT count(*) FROM users", False),
|
||||
("sessions-denied", "SELECT count(*) FROM sessions", False),
|
||||
("ddl-denied", "CREATE TABLE security_escape (id integer)", False),
|
||||
]
|
||||
for name, sql, expected in probes:
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text(sql))
|
||||
await connection.rollback()
|
||||
success = True
|
||||
except DBAPIError:
|
||||
success = False
|
||||
record("worker-db:" + name, success == expected)
|
||||
await engine.dispose()
|
||||
for method, key, expected in [
|
||||
("PUT", "variants/security-probe", 200),
|
||||
("GET", "variants/security-probe", 200),
|
||||
("PUT", "staging/security-probe", 403),
|
||||
("GET", "private/security-probe", 403),
|
||||
("DELETE", "variants/security-probe", 403),
|
||||
]:
|
||||
status = signed_s3(data, method, key, b"probe" if method == "PUT" else b"")
|
||||
record("worker-s3:" + method + ":" + key, status == expected, status=status)
|
||||
parsed = urlsplit(data["BROKER_URL"])
|
||||
url = urlunsplit(
|
||||
("amqps", parsed.netloc.replace("127.0.0.1:5672", "broker:5671"), parsed.path, "", "")
|
||||
)
|
||||
conn = await aio_pika.connect(url, ssl_context=context("worker"), timeout=5)
|
||||
try:
|
||||
channel = await conn.channel()
|
||||
queue = await channel.get_queue("attachments.process")
|
||||
message = await queue.get(fail=False)
|
||||
if message:
|
||||
await message.nack(requeue=True)
|
||||
record("worker-queue:consume", True)
|
||||
channel = await conn.channel()
|
||||
try:
|
||||
exchange = await channel.get_exchange("attachments", ensure=False)
|
||||
await exchange.publish(aio_pika.Message(b"forbidden"), routing_key="process")
|
||||
denied = False
|
||||
except aio_pika.exceptions.AMQPException:
|
||||
denied = True
|
||||
record("worker-queue:publish-denied", denied)
|
||||
channel = await conn.channel()
|
||||
try:
|
||||
await channel.declare_queue("security-escape")
|
||||
denied = False
|
||||
except aio_pika.exceptions.AMQPException:
|
||||
denied = True
|
||||
record("worker-queue:configure-denied", denied)
|
||||
finally:
|
||||
await conn.close()
|
||||
|
||||
|
||||
async def dependency_acl():
|
||||
_, data = credentials("api")
|
||||
cache = redis.from_url(
|
||||
data["CACHE_URL"].replace("redis://", "rediss://").replace("127.0.0.1:6379", "valkey:6380"),
|
||||
ssl_ca_certs=str(PKI / "api/ca.crt"),
|
||||
ssl_certfile=str(PKI / "api/tls.crt"),
|
||||
ssl_keyfile=str(PKI / "api/tls.key"),
|
||||
socket_timeout=3,
|
||||
)
|
||||
await cache.set("session:security-probe", "probe", ex=30)
|
||||
record("valkey:own-prefix", await cache.get("session:security-probe") == b"probe")
|
||||
for name, action in [
|
||||
("foreign-prefix", lambda: cache.get("foreign:security-probe")),
|
||||
("admin", lambda: cache.config_get("*")),
|
||||
]:
|
||||
try:
|
||||
await action()
|
||||
denied = False
|
||||
except redis.ResponseError:
|
||||
denied = True
|
||||
record("valkey:" + name + "-denied", denied)
|
||||
await cache.delete("session:security-probe")
|
||||
await cache.aclose()
|
||||
dsn = data["DATABASE_URL"].replace("postgresql://", "postgresql+asyncpg://")
|
||||
for label, ssl_mode in [("plaintext", False), ("untrusted-ca", ssl.create_default_context())]:
|
||||
engine = create_async_engine(dsn, connect_args={"ssl": ssl_mode}, hide_parameters=True)
|
||||
try:
|
||||
async with engine.connect():
|
||||
pass
|
||||
denied = False
|
||||
except Exception:
|
||||
denied = True
|
||||
finally:
|
||||
await engine.dispose()
|
||||
record("postgres:" + label + "-denied", denied)
|
||||
|
||||
|
||||
def telemetry():
|
||||
for host, path in [
|
||||
("prometheus", "/api/v1/query?query=up"),
|
||||
("loki", "/loki/api/v1/labels"),
|
||||
("tempo", "/api/search?limit=10"),
|
||||
]:
|
||||
status, body = http("grafana", "https://" + host + ":9443" + path)
|
||||
record("telemetry-query:" + host, status == 200, bytes=len(body))
|
||||
for host, path in [("prometheus", "/api/v1/query?query=up"), ("loki", "/loki/api/v1/labels")]:
|
||||
status, _ = http("otel-collector", "https://" + host + ":9443" + path)
|
||||
record("collector-read-denied:" + host, status == 403)
|
||||
for host, path in [("prometheus", "/api/v1/otlp/v1/metrics"), ("loki", "/otlp/v1/logs")]:
|
||||
status, _ = http("grafana", "https://" + host + ":9443" + path, b"", method="POST")
|
||||
record("grafana-write-denied:" + host, status == 403)
|
||||
for address in sorted(
|
||||
{item[4][0] for item in socket.getaddrinfo("api", 8443, type=socket.SOCK_STREAM)}
|
||||
):
|
||||
payload = b"GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
|
||||
for role, expected in [
|
||||
("lb", True),
|
||||
(None, False),
|
||||
("outsider", False),
|
||||
("foreign", False),
|
||||
]:
|
||||
record(
|
||||
"api-replica:" + address + ":" + str(role),
|
||||
tls(address, 8443, role, payload, hostname="api") == expected,
|
||||
)
|
||||
|
||||
|
||||
def telemetry_dump():
|
||||
queries = {
|
||||
"metrics": "https://prometheus:9443/api/v1/query?"
|
||||
+ urlencode({"query": '{__name__=~"http_server.*|messenger.*"}'}),
|
||||
"logs": "https://loki:9443/loki/api/v1/query_range?"
|
||||
+ urlencode({"query": '{service_name=~"messenger-.+"}', "limit": 1000}),
|
||||
"traces": "https://tempo:9443/api/search?limit=20",
|
||||
}
|
||||
data = {name: json.loads(http("operator", url)[1]) for name, url in queries.items()}
|
||||
data["trace_details"] = [
|
||||
json.loads(http("operator", "https://tempo:9443/api/traces/" + trace["traceID"])[1])
|
||||
for trace in data["traces"].get("traces", [])
|
||||
]
|
||||
print(json.dumps(data))
|
||||
|
||||
|
||||
async def revoked():
|
||||
data = json.loads((PKI / "previous-worker/credentials.json").read_text())
|
||||
for host, port, payload in [
|
||||
("broker", 5671, b"AMQP\x00\x00\x09\x01"),
|
||||
("s3", 9443, b"GET / HTTP/1.0\r\n\r\n"),
|
||||
("otel-collector", 44318, b"GET / HTTP/1.0\r\n\r\n"),
|
||||
]:
|
||||
record("revoked-cert:" + host, not tls(host, port, "previous-worker", payload))
|
||||
status, _ = http(
|
||||
"previous-worker", "https://openbao:8200/v1/auth/cert/login", {"name": "worker"}
|
||||
)
|
||||
record("revoked-bao-cert", status in {400, 403}, status=status)
|
||||
engine = create_async_engine(
|
||||
data["DATABASE_URL"].replace("postgresql://", "postgresql+asyncpg://"),
|
||||
connect_args={"ssl": context()},
|
||||
hide_parameters=True,
|
||||
)
|
||||
try:
|
||||
async with engine.connect():
|
||||
pass
|
||||
denied = False
|
||||
except Exception:
|
||||
denied = True
|
||||
finally:
|
||||
await engine.dispose()
|
||||
record("rotated-db-password", denied)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "telemetry-dump" in sys.argv:
|
||||
telemetry_dump()
|
||||
raise SystemExit(0)
|
||||
if "revoked" in sys.argv:
|
||||
asyncio.run(revoked())
|
||||
print(
|
||||
json.dumps(
|
||||
{"checks": RESULTS, "passed": all(item["passed"] for item in RESULTS)}, indent=2
|
||||
)
|
||||
)
|
||||
raise SystemExit(0 if all(item["passed"] for item in RESULTS) else 1)
|
||||
transport_matrix()
|
||||
telemetry()
|
||||
asyncio.run(worker_scope())
|
||||
asyncio.run(dependency_acl())
|
||||
print(
|
||||
json.dumps({"checks": RESULTS, "passed": all(item["passed"] for item in RESULTS)}, indent=2)
|
||||
)
|
||||
raise SystemExit(0 if all(item["passed"] for item in RESULTS) else 1)
|
||||
@@ -0,0 +1,59 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\set big '''00000000-0000-7000-8000-00000000c001'''
|
||||
\set cursor_at '''2026-01-01T02:46:40Z'''
|
||||
\set cursor_id '''00000000-0000-7000-8001-000000002710'''
|
||||
|
||||
PREPARE history_first (uuid, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2;
|
||||
|
||||
PREPARE history_after (uuid, timestamptz, uuid, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||
ORDER BY created_at, id
|
||||
LIMIT $4;
|
||||
|
||||
PREPARE history_offset (uuid, int, int) AS
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
ORDER BY created_at, id
|
||||
LIMIT $2 OFFSET $3;
|
||||
|
||||
SELECT count(*) AS chat_messages FROM messages WHERE chat_id = :big;
|
||||
SELECT count(*) AS all_messages FROM messages;
|
||||
SELECT pg_size_pretty(pg_relation_size('messages_history_idx')) AS history_index_size;
|
||||
|
||||
\echo '== Первая страница, limit=50 (запрос HISTORY_FIRST приложения, LIMIT limit+1)'
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_first(:big, 51);
|
||||
|
||||
\echo '== Глубокая страница: keyset после 10 000-го сообщения (запрос HISTORY_AFTER приложения)'
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_after(:big, :cursor_at, :cursor_id, 51);
|
||||
|
||||
\echo '== Та же глубокая страница через OFFSET 10000 (не используется приложением, для сравнения)'
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_offset(:big, 51, 10000);
|
||||
|
||||
\echo '== Проверка: keyset и OFFSET возвращают одну и ту же страницу'
|
||||
SELECT (
|
||||
SELECT array_agg(id ORDER BY created_at, id) FROM (
|
||||
SELECT id, created_at FROM messages
|
||||
WHERE chat_id = :big AND (created_at, id) > (:cursor_at, :cursor_id)
|
||||
ORDER BY created_at, id LIMIT 51
|
||||
) AS keyset
|
||||
) = (
|
||||
SELECT array_agg(id ORDER BY created_at, id) FROM (
|
||||
SELECT id, created_at FROM messages
|
||||
WHERE chat_id = :big
|
||||
ORDER BY created_at, id LIMIT 51 OFFSET 10000
|
||||
) AS skipped
|
||||
) AS same_page;
|
||||
|
||||
\echo '== Контрольный план без индекса истории (DROP INDEX внутри транзакции, затем ROLLBACK)'
|
||||
BEGIN;
|
||||
DROP INDEX messages_history_idx;
|
||||
EXPLAIN (ANALYZE, BUFFERS) EXECUTE history_after(:big, :cursor_at, :cursor_id, 51);
|
||||
ROLLBACK;
|
||||
@@ -0,0 +1,40 @@
|
||||
\set ON_ERROR_STOP on
|
||||
\set author '''00000000-0000-7000-8000-00000000a001'''
|
||||
\set big '''00000000-0000-7000-8000-00000000c001'''
|
||||
\set epoch '''2026-01-01T00:00:00Z'''
|
||||
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES (:author, 'seed_author', 'Синтетический автор', '$argon2id$v=19$m=19456,t=2,p=1$c2VlZA$c2VlZA', :epoch)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
SELECT ('00000000-0000-7000-8000-00000000c' || lpad(to_hex(chat), 3, '0'))::uuid,
|
||||
'Синтетический чат ' || chat, :epoch
|
||||
FROM generate_series(1, 21) AS chat
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
|
||||
SELECT id, :author, 1, created_at FROM chats WHERE title LIKE 'Синтетический чат %'
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT ('00000000-0000-7000-8001-' || lpad(to_hex(n), 12, '0'))::uuid, :big, :author,
|
||||
'синтетическое сообщение ' || n, :epoch::timestamptz + n * interval '1 second'
|
||||
FROM generate_series(1, 20000) AS n
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT ('00000000-0000-7000-8002-' || lpad(to_hex(chat * 1000 + n), 12, '0'))::uuid,
|
||||
('00000000-0000-7000-8000-00000000c' || lpad(to_hex(chat), 3, '0'))::uuid, :author,
|
||||
'фоновое сообщение ' || n, :epoch::timestamptz + n * interval '1 second'
|
||||
FROM generate_series(2, 21) AS chat, generate_series(1, 500) AS n
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
UPDATE chats
|
||||
SET last_message_at = (SELECT max(created_at) FROM messages WHERE messages.chat_id = chats.id)
|
||||
WHERE title LIKE 'Синтетический чат %';
|
||||
|
||||
ANALYZE;
|
||||
|
||||
SELECT count(*) FILTER (WHERE chat_id = :big) AS big_chat_messages, count(*) AS all_messages
|
||||
FROM messages;
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
size="select pg_database_size(current_database()), coalesce((select n_live_tup from pg_stat_user_tables where relname = 'messages'), 0)"
|
||||
echo "$(date -u +%T) database bytes,messages: $(docker compose exec -T postgres psql -X -At -F, -U messenger -d messenger -c "$size")"
|
||||
docker stats --no-stream --format '{{.Name}} cpu={{.CPUPerc}} mem={{.MemUsage}}' $(docker compose ps -q)
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
ids=$(docker compose ps -q "${API_SERVICE:-api}")
|
||||
[ -n "$ids" ] || { echo "no running ${API_SERVICE:-api} replicas" >&2; exit 3; }
|
||||
target=$(docker inspect -f '{{.Id}} {{.Config.Hostname}}' $ids | awk -v t="$TARGET_INSTANCE_ID" '$2 == t {print $1}')
|
||||
[ -n "$target" ] || { echo "no running ${API_SERVICE:-api} replica answers as $TARGET_INSTANCE_ID" >&2; exit 3; }
|
||||
docker stop -t "${STOP_TIMEOUT:-7}" "$target" >/dev/null
|
||||
Executable
+124
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
seed = __import__("lab4_seed")
|
||||
FORMAT = "{:>5} {:>5} {:>4} {:<18} {:>7} {:>7} {:>8} {:>8} {:>7} {:>8} {:>6}"
|
||||
COLUMNS = FORMAT.format(
|
||||
"slots",
|
||||
"size",
|
||||
"conc",
|
||||
"codes",
|
||||
"p50_ms",
|
||||
"p95_ms",
|
||||
"api_idle",
|
||||
"api_peak",
|
||||
"api_oom",
|
||||
"lb_peak",
|
||||
"lb_oom",
|
||||
)
|
||||
|
||||
|
||||
OVERRIDES = ("UPLOAD_CONCURRENCY", "MALLOC_MMAP_THRESHOLD_")
|
||||
|
||||
|
||||
def recreate(slots):
|
||||
env = dict(os.environ, UPLOAD_CONCURRENCY=str(slots))
|
||||
if not slots:
|
||||
env = {k: v for k, v in os.environ.items() if k not in OVERRIDES}
|
||||
cmd = ["docker", "compose", "up", "-d", "--no-deps", "--force-recreate", "--wait", "api", "lb"]
|
||||
subprocess.run(cmd, cwd=ROOT, env=env, check=True, capture_output=True)
|
||||
subprocess.run([str(ROOT / "scripts/lb-wait.sh")], cwd=ROOT, check=True)
|
||||
|
||||
|
||||
def balancer():
|
||||
cid = seed.run(["docker", "compose", "ps", "-q", "lb"]).strip()
|
||||
events = dict(row.split() for row in seed.cgroup(cid, "memory.events").splitlines())
|
||||
peak = seed.cgroup(cid, "memory.peak")
|
||||
return {
|
||||
"cgroup_memory_peak_mib": round(int(peak) / 1048576, 1),
|
||||
"oom_kill": int(events["oom_kill"]),
|
||||
}
|
||||
|
||||
|
||||
def line(report):
|
||||
memory = report["memory"].values()
|
||||
codes = ",".join(f"{k}x{v}" for k, v in sorted(report["status_codes"].items()))
|
||||
return FORMAT.format(
|
||||
report["upload_concurrency"],
|
||||
f"{report['body_bytes'] / 1048576:.1f}M",
|
||||
report["concurrency"],
|
||||
codes,
|
||||
report["latency_ms"]["p50"],
|
||||
report["latency_ms"]["p95"],
|
||||
max(m["idle_mib"] for m in memory),
|
||||
max(m["cgroup_memory_peak_mib"] or 0 for m in memory),
|
||||
sum(m["oom_kill"] for m in memory),
|
||||
report["lb"]["cgroup_memory_peak_mib"],
|
||||
report["lb"]["oom_kill"],
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Peak memory of API replicas under concurrent uploads")
|
||||
p.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
p.add_argument("--slots", type=int, nargs="+", default=[64, 3])
|
||||
p.add_argument("--sizes", type=int, nargs="+", default=[1 << 20, 10 << 20])
|
||||
p.add_argument("--levels", type=int, nargs="+", default=[10, 20, 40])
|
||||
p.add_argument("--rounds", type=int, default=2, help="uploads per concurrent client")
|
||||
p.add_argument("--out", default="evidence/upload-memory")
|
||||
args = p.parse_args()
|
||||
out = ROOT / args.out
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
if any(out.iterdir()):
|
||||
p.error("output directory must be empty; choose a new --out")
|
||||
commit = seed.run(["git", "rev-parse", "HEAD"]).strip()
|
||||
threshold = os.environ.get("MALLOC_MMAP_THRESHOLD_", "131072")
|
||||
lines = [
|
||||
f"# {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} commit {commit}; api x2: 1 CPU,"
|
||||
f" 512 MiB, 2 workers; MALLOC_MMAP_THRESHOLD_={threshold}; {args.rounds} uploads"
|
||||
" per client; peaks from cgroup memory.peak, MiB",
|
||||
COLUMNS,
|
||||
]
|
||||
print("\n".join(lines), flush=True)
|
||||
try:
|
||||
for slots in args.slots:
|
||||
for size in args.sizes:
|
||||
for level in args.levels:
|
||||
recreate(slots)
|
||||
run = argparse.Namespace(
|
||||
base_url=args.base_url,
|
||||
timeout=60,
|
||||
size=size,
|
||||
count=level * args.rounds,
|
||||
concurrency=level,
|
||||
sample=True,
|
||||
service="api",
|
||||
link=0,
|
||||
ids_out=None,
|
||||
)
|
||||
report = {
|
||||
"date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"commit": commit,
|
||||
"upload_concurrency": slots,
|
||||
**seed.over_http(run),
|
||||
}
|
||||
report["lb"] = balancer()
|
||||
name = f"slots{slots}-{size >> 20}mib-c{level}.json"
|
||||
(out / name).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
lines.append(line(report))
|
||||
print(lines[-1], flush=True)
|
||||
finally:
|
||||
recreate(None)
|
||||
(out / "summary.txt").write_text("\n".join(lines) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE=${COMPOSE:-docker compose}
|
||||
service=${WORKER_SERVICE:-worker}
|
||||
case "${1:-}" in
|
||||
stop) $COMPOSE stop -t 10 "$service" ;;
|
||||
kill) $COMPOSE kill -s KILL "$service" ;;
|
||||
start) $COMPOSE up -d --no-deps --wait --wait-timeout 60 "$service" ;;
|
||||
status) $COMPOSE ps -a --format '{{.Service}} {{.State}} {{.Status}}' "$service" ;;
|
||||
*) echo "usage: $0 stop|kill|start|status" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,148 @@
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
import pki
|
||||
import security_operator as operator
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
|
||||
def compose(*args, capture=False):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *args], check=True, capture_output=True, text=True
|
||||
)
|
||||
return result.stdout if capture else None
|
||||
|
||||
|
||||
def publication_counts(attachments):
|
||||
rows = []
|
||||
for attachment in attachments:
|
||||
identifier = str(UUID(attachment["id"]))
|
||||
query = (
|
||||
"SELECT json_build_object('jobs', "
|
||||
"(SELECT count(*) FROM jobs WHERE attachment_id=:'id'), "
|
||||
"'variants', (SELECT count(*) FROM attachment_variants WHERE attachment_id=:'id'), "
|
||||
"'published_version', (SELECT published_version FROM attachments WHERE id=:'id'));"
|
||||
)
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"messenger",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-At",
|
||||
"-v",
|
||||
"id=" + identifier,
|
||||
],
|
||||
input=query,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
check=True,
|
||||
)
|
||||
counts = json.loads(result.stdout)
|
||||
if counts != {"jobs": 1, "variants": 3, "published_version": 1}:
|
||||
raise RuntimeError("Unexpected repeated/missing published effects")
|
||||
rows.append({"attachment_id": identifier, **counts})
|
||||
return rows
|
||||
|
||||
|
||||
def experiment(number):
|
||||
client = importlib.import_module("client").Client(
|
||||
"https://localhost:18443", str(ROOT / "secrets/pki/operator/ca.crt")
|
||||
)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
saved = ROOT / "secrets/pki/previous-worker"
|
||||
if saved.exists():
|
||||
for file in saved.iterdir():
|
||||
file.chmod(0o600)
|
||||
shutil.rmtree(saved)
|
||||
shutil.copytree(ROOT / "secrets/pki/worker", saved)
|
||||
for file in saved.iterdir():
|
||||
file.chmod(0o600)
|
||||
(saved / "credentials.json").write_text(json.dumps(operator.configuration("worker")))
|
||||
(saved / "credentials.json").chmod(0o444)
|
||||
for file in saved.iterdir():
|
||||
file.chmod(0o444)
|
||||
since = str(int(time.time()))
|
||||
started = time.monotonic()
|
||||
operator.call("auth/cert/certs/worker", token=operator.operator_token(), method="DELETE")
|
||||
while "security.authorization.expired" not in compose(
|
||||
"logs", "--since", since, "worker", capture=True
|
||||
):
|
||||
if time.monotonic() - started > 80:
|
||||
raise RuntimeError("Worker did not stop within authorization deadline")
|
||||
time.sleep(1)
|
||||
stopped = time.monotonic() - started
|
||||
uploads = [client.attachment(alice, chat) for _ in range(3)]
|
||||
queued = [
|
||||
client.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")[
|
||||
"json"
|
||||
]["status"]
|
||||
for att, _ in uploads
|
||||
]
|
||||
if queued != ["queued"] * 3:
|
||||
raise RuntimeError("Tasks did not remain queued during revocation")
|
||||
recovered = time.monotonic()
|
||||
pki.issue("worker")
|
||||
pki.revoke("worker")
|
||||
password = secrets.token_hex(24)
|
||||
(ROOT / "secrets/db_worker").write_text(password)
|
||||
operator.rotate_worker(password)
|
||||
operator.configure("worker")
|
||||
compose("restart", "s3-tls", "broker-tls", "otel-collector-tls")
|
||||
compose("restart", "worker")
|
||||
ready = [client.wait_ready(alice, att, wait_seconds=90) for att, _ in uploads]
|
||||
for (att, content), result in zip(uploads, ready):
|
||||
body = client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=alice)[
|
||||
"bytes"
|
||||
]
|
||||
if (
|
||||
hashlib.sha256(body).hexdigest() != hashlib.sha256(content).hexdigest()
|
||||
or result["sha256"] != hashlib.sha256(content).hexdigest()
|
||||
):
|
||||
raise RuntimeError("Restored attachment checksum differs")
|
||||
recovery = time.monotonic() - recovered
|
||||
denial = json.loads(
|
||||
compose("run", "--rm", "--no-deps", "security-audit", "revoked", capture=True)
|
||||
)
|
||||
if not denial["passed"]:
|
||||
raise RuntimeError("Revoked identity accepted")
|
||||
row = {
|
||||
"run": number,
|
||||
"authorization_stop_seconds": round(stopped, 3),
|
||||
"recovery_seconds": round(recovery, 3),
|
||||
"queued": len(queued),
|
||||
"ready": len(ready),
|
||||
"checksums_preserved": True,
|
||||
"publications": publication_counts(ready),
|
||||
"revoked": denial,
|
||||
}
|
||||
print(json.dumps(row), flush=True)
|
||||
for file in saved.iterdir():
|
||||
file.chmod(0o600)
|
||||
shutil.rmtree(saved)
|
||||
return row
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.chdir(ROOT)
|
||||
results = [experiment(number) for number in range(1, 4)]
|
||||
(ROOT / "evidence/security/worker-compromise.json").write_text(
|
||||
json.dumps(results, indent=2) + "\n"
|
||||
)
|
||||
Reference in New Issue
Block a user