solution
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# Create local Swarm secret files under secrets/ (gitignored, never printed).
|
||||
# Existing files are never overwritten, so rerunning the script is safe.
|
||||
# Usage: sh scripts/bootstrap-secrets.sh
|
||||
set -eu
|
||||
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
dir="$root/secrets"
|
||||
|
||||
# Files are created with mode 600: group and other have no access.
|
||||
umask 077
|
||||
mkdir -p "$dir"
|
||||
|
||||
random_hex() {
|
||||
head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n'
|
||||
}
|
||||
|
||||
# 10 bytes = 20 hex chars: MinIO access keys are limited to 20 characters.
|
||||
random_access_key() {
|
||||
head -c 10 /dev/urandom | od -An -tx1 | tr -d ' \n'
|
||||
}
|
||||
|
||||
# write <name> <value>: keeps the current file if it already has content.
|
||||
write() {
|
||||
name=$1
|
||||
value=$2
|
||||
if [ -s "$dir/$name" ]; then
|
||||
printf 'keep secrets/%s\n' "$name"
|
||||
return 0
|
||||
fi
|
||||
printf '%s\n' "$value" > "$dir/$name"
|
||||
printf 'create secrets/%s\n' "$name"
|
||||
}
|
||||
|
||||
write postgres_password "$(random_hex)"
|
||||
write cursor_secret "$(random_hex)"
|
||||
write cache_url 'redis://valkey:6379/0'
|
||||
# The password is hex, so the URL needs no percent-encoding.
|
||||
write database_url "postgresql+asyncpg://messenger:$(cat "$dir/postgres_password")@postgres:5432/messenger"
|
||||
|
||||
# MinIO: root credentials only for minio-init; API uses a separate restricted
|
||||
# pair. The access key is 20 hex chars (MinIO limit), the secret is 64 hex chars.
|
||||
write s3_root_user 'messenger-root'
|
||||
write s3_root_password "$(random_hex)"
|
||||
write s3_access_key_id "$(random_access_key)"
|
||||
write s3_secret_access_key "$(random_hex)"
|
||||
|
||||
printf 'done: %s\n' "$dir"
|
||||
printf 'next: sh scripts/deploy.sh\n'
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
# Проверка приватности bucket и ограниченности API-пользователя.
|
||||
#
|
||||
# Запускается в образе MinIO (в нём есть mc и curl) на backend-сети стенда:
|
||||
# docker run --rm --network lab4_backend --user 0 \
|
||||
# -v "$PWD/scripts:/scripts:ro" -v "$PWD/secrets:/run/secrets:ro" \
|
||||
# -e S3_ENDPOINT=http://minio:9000 -e S3_BUCKET=messenger-attachments \
|
||||
# --entrypoint /bin/sh minio/minio:... /scripts/check-bucket-private.sh
|
||||
#
|
||||
# Root нужен только для чтения local secrets в этом проверочном контейнере;
|
||||
# API-пользователь проверяется отдельным alias и не имеет прав на bucket.
|
||||
set -eu
|
||||
|
||||
endpoint=${S3_ENDPOINT:-http://minio:9000}
|
||||
bucket=${S3_BUCKET:-messenger-attachments}
|
||||
export MC_CONFIG_DIR=${MC_CONFIG_DIR:-/tmp/.mc}
|
||||
mkdir -p "$MC_CONFIG_DIR"
|
||||
|
||||
root_user=$(cat "${MINIO_ROOT_USER_FILE:?}")
|
||||
root_password=$(cat "${MINIO_ROOT_PASSWORD_FILE:?}")
|
||||
access_key=$(cat "${S3_ACCESS_KEY_ID_FILE:?}")
|
||||
secret_key=$(cat "${S3_SECRET_ACCESS_KEY_FILE:?}")
|
||||
|
||||
mc alias set root "$endpoint" "$root_user" "$root_password" >/dev/null
|
||||
mc alias set api "$endpoint" "$access_key" "$secret_key" >/dev/null
|
||||
|
||||
printf 'anonymous-policy: '
|
||||
mc anonymous get "root/$bucket" 2>&1 || true
|
||||
printf 'anonymous-http-get: '
|
||||
curl -s -o /dev/null -w '%{http_code}\n' "$endpoint/$bucket/attachments/does-not-exist"
|
||||
printf 'api-list-attachments: '
|
||||
mc ls "api/$bucket/attachments/" >/tmp/list.txt 2>&1 && head -1 /tmp/list.txt || cat /tmp/list.txt
|
||||
printf 'api-create-bucket: '
|
||||
if mc mb "api/should-not-exist" >/dev/null 2>&1; then
|
||||
printf 'ALLOWED (unexpected)\n'
|
||||
mc rb "api/should-not-exist" >/dev/null 2>&1 || true
|
||||
else
|
||||
printf 'denied (expected)\n'
|
||||
fi
|
||||
printf 'api-put-other-bucket: '
|
||||
echo test >/tmp/probe
|
||||
if mc cp /tmp/probe "api/other-bucket/" >/dev/null 2>&1; then
|
||||
printf 'ALLOWED (unexpected)\n'
|
||||
else
|
||||
printf 'denied (expected)\n'
|
||||
fi
|
||||
printf 'root-bucket-list: '
|
||||
mc ls "root/$bucket/" >/dev/null 2>&1 && printf 'ok\n' || printf 'failed\n'
|
||||
@@ -0,0 +1,117 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собирает текстовый evidence об инфраструктуре без секретов.
|
||||
|
||||
Все команды выполняются локальным Docker CLI; stdout/stderr сохраняются как
|
||||
есть. Секреты в вывод не попадают: печатаются только имена Docker secrets и
|
||||
пути внутри контейнеров, но не их значения.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence" / "12-infrastructure.txt"
|
||||
STACK = os.environ.get("STACK_NAME", "lab4")
|
||||
IMAGE = os.environ.get("API_IMAGE", "mtusi-messenger-lab4:4.0.0")
|
||||
MINIO = "minio/minio@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e"
|
||||
|
||||
|
||||
def run(*args: str) -> tuple[int, str]:
|
||||
result = subprocess.run(["docker", *args], capture_output=True, text=True, encoding="utf-8", errors="replace")
|
||||
text = result.stdout
|
||||
if result.stderr:
|
||||
text += "$ stderr\n" + result.stderr
|
||||
return result.returncode, text
|
||||
|
||||
|
||||
def main() -> int:
|
||||
lines: list[str] = []
|
||||
lines.append("# Infrastructure and image pinning")
|
||||
lines.append("host=" + platform.node() + " platform=" + platform.platform())
|
||||
lines.append("python=" + sys.version.split()[0])
|
||||
lines.append("")
|
||||
for label, args in [
|
||||
("docker version", ("version", "--format", "client={{.Client.Version}} server={{.Server.Version}}")),
|
||||
("docker info", ("info", "--format", "swarm={{.Swarm.LocalNodeState}} cpus={{.NCPU}} mem={{.MemTotal}}")),
|
||||
("stack services", ("stack", "services", STACK)),
|
||||
(
|
||||
"api service",
|
||||
(
|
||||
"service", "inspect", STACK + "_api", "--format",
|
||||
"image={{.Spec.TaskTemplate.ContainerSpec.Image}} ports={{json .Endpoint.Ports}} "
|
||||
"limits={{json .Spec.TaskTemplate.Resources.Limits}} "
|
||||
"reservations={{json .Spec.TaskTemplate.Resources.Reservations}} "
|
||||
"update={{json .Spec.UpdateConfig}}",
|
||||
),
|
||||
),
|
||||
(
|
||||
"minio service",
|
||||
(
|
||||
"service", "inspect", STACK + "_minio", "--format",
|
||||
"image={{.Spec.TaskTemplate.ContainerSpec.Image}} ports={{json .Endpoint.Ports}} "
|
||||
"limits={{json .Spec.TaskTemplate.Resources.Limits}} "
|
||||
"mounts={{json .Spec.TaskTemplate.ContainerSpec.Mounts}}",
|
||||
),
|
||||
),
|
||||
("traefik ports", ("service", "inspect", STACK + "_traefik", "--format", "ports={{json .Endpoint.Ports}}")),
|
||||
("volumes", ("volume", "ls", "--filter", "name=" + STACK, "--format", "{{.Name}} {{.Driver}}")),
|
||||
("secrets (names only)", ("secret", "ls", "--filter", "name=" + STACK, "--format", "{{.Name}}")),
|
||||
("configs (names only)", ("config", "ls", "--filter", "name=" + STACK, "--format", "{{.Name}}")),
|
||||
("api secret mounts", ("service", "inspect", STACK + "_api", "--format", "{{json .Spec.TaskTemplate.ContainerSpec.Secrets}}")),
|
||||
("minio-init secret mounts", ("service", "inspect", STACK + "_minio-init", "--format", "{{json .Spec.TaskTemplate.ContainerSpec.Secrets}}")),
|
||||
("migrate log", ("service", "logs", STACK + "_migrate", "--tail", "20")),
|
||||
("minio-init log", ("service", "logs", STACK + "_minio-init", "--tail", "20")),
|
||||
]:
|
||||
lines.append("## " + label)
|
||||
code, text = run(*args)
|
||||
lines.append("exit=" + str(code))
|
||||
lines.append(text.rstrip())
|
||||
lines.append("")
|
||||
|
||||
lines.append("## other service ports (must be null)")
|
||||
for name in ("postgres", "valkey", "minio-init", "migrate"):
|
||||
code, text = run("service", "inspect", STACK + "_" + name, "--format", "{{.Spec.Name}} ports={{json .Endpoint.Ports}}")
|
||||
lines.append("exit=" + str(code) + " " + text.strip())
|
||||
lines.append("")
|
||||
|
||||
lines.append("## image digests")
|
||||
for image in (
|
||||
IMAGE,
|
||||
MINIO,
|
||||
"postgres@sha256:0ea6700a3b4f0ae6ce746519073558aed4d88a79d8d07622a9a644946c7319c4",
|
||||
"valkey/valkey@sha256:4436c94fc34ce4af0354b9379d433a1f258998fb955f995c89822f98c14a8cab",
|
||||
"traefik:v3.5.4",
|
||||
"python:3.11.9-slim-bookworm",
|
||||
):
|
||||
code, text = run("image", "inspect", image, "--format", "{{.RepoTags}} id={{.Id}} digests={{json .RepoDigests}}")
|
||||
lines.append("exit=" + str(code) + " " + text.strip())
|
||||
lines.append("")
|
||||
|
||||
lines.append("## alembic current / check")
|
||||
secrets = str(ROOT / "secrets")
|
||||
for name, args in (
|
||||
("current", ("-d", "--name", "alembic-current", "--network", STACK + "_backend", "--user", "0",
|
||||
"-v", secrets + ":/run/secrets:ro", "-e", "DATABASE_URL_FILE=/run/secrets/database_url",
|
||||
"--entrypoint", "alembic", IMAGE, "current")),
|
||||
("check", ("-d", "--name", "alembic-check", "--network", STACK + "_backend", "--user", "0",
|
||||
"-v", secrets + ":/run/secrets:ro", "-e", "DATABASE_URL_FILE=/run/secrets/database_url",
|
||||
"--entrypoint", "alembic", IMAGE, "check")),
|
||||
):
|
||||
run("run", *args)
|
||||
run("wait", "alembic-" + name)
|
||||
code, text = run("logs", "alembic-" + name)
|
||||
lines.append("-- " + name + " exit=" + str(code))
|
||||
lines.append(text.rstrip())
|
||||
run("rm", "-f", "alembic-" + name)
|
||||
|
||||
OUT.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
print("wrote", OUT)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper for scripts/hooks.ps1 (deploy).
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode deploy %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/bin/sh
|
||||
# Build the application image, create local Swarm secrets once, deploy the stack.
|
||||
#
|
||||
# Prerequisites: Docker Engine with Swarm mode (docker swarm init is done here if
|
||||
# needed) and the files created by scripts/bootstrap-secrets.sh. No secret value
|
||||
# is printed. This is the one documented bootstrap sequence for stack.yaml.
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
|
||||
# The public failover test invokes the action script without a shell; it must be
|
||||
# executable on POSIX. Git may not preserve the mode on a Windows checkout.
|
||||
chmod +x scripts/stop-one.sh scripts/restore.sh scripts/restart.sh scripts/rolling-update.sh scripts/deploy.sh 2>/dev/null || true
|
||||
|
||||
stack=${STACK_NAME:-lab4}
|
||||
image=${API_IMAGE:-mtusi-messenger-lab4:4.0.0}
|
||||
|
||||
state=$(docker info --format '{{.Swarm.LocalNodeState}}')
|
||||
if [ "$state" != "active" ]; then
|
||||
docker swarm init >/dev/null
|
||||
fi
|
||||
|
||||
sh scripts/bootstrap-secrets.sh
|
||||
for name in database_url cache_url postgres_password cursor_secret s3_root_user s3_root_password s3_access_key_id s3_secret_access_key; do
|
||||
if ! docker secret inspect "${stack}_${name}" >/dev/null 2>&1; then
|
||||
docker secret create "${stack}_${name}" "secrets/${name}" >/dev/null
|
||||
fi
|
||||
done
|
||||
|
||||
docker build -t "$image" .
|
||||
|
||||
# Swarm configs неизменяемы. Перед повторным deploy убираем завершившийся
|
||||
# minio-init и его config, иначе stack deploy попытается обновить config и
|
||||
# получит "only updates to Labels are allowed". На первом deploy это no-op.
|
||||
docker service rm "${stack}_minio-init" >/dev/null 2>&1 || true
|
||||
docker config rm "${stack}_lab4_minio_init" >/dev/null 2>&1 || true
|
||||
|
||||
API_IMAGE="$image" docker stack deploy --resolve-image never -c stack.yaml "$stack"
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 90 ]; do
|
||||
if curl -fsS http://127.0.0.1:8080/health/ready >/dev/null 2>&1; then
|
||||
printf 'deployed: http://127.0.0.1:8080 (image %s)\n' "$image"
|
||||
docker stack services "$stack"
|
||||
exit 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 2
|
||||
done
|
||||
printf 'stack did not become ready within 180s\n' >&2
|
||||
docker stack services "$stack" >&2 || true
|
||||
exit 1
|
||||
@@ -0,0 +1,165 @@
|
||||
# Windows twin of scripts/deploy.sh, stop-one.sh, restore.sh, restart.sh and
|
||||
# rolling-update.sh. The public resilience test launches an action script with
|
||||
# Popen([script]) without a shell; on native Windows a .cmd wrapper is required.
|
||||
#
|
||||
# X-Instance-Id is the Swarm task container hostname, so a target is resolved by
|
||||
# inspecting running task containers, not by trusting the header alone.
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet('deploy', 'stop-one', 'restore', 'restart', 'rollout')]
|
||||
[string]$Mode,
|
||||
[string]$Image = ''
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
|
||||
Set-Location $root
|
||||
$stack = if ($env:STACK_NAME) { $env:STACK_NAME } else { 'lab4' }
|
||||
$service = "$stack" + '_api'
|
||||
if (-not $Image) {
|
||||
$Image = if ($env:API_IMAGE) { $env:API_IMAGE } else { 'mtusi-messenger-lab4:4.0.0' }
|
||||
}
|
||||
|
||||
function Invoke-Docker {
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Arguments)
|
||||
& docker @Arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "docker $($Arguments -join ' ') failed with exit code $LASTEXITCODE"
|
||||
}
|
||||
}
|
||||
|
||||
function Test-Ready {
|
||||
try {
|
||||
$response = Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:8080/health/ready' -TimeoutSec 3
|
||||
return $response.StatusCode -eq 200
|
||||
} catch {
|
||||
return $false
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-Ready {
|
||||
param([int]$Seconds = 180)
|
||||
$deadline = (Get-Date).AddSeconds($Seconds)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if (Test-Ready) { return }
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
throw "stack did not become ready within $Seconds seconds"
|
||||
}
|
||||
|
||||
function Get-RunningTasks {
|
||||
return @(& docker service ps -q $service --filter desired-state=running)
|
||||
}
|
||||
|
||||
function Find-TargetContainer {
|
||||
param([string]$Target)
|
||||
foreach ($task in (Get-RunningTasks)) {
|
||||
$container = (& docker inspect -f '{{.Status.ContainerStatus.ContainerID}}' $task 2>$null)
|
||||
if (-not $container) { continue }
|
||||
$hostname = (& docker inspect -f '{{.Config.Hostname}}' $container 2>$null)
|
||||
if ($hostname -eq $Target) { return $container }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function New-HexSecret {
|
||||
param([int]$Bytes = 32)
|
||||
$buffer = New-Object byte[] $Bytes
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($buffer)
|
||||
return (-join ($buffer | ForEach-Object { $_.ToString('x2') }))
|
||||
}
|
||||
|
||||
function Ensure-SecretFiles {
|
||||
New-Item -ItemType Directory -Force -Path 'secrets' | Out-Null
|
||||
$passwordPath = Join-Path 'secrets' 'postgres_password'
|
||||
$password = if ((Test-Path $passwordPath) -and (Get-Item $passwordPath).Length -gt 0) {
|
||||
(Get-Content $passwordPath -Raw).Trim()
|
||||
} else {
|
||||
New-HexSecret
|
||||
}
|
||||
$defaults = [ordered]@{
|
||||
postgres_password = $password
|
||||
cursor_secret = (New-HexSecret)
|
||||
cache_url = 'redis://valkey:6379/0'
|
||||
database_url = "postgresql+asyncpg://messenger:$password@postgres:5432/messenger"
|
||||
s3_root_user = 'messenger-root'
|
||||
s3_root_password = (New-HexSecret)
|
||||
s3_access_key_id = (New-HexSecret -Bytes 10)
|
||||
s3_secret_access_key = (New-HexSecret)
|
||||
}
|
||||
foreach ($name in $defaults.Keys) {
|
||||
$path = Join-Path 'secrets' $name
|
||||
if (-not (Test-Path $path) -or (Get-Item $path).Length -eq 0) {
|
||||
Set-Content -NoNewline -Encoding ascii -Path $path -Value $defaults[$name]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Ensure-Secrets {
|
||||
$names = @('database_url', 'cache_url', 'postgres_password', 'cursor_secret', 's3_root_user', 's3_root_password', 's3_access_key_id', 's3_secret_access_key')
|
||||
$existing = @(& docker secret ls --format '{{.Name}}')
|
||||
foreach ($name in $names) {
|
||||
$secret = "$stack" + '_' + $name
|
||||
if ($existing -notcontains $secret) {
|
||||
Invoke-Docker secret create $secret (Join-Path 'secrets' $name) | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch ($Mode) {
|
||||
'deploy' {
|
||||
$state = (& docker info --format '{{.Swarm.LocalNodeState}}').Trim()
|
||||
if ($state -ne 'active') { Invoke-Docker swarm init | Out-Null }
|
||||
Ensure-SecretFiles
|
||||
Ensure-Secrets
|
||||
Invoke-Docker build -t $Image . | Out-Null
|
||||
$env:API_IMAGE = $Image
|
||||
# Swarm configs неизменяемы: перед повторным deploy убираем завершившийся
|
||||
# minio-init и его config; на первом deploy это no-op.
|
||||
& cmd /c "docker service rm ${stack}_minio-init >nul 2>&1"
|
||||
& cmd /c "docker config rm ${stack}_lab4_minio_init >nul 2>&1"
|
||||
Invoke-Docker stack deploy --resolve-image never -c stack.yaml $stack | Out-Null
|
||||
Wait-Ready
|
||||
& docker stack services $stack
|
||||
}
|
||||
'stop-one' {
|
||||
$target = $env:TARGET_INSTANCE_ID
|
||||
if (-not $target) { throw 'TARGET_INSTANCE_ID is required' }
|
||||
$container = Find-TargetContainer $target
|
||||
if (-not $container) { throw "target instance $target not found among running tasks" }
|
||||
Write-Output "stopping instance $target container $container"
|
||||
Invoke-Docker stop --time 15 $container | Out-Null
|
||||
# Swarm may already be creating a replacement task; the target container
|
||||
# itself was stopped by id and its X-Instance-Id will not be served again.
|
||||
Write-Output "instance $target stopped"
|
||||
}
|
||||
'restore' {
|
||||
Invoke-Docker service update --restart-condition any --replicas 2 $service | Out-Null
|
||||
$running = @(Get-RunningTasks).Count
|
||||
if ($running -lt 2) { Invoke-Docker service update --force $service | Out-Null }
|
||||
$deadline = (Get-Date).AddSeconds(120)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
$running = @(Get-RunningTasks).Count
|
||||
if ($running -ge 2 -and (Test-Ready)) {
|
||||
Write-Output "api restored: $running running tasks and readiness OK"
|
||||
exit 0
|
||||
}
|
||||
Start-Sleep -Seconds 2
|
||||
}
|
||||
throw 'api did not recover within 120s'
|
||||
}
|
||||
'restart' {
|
||||
foreach ($name in @('postgres', 'valkey', 'minio', 'api', 'traefik')) {
|
||||
$svc = $stack + '_' + $name
|
||||
Write-Output "restarting $svc"
|
||||
Invoke-Docker service update --force $svc | Out-Null
|
||||
}
|
||||
Wait-Ready
|
||||
Write-Output 'stack ready after restart'
|
||||
}
|
||||
'rollout' {
|
||||
Invoke-Docker build --build-arg APP_REVISION=$Image -t $Image . | Out-Null
|
||||
Invoke-Docker service update --image $Image --update-order start-first --update-parallelism 1 --update-delay 5s --update-failure-action rollback $service | Out-Null
|
||||
& docker service ps $service --no-trunc
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентный bootstrap приватного bucket и ограниченного S3-пользователя.
|
||||
#
|
||||
# Запускается один раз сервисом minio-init (образ MinIO уже содержит mc).
|
||||
# Повторный запуск не удаляет данные: bucket создаётся с --ignore-existing,
|
||||
# пользователь переиспользуется, политика пересоздаётся и привязывается заново.
|
||||
# Root-credentials используются только здесь; API получает отдельную пару.
|
||||
set -eu
|
||||
|
||||
endpoint=${S3_ENDPOINT:-http://minio:9000}
|
||||
bucket=${S3_BUCKET:-messenger-attachments}
|
||||
policy_name=${S3_POLICY_NAME:-messenger-attachments-rw}
|
||||
|
||||
read_secret() {
|
||||
# $1 — путь к Docker secret; секрет не печатается.
|
||||
cat "$1"
|
||||
}
|
||||
|
||||
root_user=$(read_secret "${MINIO_ROOT_USER_FILE:?MINIO_ROOT_USER_FILE is required}")
|
||||
root_password=$(read_secret "${MINIO_ROOT_PASSWORD_FILE:?MINIO_ROOT_PASSWORD_FILE is required}")
|
||||
access_key=$(read_secret "${S3_ACCESS_KEY_ID_FILE:?S3_ACCESS_KEY_ID_FILE is required}")
|
||||
secret_key=$(read_secret "${S3_SECRET_ACCESS_KEY_FILE:?S3_SECRET_ACCESS_KEY_FILE is required}")
|
||||
|
||||
export MC_CONFIG_DIR=${MC_CONFIG_DIR:-/tmp/.mc}
|
||||
mkdir -p "$MC_CONFIG_DIR"
|
||||
|
||||
i=0
|
||||
until mc alias set local "$endpoint" "$root_user" "$root_password" --api S3v4 >/dev/null 2>&1; do
|
||||
i=$((i + 1))
|
||||
if [ "$i" -ge 60 ]; then
|
||||
printf 'minio is not reachable at %s\n' "$endpoint" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
until mc ready local >/dev/null 2>&1; do
|
||||
i=$((i + 1))
|
||||
if [ "$i" -ge 120 ]; then
|
||||
printf 'minio did not become ready\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
mc mb --ignore-existing "local/$bucket" >/dev/null
|
||||
mc anonymous set none "local/$bucket" >/dev/null
|
||||
|
||||
# Пользователь API: при повторном запуске оставляем существующего, чтобы не
|
||||
# разорвать уже работающий API. Секрет при первом создании берётся из secrets.
|
||||
mc admin user add local "$access_key" "$secret_key" >/dev/null 2>&1 || true
|
||||
if ! mc admin user info local "$access_key" >/dev/null 2>&1; then
|
||||
printf 'failed to create API user\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cat >/tmp/messenger-attachments-policy.json <<EOF
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::$bucket/attachments/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::$bucket"],
|
||||
"Condition": {"StringLike": {"s3:prefix": ["attachments/*"]}}
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation"],
|
||||
"Resource": ["arn:aws:s3:::$bucket"]
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
mc admin policy detach local "$policy_name" --user "$access_key" >/dev/null 2>&1 || true
|
||||
mc admin policy remove local "$policy_name" >/dev/null 2>&1 || true
|
||||
mc admin policy create local "$policy_name" /tmp/messenger-attachments-policy.json >/dev/null
|
||||
mc admin policy attach local "$policy_name" --user "$access_key" >/dev/null
|
||||
|
||||
printf 'minio bootstrap complete: bucket=%s private=yes policy=%s\n' "$bucket" "$policy_name"
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Запуск сверки PostgreSQL/S3 внутри работающего API-контейнера.
|
||||
#
|
||||
# Использует те же secrets и переменные окружения, что и API, поэтому не
|
||||
# требует отдельного набора credentials. По умолчанию — dry-run; для удаления
|
||||
# мусора добавьте --apply.
|
||||
set -eu
|
||||
stack=${STACK_NAME:-lab4}
|
||||
container=$(docker ps -q -f "name=${stack}_api" | head -n 1)
|
||||
if [ -z "$container" ]; then
|
||||
printf 'no running %s_api container\n' "$stack" >&2
|
||||
exit 2
|
||||
fi
|
||||
docker exec "$container" python -m messenger.reconcile "$@"
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper for scripts/hooks.ps1 (restart).
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode restart %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
# Restart API and every state store without deleting volumes.
|
||||
#
|
||||
# Used by make test-persistence. Sessions live in Valkey with AOF and users,
|
||||
# chats and messages in PostgreSQL, so the same bearer token and data survive.
|
||||
set -eu
|
||||
stack=${STACK_NAME:-lab4}
|
||||
for service in "${stack}_postgres" "${stack}_valkey" "${stack}_minio" "${stack}_api" "${stack}_traefik"; do
|
||||
printf 'restarting %s\n' "$service"
|
||||
docker service update --force "$service" >/dev/null
|
||||
done
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 60 ]; do
|
||||
if curl -fsS http://127.0.0.1:8080/health/ready >/dev/null 2>&1; then
|
||||
printf 'stack ready after restart\n'
|
||||
exit 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 2
|
||||
done
|
||||
printf 'stack did not become ready within 120s\n' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper for scripts/hooks.ps1 (restore).
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode restore %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Restore the API service to 2 replicas after scripts/stop-one.sh.
|
||||
set -eu
|
||||
stack=${STACK_NAME:-lab4}
|
||||
service="${stack}_api"
|
||||
|
||||
# Swarm normally creates the replacement itself after stopping one task. This hook
|
||||
# restores the declared replica count and waits for two healthy tasks; a forced
|
||||
# rolling update is used only when the service is still under-replicated.
|
||||
docker service update --restart-condition any --replicas 2 "$service" >/dev/null
|
||||
running=$(docker service ps -q "$service" --filter desired-state=running | wc -l | tr -d ' ')
|
||||
if [ "$running" -lt 2 ]; then
|
||||
docker service update --force "$service" >/dev/null
|
||||
fi
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 60 ]; do
|
||||
running=$(docker service ps -q "$service" --filter desired-state=running | wc -l | tr -d ' ')
|
||||
if [ "$running" -ge 2 ] && curl -fsS http://127.0.0.1:8080/health/ready >/dev/null 2>&1; then
|
||||
printf 'api restored: %s running tasks and readiness OK\n' "$running"
|
||||
exit 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 2
|
||||
done
|
||||
printf 'api did not recover within 120s\n' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper for scripts/hooks.ps1 (rollout).
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode rollout %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Start-first rolling update of the API service under load.
|
||||
#
|
||||
# Swarm replaces one task at a time (parallelism 1), waiting for the new task's
|
||||
# health check before removing the old one. Traefik keeps routing to ready tasks.
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$root"
|
||||
stack=${STACK_NAME:-lab4}
|
||||
image=${API_IMAGE:-mtusi-messenger-lab4:4.0.1}
|
||||
|
||||
docker build --build-arg APP_REVISION="$image" -t "$image" .
|
||||
docker service update \
|
||||
--image "$image" \
|
||||
--update-order start-first \
|
||||
--update-parallelism 1 \
|
||||
--update-delay 5s \
|
||||
--update-failure-action rollback \
|
||||
"${stack}_api"
|
||||
docker service ps "${stack}_api" --no-trunc
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper for scripts/hooks.ps1 (stop-one).
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0hooks.ps1" -Mode stop-one %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,50 @@
|
||||
#!/bin/sh
|
||||
# Stop exactly one API replica selected by TARGET_INSTANCE_ID.
|
||||
#
|
||||
# The public failover test sets TARGET_INSTANCE_ID to the X-Instance-Id that served
|
||||
# the test request. In this stack X-Instance-Id is the container hostname, so the
|
||||
# target task is found by inspecting every running task's container and stopped by
|
||||
# container id. Swarm then creates a *new* task (new hostname) after its restart
|
||||
# delay: the laboratory explicitly allows that, and the test checks that the old
|
||||
# X-Instance-Id disappears from responses. Restore with scripts/restore.sh.
|
||||
set -eu
|
||||
|
||||
stack=${STACK_NAME:-lab4}
|
||||
service="${stack}_api"
|
||||
target=${TARGET_INSTANCE_ID:-}
|
||||
if [ -z "$target" ]; then
|
||||
printf 'TARGET_INSTANCE_ID is required\n' >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if ! docker service inspect "$service" >/dev/null 2>&1; then
|
||||
printf 'service %s not found\n' "$service" >&2
|
||||
exit 3
|
||||
fi
|
||||
|
||||
find_container() {
|
||||
# Prints the container id whose hostname equals $target; empty if not found.
|
||||
for task in $(docker service ps -q "$service" --filter desired-state=running); do
|
||||
container=$(docker inspect -f '{{.Status.ContainerStatus.ContainerID}}' "$task" 2>/dev/null || true)
|
||||
[ -n "$container" ] || continue
|
||||
hostname=$(docker inspect -f '{{.Config.Hostname}}' "$container" 2>/dev/null || true)
|
||||
if [ "$hostname" = "$target" ]; then
|
||||
printf '%s\n' "$container"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 0
|
||||
}
|
||||
|
||||
container=$(find_container)
|
||||
if [ -z "$container" ]; then
|
||||
printf 'target instance %s not found among running tasks\n' "$target" >&2
|
||||
exit 4
|
||||
fi
|
||||
|
||||
printf 'stopping instance %s container %s\n' "$target" "$container"
|
||||
docker stop --time 15 "$container" >/dev/null
|
||||
|
||||
# Swarm may already be creating a replacement task with a different hostname;
|
||||
# the target container itself was stopped by id and is no longer served.
|
||||
printf 'instance %s stopped\n' "$target"
|
||||
Reference in New Issue
Block a user