ЛР4: S3-вложения, приватный bucket и согласованность хранилищ (трек 2)

This commit is contained in:
IvanMeln1k
2026-12-04 14:19:19 +03:00
parent ec540a1a72
commit f1fae32722
1134 changed files with 557640 additions and 21 deletions
Regular → Executable
View File
+108
View File
@@ -0,0 +1,108 @@
#!/bin/sh
# Build and test the committed revision from a separate clone with empty named
# volumes, then remove only that clone's containers, network, volumes and image.
#
# The main lab4 stand (if running) is stopped with data preserved for the
# duration so both stands fit the 2 vCPU / ~2 GiB Colima VM, and restarted at
# the end. The temporary clone lives under .local/highload-tasks/lab4-artifacts
# because Colima only shares the user's home into the VM.
set -eu
cd "$(dirname "$0")/.."
root=$(pwd)
revision=$(git rev-parse HEAD)
if [ -n "$(git status --porcelain)" ]; then
echo "clean-clone-check: working tree is dirty; commit first" >&2
exit 2
fi
artifact_root=${LAB4_ARTIFACTS:-$(cd "$root/../.." && pwd)/.local/highload-tasks/lab4-artifacts}
mkdir -p "$artifact_root"
tmp=$(mktemp -d "$artifact_root/clean-clone.XXXXXX")
project=mtusi-lab4-melnikov-clean
port=8085
image=$project:local
main_was_running=0
if docker ps --format '{{.Names}}' | grep -q '^mtusi-lab4-melnikov-'; then
main_was_running=1
fi
cleanup() {
status=$?
if [ -d "$tmp" ]; then
(cd "$tmp" && COMPOSE_PROJECT_NAME=$project LB_PORT=$port \
./scripts/compose.sh --env-file .env down -v --remove-orphans >/dev/null 2>&1 || true)
docker image rm -f "$image" >/dev/null 2>&1 || true
case "$tmp" in
"$artifact_root"/clean-clone.*) rm -rf "$tmp" ;;
*) echo "clean-clone-check: refusing to remove unexpected path $tmp" >&2 ;;
esac
fi
if [ "$main_was_running" = "1" ]; then
(cd "$root" && make up >/dev/null 2>&1 && ./scripts/wait-ready.sh >/dev/null 2>&1 || true)
fi
exit "$status"
}
trap cleanup EXIT INT TERM
echo "== clean clone =="
echo "source revision: $revision"
echo "clone: $tmp"
echo "project: $project; LB port: $port; image: $image"
if [ "$main_was_running" = "1" ]; then
echo "stopping the main lab4 stand with data preserved for the check"
(cd "$root" && make stop >/dev/null)
fi
git clone --quiet "$root" "$tmp"
cd "$tmp"
test "$(git rev-parse HEAD)" = "$revision"
echo "== local configuration with fresh synthetic credentials =="
./scripts/init-env.sh
python3 - "$tmp/.env" "$port" <<'PY'
import sys
path, port = sys.argv[1], sys.argv[2]
lines = []
for line in open(path):
if line.startswith('LB_PORT='):
line = 'LB_PORT=%s\n' % port
lines.append(line)
open(path, 'w').writelines(lines)
PY
export COMPOSE_PROJECT_NAME=$project
export LB_PORT=$port
export IMAGE=$image
export BASE_URL=http://127.0.0.1:$port
echo "== offline contract and syntax checks =="
make check
echo "== build, migrate and bootstrap the bucket from empty volumes =="
GIT_REVISION=$revision API_IMAGE=$image make up
postgres=$(./scripts/compose.sh --env-file .env ps -q postgres)
set -a
. ./.env
set +a
docker exec -i "$postgres" psql -X -A -t -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
-c "SELECT 'users=' || count(*) FROM users;" \
-c "SELECT 'attachments=' || count(*) FROM attachments;" \
-c "SELECT 'migrations=' || string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;"
./scripts/compose.sh --env-file .env logs s3-init 2>&1 | grep -E '"created":(true|false)' || true
./scripts/compose.sh --env-file .env ps --format 'table {{.Name}}\t{{.Status}}'
echo "== public and own API tests on the clean stand =="
make test
make test-student
make test-persistence ACTION_SCRIPT=scripts/restart.sh
echo "== intentional cleanup of this temporary clone's resources =="
make purge
docker image rm -f "$image" >/dev/null 2>&1 || true
if docker ps -aq --filter label=com.docker.compose.project=$project | grep -q .; then
echo "clean-clone-check: containers remain" >&2
exit 1
fi
if docker volume ls -q | grep -q "^${project}-"; then
echo "clean-clone-check: volumes remain" >&2
exit 1
fi
echo "PASS: clean clone built, migrated, bootstrapped and tested; temporary resources removed"
+93
View File
@@ -0,0 +1,93 @@
#!/bin/bash
# Reproduce the lab4 mandatory and own checks on the running stand and keep
# their real stdout under evidence/commands/. No secrets are printed by these
# commands; the context block contains versions and image ids only.
set -euo pipefail
cd "$(dirname "$0")/.."
export BASE_URL=${BASE_URL:-http://127.0.0.1:8084}
PY39=/usr/bin/python3
out=evidence/commands
mkdir -p "$out"
stamp=$(date -u +%Y-%m-%dT%H:%M:%SZ)
{
echo "started_at: $stamp"
echo "base_url: $BASE_URL"
echo "git_revision: $(git rev-parse HEAD)"
echo "git_status_lines: $(git status --porcelain | wc -l | tr -d ' ')"
echo "python3: $(python3 --version 2>&1)"
echo "python39: $($PY39 --version 2>&1)"
echo "go: $(go version)"
echo "docker_server: $(docker version --format '{{.Server.Version}}')"
echo "docker_cpus_mem: $(docker info --format 'CPUs={{.NCPU}} MemTotal={{.MemTotal}}')"
echo "api_images:"
for id in $(./scripts/compose.sh --env-file .env ps -q api); do
docker inspect -f ' {{.Name}} image={{.Image}} started={{.State.StartedAt}}' "$id"
done
echo "s3_image:"
for id in $(./scripts/compose.sh --env-file .env ps -q s3); do
docker inspect -f ' {{.Name}} image={{.Image}}' "$id"
done
} | tee "$out/context.txt"
run() {
name=$1
shift
{
echo
echo "### $name"
echo "### command: $*"
echo "### started_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
} | tee "$out/$name.txt"
set +e
"$@" 2>&1 | tee -a "$out/$name.txt"
code=${PIPESTATUS[0]}
set -e
echo "### exit_code: $code" | tee -a "$out/$name.txt"
if [ "$code" -ne 0 ]; then
echo "evidence collection stopped: $name failed" >&2
exit "$code"
fi
}
restore_replicas() {
./scripts/compose.sh --env-file .env up -d --no-deps api >/dev/null
./scripts/wait-ready.sh
# The LB needs a moment to see the restarted backend. Do not continue until
# the public health endpoint reports two distinct X-Instance-Id values.
attempt=0
while [ "$attempt" -lt 60 ]; do
visible=$(for _ in $(seq 1 20); do
curl -fsS -D - -o /dev/null "$BASE_URL/health/ready" 2>/dev/null \
| tr -d '\r' | awk 'tolower($1)=="x-instance-id:"{print $2}'
done | sort -u | wc -l | tr -d ' ')
if [ "$visible" -ge 2 ]; then
return 0
fi
attempt=$((attempt + 1))
sleep 0.5
done
echo "restore_replicas: LB still sees fewer than two API instances" >&2
return 1
}
run make_check make PYTHON=$PY39 check
run make_validate make PYTHON=.venv/bin/python validate
run go_tests make PYTHON=$PY39 test-student
run go_race make PYTHON=$PY39 test-student-race
run smoke make PYTHON=$PY39 test
run smoke_python39 ./scripts/py39-tests.sh
run attachment_checks make PYTHON=$PY39 test-attachment
run container_checks make PYTHON=$PY39 test-container
run persistence_public make PYTHON=$PY39 test-persistence ACTION_SCRIPT=scripts/restart.sh
run persistence_evidence $PY39 scripts/persistence-evidence.py --base-url "$BASE_URL"
run failover_public make PYTHON=$PY39 test-failover ACTION_SCRIPT=scripts/stop-one.sh
restore_replicas
run failover_upload $PY39 scripts/failover-upload.py --base-url "$BASE_URL"
run track2 make PYTHON=$PY39 test-consistency
run experiment make PYTHON=$PY39 experiment
run smoke_after_experiment make PYTHON=$PY39 test
echo "finished_at: $(date -u +%Y-%m-%dT%H:%M:%SZ)" | tee "$out/summary.txt"
grep -h '^### exit_code:' "$out"/*.txt | sort | uniq -c | tee -a "$out/summary.txt"
echo "PASS: evidence collection finished; raw command logs are in $out"
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Accept both the Compose v2 plugin ("docker compose") and the standalone
# binary ("docker-compose"), so the same Makefile works on machines where only
# one of them is installed. This wrapper does not change any global setting.
set -eu
if docker compose version >/dev/null 2>&1; then
exec docker compose "$@"
fi
if command -v docker-compose >/dev/null 2>&1; then
exec docker-compose "$@"
fi
echo "Docker Compose is required (docker compose or docker-compose)" >&2
exit 2
+232
View File
@@ -0,0 +1,232 @@
#!/usr/bin/env python3
"""Lab4 infrastructure evidence from actual Docker state, not compose.yaml.
Checks:
* at least two API processes with distinct container ids and hostnames;
* only HAProxy is published, on 127.0.0.1, and API/S3/admin ports are not;
* API is non-root, read-only, cap-drop ALL, no state volume; S3 has its data volume;
* every stand service has CPU and memory limits; named volumes use the lab prefix;
* the API S3 identity is bucket-scoped and differs from the admin identity,
and the admin identity is never present in an API container;
* the bucket bootstrap is idempotent (second run reports created=false);
* an anonymous S3 GET/list outside the API is denied;
* one session is served by both API replicas through the LB.
Python 3.9+, standard library only. Requires the running stand and Docker.
Writes evidence/container-checks.json and .txt.
"""
import json
import re
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
def docker_exec(container, *args):
return subprocess.run(['docker', 'exec', container] + list(args),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
def wait_exited(container, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = M.inspect(container).get('State', {})
if state.get('Status') == 'exited':
return state.get('ExitCode')
time.sleep(0.5)
raise RuntimeError('container did not exit: ' + container)
def main():
args = arguments('Lab4 container, S3 privacy and credential checks')
checks = {}
failures = []
compose_text = (ROOT / 'compose.yaml').read_text()
checks['no_container_name_in_compose'] = not re.search(r'^\s*container_name\s*:', compose_text, re.MULTILINE)
images = re.findall(r'^\s*image:\s*(\S+)', compose_text, re.MULTILINE)
third_party = [image for image in images if not image.startswith('${API_IMAGE')]
checks['third_party_images_pinned_by_digest'] = all('@sha256:' in image for image in third_party)
checks['third_party_images'] = third_party
api = M.containers('api')
lb = M.containers('lb')
postgres = M.containers('postgres')
valkey = M.containers('valkey')
s3 = M.containers('s3')
check(len(api) >= 2, 'expected at least two API containers')
check(len(lb) == 1 and len(postgres) == 1 and len(valkey) == 1 and len(s3) == 1,
'expected one LB, PostgreSQL, Valkey and S3 container')
checks['api_replica_count'] = len(api)
checks['api_container_ids_distinct'] = len({item['container_id'] for item in api}) == len(api)
checks['api_hostnames_distinct'] = len({item['hostname'] for item in api}) == len(api)
checks['api_image_ids'] = sorted({item['image_id'] for item in api})
checks['s3_image_id'] = s3[0]['image_id']
checks['git_revision'] = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_ports = {item['name']: M.run(['docker', 'port', item['container_id']]).stdout.strip() for item in api}
s3_ports = M.run(['docker', 'port', s3[0]['container_id']]).stdout.strip()
lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip()
checks['api_ports'] = api_ports
checks['s3_published_ports'] = s3_ports
checks['lb_ports'] = lb_ports
checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values())
checks['s3_has_no_published_ports'] = s3_ports == ''
checks['lb_published_loopback_only'] = ('127.0.0.1:' in lb_ports and '8080' in lb_ports)
limits = {}
for service, items in (('api', api), ('postgres', postgres), ('valkey', valkey), ('s3', s3), ('lb', lb)):
rows = []
for item in items:
data = M.inspect(item['container_id'])
host = data.get('HostConfig', {})
rows.append({
'name': item['name'],
'nano_cpus': host.get('NanoCpus'),
'memory_bytes': host.get('Memory'),
'readonly_rootfs': host.get('ReadonlyRootfs'),
'cap_drop': host.get('CapDrop'),
'security_opt': host.get('SecurityOpt'),
'user': data.get('Config', {}).get('User'),
'mounts': [mount.get('Name') or mount.get('Source') for mount in data.get('Mounts', [])],
'volume_mounts': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
limits[service] = rows
checks['limits'] = limits
checks['all_services_have_cpu_and_memory_limits'] = all(
row['nano_cpus'] and row['memory_bytes']
for rows in limits.values() for row in rows)
checks['api_non_root'] = all((row['user'] or '').startswith('10001') for row in limits['api'])
checks['api_read_only_rootfs'] = all(row['readonly_rootfs'] for row in limits['api'])
checks['api_cap_drop_all'] = all(row['cap_drop'] == ['ALL'] for row in limits['api'])
checks['api_no_new_privileges'] = all(
any('no-new-privileges' in value for value in (row['security_opt'] or []))
for row in limits['api'])
checks['api_has_no_state_volume'] = all(not row['mounts'] for row in limits['api'])
checks['s3_has_data_volume'] = any(
row['volume_mounts'] and all(name.startswith(M.PROJECT + '-') for name in row['volume_mounts'])
for row in limits['s3'])
volume_names = set()
for item in postgres + valkey + s3:
for mount in M.inspect(item['container_id']).get('Mounts', []):
if mount.get('Type') == 'volume':
volume_names.add(mount.get('Name'))
checks['named_volumes'] = sorted(volume_names)
checks['volumes_have_prefix'] = all(name.startswith(M.PROJECT + '-') for name in volume_names)
# S3 credentials: the API must not receive the administrative identity and
# must fail on a bucket outside its grant.
api_env = api[0]['env']
s3_init = M.compose('ps', '-a', '-q', 's3-init').stdout.strip()
check(s3_init != '', 's3-init container is missing')
init_env = M.inspect(s3_init).get('Config', {}).get('Env', [])
admin_access = ''
for item in init_env:
if item.startswith('S3_ADMIN_ACCESS_KEY='):
admin_access = item.split('=', 1)[1]
checks['api_s3_access_key_present'] = bool(api_env.get('S3_ACCESS_KEY'))
checks['api_s3_secret_present'] = bool(api_env.get('S3_SECRET_KEY'))
checks['api_credentials_differ_from_admin'] = (
bool(admin_access) and api_env.get('S3_ACCESS_KEY') != admin_access)
checks['api_has_no_admin_credentials'] = not any(
key.startswith('S3_ADMIN_') for key in api_env)
buckets = M.s3ctl('-op', 'list', '-prefix', '').stdout
checks['api_credentials_can_list_own_bucket'] = '"objects"' in buckets
other = M.s3ctl('-op', 'list', '-prefix', '', '-bucket', 'definitely-not-granted', check=False)
checks['api_credentials_denied_other_bucket'] = other.returncode != 0
# Bucket bootstrap is idempotent: run the same one-shot container again.
first = M.run(['docker', 'start', '-a', s3_init.strip()], check=False)
code = wait_exited(s3_init.strip())
logs = M.run(['docker', 'logs', '--tail', '5', s3_init.strip()]).stdout + M.run(
['docker', 'logs', '--tail', '5', s3_init.strip()]).stderr
checks['bucket_bootstrap_second_run_exit'] = code
checks['bucket_bootstrap_second_run_created_false'] = '"created":false' in logs
checks['bucket_bootstrap_second_run_verified'] = '"verified":true' in logs
# Anonymous access outside the API must not return an object or a listing.
alice, bob, eve, chat = Client(args.base_url, args.ca_file).bootstrap()
attachment, content = Client(args.base_url, args.ca_file).attachment(alice, chat)
object_key = M.psql(
"SELECT object_key FROM attachments WHERE id = '%s'" % attachment['id'])
bucket = api_env.get('S3_BUCKET', '')
check(bucket and object_key, 'cannot resolve bucket/object key for the privacy probe')
anonymous_object = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '/' + object_key)
anonymous_list = docker_exec(api[0]['container_id'], 'wget', '-q', '-S', '-O', '/dev/null',
'http://s3:8333/' + bucket + '?list-type=2')
checks['anonymous_object_get_status'] = anonymous_object.stderr + anonymous_object.stdout
checks['anonymous_object_get_denied'] = (
anonymous_object.returncode != 0 and '403' in checks['anonymous_object_get_status'])
checks['anonymous_list_status'] = anonymous_list.stderr + anonymous_list.stdout
checks['anonymous_list_denied'] = (
anonymous_list.returncode != 0 and '403' in checks['anonymous_list_status'])
checks['attachment_download_still_authorized'] = (
Client(args.base_url, args.ca_file).call(
'GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)['bytes'] == content)
# One session crosses the real replicas through the LB.
client = Client(args.base_url, args.ca_file)
observed = set()
for _ in range(40):
response = client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
observed.add(response['headers']['X-Instance-Id'])
checks['observed_instances'] = sorted(observed)
checks['session_crosses_replicas'] = len(observed) >= 2
checks['session_instances_are_api_hostnames'] = observed.issubset({item['hostname'] for item in api})
checks['health_ready_via_lb'] = client.call('GET', '/health/ready', schema='Health')['status'] == 200
for key, value in checks.items():
if isinstance(value, bool) and not value:
failures.append(key)
checks['result'] = 'PASS' if not failures else 'FAIL'
checks['failed'] = failures
checks['checked_at'] = M.now_iso()
checks['base_url'] = args.base_url
output = ROOT / 'evidence' / 'container-checks.json'
output.parent.mkdir(parents=True, exist_ok=True)
M.write_json(output, checks)
lines = [
'lab4 container checks at ' + checks['checked_at'],
'result: ' + checks['result'],
'git revision: ' + checks['git_revision'],
'API replicas: %d (%s)' % (len(api), ', '.join(item['hostname'] for item in api)),
'API image ids: ' + ', '.join(checks['api_image_ids']),
'S3 image id: ' + checks['s3_image_id'],
'API ports published: %r' % api_ports,
'S3 ports published: %r' % s3_ports,
'LB ports: ' + lb_ports,
'volumes: ' + ', '.join(checks['named_volumes']),
'limits: ' + json.dumps(limits, separators=(',', ':')),
'observed session instances: ' + ', '.join(sorted(observed)),
'anonymous object GET denied: %r' % checks['anonymous_object_get_denied'],
'anonymous bucket list denied: %r' % checks['anonymous_list_denied'],
'bootstrap second run: exit=%r created_false=%r' % (
checks['bucket_bootstrap_second_run_exit'],
checks['bucket_bootstrap_second_run_created_false']),
]
(ROOT / 'evidence' / 'container-checks.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8')
print('\n'.join(lines))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(failures))
print('PASS: container, S3 privacy and credential checks')
if __name__ == '__main__':
try:
main()
except Exception as exc: # noqa: BLE001
import traceback
traceback.print_exc()
print('FAIL:', exc)
raise SystemExit(1)
+155
View File
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
"""Lab4 failover evidence: upload, stop the serving API replica, read elsewhere.
The public `make test-failover` checks writes and idempotency. This script adds
the lab4-specific proof: the attachment is uploaded by a known replica, that
replica is stopped with scripts/stop-one.sh, and the same original is
downloaded through a different replica with an identical SHA-256.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import hashlib
import json
import os
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'resilience'
def upload_with_instance(c, actor, chat, data):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=failover.png',
201, actor=actor, raw=data, headers={'Content-Type': 'image/png'},
schema='Attachment')
return response['json'], response['headers']['X-Instance-Id']
def main():
args = arguments('Lab4 upload/failover evidence; stops one API replica and restores it')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file, timeout=20)
alice, bob, eve, chat = c.bootstrap()
data = M.png_random(1400, 1000, seed=42)
attachment, uploader = upload_with_instance(c, alice, chat, data)
observed = set()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
observed.add(c.call('GET', '/api/v1/users/me', actor=alice,
schema='User')['headers']['X-Instance-Id'])
if len(observed) >= 2:
break
time.sleep(0.3)
check(len(observed) >= 2, 'expected at least two API replicas before failover')
check(uploader in observed, 'upload was served by an unknown instance: ' + uploader)
command = [str(ROOT / 'scripts/stop-one.sh')]
environment = dict(os.environ)
environment['TARGET_INSTANCE_ID'] = uploader
started = M.now_iso()
process = subprocess.run(command, cwd=str(ROOT), env=environment,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stopped = M.now_iso()
check(process.returncode == 0, 'stop-one.sh failed: ' + process.stderr.strip()[-500:])
# The stopped replica must be the actual Docker container and stay stopped.
target_ids = []
for container in M.compose('ps', '-a', '-q', 'api').stdout.split():
hostname = M.run(['docker', 'inspect', '-f', '{{.Config.Hostname}}', container]).stdout.strip()
if hostname == uploader:
target_ids.append(container)
check(len(target_ids) == 1, 'could not map the upload instance to exactly one API container')
state = M.inspect(target_ids[0])['State']
check(state['Status'] == 'exited', 'target container is not stopped: ' + state['Status'])
M.wait_ready(60)
replica_set = set()
download = None
restored_at = None
restored_instances = set()
try:
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
replica_set.add(download['headers']['X-Instance-Id'])
if download['headers']['X-Instance-Id'] != uploader and download['bytes'] == data:
break
time.sleep(0.3)
check(download is not None and download['bytes'] == data,
'download after failover differs from the original')
check(download['headers']['X-Instance-Id'] != uploader,
'download was served by the stopped replica')
check(uploader not in replica_set, 'download hit the stopped replica')
metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob,
schema='Attachment')['json']
check(metadata['sha256'] == hashlib.sha256(data).hexdigest(),
'metadata checksum changed after failover')
check(metadata['size_bytes'] == len(data), 'metadata size changed after failover')
finally:
# Restore the replica explicitly; the failover hook itself must leave it
# down, and this cleanup runs even when an assertion above fails.
M.compose('up', '-d', '--no-deps', 'api')
M.wait_ready(120)
restored_at = M.now_iso()
deadline = time.monotonic() + 30
while time.monotonic() < deadline:
restored_instances.add(
c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['headers']['X-Instance-Id'])
if len(restored_instances) >= 2:
break
time.sleep(0.3)
check(len(restored_instances) >= 2, 'restored stand does not serve two API replicas')
result = {
'checked_at': M.now_iso(),
'base_url': args.base_url,
'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
'attachment_id': attachment['id'],
'content_bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'instances_before': sorted(observed),
'upload_instance': uploader,
'stopped_container_id': target_ids[0],
'stopped_container_state': state['Status'],
'stop_started_at': started,
'stop_finished_at': stopped,
'download_instance': download['headers']['X-Instance-Id'] if download else None,
'download_instances_seen': sorted(replica_set),
'download_sha256': hashlib.sha256(download['bytes']).hexdigest() if download else None,
'restored_at': restored_at,
'restored_instances': sorted(restored_instances),
'result': 'PASS',
'notes': [
'The upload response X-Instance-Id was mapped to the exact Docker hostname.',
'scripts/stop-one.sh left that container exited; the hook is not a restart helper.',
'The download was served by the remaining replica and matched the original bytes.',
'The stopped replica was restored explicitly with docker compose up -d api; Compose may recreate it with a new hostname.',
],
}
M.write_json(EVIDENCE / 'failover-upload.json', result)
print(json.dumps({
'upload_instance': uploader,
'download_instance': result['download_instance'],
'instances_seen': result['download_instances_seen'],
'sha256_matches': result['download_sha256'] == result['sha256'],
'stopped_container_state': result['stopped_container_state'],
'restored_at': result['restored_at'],
}, ensure_ascii=False))
print('PASS: upload survived replica stop and downloaded with the same SHA-256 via another replica')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+93
View File
@@ -0,0 +1,93 @@
#!/bin/sh
# Create a local .env with fresh synthetic passwords and generate the ignored
# SeaweedFS S3 identity file from those values. Nothing is printed: the files
# are readable only by the current user. This stand never talks to a remote
# secret store.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
random_secret() {
LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 32
}
postgres_password=$(random_secret)
valkey_password=$(random_secret)
s3_admin_access=$(random_secret)
s3_admin_secret=$(random_secret)
s3_api_access=$(random_secret)
s3_api_secret=$(random_secret)
for value in "$postgres_password" "$valkey_password" "$s3_admin_access" "$s3_admin_secret" "$s3_api_access" "$s3_api_secret"; do
if [ "${#value}" -ne 32 ]; then
echo "could not generate local secrets" >&2
exit 1
fi
done
revision=$(git rev-parse HEAD 2>/dev/null || echo unknown)
umask 077
sed \
-e "s|^POSTGRES_PASSWORD=.*|POSTGRES_PASSWORD=${postgres_password}|" \
-e "s|^VALKEY_PASSWORD=.*|VALKEY_PASSWORD=${valkey_password}|" \
-e "s|^S3_ADMIN_ACCESS_KEY=.*|S3_ADMIN_ACCESS_KEY=${s3_admin_access}|" \
-e "s|^S3_ADMIN_SECRET_KEY=.*|S3_ADMIN_SECRET_KEY=${s3_admin_secret}|" \
-e "s|^S3_API_ACCESS_KEY=.*|S3_API_ACCESS_KEY=${s3_api_access}|" \
-e "s|^S3_API_SECRET_KEY=.*|S3_API_SECRET_KEY=${s3_api_secret}|" \
-e "s|^GIT_REVISION=.*|GIT_REVISION=${revision}|" \
.env.example > .env
chmod 600 .env
echo "wrote .env with generated local synthetic credentials (mode 600); values not printed"
else
echo ".env already exists; keeping it"
fi
# Read the values back from the ignored file. The generated secrets use only
# [A-Za-z0-9], so a simple sed extraction is sufficient and never echoes them.
value() {
sed -n "s/^$1=//p" .env | head -n 1
}
postgres_password=$(value POSTGRES_PASSWORD)
valkey_password=$(value VALKEY_PASSWORD)
s3_admin_access=$(value S3_ADMIN_ACCESS_KEY)
s3_admin_secret=$(value S3_ADMIN_SECRET_KEY)
s3_api_access=$(value S3_API_ACCESS_KEY)
s3_api_secret=$(value S3_API_SECRET_KEY)
s3_bucket=$(value S3_BUCKET)
s3_bucket=${s3_bucket:-messenger-attachments}
for value_name in postgres_password valkey_password s3_admin_access s3_admin_secret s3_api_access s3_api_secret; do
eval "check=\${$value_name}"
if [ -z "$check" ]; then
echo "init-env: $value_name is empty in .env" >&2
exit 1
fi
done
umask 077
mkdir -p infra
cat > infra/seaweedfs-s3.json <<EOF
{
"identities": [
{
"name": "lab4-admin-bootstrap",
"credentials": [
{"accessKey": "${s3_admin_access}", "secretKey": "${s3_admin_secret}"}
],
"actions": ["Admin"]
},
{
"name": "lab4-api-bucket-scoped",
"credentials": [
{"accessKey": "${s3_api_access}", "secretKey": "${s3_api_secret}"}
],
"actions": [
"Read:${s3_bucket}",
"Write:${s3_bucket}",
"List:${s3_bucket}"
]
}
]
}
EOF
chmod 600 infra/seaweedfs-s3.json
echo "wrote infra/seaweedfs-s3.json (mode 600); values not printed"
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Shared operator helpers for the lab4 evidence scripts.
Python 3.9+, standard library only. The module wraps Docker/Compose and
PostgreSQL access used by student tests and experiments. It never prints
credentials: values are read from the running containers or the ignored .env
and are returned only to the caller.
"""
import datetime as dt
import json
import os
import random
import struct
import subprocess
import time
import zlib
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
BASE_URL = os.environ.get('BASE_URL', 'http://127.0.0.1:8084')
PROJECT = 'mtusi-lab4-melnikov'
def run(args, cwd=ROOT, check=True, input_bytes=None):
process = subprocess.run(
args, cwd=str(cwd), input=input_bytes, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=input_bytes is None,
)
if check and process.returncode != 0:
stderr = process.stderr if isinstance(process.stderr, str) else process.stderr.decode('utf-8', 'replace')
raise RuntimeError('command failed: %s\n%s' % (' '.join(args), stderr.strip()[:2000]))
return process
def compose(*args):
return run([str(ROOT / 'scripts/compose.sh'), '--env-file', '.env'] + list(args))
def compose_ids(service):
output = compose('ps', '-q', service).stdout
return [line.strip() for line in output.splitlines() if line.strip()]
def inspect(container):
output = run(['docker', 'inspect', container]).stdout
return json.loads(output)[0]
def containers(service):
result = []
for container_id in compose_ids(service):
data = inspect(container_id)
result.append({
'container_id': data['Id'],
'name': (data.get('Name') or '').lstrip('/'),
'hostname': data.get('Config', {}).get('Hostname', ''),
'image_id': data.get('Image', ''),
'image_ref': (data.get('Config', {}).get('Image') or ''),
'status': (data.get('State') or {}).get('Status', ''),
'env': dict(item.split('=', 1) for item in (data.get('Config', {}).get('Env') or []) if '=' in item),
})
return result
def env_value(container, name):
for item in inspect(container).get('Config', {}).get('Env', []) or []:
if item.startswith(name + '='):
return item.split('=', 1)[1]
return ''
def postgres_identity():
postgres = compose_ids('postgres')
if not postgres:
raise RuntimeError('postgres container is not running')
user = env_value(postgres[0], 'POSTGRES_USER')
database = env_value(postgres[0], 'POSTGRES_DB')
return postgres[0], user, database
def psql(sql):
container, user, database = postgres_identity()
process = subprocess.run(
['docker', 'exec', '-i', container, 'psql', '-X', '-A', '-t', '-v', 'ON_ERROR_STOP=1',
'-U', user, '-d', database, '-c', sql],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
)
if process.returncode != 0:
raise RuntimeError('psql failed: ' + process.stderr.strip()[:2000])
return process.stdout.strip()
def s3ctl(*args, check=True):
api = compose_ids('api')
if not api:
raise RuntimeError('no API container is running')
return run(['docker', 'exec', api[0], '/app/s3ctl'] + list(args), check=check)
def s3_list(prefix='attachments/'):
output = s3ctl('-op', 'list', '-prefix', prefix).stdout
return json.loads(output)['objects']
def s3_count(prefix='attachments/'):
return len(s3_list(prefix))
def wait_ready(timeout=90, base_url=None):
import urllib.error
import urllib.request
url = (base_url or BASE_URL).rstrip('/') + '/health/ready'
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
return True
except (urllib.error.URLError, OSError):
pass
time.sleep(0.5)
raise RuntimeError('stack did not become ready: ' + url)
def wait_healthy(service, timeout=60):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
ids = compose_ids(service)
if ids:
state = inspect(ids[0]).get('State', {})
health = state.get('Health', {}).get('Status')
if health in (None, 'healthy'):
return True
time.sleep(0.5)
raise RuntimeError('service did not become healthy: ' + service)
def now_iso():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def monotonic_ms():
return int(time.monotonic() * 1000)
def png_chunk(kind, payload):
body = kind + payload
return struct.pack('>I', len(payload)) + body + struct.pack('>I', zlib.crc32(body) & 0xffffffff)
def _png_header(width, height, color_type=2, bit_depth=8):
return (b'\x89PNG\r\n\x1a\n'
+ png_chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, bit_depth, color_type, 0, 0, 0)))
def png_solid(width, height, rgb=(90, 130, 200)):
"""Small, valid PNG that compresses extremely well (used for pixel limits)."""
row = b'\x00' + bytes(rgb) * width
compressor = zlib.compressobj(6)
payload = bytearray()
for _ in range(height):
payload += compressor.compress(row)
payload += compressor.flush()
return (_png_header(width, height)
+ png_chunk(b'IDAT', bytes(payload))
+ png_chunk(b'IEND', b''))
def png_random(width, height, seed=7):
"""Valid PNG with incompressible RGB rows for byte-size and load profiles."""
generator = random.Random(seed)
compressor = zlib.compressobj(1)
payload = bytearray()
row_size = width * 3 + 1
for _ in range(height):
payload += compressor.compress(b'\x00' + generator.randbytes(row_size - 1))
payload += compressor.flush()
return (_png_header(width, height)
+ png_chunk(b'IDAT', bytes(payload))
+ png_chunk(b'IEND', b''))
def png_corrupt(width=320, height=200):
data = bytearray(png_solid(width, height))
# Flip a byte inside IDAT; the signature and IHDR still look like PNG, so
# the failure must come from the real decoder, not from MIME sniffing.
data[len(data) // 2] ^= 0xff
return bytes(data)
def fixture_bytes(name='sample.png'):
return (ROOT / 'tests' / 'fixtures' / name).read_bytes()
def write_json(path, value):
target = Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(value, indent=2, ensure_ascii=False) + '\n', encoding='utf-8')
return target
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
"""Operator evidence for lab4 persistence: real containers restarted, volumes kept.
The public `make test-persistence` proves the contract result. This script adds
the missing infrastructure evidence: every API/PostgreSQL/Valkey/S3 container
has the same id but a new StartedAt, the named volumes are unchanged, and the
same token, message and original attachment still work afterwards.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'resilience'
def snapshot():
state = {'services': {}, 'volumes': [], 'captured_at': M.now_iso()}
for service in ('api', 'postgres', 'valkey', 's3'):
state['services'][service] = []
for item in M.containers(service):
data = M.inspect(item['container_id'])
state['services'][service].append({
'container_id': item['container_id'],
'name': item['name'],
'started_at': data['State'].get('StartedAt'),
'restart_count': data['RestartCount'],
'image_id': item['image_id'],
'volumes': [mount.get('Name') for mount in data.get('Mounts', [])
if mount.get('Type') == 'volume'],
})
volumes = M.run(['docker', 'volume', 'ls', '--format', '{{.Name}}']).stdout.splitlines()
state['volumes'] = sorted(name for name in volumes if name.startswith(M.PROJECT + '-'))
return state
def main():
args = arguments('Lab4 persistence infrastructure evidence; restarts the stand')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file)
alice, bob, chat = None, None, None
alice, bob, eve, chat = c.bootstrap()
message = c.message(alice, chat, 'persistence evidence ' + uuid.uuid4().hex)['json']
attachment, content = c.attachment(alice, chat)
before = snapshot()
check(len(before['services']['api']) >= 2, 'need at least two API replicas')
check(len(before['volumes']) >= 3, 'expected pgdata, valkeydata and s3data volumes')
started = M.now_iso()
print('running scripts/restart.sh (all API replicas and used stores, volumes kept)')
process = subprocess.run([str(ROOT / 'scripts/restart.sh')], cwd=str(ROOT),
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
check(process.returncode == 0, 'restart.sh failed: ' + process.stderr.strip()[-500:])
finished = M.now_iso()
M.wait_ready(120)
after = snapshot()
checks = {}
checks['same_container_ids'] = all(
before['services'][service][index]['container_id'] == after['services'][service][index]['container_id']
for service in before['services'] for index in range(len(before['services'][service])))
checks['started_at_changed'] = all(
before['services'][service][index]['started_at'] != after['services'][service][index]['started_at']
for service in before['services'] for index in range(len(before['services'][service])))
checks['all_services_restarted'] = all(
len(before['services'][service]) == len(after['services'][service])
for service in before['services'])
checks['volumes_unchanged'] = before['volumes'] == after['volumes']
# Same token, no re-login. The session lives in the restarted Valkey with
# an absolute deadline; the original attachment lives in the restarted S3
# with its metadata in PostgreSQL.
me = c.call('GET', '/api/v1/users/me', actor=alice, schema='User')['json']
checks['same_token_still_valid'] = me['id'] == alice['id']
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=100',
actor=bob, schema='MessagePage')['json']
checks['message_survived'] = any(item == message for item in page['items'])
metadata = c.call('GET', '/api/v1/attachments/' + attachment['id'], actor=bob, schema='Attachment')['json']
checks['attachment_metadata_survived'] = metadata['sha256'] == attachment['sha256']
download = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob)
checks['attachment_bytes_survived'] = download['bytes'] == content
failed = [key for key, value in checks.items() if not value]
result = {
'checked_at': M.now_iso(),
'base_url': args.base_url,
'git_revision': M.run(['git', 'rev-parse', 'HEAD']).stdout.strip(),
'restart_started_at': started,
'restart_finished_at': finished,
'hook_exit_code': process.returncode,
'hook_stdout': process.stdout,
'hook_stderr': process.stderr,
'before': before,
'after': after,
'checks': checks,
'result': 'PASS' if not failed else 'FAIL',
'failed': failed,
'notes': [
'Container ids are unchanged: compose restarted real containers, it did not recreate them.',
'StartedAt changed for every API/PostgreSQL/Valkey/S3 container.',
'Named volumes were preserved; no volume was removed or re-created.',
'The public make test-persistence additionally checks the contract with the old token.',
],
}
M.write_json(EVIDENCE / 'persistence.json', result)
print(json.dumps({'result': result['result'], 'checks': checks}, ensure_ascii=False))
if failed:
raise SystemExit('FAILED checks: ' + ', '.join(failed))
print('PASS: real containers restarted, volumes and data preserved')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Run the public and own black-box suites with the oldest promised Python
# (system Python 3.9 on this machine) against the running stand.
set -eu
cd "$(dirname "$0")/.."
base_url=${BASE_URL:-http://127.0.0.1:8084}
/usr/bin/python3 --version
/usr/bin/python3 -m py_compile scripts/*.py student-tests/*.py tests/*.py
/usr/bin/python3 scripts/check_contract.py
/usr/bin/python3 tests/smoke.py --base-url "$base_url"
/usr/bin/python3 student-tests/blackbox.py --base-url "$base_url"
echo "PASS: Python 3.9 compilation, public smoke and student black-box suite"
+56
View File
@@ -0,0 +1,56 @@
#!/bin/sh
# Restart the API and every state store this lab uses, keeping the named
# volumes and all data. This is the hook for:
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
#
# It never removes volumes, never re-seeds and never prints credentials.
set -eu
cd "$(dirname "$0")/.."
if [ ! -f .env ]; then
echo "restart.sh: .env is missing; run make env first" >&2
exit 2
fi
compose="./scripts/compose.sh --env-file .env"
wait_healthy() {
container=$1
attempts=0
while [ "$attempts" -lt 60 ]; do
status=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container" 2>/dev/null || echo missing)
if [ "$status" = "healthy" ] || [ "$status" = "running" ]; then
return 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: $container did not become healthy" >&2
return 1
}
echo "restart.sh: restarting shared postgres, valkey and the private S3 store (volumes kept)"
postgres=$($compose ps -q postgres)
valkey=$($compose ps -q valkey)
s3=$($compose ps -q s3)
$compose restart postgres valkey s3
wait_healthy "$postgres"
wait_healthy "$valkey"
wait_healthy "$s3"
echo "restart.sh: restarting every api replica"
$compose restart api
for container in $($compose ps -q api); do
wait_healthy "$container"
done
attempts=0
while [ "$attempts" -lt 90 ]; do
if curl -fsS -o /dev/null "http://127.0.0.1:${LB_PORT:-8084}/health/ready" 2>/dev/null; then
echo "restart.sh: all lab4 services restarted; volumes preserved"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "restart.sh: LB readiness did not recover" >&2
exit 1
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
# Stop exactly the API replica that served TARGET_INSTANCE_ID and leave it
# stopped. This is the hook for:
# make test-failover ACTION_SCRIPT=scripts/stop-one.sh
#
# X-Instance-Id is the container hostname in lab4, so the mapping is an exact
# identity match, not a guess from a header prefix. The script touches only
# that one API container: no DB, no sessions, no volumes, no LB.
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
if [ ! -f .env ]; then
echo "stop-one.sh: .env is missing; run make env first" >&2
exit 2
fi
target=""
for container in $(./scripts/compose.sh --env-file .env ps -q api); do
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
target=$container
break
fi
done
if [ -z "$target" ]; then
echo "stop-one.sh: no running API container has hostname $TARGET_INSTANCE_ID" >&2
exit 1
fi
echo "stop-one.sh: stopping API container $target (instance $TARGET_INSTANCE_ID)"
# SIGTERM starts the drain window; compose stop_grace_period is 15 s and the
# application's hard shutdown budget is 6 s, so this returns well within the
# test's 10 s hook budget. The container stays stopped afterwards.
docker stop --time 15 "$target" >/dev/null
state=$(docker inspect -f '{{.State.Status}}' "$target")
if [ "$state" != "exited" ] && [ "$state" != "dead" ]; then
echo "stop-one.sh: container state is $state, expected exited" >&2
exit 1
fi
echo "stop-one.sh: container $target is $state; other replicas keep serving"
+448
View File
@@ -0,0 +1,448 @@
#!/usr/bin/env python3
"""Track 2: repeatable reconciler experiment for the two lab4 stores.
Hypothesis: a single-pass reconciler that compares PostgreSQL attachment rows
with the private bucket, protects everything younger than a configurable grace
period, and re-reads each row immediately before a mutation can remove only
provably unreferenced stale objects and stale upload intents. It must never
delete a ready attachment that a message uses, a fresh upload in flight, or a
file whose metadata and bytes still agree, and it must not invent missing
bytes or report a missing object as ready.
Protocol:
1. create a reproducible base set of attachments (half linked to messages);
2. measure clean dry-run scans (cost of the traversal);
3. inject real faults on both sides:
- stale orphan object (S3 has no metadata row),
- stale pending intent with object (crash between PUT and COMMIT),
- stale pending intent without object,
- ready metadata whose object is gone (missing, used and unused),
- fresh orphan object and fresh pending intent (must be protected);
4. dry-run (no mutations), verify findings and unchanged counts;
5. apply, verify only the provable stale items changed;
6. rerun apply immediately (no new deletions while fresh items are young);
7. wait past the grace period and apply again: the fresh orphan is then old
enough to remove, while a completed real attachment stays intact;
8. verify the API still serves used attachments and new uploads.
Python 3.9+, standard library only. Requires the running stand and Docker.
Raw reports and a compact summary are written under evidence/track2/.
"""
import concurrent.futures
import hashlib
import json
import statistics
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'track2'
BASE_SIZE = 300
USED_SIZE = 150
GRACE = 20
RESULTS = []
def ok(condition, message):
RESULTS.append({'check': message, 'passed': bool(condition)})
check(condition, message)
def reconcile(apply, grace, output_path):
command = [
str(ROOT / 'scripts/compose.sh'), '--env-file', '.env', 'run', '--rm', '--no-deps', '-T',
'--entrypoint', '/app/reconciler', 'api', '-prefix', 'attachments/', '-grace', '%ds' % grace,
]
if apply:
command.append('-apply')
started = M.now_iso()
process = M.run(command)
finished = M.now_iso()
report = json.loads(process.stdout.strip())
report['_invocation'] = {'command': ' '.join(command), 'started_at': started, 'finished_at': finished}
M.write_json(output_path, report)
return report
def object_keys(report, section):
return {item['object_key'] for item in (report['findings'].get(section) or [])}
def item_ids(report, section):
return {item['id'] for item in (report['findings'].get(section) or []) if item.get('id')}
def attachment_count(status=None):
where = '' if status is None else " WHERE status = '%s'" % status
return int(M.psql('SELECT count(*) FROM attachments' + where))
def link_count():
return int(M.psql('SELECT count(*) FROM message_attachments'))
def object_exists(key):
return M.s3ctl('-op', 'stat', '-key', key, check=False).returncode == 0
def put_object(key, data, container=None):
container = container or M.compose_ids('api')[0]
name = '/tmp/lab4-track2-object.bin'
process = subprocess.run(
['docker', 'exec', '-i', container, 'sh', '-c', 'cat > ' + name],
input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
if process.returncode != 0:
raise RuntimeError('could not stage object in API container')
M.s3ctl('-op', 'put', '-key', key, '-file', name, '-content-type', 'image/png')
M.run(['docker', 'exec', container, 'rm', '-f', name])
def delete_object(key):
M.s3ctl('-op', 'delete', '-key', key)
def insert_pending(attachment_id, chat_id, owner_id, object_key, data, age_seconds):
M.psql(
"INSERT INTO attachments "
"(id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, error_code, "
" object_key, created_at, updated_at) VALUES "
"('%s'::uuid, '%s'::uuid, '%s'::uuid, 'crash.png', 'image/png', %d, '%s', 'pending', NULL, "
" '%s', now() - interval '%d seconds', now() - interval '%d seconds')" % (
attachment_id, chat_id, owner_id, len(data), hashlib.sha256(data).hexdigest(),
object_key, age_seconds, age_seconds))
def promote_ready(attachment_id):
M.psql("UPDATE attachments SET status = 'ready', updated_at = now() "
"WHERE id = '%s'::uuid AND status = 'pending'" % attachment_id)
def all_messages(c, actor, chat):
from urllib.parse import quote
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100'
items, seen = [], set()
for _ in range(1000):
page = c.call('GET', path, actor=actor, schema='MessagePage')['json']
items.extend(page['items'])
cursor = page['next_cursor']
if cursor is None:
return items
if cursor in seen:
raise Failure('message cursor cycle')
seen.add(cursor)
path = '/api/v1/chats/' + chat['id'] + '/messages?limit=100&cursor=' + quote(cursor, safe='')
raise Failure('message history exceeded safety bound')
def sleep_until_age(started_monotonic, grace, margin=1.5):
while time.monotonic() - started_monotonic < grace + margin:
time.sleep(0.25)
def main():
args = arguments('Track 2 reconciler experiment; injects faults into SQL and S3')
EVIDENCE.mkdir(parents=True, exist_ok=True)
c = Client(args.base_url, args.ca_file)
alice, bob, eve, chat = c.bootstrap()
sample = M.fixture_bytes('sample.png')
sha = hashlib.sha256(sample).hexdigest()
revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
api_image = M.containers('api')[0]['image_id']
print('== reproducible base set ==')
rows_pre = attachment_count()
objects_pre = M.s3_count()
attachments = []
for index in range(BASE_SIZE):
response = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=track2-%03d.png' % index,
201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'},
schema='Attachment')
attachments.append({'id': response['json']['id'], 'used': False,
'size_bytes': response['json']['size_bytes']})
used_messages = []
for index in range(USED_SIZE // 10):
chosen = attachments[index * 10:(index + 1) * 10]
message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': 'track2 link %02d' % index,
'attachment_ids': [item['id'] for item in chosen]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
used_messages.append(message)
for item in chosen:
item['used'] = True
used = [item for item in attachments if item['used']]
unused = [item for item in attachments if not item['used']]
ok(len(attachments) == BASE_SIZE and len(used) == USED_SIZE and len(unused) == BASE_SIZE - USED_SIZE,
'base attachment set is incomplete')
ok(all(message['attachment_ids'] == [item['id'] for item in attachments[index * 10:(index + 1) * 10]]
for index, message in enumerate(used_messages)), 'message attachments were reordered')
baseline_rows = attachment_count() - rows_pre
baseline_objects = M.s3_count() - objects_pre
baseline_links = link_count()
ok(baseline_rows == BASE_SIZE and baseline_objects == BASE_SIZE,
'base rows/objects were not exactly the %d uploads' % BASE_SIZE)
# A previous interrupted run may have left stale pending rows/orphans.
# One preliminary apply makes the cost baseline honest on a reused stand;
# on a clean stand it deletes nothing.
cleanup = reconcile(True, GRACE, EVIDENCE / 'raw-cleanup.json')
cleanup_deleted = list(cleanup['actions'].get('deleted_objects') or []) + list(
cleanup['actions'].get('deleted_pending_rows') or [])
if cleanup_deleted:
print('pre-run cleanup removed %d leftovers from an earlier interrupted run' % len(cleanup_deleted))
print('== cost of a clean traversal ==')
cost_runs = []
for index in range(3):
report = reconcile(False, 3600, EVIDENCE / ('raw-cost-%d.json' % index))
cost_runs.append({
'run': index + 1,
'generated_at': report['generated_at'],
'db_scan_ms': report['timing']['db_scan_ms'],
's3_list_ms': report['timing']['s3_list_ms'],
'total_ms': report['timing']['total_ms'],
'db_rows': report['timing']['db_rows'],
's3_objects': report['timing']['s3_objects'],
})
ok(all(run['db_rows'] >= BASE_SIZE and run['s3_objects'] >= BASE_SIZE for run in cost_runs),
'cost run did not scan the full base set')
print('== inject faults on both sides ==')
stale_started = time.monotonic()
stale_orphan = 'attachments/orphan-stale-' + uuid.uuid4().hex
put_object(stale_orphan, sample)
crash_one = str(uuid.uuid4())
crash_one_key = 'attachments/' + crash_one
insert_pending(crash_one, chat['id'], alice['id'], crash_one_key, sample, 60)
put_object(crash_one_key, sample)
crash_two = str(uuid.uuid4())
crash_two_key = 'attachments/' + crash_two
insert_pending(crash_two, chat['id'], alice['id'], crash_two_key, sample, 60)
missing_used = used[0]
missing_unused = unused[0]
missing_used_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_used['id'])
missing_unused_key = M.psql("SELECT object_key FROM attachments WHERE id = '%s'::uuid" % missing_unused['id'])
delete_object(missing_used_key)
delete_object(missing_unused_key)
ok(not object_exists(missing_used_key) and not object_exists(missing_unused_key),
'missing objects were not removed from S3')
# The stale orphan must be older than the grace period. The injected rows
# are already older by construction; the S3 object uses its real mtime.
sleep_until_age(stale_started, GRACE)
active_id = str(uuid.uuid4())
active_key = 'attachments/' + active_id
insert_pending(active_id, chat['id'], alice['id'], active_key, sample, 0)
put_object(active_key, sample)
fresh_orphan = 'attachments/orphan-fresh-' + uuid.uuid4().hex
put_object(fresh_orphan, sample)
fresh_started = time.monotonic()
rows_before = attachment_count()
objects_before = M.s3_count()
links_before = link_count()
print('== dry run: detection without mutation ==')
dry = reconcile(False, GRACE, EVIDENCE / 'raw-dry-run.json')
ok(stale_orphan in object_keys(dry, 'orphan_objects'), 'stale orphan object not detected')
ok(fresh_orphan in object_keys(dry, 'protected_recent_objects'), 'fresh orphan object not protected')
ok({crash_one, crash_two} <= item_ids(dry, 'stale_pending'), 'stale upload intents not detected')
ok(active_id in item_ids(dry, 'protected_pending'), 'fresh upload intent not protected')
ok({missing_used['id'], missing_unused['id']} <= item_ids(dry, 'missing_objects'),
'missing objects not detected')
ok(not (dry['actions'].get('deleted_objects') or []), 'dry run deleted objects')
ok(not (dry['actions'].get('deleted_pending_rows') or []), 'dry run deleted rows')
ok(attachment_count() == rows_before and M.s3_count() == objects_before and link_count() == links_before,
'dry run mutated either store')
ok(object_exists(stale_orphan) and object_exists(fresh_orphan), 'dry run removed an object')
ok(object_exists(active_key), 'dry run removed an active upload object')
print('== apply: only provable stale items ==')
def upload_worker(index):
local = Client(c.base)
response = local.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=concurrent-%d.png' % index,
201, actor=alice, raw=sample, headers={'Content-Type': 'image/png'}, schema='Attachment')
return response['json']
upload_pool = concurrent.futures.ThreadPoolExecutor(max_workers=6)
upload_futures = [upload_pool.submit(upload_worker, index) for index in range(6)]
# Run the reconciler while those uploads are in flight. Their rows/objects
# are younger than the grace period and must not be touched.
apply = reconcile(True, GRACE, EVIDENCE / 'raw-apply.json')
uploaded_concurrently = [future.result() for future in upload_futures]
upload_pool.shutdown()
ok(all(item['status'] == 'ready' for item in uploaded_concurrently),
'concurrent upload during reconcile did not finish ready')
deleted_objects = set(apply['actions'].get('deleted_objects') or [])
deleted_rows = set(apply['actions'].get('deleted_pending_rows') or [])
ok(stale_orphan in deleted_objects, 'stale orphan object was not removed')
ok(crash_one in deleted_rows and crash_two in deleted_rows, 'stale pending rows were not removed')
ok(crash_one_key in deleted_objects, 'stale pending object was not removed')
ok(not object_exists(stale_orphan) and not object_exists(crash_one_key) and not object_exists(crash_two_key),
'stale S3 objects survived apply')
ok(M.psql("SELECT count(*) FROM attachments WHERE id IN ('%s'::uuid, '%s'::uuid)" % (crash_one, crash_two)).strip() == '0',
'stale pending rows survived apply')
ok(object_exists(fresh_orphan), 'fresh orphan object was deleted inside grace')
rows_after_apply = rows_before + len(uploaded_concurrently) - 2
ok(object_exists(active_key) and attachment_count() == rows_after_apply,
'active upload, concurrent upload or active row was deleted')
ok({missing_used['id'], missing_unused['id']} <= set(apply['actions'].get('unresolved_missing') or []),
'missing objects were not left for manual recovery')
ok(link_count() == links_before, 'apply changed message attachment links')
ok(M.psql("SELECT status FROM attachments WHERE id = '%s'::uuid" % active_id).strip() == 'pending',
'active upload intent changed state unexpectedly')
# The simulated in-flight upload completes: the same row is promoted ready
# and becomes usable, proving the reconciler protected a real file.
promote_ready(active_id)
active_message = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice,
body={'text': '', 'attachment_ids': [active_id]},
headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message')['json']
ok(active_message['attachment_ids'] == [active_id], 'protected upload cannot be attached after completion')
active_download = c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)
ok(active_download['bytes'] == sample, 'protected upload bytes changed')
print('== rerun before grace expiry: no new deletions ==')
rerun = reconcile(True, GRACE, EVIDENCE / 'raw-rerun.json')
ok(not (rerun['actions'].get('deleted_objects') or []), 'rerun deleted objects')
ok(not (rerun['actions'].get('deleted_pending_rows') or []), 'rerun deleted rows')
ok(fresh_orphan in object_keys(rerun, 'protected_recent_objects'), 'fresh orphan lost protection on rerun')
ok(object_exists(fresh_orphan), 'fresh orphan removed on rerun')
print('== grace expiry: the fresh orphan is now old enough ==')
sleep_until_age(fresh_started, GRACE)
expired = reconcile(True, GRACE, EVIDENCE / 'raw-after-grace.json')
ok(fresh_orphan in set(expired['actions'].get('deleted_objects') or []),
'aged orphan was not removed after grace')
ok(not object_exists(fresh_orphan), 'aged orphan object still exists')
ok(attachment_count() == rows_after_apply, 'grace expiry deleted a metadata row')
ok(c.call('GET', '/api/v1/attachments/' + active_id + '/content', actor=bob)['bytes'] == sample,
'completed protected attachment lost after grace expiry')
print('== API and used attachments after reconciliation ==')
history = all_messages(c, bob, chat)
indexed = {item['id']: item for item in history}
for message in used_messages:
ok(message['id'] in indexed, 'used message disappeared from history')
ok(indexed[message['id']]['attachment_ids'] == message['attachment_ids'],
'used message lost or reordered its attachment links')
sample_used = used[10]
download = c.call('GET', '/api/v1/attachments/' + sample_used['id'] + '/content', actor=bob)
ok(download['bytes'] == sample, 'used attachment bytes changed or disappeared')
c.call('GET', '/api/v1/attachments/' + sample_used['id'], 404, actor=eve)
c.call('GET', '/api/v1/attachments/' + missing_used['id'], 404, actor=bob)
c.call('GET', '/api/v1/attachments/' + missing_unused['id'] + '/content', 404, actor=bob)
new_attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after.png', 201,
actor=alice, raw=sample, headers={'Content-Type': 'image/png'},
schema='Attachment')['json']
ok(new_attachment['sha256'] == sha, 'new upload after reconciliation failed')
failures = [item for item in RESULTS if not item['passed']]
summary = {
'track': 'Track 2: consistency of two stores',
'hypothesis': ('A grace-protected, re-checked reconciler removes only stale orphan objects and '
'stale upload intents, and never deletes ready/used/fresh attachments or invents '
'missing bytes.'),
'generated_at': M.now_iso(),
'git_revision': revision,
'api_image_id': api_image,
'database_rows_base': baseline_rows,
'object_store_objects_base': baseline_objects,
'message_attachment_links_base': baseline_links,
'base_profile': {
'attachments': BASE_SIZE,
'linked_attachments': USED_SIZE,
'unlinked_ready_attachments': BASE_SIZE - USED_SIZE,
'bytes_per_attachment': len(sample),
'total_attachment_bytes': BASE_SIZE * len(sample),
'image_profile': 'tests/fixtures/sample.png 320x200, identical synthetic bytes',
},
'grace_seconds': GRACE,
'cost_runs': cost_runs,
'cost_summary': {
'runs': len(cost_runs),
'db_scan_ms_median': statistics.median(run['db_scan_ms'] for run in cost_runs),
's3_list_ms_median': statistics.median(run['s3_list_ms'] for run in cost_runs),
'total_ms_median': statistics.median(run['total_ms'] for run in cost_runs),
'note': 'traversal cost is O(rows + objects); timings are wall-clock milliseconds '
'reported by the reconciler process on this local stand',
},
'injected': {
'stale_orphan_object': stale_orphan,
'stale_pending_with_object': {'id': crash_one, 'object_key': crash_one_key},
'stale_pending_without_object': {'id': crash_two, 'object_key': crash_two_key},
'missing_used_attachment': {'id': missing_used['id'], 'object_key': missing_used_key},
'missing_unused_attachment': {'id': missing_unused['id'], 'object_key': missing_unused_key},
'fresh_orphan_object': fresh_orphan,
'active_upload_intent': {'id': active_id, 'object_key': active_key},
},
'dry_run': {
'orphan_objects': sorted(object_keys(dry, 'orphan_objects')),
'protected_recent_objects': sorted(object_keys(dry, 'protected_recent_objects')),
'stale_pending': sorted(item_ids(dry, 'stale_pending')),
'protected_pending': sorted(item_ids(dry, 'protected_pending')),
'missing_objects': sorted(item_ids(dry, 'missing_objects')),
'deleted_objects': dry['actions'].get('deleted_objects') or [],
'deleted_pending_rows': dry['actions'].get('deleted_pending_rows') or [],
},
'apply': {
'deleted_objects': sorted(deleted_objects),
'deleted_pending_rows': sorted(deleted_rows),
'unresolved_missing': apply['actions'].get('unresolved_missing') or [],
},
'rerun': {
'deleted_objects': rerun['actions'].get('deleted_objects') or [],
'deleted_pending_rows': rerun['actions'].get('deleted_pending_rows') or [],
},
'after_grace': {
'deleted_objects': expired['actions'].get('deleted_objects') or [],
'deleted_pending_rows': expired['actions'].get('deleted_pending_rows') or [],
},
'assertions': RESULTS,
'assertions_failed': len(failures),
'result': 'PASS' if not failures else 'FAIL',
'limitations': [
'The reconciler never deletes or fabricates a missing original: bytes cannot be restored '
'automatically, so those rows are reported as unresolved for operator recovery.',
'A simulated in-flight upload row is used as the deterministic active state; real concurrent '
'uploads are additionally exercised and must finish ready.',
'Cost is measured on this 2 vCPU / ~2 GiB Colima stand and does not extrapolate to production.',
'The S3 ListObjects scan is not a snapshot: concurrent uploads are protected by the grace '
'period and by the immediate database re-check before each delete.',
],
}
M.write_json(EVIDENCE / 'dataset.json', {
'generated_at': summary['generated_at'],
'base_profile': summary['base_profile'],
'attachments': attachments,
'used_messages': [{'id': item['id'], 'attachment_ids': item['attachment_ids']} for item in used_messages],
'concurrent_uploads': [item['id'] for item in uploaded_concurrently],
})
M.write_json(EVIDENCE / 'summary.json', summary)
print(json.dumps({'result': summary['result'], 'assertions': len(RESULTS),
'failed': len(failures), 'cost_ms_median': summary['cost_summary']['total_ms_median']},
ensure_ascii=False))
if failures:
raise SystemExit('FAILED checks: ' + ', '.join(item['check'] for item in failures))
print('PASS: track 2 reconciler experiment')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
+335
View File
@@ -0,0 +1,335 @@
#!/usr/bin/env python3
"""Mandatory lab4 upload experiment: >=10 simultaneous uploads + API memory.
Metrics and units (do not confuse them):
* process RSS: VmRSS from /proc/1/status inside each API container, bytes.
This is the resident set of the API process (PID 1), sampled by `docker exec`.
* process peak RSS (HWM): VmHWM from the same file, bytes. The kernel high-water
mark since that process started; the API is restarted before the run so the
baseline is fresh.
* cgroup memory.current / memory.peak: the whole container cgroup, bytes,
including page cache and any other process. It is reported separately and
is NOT presented as process RSS.
The run uploads a reproducible profile of generated PNGs (no giant fixtures in
Git), records real UTC timestamps, per-upload intervals, observed concurrency,
HTTP results and the Sampled RSS of both API replicas. Raw samples and the
compact summary are stored under evidence/experiment/.
Python 3.9+, standard library only. Requires the running stand and Docker.
"""
import concurrent.futures
import datetime as dt
import hashlib
import json
import sys
import threading
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
sys.path.insert(0, str(ROOT / 'scripts'))
from client import Client, Failure, arguments, check # noqa: E402
import lab4_metrics as M # noqa: E402
EVIDENCE = ROOT / 'evidence' / 'experiment'
CONCURRENCY = 12
SAMPLE_INTERVAL_SECONDS = 0.2
def iso_now():
return dt.datetime.now(dt.timezone.utc).isoformat().replace('+00:00', 'Z')
def process_memory(container):
process = M.run(['docker', 'exec', container, 'cat', '/proc/1/status'], check=False)
if process.returncode != 0:
return None
values = {}
for line in process.stdout.splitlines():
if line.startswith('VmRSS:'):
values['rss_bytes'] = int(line.split()[1]) * 1024
elif line.startswith('VmHWM:'):
values['hwm_bytes'] = int(line.split()[1]) * 1024
return values
def cgroup_memory(container):
result = {}
current = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.current'], check=False)
peak = M.run(['docker', 'exec', container, 'cat', '/sys/fs/cgroup/memory.peak'], check=False)
if current.returncode == 0:
result['current_bytes'] = int(current.stdout.strip())
if peak.returncode == 0:
result['peak_bytes'] = int(peak.stdout.strip())
return result or None
class Sampler(threading.Thread):
def __init__(self, containers):
super().__init__(daemon=True)
self.containers = containers
self.samples = []
self.error = None
self._stop_event = threading.Event() # never name this Thread._stop
def run(self):
try:
while not self._stop_event.is_set():
started = iso_now()
monotonic = time.monotonic()
row = {'sampled_at': started, 'monotonic_seconds': round(monotonic, 6), 'api': {}}
for container in self.containers:
row['api'][container['hostname']] = {
'process': process_memory(container['container_id']),
'cgroup': cgroup_memory(container['container_id']),
}
self.samples.append(row)
self._stop_event.wait(SAMPLE_INTERVAL_SECONDS)
except Exception as exc: # noqa: BLE001 - reported in the summary
self.error = type(exc).__name__ + ': ' + str(exc)
def stop(self):
self._stop_event.set()
def main():
args = arguments('Lab4 >=10 concurrent uploads with API process RSS sampling')
EVIDENCE.mkdir(parents=True, exist_ok=True)
api = M.containers('api')
check(len(api) >= 2, 'the experiment needs at least two API replicas')
api_limit = M.inspect(api[0]['container_id'])['HostConfig'].get('Memory')
gomemlimit = api[0]['env'].get('GOMEMLIMIT', '')
decode_concurrency = api[0]['env'].get('UPLOAD_DECODE_CONCURRENCY', '')
put_concurrency = api[0]['env'].get('S3_PUT_CONCURRENCY', '')
max_upload = api[0]['env'].get('MAX_UPLOAD_BYTES', '')
max_pixels = api[0]['env'].get('MAX_IMAGE_PIXELS', '')
revision = M.run(['git', 'rev-parse', 'HEAD']).stdout.strip()
image_id = api[0]['image_id']
print('== restart API replicas to reset the process high-water mark ==')
M.compose('restart', 'api')
M.wait_ready(120)
api = M.containers('api')
check(len(api) >= 2, 'API replicas did not come back')
restarts_before = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api}
baseline = {}
for item in api:
baseline[item['hostname']] = {
'process': process_memory(item['container_id']),
'cgroup': cgroup_memory(item['container_id']),
}
print('== generate the reproducible upload profile ==')
profiles = []
for index in range(CONCURRENCY):
if index < 6:
width, height = 1000, 700
profile = 'small'
elif index < 10:
width, height = 1500, 1100
profile = 'medium'
else:
width, height = 1600, 2167
profile = 'near-max-bytes'
data = M.png_random(width, height, seed=1000 + index)
profiles.append({
'index': index,
'profile': profile,
'filename': 'load-%02d.png' % index,
'width': width,
'height': height,
'pixels': width * height,
'bytes': len(data),
'sha256': hashlib.sha256(data).hexdigest(),
'content': data,
})
check(all(item['pixels'] <= 40_000_000 and item['bytes'] <= 10 * 1024 * 1024 for item in profiles),
'generated profile violates contract limits')
check(max(item['bytes'] for item in profiles) > 10 * 1024 * 1024 - 100000,
'profile does not include a near-limit file')
client = Client(args.base_url, args.ca_file, timeout=60)
alice, bob, eve, chat = client.bootstrap()
barrier = threading.Barrier(CONCURRENCY)
def upload(item):
local = Client(args.base_url, args.ca_file, timeout=60)
barrier.wait()
started_monotonic = time.monotonic()
started_utc = iso_now()
response = local.call(
'POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + item['filename'],
201, actor=alice, raw=item['content'],
headers={'Content-Type': 'image/png'}, schema='Attachment')
finished_monotonic = time.monotonic()
return {
'index': item['index'],
'profile': item['profile'],
'filename': item['filename'],
'width': item['width'],
'height': item['height'],
'pixels': item['pixels'],
'bytes': item['bytes'],
'sha256': item['sha256'],
'started_at': started_utc,
'finished_at': iso_now(),
'started_monotonic': started_monotonic,
'finished_monotonic': finished_monotonic,
'duration_ms': round((finished_monotonic - started_monotonic) * 1000, 3),
'status': response['status'],
'instance_id': response['headers'].get('X-Instance-Id', ''),
'attachment_id': response['json']['id'],
'server_sha256': response['json']['sha256'],
'server_size_bytes': response['json']['size_bytes'],
'server_status': response['json']['status'],
}
sampler = Sampler(api)
sampler.start()
started_utc = iso_now()
started_monotonic = time.monotonic()
with concurrent.futures.ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
results = list(pool.map(upload, profiles))
finished_monotonic = time.monotonic()
finished_utc = iso_now()
time.sleep(0.5)
sampler.stop()
sampler.join(timeout=5)
check(sampler.error is None, 'memory sampler failed: ' + str(sampler.error))
# Observed concurrency from the real client intervals.
events = []
for item in results:
events.append((item['started_monotonic'], 1))
events.append((item['finished_monotonic'], -1))
active = peak = 0
for _, delta in sorted(events, key=lambda pair: (pair[0], -pair[1])):
active += delta
peak = max(peak, active)
per_instance = {}
for item in results:
bucket = per_instance.setdefault(item['instance_id'], {'uploads': 0, 'bytes': 0})
bucket['uploads'] += 1
bucket['bytes'] += item['bytes']
memory = {}
for hostname in baseline:
rss = [row['api'][hostname]['process']['rss_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['process']]
hwm = [row['api'][hostname]['process']['hwm_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['process']]
cgroup = [row['api'][hostname]['cgroup']['current_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['cgroup']]
cgroup_peak = [row['api'][hostname]['cgroup']['peak_bytes']
for row in sampler.samples
if row['api'].get(hostname) and row['api'][hostname]['cgroup']]
memory[hostname] = {
'samples': len(rss),
'baseline_rss_bytes': baseline[hostname]['process']['rss_bytes'] if baseline[hostname]['process'] else None,
'baseline_hwm_bytes': baseline[hostname]['process']['hwm_bytes'] if baseline[hostname]['process'] else None,
'peak_sampled_rss_bytes': max(rss) if rss else None,
'peak_sampled_rss_delta_bytes': (max(rss) - baseline[hostname]['process']['rss_bytes'])
if rss and baseline[hostname]['process'] else None,
'final_hwm_bytes': hwm[-1] if hwm else None,
'peak_cgroup_current_bytes': max(cgroup) if cgroup else None,
'peak_cgroup_memory_peak_bytes': max(cgroup_peak) if cgroup_peak else None,
'api_memory_limit_bytes': api_limit,
}
successes = [item for item in results if item['status'] == 201 and item['server_status'] == 'ready'
and item['server_sha256'] == item['sha256'] and item['server_size_bytes'] == item['bytes']]
failures = [item for item in results if item not in successes]
restarts_after = {item['hostname']: M.inspect(item['container_id'])['RestartCount'] for item in api}
check(len(results) == CONCURRENCY, 'not all uploads returned')
check(len(successes) == CONCURRENCY, 'some uploads failed')
check(peak >= 10, 'observed concurrency below 10: %d' % peak)
check(not failures, 'failed uploads: %r' % [(item['index'], item['status']) for item in failures])
check(restarts_after == restarts_before, 'an API container restarted during the experiment')
for hostname, item in memory.items():
check(item['peak_sampled_rss_bytes'] and item['peak_sampled_rss_bytes'] < api_limit,
'process RSS exceeded the container limit on ' + hostname)
summary = {
'experiment': 'lab4 concurrent upload: peak API process RSS',
'generated_at': iso_now(),
'git_revision': revision,
'api_image_id': image_id,
'base_url': args.base_url,
'started_at': started_utc,
'finished_at': finished_utc,
'wall_seconds': round(finished_monotonic - started_monotonic, 3),
'configured_concurrency': CONCURRENCY,
'observed_peak_concurrency': peak,
'successful_uploads': len(successes),
'failed_uploads': len(failures),
'api_instances': sorted(per_instance),
'uploads_per_instance': per_instance,
'profile': {
'files': len(profiles),
'total_bytes': sum(item['bytes'] for item in profiles),
'min_bytes': min(item['bytes'] for item in profiles),
'max_bytes': max(item['bytes'] for item in profiles),
'max_pixels': max(item['pixels'] for item in profiles),
'small': {'count': 6, 'width': 1000, 'height': 700},
'medium': {'count': 4, 'width': 1500, 'height': 1100},
'near_max_bytes': {'count': 2, 'width': 1600, 'height': 2167},
},
'limits': {
'api_memory_limit_bytes': api_limit,
'GOMEMLIMIT': gomemlimit,
'UPLOAD_DECODE_CONCURRENCY': decode_concurrency,
'S3_PUT_CONCURRENCY': put_concurrency,
'MAX_UPLOAD_BYTES': max_upload,
'MAX_IMAGE_PIXELS': max_pixels,
},
'memory_metrics': {
'process_rss_source': '/proc/1/status VmRSS inside each API container, sampled by docker exec',
'process_hwm_source': '/proc/1/status VmHWM inside each API container',
'cgroup_source': '/sys/fs/cgroup/memory.current and memory.peak (whole container cgroup)',
'sample_interval_seconds': SAMPLE_INTERVAL_SECONDS,
'samples_taken': len(sampler.samples),
'first_sample_at': sampler.samples[0]['sampled_at'] if sampler.samples else None,
'last_sample_at': sampler.samples[-1]['sampled_at'] if sampler.samples else None,
'max_sample_gap_seconds': round(max(
sampler.samples[index]['monotonic_seconds'] - sampler.samples[index - 1]['monotonic_seconds']
for index in range(1, len(sampler.samples))), 3) if len(sampler.samples) > 1 else None,
'per_instance': memory,
},
'uploads': [{key: value for key, value in item.items() if key != 'content'} for item in results],
'result': 'PASS',
'limitations': [
'One local stand: RSS includes Go runtime and handler state, not a production profile.',
'The sampler uses docker exec every 200 ms; a shorter allocation spike between samples is '
'bounded by VmHWM, which is also reported.',
'cgroup memory.current includes page cache and is not process RSS.',
],
}
M.write_json(EVIDENCE / 'uploads.json', summary['uploads'])
M.write_json(EVIDENCE / 'rss-samples.json', {'samples': sampler.samples, 'baseline': baseline})
M.write_json(EVIDENCE / 'summary.json', summary)
print(json.dumps({
'result': 'PASS',
'observed_peak_concurrency': peak,
'successful_uploads': len(successes),
'wall_seconds': summary['wall_seconds'],
'process_peak_sampled_rss_bytes': {key: value['peak_sampled_rss_bytes'] for key, value in memory.items()},
'process_final_hwm_bytes': {key: value['final_hwm_bytes'] for key, value in memory.items()},
'api_memory_limit_bytes': api_limit,
}, ensure_ascii=False))
print('PASS: >=10 concurrent uploads with bounded API process RSS')
if __name__ == '__main__':
try:
main()
except (Failure, ValueError, OSError) as exc:
print('FAIL:', str(exc))
raise SystemExit(1)
Regular → Executable
View File
+16
View File
@@ -0,0 +1,16 @@
#!/bin/sh
# Wait until /health/ready answers 200 through the load balancer.
# Usage: scripts/wait-ready.sh [url]
set -eu
url=${1:-http://127.0.0.1:${LB_PORT:-8084}/health/ready}
attempts=0
while [ "$attempts" -lt 120 ]; do
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
echo "ready: $url"
exit 0
fi
attempts=$((attempts + 1))
sleep 1
done
echo "not ready after 120 seconds: $url" >&2
exit 1