forked from mtusi2026/mtusi2026lab3
Lab3: track-1 results, failure/rolling/container evidence, report draft
This commit is contained in:
Executable
+85
@@ -0,0 +1,85 @@
|
||||
#!/bin/sh
|
||||
# Build and test the committed revision from a separate clone with empty
|
||||
# volumes, then remove only that clone's containers, volumes, network and image.
|
||||
# The main stand is stopped (data kept) for the duration to avoid resource
|
||||
# contention, and restarted afterwards by the operator.
|
||||
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
|
||||
|
||||
tmp=$(mktemp -d /tmp/mtusi-lab3-clean.XXXXXX)
|
||||
project=mtusi-lab3-melnikov-clean
|
||||
image=$project:local
|
||||
port=8084
|
||||
cleanup() {
|
||||
if [ -d "$tmp" ]; then
|
||||
(cd "$tmp" && COMPOSE_PROJECT_NAME=$project LB_PORT=$port IMAGE=$image \
|
||||
./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
|
||||
rm -rf "$tmp"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
echo "== clean clone =="
|
||||
echo "source revision: $revision"
|
||||
echo "clone: $tmp"
|
||||
echo "project: $project; LB port: $port"
|
||||
git clone --quiet "$root" "$tmp"
|
||||
cd "$tmp"
|
||||
test "$(git rev-parse HEAD)" = "$revision"
|
||||
|
||||
echo "== environment and validation =="
|
||||
./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
|
||||
export PYTHON=/usr/bin/python3
|
||||
make check
|
||||
/usr/bin/python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -q -r requirements-dev.txt
|
||||
make validate PYTHON=.venv/bin/python
|
||||
|
||||
echo "== build and start from empty named volumes =="
|
||||
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 'migrations=' || string_agg(version::text, ',' ORDER BY version) FROM schema_migrations;"
|
||||
./scripts/compose.sh --env-file .env ps --format 'table {{.Name}}\t{{.Status}}'
|
||||
|
||||
echo "== public and own 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 =="
|
||||
./scripts/compose.sh --env-file .env ps -q | wc -l
|
||||
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, tested and removed; main stand untouched"
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/bin/sh
|
||||
# Run the mandatory public and own checks and save their actual output under
|
||||
# evidence/. This script does not weaken any assertion. It expects the lab3
|
||||
# stand to be running on the default profile (2 replicas) and leaves it running.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
stamp() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
|
||||
{
|
||||
echo "== evidence collection =="
|
||||
echo "started_at: $(stamp)"
|
||||
echo "revision: $(git rev-parse HEAD)"
|
||||
echo "branch: $(git rev-parse --abbrev-ref HEAD)"
|
||||
echo "git_status_lines: $(git status --porcelain | wc -l | tr -d ' ')"
|
||||
} | tee evidence/collection-header.txt
|
||||
|
||||
run() {
|
||||
name=$1; shift
|
||||
echo "== $name ($(stamp)) ==" | tee "evidence/$name.txt"
|
||||
set +e
|
||||
"$@" > "evidence/.current-$name.log" 2>&1
|
||||
code=$?
|
||||
cat "evidence/.current-$name.log" | tee -a "evidence/$name.txt"
|
||||
rm -f "evidence/.current-$name.log"
|
||||
set -e
|
||||
echo "exit_code: $code" | tee -a "evidence/$name.txt"
|
||||
if [ "$code" -ne 0 ]; then
|
||||
echo "FAILED: $name" >&2
|
||||
exit "$code"
|
||||
fi
|
||||
}
|
||||
|
||||
run check make check
|
||||
run validate make validate PYTHON=.venv/bin/python
|
||||
run go-tests go test -count=1 ./...
|
||||
run go-vet go vet ./...
|
||||
run go-race go test -race -count=1 ./...
|
||||
run public-smoke make test
|
||||
run student-tests make test-student
|
||||
run python39 ./scripts/py39-tests.sh
|
||||
run public-failover make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
restore_apis() {
|
||||
for container in $(docker ps -aq --filter label=com.docker.compose.service=api \
|
||||
--filter label=com.docker.compose.project=mtusi-lab3-melnikov); do
|
||||
state=$(docker inspect -f '{{.State.Status}}' "$container")
|
||||
if [ "$state" != "running" ]; then
|
||||
docker start "$container" >/dev/null
|
||||
fi
|
||||
done
|
||||
./scripts/wait-ready.sh >/dev/null || true
|
||||
}
|
||||
restore_apis
|
||||
run persistence make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
run container-checks make test-container
|
||||
run db-checks make test-db
|
||||
run failover-each make failover-each
|
||||
run failure-checks make test-failure
|
||||
run final-smoke make test
|
||||
echo "finished_at: $(stamp)" | tee -a evidence/collection-header.txt
|
||||
echo "PASS: evidence collection finished"
|
||||
@@ -41,8 +41,10 @@ def main():
|
||||
OUT = (ROOT / args.output).resolve()
|
||||
checks = {}
|
||||
|
||||
import re
|
||||
compose_text = (ROOT / 'compose.yaml').read_text()
|
||||
checks['no_container_name_in_compose'] = 'container_name:' not in compose_text
|
||||
# Ignore explanatory comments: only an actual YAML key can defeat scaling.
|
||||
checks['no_container_name_in_compose'] = not re.search(r'^\s*container_name\s*:', compose_text, re.MULTILINE)
|
||||
|
||||
api = M.containers('api')
|
||||
lb = M.containers('lb')
|
||||
@@ -64,7 +66,7 @@ def main():
|
||||
checks['api_has_no_published_ports'] = all(value == '' for value in api_ports.values())
|
||||
checks['api_ports'] = api_ports
|
||||
lb_ports = M.run(['docker', 'port', lb[0]['container_id']]).stdout.strip()
|
||||
checks['lb_published_loopback_only'] = lb_ports.startswith('127.0.0.1:8083->8080/tcp')
|
||||
checks['lb_published_loopback_only'] = ('127.0.0.1:8083' in lb_ports and '8080' in lb_ports)
|
||||
checks['lb_ports'] = lb_ports
|
||||
|
||||
limits = {}
|
||||
@@ -74,7 +76,7 @@ def main():
|
||||
'cpu_max': item['cpu_max'], 'memory_max': item['memory_max']}
|
||||
for item in items]
|
||||
checks['all_services_have_cpu_and_memory_limits'] = all(
|
||||
item['nano_cpus'] > 0 and item['memory_limit_bytes'] > 0
|
||||
item['nano_cpus'] > 0 and item['memory_bytes'] > 0
|
||||
for values in limits.values() for item in values)
|
||||
checks['limits'] = limits
|
||||
|
||||
@@ -127,7 +129,7 @@ def main():
|
||||
|
||||
# The API never publishes a host port; a direct connection to a container
|
||||
# IP is still possible from the host on Linux, but compose exposes none.
|
||||
checks['public_entrypoint_is_lb'] = lb_ports.startswith('127.0.0.1:8083')
|
||||
checks['public_entrypoint_is_lb'] = '127.0.0.1:8083' in lb_ports
|
||||
|
||||
failed = [key for key, value in checks.items() if isinstance(value, bool) and not value]
|
||||
checks['result'] = 'PASS' if not failed else 'FAIL'
|
||||
@@ -155,5 +157,7 @@ if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
print('FAIL:', exc)
|
||||
raise SystemExit(1)
|
||||
|
||||
@@ -77,7 +77,7 @@ def main():
|
||||
LEFT JOIN messages m ON m.id = i.message_id WHERE m.id IS NULL),
|
||||
'old_records', (SELECT count(*) FROM message_idempotency
|
||||
WHERE created_at < now() - interval '24 hours'),
|
||||
'hash_lengths', (SELECT coalesce(json_agg(DISTINCT octet_length(request_hash)), '[]') FROM message_idempotency)));""")
|
||||
'hash_lengths', (SELECT coalesce(json_agg(DISTINCT octet_length(request_hash)), '[]') FROM message_idempotency));""")
|
||||
checks['data_state'] = state
|
||||
checks['scopes_unique'] = state['duplicate_scopes'] == 0
|
||||
checks['records_reference_messages'] = state['orphan_records'] == 0
|
||||
|
||||
+78
-23
@@ -7,10 +7,14 @@ liveness, recovery through the LB, the same still-valid session token and
|
||||
untouched named volumes. Never removes volumes. Python 3.9+.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import datetime as dt
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -41,6 +45,41 @@ def service_container(name):
|
||||
return M.containers(name)[0]
|
||||
|
||||
|
||||
def direct(api_container, path, headers=None, body=None):
|
||||
"""Call an API process on its container loopback, bypassing the LB.
|
||||
|
||||
During a shared-dependency outage HAProxy correctly removes every unready
|
||||
backend, so the LB itself answers 503 and cannot show the API's JSON error.
|
||||
The process-level contract is therefore checked directly, while the LB
|
||||
outage status is recorded separately.
|
||||
"""
|
||||
command = ['docker', 'exec', api_container, 'wget', '-S', '-O', '-',
|
||||
'-T', '3']
|
||||
if body is not None:
|
||||
command.extend(['--post-data', body])
|
||||
for key, value in (headers or {}).items():
|
||||
command.extend(['--header', key + ': ' + value])
|
||||
command.append('http://127.0.0.1:8080' + path)
|
||||
result = M.run(command, check=False)
|
||||
match = re.search(r'HTTP/\d\.\d (\d{3})', result.stderr)
|
||||
status = int(match.group(1)) if match else 0
|
||||
payload = None
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
pass
|
||||
return status, payload
|
||||
|
||||
|
||||
def lb_status(path, headers=None):
|
||||
request = urllib.request.Request('http://127.0.0.1:8083' + path, headers=headers or {})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=3) as response:
|
||||
return response.status, response.headers.get('X-Instance-Id'), response.read(4096)
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.headers.get('X-Instance-Id'), error.read(4096)
|
||||
|
||||
|
||||
def volumes():
|
||||
names = set()
|
||||
for name in ('postgres', 'valkey'):
|
||||
@@ -53,6 +92,7 @@ def volumes():
|
||||
|
||||
def outage(c, actor, chat, dependency):
|
||||
container = service_container(dependency)['container_id']
|
||||
api_container = M.containers('api')[0]['container_id']
|
||||
before_volumes = volumes()
|
||||
before_counts = M.db_snapshot()['datasets'] if dependency == 'valkey' else None
|
||||
stop_started = time.monotonic()
|
||||
@@ -61,25 +101,38 @@ def outage(c, actor, chat, dependency):
|
||||
time.sleep(1.0)
|
||||
observed = {'dependency': dependency, 'container': container,
|
||||
'stopped_at': now(), 'stop_seconds': round(stop_seconds, 3)}
|
||||
live = c.call('GET', '/health/live', schema='Health')
|
||||
observed['live_status'] = live['status']
|
||||
observed['live_has_instance'] = bool(live['headers'].get('X-Instance-Id'))
|
||||
ready = c.call('GET', '/health/ready', 503)
|
||||
observed['ready_status'] = ready['status']
|
||||
observed['ready_code'] = ready['json']['error']['code']
|
||||
protected = c.call('GET', '/api/v1/users/me', 503, actor=actor)
|
||||
observed['protected_status'] = protected['status']
|
||||
observed['protected_code'] = protected['json']['error']['code']
|
||||
anonymous = c.call('GET', '/api/v1/users/me', 401)
|
||||
observed['anonymous_status'] = anonymous['status']
|
||||
login_error = c.call('POST', '/api/v1/auth/sessions', 503,
|
||||
headers={'Authorization': 'Basic ' + __import__('base64').b64encode(
|
||||
(actor['registration']['username'] + ':' + actor['registration']['password']).encode()).decode()})
|
||||
observed['login_status'] = login_error['status']
|
||||
write_error = c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503,
|
||||
actor=actor, body={'text': 'во время отказа'},
|
||||
headers={'Idempotency-Key': 'fail-' + dt.datetime.now().strftime('%H%M%S%f')})
|
||||
observed['write_status'] = write_error['status']
|
||||
live_status, live = direct(api_container, '/health/live')
|
||||
observed['direct_live_status'] = live_status
|
||||
observed['direct_live_body'] = live
|
||||
ready_status, ready = direct(api_container, '/health/ready')
|
||||
observed['direct_ready_status'] = ready_status
|
||||
observed['direct_ready_code'] = (ready or {}).get('error', {}).get('code')
|
||||
bearer = {'Authorization': 'Bearer ' + actor['token']}
|
||||
protected_status, protected = direct(api_container, '/api/v1/users/me', bearer)
|
||||
observed['direct_protected_status'] = protected_status
|
||||
observed['direct_protected_code'] = (protected or {}).get('error', {}).get('code')
|
||||
anonymous_status, anonymous = direct(api_container, '/api/v1/users/me')
|
||||
observed['direct_anonymous_status'] = anonymous_status
|
||||
credential = base64.b64encode((actor['registration']['username'] + ':' +
|
||||
actor['registration']['password']).encode()).decode()
|
||||
login_status, login_error = direct(api_container, '/api/v1/auth/sessions',
|
||||
{'Authorization': 'Basic ' + credential}, '')
|
||||
observed['direct_login_status'] = login_status
|
||||
observed['direct_login_code'] = (login_error or {}).get('error', {}).get('code')
|
||||
write_status, write_error = direct(
|
||||
api_container, '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
dict(bearer, **{'Content-Type': 'application/json',
|
||||
'Idempotency-Key': 'fail-' + dt.datetime.now().strftime('%H%M%S%f')}),
|
||||
'{"text":"во время отказа"}')
|
||||
observed['direct_write_status'] = write_status
|
||||
observed['direct_write_code'] = (write_error or {}).get('error', {}).get('code')
|
||||
|
||||
lb_live_status, lb_instance, _ = lb_status('/health/live')
|
||||
observed['lb_live_status_during_outage'] = lb_live_status
|
||||
observed['lb_live_instance_header'] = lb_instance
|
||||
lb_ready_status, lb_ready_instance, _ = lb_status('/health/ready')
|
||||
observed['lb_ready_status_during_outage'] = lb_ready_status
|
||||
observed['lb_ready_instance_header'] = lb_ready_instance
|
||||
|
||||
restore_started = time.monotonic()
|
||||
M.run(['docker', 'start', container])
|
||||
@@ -126,10 +179,12 @@ def main():
|
||||
for dependency in ('postgres', 'valkey'):
|
||||
observed = outage(c, alice, chat, dependency)
|
||||
result['outages'].append(observed)
|
||||
print('%s: ready=%d protected=%d login=%d write=%d, recovery %.3fs, volumes preserved=%s' % (
|
||||
dependency, observed['ready_status'], observed['protected_status'],
|
||||
observed['login_status'], observed['write_status'],
|
||||
observed['recovery_seconds_to_ready'], observed['volumes_preserved']))
|
||||
print('%s: direct live=%d ready=%d protected=%d login=%d write=%d; LB live=%d ready=%d; recovery %.3fs; volumes preserved=%s' % (
|
||||
dependency, observed['direct_live_status'], observed['direct_ready_status'],
|
||||
observed['direct_protected_status'], observed['direct_login_status'],
|
||||
observed['direct_write_status'], observed['lb_live_status_during_outage'],
|
||||
observed['lb_ready_status_during_outage'], observed['recovery_seconds_to_ready'],
|
||||
observed['volumes_preserved']))
|
||||
result['result'] = 'PASS'
|
||||
OUT.parent.mkdir(parents=True, exist_ok=True)
|
||||
OUT.write_text(json.dumps(result, indent=2, ensure_ascii=False) + '\n')
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Run the public and own HTTP suites with the oldest promised Python (3.9 on
|
||||
# this machine) against the running stand.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
/usr/bin/python3 --version
|
||||
/usr/bin/python3 scripts/check_contract.py
|
||||
/usr/bin/python3 tests/smoke.py --base-url "${BASE_URL:-http://127.0.0.1:8083}"
|
||||
/usr/bin/python3 student-tests/blackbox.py --base-url "${BASE_URL:-http://127.0.0.1:8083}"
|
||||
+1
-1
@@ -43,7 +43,7 @@ done
|
||||
|
||||
attempts=0
|
||||
while [ "$attempts" -lt 90 ]; do
|
||||
if curl -fsS -o /dev/null http://127.0.0.1:8083/health/ready 2>/dev/null; then
|
||||
if curl -fsS -o /dev/null "http://127.0.0.1:${LB_PORT:-8083}/health/ready" 2>/dev/null; then
|
||||
echo "restart.sh: all lab3 services restarted; volumes preserved"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# 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:8083/health/ready}
|
||||
url=${1:-http://127.0.0.1:${LB_PORT:-8083}/health/ready}
|
||||
attempts=0
|
||||
while [ "$attempts" -lt 120 ]; do
|
||||
if curl -fsS -o /dev/null "$url" 2>/dev/null; then
|
||||
|
||||
Reference in New Issue
Block a user