Добавил защиту сервисов

This commit is contained in:
Югай Артур Рустамович
2026-12-02 19:04:51 +03:00
parent 20afc2c790
commit e260e84e4e
78 changed files with 12473 additions and 91 deletions
+293
View File
@@ -0,0 +1,293 @@
name: mtusi-lab6
x-app: &app
image: mtusi-messenger:lab6
build: .
environment: &environment
APP_HOST: 0.0.0.0
APP_PORT: 8080
APP_ENV: lab
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
SERVICE_VERSION: ${SERVICE_VERSION:-lab6}
DATABASE_URL_FILE: /run/secrets/database_url
CURSOR_SECRET_FILE: /run/secrets/cursor_key
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
S3_ENDPOINT: http://s3:9000
S3_REGION: us-east-1
S3_BUCKET: ${S3_BUCKET:-messenger-lab6-attachments}
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
BROKER_URL_FILE: /run/secrets/broker_url
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
secrets:
- database_url
- cursor_key
- broker_url
- s3_access_key_id
- s3_secret_access_key
stop_grace_period: 20s
services:
db:
image: postgres:17.11-bookworm@sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994
environment:
POSTGRES_USER: messenger
POSTGRES_DB: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
secrets:
- postgres_password
volumes:
- pgdata:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 2s
timeout: 3s
retries: 30
stop_grace_period: 10s
s3-storage:
image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15
command: ["server", "-filer", "-dir=/data", "-ip=s3-storage", "-ip.bind=0.0.0.0",
"-master.volumeSizeLimitMB=128", "-volume.max=64", "-master.electionTimeout=1s",
"-master.heartbeatInterval=100ms"]
volumes:
- s3data:/data
networks:
- storage
healthcheck:
test: ["CMD-SHELL", "wget -q -O - http://127.0.0.1:9333/cluster/status | grep -q '\"IsLeader\":true'"]
interval: 2s
timeout: 2s
retries: 45
stop_grace_period: 10s
s3:
image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15
command: ["s3", "-filer=s3-storage:8888", "-port=9000", "-ip.bind=0.0.0.0",
"-config=/run/secrets/s3_config", "-iam=false", "-port.iceberg=0", "-port.lance=0"]
secrets:
- s3_config
networks:
- default
- storage
depends_on:
s3-storage:
condition: service_healthy
stop_grace_period: 3s
migrate:
<<: *app
command: ["python", "-m", "src.migrate"]
secrets:
- database_url
healthcheck:
disable: true
depends_on:
db:
condition: service_healthy
bootstrap:
<<: *app
command: ["python", "-m", "src.bootstrap"]
environment:
<<: *environment
S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id
S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key
secrets:
- s3_access_key_id
- s3_secret_access_key
- s3_admin_access_key_id
- s3_admin_secret_access_key
healthcheck:
disable: true
depends_on:
s3:
condition: service_started
broker:
image: rabbitmq:4.4.1-management@sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677
hostname: broker
environment:
RABBITMQ_CONFIG_FILE: /run/secrets/rabbitmq
RABBITMQ_NODENAME: rabbit@broker
secrets:
- source: rabbitmq_config
target: rabbitmq.conf
volumes:
- brokerdata:/var/lib/rabbitmq
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 3s
timeout: 5s
retries: 40
stop_grace_period: 10s
worker:
<<: *app
command: ["python", "-m", "src.worker"]
mem_limit: 768m
restart: unless-stopped
healthcheck:
disable: true
depends_on:
broker:
condition: service_healthy
migrate:
condition: service_completed_successfully
bootstrap:
condition: service_completed_successfully
api1: &api
<<: *app
mem_limit: 768m
depends_on:
broker:
condition: service_healthy
db:
condition: service_healthy
migrate:
condition: service_completed_successfully
bootstrap:
condition: service_completed_successfully
api2:
<<: *api
cleanup:
<<: *app
command: ["python", "-m", "src.cleanup"]
restart: unless-stopped
healthcheck:
disable: true
depends_on:
migrate:
condition: service_completed_successfully
bootstrap:
condition: service_completed_successfully
lb:
image: haproxy:3.2.26@sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953
ports:
- "127.0.0.1:${HTTP_PORT:-8080}:8080"
volumes:
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
depends_on:
api1:
condition: service_started
api2:
condition: service_started
stop_grace_period: 3s
otel-collector:
image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea
command: ["--config=/etc/otel/collector.yaml"]
volumes:
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
mem_limit: 256m
restart: unless-stopped
depends_on:
- loki
- tempo
stop_grace_period: 10s
prometheus:
image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06
command: ["--config.file=/etc/prometheus/prometheus.yaml", "--storage.tsdb.path=/prometheus",
"--storage.tsdb.retention.time=24h", "--storage.tsdb.retention.size=1GB"]
volumes:
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
- prometheusdata:/prometheus
mem_limit: 512m
restart: unless-stopped
stop_grace_period: 15s
loki:
image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7
command: ["-config.file=/etc/loki/loki.yaml"]
volumes:
- ./infra/otel/loki.yaml:/etc/loki/loki.yaml:ro
- lokidata:/loki
mem_limit: 512m
restart: unless-stopped
stop_grace_period: 15s
tempo:
image: grafana/tempo:3.1.1@sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044
command: ["-config.file=/etc/tempo/tempo.yaml"]
volumes:
- ./infra/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro
- tempodata:/var/tempo
mem_limit: 768m
restart: unless-stopped
stop_grace_period: 15s
grafana:
image: grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf
environment:
GF_SECURITY_ADMIN_USER: admin
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password
GF_USERS_ALLOW_SIGN_UP: 'false'
GF_AUTH_ANONYMOUS_ENABLED: 'false'
GF_ANALYTICS_REPORTING_ENABLED: 'false'
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
ports:
- "127.0.0.1:${GRAFANA_PORT:-3306}:3000"
volumes:
- grafanadata:/var/lib/grafana
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
secrets:
- grafana_password
mem_limit: 384m
restart: unless-stopped
stop_grace_period: 10s
volumes:
pgdata:
s3data:
brokerdata:
prometheusdata:
lokidata:
tempodata:
grafanadata:
networks:
default:
ipam:
config:
- subnet: ${LAB6_APP_SUBNET:-10.240.60.0/24}
storage:
internal: true
ipam:
config:
- subnet: ${LAB6_STORAGE_SUBNET:-10.240.61.0/24}
secrets:
postgres_password:
file: ./secrets/postgres_password
database_url:
file: ./secrets/database_url
cursor_key:
file: ./secrets/cursor_key
s3_config:
file: ./secrets/s3_config.json
s3_access_key_id:
file: ./secrets/s3_access_key_id
s3_secret_access_key:
file: ./secrets/s3_secret_access_key
s3_admin_access_key_id:
file: ./secrets/s3_admin_access_key_id
s3_admin_secret_access_key:
file: ./secrets/s3_admin_secret_access_key
broker_url:
file: ./secrets/broker_url
rabbitmq_config:
file: ./secrets/rabbitmq.conf
grafana_password:
file: ./secrets/grafana_password
+270
View File
@@ -0,0 +1,270 @@
{
"uid": "messenger-lab6",
"title": "Мессенджер — ЛР7",
"schemaVersion": 39,
"version": 1,
"editable": false,
"refresh": "5s",
"timezone": "browser",
"time": {
"from": "now-15m",
"to": "now"
},
"tags": [
"lab7"
],
"templating": {
"list": [
{
"name": "service",
"label": "Сервис (логи/трассы)",
"type": "custom",
"query": "messenger-api,messenger-worker",
"multi": true,
"includeAll": true,
"allValue": ".*",
"current": {
"text": "All",
"value": "$__all"
}
},
{
"name": "instance",
"label": "API-реплика",
"type": "query",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"query": "label_values(messenger_http_requests_total,service_instance_id)",
"refresh": 2,
"multi": true,
"includeAll": true,
"allValue": ".*",
"current": {
"text": "All",
"value": "$__all"
}
}
]
},
"panels": [
{
"id": 1,
"title": "RPS API",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_instance_id) (rate(messenger_http_requests_total{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m]))",
"legendFormat": "{{service_instance_id}} {{outcome}}"
}
]
},
{
"id": 2,
"title": "Серверные ошибки, запросов/с",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\",service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])) or vector(0)",
"legendFormat": "{{service_instance_id}} {{outcome}}"
}
]
},
{
"id": 3,
"title": "Доля 5xx",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\",service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])), 0.000001)",
"legendFormat": "{{service_instance_id}} {{outcome}}"
}
]
},
{
"id": 4,
"title": "Время API, среднее",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_duration_seconds_sum{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])) / clamp_min(sum(rate(messenger_http_duration_seconds_count{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])), 0.000001)",
"legendFormat": "{{service_instance_id}} {{outcome}}"
}
]
},
{
"id": 5,
"title": "Попытки worker, всего",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (messenger_jobs_total)",
"legendFormat": "{{service_instance_id}} {{outcome}}"
}
]
},
{
"id": 6,
"title": "Время попытки worker, среднее",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_job_duration_seconds_sum[1m])) / clamp_min(sum by (outcome) (rate(messenger_job_duration_seconds_count[1m])), 0.000001)",
"legendFormat": "{{service_instance_id}} {{outcome}}"
}
]
},
{
"id": 7,
"title": "События API и worker",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 24,
"h": 10
},
"options": {
"showTime": true,
"showLabels": true,
"sortOrder": "Descending"
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"$service\"}"
}
]
},
{
"id": 8,
"title": "Трассы API и worker",
"type": "table",
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"gridPos": {
"x": 0,
"y": 34,
"w": 24,
"h": 10
},
"targets": [
{
"refId": "A",
"queryType": "traceql",
"query": "{ resource.service.name =~ \"$service\" }",
"limit": 20
}
]
}
]
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: ЛР7
type: file
disableDeletion: true
editable: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,39 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 5s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: Trace
matcherRegex: trace_id
matcherType: label
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: '-1m'
spanEndTimeShift: '1m'
filterByTraceID: true
tags:
- key: service.name
value: service_name
+48
View File
@@ -0,0 +1,48 @@
global
log stdout format raw local0
maxconn 256
defaults
mode http
log global
timeout connect 1s
timeout client 60s
timeout server 60s
timeout check 3s
retries 0
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API temporarily unavailable","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb
resolvers docker
nameserver local 127.0.0.11:53
resolve_retries 2
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold nx 1s
hold obsolete 1s
frontend public
bind :8443 ssl crt /run/server/bundle.pem ssl-min-ver TLSv1.2
unique-id-format %[uuid()]
stick-table type ip size 100k expire 10s store http_req_rate(1s)
http-request set-header X-Forwarded-For %[src]
http-request track-sc0 src if { path /api/v1/auth/sessions } METH_POST
http-request return status 429 content-type application/json lf-string '{"error":{"code":"rate_limited","message":"Too many logins","request_id":"%[unique-id]"}}' hdr Retry-After 1 hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb if { path /api/v1/auth/sessions } METH_POST { sc_http_req_rate(0) gt 20 }
use_backend api_live if { path /health/live }
default_backend api_ready
backend api_ready
balance roundrobin
option httpchk GET /health/ready
http-check expect status 200
default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
server first api1:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api1 sni str(api1) check-sni api1
server second api2:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api2 sni str(api2) check-sni api2
backend api_live
balance roundrobin
option httpchk GET /health/live
http-check expect status 200
default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
server first api1:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api1 sni str(api1) check-sni api1
server second api2:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api2 sni str(api2) check-sni api2
+63
View File
@@ -0,0 +1,63 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
queue_size: 128
num_consumers: 2
retry_on_failure:
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
otlp_grpc/tempo:
endpoint: tempo:4317
tls:
insecure: true
timeout: 2s
sending_queue:
queue_size: 128
num_consumers: 2
retry_on_failure:
initial_interval: 1s
max_interval: 5s
max_elapsed_time: 30s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
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: [otlp_grpc/tempo]
+45
View File
@@ -0,0 +1,45 @@
auth_enabled: false
server:
http_listen_port: 3100
common:
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
ingester:
wal:
enabled: true
dir: /loki/wal
limits_config:
allow_structured_metadata: true
retention_period: 24h
ingestion_rate_mb: 4
ingestion_burst_size_mb: 8
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes: [service.name, deployment.environment.name]
- action: structured_metadata
attributes: [service.version, service.instance.id]
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+7
View File
@@ -0,0 +1,7 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
scrape_configs:
- job_name: messenger
static_configs:
- targets: [otel-collector:8889]
+22
View File
@@ -0,0 +1,22 @@
target: all
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
overrides:
defaults:
compaction:
block_retention: 24h
usage_report:
reporting_enabled: false