Лабораторная 7

This commit is contained in:
MacBook
2026-11-24 12:20:21 +03:00
parent 20afc2c790
commit b962fa0d5d
99 changed files with 11329 additions and 107 deletions
+16
View File
@@ -0,0 +1,16 @@
# Build MinIO from a pinned commit of the official upstream source.
FROM golang:1.26.11-alpine3.23@sha256:23f198931d4bd83b4f5a613bd75656257ae8bf832dcbc2db80e1050b5219ca2a AS build
ADD --checksum=sha256:be6d0bd3696c3a13a35f02d3a0280b64319c67918b4501c5c3d87f96d000085c https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-10-15T17-29-55Z /source.tar.gz
WORKDIR /src
RUN tar -xzf /source.tar.gz --strip-components=1 -C /src
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 GOMAXPROCS=2 go build -p 2 -trimpath -buildvcs=false \
-ldflags='-s -w -X github.com/minio/minio/cmd.Version=2025-10-15T17:29:55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z -X github.com/minio/minio/cmd.CommitID=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a -X github.com/minio/minio/cmd.CopyrightYear=2025' \
-o /minio .
FROM busybox:1.37.0-musl
COPY --from=build /minio /minio
COPY --from=build /src/LICENSE /licenses/MinIO-LICENSE
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
RUN mkdir -p /data
ENTRYPOINT ["/minio"]
+8
View File
@@ -0,0 +1,8 @@
FROM application AS app_binary
FROM python:3.13.16-slim-bookworm@sha256:73aa5faee130c60da030e105ec971ccf57473fbd22ce73bd6fc9ba99a40b838d
RUN pip install --no-cache-dir Pillow==13.0.0
COPY --from=app_binary /messenger /messenger
COPY worker/process_image.py /opt/process_image.py
USER 65532:65532
ENTRYPOINT ["/messenger"]
CMD ["worker"]
+43
View File
@@ -0,0 +1,43 @@
#!/bin/sh
set -eu
upstream=/run/nginx-upstream.conf
write_servers() {
if [ "$1" = 1 ]; then
printf '%s\n' 'server api1:8080 resolve max_fails=0;'
fi
if [ "$2" = 1 ]; then
printf '%s\n' 'server api2:8080 resolve max_fails=0;'
fi
}
# With no healthy replica, keep both reachable so API can return its normal
# 401/503 JSON responses instead of Nginx reporting "no live upstreams".
write_servers 1 1 > "$upstream"
monitor() {
sleep 2
while :; do
ready1=0
ready2=0
curl -fsS --max-time 2 --cacert /run/ca/ca.crt --cert /run/tls/cert.crt --key /run/tls/key.key -o /dev/null https://api1:8080/health/ready && ready1=1 || true
curl -fsS --max-time 2 --cacert /run/ca/ca.crt --cert /run/tls/cert.crt --key /run/tls/key.key -o /dev/null https://api2:8080/health/ready && ready2=1 || true
if [ "$ready1" = 0 ] && [ "$ready2" = 0 ]; then
ready1=1
ready2=1
fi
next=$(mktemp /run/nginx-upstream.XXXXXX)
write_servers "$ready1" "$ready2" > "$next"
if cmp -s "$next" "$upstream"; then
rm -f "$next"
else
mv "$next" "$upstream"
nginx -t >/dev/null 2>&1 && nginx -s reload
fi
sleep 1
done
}
monitor &
exec nginx -g 'daemon off;'
+46
View File
@@ -0,0 +1,46 @@
pid /run/nginx.pid;
events {}
http {
access_log /dev/stdout;
error_log /dev/stderr notice;
resolver 127.0.0.11 valid=2s ipv6=off;
upstream messenger_api {
zone messenger_api 64k;
include /run/nginx-upstream.conf;
keepalive 16;
}
server {
listen 8443 ssl;
ssl_certificate /run/tls/cert.crt;
ssl_certificate_key /run/tls/key.key;
ssl_protocols TLSv1.2 TLSv1.3;
add_header Strict-Transport-Security "max-age=86400" always;
client_max_body_size 0;
client_body_timeout 20s;
location / {
proxy_request_buffering off;
proxy_buffering off;
proxy_pass https://messenger_api;
proxy_ssl_verify on;
proxy_ssl_trusted_certificate /run/ca/ca.crt;
proxy_ssl_server_name on;
proxy_ssl_name messenger-api;
proxy_ssl_certificate /run/tls/cert.crt;
proxy_ssl_certificate_key /run/tls/key.key;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 500ms;
proxy_send_timeout 65s;
proxy_read_timeout 65s;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
}
+7 -6
View File
@@ -1,7 +1,8 @@
# Конфигурация наблюдаемости — реализовать
# Observability retained from lab6
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Collector/Prometheus/Loki/Tempo/Grafana provisioning and dashboard remain in this
directory. Lab7 changes transport: TLS sidecars isolate native loopback listeners;
application OTLP, exporter, scrape and datasource connections verify CA/hostname
and service identities. See `contracts/trust-matrix.md` and `infra/security/`.
Grafana is HTTPS localhost13007, password is local secret. No insecure TLS flags.
Signals and alert/runbook semantics remain documented in signals.md/runbook.md.
+23
View File
@@ -0,0 +1,23 @@
groups:
- name: messenger-slo
rules:
- record: messenger:api_error_ratio:rate1m
expr: (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[1m])), 0.001)
- record: messenger:api_availability:rate5m
expr: 1 - (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[5m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[5m])), 0.001)
- alert: MessengerHighErrorRate
expr: messenger:api_error_ratio:rate1m > 0.05
for: 10s
labels:
severity: warning
annotations:
summary: Business API 5xx ratio exceeds 5% over 1 minute
description: Inspect database spans, DB availability and pool panels; see infra/otel/runbook.md.
- alert: MessengerQueueLag
expr: max(messenger_queue_oldest_age_seconds) > 10 and max(messenger_queue_depth) > 0
for: 10s
labels:
severity: warning
annotations:
summary: Oldest queued job exceeds 10 seconds
description: Compare worker busy/capacity, job outcomes and queue age; see infra/otel/runbook.md.
+82
View File
@@ -0,0 +1,82 @@
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 64
send_batch_max_size: 128
exporters:
prometheus:
endpoint: 127.0.0.1:18889
resource_to_telemetry_conversion:
enabled: true
otlphttp/tempo:
endpoint: https://tempo:4318
timeout: 2s
tls:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
sending_queue:
enabled: true
num_consumers: 2
queue_size: 32
block_on_overflow: false
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 5s
otlphttp/loki:
endpoint: https://loki:3100/otlp
timeout: 2s
tls:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
sending_queue:
enabled: true
num_consumers: 2
queue_size: 32
block_on_overflow: false
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 5s
extensions:
health_check:
endpoint: 127.0.0.1:13133
service:
extensions: [health_check]
telemetry:
logs:
encoding: json
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 18888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
@@ -0,0 +1,669 @@
{
"uid": "mtusi-messenger",
"title": "MTUSI Messenger — lab7",
"schemaVersion": 39,
"version": 1,
"refresh": "5s",
"tags": [
"mtusi",
"lab7"
],
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "API RPS (business routes)",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_instance_id) (rate(messenger_http_requests_total{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m]))",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
}
},
{
"id": 2,
"title": "Business API error ratio: 5xx / all",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger:api_error_ratio:rate1m",
"legendFormat": "5xx ratio"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 3,
"title": "API p50 from histogram",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
"legendFormat": "p50"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 4,
"title": "API p95 from histogram",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 5,
"title": "API p99 from histogram",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name=\"messenger-api\",route!~\"/health/.*\"}[1m])))",
"legendFormat": "p99"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 6,
"title": "Worker job outcomes",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 7,
"title": "Worker p95 processing duration",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 8,
"title": "End-to-end p95 time to ready",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))",
"legendFormat": "p95"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 9,
"title": "Queue depth",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_depth)",
"legendFormat": "queued"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 10,
"title": "Oldest queued job age",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "max(messenger_queue_oldest_age_seconds)",
"legendFormat": "oldest"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
},
{
"id": 11,
"title": "DB pool used / waiting",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_pool_used",
"legendFormat": "used {{service_instance_id}}"
},
{
"refId": "B",
"expr": "messenger_db_pool_waiting",
"legendFormat": "waiting {{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 12,
"title": "DB pool wait rate",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_instance_id) (rate(messenger_db_pool_acquire_wait_total[1m]))",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
}
},
{
"id": 13,
"title": "Worker saturation: busy / capacity",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_worker_busy / messenger_worker_capacity",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 14,
"title": "Worker capacity",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_worker_capacity",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 15,
"title": "Container CPU time rate (includes decoder)",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "rate(messenger_container_cpu_seconds_total[1m])",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "cores"
},
"overrides": []
}
},
{
"id": 16,
"title": "Container memory",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_container_memory_bytes",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
}
},
{
"id": 17,
"title": "Database available",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_available",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 18,
"title": "SLI availability, rolling 5m (SLO 99%)",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger:api_availability:rate5m",
"legendFormat": "availability"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
}
},
{
"id": 19,
"title": "Local alert states",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 72,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"Messenger.*\"}",
"legendFormat": "{{alertname}} {{alertstate}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 20,
"title": "Collector queued export batches",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 72,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "{{exporter}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 21,
"title": "Collector failed trace exports",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 80,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_send_failed_spans_total",
"legendFormat": "{{exporter}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 22,
"title": "SDK exporter errors",
"type": "timeseries",
"gridPos": {
"x": 12,
"y": 80,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "messenger_telemetry_export_errors",
"legendFormat": "{{service_instance_id}}"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
}
},
{
"id": 23,
"title": "Worker heartbeat age (stale if stopped)",
"type": "timeseries",
"gridPos": {
"x": 0,
"y": 88,
"w": 12,
"h": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"targets": [
{
"refId": "A",
"expr": "time() - messenger_process_last_observed_seconds{service_name=\"messenger-worker\"}",
"legendFormat": "worker heartbeat age"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
}
}
],
"annotations": {
"list": []
}
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: Messenger
orgId: 1
folder: MTUSI
type: file
disableDeletion: false
editable: false
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,55 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: $TLS_CA_PEM
tlsClientCert: $TLS_CERT_PEM
tlsClientKey: $TLS_KEY_PEM
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: $${__value.raw}
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: $TLS_CA_PEM
tlsClientCert: $TLS_CERT_PEM
tlsClientKey: $TLS_KEY_PEM
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
filterByTraceID: true
filterBySpanID: false
serviceMap:
datasourceUid: prometheus
tlsAuth: true
tlsAuthWithCACert: true
secureJsonData:
tlsCACert: $TLS_CA_PEM
tlsClientCert: $TLS_CERT_PEM
tlsClientKey: $TLS_KEY_PEM
+32
View File
@@ -0,0 +1,32 @@
auth_enabled: false
server:
http_listen_address: 127.0.0.1
http_listen_port: 13100
grpc_listen_address: 127.0.0.1
common:
instance_addr: 127.0.0.1
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 24h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
+24
View File
@@ -0,0 +1,24 @@
global:
scrape_interval: 3s
evaluation_interval: 5s
rule_files:
- /etc/prometheus/alerts.yaml
scrape_configs:
- job_name: messenger
static_configs:
- targets:
- otel-collector:8889
scheme: https
tls_config:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
- job_name: collector
static_configs:
- targets:
- otel-collector:8888
scheme: https
tls_config:
ca_file: /run/ca/ca.crt
cert_file: /run/tls/cert.crt
key_file: /run/tls/key.key
+42
View File
@@ -0,0 +1,42 @@
# Локальная диагностика
Открыть Grafana → MTUSI → **MTUSI Messenger — lab7**. В Explore доступны Prometheus, Loki и Tempo. Пароль admin хранится локально в `secrets/grafana_admin_password`, в Git его нет.
## MessengerQueueLag
Условие: oldest queued job > 10 s при depth > 0 в течение 10 s. Интервал оценки — 5 s, scrape — 3 s.
1. Посмотреть Queue depth и Oldest queued job age: растут ли они вместе.
2. Посмотреть Worker heartbeat age и busy/capacity. Старый heartbeat при busy=0 означает отсутствие свежих наблюдений worker, а не доказательство его здоровья.
3. Найти `job.published` в Loki и trace upload в Tempo. Если producer есть, а нового consumer нет, искать недоступный worker/доставку. Если consumer есть с error, посмотреть его S3/DB child spans.
4. После устранения причины наблюдать jobs outcome=success, снижение depth/age, свежий heartbeat и resolved (alert исчезает из активных).
Для демонстрации: `docker compose --env-file .env stop worker`, загрузить изображение; восстановить `docker compose --env-file .env start worker`. Проверки автоматизированы в `student-tests/verify_incidents.py`.
## MessengerHighErrorRate
Условие: 5xx / все бизнес-запросы > 5% за 1 минуту в течение 10 s. Health исключены. Ошибки клиента 400/401/404 не входят в числитель.
1. Посмотреть Business API error ratio и API percentiles.
2. По `X-Trace-Id` ответа открыть trace в Tempo. В Loki фильтровать `trace_id` или `request_id`.
3. Для отказа PostgreSQL видны error spans `db.pool.acquire`/`db.select`, `messenger_db_available=0` и ожидание пула. Длительность HTTP без DB error сама по себе не доказывает отказ БД.
4. Восстановить PostgreSQL. Проверить успешные запросы, DB availability=1 и падение error ratio в движущемся окне. Resolved может наступить после обновления окна и нескольких scrape/evaluation.
## Tempo недоступен
1. API продолжает записи; проверить бизнес-операцию, а не только `/health/live`.
2. В Prometheus посмотреть `otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"}` и `otelcol_exporter_queue_size`.
3. Collector queue ограничена 32 batch requests, retry — 5 s; SDK queue — 256 spans/log records, exporter timeout — 2 s. Ожидание backend не переносится в HTTP handler.
4. При переполнении/исчерпании retry данные telemetry могут быть потеряны. В JSON-логах Collector финальная потеря содержит `dropped_items`. Счётчик failed sends не следует считать числом уникальных потерянных трасс.
5. После восстановления проверить свежий trace. Старые потерянные spans автоматически не восстанавливаются из бизнес-БД.
## SLI/SLO
SLI: доля бизнес HTTP-запросов без 5xx за скользящие **5 минут**. SLO: **≥99%**.
```promql
1 - (sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*",status_class="5xx"}[5m])) or vector(0))
/ clamp_min(sum(rate(messenger_http_requests_total{service_name="messenger-api",route!~"/health/.*"}[5m])), 0.001)
```
SLO оценивается на окне с реальным трафиком; при отсутствии запросов правило не должно порождать ошибку деления. Alert использует более короткое 1m окно и порог 5% для локальной диагностики. Это не burn-rate исследование оценки 5.
+53
View File
@@ -0,0 +1,53 @@
# Схема сигналов v1
SDK: OpenTelemetry Go traces/metrics **1.47.0**, logs API/SDK **1.47.0**, log exporter **0.23.0**. Resource schema URL — OTel semantic conventions **1.37.0**; прикладные имена и labels ниже зафиксированы собственной схемой `mtusi-messenger/telemetry-v1`.
Resources: `service.name` = messenger-api / messenger-worker / messenger-dispatcher; `service.version=lab6-v1` (версия перенесённой business instrumentation; deployment lab7 использует TLS), `service.instance.id` = api-1/api-2/worker-1/dispatcher-1, `deployment.environment.name=lab`. Collector превращает resource attrs в Prometheus labels, например service_name.
| Prometheus metric | Тип, единица | Labels |
|---|---|---|
| messenger_http_requests_total | counter, requests | method, route template, status_class |
| messenger_http_duration_seconds_bucket/count/sum | histogram, seconds | те же |
| messenger_jobs_processed_total | counter, attempts | job_type, outcome |
| messenger_job_duration_seconds_bucket/count/sum | histogram, seconds | job_type, outcome |
| messenger_time_to_ready_seconds_bucket/count/sum | histogram, seconds | job_type |
| messenger_queue_depth | gauge, jobs | queue; только dispatcher |
| messenger_queue_oldest_age_seconds | gauge, seconds | queue; только dispatcher |
| messenger_db_pool_used/idle/waiting/capacity | gauge, connections/acquires | resource instance |
| messenger_db_pool_acquire_wait_total | counter, empty pool acquires | resource instance |
| messenger_db_pool_acquire_wait_duration_seconds_total | counter, cumulative seconds | resource instance |
| messenger_worker_busy/capacity | gauge, attempts/slots | worker instance |
| messenger_process_cpu_seconds_total | counter, Go process CPU seconds | instance |
| messenger_container_cpu_seconds_total | counter, cgroup CPU seconds including decoder | instance |
| messenger_process_memory_bytes | gauge, Go runtime reserved memory (Sys), не RSS | instance |
| messenger_container_memory_bytes/limit_bytes | gauge, cgroup bytes | instance |
| messenger_process_last_observed_seconds | gauge, Unix timestamp | instance |
| messenger_db_available | gauge, 0/1 | dispatcher |
| messenger_telemetry_export_errors | gauge, cumulative SDK export errors | instance |
`waiting` — незавершённые Acquire; EmptyAcquire counter показывает обращения к пустому пулу. Busy/capacity — текущая занятость обработчиков, а не CPU%. E2E время измерено от created_at job в транзакции durable acceptance до COMMIT ready, включает queue wait и retry. Replay использует исходное время принятия.
Percentiles вычисляются объединением histogram buckets реплик:
```promql
histogram_quantile(0.95,
sum by (le) (rate(messenger_http_duration_seconds_bucket{service_name="messenger-api",route!~"/health/.*"}[1m])))
```
p50 и p99 используют 0.50 и 0.99. Единицы всех duration panels — секунды. Суммируются buckets, не percentiles отдельных реплик. Полные исполняемые запросы находятся в `grafana/dashboards/messenger.json`.
## Логи и трассы
API log event `http.request`: timestamp, severity, service.name, method, route template, status, duration_ms, request_id, trace_id, span_id. Worker — `job.started`, `job.completed`; dispatcher — `job.published`.
Технические request_id/job_id допустимы только в логах/трассах для корреляции синтетических работ. В labels метрик они отсутствуют. SQL text/args, URL/query, filename, headers Authorization, пароли, токены, текст сообщения и содержимое файлов не записываются.
HTTP server span принимает W3C traceparent/tracestate. Upload транзакционно сохраняет их в job. Producer span публикует свой контекст в разрешённых полях JSON брокера; consumer span извлекает его как parent. Повторы образуют новые producer/consumer ветки того же trace. S3, Redis sessions, DB acquire/query/commit и image.process имеют реальные дочерние spans.
Log body — структурный JSON, дополнительно отправляемый OTLP Log SDK с trace/span context. В Grafana Loki TraceID derived field открывает Tempo; поиск по trace_id показывает связанные события. Заголовок X-Trace-Id добавлен для диагностики; X-Request-Id и бизнес-контракт сохранены.
## Буферизация
SDK: batch queue 256, batch 64, export interval 500 ms, exporter timeout 2 s, retry SDK выключен; metrics interval 2 s. Collector: memory limiter 128 MiB со spike 32 MiB, hard limit контейнера 256 MiB; batch size 64/max128; по 32 batches и 2 consumers для traces/logs, неблокирующее переполнение, retry deadline 5 s. Метрики предоставляются ограниченным набором series на pull endpoint Collector; Prometheus хранит историю в volume. Retention storage — 24 h.
При отказе telemetry допускаются потери signals. Ошибки SDK учитываются отдельно; Collector показывает failed exports/queue, а финальные drops записывает с dropped_items. Business transaction от успешности экспорта не зависит.
+24
View File
@@ -0,0 +1,24 @@
server:
http_listen_address: 127.0.0.1
http_listen_port: 13200
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
grpc:
endpoint: 127.0.0.1:14317
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 24h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
+2
View File
@@ -0,0 +1,2 @@
FROM nginx:1.29.1-alpine3.22
RUN apk add --no-cache curl
+4
View File
@@ -0,0 +1,4 @@
FROM python:3.13.16-slim-bookworm@sha256:73aa5faee130c60da030e105ec971ccf57473fbd22ce73bd6fc9ba99a40b838d
COPY infra/security/tls_proxy.py /tls_proxy.py
USER 65532:65532
ENTRYPOINT ["python3","/tls_proxy.py"]
+65
View File
@@ -0,0 +1,65 @@
# Security boundary
TLS roots are generated by the operator in `secrets/operator/ca.key` (never mounted
in services). Each service receives only its leaf directory plus the public CA.
Leaf lifetime: 7 days. Root lifetime: 365 days. Keys are generated, never in Git
or images. `scripts/pki.py` is idempotent; it does not silently replace a CA.
The native backend processes Redis/MinIO/Collector/Prometheus/Loki/Tempo share
only their corresponding TLS-sidecar network namespace (`network_mode:
service:tls-...`). They bind plaintext listeners to 127.0.0.1 on distinct ports.
Only the sidecar binds the network-facing port. No plaintext port is published.
The proxy verifies client CA, expiry, DNS SAN allowlist and serial denylist on
EVERY new connection. It disables tickets and reloads leaf files per connection.
For broker it additionally parses bounded RESP frames, binds AUTH/HELLO username
to the certificate SAN, and restricts consumer XADD to the invalid-envelope DLQ;
Redis independently enforces producer/consumer command/key ACLs.
A connection can stay alive until its finite 75s socket timeout; certificate
rotation restarts the affected caller to drain its old connections. Denylist
checks refer to NEW connections. No claim of revoking already completed actions.
PostgreSQL uses native TLS and verify-full URLs; separate API/worker/dispatcher/
cleanup database roles. Only the operator migration identity owns schema. API
must read password hashes to authenticate; worker cannot read users. S3 policies
separate API staging writes from worker originals/variants writes. MinIO admin
credentials exist only at the server and one-shot operator bootstrap.
OpenBao uses native TLS, non-dev persistent file storage, cert auth bound to exact
leaf certificates and a read-only policy for each KV path. Tokens: TTL60s/max120s.
Services reauthenticate every20s; this is renewal by scoped reauthentication,
not use of a permanent bootstrap token. Revocation replaces exact cert bindings.
If refresh fails, the last granted lease remains valid only until its deadline;
API then returns contract 503 (liveness stays up), workers exit75 and restart
fail-closed until authority recovery. Secrets are loaded only from Bao; no file
or plaintext fallback. Secret rotation restarts only the affected process/pool,
without building an image. Bootstrap and renewal remain explicit operator tasks.
## Operator commands
```sh
sh scripts/start.sh
python3 scripts/bao-operator.py seal
python3 scripts/bao-operator.py unseal
python3 scripts/rotate-db-secret.py
python3 scripts/rotate-leaf.py worker
```
The operator owns `secrets/operator/bao-init.json`, root token and unseal share;
file mode0600 under mode0700 directory. Neither OpenBao nor apps mount this
operator directory. One-share Shamir is a local teaching compromise; production
requires separated custodians / protected auto-unseal. Restart hook explicitly
runs as operator and unseals using LOCAL operator material; it is not server-side
unattended unseal. Keep an offline protected backup; losing it can make Bao data
unrecoverable. Never delete volumes to recover a forgotten unseal key.
App/worker are non-root; read-only root filesystems, no-new-privileges and
cap_drop ALL apply to runtime services. Writable volumes contain state, bounded
tmpfs contains temporary processing data. One-shot volume ownership init uses
only CHOWN, no network; this is the documented exception, not application power.
Docker socket/host network/privileged mode are absent. Operator audit is a profile,
not a production service, and explicitly mounts audit leaf material read-only.
Runtime secret bind files have mode0444 inside mounts so non-root Linux UIDs can read them. The enclosing host secrets directory stays0700; operator CA key/root token/unseal file stay0600 and are never runtime mounts. Each container receives only its own named files/leaf directory.
Redis sessions: отдельный user api ограничен session:*/login:* и GET/SET/DEL/INCR/EXPIRE/EVAL; CONFIG/FLUSHALL/чужие prefixes не разрешены. Operator health/expiry использует отдельную identity.
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
export PGPASSWORD="$(cat /run/secrets/postgres_password)"
exec psql -X -v ON_ERROR_STOP=1 -h postgres -U messenger -d messenger -f /bootstrap/db-grants.sql
+10
View File
@@ -0,0 +1,10 @@
ui = false
storage "file" { path = "/bao/data" }
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/tls/cert.crt"
tls_key_file = "/run/tls/key.key"
tls_client_ca_file = "/run/ca/ca.crt"
tls_min_version = "tls12"
}
api_addr = "https://openbao:8200"
+3
View File
@@ -0,0 +1,3 @@
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
+3
View File
@@ -0,0 +1,3 @@
path "secret/api1" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/api2" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/cleanup" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/dispatcher" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/migrate" {
capabilities = ["read"]
}
+3
View File
@@ -0,0 +1,3 @@
path "secret/worker" {
capabilities = ["read"]
}
+39
View File
@@ -0,0 +1,39 @@
# Разбор результатов сканирования зависимостей и образов — 23 ноября 2026
Повторный запуск: `python3 scripts/scan.py` после сборки образов. Trivy 0.76.2
проверяет сохранённые Docker-архивы, без доступа к Docker socket. Govulncheck 1.1.4
использует Go 1.26.11 — ту же версию, что и сборка приложения.
Сводка находится в `evidence/scan-summary.json`.
Проверены исполняемый файл приложения, ОС, Python и зависимости образа worker.
Это не проверка каждого инфраструктурного образа и не доказательство полного
отсутствия уязвимостей.
Перед итоговым сканированием обновлены:
- Go 1.26.8 → 1.26.11: исправления X509/TLS/HTTP;
- Python 3.13.7 → 3.13.16, Pillow 12 → 13;
- pgx 5.7.6 → 5.13.0, OpenTelemetry 1.38 → 1.47;
- x/crypto 0.42 → 0.59, x/net 0.43 → 0.63;
- grpc 1.75 → 1.85, jwt 4.5.0 → 4.5.2, compress 1.18 → 1.20.5.
Точные версии и digest закреплены в Dockerfile и зависимостях Go. После обновлений
выполнены регрессионные проверки бизнес-функций и TLS.
| Группа находок | Применимость и принятое решение |
|---|---|
| Уязвимости Go HTTP/TLS/X509, pgx и обработки изображений Pillow в перенесённой версии | Актуальны: эти компоненты обрабатывают сетевые запросы и недоверенные изображения. Установлены исправленные версии, образы пересобраны, тесты повторены. Внутренняя сеть сама по себе не считается исправлением. |
| GO-2026-5264/5381/5662/5710, модуль Prometheus через madmin | Приложение импортирует только `github.com/prometheus/prometheus/model/histogram`; это проверяется командой `go list -deps ./cmd/messenger`. Оно не подключает обработчики remote-read, config и веб-интерфейса Prometheus, не использует Azure OAuth remote-write. Указанный сканером `histogram.init` не доказывает достижимость уязвимых веб-обработчиков. Косвенная зависимость сохранена до совместимого обновления madmin. Этот вывод относится к исполняемому файлу приложения, а не к отдельному контейнеру Prometheus. |
| CVE-2023-45853, zlib/minizip | Описание относится к функции записи ZIP в minizip, а не к используемой распаковке PNG через zlib. Worker декодирует PNG/JPEG и кодирует JPEG/WebP; ZIP не создаётся, minizip не вызывается. Находка пакета Debian сохранена в результатах. |
| CVE-2025-7458, SQLite | Конвейер worker не открывает SQLite и не выполняет SQLite-запросы. Приложение использует PostgreSQL, обработка Pillow принимает PNG/JPEG. Пакет остаётся в базовом образе Python, но в проверяемом сценарии входные данные в SQLite не передаются. |
| certifi внутри pip, GHSA-6q48-6c7w-9gw2 | Во время работы приложение не использует requests/certifi для доверия внешним адресам: клиенты Go и Python явно доверяют локальному CA. Подпроцесс обработки не получает URL. Pip устанавливает закреплённый Pillow при сборке. Обновления базового образа и pip всё равно необходимы; находка не объявляется безопасной для любого использования. |
| Другие находки Debian: mount/PAM/systemd/apt и библиотеки | Применимость зависит от конкретного пути выполнения. Запрещены mount capabilities, повышение привилегий и установка пакетов во время работы; используются non-root, read-only rootfs и ограниченный подпроцесс. Находки высокой важности остаются в сводке. Для промышленного выпуска нужны дальнейшее сокращение/обновление образа и разбор отдельных уведомлений. Учебная изоляция не устраняет сами CVE. |
## Ограничения анализа
Базы сканеров обновляются, поэтому количество находок — снимок на дату проверки,
а не оценка безопасности в баллах. Изоляция уменьшает последствия, но не исправляет
достижимую ошибку нативного декодера.
Оставшиеся находки явно сохранены и объяснены с учётом выполняемых операций.
Полное отсутствие CVE и завершённая промышленная защита не заявляются.
+29
View File
@@ -0,0 +1,29 @@
# Модель угроз — лабораторная 7, оценка 4
**Защищаемые активы:** хеши паролей, Bearer-сессии, права доступа к чатам,
оригиналы/варианты/staging, целостность заданий, сервисные credentials, ключи PKI,
сохранённая телеметрия и состояние OpenBao.
**Участники:** анонимный клиент, авторизованный пользователь вне чата, клиент
с другим сертификатом доверенного CA, неисправный сервис, скомпрометированный
worker в пределах выданной роли и локальный оператор.
Компрометация хоста, root или самого оператора не покрывается этим учебным стендом.
| Конкретная угроза | Механизм защиты | Воспроизводимая отрицательная проверка |
|---|---|---|
| Перехват соединения (MITM) или подмена сервера | TLS с проверкой CA и hostname, без отключения верификации | `make test-security`; неверный hostname в `verify_security` |
| Обход балансировщика и прямой доступ к API | Порты реплик не опубликованы; mTLS и проверка SAN балансировщика; собственный сертификат API разрешён только для health | `verify_tls`: обе реплики отклоняют запросы без сертификата, с чужим CA и посторонним SAN |
| Клиент доверенного CA выдаёт себя за отправителя заданий | Список разрешённых SAN, разделение портов, привязка Redis AUTH и команд к identity, Redis ACL | `verify_tls`: worker не может выполнить XADD в поток заданий; посторонний клиент не допускается к broker |
| Посторонний сервис отправляет поддельную телеметрию | mTLS Collector с разрешёнными SAN, отдельные identities для сбора метрик | `verify_tls`: посторонний клиент не допускается к приёму данных; прямой локальный listener недоступен извне |
| Чтение чужих вложений или подмена пользовательского заголовка | Bearer-сессия, проверка участия в чате в БД, отсутствие публичных объектов S3 | `verify_security`: чужие metadata/content/upload недоступны, X-User-Id не меняет пользователя |
| Исчерпание CPU/RAM массовыми попытками входа | Argon2id 19 MiB/t2/p1; два параллельных хеширования на реплику; общий Redis-лимит 120 запросов/мин и 10 попыток/мин на username | `verify_security`: общий 429/Retry-After; измерение стоимости Argon2id |
| Worker читает секреты API или хеши паролей | Привязка OpenBao к точному сертификату и scoped policy, отдельная роль БД, ограниченные S3-prefixes | `verify_tls`: разрешения/запреты OpenBao; команда worker `security-audit` |
| Утечка или дальнейшее использование старой сервисной identity | Ограниченный срок сертификата/token, запрет старого serial, замена cert-auth binding, перезапуск пула соединений | `verify_lifecycle`: старые пароль и сертификат отклоняются на новых соединениях |
| Sealed OpenBao приводит к бессрочному использованию старых credentials | Срок lease; после истечения API возвращает 503, worker завершается; сетевые таймауты ограничены | `verify_lifecycle`: seal → истечение lease и 503 → восстановление после unseal |
| Вредоносное изображение исчерпывает ресурсы | Лимиты 10 MiB/40 млн пикселей, подпроцесс 1 GiB с таймаутом, worker CPU1/RAM1536 MiB/tmpfs128 MiB | `verify_variants` и проверки восстановления pipeline |
| Секреты попадают в логи или трассы | Безопасные поля событий, отсутствие SQL-аргументов/заголовков/тела запроса, шаблоны маршрутов в labels | `verify_observability`: поиск специально заданных секретных значений и проверка labels |
Не заявляется защита от злонамеренного оператора хоста, полной потери компьютера
или неограниченная доступность при массовой атаке на login. Общий лимит входа
осознанно ограничивает доступность авторизации ради ограничения дорогой работы.
+83
View File
@@ -0,0 +1,83 @@
"""Bounded mTLS TCP proxy. The backend shares this network namespace and
binds only loopback. Certificate chain AND DNS SAN role are mandatory.
Each new connection reloads leaf and denylist: no session resumption cache.
"""
import os, socket, ssl, threading, time, json
from pathlib import Path
ROLE=os.environ['PROXY_ROLE']
ALLOWED=set(os.environ['ALLOWED_IDENTITIES'].split(','))
PORTS=[tuple(map(int,p.split(':'))) for p in os.environ['PORT_MAP'].split(',')]
PER_PORT=json.loads(os.environ.get("PORT_IDENTITIES","{}"))
SLOTS=threading.BoundedSemaphore(64)
def serve(conn,upstream,port):
try:
conn.settimeout(5)
ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);ctx.minimum_version=ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain('/run/tls/cert.crt','/run/tls/key.key');ctx.load_verify_locations('/run/ca/ca.crt');ctx.verify_mode=ssl.CERT_REQUIRED
ctx.options |= ssl.OP_NO_TICKET
with ctx.wrap_socket(conn,server_side=True) as client:
cert=client.getpeercert();names={v for k,v in cert.get('subjectAltName',[]) if k=='DNS'}
revoked=Path('/run/ca/revoked-serials').read_text().lower().split()
if not names.intersection(set(PER_PORT.get(str(port),list(ALLOWED)))) or cert.get('serialNumber','').lower().lstrip('0') in [s.lstrip('0') for s in revoked]:return
principal=next(iter(names.intersection(set(PER_PORT.get(str(port),list(ALLOWED))))))
with socket.create_connection(('127.0.0.1',upstream),timeout=3) as backend:
client.settimeout(75);backend.settimeout(75)
# Two blocking directions; finite socket timeouts, bounded connections.
def copy(a,b):
try:
while True:
data=a.recv(32768)
if not data:break
b.sendall(data)
except (OSError,ssl.SSLError):pass
finally:
try:b.shutdown(socket.SHUT_WR)
except OSError:pass
def redis_commands():
try:
stream=client.makefile('rb')
while True:
header=stream.readline(128)
if not header:break
if not header.startswith(b'*'):break
count=int(header[1:]);args=[];wire=bytearray(header)
if not 1<=count<=64:break
for _ in range(count):
size=stream.readline(128)
if not size.startswith(b'$'):raise ValueError('invalid RESP')
n=int(size[1:])
if not 0<=n<=1048576:raise ValueError('oversized command')
value=stream.read(n+2)
if len(value)!=n+2:raise ValueError('truncated RESP')
args.append(value[:-2]);wire.extend(size);wire.extend(value)
op=args[0].lower()
allowed={b'ping',b'hello',b'auth',b'client'}
if principal=='worker':allowed|={b'xgroup',b'xautoclaim',b'xreadgroup',b'xack',b'xdel',b'xadd'}
if principal=='dispatcher':allowed|={b'xadd'}
if principal!='operator':
if op not in allowed:break
if op==b'auth' and (len(args)!=3 or args[1].decode()!=principal):break
if op==b'hello' and b'auth' in [a.lower() for a in args]:
i=[a.lower() for a in args].index(b'auth')
if args[i+1].decode()!=principal:break
if op==b'xadd':
expected=b'attachment.invalid.dlq' if principal=='worker' else b'attachment.jobs.v1'
if len(args)<2 or args[1]!=expected:break
backend.sendall(wire)
except (OSError,ValueError,IndexError,UnicodeError):pass
finally:
try:backend.shutdown(socket.SHUT_WR)
except OSError:pass
t=threading.Thread(target=redis_commands if ROLE=='broker' else copy,args=() if ROLE=='broker' else (client,backend),daemon=True)
t.start();copy(backend,client);t.join(timeout=1)
except (OSError,ssl.SSLError):conn.close()
finally:SLOTS.release()
def listen(port,upstream):
with socket.socket() as s:
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);s.bind(('0.0.0.0',port));s.listen(32)
while True:
conn,_=s.accept()
if not SLOTS.acquire(blocking=False):conn.close();continue
threading.Thread(target=serve,args=(conn,upstream,port),daemon=True).start()
for port,upstream in PORTS:threading.Thread(target=listen,args=(port,upstream),daemon=True).start()
while True:time.sleep(3600)