Лабораторная 4 — вложения и приватное S3

This commit is contained in:
2026-11-13 10:39:20 +03:00
parent ec540a1a72
commit 4cd025e477
62 changed files with 3545 additions and 22 deletions
+13
View File
@@ -0,0 +1,13 @@
# syntax=docker/dockerfile:1
FROM public.ecr.aws/docker/library/golang:1.24.2-alpine@sha256:7772cb5322baa875edd74705556d08f0eeca7b9c4b5367754ce3f2f00041ccee AS build
ENV CGO_ENABLED=0 GOPROXY="https://proxy.golang.org|https://goproxy.io|direct"
WORKDIR /src/minio
ADD https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-09-07T16-13-09Z /tmp/minio.tar.gz
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build tar -xzf /tmp/minio.tar.gz --strip-components=1 && go build -o /out/minio .
WORKDIR /src/mc
ADD https://codeload.github.com/minio/mc/tar.gz/refs/tags/RELEASE.2025-08-13T08-35-41Z /tmp/mc.tar.gz
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build tar -xzf /tmp/mc.tar.gz --strip-components=1 && go build -o /out/mc .
FROM python:3.12-slim-bookworm@sha256:392307d22300de8b5986851a12d9176dfc0fc073e65bf6523ebd7dcbeb23564e
COPY --from=build /out/minio /out/mc /usr/local/bin/
ENTRYPOINT ["minio"]
+9
View File
@@ -5,3 +5,12 @@
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Lab4 запускает MinIO и клиент mc из версий, указанных в `Dockerfile.s3`. Bootstrap подключается к MinIO внутри сети Compose. API и cleaner используют отдельные credentials. При повторном запуске bootstrap подтверждает приватность бакета и заново применяет политику приложения.
```sh
docker compose run --rm s3-bootstrap
docker compose run --rm s3-bootstrap verify
```
Проверка записывает временный объект под `attachments/`, сверяет его под credentials API, проверяет анонимный HTTP 403 и удаляет тестовый объект.
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# Active readiness bridge for open-source Nginx. No Docker socket or credentials.
set -eu
probe() {
if wget -T 1 -q -O /dev/null "http://$1:8080/health/ready" 2>/dev/null; then
echo up > "/tmp/$1.health"
else
echo down > "/tmp/$1.health"
fi
}
control() { cat "/tmp/control-$1" 2>/dev/null || echo serve:boot; }
echo $$ > /tmp/healthwatch.pid
while :; do
sleep 1
probe api-a &
first=$!
probe api-b &
second=$!
wait "$first"
wait "$second"
# Read desired state AFTER probes. A generation is acknowledged only after
# the matching upstream configuration has been applied, never from a stale probe.
a_control=$(control api-a)
b_control=$(control api-b)
a_state=$(cat /tmp/api-a.health)
b_state=$(cat /tmp/api-b.health)
case "$a_control" in drain:*) a_state=down;; esac
case "$b_control" in drain:*) b_state=down;; esac
: > /tmp/upstreams.next
for service in api-a api-b; do
if [ "$service" = api-a ]; then state=$a_state; else state=$b_state; fi
suffix=''
[ "$state" = up ] || suffix=' down'
printf 'server %s:8080 resolve max_fails=1 fail_timeout=2s%s;\n' "$service" "$suffix" >> /tmp/upstreams.next
done
if ! cmp -s /tmp/upstreams.next /etc/nginx/upstreams.conf; then
cp /etc/nginx/upstreams.conf /tmp/upstreams.previous
# Rename on the same filesystem: readers never see missing/partial config.
cp /tmp/upstreams.next /etc/nginx/upstreams.next
mv -f /etc/nginx/upstreams.next /etc/nginx/upstreams.conf
if nginx -t && nginx -s reload; then
echo 'readiness upstream set updated'
else
cp /tmp/upstreams.previous /etc/nginx/upstreams.next
mv -f /etc/nginx/upstreams.next /etc/nginx/upstreams.conf
exit 1
fi
fi
printf '%s %s\n' "$a_control" "$a_state" > /tmp/applied-api-a.next
mv -f /tmp/applied-api-a.next /tmp/applied-api-a
printf '%s %s\n' "$b_control" "$b_state" > /tmp/applied-api-b.next
mv -f /tmp/applied-api-b.next /tmp/applied-api-b
done
+49
View File
@@ -0,0 +1,49 @@
worker_processes 1;
worker_shutdown_timeout 6s;
events { worker_connections 1024; }
http {
resolver 127.0.0.11 valid=1s ipv6=off;
resolver_timeout 1s;
log_format lab '$time_iso8601 $request_method $uri $status upstream=$upstream_addr '
'instance=$upstream_http_x_instance_id time=$request_time';
access_log /dev/stdout lab;
error_log /dev/stderr warn;
upstream api {
zone api 64k;
include /etc/nginx/upstreams.conf;
}
server {
listen 8080;
client_max_body_size 1m;
client_body_timeout 5s;
proxy_http_version 1.1;
proxy_set_header Connection close;
proxy_set_header Host $host;
proxy_set_header X-Request-Id $http_x_request_id;
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
proxy_send_timeout 5s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 6s;
location ~ ^/api/v1/chats/[^/]+/attachments$ {
# Keep a proxy ceiling above the API limit so the API can return its JSON 413.
client_max_body_size 11m;
proxy_read_timeout 45s;
proxy_send_timeout 30s;
proxy_next_upstream off;
proxy_pass http://api;
}
location ~ ^/api/v1/attachments/[^/]+/content$ {
proxy_buffering off;
proxy_read_timeout 10s;
# A shared S3 outage returns 503 without marking the API itself down.
proxy_next_upstream error timeout http_502 http_504;
proxy_pass http://api;
}
location / {
proxy_pass http://api;
}
}
}
+73
View File
@@ -0,0 +1,73 @@
#!/bin/sh
set -eu
umask 077
bucket=${S3_BUCKET:-messenger-attachments}
case "$bucket" in
''|*[!a-z0-9.-]*) echo 'Invalid S3 bucket name' >&2; exit 1 ;;
esac
config=$(mktemp -d)
trap 'rm -rf "$config"' EXIT
export MC_CONFIG_DIR="$config"
root_user=$(cat /run/secrets/s3_root_user)
root_password=$(cat /run/secrets/s3_root_password)
api_user=$(cat /run/secrets/s3_access_key_id)
api_password=$(cat /run/secrets/s3_secret_access_key)
endpoint=${S3_ENDPOINT:-http://s3:9000}
if [ "${1:-}" = verify ]; then
export MC_HOST_api="http://$api_user:$api_password@${endpoint#http://}"
key="attachments/probe-${config##*/}"
object="api/$bucket/$key"
trap 'mc rm "$object" >/dev/null 2>&1 || true; rm -rf "$config"' EXIT
printf '%s' 'lab4-private-bucket-probe' | mc pipe "$object" >/dev/null
test "$(mc cat "$object")" = 'lab4-private-bucket-probe'
python3 - "$endpoint/$bucket/$key" <<'PYTEST'
import sys
from urllib.error import HTTPError
from urllib.request import urlopen
try:
with urlopen(sys.argv[1], timeout=5):
raise SystemExit("FAIL: anonymous GET succeeded")
except HTTPError as exc:
if exc.code != 403:
raise
print("PASS: authenticated round trip; anonymous GET returned 403")
PYTEST
mc rm "$object" >/dev/null
exit 0
fi
attempt=0
until mc alias set storage "$endpoint" "$root_user" "$root_password" >/dev/null 2>&1 &&
mc admin info storage >/dev/null 2>&1; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 30 ]; then
echo 'S3 bootstrap could not connect or authenticate' >&2
exit 1
fi
sleep 1
done
mc mb --ignore-existing "storage/$bucket"
mc anonymous set none "storage/$bucket"
cat > "$config/api-policy.json" <<POLICY
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::$bucket/attachments/*"]
}, {
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::$bucket"]
}]
}
POLICY
mc admin policy create storage lab4-attachments "$config/api-policy.json"
mc admin user add storage "$api_user" "$api_password" >/dev/null
mc admin policy attach storage lab4-attachments --user "$api_user"
echo 'PASS: private S3 bucket and scoped API policy configured'
+2
View File
@@ -0,0 +1,2 @@
server api-a:8080 resolve max_fails=1 fail_timeout=2s;
server api-b:8080 resolve max_fails=1 fail_timeout=2s;