forked from mtusi2026/mtusi2026lab6
lab6: OpenTelemetry (traces, metrics, logs), Collector, Prometheus, Loki, Tempo, Grafana; перенос trace context через outbox и AMQP
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Прогоняет проверки lab3–lab6 на запущенном Docker-стенде и сохраняет вывод в evidence/.
|
||||
# Токены и секреты не печатаются (тесты держат их в памяти, mc читает их внутри контейнера).
|
||||
#
|
||||
# sh scripts/collect-evidence.sh base # уровни 3–4 lab3/lab4 + smoke/persistence/failover lab5
|
||||
# sh scripts/collect-evidence.sh files # вложения lab4: негативный набор, отказы S3/БД, приватность, память
|
||||
# sh scripts/collect-evidence.sh pipeline # lab5: демонстрация, outbox, падения worker, broker, retry, replay, лимиты
|
||||
# sh scripts/collect-evidence.sh obs # lab6: сигналы, сквозная трасса, утечки, инциденты, отказ backend
|
||||
# sh scripts/collect-evidence.sh track1 # lab6 трек 1: цена наблюдаемости (off / full / head10 / tail)
|
||||
# sh scripts/collect-evidence.sh all
|
||||
# Windows (Git Bash): PYTHON=python STOP=scripts/win/stop-one.cmd RESTART=scripts/win/restart.cmd sh scripts/collect-evidence.sh all
|
||||
cd "$(dirname "$0")/.."
|
||||
PY=${PYTHON:-python3}
|
||||
STOP=${STOP:-scripts/stop-one.sh}
|
||||
RESTART=${RESTART:-scripts/restart.sh}
|
||||
BASE=${BASE_URL:-http://localhost:8080}
|
||||
WHAT=${1:-all}
|
||||
export PYTHONUTF8=1
|
||||
mkdir -p evidence evidence/files evidence/pipeline evidence/obs evidence/track1
|
||||
|
||||
step() { echo "== $*"; }
|
||||
|
||||
base() {
|
||||
step "состояние стенда и образы"
|
||||
{ date -u +%Y-%m-%dT%H:%M:%SZ; docker compose version; docker compose ps; } > evidence/docker_ps.txt
|
||||
for img in $(docker compose config --images | sort -u); do
|
||||
printf '%s %s\n' "$img" "$(docker image inspect --format '{{index .RepoDigests 0}}' "$img" 2>/dev/null || echo local-build)"
|
||||
done > evidence/images.txt
|
||||
cat evidence/images.txt
|
||||
|
||||
step "X-Instance-Id через LB"
|
||||
$PY - "$BASE" > evidence/instances.txt <<'EOF'
|
||||
import sys, urllib.request, collections
|
||||
seen = collections.Counter()
|
||||
for _ in range(20):
|
||||
with urllib.request.urlopen(sys.argv[1] + '/health/ready') as r:
|
||||
seen[r.headers['X-Instance-Id']] += 1
|
||||
for k, v in sorted(seen.items()):
|
||||
print(k, v)
|
||||
EOF
|
||||
cat evidence/instances.txt
|
||||
|
||||
step "smoke (lab5: 202 → ready, thumbnail 256×160)"
|
||||
$PY tests/smoke.py --base-url "$BASE" | tee evidence/smoke.txt
|
||||
|
||||
step "конкурентная идемпотентность"
|
||||
$PY student-tests/idempotency_concurrent.py --base-url "$BASE" --output evidence/idempotency_concurrent.json | tail -1
|
||||
|
||||
step "регрессии lab3"
|
||||
$PY student-tests/regressions.py --base-url "$BASE" > evidence/regressions.txt 2>&1
|
||||
cat evidence/regressions.txt
|
||||
|
||||
step "публичный failover (с вложением), 2 прогона"
|
||||
for n in 1 2; do
|
||||
{ $PY tests/resilience.py --mode failover --action-script "$STOP" --base-url "$BASE" || echo "FAILED"; \
|
||||
echo "-- контейнеры api после stop-one:"; docker compose ps -a api --format '{{.Name}} {{.ID}} {{.Status}}'; } \
|
||||
> evidence/failover_$n.txt 2>&1
|
||||
cat evidence/failover_$n.txt
|
||||
sh scripts/restore.sh >> evidence/failover_$n.txt
|
||||
done
|
||||
|
||||
step "persistence (restart всего стенда: PostgreSQL, Redis, S3, RabbitMQ, с volumes)"
|
||||
{ echo "-- до:"; docker compose ps --format '{{.Name}} {{.Status}}'; \
|
||||
$PY tests/resilience.py --mode persistence --action-script "$RESTART" --base-url "$BASE" || echo "FAILED"; \
|
||||
echo "-- после:"; docker compose ps --format '{{.Name}} {{.Status}}'; } > evidence/persistence.txt 2>&1
|
||||
cat evidence/persistence.txt
|
||||
|
||||
step "серия отказов каждой реплики под нагрузкой"
|
||||
$PY student-tests/failover_series.py --base-url "$BASE" --output evidence/failover_series.json | tail -1
|
||||
|
||||
step "rolling update под нагрузкой"
|
||||
docker compose build -q api
|
||||
{ echo "-- до:"; docker compose ps api --format '{{.Name}} {{.ID}} {{.Status}}'; } > evidence/rolling_update.txt
|
||||
$PY tests/load.py --base-url "$BASE" --duration 90 --concurrency 4 --output evidence/rolling_update_load.json > /dev/null &
|
||||
LOAD=$!
|
||||
sleep 5
|
||||
start=$(date +%s)
|
||||
sh scripts/rolling-update.sh >> evidence/rolling_update.txt 2>&1
|
||||
echo "-- замена заняла $(( $(date +%s) - start )) s (внутри 90 s нагрузки)" >> evidence/rolling_update.txt
|
||||
wait $LOAD
|
||||
tail -4 evidence/rolling_update.txt; cat evidence/rolling_update_load.json
|
||||
}
|
||||
|
||||
files() {
|
||||
step "негативный набор вложений"
|
||||
$PY student-tests/attachments_negative.py --base-url "$BASE" > evidence/files/attachments_negative.txt 2>&1 || echo "FAILED: attachments_negative"
|
||||
tail -3 evidence/files/attachments_negative.txt
|
||||
for s in failover s3-outage interrupt security db-gap memory; do
|
||||
step "вложения: $s"
|
||||
$PY student-tests/attachments_ops.py "$s" --base-url "$BASE" --output "evidence/files/files_$s.json" > "evidence/files/files_$s.log" 2>&1 || echo "FAILED: $s"
|
||||
tail -1 "evidence/files/files_$s.log"
|
||||
done
|
||||
}
|
||||
|
||||
pipeline() {
|
||||
for s in demo outbox-gap crash-effect crash-commit broker-restart transient failed-replay limits; do
|
||||
step "pipeline: $s"
|
||||
$PY student-tests/pipeline_ops.py "$s" --base-url "$BASE" --output "evidence/pipeline/$s.json" > "evidence/pipeline/$s.log" 2>&1 || echo "FAILED: $s"
|
||||
tail -1 "evidence/pipeline/$s.log"
|
||||
done
|
||||
docker compose logs --no-color worker relay 2>&1 | grep -E 'FAULT|lease|duplicate|retry|dead-letter|failed' | tail -60 > evidence/pipeline/worker_relay_log.txt || true
|
||||
}
|
||||
|
||||
obs() {
|
||||
for s in signals retry-trace incident-worker incident-db backend-down; do
|
||||
step "наблюдаемость: $s"
|
||||
$PY student-tests/observability_ops.py "$s" --base-url "$BASE" --output "evidence/obs/$s.json" > "evidence/obs/$s.log" 2>&1 || echo "FAILED: $s"
|
||||
tail -1 "evidence/obs/$s.log"
|
||||
done
|
||||
step "правила, alerts, имена метрик (из Prometheus через Grafana)"
|
||||
(cd student-tests && $PY - <<'EOF' > ../evidence/obs/prometheus_state.json
|
||||
import json, obsutil as o
|
||||
names = o.prom_label_values('__name__')
|
||||
keep = [n for n in names if n.startswith(('http_', 'messenger', 'pgxpool', 'process_', 'go_', 'otelcol_exporter', 'otelcol_receiver', 'rabbitmq_detailed_queue_messages', 'target_info'))]
|
||||
rules = o.grafana('/api/datasources/proxy/uid/prometheus/api/v1/rules')['data']['groups']
|
||||
print(json.dumps({'metric_names': keep,
|
||||
'rules': [{'group': g['name'], 'name': r['name'], 'type': r['type'], 'health': r['health'],
|
||||
'state': r.get('state'), 'query': r['query'], 'duration': r.get('duration')}
|
||||
for g in rules for r in g['rules']],
|
||||
'alerts_now': o.alerts()}, ensure_ascii=False, indent=1))
|
||||
EOF
|
||||
) || echo "FAILED: prometheus_state"
|
||||
step "снимок dashboard (headless Chrome, анонимный Viewer только в CI)"
|
||||
if command -v google-chrome >/dev/null 2>&1; then
|
||||
google-chrome --headless=new --no-sandbox --disable-gpu --hide-scrollbars --window-size=1600,3000 --virtual-time-budget=25000 --screenshot=evidence/obs/dashboard.png "http://127.0.0.1:3000/d/messenger-overview/?orgId=1&from=now-45m&to=now&kiosk" >/dev/null 2>&1 || echo "screenshot failed"
|
||||
fi
|
||||
}
|
||||
|
||||
track1() {
|
||||
step "трек 1: цена наблюдаемости (3 повтора × 4 конфигурации)"
|
||||
$PY student-tests/telemetry_cost.py --rounds 3 --base-url "$BASE" --output evidence/track1/telemetry_cost.json > evidence/track1/telemetry_cost.log 2>&1 || echo "FAILED: telemetry_cost"
|
||||
tail -60 evidence/track1/telemetry_cost.log
|
||||
}
|
||||
|
||||
case "$WHAT" in
|
||||
base) base ;;
|
||||
files) files ;;
|
||||
pipeline) pipeline ;;
|
||||
obs) obs ;;
|
||||
track1) track1 ;;
|
||||
all) base; files; pipeline; obs; track1 ;;
|
||||
*) echo "usage: $0 base|files|pipeline|obs|track1|all" >&2; exit 2 ;;
|
||||
esac
|
||||
docker stats --no-stream --format '{{.Name}} {{.CPUPerc}} {{.MemUsage}}' > "evidence/docker_stats_$WHAT.txt"
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Генератор dashboard Grafana (infra/grafana/dashboards/messenger.json).
|
||||
|
||||
JSON в Git — то, что импортирует provisioning; этот скрипт лишь делает его
|
||||
воспроизводимым: python3 scripts/gen_dashboard.py. Все percentile считаются
|
||||
histogram_quantile по сумме buckets всех реплик (sum by le), не из средних.
|
||||
"""
|
||||
import json
|
||||
import pathlib
|
||||
|
||||
PROM = {'type': 'prometheus', 'uid': 'prometheus'}
|
||||
LOKI = {'type': 'loki', 'uid': 'loki'}
|
||||
TEMPO = {'type': 'tempo', 'uid': 'tempo'}
|
||||
API = 'job="messenger-api", http_route!~"/health/.*"'
|
||||
|
||||
panels = []
|
||||
y = 0
|
||||
pid = 0
|
||||
|
||||
|
||||
def nid():
|
||||
global pid
|
||||
pid += 1
|
||||
return pid
|
||||
|
||||
|
||||
def row(title):
|
||||
global y
|
||||
panels.append({'type': 'row', 'title': title, 'id': nid(), 'collapsed': False,
|
||||
'gridPos': {'h': 1, 'w': 24, 'x': 0, 'y': y}, 'panels': []})
|
||||
y += 1
|
||||
|
||||
|
||||
def ts(title, targets, unit, x, w=8, h=8, desc='', stack=False, minv=None):
|
||||
p = {'type': 'timeseries', 'title': title, 'id': nid(), 'datasource': PROM, 'description': desc,
|
||||
'gridPos': {'h': h, 'w': w, 'x': x, 'y': y},
|
||||
'fieldConfig': {'defaults': {'unit': unit, 'custom': {'fillOpacity': 10, 'showPoints': 'never',
|
||||
'stacking': {'mode': 'normal' if stack else 'none'}}},
|
||||
'overrides': []},
|
||||
'options': {'legend': {'displayMode': 'list', 'placement': 'bottom'}, 'tooltip': {'mode': 'multi'}},
|
||||
'targets': [{'datasource': PROM, 'expr': e, 'legendFormat': l, 'refId': chr(65 + i),
|
||||
'exemplar': True} for i, (e, l) in enumerate(targets)]}
|
||||
if minv is not None:
|
||||
p['fieldConfig']['defaults']['min'] = minv
|
||||
panels.append(p)
|
||||
|
||||
|
||||
def stat(title, expr, unit, x, w=4, h=4, desc='', thresholds=None):
|
||||
steps = thresholds or [{'color': 'green', 'value': None}]
|
||||
panels.append({'type': 'stat', 'title': title, 'id': nid(), 'datasource': PROM, 'description': desc,
|
||||
'gridPos': {'h': h, 'w': w, 'x': x, 'y': y},
|
||||
'fieldConfig': {'defaults': {'unit': unit, 'thresholds': {'mode': 'absolute', 'steps': steps}},
|
||||
'overrides': []},
|
||||
'options': {'reduceOptions': {'calcs': ['lastNotNull']}, 'colorMode': 'value'},
|
||||
'targets': [{'datasource': PROM, 'expr': expr, 'refId': 'A'}]})
|
||||
|
||||
|
||||
def q(expr, by='le'):
|
||||
return lambda p: f'histogram_quantile({p}, sum by ({by}) (rate({expr}[$__rate_interval])))'
|
||||
|
||||
|
||||
# ---------------- SLO / сводка ----------------
|
||||
row('Сводка и SLO')
|
||||
stat('RPS API (бизнес)', 'messenger:http_requests:rate1m', 'reqps', 0,
|
||||
desc='sum(rate(http_server_request_duration_seconds_count)) без /health/*')
|
||||
stat('Доля 5xx (1m)', 'messenger:http_error_ratio:rate1m', 'percentunit', 4,
|
||||
desc='5xx / все бизнес-запросы (кроме /health/*). SLO: ≤ 0.5%',
|
||||
thresholds=[{'color': 'green', 'value': None}, {'color': 'orange', 'value': 0.005}, {'color': 'red', 'value': 0.05}])
|
||||
stat('Быстрее 250 ms (5m)', 'messenger:http_fast_ratio:rate5m', 'percentunit', 8,
|
||||
desc='SLO задержки: ≥ 95% бизнес-запросов быстрее 250 ms',
|
||||
thresholds=[{'color': 'red', 'value': None}, {'color': 'green', 'value': 0.95}])
|
||||
stat('Ready быстрее 30 s (5m)', 'messenger:time_to_ready_fast_ratio:rate5m', 'percentunit', 12,
|
||||
desc='SLO времени до ready: ≥ 95% вложений',
|
||||
thresholds=[{'color': 'red', 'value': None}, {'color': 'green', 'value': 0.95}])
|
||||
stat('Старейшая job', 'max(messenger_jobs_oldest_age_seconds)', 's', 16,
|
||||
thresholds=[{'color': 'green', 'value': None}, {'color': 'orange', 'value': 30}, {'color': 'red', 'value': 60}])
|
||||
stat('Alerts firing', 'count(ALERTS{alertstate="firing"}) or vector(0)', 'none', 20,
|
||||
thresholds=[{'color': 'green', 'value': None}, {'color': 'red', 'value': 1}])
|
||||
y += 4
|
||||
|
||||
# ---------------- API ----------------
|
||||
row('API (messenger-api)')
|
||||
hist = f'http_server_request_duration_seconds_bucket{{{API}}}'
|
||||
ts('RPS по маршруту и классу ответа',
|
||||
[(f'sum by (http_route, http_response_status_class) (rate(http_server_request_duration_seconds_count{{{API}}}[$__rate_interval]))',
|
||||
'{{http_route}} {{http_response_status_class}}')], 'reqps', 0, desc='Счётчик = _count histogram (одна метрика, не две)')
|
||||
ts('Задержка API p50 / p95 / p99 (все реплики)',
|
||||
[(q(hist)(0.5), 'p50'), (q(hist)(0.95), 'p95'), (q(hist)(0.99), 'p99')], 's', 8,
|
||||
desc='histogram_quantile по сумме buckets всех реплик; среднее p99 реплик не используется')
|
||||
ts('Доля ошибок 5xx и 4xx',
|
||||
[('messenger:http_error_ratio:rate1m', '5xx / все'),
|
||||
(f'sum(rate(http_server_request_duration_seconds_count{{{API}, http_response_status_class="4xx"}}[1m])) / messenger:http_requests:rate1m', '4xx / все (ошибки клиента)')],
|
||||
'percentunit', 16, minv=0)
|
||||
y += 8
|
||||
ts('p95 по маршруту', [(f'histogram_quantile(0.95, sum by (le, http_route) (rate({hist}[$__rate_interval])))', '{{http_route}}')],
|
||||
's', 0, w=12)
|
||||
ts('Запросы в обработке (in-flight) по реплике',
|
||||
[('sum by (instance) (http_server_active_requests{job="messenger-api"})', '{{instance}}')], 'none', 12, w=12)
|
||||
y += 8
|
||||
|
||||
# ---------------- Worker / очередь ----------------
|
||||
row('Worker и очередь')
|
||||
ts('Jobs по исходу (rate)', [('sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))', '{{outcome}}')],
|
||||
'ops', 0, desc='done / retry / failed / duplicate / not_due / requeue …')
|
||||
jd = 'messenger_job_duration_seconds_bucket{outcome="done"}'
|
||||
ts('Длительность обработки job p50 / p95 / p99', [(q(jd)(0.5), 'p50'), (q(jd)(0.95), 'p95'), (q(jd)(0.99), 'p99')], 's', 8)
|
||||
tr = 'messenger_attachment_time_to_ready_seconds_bucket'
|
||||
ts('Время до ready (202 → ready) p50 / p95', [(q(tr)(0.5), 'p50'), (q(tr)(0.95), 'p95')], 's', 16)
|
||||
y += 8
|
||||
ts('Очередь: jobs по состоянию (PostgreSQL)', [('sum by (state) (messenger_jobs_backlog)', '{{state}}'),
|
||||
('sum(messenger_outbox_pending)', 'outbox не опубликовано')], 'none', 0)
|
||||
ts('Возраст старейшей job / outbox', [('max(messenger_jobs_oldest_age_seconds)', 'job (queued/processing)'),
|
||||
('max(messenger_outbox_oldest_age_seconds)', 'outbox')], 's', 8,
|
||||
desc='Backlog (сколько ждёт) ≠ latency обработки; alert при > 60 s')
|
||||
ts('RabbitMQ: сообщения в очередях',
|
||||
[('sum by (queue) (rabbitmq_detailed_queue_messages_ready or rabbitmq_queue_messages_ready)', 'ready {{queue}}'),
|
||||
('sum by (queue) (rabbitmq_detailed_queue_messages_unacked or rabbitmq_queue_messages_unacked)', 'unacked {{queue}}')],
|
||||
'none', 16)
|
||||
y += 8
|
||||
ts('Saturation worker (busy / capacity)',
|
||||
[('sum(messenger_worker_busy) / sum(messenger_worker_capacity)', 'занято слотов')], 'percentunit', 0, minv=0)
|
||||
ts('Publish outbox → broker (confirm) p95',
|
||||
[(q('messenger_outbox_publish_duration_seconds_bucket')(0.95), 'p95'),
|
||||
('sum(rate(messenger_outbox_published_total[$__rate_interval]))', 'сообщений/с')], 's', 8)
|
||||
ts('Пул БД: занято / ожидания',
|
||||
[('sum by (job) (pgxpool_acquired_connections)', 'занято {{job}}'),
|
||||
('sum by (job) (pgxpool_max_connections)', 'max {{job}}'),
|
||||
('sum by (job) (rate(pgxpool_empty_acquire_total[$__rate_interval]))', 'ожиданий/с {{job}}')], 'none', 16,
|
||||
desc='empty_acquire — acquire, которому пришлось ждать свободное соединение')
|
||||
y += 8
|
||||
|
||||
# ---------------- Ресурсы ----------------
|
||||
row('Ресурсы процессов и телеметрии')
|
||||
ts('CPU процессов', [('sum by (job, instance) (rate(process_cpu_time_seconds_total[$__rate_interval]))', '{{job}} {{instance}}')],
|
||||
'percentunit', 0, desc='доля одного ядра; лимиты контейнеров в compose.yaml')
|
||||
ts('Память Go (used)', [('sum by (job, instance) (go_memory_used_bytes)', '{{job}} {{instance}}')], 'bytes', 8)
|
||||
ts('Collector: принято / отправлено / потеряно spans',
|
||||
[('sum(rate(otelcol_receiver_accepted_spans_total[$__rate_interval]))', 'принято'),
|
||||
('sum(rate(otelcol_exporter_sent_spans_total[$__rate_interval]))', 'отправлено'),
|
||||
('sum(rate(otelcol_exporter_send_failed_spans_total[$__rate_interval]))', 'не доставлено'),
|
||||
('sum(rate(otelcol_receiver_refused_spans_total[$__rate_interval]))', 'отклонено (memory_limiter)'),
|
||||
('sum(otelcol_exporter_queue_size)', 'очередь экспортёров')], 'none', 16)
|
||||
y += 8
|
||||
|
||||
# ---------------- Логи и трассы ----------------
|
||||
row('Логи и трассы')
|
||||
panels.append({'type': 'logs', 'title': 'Логи API и worker (ошибки и предупреждения)', 'id': nid(), 'datasource': LOKI,
|
||||
'gridPos': {'h': 10, 'w': 12, 'x': 0, 'y': y},
|
||||
'options': {'showTime': True, 'wrapLogMessage': True, 'enableLogDetails': True, 'sortOrder': 'Descending'},
|
||||
'targets': [{'datasource': LOKI, 'refId': 'A',
|
||||
'expr': '{service_name=~"messenger-(api|worker|relay)"} | detected_level=~"warn|error|WARN|ERROR"'}]})
|
||||
panels.append({'type': 'table', 'title': 'Трассы worker (последние)', 'id': nid(), 'datasource': TEMPO,
|
||||
'gridPos': {'h': 10, 'w': 12, 'x': 12, 'y': y},
|
||||
'targets': [{'datasource': TEMPO, 'refId': 'A', 'queryType': 'traceql', 'limit': 20,
|
||||
'query': '{resource.service.name="messenger-worker" && name="attachment.process process"}'}]})
|
||||
y += 10
|
||||
|
||||
dash = {
|
||||
'uid': 'messenger-overview', 'title': 'Messenger — API, worker, очередь', 'tags': ['lab6', 'messenger'],
|
||||
'timezone': 'browser', 'schemaVersion': 39, 'version': 1, 'refresh': '10s',
|
||||
'time': {'from': 'now-30m', 'to': 'now'}, 'editable': False, 'graphTooltip': 1,
|
||||
'panels': panels, 'templating': {'list': []}, 'annotations': {'list': [
|
||||
{'name': 'Alerts', 'datasource': PROM, 'enable': True, 'iconColor': 'red',
|
||||
'expr': 'ALERTS{alertstate="firing"}', 'titleFormat': '{{alertname}}', 'step': '10s'}]},
|
||||
}
|
||||
out = pathlib.Path(__file__).resolve().parent.parent / 'infra' / 'grafana' / 'dashboards' / 'messenger.json'
|
||||
out.write_text(json.dumps(dash, ensure_ascii=False, indent=1) + '\n', encoding='utf-8')
|
||||
print(out, len(panels), 'panels')
|
||||
@@ -0,0 +1,32 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Создаёт локальные .env и secrets/ для учебного стенда. Повторный запуск ничего
|
||||
# не перезаписывает (иначе пароль разойдётся с уже инициализированным volume).
|
||||
cd "$(dirname "$0")/.."
|
||||
[ -f .env ] || cp .env.example .env
|
||||
mkdir -p secrets
|
||||
chmod 700 secrets
|
||||
if [ ! -f secrets/postgres_password ]; then
|
||||
# 32 случайных байта в hex — без символов, требующих экранирования в URL.
|
||||
pw=$(od -An -N32 -tx1 /dev/urandom | tr -d ' \n')
|
||||
printf '%s' "$pw" > secrets/postgres_password
|
||||
printf 'postgres://messenger:%s@postgres:5432/messenger?sslmode=disable' "$pw" > secrets/database_url
|
||||
fi
|
||||
[ -f secrets/cache_url ] || printf '%s' 'redis://redis:6379/0' > secrets/cache_url
|
||||
rnd() { od -An -N"$1" -tx1 /dev/urandom | tr -d ' \n'; }
|
||||
# MinIO: root — только для s3 и s3-init; отдельный ключ API с правами на один bucket.
|
||||
[ -f secrets/s3_root_user ] || printf 'root-%s' "$(rnd 6)" > secrets/s3_root_user
|
||||
[ -f secrets/s3_root_password ] || printf '%s' "$(rnd 24)" > secrets/s3_root_password
|
||||
[ -f secrets/s3_access_key_id ] || printf 'api-%s' "$(rnd 8)" > secrets/s3_access_key_id
|
||||
[ -f secrets/s3_secret_access_key ] || printf '%s' "$(rnd 24)" > secrets/s3_secret_access_key
|
||||
# RabbitMQ: отдельный пользователь вместо guest; URL для relay/worker.
|
||||
if [ ! -f secrets/broker_url ]; then
|
||||
bpw=$(rnd 24)
|
||||
printf 'default_user = messenger\ndefault_pass = %s\nloopback_users.guest = true\n' "$bpw" > secrets/rabbitmq.conf
|
||||
printf 'amqp://messenger:%s@rabbitmq:5672/' "$bpw" > secrets/broker_url
|
||||
fi
|
||||
# Grafana: пароль admin (UI/API только на 127.0.0.1:3000).
|
||||
[ -f secrets/grafana_admin_password ] || printf '%s' "$(rnd 18)" > secrets/grafana_admin_password
|
||||
# 644: файлы монтируются в контейнеры (uid 1001) как есть; доступ с хоста закрывает каталог 700.
|
||||
chmod 644 secrets/* 2>/dev/null || true
|
||||
echo "secrets ready in ./secrets (values not printed)"
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Перезапускает API, LB, reconciler, relay, worker, все хранилища (PostgreSQL, Redis, S3, RabbitMQ)
|
||||
# и стек наблюдаемости (Collector, Prometheus, Loki, Tempo, Grafana)
|
||||
# с сохранением volumes.
|
||||
# Никаких down -v / FLUSH / повторного seed.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop lb api reconciler relay worker
|
||||
docker compose restart postgres redis s3 rabbitmq otel-collector prometheus loki tempo grafana
|
||||
|
||||
until docker compose exec -T postgres pg_isready -U messenger -d messenger >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
until docker compose exec -T redis redis-cli ping >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q s3)")" = healthy ]; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q rabbitmq)")" = healthy ]; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
docker compose start api lb reconciler relay worker
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Запускает остановленные stop-one.sh API-реплики и ждёт их готовности.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose start api >/dev/null
|
||||
deadline=$(( $(date +%s) + 60 ))
|
||||
while :; do
|
||||
bad=0
|
||||
for cid in $(docker compose ps -aq api); do
|
||||
st=$(docker inspect -f '{{.State.Health.Status}}' "$cid")
|
||||
[ "$st" = healthy ] || bad=1
|
||||
done
|
||||
[ $bad -eq 0 ] && break
|
||||
[ "$(date +%s)" -lt $deadline ] || { echo "api replicas not healthy in 60s" >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
docker compose ps api --format '{{.Name}} {{.Status}}'
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Поочерёдная замена API-реплик без остановки сервиса (Compose).
|
||||
# Для каждой старой реплики: поднять одну новую → дождаться healthy (LB сам
|
||||
# найдёт её через DNS) → остановить старую (drain) → удалить.
|
||||
# Миграции выполняются ДО замены отдельным сервисом migrate и должны быть
|
||||
# совместимы со старой версией (expand → contract).
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose build api
|
||||
docker compose run --rm migrate >/dev/null
|
||||
|
||||
wait_healthy() {
|
||||
want=$1; deadline=$(( $(date +%s) + 90 ))
|
||||
while :; do
|
||||
n=0
|
||||
# Своё имя переменной: в sh у функций общая область видимости, и `cid`
|
||||
# перезаписал бы переменную внешнего цикла (тогда удалялась бы новая реплика).
|
||||
for c in $(docker compose ps -q api); do
|
||||
[ "$(docker inspect -f '{{.State.Health.Status}}' "$c")" = healthy ] && n=$((n+1))
|
||||
done
|
||||
[ $n -ge "$want" ] && return 0
|
||||
[ "$(date +%s)" -lt $deadline ] || { echo "new replica not healthy in 90s" >&2; return 1; }
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
old=$(docker compose ps -q api)
|
||||
for cid in $old; do
|
||||
cur=$(docker compose ps -q api | wc -l | tr -d ' ')
|
||||
docker compose up -d --no-deps --no-recreate --scale api=$((cur + 1)) api
|
||||
wait_healthy $((cur + 1))
|
||||
name=$(docker inspect -f '{{.Name}}' "$cid")
|
||||
docker stop -t 15 "$cid" >/dev/null
|
||||
docker rm "$cid" >/dev/null
|
||||
echo "replaced $name"
|
||||
done
|
||||
docker compose ps api --format '{{.Name}} {{.ID}} {{.Image}} {{.Status}}'
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Останавливает ОДНУ API-реплику, чей X-Instance-Id передан в TARGET_INSTANCE_ID,
|
||||
# и оставляет её остановленной. X-Instance-Id = hostname контейнера = префикс его ID.
|
||||
# БД, Redis, LB и volumes не трогаются. Восстановление: scripts/restore.sh.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!0-9a-f]*) echo "unexpected instance id format" >&2; exit 2 ;;
|
||||
esac
|
||||
[ ${#TARGET_INSTANCE_ID} -ge 12 ] || { echo "instance id too short" >&2; exit 2; }
|
||||
for cid in $(docker compose ps -q api); do
|
||||
case "$cid" in
|
||||
"$TARGET_INSTANCE_ID"*)
|
||||
name=$(docker inspect -f '{{.Name}}' "$cid")
|
||||
# SIGTERM → API отвечает 503 на /health/ready (DRAIN_DELAY), LB исключает её,
|
||||
# затем http.Server.Shutdown дожидается текущих запросов.
|
||||
docker stop -t 15 "$cid" >/dev/null
|
||||
echo "stopped $name ($TARGET_INSTANCE_ID)"
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
done
|
||||
echo "no running api container matches $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
rem Windows wrapper: Python subprocess cannot exec .sh directly (WinError 193).
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0..\restart.sh" %*
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
rem Windows wrapper: Python subprocess cannot exec .sh directly (WinError 193).
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0..\restore.sh" %*
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
rem Windows wrapper: Python subprocess cannot exec .sh directly (WinError 193).
|
||||
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0..\stop-one.sh" %*
|
||||
Reference in New Issue
Block a user