выполнение лабы на 5

This commit is contained in:
kaktuz20000
2026-10-21 09:44:11 +03:00
commit 176b9de2de
92 changed files with 12727 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
SECRETS_DIR="$ROOT/secrets"
PASSWORD_FILE="$SECRETS_DIR/postgres_password"
DATABASE_URL_FILE="$SECRETS_DIR/database_url"
if [ -e "$PASSWORD_FILE" ] || [ -e "$DATABASE_URL_FILE" ]; then
printf '%s\n' 'Secret files already exist; refusing to overwrite them.' >&2
exit 1
fi
command -v openssl >/dev/null 2>&1 || {
printf '%s\n' 'openssl is required to generate local credentials.' >&2
exit 1
}
mkdir -p "$SECRETS_DIR"
chmod 700 "$SECRETS_DIR"
umask 077
password=$(openssl rand -hex 32)
printf '%s' "$password" > "$PASSWORD_FILE"
printf 'postgresql://messenger:%s@postgres:5432/messenger' "$password" > "$DATABASE_URL_FILE"
chmod 644 "$PASSWORD_FILE" "$DATABASE_URL_FILE"
unset password
printf '%s\n' 'Local PostgreSQL secret files created.'
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env python3
"""Offline structural checks; full schema validation is a separate target."""
import ast
import json
from pathlib import Path
import re
ROOT = Path(__file__).resolve().parents[1]
def main():
lab = json.loads((ROOT/'lab.json').read_text())['number']
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
assert spec['openapi']=='3.1.0'
assert spec['info']['version']=='1.%d.0'%lab
operation_ids = set()
def walk(value):
if isinstance(value,dict):
if '$ref' in value:
pointer = value['$ref']
assert pointer.startswith('#/'), 'unexpected external reference'
target = spec
for part in pointer[2:].split('/'):
target = target[part.replace('~1','/').replace('~0','~')]
for v in value.values():
walk(v)
elif isinstance(value,list):
for v in value:
walk(v)
walk(spec)
for route,methods in spec['paths'].items():
placeholders = set(re.findall(r'\{([^}]+)\}',route))
for method,op in methods.items():
assert op['operationId'] not in operation_ids, 'duplicate operationId'
operation_ids.add(op['operationId'])
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
assert placeholders==params, 'path parameter mismatch: '+route
for response in op['responses'].values():
assert 'X-Request-Id' in response['headers']
if lab>=3:
assert 'X-Instance-Id' in response['headers']
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
ast.parse(file.read_text(),filename=str(file))
for file in ROOT.rglob('*.json'):
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
continue
json.loads(file.read_text())
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
assert (ROOT/required).is_file(), 'missing '+required
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
if __name__=='__main__':
main()
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
# Allow operator unseal if required in lab7; do not print credentials.
# Exit 0 only after the intended action; test waits for API readiness separately.
printf '%s
' 'TODO: implement restart.sh for your infrastructure' >&2
exit 2
+9
View File
@@ -0,0 +1,9 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
docker compose --env-file .env restart postgres
docker compose --env-file .env up -d --wait --wait-timeout 60 postgres
docker compose --env-file .env restart api load_balancer
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
docker compose --env-file .env up -d --scale api=2 --wait --wait-timeout 60
containers=$(docker compose --env-file .env ps -q api)
if [ -z "$containers" ]; then
printf '%s\n' 'No running API containers found.' >&2
exit 1
fi
for container in $containers; do
docker stop --time 15 "$container" >/dev/null
docker start "$container" >/dev/null
attempts=0
while [ "$attempts" -lt 40 ]; do
state=$(docker inspect --format '{{.State.Health.Status}}' "$container")
if [ "$state" = healthy ]; then
printf 'PASS: API container %s restarted and is healthy\n' "$container"
break
fi
if [ "$state" = unhealthy ] || [ "$state" = none ]; then
printf 'API container %s failed health check (state: %s)\n' "$container" "$state" >&2
exit 1
fi
attempts=$((attempts + 1))
sleep 1
done
if [ "$attempts" -eq 40 ]; then
printf 'API container %s did not become healthy in 40 seconds\n' "$container" >&2
exit 1
fi
done
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task.
# Stop that instance and leave it stopped; no stop of DB/LB/volumes.
# Return quickly (within 10 s); the test sends requests during this script.
# Restore the replica explicitly after the test. Never print credentials.
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
printf '%s
' 'TODO: implement stop-one.sh for your infrastructure' >&2
exit 2
+32
View File
@@ -0,0 +1,32 @@
#!/bin/sh
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
target_container=
for container in $(docker compose --env-file .env ps -q api); do
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
target_container=$container
break
fi
done
if [ -z "$target_container" ]; then
printf '%s\n' 'No running API container matches TARGET_INSTANCE_ID.' >&2
exit 1
fi
if [ -n "${FAILOVER_EVIDENCE_FILE:-}" ]; then
case "$FAILOVER_EVIDENCE_FILE" in
/*) evidence_file=$FAILOVER_EVIDENCE_FILE ;;
*) evidence_file="$ROOT/$FAILOVER_EVIDENCE_FILE" ;;
esac
printf '%s target_instance=%s container=%s\n' \
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$TARGET_INSTANCE_ID" "$target_container" \
>> "$evidence_file"
fi
docker stop --time 2 "$target_container" >/dev/null
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
import json
from pathlib import Path
from openapi_spec_validator import validate
from jsonschema import Draft202012Validator
root = Path(__file__).resolve().parents[1]
spec = json.loads((root/'contracts/openapi.json').read_text())
validate(spec)
from referencing import Registry, Resource
# The base URI resolves local #/components references inside examples.
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
Draft202012Validator(schema, registry=registry).validate(example)
for path in (root/'contracts').glob('*.schema.json'):
schema = json.loads(path.read_text())
Draft202012Validator.check_schema(schema)
for example in schema.get('examples',[]):
Draft202012Validator(schema).validate(example)
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')