Лабораторная 4
This commit is contained in:
@@ -8,8 +8,8 @@ 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())
|
||||
lab = json.loads((ROOT/'lab.json').read_text(encoding='utf-8'))['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text(encoding='utf-8'))
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
@@ -41,11 +41,11 @@ def main():
|
||||
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))
|
||||
ast.parse(file.read_text(encoding='utf-8'),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())
|
||||
json.loads(file.read_text(encoding='utf-8'))
|
||||
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.')
|
||||
|
||||
Executable
+73
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reconcile attachment metadata in PostgreSQL against the MinIO object store."""
|
||||
import argparse
|
||||
import datetime
|
||||
import os
|
||||
|
||||
import boto3
|
||||
import psycopg
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--apply", action="store_true")
|
||||
p.add_argument("--grace-hours", type=int, default=24)
|
||||
p.add_argument("--bucket", default=os.environ.get("S3_BUCKET", "messenger-attachments"))
|
||||
args = p.parse_args()
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"],
|
||||
aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"],
|
||||
config=Config(s3={"addressing_style": "path"}),
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
)
|
||||
objects = set()
|
||||
token = None
|
||||
while True:
|
||||
kwargs = {"Bucket": args.bucket}
|
||||
if token:
|
||||
kwargs["ContinuationToken"] = token
|
||||
page = s3.list_objects_v2(**kwargs)
|
||||
objects.update(x["Key"] for x in page.get("Contents", []))
|
||||
if not page.get("IsTruncated"):
|
||||
break
|
||||
token = page["NextContinuationToken"]
|
||||
|
||||
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id,object_key,status,created_at FROM attachments"
|
||||
).fetchall()
|
||||
|
||||
db_keys = {row[1]: row for row in rows}
|
||||
missing = [row for key, row in db_keys.items() if key not in objects]
|
||||
orphaned = [key for key in objects if key not in db_keys]
|
||||
print(f"metadata={len(db_keys)} objects={len(objects)} missing={len(missing)} orphaned={len(orphaned)}")
|
||||
|
||||
if args.apply:
|
||||
grace = datetime.datetime.now(datetime.timezone.utc) - datetime.timedelta(hours=args.grace_hours)
|
||||
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
|
||||
for row in missing:
|
||||
if row[3] < grace:
|
||||
conn.execute(
|
||||
"UPDATE attachments SET status='failed',error_code='missing_object' WHERE id=%s",
|
||||
(row[0],),
|
||||
)
|
||||
deleted = 0
|
||||
for key in orphaned:
|
||||
head = s3.head_object(Bucket=args.bucket, Key=key)
|
||||
modified = head["LastModified"]
|
||||
if modified.tzinfo is None:
|
||||
modified = modified.replace(tzinfo=datetime.timezone.utc)
|
||||
if modified < grace:
|
||||
s3.delete_object(Bucket=args.bucket, Key=key)
|
||||
deleted += 1
|
||||
print(f"marked_missing={len(missing)} deleted_orphans={deleted}")
|
||||
else:
|
||||
print("dry-run only; use --apply to make changes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose --env-file .env restart postgres s3 api1 api2 nginx
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "restart", "postgres", "s3", "api1", "api2", "nginx"],
|
||||
cwd=root,
|
||||
check=True,
|
||||
)
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart postgres s3 api1 api2 nginx
|
||||
docker compose --env-file .env up -d s3-bootstrap
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
if "%TARGET_INSTANCE_ID%"=="api-1" docker compose --env-file .env stop api1
|
||||
if "%TARGET_INSTANCE_ID%"=="api-2" docker compose --env-file .env stop api2
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
target = os.environ["TARGET_INSTANCE_ID"]
|
||||
service = {"api-1": "api1", "api-2": "api2"}[target]
|
||||
subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", "stop", service],
|
||||
cwd=root,
|
||||
check=True,
|
||||
)
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
api-1) docker compose --env-file .env stop api1 ;;
|
||||
api-2) docker compose --env-file .env stop api2 ;;
|
||||
*) echo "Unknown API instance alias" >&2; exit 2 ;;
|
||||
esac
|
||||
Reference in New Issue
Block a user