forked from mtusi2026/mtusi2026lab4
feat: moved code from lab3
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import secrets
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--restart", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
def call(method, path, expected=200, body=None, token=None, headers=None):
|
||||
headers = dict(headers or {})
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
data = None
|
||||
if body is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
request = Request(
|
||||
args.base_url + path, data=data, headers=headers, method=method
|
||||
)
|
||||
try:
|
||||
response = urlopen(request, timeout=10)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
assert response.status == expected, (
|
||||
f"{method} {path}: expected {expected}, got {response.status}"
|
||||
)
|
||||
assert response.headers.get("X-Request-Id"), "Missing request ID"
|
||||
raw = response.read()
|
||||
return json.loads(raw) if raw else None
|
||||
|
||||
call("GET", "/health/ready")
|
||||
password = secrets.token_hex(16)
|
||||
users = []
|
||||
for name in ("alice", "bob"):
|
||||
username = name + "_" + secrets.token_hex(6)
|
||||
user = call(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
201,
|
||||
{"username": username, "display_name": name, "password": password},
|
||||
)
|
||||
credentials = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
session = call(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
201,
|
||||
headers={"Authorization": "Basic " + credentials},
|
||||
)
|
||||
users.append((user, session["token"]))
|
||||
alice, token = users[0]
|
||||
bob, bob_token = users[1]
|
||||
chat = call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
{"title": "Baseline lab4", "member_ids": [alice["id"], bob["id"]]},
|
||||
token,
|
||||
)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = secrets.token_hex(16)
|
||||
body = {"text": "Перенос из лабораторной 3"}
|
||||
message = call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
body,
|
||||
token,
|
||||
{"Idempotency-Key": key},
|
||||
)
|
||||
assert call("GET", path, token=bob_token)["items"] == [message]
|
||||
call("GET", "/api/v1/users/me", 401)
|
||||
if args.restart:
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
subprocess.run([str(root / "scripts/restart.sh")], cwd=root, check=True)
|
||||
assert call("GET", "/api/v1/users/me", token=token) == alice
|
||||
assert call("GET", path, token=bob_token)["items"] == [message]
|
||||
assert call("POST", path, 201, body, token, {"Idempotency-Key": key}) == message
|
||||
assert call("GET", path, token=bob_token)["items"] == [message]
|
||||
call("DELETE", "/api/v1/auth/sessions/current", 204, token=token)
|
||||
call("GET", "/api/v1/users/me", 401, token=token)
|
||||
print(
|
||||
"PASS: transferred API, shared sessions, chat, message, logout"
|
||||
+ (", persistence and idempotent replay across restart.sh" if args.restart else "")
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,64 @@
|
||||
import os
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def read_values(path):
|
||||
values = {}
|
||||
if path.exists():
|
||||
for line in path.read_text(encoding="utf-8").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
key, value = line.split("=", 1)
|
||||
values[key.strip()] = value.strip().strip("\"'")
|
||||
return values
|
||||
|
||||
def main():
|
||||
path = ROOT / ".env"
|
||||
existing = read_values(path)
|
||||
defaults = read_values(ROOT / ".env.example")
|
||||
defaults.update(POSTGRES_DB="messenger", POSTGRES_USER="messenger",
|
||||
POSTGRES_PASSWORD=secrets.token_hex(24))
|
||||
values = defaults | existing
|
||||
for name, lower, upper in (("APP_PORT", 1, 65535), ("API_REPLICAS", 2, 32),
|
||||
("SESSION_TTL_SECONDS", 1, 31536000),
|
||||
("IDEMPOTENCY_TTL_SECONDS", 1, 31536000)):
|
||||
try:
|
||||
valid = lower <= int(values[name]) <= upper
|
||||
except (ValueError, KeyError):
|
||||
valid = False
|
||||
if not valid:
|
||||
raise SystemExit(f"{name} must be between {lower} and {upper}")
|
||||
for name in ("POSTGRES_DB", "POSTGRES_USER", "POSTGRES_PASSWORD", "APP_HOST", "APP_ENV"):
|
||||
if not values[name]:
|
||||
raise SystemExit(f"{name} must not be empty")
|
||||
# Existing values, including credentials, are never replaced.
|
||||
missing = {key: value for key, value in values.items() if key not in existing}
|
||||
if missing:
|
||||
prefix = "\n" if path.exists() and path.stat().st_size else ""
|
||||
with path.open("a", encoding="utf-8") as file:
|
||||
file.write(prefix + "".join(f"{key}={value}\n" for key, value in missing.items()))
|
||||
os.chmod(path, 0o600)
|
||||
secret_dir = ROOT / "secrets"
|
||||
secret_dir.mkdir(mode=0o700, exist_ok=True)
|
||||
database_url = "postgres://{}:{}@db:5432/{}?sslmode=disable".format(
|
||||
quote(values["POSTGRES_USER"], safe=""), quote(values["POSTGRES_PASSWORD"], safe=""),
|
||||
quote(values["POSTGRES_DB"], safe=""))
|
||||
for name, content in (("DATABASE_URL_FILE", database_url),
|
||||
("CACHE_URL_FILE", "redis://redis:6379/0")):
|
||||
container_path = Path(values[name])
|
||||
if container_path.parent != Path("/run/secrets") or not container_path.name:
|
||||
raise SystemExit(f"{name} must name a file directly inside /run/secrets")
|
||||
target = secret_dir / ("database_url" if name == "DATABASE_URL_FILE" else "cache_url")
|
||||
if not target.exists():
|
||||
# Containers run as an unprivileged user; the private host directory
|
||||
# protects the files, while read permission lets the API consume them.
|
||||
with target.open("x", encoding="utf-8") as file:
|
||||
file.write(content + "\n")
|
||||
os.chmod(target, 0o644)
|
||||
print("Local .env and connection files ready; existing values and files preserved.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart db redis >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait db redis >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml restart api >/dev/null
|
||||
docker compose --project-name highload-lab4 --env-file .env -f compose.yml up -d --wait >/dev/null
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID to the X-Instance-Id of an API replica}"
|
||||
for container in $(docker compose --project-name highload-lab4 --env-file .env -f compose.yml ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
# Only containers from this Compose project's api service are eligible.
|
||||
docker stop --timeout 8 "$container" >/dev/null
|
||||
printf 'Stopped API instance %s\n' "$hostname"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
printf 'No running API replica matches TARGET_INSTANCE_ID\n' >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user