forked from mtusi2026/mtusi2026lab5
solution
This commit is contained in:
+13
-4
@@ -1,7 +1,16 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
`compose.yaml`: две API-реплики за Nginx, PostgreSQL, Redis сессий,
|
||||
RabbitMQ, приватный MinIO, publisher, worker и cleanup. Настройки берутся
|
||||
из `.env`, секреты передаются файлами из `secrets/`. Миграции и bootstrap
|
||||
завершаются до старта зависимых сервисов.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
Publisher читает outbox PostgreSQL и ждёт подтверждения RabbitMQ.
|
||||
Worker фиксирует результат в MinIO/PostgreSQL до ack, prefetch=1.
|
||||
Хранилища и брокер не публикуют внешние порты.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
`python3 scripts/test.py` создаёт временные Docker daemon и тестовый клиент.
|
||||
Внутри запускается тот же Compose с `compose.test.yaml`, открывающим
|
||||
PostgreSQL/Redis только по loopback временной среды. После прогона
|
||||
удаляются весь вложенный стенд и внешние временные ресурсы.
|
||||
Результаты копируются в `evidence/lab5/` до удаления.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export RABBITMQ_DEFAULT_PASS="$(cat "${BROKER_PASSWORD_FILE:?}")"
|
||||
export RABBITMQ_DEFAULT_USER="${BROKER_USER:?}"
|
||||
export RABBITMQ_DEFAULT_VHOST="${BROKER_VHOST:?}"
|
||||
export RABBITMQ_NODE_PORT="${BROKER_PORT:?}"
|
||||
exec /usr/local/bin/docker-entrypoint.sh rabbitmq-server
|
||||
@@ -0,0 +1,22 @@
|
||||
FROM golang:1.24.8-bookworm AS compiler
|
||||
ENV CGO_ENABLED=0 GOTOOLCHAIN=local GOBIN=/out GOMAXPROCS=4
|
||||
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
|
||||
go install -p 4 -ldflags='-s -w -X github.com/minio/minio/cmd.Version=RELEASE.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
|
||||
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
|
||||
go install -p 4 -ldflags='-s -w' github.com/minio/mc@RELEASE.2025-08-13T08-35-41Z
|
||||
|
||||
FROM python:3.12.15-slim-bookworm AS runtime
|
||||
RUN useradd --system --uid 10001 --no-create-home minio && mkdir /data && chown minio /data
|
||||
USER minio
|
||||
|
||||
FROM runtime AS server
|
||||
COPY --from=compiler /out/minio /usr/local/bin/minio
|
||||
LABEL org.opencontainers.image.source="https://github.com/minio/minio" \
|
||||
org.opencontainers.image.version="RELEASE.2025-10-15T17-29-55Z"
|
||||
VOLUME ["/data"]
|
||||
ENTRYPOINT ["/usr/local/bin/minio"]
|
||||
|
||||
FROM runtime AS bootstrap
|
||||
COPY --from=compiler /out/mc /usr/local/bin/mc
|
||||
COPY infra/minio/bootstrap.py /bootstrap.py
|
||||
ENTRYPOINT ["python", "/bootstrap.py"]
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Идемпотентный private bucket и отдельная ограниченная учётная запись API."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from tempfile import TemporaryDirectory
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
def secret(name):
|
||||
value = Path(os.environ[name.upper() + "_FILE"]).read_text().strip()
|
||||
if not value:
|
||||
raise ValueError("Пустой файл секрета")
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
endpoint = os.environ["S3_ENDPOINT"]
|
||||
bucket = os.environ["S3_BUCKET"]
|
||||
root_user, root_password = secret("minio_root_user"), secret("minio_root_password")
|
||||
access, password = secret("s3_access_key_id"), secret("s3_secret_access_key")
|
||||
if access == root_user:
|
||||
raise ValueError("API не должен использовать root credentials")
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
with urlopen(endpoint + "/minio/health/ready", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("MinIO не готов за 60 секунд")
|
||||
time.sleep(1)
|
||||
with TemporaryDirectory(prefix="minio-bootstrap-") as directory:
|
||||
config = Path(directory)
|
||||
|
||||
config_file = config / "config.json"
|
||||
config_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": "10",
|
||||
"aliases": {
|
||||
"storage": {
|
||||
"url": endpoint,
|
||||
"accessKey": root_user,
|
||||
"secretKey": root_password,
|
||||
"api": "S3v4",
|
||||
"path": "auto",
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
config_file.chmod(0o600)
|
||||
|
||||
def mc(*args):
|
||||
result = subprocess.run(
|
||||
["mc", "--config-dir", directory, *args],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=30,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
"Ошибка bootstrap MinIO; значения credentials скрыты"
|
||||
)
|
||||
|
||||
mc("mb", "--ignore-existing", "storage/" + bucket)
|
||||
mc("anonymous", "set", "none", "storage/" + bucket)
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": [f"arn:aws:s3:::{bucket}"],
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": [
|
||||
f"arn:aws:s3:::{bucket}/{prefix}/*"
|
||||
for prefix in ("originals", "staging", "variants")
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
policy_file = config / "policy.json"
|
||||
policy_file.write_text(json.dumps(policy))
|
||||
mc(
|
||||
"admin",
|
||||
"policy",
|
||||
"create",
|
||||
"storage",
|
||||
"messenger-attachments",
|
||||
str(policy_file),
|
||||
)
|
||||
|
||||
mc("admin", "user", "add", "storage", access, password)
|
||||
mc(
|
||||
"admin",
|
||||
"policy",
|
||||
"attach",
|
||||
"storage",
|
||||
"messenger-attachments",
|
||||
"--user",
|
||||
access,
|
||||
)
|
||||
print("MinIO private bucket and API policy configured", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
print("MinIO bootstrap failed: " + type(error).__name__, flush=True)
|
||||
raise SystemExit(1) from None
|
||||
@@ -0,0 +1,124 @@
|
||||
|
||||
worker_processes 2;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
map $upstream_http_x_request_id $response_request_id {
|
||||
"" $request_id;
|
||||
default $upstream_http_x_request_id;
|
||||
}
|
||||
|
||||
log_format requests escape=json
|
||||
'{"time":"$time_iso8601","request_id":"$response_request_id",'
|
||||
'"method":"$request_method","uri":"$uri","status":$status,'
|
||||
'"bytes":$body_bytes_sent,"request_time":$request_time,'
|
||||
'"upstream":"$upstream_addr","upstream_status":"$upstream_status",'
|
||||
'"upstream_time":"$upstream_response_time",'
|
||||
'"instance_id":"$upstream_http_x_instance_id",'
|
||||
'"limit_status":"$limit_req_status"}';
|
||||
|
||||
access_log /dev/stdout requests;
|
||||
error_log /dev/stderr warn;
|
||||
server_tokens off;
|
||||
|
||||
resolver 127.0.0.11 valid=5s ipv6=off;
|
||||
resolver_timeout 1s;
|
||||
|
||||
limit_req_zone $binary_remote_addr zone=per_client:10m rate=50r/s;
|
||||
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_comp_level 3;
|
||||
gzip_types application/json;
|
||||
|
||||
upstream api_backend {
|
||||
zone api_backend 64k;
|
||||
server api:8080 resolve max_fails=1 fail_timeout=5s;
|
||||
|
||||
keepalive 16;
|
||||
keepalive_timeout 4s;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
|
||||
client_header_timeout 10s;
|
||||
client_body_timeout 10s;
|
||||
client_max_body_size 0;
|
||||
client_body_buffer_size 64k;
|
||||
send_timeout 10s;
|
||||
keepalive_timeout 30s;
|
||||
|
||||
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_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_connect_timeout 500ms;
|
||||
proxy_send_timeout 10s;
|
||||
proxy_read_timeout 10s;
|
||||
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
proxy_next_upstream_timeout 2s;
|
||||
|
||||
proxy_intercept_errors off;
|
||||
error_page 429 = @rate_limited;
|
||||
error_page 502 503 504 = @unavailable;
|
||||
|
||||
location = /lb-health {
|
||||
access_log off;
|
||||
default_type text/plain;
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
location /health/ {
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location / {
|
||||
limit_req zone=per_client burst=100 nodelay;
|
||||
limit_req_status 429;
|
||||
limit_req_log_level warn;
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/chats/[^/]+/attachments$ {
|
||||
limit_req zone=per_client burst=100 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_request_buffering off;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 65s;
|
||||
proxy_send_timeout 15s;
|
||||
proxy_next_upstream off;
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/attachments/[^/]+/content$ {
|
||||
limit_req zone=per_client burst=100 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 65s;
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location @rate_limited {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header Retry-After 1 always;
|
||||
return 429 '{"error":{"code":"rate_limited","message":"Request rate exceeded","request_id":"$request_id"}}';
|
||||
}
|
||||
|
||||
location @unavailable {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header Retry-After 1 always;
|
||||
return 503 '{"error":{"code":"unavailable","message":"API temporarily unavailable","request_id":"$request_id"}}';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
dir /data
|
||||
appendonly yes
|
||||
appendfsync always
|
||||
maxmemory 256mb
|
||||
maxmemory-policy noeviction
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
password_hash=$(tr -d '\r\n' </run/secrets/redis_password | sha256sum | cut -d ' ' -f 1)
|
||||
mkdir -p /run/redis
|
||||
umask 077
|
||||
printf 'user default reset on #%s ~* &* +@all\n' "$password_hash" >/run/redis/users.acl
|
||||
chown redis:redis /run/redis/users.acl
|
||||
chmod 600 /run/redis/users.acl
|
||||
exec /usr/local/bin/docker-entrypoint.sh redis-server /usr/local/etc/redis/redis.conf --aclfile /run/redis/users.acl
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM docker:29.1.3-cli AS dockercli
|
||||
FROM python:3.12.15-slim-bookworm
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1
|
||||
COPY --from=dockercli /usr/local/bin/docker /usr/local/bin/docker
|
||||
COPY --from=dockercli /usr/local/libexec/docker/cli-plugins /usr/local/libexec/docker/cli-plugins
|
||||
WORKDIR /workspace
|
||||
COPY requirements.txt requirements-dev.txt ./
|
||||
RUN pip install -r requirements.txt -r requirements-dev.txt
|
||||
COPY scripts/container_tests.py /usr/local/bin/container_tests.py
|
||||
CMD ["python3", "/usr/local/bin/container_tests.py"]
|
||||
Reference in New Issue
Block a user