solution
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
# Create local Compose secrets 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'
|
||||
}
|
||||
|
||||
# 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"
|
||||
|
||||
printf 'done: %s\n' "$dir"
|
||||
printf 'next: docker compose up -d --build\n'
|
||||
@@ -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,48 @@
|
||||
#!/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:-lab3}
|
||||
image=${API_IMAGE:-mtusi-messenger-lab3:3.0.0}
|
||||
# Single host uses the locally built image; multi-node requires a registry and
|
||||
# RESOLVE_IMAGE=always after `docker push` (see REPORT.md).
|
||||
resolve=${RESOLVE_IMAGE:-never}
|
||||
|
||||
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; 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" .
|
||||
API_IMAGE="$image" docker stack deploy --resolve-image "$resolve" -c stack.yaml "$stack"
|
||||
|
||||
i=0
|
||||
while [ "$i" -lt 90 ]; do
|
||||
if curl -fsS "http://127.0.0.1:${APP_PORT:-8080}/health/ready" >/dev/null 2>&1; then
|
||||
printf 'deployed: http://127.0.0.1:%s (image %s)\n' "${APP_PORT:-8080}" "$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,158 @@
|
||||
# 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 { 'lab3' }
|
||||
$service = "$stack" + '_api'
|
||||
$port = if ($env:APP_PORT) { $env:APP_PORT } else { '8080' }
|
||||
$resolveImage = if ($env:RESOLVE_IMAGE) { $env:RESOLVE_IMAGE } else { 'never' }
|
||||
if (-not $Image) {
|
||||
$Image = if ($env:API_IMAGE) { $env:API_IMAGE } else { 'mtusi-messenger-lab3:3.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:$port/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 {
|
||||
$bytes = New-Object byte[] 32
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
|
||||
return (-join ($bytes | 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"
|
||||
}
|
||||
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')
|
||||
$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
|
||||
Invoke-Docker stack deploy --resolve-image $resolveImage -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', 'api')) {
|
||||
$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,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:-lab3}
|
||||
for service in "${stack}_postgres" "${stack}_valkey" "${stack}_api"; 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:${APP_PORT:-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:-lab3}
|
||||
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:${APP_PORT:-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:-lab3}
|
||||
image=${API_IMAGE:-mtusi-messenger-lab3:3.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:-lab3}
|
||||
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