forked from mtusi2026/mtusi2026lab4
solution
This commit is contained in:
+4
-4
@@ -1,7 +1,7 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура лабораторной 4
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
Compose объединяет Nginx, api-a/api-b, PostgreSQL, Redis, MinIO, однократные migrate/minio-init и периодический cleanup. Тома pgdata и miniodata сохраняются при restart. Исходники MinIO и mc закреплены в infra/minio/Dockerfile, зависимости Python — в requirements.txt.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
Bootstrap идемпотентно создаёт приватный bucket и ограниченную учётную запись. API разрешены Get/Put/Delete только originals/* и ListBucket/GetBucketLocation только выбранного bucket. Консоль и внутренние службы не публикуют host-порты.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
Команды Windows/Linux: [GUIDE.md](../GUIDE.md). Контрактные роли из чистого skeleton сохранены в contracts/infrastructure.json; фактический стенд задаётся compose.yaml.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
# MinIO distributes its security release as source only. Compile the official,
|
||||
# pinned releases; no dependency on a removed Docker Hub / Quay image or make.
|
||||
FROM golang:1.24.8-bookworm AS go-build
|
||||
ENV CGO_ENABLED=0 GOTOOLCHAIN=local GOBIN=/out GOMAXPROCS=2
|
||||
|
||||
FROM go-build AS minio-build
|
||||
RUN go install -p 2 -trimpath \
|
||||
-ldflags="-s -w -X github.com/minio/minio/cmd.Version=2025-10-15T17:29:55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z" \
|
||||
github.com/minio/minio@RELEASE.2025-10-15T17-29-55Z
|
||||
|
||||
FROM go-build AS mc-build
|
||||
RUN go install -p 2 -trimpath \
|
||||
-ldflags="-s -w -X github.com/minio/mc/cmd.Version=2025-08-13T08:35:41Z -X github.com/minio/mc/cmd.ReleaseTag=RELEASE.2025-08-13T08-35-41Z" \
|
||||
github.com/minio/mc@RELEASE.2025-08-13T08-35-41Z
|
||||
|
||||
FROM python:3.12.8-slim-bookworm AS server
|
||||
LABEL org.opencontainers.image.source="https://github.com/minio/minio" \
|
||||
org.opencontainers.image.version="RELEASE.2025-10-15T17-29-55Z"
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
COPY --from=minio-build /out/minio /usr/local/bin/minio
|
||||
COPY infra/minio/healthcheck.py /opt/minio/healthcheck.py
|
||||
RUN mkdir /data && chown 10001:10001 /data
|
||||
USER 10001:10001
|
||||
EXPOSE 9000
|
||||
ENTRYPOINT ["minio"]
|
||||
CMD ["server", "/data", "--address", ":9000", "--console-address", "127.0.0.1:9001", "--certs-dir", "/tmp/minio-certs"]
|
||||
|
||||
FROM python:3.12.8-slim-bookworm AS bootstrap
|
||||
LABEL org.opencontainers.image.source="https://github.com/minio/mc" \
|
||||
org.opencontainers.image.version="RELEASE.2025-08-13T08-35-41Z"
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
COPY --from=mc-build /out/mc /usr/local/bin/mc
|
||||
COPY infra/minio/bootstrap.py /opt/minio/bootstrap.py
|
||||
USER 10001:10001
|
||||
ENTRYPOINT ["python", "/opt/minio/bootstrap.py"]
|
||||
@@ -0,0 +1,77 @@
|
||||
"""Idempotent private bucket and least-privilege application account setup."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.environ["S3_BUCKET"]
|
||||
endpoint = urlsplit(os.environ["S3_ENDPOINT_URL"])
|
||||
if not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", bucket):
|
||||
raise ValueError("Invalid S3_BUCKET")
|
||||
if endpoint.scheme not in ("http", "https") or not endpoint.netloc:
|
||||
raise ValueError("Invalid S3_ENDPOINT_URL")
|
||||
root_user = os.environ["MINIO_ROOT_USER"]
|
||||
root_password = os.environ["MINIO_ROOT_PASSWORD"]
|
||||
access_key = os.environ["S3_ACCESS_KEY"]
|
||||
secret_key = os.environ["S3_SECRET_KEY"]
|
||||
if access_key == root_user or secret_key == root_password:
|
||||
raise ValueError("API credentials must differ from MinIO root credentials")
|
||||
if len(secret_key) < 32 or len(root_password) < 32:
|
||||
raise ValueError("S3 secret and root password must contain at least 32 characters")
|
||||
|
||||
mc_env = {
|
||||
**os.environ,
|
||||
"MC_HOST_store": "%s://%s:%s@%s" % (
|
||||
endpoint.scheme, quote(root_user, safe=""),
|
||||
quote(root_password, safe=""), endpoint.netloc,
|
||||
),
|
||||
}
|
||||
secrets = (root_user, root_password, access_key, secret_key, mc_env["MC_HOST_store"])
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="minio-bootstrap-") as temporary:
|
||||
def run_mc(step, *arguments, stdin=None):
|
||||
result = subprocess.run(
|
||||
["mc", "--config-dir", temporary, *arguments],
|
||||
input=stdin, env=mc_env, text=True, capture_output=True, timeout=30,
|
||||
)
|
||||
if result.returncode:
|
||||
detail = result.stderr
|
||||
for value in secrets:
|
||||
detail = detail.replace(value, "[redacted]")
|
||||
raise RuntimeError("%s: %s" % (step, detail[:1000]))
|
||||
|
||||
run_mc("create bucket", "mb", "--ignore-existing", "store/" + bucket)
|
||||
run_mc("disable anonymous access", "anonymous", "set", "none", "store/" + bucket)
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::" + bucket],
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::" + bucket + "/originals/*"],
|
||||
},
|
||||
],
|
||||
}
|
||||
path = Path(temporary) / "api-policy.json"
|
||||
path.write_text(json.dumps(policy), encoding="utf-8")
|
||||
run_mc("create policy", "admin", "policy", "create", "store", "messenger-api", str(path))
|
||||
# stdin avoids placing keys in process arguments. AddUser is an upsert.
|
||||
run_mc("create API user", "admin", "user", "add", "store", stdin=access_key + "\n" + secret_key + "\n")
|
||||
# mc treats an already attached policy as success.
|
||||
run_mc("attach policy", "admin", "policy", "attach", "store", "messenger-api", "--user", access_key)
|
||||
print("PASS: private bucket and separate restricted API account configured")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Liveness of the private MinIO service; no credentials in process arguments."""
|
||||
|
||||
import sys
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
try:
|
||||
with urlopen("http://127.0.0.1:9000/minio/health/live", timeout=2) as response:
|
||||
sys.exit(0 if response.status == 200 else 1)
|
||||
except OSError:
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
render() {
|
||||
printf 'upstream api_backend {\n zone api_backend 64k;\n'
|
||||
count=0
|
||||
for host in api-a api-b; do
|
||||
if [ ! -e "/tmp/drain-$host" ] && wget -q -T 1 -O /dev/null "http://$host:8080/health/ready"; then
|
||||
printf ' server %s:8080 resolve max_fails=1 fail_timeout=2s;\n' "$host"
|
||||
count=$((count + 1))
|
||||
fi
|
||||
done
|
||||
if [ "$count" -eq 0 ]; then
|
||||
printf ' server 127.0.0.1:9;\n'
|
||||
fi
|
||||
printf '}\n'
|
||||
}
|
||||
|
||||
render > /tmp/backends.conf
|
||||
nginx -c /opt/lb/nginx.conf -g 'daemon off;' &
|
||||
master=$!
|
||||
|
||||
shutdown() {
|
||||
kill -QUIT "$master" 2>/dev/null || true
|
||||
wait "$master" || true
|
||||
exit 0
|
||||
}
|
||||
trap shutdown TERM INT QUIT
|
||||
|
||||
while kill -0 "$master" 2>/dev/null; do
|
||||
sleep 1 &
|
||||
wait $! || true
|
||||
render > /tmp/backends.next
|
||||
if ! cmp -s /tmp/backends.next /tmp/backends.conf; then
|
||||
cp /tmp/backends.conf /tmp/backends.previous
|
||||
mv /tmp/backends.next /tmp/backends.conf
|
||||
if nginx -t -c /opt/lb/nginx.conf; then
|
||||
kill -HUP "$master"
|
||||
printf 'LB ready backends: %s\n' "$(tr '\n' ' ' < /tmp/backends.conf)"
|
||||
else
|
||||
mv /tmp/backends.previous /tmp/backends.conf
|
||||
fi
|
||||
fi
|
||||
done
|
||||
wait "$master"
|
||||
@@ -0,0 +1,62 @@
|
||||
worker_processes 1;
|
||||
pid /tmp/nginx.pid;
|
||||
error_log /dev/stderr warn;
|
||||
worker_shutdown_timeout 5s;
|
||||
events { worker_connections 1024; }
|
||||
http {
|
||||
log_format upstream '$request_method $uri status=$status upstream=$upstream_addr upstream_status=$upstream_status time=$request_time';
|
||||
access_log /dev/stdout upstream;
|
||||
resolver 127.0.0.11 valid=1s ipv6=off;
|
||||
resolver_timeout 1s;
|
||||
include /tmp/backends.conf;
|
||||
server {
|
||||
listen 8080;
|
||||
server_tokens off;
|
||||
# The API enforces the exact 10 MiB file limit while streaming.
|
||||
client_max_body_size 11m;
|
||||
client_header_timeout 5s;
|
||||
client_body_timeout 10s;
|
||||
keepalive_timeout 2s;
|
||||
error_page 413 = @payload_too_large;
|
||||
error_page 502 504 = @unavailable;
|
||||
location @unavailable {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
return 503 '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"$request_id"}}';
|
||||
}
|
||||
location @payload_too_large {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
return 413 '{"error":{"code":"payload_too_large","message":"Request body too large","request_id":"$request_id"}}';
|
||||
}
|
||||
location ~ ^/api/v1/chats/[^/]+/attachments$ {
|
||||
proxy_pass http://api_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_read_timeout 75s;
|
||||
proxy_send_timeout 75s;
|
||||
proxy_request_buffering off;
|
||||
proxy_buffering off;
|
||||
# A binary POST has no idempotency key and must not be replayed.
|
||||
proxy_next_upstream off;
|
||||
}
|
||||
location / {
|
||||
proxy_pass http://api_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_read_timeout 8s;
|
||||
proxy_send_timeout 8s;
|
||||
proxy_request_buffering off;
|
||||
proxy_buffering off;
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
proxy_next_upstream_timeout 9s;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user