Реализовать наблюдаемость и доказательства уровня 4
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
cd /d "%~dp0\.."
|
||||
if not defined ENV_FILE set "ENV_FILE=.env"
|
||||
|
||||
docker compose --env-file "%ENV_FILE%" --profile verification run --rm private-bucket-check
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
: "${ENV_FILE:=.env}"
|
||||
|
||||
docker compose --env-file "$ENV_FILE" --profile verification run --rm private-bucket-check
|
||||
@@ -0,0 +1,120 @@
|
||||
param(
|
||||
[int]$DurationSeconds = 165,
|
||||
[string]$BaseUrl = "http://localhost:8080",
|
||||
[string]$EnvFile = ".env"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$project = Split-Path -Parent $PSScriptRoot
|
||||
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
|
||||
$evidenceDir = Join-Path $project "evidence\lab6-$stamp-database-stop"
|
||||
New-Item -ItemType Directory -Force -Path $evidenceDir | Out-Null
|
||||
|
||||
Push-Location $project
|
||||
try {
|
||||
docker compose --env-file $EnvFile stop postgres
|
||||
$samples = @()
|
||||
$deadline = (Get-Date).AddSeconds($DurationSeconds)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
$started = Get-Date
|
||||
try {
|
||||
$response = Invoke-WebRequest -Uri "$BaseUrl/health/ready" `
|
||||
-SkipHttpErrorCheck -TimeoutSec 5
|
||||
$readyStatus = [int]$response.StatusCode
|
||||
}
|
||||
catch {
|
||||
$readyStatus = 0
|
||||
}
|
||||
try {
|
||||
$response = Invoke-WebRequest -Uri "$BaseUrl/api/v1/users/me" `
|
||||
-Headers @{ Authorization = "Bearer incident-synthetic-token" } `
|
||||
-SkipHttpErrorCheck -TimeoutSec 5
|
||||
$businessStatus = [int]$response.StatusCode
|
||||
}
|
||||
catch {
|
||||
$businessStatus = 0
|
||||
}
|
||||
$samples += [ordered]@{
|
||||
at = $started.ToUniversalTime().ToString("o")
|
||||
ready_status = $readyStatus
|
||||
business_status = $businessStatus
|
||||
duration_ms = [math]::Round(((Get-Date) - $started).TotalMilliseconds, 1)
|
||||
}
|
||||
Start-Sleep -Seconds 1
|
||||
}
|
||||
$samples | ConvertTo-Json -Depth 5 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "http-samples.json")
|
||||
|
||||
$alertsSnapshot = Invoke-RestMethod "http://localhost:9090/api/v1/alerts"
|
||||
$highErrorAlert = @($alertsSnapshot.data.alerts | Where-Object {
|
||||
$_.labels.alertname -eq "MessengerApiHighErrorRate" -and $_.state -eq "firing"
|
||||
})
|
||||
$observations = [ordered]@{
|
||||
captured_at = (Get-Date).ToUniversalTime().ToString("o")
|
||||
api_5xx = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=sum(rate(http_server_request_duration_seconds_count%7Bhttp_response_status_code%3D~%225..%22%7D%5B2m%5D))"
|
||||
alerts = $alertsSnapshot
|
||||
alert_firing = ($highErrorAlert.Count -gt 0)
|
||||
jdbc_spans_hint = "Grafana Explore -> Tempo: { resource.service.name = `"messenger-api`" && span.db.system.name = `"postgresql`" }"
|
||||
correlated_logs_hint = "Grafana Explore -> Loki: {service_name=`"messenger-api`"} | json | level=`"ERROR`""
|
||||
}
|
||||
$observations | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "failure-observation.json")
|
||||
if ($highErrorAlert.Count -eq 0) {
|
||||
throw "MessengerApiHighErrorRate did not reach firing state"
|
||||
}
|
||||
|
||||
$end = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() * 1000000
|
||||
$start = [DateTimeOffset]::UtcNow.AddMinutes(-10).ToUnixTimeMilliseconds() * 1000000
|
||||
$logQuery = [uri]::EscapeDataString('{service_name="messenger-api"}')
|
||||
Invoke-RestMethod "http://localhost:3100/loki/api/v1/query_range?query=$logQuery&start=$start&end=$end&limit=100&direction=backward" |
|
||||
ConvertTo-Json -Depth 30 | Set-Content -Encoding utf8 (Join-Path $evidenceDir "loki-api-logs.json")
|
||||
$dbTraceQuery = [uri]::EscapeDataString('{ span.db.system = "postgresql" && status = error }')
|
||||
Invoke-RestMethod "http://localhost:3200/api/search?q=$dbTraceQuery&limit=100" |
|
||||
ConvertTo-Json -Depth 30 | Set-Content -Encoding utf8 (Join-Path $evidenceDir "tempo-postgres-errors.json")
|
||||
$httpTraceQuery = [uri]::EscapeDataString('{ name = "GET /health/ready" && status = error }')
|
||||
Invoke-RestMethod "http://localhost:3200/api/search?q=$httpTraceQuery&limit=100" |
|
||||
ConvertTo-Json -Depth 30 | Set-Content -Encoding utf8 (Join-Path $evidenceDir "tempo-http-errors.json")
|
||||
}
|
||||
finally {
|
||||
docker compose --env-file $EnvFile start postgres
|
||||
try {
|
||||
$readyDeadline = (Get-Date).AddMinutes(2)
|
||||
do {
|
||||
Start-Sleep -Seconds 5
|
||||
try {
|
||||
$readyResponse = Invoke-WebRequest -Uri "$BaseUrl/health/ready" `
|
||||
-SkipHttpErrorCheck -TimeoutSec 10
|
||||
$ready = ([int]$readyResponse.StatusCode -eq 200)
|
||||
}
|
||||
catch {
|
||||
$ready = $false
|
||||
}
|
||||
} while (-not $ready -and (Get-Date) -lt $readyDeadline)
|
||||
|
||||
$alertDeadline = (Get-Date).AddMinutes(6)
|
||||
do {
|
||||
Start-Sleep -Seconds 10
|
||||
$recoveryAlerts = Invoke-RestMethod "http://localhost:9090/api/v1/alerts"
|
||||
$activeHighError = @($recoveryAlerts.data.alerts | Where-Object {
|
||||
$_.labels.alertname -eq "MessengerApiHighErrorRate"
|
||||
})
|
||||
} while ($activeHighError.Count -gt 0 -and (Get-Date) -lt $alertDeadline)
|
||||
|
||||
[ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
readiness_recovered = $ready
|
||||
alerts = $recoveryAlerts
|
||||
alert_resolved = ($activeHighError.Count -eq 0)
|
||||
api_5xx_ratio = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=%28sum%28rate%28http_server_request_duration_seconds_count%7Bservice_name%3D%22messenger-api%22%2Chttp_response_status_code%3D~%225..%22%2Chttp_route%21~%22%2Fhealth%2F.%2A%22%7D%5B5m%5D%29%29%20or%20vector%280%29%29%20%2F%20clamp_min%28sum%28rate%28http_server_request_duration_seconds_count%7Bservice_name%3D%22messenger-api%22%2Chttp_route%21~%22%2Fhealth%2F.%2A%22%7D%5B5m%5D%29%29%2C%200.001%29"
|
||||
} | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "recovery-observation.json")
|
||||
if (-not $ready -or $activeHighError.Count -gt 0) {
|
||||
throw "database or MessengerApiHighErrorRate did not recover before the deadline"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Evidence saved to $evidenceDir"
|
||||
@@ -0,0 +1,117 @@
|
||||
param(
|
||||
[string]$BaseUrl = "http://localhost:8080",
|
||||
[string]$EnvFile = ".env",
|
||||
[int]$RecoveryWaitSeconds = 60
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$project = Split-Path -Parent $PSScriptRoot
|
||||
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
|
||||
$evidenceDir = Join-Path $project "evidence\lab6-$stamp-retry-trace"
|
||||
New-Item -ItemType Directory -Force -Path $evidenceDir | Out-Null
|
||||
|
||||
function Ensure-Running([string]$container) {
|
||||
$state = docker inspect --format '{{.State.Status}}' $container
|
||||
if ($state -ne 'running') {
|
||||
docker start $container | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
Push-Location $project
|
||||
try {
|
||||
$worker = docker compose --env-file $EnvFile ps -q worker
|
||||
$minio = docker compose --env-file $EnvFile ps -q minio
|
||||
if (-not $worker -or -not $minio) {
|
||||
throw "worker/minio containers do not exist; start the stack first"
|
||||
}
|
||||
|
||||
docker stop $worker | Out-Null
|
||||
$env:PYTHONUTF8 = "1"
|
||||
python tests/attachment_load.py --base-url $BaseUrl --count 1 --interval 0 `
|
||||
--output (Join-Path $evidenceDir "load.json")
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "synthetic upload failed"
|
||||
}
|
||||
|
||||
docker stop $minio | Out-Null
|
||||
$startedAt = [DateTimeOffset]::UtcNow
|
||||
$dockerSince = $startedAt.ToString("yyyy-MM-ddTHH:mm:ssZ")
|
||||
docker start $worker | Out-Null
|
||||
|
||||
$retrySeen = $false
|
||||
$deadline = (Get-Date).AddMinutes(4)
|
||||
do {
|
||||
Start-Sleep -Seconds 1
|
||||
$workerLogs = docker logs --since $dockerSince $worker 2>&1 | Out-String
|
||||
$retrySeen = $workerLogs.Contains("attachment_job_retry_scheduled")
|
||||
} while (-not $retrySeen -and (Get-Date) -lt $deadline)
|
||||
|
||||
if (-not $retrySeen) {
|
||||
throw "worker did not schedule a retry before the deadline"
|
||||
}
|
||||
Ensure-Running $minio
|
||||
Start-Sleep -Seconds $RecoveryWaitSeconds
|
||||
|
||||
$startNanos = $startedAt.ToUnixTimeMilliseconds() * 1000000
|
||||
$retryQuery = [uri]::EscapeDataString('{service_name="messenger-worker"} | event="attachment_job_retry_scheduled"')
|
||||
$retryResult = Invoke-RestMethod "http://localhost:3100/loki/api/v1/query_range?query=$retryQuery&start=$startNanos&limit=20&direction=forward"
|
||||
$retryStream = $retryResult.data.result | Where-Object { $_.stream.trace_id } | Select-Object -First 1
|
||||
if (-not $retryStream) {
|
||||
throw "retry event was not found in Loki"
|
||||
}
|
||||
$traceId = $retryStream.stream.trace_id
|
||||
|
||||
$successQueryText = '{service_name="messenger-worker"} | trace_id="' + $traceId + '" | event="attachment_job_completed"'
|
||||
$successQuery = [uri]::EscapeDataString($successQueryText)
|
||||
$successResult = Invoke-RestMethod "http://localhost:3100/loki/api/v1/query_range?query=$successQuery&start=$startNanos&limit=20&direction=forward"
|
||||
if (-not $successResult.data.result) {
|
||||
throw "successful retry completion was not found in Loki"
|
||||
}
|
||||
|
||||
$trace = Invoke-RestMethod "http://localhost:3200/api/traces/$traceId"
|
||||
$spans = @()
|
||||
foreach ($batch in $trace.batches) {
|
||||
$service = ($batch.resource.attributes | Where-Object key -eq 'service.name').value.stringValue
|
||||
foreach ($scope in $batch.scopeSpans) {
|
||||
foreach ($span in $scope.spans) {
|
||||
if ($span.name -match 'attachments|publish|process|PUT|DELETE|INSERT|UPDATE|SELECT') {
|
||||
$spans += [ordered]@{
|
||||
service = $service
|
||||
name = $span.name
|
||||
kind = $span.kind
|
||||
span_id = $span.spanId
|
||||
parent_span_id = $span.parentSpanId
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$producerCount = @($spans | Where-Object kind -eq 'SPAN_KIND_PRODUCER').Count
|
||||
$consumerCount = @($spans | Where-Object kind -eq 'SPAN_KIND_CONSUMER').Count
|
||||
if ($producerCount -lt 2 -or $consumerCount -lt 2) {
|
||||
throw "trace does not contain both initial and retry producer/consumer spans"
|
||||
}
|
||||
|
||||
[ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
trace_id = $traceId
|
||||
retry_event = $retryStream.stream.event
|
||||
retry_attempt = $retryStream.stream.attempt
|
||||
retry_error_code = $retryStream.stream.error_code
|
||||
completion_event = "attachment_job_completed"
|
||||
producer_spans = $producerCount
|
||||
consumer_spans = $consumerCount
|
||||
same_trace = $true
|
||||
synthetic_data_only = $true
|
||||
spans = $spans
|
||||
} | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "retry-trace-summary.json")
|
||||
}
|
||||
finally {
|
||||
if ($minio) { Ensure-Running $minio }
|
||||
if ($worker) { Ensure-Running $worker }
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
Write-Host "Evidence saved to $evidenceDir"
|
||||
@@ -0,0 +1,149 @@
|
||||
param(
|
||||
[string]$BaseUrl = "http://localhost:8080",
|
||||
[string]$EnvFile = ".env",
|
||||
[int]$LoadSeconds = 75,
|
||||
[int]$Concurrency = 4
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$project = Split-Path -Parent $PSScriptRoot
|
||||
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
|
||||
$evidenceDir = Join-Path $project "evidence\lab6-$stamp-telemetry-backend"
|
||||
New-Item -ItemType Directory -Force -Path $evidenceDir | Out-Null
|
||||
|
||||
function Query-Scalar([string]$expression) {
|
||||
try {
|
||||
$encoded = [uri]::EscapeDataString($expression)
|
||||
$response = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=$encoded"
|
||||
if (@($response.data.result).Count -eq 0) { return 0.0 }
|
||||
return [double]$response.data.result[0].value[1]
|
||||
}
|
||||
catch { return 0.0 }
|
||||
}
|
||||
|
||||
function Convert-MemoryToBytes([string]$value) {
|
||||
if ($value -notmatch '^([0-9.]+)([KMG]iB)$') { return 0 }
|
||||
$number = [double]$Matches[1]
|
||||
$factor = switch ($Matches[2]) {
|
||||
'KiB' { 1KB }
|
||||
'MiB' { 1MB }
|
||||
'GiB' { 1GB }
|
||||
}
|
||||
return [long]($number * $factor)
|
||||
}
|
||||
|
||||
function Capture-Sample {
|
||||
$stats = docker stats --no-stream --format '{{json .}}' $collector | ConvertFrom-Json
|
||||
$used = ($stats.MemUsage -split '/')[0].Trim()
|
||||
return [ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
collector_memory = $used
|
||||
collector_memory_bytes = Convert-MemoryToBytes $used
|
||||
collector_memory_percent = $stats.MemPerc
|
||||
exporter_queue_size = Query-Scalar 'max(otelcol_exporter_queue_size)'
|
||||
exporter_queue_capacity = Query-Scalar 'max(otelcol_exporter_queue_capacity)'
|
||||
failed_spans_total = Query-Scalar 'sum(otelcol_exporter_send_failed_spans_total) or vector(0)'
|
||||
failed_logs_total = Query-Scalar 'sum(otelcol_exporter_send_failed_log_records_total) or vector(0)'
|
||||
}
|
||||
}
|
||||
|
||||
function Ensure-Running([string]$container) {
|
||||
if ($container -and (docker inspect --format '{{.State.Status}}' $container) -ne 'running') {
|
||||
docker start $container | Out-Null
|
||||
}
|
||||
}
|
||||
|
||||
$samples = @()
|
||||
$loadJob = $null
|
||||
Push-Location $project
|
||||
try {
|
||||
$collector = docker compose --env-file $EnvFile ps -q otel-collector
|
||||
$loki = docker compose --env-file $EnvFile ps -q loki
|
||||
$tempo = docker compose --env-file $EnvFile ps -q tempo
|
||||
if (-not $collector -or -not $loki -or -not $tempo) {
|
||||
throw "collector/loki/tempo containers do not exist; start the stack first"
|
||||
}
|
||||
|
||||
$samples += Capture-Sample
|
||||
docker stop $loki $tempo | Out-Null
|
||||
|
||||
$makeOutput = & make test BASE_URL=$BaseUrl PYTHON=python 2>&1
|
||||
$makeExit = $LASTEXITCODE
|
||||
$makeOutput | Set-Content -Encoding utf8 (Join-Path $evidenceDir "make-test.txt")
|
||||
|
||||
$loadOutput = Join-Path $evidenceDir "message-load.json"
|
||||
$loadJob = Start-Job -ArgumentList $project,$BaseUrl,$LoadSeconds,$Concurrency,$loadOutput -ScriptBlock {
|
||||
param($projectPath,$url,$duration,$workers,$outputPath)
|
||||
Set-Location $projectPath
|
||||
$env:PYTHONUTF8 = "1"
|
||||
& python tests/load.py --base-url $url --duration $duration `
|
||||
--concurrency $workers --output $outputPath
|
||||
[pscustomobject]@{ exit_code = $LASTEXITCODE }
|
||||
}
|
||||
|
||||
while ($loadJob.State -in @('NotStarted','Running')) {
|
||||
$samples += Capture-Sample
|
||||
Start-Sleep -Seconds 5
|
||||
}
|
||||
$loadJobResult = Receive-Job $loadJob
|
||||
$loadExit = @($loadJobResult | Where-Object { $_.PSObject.Properties.Name -contains 'exit_code' })[-1].exit_code
|
||||
$samples += Capture-Sample
|
||||
|
||||
$maxMemory = (($samples | ForEach-Object { [long]$_['collector_memory_bytes'] }) |
|
||||
Measure-Object -Maximum).Maximum
|
||||
$maxQueue = (($samples | ForEach-Object { [double]$_['exporter_queue_size'] }) |
|
||||
Measure-Object -Maximum).Maximum
|
||||
$maxFailedSpans = (($samples | ForEach-Object { [double]$_['failed_spans_total'] }) |
|
||||
Measure-Object -Maximum).Maximum
|
||||
$maxFailedLogs = (($samples | ForEach-Object { [double]$_['failed_logs_total'] }) |
|
||||
Measure-Object -Maximum).Maximum
|
||||
$loadReport = Get-Content $loadOutput -Raw | ConvertFrom-Json
|
||||
|
||||
$samples | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "collector-samples.json")
|
||||
[ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
make_test_passed = ($makeExit -eq 0 -and ($makeOutput -join "`n") -match 'PASS:')
|
||||
message_load_exit_code = $loadExit
|
||||
successful_message_requests = $loadReport.successful_requests
|
||||
failed_message_requests = $loadReport.failed_requests
|
||||
collector_memory_limit_bytes = 536870912
|
||||
collector_memory_limiter_bytes = 402653184
|
||||
max_collector_memory_bytes = $maxMemory
|
||||
max_exporter_queue_size = $maxQueue
|
||||
exporter_queue_capacity = 2048
|
||||
failed_spans_total = $maxFailedSpans
|
||||
failed_log_records_total = $maxFailedLogs
|
||||
bounded = ($maxMemory -lt 536870912 -and $maxQueue -le 2048)
|
||||
} | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "failure-observation.json")
|
||||
|
||||
if ($makeExit -ne 0 -or $loadExit -ne 0 -or $loadReport.successful_requests -lt 1) {
|
||||
throw "business traffic failed while telemetry backends were unavailable"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if ($loadJob) { Remove-Job $loadJob -Force -ErrorAction SilentlyContinue }
|
||||
if ($loki) { Ensure-Running $loki }
|
||||
if ($tempo) { Ensure-Running $tempo }
|
||||
Pop-Location
|
||||
}
|
||||
|
||||
$recoveryDeadline = (Get-Date).AddMinutes(2)
|
||||
$recovery = [ordered]@{
|
||||
captured_at = [DateTimeOffset]::UtcNow.ToString("o")
|
||||
loki_ready = $false
|
||||
tempo_ready = $false
|
||||
exporter_queue_size = Query-Scalar 'max(otelcol_exporter_queue_size)'
|
||||
}
|
||||
do {
|
||||
Start-Sleep -Seconds 5
|
||||
try { $recovery.loki_ready = ((Invoke-WebRequest http://localhost:3100/ready -TimeoutSec 5).StatusCode -eq 200) } catch {}
|
||||
try { $recovery.tempo_ready = ((Invoke-WebRequest http://localhost:3200/ready -TimeoutSec 5).StatusCode -eq 200) } catch {}
|
||||
} while ((-not $recovery.loki_ready -or -not $recovery.tempo_ready) -and
|
||||
(Get-Date) -lt $recoveryDeadline)
|
||||
$recovery.exporter_queue_size = Query-Scalar 'max(otelcol_exporter_queue_size)'
|
||||
$recovery | ConvertTo-Json -Depth 10 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "recovery-observation.json")
|
||||
|
||||
Write-Host "Evidence saved to $evidenceDir"
|
||||
@@ -0,0 +1,85 @@
|
||||
param(
|
||||
[int]$DurationSeconds = 150,
|
||||
[int]$JobCount = 10,
|
||||
[string]$BaseUrl = "http://localhost:8080",
|
||||
[string]$EnvFile = ".env"
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$project = Split-Path -Parent $PSScriptRoot
|
||||
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
|
||||
$evidenceDir = Join-Path $project "evidence\lab6-$stamp-worker-stop"
|
||||
New-Item -ItemType Directory -Force -Path $evidenceDir | Out-Null
|
||||
|
||||
Push-Location $project
|
||||
try {
|
||||
$workerContainer = docker compose --env-file $EnvFile ps -q worker
|
||||
if (-not $workerContainer) {
|
||||
throw "worker container does not exist; start the stack first"
|
||||
}
|
||||
docker stop $workerContainer
|
||||
python tests/attachment_load.py --base-url $BaseUrl --count $JobCount `
|
||||
--output (Join-Path $evidenceDir "load.json")
|
||||
Start-Sleep -Seconds $DurationSeconds
|
||||
|
||||
$failureAlerts = Invoke-RestMethod "http://localhost:9090/api/v1/alerts"
|
||||
$firingQueueAlert = @($failureAlerts.data.alerts | Where-Object {
|
||||
$_.labels.alertname -eq "AttachmentQueueLagHigh" -and $_.state -eq "firing"
|
||||
})
|
||||
$queries = [ordered]@{
|
||||
captured_at = (Get-Date).ToUniversalTime().ToString("o")
|
||||
queue_depth = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=max(messenger_queue_depth)"
|
||||
oldest_job_age = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=max(messenger_queue_oldest_job_age_seconds)"
|
||||
alerts = $failureAlerts
|
||||
alert_firing = ($firingQueueAlert.Count -gt 0)
|
||||
}
|
||||
$queries | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "failure-observation.json")
|
||||
if ($firingQueueAlert.Count -eq 0) {
|
||||
throw "AttachmentQueueLagHigh did not reach firing state"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
if ($workerContainer) {
|
||||
docker start $workerContainer
|
||||
}
|
||||
$deadline = (Get-Date).AddMinutes(4)
|
||||
do {
|
||||
Start-Sleep -Seconds 5
|
||||
try {
|
||||
$depth = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=max(messenger_queue_depth)"
|
||||
$remaining = [double]$depth.data.result[0].value[1]
|
||||
}
|
||||
catch {
|
||||
$remaining = [double]::PositiveInfinity
|
||||
}
|
||||
} while ($remaining -gt 0 -and (Get-Date) -lt $deadline)
|
||||
$alertDeadline = (Get-Date).AddMinutes(2)
|
||||
do {
|
||||
Start-Sleep -Seconds 5
|
||||
$recoveryAlerts = Invoke-RestMethod "http://localhost:9090/api/v1/alerts"
|
||||
$queueAlert = @($recoveryAlerts.data.alerts | Where-Object {
|
||||
$_.labels.alertname -eq "AttachmentQueueLagHigh"
|
||||
})
|
||||
} while ($queueAlert.Count -gt 0 -and (Get-Date) -lt $alertDeadline)
|
||||
try {
|
||||
$recovery = [ordered]@{
|
||||
captured_at = (Get-Date).ToUniversalTime().ToString("o")
|
||||
queue_depth = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=max(messenger_queue_depth)"
|
||||
oldest_job_age = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=max(messenger_queue_oldest_job_age_seconds)"
|
||||
jobs = Invoke-RestMethod "http://localhost:9090/api/v1/query?query=sum%20by%20(outcome)%20(increase(messenger_jobs_processed_total%5B10m%5D))"
|
||||
alerts = $recoveryAlerts
|
||||
alert_resolved = ($queueAlert.Count -eq 0)
|
||||
}
|
||||
$recovery | ConvertTo-Json -Depth 20 | Set-Content -Encoding utf8 `
|
||||
(Join-Path $evidenceDir "recovery-observation.json")
|
||||
if ($queueAlert.Count -gt 0) {
|
||||
throw "AttachmentQueueLagHigh did not resolve before the deadline"
|
||||
}
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Evidence saved to $evidenceDir"
|
||||
@@ -0,0 +1,73 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$AttachmentId,
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateRange(1, 2)]
|
||||
[int]$PipelineVersion,
|
||||
[string]$RequestedBy = $env:USERNAME,
|
||||
[string]$EnvFile = ".env"
|
||||
)
|
||||
|
||||
$parsedAttachmentId = [guid]::Empty
|
||||
if (-not [guid]::TryParse($AttachmentId, [ref]$parsedAttachmentId)) {
|
||||
throw "AttachmentId must be a UUID"
|
||||
}
|
||||
if ($RequestedBy -notmatch '^[A-Za-z0-9_.@-]{1,128}$') {
|
||||
throw "RequestedBy contains unsupported characters"
|
||||
}
|
||||
|
||||
$sql = @"
|
||||
WITH candidate AS (
|
||||
SELECT id, pipeline_version
|
||||
FROM attachments
|
||||
WHERE id = '$parsedAttachmentId'::uuid AND pipeline_version < $PipelineVersion
|
||||
FOR UPDATE
|
||||
), superseded AS (
|
||||
UPDATE attachment_jobs j
|
||||
SET status = 'superseded', published = true,
|
||||
last_error_code = 'superseded_by_v$PipelineVersion',
|
||||
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
FROM candidate c
|
||||
WHERE j.attachment_id = c.id AND j.pipeline_version < $PipelineVersion
|
||||
AND j.status IN ('queued', 'processing')
|
||||
RETURNING j.id
|
||||
), created AS (
|
||||
INSERT INTO attachment_jobs
|
||||
(id, attachment_id, pipeline_version, attempt, status, published,
|
||||
next_attempt_at, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), id, $PipelineVersion, 1, 'queued', false,
|
||||
clock_timestamp(), clock_timestamp(), clock_timestamp()
|
||||
FROM candidate
|
||||
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING
|
||||
RETURNING id, attachment_id
|
||||
), promoted AS (
|
||||
UPDATE attachments a
|
||||
SET pipeline_version = $PipelineVersion, status = 'queued', error_code = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
FROM candidate c, created n
|
||||
WHERE a.id = c.id AND n.attachment_id = c.id
|
||||
RETURNING a.id
|
||||
), audited AS (
|
||||
INSERT INTO attachment_pipeline_promotions
|
||||
(attachment_id, from_version, to_version, job_id, requested_by)
|
||||
SELECT c.id, c.pipeline_version, $PipelineVersion, n.id, '$RequestedBy'
|
||||
FROM candidate c
|
||||
JOIN created n ON n.attachment_id = c.id
|
||||
JOIN promoted p ON p.id = c.id
|
||||
RETURNING job_id
|
||||
)
|
||||
SELECT COALESCE((SELECT job_id::text FROM audited), 'no-op');
|
||||
"@
|
||||
|
||||
$result = docker compose --env-file $EnvFile exec -T postgres `
|
||||
psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c $sql
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Pipeline promotion transaction failed"
|
||||
}
|
||||
|
||||
$last = ($result | Select-Object -Last 1).Trim()
|
||||
if ($last -eq "no-op") {
|
||||
Write-Output "No-op: attachment is missing, already at v$PipelineVersion, or that version already exists"
|
||||
} else {
|
||||
Write-Output "Promoted attachment $parsedAttachmentId to pipeline v$PipelineVersion with job $last"
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
attachment_id="${1:?usage: promote-pipeline.sh ATTACHMENT_UUID PIPELINE_VERSION [REQUESTED_BY] [ENV_FILE]}"
|
||||
pipeline_version="${2:?pipeline version is required}"
|
||||
requested_by="${3:-operator}"
|
||||
env_file="${4:-.env}"
|
||||
|
||||
case "$attachment_id" in
|
||||
????????-????-????-????-????????????) ;;
|
||||
*) echo "AttachmentId must be a UUID" >&2; exit 2 ;;
|
||||
esac
|
||||
case "$pipeline_version" in
|
||||
1|2) ;;
|
||||
*) echo "PipelineVersion must be 1 or 2" >&2; exit 2 ;;
|
||||
esac
|
||||
case "$requested_by" in
|
||||
*[!A-Za-z0-9_.@-]*|'') echo "RequestedBy contains unsupported characters" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
sql="WITH candidate AS (
|
||||
SELECT id, pipeline_version FROM attachments
|
||||
WHERE id = '$attachment_id'::uuid AND pipeline_version < $pipeline_version FOR UPDATE
|
||||
), superseded AS (
|
||||
UPDATE attachment_jobs j SET status = 'superseded', published = true,
|
||||
last_error_code = 'superseded_by_v$pipeline_version',
|
||||
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
FROM candidate c WHERE j.attachment_id = c.id
|
||||
AND j.pipeline_version < $pipeline_version AND j.status IN ('queued', 'processing')
|
||||
RETURNING j.id
|
||||
), created AS (
|
||||
INSERT INTO attachment_jobs
|
||||
(id, attachment_id, pipeline_version, attempt, status, published,
|
||||
next_attempt_at, created_at, updated_at)
|
||||
SELECT gen_random_uuid(), id, $pipeline_version, 1, 'queued', false,
|
||||
clock_timestamp(), clock_timestamp(), clock_timestamp() FROM candidate
|
||||
ON CONFLICT (attachment_id, pipeline_version) DO NOTHING
|
||||
RETURNING id, attachment_id
|
||||
), promoted AS (
|
||||
UPDATE attachments a SET pipeline_version = $pipeline_version,
|
||||
status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
FROM candidate c, created n WHERE a.id = c.id AND n.attachment_id = c.id
|
||||
RETURNING a.id
|
||||
), audited AS (
|
||||
INSERT INTO attachment_pipeline_promotions
|
||||
(attachment_id, from_version, to_version, job_id, requested_by)
|
||||
SELECT c.id, c.pipeline_version, $pipeline_version, n.id, '$requested_by'
|
||||
FROM candidate c JOIN created n ON n.attachment_id = c.id
|
||||
JOIN promoted p ON p.id = c.id RETURNING job_id
|
||||
)
|
||||
SELECT COALESCE((SELECT job_id::text FROM audited), 'no-op');"
|
||||
|
||||
result="$(docker compose --env-file "$env_file" exec -T postgres \
|
||||
psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c "$sql")"
|
||||
if [ "$result" = "no-op" ]; then
|
||||
echo "No-op: attachment is missing, already at v$pipeline_version, or that version already exists"
|
||||
else
|
||||
echo "Promoted attachment $attachment_id to pipeline v$pipeline_version with job $result"
|
||||
fi
|
||||
@@ -0,0 +1,58 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[string]$JobId,
|
||||
[string]$RequestedBy = $env:USERNAME,
|
||||
[string]$EnvFile = ".env"
|
||||
)
|
||||
|
||||
$parsedJobId = [guid]::Empty
|
||||
if (-not [guid]::TryParse($JobId, [ref]$parsedJobId)) {
|
||||
throw "JobId must be a UUID"
|
||||
}
|
||||
if ($RequestedBy -notmatch '^[A-Za-z0-9_.@-]{1,128}$') {
|
||||
throw "RequestedBy contains unsupported characters"
|
||||
}
|
||||
|
||||
$sql = @"
|
||||
WITH candidate AS (
|
||||
SELECT j.id, j.attachment_id, j.attempt
|
||||
FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = '$parsedJobId'::uuid
|
||||
AND j.status = 'failed' AND a.status = 'failed'
|
||||
AND j.pipeline_version = a.pipeline_version
|
||||
FOR UPDATE OF j, a
|
||||
), audited AS (
|
||||
INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt)
|
||||
SELECT id, '$RequestedBy', attempt FROM candidate
|
||||
RETURNING job_id
|
||||
), reset_job AS (
|
||||
UPDATE attachment_jobs j
|
||||
SET status = 'queued', attempt = 1, published = false,
|
||||
last_error_code = NULL, next_attempt_at = clock_timestamp(),
|
||||
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
FROM candidate c, audited a
|
||||
WHERE j.id = c.id AND a.job_id = c.id
|
||||
RETURNING j.attachment_id
|
||||
), reset_attachment AS (
|
||||
UPDATE attachments a
|
||||
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
|
||||
FROM reset_job r
|
||||
WHERE a.id = r.attachment_id AND a.status = 'failed'
|
||||
RETURNING a.id
|
||||
)
|
||||
SELECT CASE WHEN EXISTS (SELECT 1 FROM reset_attachment)
|
||||
THEN 'replayed' ELSE 'no-op' END;
|
||||
"@
|
||||
|
||||
$result = docker compose --env-file $EnvFile exec -T postgres `
|
||||
psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c $sql
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Replay transaction failed"
|
||||
}
|
||||
|
||||
if (($result | Select-Object -Last 1).Trim() -eq "replayed") {
|
||||
Write-Output "Replay requested for failed job $parsedJobId by $RequestedBy"
|
||||
} else {
|
||||
Write-Output "No-op: job $parsedJobId is missing, not failed, or already recovered"
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
job_id="${1:?usage: replay-failed.sh JOB_UUID [REQUESTED_BY] [ENV_FILE]}"
|
||||
requested_by="${2:-operator}"
|
||||
env_file="${3:-.env}"
|
||||
|
||||
case "$job_id" in
|
||||
????????-????-????-????-????????????) ;;
|
||||
*) echo "JobId must be a UUID" >&2; exit 2 ;;
|
||||
esac
|
||||
case "$requested_by" in
|
||||
*[!A-Za-z0-9_.@-]*|'') echo "RequestedBy contains unsupported characters" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
sql="WITH candidate AS (
|
||||
SELECT j.id, j.attachment_id, j.attempt FROM attachment_jobs j
|
||||
JOIN attachments a ON a.id = j.attachment_id
|
||||
WHERE j.id = '$job_id'::uuid AND j.status = 'failed' AND a.status = 'failed'
|
||||
AND j.pipeline_version = a.pipeline_version
|
||||
FOR UPDATE OF j, a
|
||||
), audited AS (
|
||||
INSERT INTO attachment_job_replays (job_id, requested_by, previous_attempt)
|
||||
SELECT id, '$requested_by', attempt FROM candidate RETURNING job_id
|
||||
), reset_job AS (
|
||||
UPDATE attachment_jobs j SET status = 'queued', attempt = 1, published = false,
|
||||
last_error_code = NULL, next_attempt_at = clock_timestamp(),
|
||||
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
|
||||
FROM candidate c, audited a WHERE j.id = c.id AND a.job_id = c.id
|
||||
RETURNING j.attachment_id
|
||||
), reset_attachment AS (
|
||||
UPDATE attachments a SET status = 'queued', error_code = NULL,
|
||||
updated_at = clock_timestamp()
|
||||
FROM reset_job r WHERE a.id = r.attachment_id AND a.status = 'failed'
|
||||
RETURNING a.id
|
||||
)
|
||||
SELECT CASE WHEN EXISTS (SELECT 1 FROM reset_attachment)
|
||||
THEN 'replayed' ELSE 'no-op' END;"
|
||||
|
||||
result="$(docker compose --env-file "$env_file" exec -T postgres \
|
||||
psql -v ON_ERROR_STOP=1 -U messenger -d messenger -At -c "$sql")"
|
||||
if [ "$result" = "replayed" ]; then
|
||||
echo "Replay requested for failed job $job_id by $requested_by"
|
||||
else
|
||||
echo "No-op: job $job_id is missing, not failed, or already recovered"
|
||||
fi
|
||||
@@ -0,0 +1,10 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
cd /d "%~dp0\.."
|
||||
if not defined ENV_FILE set "ENV_FILE=.env"
|
||||
|
||||
docker compose --env-file "%ENV_FILE%" stop nginx api redis postgres minio || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 postgres redis minio || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" run --rm minio-init || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api || exit /b 1
|
||||
docker compose --env-file "%ENV_FILE%" up -d --no-deps nginx || exit /b 1
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
: "${ENV_FILE:=.env}"
|
||||
|
||||
# Preserve named volumes and the network. The migration job is intentionally
|
||||
# not re-run during a same-version restart.
|
||||
docker compose --env-file "$ENV_FILE" stop nginx api redis postgres minio
|
||||
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 postgres redis minio
|
||||
docker compose --env-file "$ENV_FILE" run --rm minio-init
|
||||
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api
|
||||
docker compose --env-file "$ENV_FILE" up -d --no-deps nginx
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
cd /d "%~dp0\.."
|
||||
if not defined ENV_FILE set "ENV_FILE=.env"
|
||||
|
||||
docker compose --env-file "%ENV_FILE%" up -d --wait --wait-timeout 90 --no-deps --scale api=2 api
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
: "${ENV_FILE:=.env}"
|
||||
|
||||
docker compose --env-file "$ENV_FILE" up -d --wait --wait-timeout 90 \
|
||||
--no-deps --scale api=2 api
|
||||
@@ -0,0 +1,16 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions
|
||||
cd /d "%~dp0\.."
|
||||
|
||||
set /a REPLICA_COUNT=0
|
||||
for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do set /a REPLICA_COUNT+=1
|
||||
if %REPLICA_COUNT% LSS 2 exit /b 2
|
||||
|
||||
for /f "usebackq delims=" %%C in (`docker compose --env-file .env ps -q api`) do call :replace_one %%C
|
||||
exit /b 0
|
||||
|
||||
:replace_one
|
||||
docker stop --time 10 %1 >nul || exit /b 1
|
||||
docker rm %1 >nul || exit /b 1
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 90 --no-deps --scale api=2 api >nul || exit /b 1
|
||||
exit /b 0
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
|
||||
original_ids=$(docker compose --env-file .env ps -q api)
|
||||
count=$(printf '%s\n' "$original_ids" | sed '/^$/d' | wc -l | tr -d ' ')
|
||||
if [ "$count" -lt 2 ]; then
|
||||
printf '%s\n' 'Rolling update requires at least two API replicas' >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
for container_id in $original_ids; do
|
||||
# Replace exactly one original replica and wait for the replacement before
|
||||
# touching the next one. Named volumes and state stores are not changed.
|
||||
docker stop --time 10 "$container_id" >/dev/null
|
||||
docker rm "$container_id" >/dev/null
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 90 \
|
||||
--no-deps --scale api=2 api >/dev/null
|
||||
done
|
||||
@@ -0,0 +1,26 @@
|
||||
@echo off
|
||||
setlocal EnableExtensions EnableDelayedExpansion
|
||||
|
||||
if "%TARGET_INSTANCE_ID%"=="" exit /b 2
|
||||
cd /d "%~dp0\.."
|
||||
if not defined ENV_FILE set "ENV_FILE=.env"
|
||||
|
||||
set "TARGET_CONTAINER="
|
||||
set /a MATCHES=0
|
||||
for /f "usebackq delims=" %%C in (`docker compose --env-file "%ENV_FILE%" ps -q api`) do (
|
||||
set "CONTAINER_ID=%%C"
|
||||
set "SHORT_ID=!CONTAINER_ID:~0,12!"
|
||||
set "HOSTNAME_VALUE="
|
||||
for /f "usebackq delims=" %%H in (`docker inspect --format "{{.Config.Hostname}}" %%C`) do set "HOSTNAME_VALUE=%%H"
|
||||
if "!HOSTNAME_VALUE!"=="%TARGET_INSTANCE_ID%" (
|
||||
set "TARGET_CONTAINER=%%C"
|
||||
set /a MATCHES+=1
|
||||
) else if "!SHORT_ID!"=="%TARGET_INSTANCE_ID%" (
|
||||
set "TARGET_CONTAINER=%%C"
|
||||
set /a MATCHES+=1
|
||||
)
|
||||
)
|
||||
|
||||
if not "!MATCHES!"=="1" exit /b 2
|
||||
docker stop --time 5 "!TARGET_CONTAINER!" >nul
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname -- "$SCRIPT_DIR")
|
||||
cd "$PROJECT_DIR"
|
||||
: "${ENV_FILE:=.env}"
|
||||
|
||||
target=""
|
||||
matches=0
|
||||
for container_id in $(docker compose --env-file "$ENV_FILE" ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
|
||||
short_id=$(printf '%s' "$container_id" | cut -c1-12)
|
||||
if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$short_id" ]; then
|
||||
target=$container_id
|
||||
matches=$((matches + 1))
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$matches" -ne 1 ]; then
|
||||
printf '%s\n' "Expected one API replica for X-Instance-Id, found $matches" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
# Five seconds keeps the operator hook below the test's ten-second budget while
|
||||
# still delivering SIGTERM and allowing Spring's graceful shutdown phase.
|
||||
docker stop --time 5 "$target" >/dev/null
|
||||
@@ -0,0 +1,19 @@
|
||||
$ErrorActionPreference = 'Continue'
|
||||
if (Test-Path variable:PSNativeCommandUseErrorActionPreference) {
|
||||
$PSNativeCommandUseErrorActionPreference = $false
|
||||
}
|
||||
|
||||
$nodes = @('hla-swarm-manager', 'hla-swarm-worker1', 'hla-swarm-worker2', 'hla-swarm-registry')
|
||||
foreach ($node in $nodes) {
|
||||
$existing = (& docker ps --all --filter "name=^/${node}$" --format '{{.Names}}')
|
||||
if ($existing -eq $node) {
|
||||
docker rm --force $node | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Cannot remove $node" }
|
||||
}
|
||||
}
|
||||
$existingNetwork = (& docker network ls --filter 'name=^hla-swarm-underlay$' --format '{{.Name}}')
|
||||
if ($existingNetwork -eq 'hla-swarm-underlay') {
|
||||
docker network rm hla-swarm-underlay | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot remove hla-swarm-underlay' }
|
||||
}
|
||||
Write-Output 'Removed the disposable three-node Swarm lab and its nested volumes.'
|
||||
@@ -0,0 +1,171 @@
|
||||
$ErrorActionPreference = 'Continue'
|
||||
if (Test-Path variable:PSNativeCommandUseErrorActionPreference) {
|
||||
$PSNativeCommandUseErrorActionPreference = $false
|
||||
}
|
||||
|
||||
$projectDir = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $projectDir
|
||||
|
||||
$manager = 'hla-swarm-manager'
|
||||
$nodes = @($manager, 'hla-swarm-worker1', 'hla-swarm-worker2')
|
||||
$network = 'hla-swarm-underlay'
|
||||
$registry = 'hla-swarm-registry'
|
||||
|
||||
function Invoke-Checked {
|
||||
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)
|
||||
$executable = $Command[0]
|
||||
$arguments = if ($Command.Length -gt 1) {
|
||||
$Command[1..($Command.Length - 1)]
|
||||
} else {
|
||||
@()
|
||||
}
|
||||
& $executable @arguments
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "Command failed: $($Command -join ' ')"
|
||||
}
|
||||
}
|
||||
|
||||
function Wait-InnerDocker([string]$Node) {
|
||||
$deadline = (Get-Date).AddSeconds(90)
|
||||
do {
|
||||
& docker exec $Node docker info *> $null
|
||||
if ($LASTEXITCODE -eq 0) { return }
|
||||
Start-Sleep -Seconds 2
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
throw "Docker daemon did not start in $Node"
|
||||
}
|
||||
|
||||
function Wait-Service([string]$Service, [string]$Expected, [int]$Seconds = 180) {
|
||||
$deadline = (Get-Date).AddSeconds($Seconds)
|
||||
do {
|
||||
$replicas = (& docker exec $manager docker service ls `
|
||||
--filter "name=$Service" --format '{{.Replicas}}' 2>$null | Select-Object -First 1)
|
||||
if ($replicas -like "$Expected*") { return }
|
||||
Start-Sleep -Seconds 2
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
throw "Service $Service did not reach $Expected replicas"
|
||||
}
|
||||
|
||||
foreach ($node in $nodes) {
|
||||
$existing = (& docker ps --all --filter "name=^/${node}$" --format '{{.Names}}')
|
||||
if ($existing -eq $node) {
|
||||
throw "Container $node already exists. Run scripts/swarm-lab-down.ps1 first."
|
||||
}
|
||||
}
|
||||
$existingRegistry = (& docker ps --all --filter "name=^/${registry}$" --format '{{.Names}}')
|
||||
if ($existingRegistry -eq $registry) {
|
||||
throw "Container $registry already exists. Run scripts/swarm-lab-down.ps1 first."
|
||||
}
|
||||
|
||||
$envValues = @{}
|
||||
Get-Content -LiteralPath '.env' | ForEach-Object {
|
||||
if ($_ -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') {
|
||||
$envValues[$matches[1]] = $matches[2].Trim('"', "'")
|
||||
}
|
||||
}
|
||||
$password = $envValues['DATABASE_PASSWORD']
|
||||
if ([string]::IsNullOrWhiteSpace($password)) { throw 'DATABASE_PASSWORD is missing from .env' }
|
||||
$database = if ($envValues['DATABASE_NAME']) { $envValues['DATABASE_NAME'] } else { 'messenger' }
|
||||
$user = if ($envValues['DATABASE_USER']) { $envValues['DATABASE_USER'] } else { 'messenger' }
|
||||
$minioRootUser = $envValues['MINIO_ROOT_USER']
|
||||
$minioRootPassword = $envValues['MINIO_ROOT_PASSWORD']
|
||||
$s3AccessKey = $envValues['S3_ACCESS_KEY_ID']
|
||||
$s3SecretKey = $envValues['S3_SECRET_ACCESS_KEY']
|
||||
$s3Bucket = if ($envValues['S3_BUCKET']) { $envValues['S3_BUCKET'] } else { 'messenger-attachments' }
|
||||
$s3Region = if ($envValues['S3_REGION']) { $envValues['S3_REGION'] } else { 'us-east-1' }
|
||||
foreach ($required in @{
|
||||
MINIO_ROOT_USER = $minioRootUser
|
||||
MINIO_ROOT_PASSWORD = $minioRootPassword
|
||||
S3_ACCESS_KEY_ID = $s3AccessKey
|
||||
S3_SECRET_ACCESS_KEY = $s3SecretKey
|
||||
}.GetEnumerator()) {
|
||||
if ([string]::IsNullOrWhiteSpace($required.Value)) { throw "$($required.Key) is missing from .env" }
|
||||
}
|
||||
|
||||
$existingNetwork = (& docker network ls --filter "name=^${network}$" --format '{{.Name}}')
|
||||
if ($existingNetwork -ne $network) { Invoke-Checked docker network create $network }
|
||||
|
||||
Invoke-Checked docker run --detach --name $registry --hostname $registry `
|
||||
--network $network --publish 127.0.0.1:15000:5000 registry:2
|
||||
|
||||
Invoke-Checked docker run --privileged --detach --name $manager --hostname $manager `
|
||||
--network $network --publish 127.0.0.1:18080:8080 `
|
||||
--volume "${projectDir}:/project:ro" --env DOCKER_TLS_CERTDIR= docker:28-dind `
|
||||
--storage-driver=overlay2 --insecure-registry=${registry}:5000
|
||||
foreach ($worker in $nodes[1..2]) {
|
||||
Invoke-Checked docker run --privileged --detach --name $worker --hostname $worker `
|
||||
--network $network --env DOCKER_TLS_CERTDIR= docker:28-dind `
|
||||
--storage-driver=overlay2 --insecure-registry=${registry}:5000
|
||||
}
|
||||
foreach ($node in $nodes) { Wait-InnerDocker $node }
|
||||
|
||||
$managerIp = (& docker inspect --format `
|
||||
'{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $manager).Trim()
|
||||
Invoke-Checked docker exec $manager docker swarm init --advertise-addr $managerIp
|
||||
$token = (& docker exec $manager docker swarm join-token --quiet worker).Trim()
|
||||
foreach ($worker in $nodes[1..2]) {
|
||||
Invoke-Checked docker exec $worker docker swarm join --token $token "$managerIp`:2377"
|
||||
}
|
||||
Invoke-Checked docker exec $manager docker node update `
|
||||
--label-add hla.state=true --label-add hla.lb=true $manager
|
||||
|
||||
Invoke-Checked docker compose --env-file .env build api
|
||||
Invoke-Checked docker tag hla-lab6-app:local localhost:15000/hla-lab6-api:swarm
|
||||
Invoke-Checked docker build --file swarm/nginx.Dockerfile `
|
||||
--tag localhost:15000/hla-lab6-nginx:swarm .
|
||||
Invoke-Checked docker push localhost:15000/hla-lab6-api:swarm
|
||||
Invoke-Checked docker push localhost:15000/hla-lab6-nginx:swarm
|
||||
|
||||
Invoke-Checked docker exec --env "DATABASE_PASSWORD=$password" `
|
||||
--env "DATABASE_NAME=$database" --env "DATABASE_USER=$user" `
|
||||
--env "MINIO_ROOT_USER=$minioRootUser" --env "MINIO_ROOT_PASSWORD=$minioRootPassword" `
|
||||
--env "S3_ACCESS_KEY_ID=$s3AccessKey" --env "S3_SECRET_ACCESS_KEY=$s3SecretKey" `
|
||||
--env "S3_BUCKET=$s3Bucket" `
|
||||
$manager docker stack deploy --compose-file /project/swarm/stack.state.yaml hla-state
|
||||
Wait-Service 'hla-state_postgres' '1/1'
|
||||
Wait-Service 'hla-state_redis' '1/1'
|
||||
Wait-Service 'hla-state_minio' '1/1'
|
||||
|
||||
$deadline = (Get-Date).AddSeconds(180)
|
||||
do {
|
||||
$minioInitState = (& docker exec $manager docker service ps hla-state_minio-init `
|
||||
--no-trunc --format '{{.CurrentState}}' | Select-Object -First 1)
|
||||
if ($minioInitState -like 'Complete*') { break }
|
||||
Start-Sleep -Seconds 2
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
if ($minioInitState -notlike 'Complete*') { throw 'MinIO bucket bootstrap did not complete' }
|
||||
|
||||
Invoke-Checked docker exec $manager docker service create --name hla-migrate `
|
||||
--mode replicated-job --replicas 1 --max-concurrent 1 `
|
||||
--network hla-state_backend --constraint node.labels.hla.state==true `
|
||||
--restart-condition on-failure --restart-delay 3s `
|
||||
--limit-cpu 0.75 --limit-memory 768M `
|
||||
--env "DATABASE_URL=jdbc:postgresql://hla-state_postgres:5432/$database" `
|
||||
--env "DATABASE_USER=$user" --env "DATABASE_PASSWORD=$password" `
|
||||
--env FLYWAY_ENABLED=true --env MIGRATE_ONLY=true `
|
||||
--env SPRING_MAIN_WEB_APPLICATION_TYPE=none `
|
||||
--env "S3_ENDPOINT=http://hla-state_minio:9000" `
|
||||
--env "S3_BUCKET=$s3Bucket" --env "S3_REGION=$s3Region" `
|
||||
--env "S3_ACCESS_KEY_ID=$s3AccessKey" --env "S3_SECRET_ACCESS_KEY=$s3SecretKey" `
|
||||
hla-swarm-registry:5000/hla-lab6-api:swarm
|
||||
$deadline = (Get-Date).AddSeconds(180)
|
||||
do {
|
||||
$state = (& docker exec $manager docker service ps hla-migrate `
|
||||
--no-trunc --format '{{.CurrentState}}' | Select-Object -First 1)
|
||||
if ($state -like 'Complete*') { break }
|
||||
Start-Sleep -Seconds 2
|
||||
} while ((Get-Date) -lt $deadline)
|
||||
if ($state -notlike 'Complete*') { throw 'Migration job did not complete' }
|
||||
Invoke-Checked docker exec $manager docker service rm hla-migrate
|
||||
|
||||
Invoke-Checked docker exec --env "DATABASE_PASSWORD=$password" `
|
||||
--env "DATABASE_NAME=$database" --env "DATABASE_USER=$user" `
|
||||
--env "S3_BUCKET=$s3Bucket" --env "S3_REGION=$s3Region" `
|
||||
--env "S3_ACCESS_KEY_ID=$s3AccessKey" --env "S3_SECRET_ACCESS_KEY=$s3SecretKey" `
|
||||
$manager docker stack deploy --compose-file /project/swarm/stack.app.yaml hla-app
|
||||
Wait-Service 'hla-app_api' '2/2'
|
||||
Wait-Service 'hla-app_nginx' '1/1'
|
||||
|
||||
Write-Output 'Swarm lab is ready at http://localhost:18080'
|
||||
Invoke-Checked docker exec $manager docker node ls
|
||||
Invoke-Checked docker exec $manager docker service ps hla-app_api
|
||||
Reference in New Issue
Block a user