forked from mtusi2026/mtusi2026lab7
3grade_1change
This commit is contained in:
+226
@@ -0,0 +1,226 @@
|
||||
x-api-common: &api-common
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
environment:
|
||||
- OPENBAO_ADDR=http://openbao:8200
|
||||
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
- OTEL_SERVICE_NAME=messenger-api
|
||||
- OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab7
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
minio:
|
||||
condition: service_healthy
|
||||
broker:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
openbao:
|
||||
condition: service_started
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
|
||||
services:
|
||||
lb:
|
||||
image: nginx:1.25-alpine
|
||||
ports:
|
||||
- "8443:8443"
|
||||
volumes:
|
||||
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./nginx/certs:/etc/nginx/certs:ro
|
||||
depends_on:
|
||||
- api1
|
||||
- api2
|
||||
|
||||
api1:
|
||||
<<: *api-common
|
||||
expose:
|
||||
- "8080"
|
||||
|
||||
api2:
|
||||
<<: *api-common
|
||||
expose:
|
||||
- "8080"
|
||||
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.worker
|
||||
command: python -m worker.main
|
||||
environment:
|
||||
- OPENBAO_ADDR=http://openbao:8200
|
||||
- OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
- OTEL_SERVICE_NAME=messenger-worker
|
||||
- OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab7
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
minio:
|
||||
condition: service_healthy
|
||||
broker:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
openbao:
|
||||
condition: service_started
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
command: python scripts/migrate.py
|
||||
environment:
|
||||
- OPENBAO_ADDR=http://openbao:8200
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
openbao:
|
||||
condition: service_started
|
||||
|
||||
openbao:
|
||||
image: openbao/openbao:2.0.0
|
||||
command: server -config=/openbao/config.hcl
|
||||
volumes:
|
||||
- ./infra/openbao/config.hcl:/openbao/config.hcl:ro
|
||||
- openbaodata:/openbao/data
|
||||
cap_add:
|
||||
- IPC_LOCK
|
||||
ports:
|
||||
- "8200:8200"
|
||||
|
||||
init-openbao:
|
||||
image: alpine/curl:latest
|
||||
volumes:
|
||||
- ./scripts/init_openbao.sh:/init_openbao.sh:ro
|
||||
command: sh /init_openbao.sh
|
||||
depends_on:
|
||||
openbao:
|
||||
condition: service_started
|
||||
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
- POSTGRES_USER=messenger
|
||||
- POSTGRES_PASSWORD=messenger_password
|
||||
- POSTGRES_DB=messenger
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
minio:
|
||||
image: pgsty/silo:latest
|
||||
command: server /data --console-address ":9001"
|
||||
environment:
|
||||
- MINIO_ROOT_USER=minioadmin
|
||||
- MINIO_ROOT_PASSWORD=minioadmin
|
||||
volumes:
|
||||
- s3data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
ports:
|
||||
- "9000:9000"
|
||||
- "9001:9001"
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.13-alpine
|
||||
environment:
|
||||
- RABBITMQ_DEFAULT_USER=guest
|
||||
- RABBITMQ_DEFAULT_PASS=guest
|
||||
volumes:
|
||||
- brokerdata:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: redis-server --appendonly yes
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.95.0
|
||||
command: ["--config=/etc/otelcol/config.yaml"]
|
||||
volumes:
|
||||
- ./observability/otel-collector-config.yaml:/etc/otelcol/config.yaml:ro
|
||||
depends_on:
|
||||
- tempo
|
||||
- loki
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.51.0
|
||||
command:
|
||||
- "--config.file=/etc/prometheus/prometheus.yml"
|
||||
- "--storage.tsdb.path=/prometheus"
|
||||
volumes:
|
||||
- ./observability/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./observability/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
|
||||
- promdata:/prometheus
|
||||
ports:
|
||||
- "9090:9090"
|
||||
|
||||
loki:
|
||||
image: grafana/loki:2.9.4
|
||||
command: -config.file=/etc/loki/local-config.yaml
|
||||
volumes:
|
||||
- ./observability/loki/loki-config.yaml:/etc/loki/local-config.yaml:ro
|
||||
- lokidata:/loki
|
||||
ports:
|
||||
- "3100:3100"
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.4.0
|
||||
command: [ "-config.file=/etc/tempo.yaml" ]
|
||||
volumes:
|
||||
- ./observability/tempo/tempo-config.yaml:/etc/tempo.yaml:ro
|
||||
- tempodata:/var/tempo
|
||||
ports:
|
||||
- "3200:3200"
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:10.4.1
|
||||
environment:
|
||||
- GF_AUTH_ANONYMOUS_ENABLED=true
|
||||
- GF_AUTH_ANONYMOUS_ORG_ROLE=Admin
|
||||
- GF_AUTH_DISABLE_LOGIN_FORM=true
|
||||
- GF_PATHS_DASHBOARDS=/var/lib/grafana/dashboards
|
||||
volumes:
|
||||
- grafanadata:/var/lib/grafana
|
||||
ports:
|
||||
- "3000:3000"
|
||||
depends_on:
|
||||
- prometheus
|
||||
- loki
|
||||
- tempo
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
s3data:
|
||||
brokerdata:
|
||||
redisdata:
|
||||
promdata:
|
||||
lokidata:
|
||||
tempodata:
|
||||
grafanadata:
|
||||
openbaodata:
|
||||
@@ -0,0 +1,11 @@
|
||||
storage "file" {
|
||||
path = "/openbao/data"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_disable = "true"
|
||||
}
|
||||
|
||||
api_addr = "http://openbao:8200"
|
||||
ui = true
|
||||
+5
-5
@@ -4,17 +4,18 @@ events { worker_connections 1024; }
|
||||
|
||||
http {
|
||||
upstream api_backend {
|
||||
# least_conn лучше распределяет запросы, чем round-robin,
|
||||
# особенно когда одна реплика чуть медленнее.
|
||||
least_conn;
|
||||
server api1:8080 max_fails=1 fail_timeout=2s;
|
||||
server api2:8080 max_fails=1 fail_timeout=2s;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
listen 8443 ssl;
|
||||
|
||||
# Пути к сертификатам (мы сгенерируем их в шаге 2)
|
||||
ssl_certificate /etc/nginx/certs/nginx.crt;
|
||||
ssl_certificate_key /etc/nginx/certs/nginx.key;
|
||||
|
||||
# Проверка, что LB жив (без проксирования в API)
|
||||
location = /lb-health {
|
||||
access_log off;
|
||||
return 200 'ok';
|
||||
@@ -29,7 +30,6 @@ http {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# Важно для быстрого отключения упавшей реплики
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_read_timeout 10s;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# --- базовые из лабы 5 ---
|
||||
fastapi==0.111.0
|
||||
uvicorn[standard]==0.30.1
|
||||
psycopg[binary,pool]==3.2.1
|
||||
pydantic-settings==2.3.4
|
||||
boto3==1.34.144
|
||||
argon2-cffi==23.1.0
|
||||
aio-pika==9.4.3
|
||||
Pillow==10.4.0
|
||||
redis==5.0.7
|
||||
python-multipart==0.0.9
|
||||
|
||||
# --- OTel для лабы 6/7 ---
|
||||
opentelemetry-api==1.25.0
|
||||
opentelemetry-sdk==1.25.0
|
||||
opentelemetry-exporter-otlp==1.25.0
|
||||
opentelemetry-instrumentation-fastapi==0.46b0
|
||||
opentelemetry-instrumentation-psycopg==0.46b0
|
||||
opentelemetry-instrumentation-requests==0.46b0
|
||||
opentelemetry-instrumentation-aio-pika==0.46b0
|
||||
prometheus-fastapi-instrumentator==7.0.0
|
||||
python-json-logger==2.0.7
|
||||
|
||||
# --- НОВОЕ для лабы 7 (OpenBao) ---
|
||||
requests==2.32.3
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
echo "Waiting for OpenBao to start..."
|
||||
sleep 5
|
||||
|
||||
INIT_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://openbao:8200/v1/sys/init)
|
||||
|
||||
if [ "$INIT_STATUS" = "200" ]; then
|
||||
echo "OpenBao is already initialized. Skipping init."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Initializing OpenBao..."
|
||||
INIT_OUTPUT=$(curl -s -X PUT http://openbao:8200/v1/sys/init -d '{"secret_shares": 1, "secret_threshold": 1}')
|
||||
ROOT_TOKEN=$(echo "$INIT_OUTPUT" | grep -o '"root_token":"[^"]*' | cut -d'"' -f4)
|
||||
UNSEAL_KEY=$(echo "$INIT_OUTPUT" | grep -o '"keys":\["[^"]*' | cut -d'"' -f4)
|
||||
|
||||
echo "Unsealing OpenBao..."
|
||||
curl -s -X PUT http://openbao:8200/v1/sys/unseal -d "{\"key\": \"$UNSEAL_KEY\"}" > /dev/null
|
||||
|
||||
echo "Writing secrets to OpenBao..."
|
||||
curl -s -X POST -H "X-Vault-Token: $ROOT_TOKEN" http://openbao:8200/v1/sys/mounts/secret -d '{"type": "kv", "options": {"version": "2"}}' > /dev/null
|
||||
|
||||
curl -s -X POST -H "X-Vault-Token: $ROOT_TOKEN" http://openbao:8200/v1/secret/data/messenger -d '{
|
||||
"data": {
|
||||
"db_password": "messenger_password",
|
||||
"s3_access_key": "minioadmin",
|
||||
"s3_secret_key": "minioadmin",
|
||||
"broker_url": "amqp://guest:guest@broker:5672/"
|
||||
}
|
||||
}' > /dev/null
|
||||
|
||||
echo "OpenBao initialization complete."
|
||||
echo "ROOT_TOKEN=$ROOT_TOKEN"
|
||||
echo "UNSEAL_KEY=$UNSEAL_KEY"
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
echo "Restarting API and Postgres (preserving volumes)..."
|
||||
docker compose restart api1 api2 postgres
|
||||
echo "Waiting for Postgres to be healthy..."
|
||||
sleep 5
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
if [ "$TARGET_INSTANCE_ID" != "api-1" ] && [ "$TARGET_INSTANCE_ID" != "api-2" ]; then
|
||||
echo "Unknown instance: $TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
SERVICE_NAME="$TARGET_INSTANCE_ID"
|
||||
if [ "$SERVICE_NAME" = "api-1" ]; then SERVICE_NAME="api1"; fi
|
||||
if [ "$SERVICE_NAME" = "api-2" ]; then SERVICE_NAME="api2"; fi
|
||||
|
||||
echo "Stopping container for $SERVICE_NAME..."
|
||||
docker compose stop "$SERVICE_NAME"
|
||||
+20
-25
@@ -1,58 +1,53 @@
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
def _read_secret(path: str | None) -> str | None:
|
||||
if not path:
|
||||
return None
|
||||
p = Path(path)
|
||||
if not p.is_file():
|
||||
return None
|
||||
return p.read_text(encoding="utf-8").strip()
|
||||
|
||||
from .vault import get_secrets
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=None, extra="ignore")
|
||||
|
||||
app_host: str = "0.0.0.0"
|
||||
app_port: int = 8080
|
||||
app_env: str = "lab6"
|
||||
app_env: str = "lab7"
|
||||
instance_id: str = ""
|
||||
log_level: str = "info"
|
||||
|
||||
session_ttl_seconds: int = 3600
|
||||
idempotency_ttl_seconds: int = 86400
|
||||
|
||||
# Секреты загружаются из OpenBao
|
||||
database_url: str = ""
|
||||
database_url_file: str = "/run/secrets/database_url"
|
||||
s3_access_key: str = ""
|
||||
s3_secret_key: str = ""
|
||||
broker_url: str = ""
|
||||
|
||||
s3_endpoint: str = "http://minio:9000"
|
||||
s3_access_key: str = "minioadmin"
|
||||
s3_secret_key: str = "minioadmin"
|
||||
s3_bucket: str = "messenger-attachments"
|
||||
s3_region: str = "us-east-1"
|
||||
|
||||
broker_url: str = "amqp://guest:guest@broker:5672/"
|
||||
broker_queue: str = "attachment_processing"
|
||||
|
||||
redis_url: str = "redis://redis:6379/0"
|
||||
|
||||
# --- OTel (лаба 6) ---
|
||||
otel_exporter_otlp_endpoint: str = "http://otel-collector:4317"
|
||||
otel_service_name: str = "messenger-api"
|
||||
otel_environment: str = "lab6"
|
||||
otel_environment: str = "lab7"
|
||||
|
||||
@property
|
||||
def db_dsn(self) -> str:
|
||||
from_file = _read_secret(self.database_url_file)
|
||||
dsn = from_file or self.database_url
|
||||
if not dsn:
|
||||
raise RuntimeError(
|
||||
"DATABASE_URL не задан: укажи DATABASE_URL или смонтируй DATABASE_URL_FILE"
|
||||
)
|
||||
return dsn
|
||||
secrets = get_secrets()
|
||||
return f"postgresql://messenger:{secrets['db_password']}@postgres:5432/messenger"
|
||||
|
||||
@property
|
||||
def aws_access_key(self) -> str:
|
||||
return get_secrets()["s3_access_key"]
|
||||
|
||||
@property
|
||||
def aws_secret_key(self) -> str:
|
||||
return get_secrets()["s3_secret_key"]
|
||||
|
||||
@property
|
||||
def rabbit_url(self) -> str:
|
||||
return get_secrets()["broker_url"]
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
|
||||
@@ -89,10 +89,22 @@ async def upload_attachment(
|
||||
att = cur.fetchone()
|
||||
|
||||
# 2. Сохраняем задачу в Outbox в ТОЙ ЖЕ транзакции
|
||||
payload = {"attachment_id": str(att["id"]), "object_key": object_key}
|
||||
# Формат соответствует contracts/jobs.schema.json (лаба 7)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
job_payload = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(uuid.uuid4()),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(att["id"]),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
}
|
||||
|
||||
cur.execute(
|
||||
"INSERT INTO outbox_messages (attachment_id, payload) VALUES (%s, %s)",
|
||||
(att["id"], json.dumps(payload))
|
||||
(att["id"], json.dumps(job_payload))
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"DB failed, compensating S3: {e}")
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import os
|
||||
import logging
|
||||
import requests
|
||||
from functools import lru_cache
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@lru_cache(maxsize=None)
|
||||
def get_secrets() -> dict:
|
||||
vault_addr = os.environ.get("OPENBAO_ADDR", "http://openbao:8200")
|
||||
token = os.environ.get("OPENBAO_TOKEN", "")
|
||||
|
||||
if not token:
|
||||
logger.warning("OPENBAO_TOKEN is not set. Using fallback default values.")
|
||||
return {
|
||||
"db_password": "messenger_password",
|
||||
"s3_access_key": "minioadmin",
|
||||
"s3_secret_key": "minioadmin",
|
||||
"broker_url": "amqp://guest:guest@broker:5672/"
|
||||
}
|
||||
|
||||
url = f"{vault_addr}/v1/secret/data/messenger"
|
||||
headers = {"X-Vault-Token": token}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, timeout=5)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()["data"]["data"]
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to fetch secrets from OpenBao: {e}")
|
||||
raise RuntimeError("Cannot fetch secrets from OpenBao")
|
||||
Reference in New Issue
Block a user