forked from mtusi2026/mtusi2026lab4
[+] add project
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Idempotently create the private bucket and restricted RustFS API user."""
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import boto3
|
||||
import botocore
|
||||
from botocore.auth import SigV4Auth
|
||||
from botocore.awsrequest import AWSRequest
|
||||
from botocore.credentials import Credentials
|
||||
from botocore.exceptions import ClientError
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def secret(name):
|
||||
return Path(os.environ[name + "_FILE"]).read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def signed_admin_request(root_access, root_secret, method, path, body=None):
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000")
|
||||
region = os.environ.get("S3_REGION", "us-east-1")
|
||||
content = json.dumps(body, separators=(",", ":")).encode("utf-8") if body else b""
|
||||
url = endpoint.rstrip("/") + path
|
||||
headers = {
|
||||
"Host": url.split("/", 3)[2],
|
||||
"Content-Type": "application/json",
|
||||
"X-Amz-Content-SHA256": hashlib.sha256(content).hexdigest(),
|
||||
}
|
||||
request = AWSRequest(method=method, url=url, data=content, headers=headers)
|
||||
SigV4Auth(Credentials(root_access, root_secret), "s3", region).add_auth(request)
|
||||
http_request = Request(
|
||||
url,
|
||||
data=content if content else None,
|
||||
headers=dict(request.headers),
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urlopen(http_request, timeout=5) as response:
|
||||
response.read()
|
||||
except HTTPError as error:
|
||||
detail = error.read(2048).decode("utf-8", "replace")
|
||||
if error.code == 409 and "add-user" in path:
|
||||
return
|
||||
raise RuntimeError(
|
||||
"RustFS IAM bootstrap request failed: "
|
||||
+ method
|
||||
+ " "
|
||||
+ path.split("?", 1)[0]
|
||||
+ " returned "
|
||||
+ str(error.code)
|
||||
+ ": "
|
||||
+ detail[:300]
|
||||
) from None
|
||||
except URLError as error:
|
||||
raise RuntimeError("RustFS IAM bootstrap service is unavailable") from error
|
||||
|
||||
|
||||
def main():
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "http://s3:9000")
|
||||
region = os.environ.get("S3_REGION", "us-east-1")
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
root_access = secret("S3_ROOT_ACCESS_KEY")
|
||||
root_secret = secret("S3_ROOT_SECRET_KEY")
|
||||
app_access = secret("S3_ACCESS_KEY_ID")
|
||||
app_secret = secret("S3_SECRET_ACCESS_KEY")
|
||||
config = Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=2,
|
||||
read_timeout=5,
|
||||
retries={"max_attempts": 2, "mode": "standard"},
|
||||
)
|
||||
root = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=root_access,
|
||||
aws_secret_access_key=root_secret,
|
||||
config=config,
|
||||
)
|
||||
for attempt in range(30):
|
||||
try:
|
||||
try:
|
||||
root.create_bucket(Bucket=bucket)
|
||||
except ClientError as error:
|
||||
if error.response.get("Error", {}).get("Code") != "BucketAlreadyOwnedByYou":
|
||||
raise
|
||||
root.head_bucket(Bucket=bucket)
|
||||
break
|
||||
except (botocore.exceptions.BotoCoreError, ClientError):
|
||||
if attempt == 29:
|
||||
raise
|
||||
time.sleep(2)
|
||||
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::" + bucket],
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::" + bucket + "/attachments/*"],
|
||||
},
|
||||
],
|
||||
}
|
||||
signed_admin_request(
|
||||
root_access,
|
||||
root_secret,
|
||||
"PUT",
|
||||
"/rustfs/admin/v3/add-user?" + urlencode({"accessKey": app_access}),
|
||||
{"secretKey": app_secret, "status": "enabled"},
|
||||
)
|
||||
signed_admin_request(
|
||||
root_access,
|
||||
root_secret,
|
||||
"PUT",
|
||||
"/rustfs/admin/v3/add-canned-policy?" + urlencode({"name": "messenger-api"}),
|
||||
policy,
|
||||
)
|
||||
signed_admin_request(
|
||||
root_access,
|
||||
root_secret,
|
||||
"POST",
|
||||
"/rustfs/admin/v3/idp/builtin/policy/attach",
|
||||
{"policies": ["messenger-api"], "user": app_access},
|
||||
)
|
||||
|
||||
api_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=app_access,
|
||||
aws_secret_access_key=app_secret,
|
||||
config=config,
|
||||
)
|
||||
api_client.head_bucket(Bucket=bucket)
|
||||
root.close()
|
||||
api_client.close()
|
||||
print("S3 bootstrap complete: private bucket and scoped API credentials are ready.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
umask 077
|
||||
mkdir -p secrets
|
||||
|
||||
create_secret() {
|
||||
name=$1
|
||||
length=$2
|
||||
if [ ! -s "secrets/$name" ]; then
|
||||
openssl rand -hex "$length" > "secrets/$name"
|
||||
chmod 600 "secrets/$name"
|
||||
fi
|
||||
}
|
||||
|
||||
create_secret database_password 32
|
||||
create_secret s3_root_access_key 16
|
||||
create_secret s3_root_secret_key 32
|
||||
create_secret s3_access_key_id 16
|
||||
create_secret s3_secret_access_key 32
|
||||
printf '%s\n' 'Local Compose secrets are ready; values were not printed.'
|
||||
Executable
+177
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reconcile attachment object keys and metadata; safe by default."""
|
||||
import argparse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from app.settings import database_connection, read_setting
|
||||
|
||||
LOGGER = logging.getLogger("attachment-reconciler")
|
||||
|
||||
|
||||
def plan_reconciliation(metadata, objects, now, grace):
|
||||
cutoff = now - grace
|
||||
object_keys = {item["Key"]: item for item in objects}
|
||||
metadata_by_key = {row["object_key"]: row for row in metadata}
|
||||
return {
|
||||
"orphan_old": sorted(
|
||||
key
|
||||
for key, item in object_keys.items()
|
||||
if key.startswith("attachments/")
|
||||
and key not in metadata_by_key
|
||||
and item.get("LastModified") is not None
|
||||
and item["LastModified"] <= cutoff
|
||||
),
|
||||
"orphan_fresh": sorted(
|
||||
key
|
||||
for key, item in object_keys.items()
|
||||
if key.startswith("attachments/")
|
||||
and key not in metadata_by_key
|
||||
and (
|
||||
item.get("LastModified") is None
|
||||
or item["LastModified"] > cutoff
|
||||
)
|
||||
),
|
||||
"missing_unreferenced_old": sorted(
|
||||
row["id"]
|
||||
for row in metadata
|
||||
if row["object_key"] not in object_keys
|
||||
and not row["referenced"]
|
||||
and row["created_at"] <= cutoff
|
||||
),
|
||||
"missing_protected": sorted(
|
||||
row["id"]
|
||||
for row in metadata
|
||||
if row["object_key"] not in object_keys
|
||||
and (row["referenced"] or row["created_at"] > cutoff)
|
||||
),
|
||||
"object_count": len(object_keys),
|
||||
"metadata_count": len(metadata_by_key),
|
||||
}
|
||||
|
||||
|
||||
def load_state(connection, s3, bucket):
|
||||
metadata = connection.execute(
|
||||
"""
|
||||
SELECT a.id::text AS id, a.object_key, a.created_at,
|
||||
EXISTS (
|
||||
SELECT 1 FROM message_attachments ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
) AS referenced
|
||||
FROM attachments a
|
||||
"""
|
||||
).fetchall()
|
||||
paginator = s3.get_paginator("list_objects_v2")
|
||||
objects = []
|
||||
for page in paginator.paginate(Bucket=bucket, Prefix="attachments/"):
|
||||
objects.extend(page.get("Contents", []))
|
||||
return metadata, objects
|
||||
|
||||
|
||||
def apply_plan(connection, s3, bucket, plan):
|
||||
deleted_objects = 0
|
||||
deleted_metadata = 0
|
||||
for key in plan["orphan_old"]:
|
||||
s3.delete_object(Bucket=bucket, Key=key)
|
||||
deleted_objects += 1
|
||||
for attachment_id in plan["missing_unreferenced_old"]:
|
||||
with connection.transaction():
|
||||
row = connection.execute(
|
||||
"""
|
||||
DELETE FROM attachments AS a
|
||||
WHERE a.id = %s
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM message_attachments ma
|
||||
WHERE ma.attachment_id = a.id
|
||||
)
|
||||
RETURNING a.id
|
||||
""",
|
||||
(attachment_id,),
|
||||
).fetchone()
|
||||
if row:
|
||||
deleted_metadata += 1
|
||||
return deleted_objects, deleted_metadata
|
||||
|
||||
|
||||
def main():
|
||||
import boto3
|
||||
import botocore
|
||||
import psycopg
|
||||
from botocore.config import Config
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument(
|
||||
"--apply",
|
||||
action="store_true",
|
||||
help="delete stale orphan objects and stale unreferenced missing metadata",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--grace-hours",
|
||||
type=float,
|
||||
default=24,
|
||||
help="minimum age before repair; defaults to 24 hours",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.grace_hours < 0:
|
||||
parser.error("--grace-hours cannot be negative")
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
started = time.monotonic()
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_setting("S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=read_setting("S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
connect_timeout=2, read_timeout=10,
|
||||
retries={"max_attempts": 2, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
try:
|
||||
with psycopg.connect(**database_connection(), row_factory=dict_row) as connection:
|
||||
metadata, objects = load_state(connection, s3, bucket)
|
||||
plan = plan_reconciliation(
|
||||
metadata,
|
||||
objects,
|
||||
datetime.now(timezone.utc),
|
||||
timedelta(hours=args.grace_hours),
|
||||
)
|
||||
changes = {"objects_deleted": 0, "metadata_deleted": 0}
|
||||
if args.apply:
|
||||
(
|
||||
changes["objects_deleted"],
|
||||
changes["metadata_deleted"],
|
||||
) = apply_plan(connection, s3, bucket, plan)
|
||||
except (psycopg.Error, botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError):
|
||||
LOGGER.exception("reconciliation failed; no success result was produced")
|
||||
raise SystemExit(1) from None
|
||||
summary = {
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"grace_hours": args.grace_hours,
|
||||
"objects_scanned": plan["object_count"],
|
||||
"metadata_scanned": plan["metadata_count"],
|
||||
"orphan_objects": len(plan["orphan_old"]) + len(plan["orphan_fresh"]),
|
||||
"orphan_old_candidates": len(plan["orphan_old"]),
|
||||
"orphan_fresh_preserved": len(plan["orphan_fresh"]),
|
||||
"missing_metadata_rows": len(plan["missing_unreferenced_old"])
|
||||
+ len(plan["missing_protected"]),
|
||||
"missing_unreferenced_old_candidates": len(plan["missing_unreferenced_old"]),
|
||||
"missing_referenced_or_fresh_preserved": len(plan["missing_protected"]),
|
||||
**changes,
|
||||
"elapsed_seconds": round(time.monotonic() - started, 3),
|
||||
}
|
||||
print(json.dumps(summary, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
docker compose restart postgres redis s3 >/dev/null
|
||||
deadline=$(( $(date +%s) + 60 ))
|
||||
for service in postgres redis; do
|
||||
container=$(docker compose ps -q "$service")
|
||||
while :; do
|
||||
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
|
||||
if [ "$status" = healthy ]; then
|
||||
break
|
||||
fi
|
||||
if [ "$status" = unhealthy ] || [ "$(date +%s)" -ge "$deadline" ]; then
|
||||
printf '%s\n' "$service did not become healthy after restart" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
done
|
||||
|
||||
docker compose run --rm --no-deps s3-bootstrap >/dev/null
|
||||
"$ROOT/scripts/rolling-restart.sh"
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
containers=$(docker compose ps -q api)
|
||||
healthy_count=0
|
||||
for container in $containers; do
|
||||
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
|
||||
if [ "$status" = healthy ]; then
|
||||
healthy_count=$((healthy_count + 1))
|
||||
fi
|
||||
done
|
||||
if [ "$healthy_count" -lt 2 ]; then
|
||||
printf '%s\n' 'Rolling restart requires at least two healthy API replicas' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
for container in $containers; do
|
||||
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
|
||||
if [ "$status" != healthy ]; then
|
||||
printf '%s\n' "Skipping unhealthy API replica: $container" >&2
|
||||
continue
|
||||
fi
|
||||
docker restart --time 10 "$container" >/dev/null
|
||||
deadline=$(( $(date +%s) + 60 ))
|
||||
while :; do
|
||||
status=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$container")
|
||||
if [ "$status" = healthy ]; then
|
||||
break
|
||||
fi
|
||||
if [ "$status" = unhealthy ] || [ "$(date +%s)" -ge "$deadline" ]; then
|
||||
printf '%s\n' "API replica did not become healthy: $container" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
done
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
|
||||
for container in $(docker compose ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop --time 2 "$container" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
printf '%s\n' 'No running API replica matches TARGET_INSTANCE_ID' >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user