forked from mtusi2026/mtusi2026lab4
all for lab4
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
FROM golang:1.24.2-bookworm AS builder
|
||||
|
||||
ENV CGO_ENABLED=0
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN git clone --depth 1 \
|
||||
--branch RELEASE.2025-04-22T22-12-26Z \
|
||||
https://github.com/minio/minio.git /src/minio
|
||||
|
||||
WORKDIR /src/minio
|
||||
|
||||
RUN go build -trimpath -o /out/minio .
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
RUN git clone --depth 1 \
|
||||
--branch RELEASE.2025-04-16T18-13-26Z \
|
||||
https://github.com/minio/mc.git /src/mc
|
||||
|
||||
WORKDIR /src/mc
|
||||
|
||||
RUN go build -trimpath -o /out/mc .
|
||||
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY --from=builder /out/minio /usr/local/bin/minio
|
||||
COPY --from=builder /out/mc /usr/local/bin/mc
|
||||
|
||||
RUN mkdir -p /data
|
||||
|
||||
EXPOSE 9000 9001
|
||||
|
||||
ENTRYPOINT ["minio"]
|
||||
CMD ["server", "/data", "--console-address", ":9001"]
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${MINIO_ROOT_USER:?}"
|
||||
: "${MINIO_ROOT_PASSWORD:?}"
|
||||
: "${S3_BUCKET:?}"
|
||||
: "${S3_ACCESS_KEY:?}"
|
||||
: "${S3_SECRET_KEY:?}"
|
||||
|
||||
if [ "$S3_ACCESS_KEY" = "$MINIO_ROOT_USER" ]; then
|
||||
echo "API must use a separate MinIO user" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$S3_SECRET_KEY" = "$MINIO_ROOT_PASSWORD" ]; then
|
||||
echo "API and administrator passwords must differ" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$S3_BUCKET" in
|
||||
""|*[!a-z0-9.-]*)
|
||||
echo "Invalid bucket name" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
mc alias set storage http://minio:9000 \
|
||||
"$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null
|
||||
|
||||
mc mb --ignore-existing "storage/$S3_BUCKET"
|
||||
|
||||
mc anonymous set none "storage/$S3_BUCKET"
|
||||
|
||||
cat > /tmp/attachments-policy.json <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Sid": "InspectAttachmentBucket",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetBucketLocation",
|
||||
"s3:ListBucket"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::$S3_BUCKET"
|
||||
]
|
||||
},
|
||||
{
|
||||
"Sid": "ManageOriginalAttachments",
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetObject",
|
||||
"s3:PutObject",
|
||||
"s3:DeleteObject",
|
||||
"s3:AbortMultipartUpload",
|
||||
"s3:ListMultipartUploadParts"
|
||||
],
|
||||
"Resource": [
|
||||
"arn:aws:s3:::$S3_BUCKET/originals/*"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
POLICY_NAME=messenger-attachments-api
|
||||
|
||||
mc admin policy create \
|
||||
storage "$POLICY_NAME" /tmp/attachments-policy.json
|
||||
|
||||
mc admin user add \
|
||||
storage "$S3_ACCESS_KEY" "$S3_SECRET_KEY" >/dev/null
|
||||
|
||||
mc admin user info --json \
|
||||
storage "$S3_ACCESS_KEY" > /tmp/api-user.json
|
||||
|
||||
if grep -Eq \
|
||||
'"policyName"[[:space:]]*:[[:space:]]*"messenger-attachments-api"' \
|
||||
/tmp/api-user.json
|
||||
then
|
||||
echo "API policy is already attached"
|
||||
else
|
||||
mc admin policy attach \
|
||||
storage "$POLICY_NAME" --user "$S3_ACCESS_KEY"
|
||||
fi
|
||||
|
||||
mc alias set app http://minio:9000 \
|
||||
"$S3_ACCESS_KEY" "$S3_SECRET_KEY" >/dev/null
|
||||
|
||||
mc stat "app/$S3_BUCKET" >/dev/null
|
||||
|
||||
echo "Bootstrap completed: private bucket and API user are ready"
|
||||
@@ -0,0 +1,98 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${S3_BUCKET:?}"
|
||||
: "${S3_ACCESS_KEY:?}"
|
||||
: "${S3_SECRET_KEY:?}"
|
||||
|
||||
mc alias set app http://minio:9000 \
|
||||
"$S3_ACCESS_KEY" "$S3_SECRET_KEY" >/dev/null
|
||||
|
||||
TEST_ID="$(cat /proc/sys/kernel/random/uuid)"
|
||||
OBJECT_KEY="originals/access-check-$TEST_ID.txt"
|
||||
OUTSIDE_KEY="outside-access-check-$TEST_ID.txt"
|
||||
|
||||
cleanup() {
|
||||
mc rm --force \
|
||||
"app/$S3_BUCKET/$OBJECT_KEY" >/dev/null 2>&1 || true
|
||||
|
||||
mc rm --force \
|
||||
"app/$S3_BUCKET/$OUTSIDE_KEY" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
|
||||
printf 'private attachment test' > /tmp/expected.txt
|
||||
|
||||
mc cp /tmp/expected.txt \
|
||||
"app/$S3_BUCKET/$OBJECT_KEY" >/dev/null
|
||||
|
||||
mc cat "app/$S3_BUCKET/$OBJECT_KEY" > /tmp/actual.txt
|
||||
|
||||
cmp /tmp/expected.txt /tmp/actual.txt
|
||||
|
||||
echo "PASS: API credentials can upload and download originals"
|
||||
|
||||
HTTP_CODE="$(
|
||||
curl --silent --show-error \
|
||||
--connect-timeout 3 \
|
||||
--max-time 10 \
|
||||
--output /tmp/anonymous-response.xml \
|
||||
--write-out '%{http_code}' \
|
||||
"http://minio:9000/$S3_BUCKET/$OBJECT_KEY"
|
||||
)"
|
||||
|
||||
if [ "$HTTP_CODE" != "403" ]; then
|
||||
echo "FAIL: anonymous GET returned HTTP $HTTP_CODE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -q '<Code>AccessDenied</Code>' \
|
||||
/tmp/anonymous-response.xml
|
||||
then
|
||||
echo "FAIL: expected S3 AccessDenied response" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: anonymous download of an existing object is denied"
|
||||
|
||||
if mc cp /tmp/expected.txt \
|
||||
"app/$S3_BUCKET/$OUTSIDE_KEY" \
|
||||
> /tmp/outside-result.txt 2>&1
|
||||
then
|
||||
echo "FAIL: API credentials can write outside originals/" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Eiq \
|
||||
'AccessDenied|Access Denied|Insufficient permissions|not authorized|not allowed' \
|
||||
/tmp/outside-result.txt
|
||||
then
|
||||
echo "FAIL: write failed for a reason other than access denial" >&2
|
||||
cat /tmp/outside-result.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: writing outside originals/ is denied"
|
||||
|
||||
if mc admin info app > /tmp/admin-result.txt 2>&1
|
||||
then
|
||||
echo "FAIL: API credentials have administrative access" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Eiq \
|
||||
'AccessDenied|Access Denied|Insufficient permissions|not authorized|not allowed' \
|
||||
/tmp/admin-result.txt
|
||||
then
|
||||
echo "FAIL: admin command failed for an unexpected reason" >&2
|
||||
cat /tmp/admin-result.txt >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: administrative access is denied"
|
||||
|
||||
mc rm "app/$S3_BUCKET/$OBJECT_KEY" >/dev/null
|
||||
|
||||
echo "PASS: API credentials can delete originals for cleanup"
|
||||
echo "PASS: S3 access checks completed"
|
||||
@@ -0,0 +1,17 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN pip install --no-cache-dir \
|
||||
boto3==1.35.99 \
|
||||
"psycopg[binary]==3.2.4"
|
||||
|
||||
COPY reconcile_worker.py /app/reconcile_worker.py
|
||||
|
||||
USER 65534:65534
|
||||
|
||||
ENTRYPOINT ["python", "/app/reconcile_worker.py"]
|
||||
@@ -0,0 +1,454 @@
|
||||
import base64
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
class Reconciler:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
self.started = time.monotonic()
|
||||
|
||||
self.cutoff = (
|
||||
datetime.now(timezone.utc)
|
||||
- timedelta(seconds=config["grace_seconds"])
|
||||
)
|
||||
|
||||
self.counts = Counter()
|
||||
self.sql_calls = 0
|
||||
self.s3_calls = Counter()
|
||||
self.examples = []
|
||||
self.db = None
|
||||
|
||||
self.s3 = boto3.client(
|
||||
"s3",
|
||||
**config["s3"],
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=3,
|
||||
read_timeout=15,
|
||||
retries={"total_max_attempts": 1},
|
||||
),
|
||||
)
|
||||
|
||||
def sql(self, statement, params=()):
|
||||
self.sql_calls += 1
|
||||
return self.db.execute(statement, params)
|
||||
|
||||
def call(self, operation, **kwargs):
|
||||
self.s3_calls[operation] += 1
|
||||
|
||||
return getattr(self.s3, operation)(
|
||||
Bucket=self.config["bucket"],
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
def event(self, name, key=None):
|
||||
self.counts[name] += 1
|
||||
|
||||
# Ограничиваем размер подробной части отчёта.
|
||||
if key is not None and len(self.examples) < 100:
|
||||
self.examples.append({
|
||||
"outcome": name,
|
||||
"object_key": key,
|
||||
})
|
||||
|
||||
def deadline(self):
|
||||
elapsed = time.monotonic() - self.started
|
||||
|
||||
if elapsed > self.config["max_seconds"]:
|
||||
raise TimeoutError("Scan deadline reached")
|
||||
|
||||
def lock(self, key):
|
||||
# Тот же ключ блокировки, что используется
|
||||
# AttachmentRepository в Java.
|
||||
row = self.sql(
|
||||
"""
|
||||
SELECT pg_try_advisory_xact_lock(
|
||||
hashtextextended(%s, 0)
|
||||
) AS ok
|
||||
""",
|
||||
("attachment-object:" + key,),
|
||||
).fetchone()
|
||||
|
||||
if not row["ok"]:
|
||||
self.event("busy", key)
|
||||
|
||||
return row["ok"]
|
||||
|
||||
def head(self, key):
|
||||
try:
|
||||
return self.call("head_object", Key=key)
|
||||
|
||||
except ClientError as error:
|
||||
code = error.response.get("Error", {}).get("Code", "")
|
||||
|
||||
if code not in (
|
||||
"404",
|
||||
"NoSuchKey",
|
||||
"NoSuchObject",
|
||||
"NotFound",
|
||||
):
|
||||
raise
|
||||
|
||||
# Проверяем, что доступен сам bucket.
|
||||
# Исчезновение bucket не считаем потерей
|
||||
# отдельного оригинала.
|
||||
self.call("head_bucket")
|
||||
|
||||
return None
|
||||
|
||||
def scan_objects(self):
|
||||
token = None
|
||||
chat_id = self.config.get("chat_id")
|
||||
|
||||
prefix = (
|
||||
f"originals/{chat_id}/"
|
||||
if chat_id
|
||||
else "originals/"
|
||||
)
|
||||
|
||||
while True:
|
||||
self.deadline()
|
||||
|
||||
args = {
|
||||
"Prefix": prefix,
|
||||
"MaxKeys": 500,
|
||||
}
|
||||
|
||||
if token:
|
||||
args["ContinuationToken"] = token
|
||||
|
||||
page = self.call("list_objects_v2", **args)
|
||||
|
||||
for item in page.get("Contents", []):
|
||||
self.deadline()
|
||||
self.event("objects_scanned")
|
||||
|
||||
key = item["Key"]
|
||||
|
||||
if item["LastModified"] >= self.cutoff:
|
||||
self.event("fresh_objects")
|
||||
continue
|
||||
|
||||
with self.db.transaction():
|
||||
if not self.lock(key):
|
||||
continue
|
||||
|
||||
# Проверяем всю таблицу, даже если проход
|
||||
# ограничен одним тестовым чатом.
|
||||
row = self.sql(
|
||||
"""
|
||||
SELECT id
|
||||
FROM attachments
|
||||
WHERE object_key = %s
|
||||
""",
|
||||
(key,),
|
||||
).fetchone()
|
||||
|
||||
if row:
|
||||
self.event("referenced_objects")
|
||||
continue
|
||||
|
||||
# Повторная проверка после блокировки.
|
||||
current = self.head(key)
|
||||
|
||||
if current is None:
|
||||
self.event("already_absent")
|
||||
|
||||
elif current["LastModified"] >= self.cutoff:
|
||||
self.event("fresh_objects")
|
||||
|
||||
elif self.config["apply"]:
|
||||
self.call("delete_object", Key=key)
|
||||
self.event("deleted_orphans", key)
|
||||
|
||||
else:
|
||||
self.event("would_delete_orphans", key)
|
||||
|
||||
if not page.get("IsTruncated"):
|
||||
break
|
||||
|
||||
token = page["NextContinuationToken"]
|
||||
|
||||
def backup(self, row):
|
||||
checksum = row["sha256"].strip()
|
||||
|
||||
if not re.fullmatch("[a-f0-9]{64}", checksum):
|
||||
raise ValueError("Invalid metadata checksum")
|
||||
|
||||
# Имя копии определяется SHA-256, а не filename.
|
||||
path = Path("/backups") / (checksum + ".bin")
|
||||
|
||||
if not path.exists():
|
||||
return None
|
||||
|
||||
# Ограничиваем чтение даже для ошибочной копии.
|
||||
with path.open("rb") as stream:
|
||||
data = stream.read(MAX_BYTES + 1)
|
||||
|
||||
valid = (
|
||||
len(data) == row["size_bytes"]
|
||||
and hashlib.sha256(data).hexdigest() == checksum
|
||||
)
|
||||
|
||||
if not valid:
|
||||
self.event("invalid_backups", row["object_key"])
|
||||
return None
|
||||
|
||||
return data
|
||||
|
||||
def check_attachment(self, attachment_id):
|
||||
# В текущем протоколе object_key неизменяем.
|
||||
initial = self.sql(
|
||||
"""
|
||||
SELECT object_key
|
||||
FROM attachments
|
||||
WHERE id = %s
|
||||
""",
|
||||
(attachment_id,),
|
||||
).fetchone()
|
||||
|
||||
if not initial:
|
||||
return
|
||||
|
||||
key = initial["object_key"]
|
||||
|
||||
with self.db.transaction():
|
||||
if not self.lock(key):
|
||||
return
|
||||
|
||||
row = self.sql(
|
||||
"""
|
||||
SELECT *
|
||||
FROM attachments
|
||||
WHERE id = %s
|
||||
FOR SHARE
|
||||
""",
|
||||
(attachment_id,),
|
||||
).fetchone()
|
||||
|
||||
if not row:
|
||||
return
|
||||
|
||||
if (
|
||||
row["object_key"] != key
|
||||
or not key.startswith("originals/")
|
||||
):
|
||||
raise ValueError("Unsupported object key")
|
||||
|
||||
if row["created_at"] >= self.cutoff:
|
||||
self.event("fresh_metadata")
|
||||
return
|
||||
|
||||
current = self.head(key)
|
||||
|
||||
if current is not None:
|
||||
if current["ContentLength"] == row["size_bytes"]:
|
||||
self.event("present_metadata")
|
||||
else:
|
||||
self.event("size_mismatches", key)
|
||||
|
||||
return
|
||||
|
||||
self.event("missing_objects", key)
|
||||
|
||||
data = self.backup(row)
|
||||
|
||||
if data is None:
|
||||
# Метаданные и сообщения сохраняем.
|
||||
self.event("unresolved_missing", key)
|
||||
return
|
||||
|
||||
if not self.config["apply"]:
|
||||
self.event("would_restore", key)
|
||||
return
|
||||
|
||||
# Восстанавливаем отсутствующий объект,
|
||||
# удерживая ту же блокировку, что и API.
|
||||
self.call(
|
||||
"put_object",
|
||||
Key=key,
|
||||
Body=data,
|
||||
ContentType=row["content_type"],
|
||||
ContentMD5=base64.b64encode(
|
||||
hashlib.md5(data).digest()
|
||||
).decode("ascii"),
|
||||
)
|
||||
|
||||
# Проверяем фактические байты после записи.
|
||||
response = self.call("get_object", Key=key)
|
||||
|
||||
with response["Body"] as stream:
|
||||
actual = stream.read(MAX_BYTES + 1)
|
||||
|
||||
valid = (
|
||||
len(actual) == row["size_bytes"]
|
||||
and hashlib.sha256(actual).hexdigest()
|
||||
== row["sha256"].strip()
|
||||
)
|
||||
|
||||
if not valid:
|
||||
raise ValueError(
|
||||
"Restored object verification failed"
|
||||
)
|
||||
|
||||
self.event("restored", key)
|
||||
|
||||
def scan_metadata(self):
|
||||
cursor = None
|
||||
chat_id = self.config.get("chat_id")
|
||||
|
||||
while True:
|
||||
self.deadline()
|
||||
|
||||
rows = self.sql(
|
||||
"""
|
||||
SELECT id
|
||||
FROM attachments
|
||||
WHERE (
|
||||
%s::uuid IS NULL
|
||||
OR chat_id = %s::uuid
|
||||
)
|
||||
AND (
|
||||
%s::uuid IS NULL
|
||||
OR id > %s::uuid
|
||||
)
|
||||
ORDER BY id
|
||||
LIMIT 500
|
||||
""",
|
||||
(chat_id, chat_id, cursor, cursor),
|
||||
).fetchall()
|
||||
|
||||
if not rows:
|
||||
return
|
||||
|
||||
for row in rows:
|
||||
self.deadline()
|
||||
self.event("metadata_scanned")
|
||||
self.check_attachment(row["id"])
|
||||
|
||||
cursor = rows[-1]["id"]
|
||||
|
||||
def run(self):
|
||||
status = "completed"
|
||||
error_type = None
|
||||
|
||||
try:
|
||||
with psycopg.connect(
|
||||
**self.config["db"],
|
||||
autocommit=True,
|
||||
row_factory=dict_row,
|
||||
connect_timeout=5,
|
||||
options=(
|
||||
"-c statement_timeout=10000 "
|
||||
"-c idle_in_transaction_session_timeout=120000"
|
||||
),
|
||||
) as db:
|
||||
self.db = db
|
||||
|
||||
# Только один полный проход этой утилиты
|
||||
# одновременно в данной БД.
|
||||
locked = self.sql(
|
||||
"""
|
||||
SELECT pg_try_advisory_lock(
|
||||
hashtextextended(
|
||||
'attachment-reconciler:v1',
|
||||
0
|
||||
)
|
||||
) AS ok
|
||||
"""
|
||||
).fetchone()["ok"]
|
||||
|
||||
if not locked:
|
||||
raise RuntimeError(
|
||||
"Another reconciler is running"
|
||||
)
|
||||
|
||||
self.call("head_bucket")
|
||||
|
||||
self.scan_objects()
|
||||
self.scan_metadata()
|
||||
|
||||
# Закрытие соединения освобождает session lock.
|
||||
# Блокировки объектов освобождаются
|
||||
# при завершении отдельных транзакций.
|
||||
|
||||
except Exception as error:
|
||||
status = "failed"
|
||||
error_type = type(error).__name__
|
||||
|
||||
finally:
|
||||
self.s3.close()
|
||||
|
||||
attention_counters = (
|
||||
"unresolved_missing",
|
||||
"size_mismatches",
|
||||
"invalid_backups",
|
||||
"busy",
|
||||
)
|
||||
|
||||
if status == "completed" and any(
|
||||
self.counts[name] for name in attention_counters
|
||||
):
|
||||
status = "needs_attention"
|
||||
|
||||
report = {
|
||||
"status": status,
|
||||
"mode": (
|
||||
"apply"
|
||||
if self.config["apply"]
|
||||
else "dry-run"
|
||||
),
|
||||
"chat_id": self.config.get("chat_id"),
|
||||
"cutoff": self.cutoff.isoformat(),
|
||||
"elapsed_seconds": round(
|
||||
time.monotonic() - self.started,
|
||||
3,
|
||||
),
|
||||
"counts": dict(self.counts),
|
||||
"sql_statement_calls": self.sql_calls,
|
||||
"s3_operation_calls": dict(self.s3_calls),
|
||||
"examples": self.examples,
|
||||
"examples_limit": 100,
|
||||
"error_type": error_type,
|
||||
}
|
||||
|
||||
print(json.dumps(
|
||||
report,
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
))
|
||||
|
||||
return {
|
||||
"completed": 0,
|
||||
"needs_attention": 2,
|
||||
"failed": 1,
|
||||
}[status]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
config = json.load(sys.stdin)
|
||||
|
||||
if (
|
||||
config["grace_seconds"] < 60
|
||||
or config["max_seconds"] < 1
|
||||
):
|
||||
raise SystemExit("Invalid scan limits")
|
||||
|
||||
raise SystemExit(Reconciler(config).run())
|
||||
Reference in New Issue
Block a user