forked from mtusi2026/mtusi2026lab6
исправления trace и span
This commit is contained in:
+38
-32
@@ -4,6 +4,8 @@ import random
|
|||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
|
from opentelemetry import propagate, trace
|
||||||
|
from opentelemetry.instrumentation.utils import suppress_instrumentation
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
import aio_pika
|
import aio_pika
|
||||||
@@ -12,20 +14,17 @@ from app.models import JobOutbox
|
|||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
BROKER_URL = os.getenv("BROKER_URL", "amqp://messenger:mq_secret_password@rabbitmq:5672/")
|
BROKER_URL = os.getenv("BROKER_URL", "amqp://messenger:mq_secret_password@rabbitmq:5672/")
|
||||||
|
|
||||||
MAIN_QUEUE = "attachment.process.v1"
|
MAIN_QUEUE = "attachment.process.v1"
|
||||||
DLX_NAME = "attachments.dlx"
|
DLX_NAME = "attachments.dlx"
|
||||||
DLQ_NAME = "attachment.process.dlq"
|
DLQ_NAME = "attachment.process.dlq"
|
||||||
RETRY_EXCHANGE = "attachments.retry"
|
RETRY_EXCHANGE = "attachments.retry"
|
||||||
|
|
||||||
# Лестница отложенных очередей: фиксированный TTL на очередь,
|
|
||||||
# поэтому нет head-of-line blocking (в отличие от per-message TTL).
|
|
||||||
RETRY_TIERS = [1, 2, 4, 8, 16, 32, 60]
|
RETRY_TIERS = [1, 2, 4, 8, 16, 32, 60]
|
||||||
BASE_DELAY = 1
|
BASE_DELAY = 1
|
||||||
MAX_DELAY = 60
|
MAX_DELAY = 60
|
||||||
|
|
||||||
_connection = None
|
_connection = None
|
||||||
_channel = None
|
_channel = None
|
||||||
|
_tracer = trace.get_tracer("messenger-api")
|
||||||
|
|
||||||
|
|
||||||
def retry_queue_name(tier: int) -> str:
|
def retry_queue_name(tier: int) -> str:
|
||||||
@@ -33,9 +32,8 @@ def retry_queue_name(tier: int) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def choose_retry_tier(attempt: int) -> int:
|
def choose_retry_tier(attempt: int) -> int:
|
||||||
"""Экспоненциальный backoff с equal jitter, квантованный по лестнице TTL."""
|
|
||||||
exp = min(BASE_DELAY * (2 ** (attempt - 1)), MAX_DELAY)
|
exp = min(BASE_DELAY * (2 ** (attempt - 1)), MAX_DELAY)
|
||||||
delay = random.uniform(exp / 2, exp) # equal jitter
|
delay = random.uniform(exp / 2, exp)
|
||||||
for tier in RETRY_TIERS:
|
for tier in RETRY_TIERS:
|
||||||
if tier >= delay:
|
if tier >= delay:
|
||||||
return tier
|
return tier
|
||||||
@@ -43,7 +41,6 @@ def choose_retry_tier(attempt: int) -> int:
|
|||||||
|
|
||||||
|
|
||||||
async def declare_topology(channel: aio_pika.Channel):
|
async def declare_topology(channel: aio_pika.Channel):
|
||||||
"""Идемпотентное объявление обменов и очередей. Аргументы неизменяемы!"""
|
|
||||||
dlx = await channel.declare_exchange(DLX_NAME, aio_pika.ExchangeType.DIRECT, durable=True)
|
dlx = await channel.declare_exchange(DLX_NAME, aio_pika.ExchangeType.DIRECT, durable=True)
|
||||||
dlq = await channel.declare_queue(DLQ_NAME, durable=True)
|
dlq = await channel.declare_queue(DLQ_NAME, durable=True)
|
||||||
await dlq.bind(dlx, routing_key=DLQ_NAME)
|
await dlq.bind(dlx, routing_key=DLQ_NAME)
|
||||||
@@ -52,67 +49,76 @@ async def declare_topology(channel: aio_pika.Channel):
|
|||||||
for tier in RETRY_TIERS:
|
for tier in RETRY_TIERS:
|
||||||
name = retry_queue_name(tier)
|
name = retry_queue_name(tier)
|
||||||
q = await channel.declare_queue(
|
q = await channel.declare_queue(
|
||||||
name,
|
name, durable=True,
|
||||||
durable=True,
|
arguments={"x-message-ttl": tier * 1000,
|
||||||
arguments={
|
"x-dead-letter-exchange": "",
|
||||||
"x-message-ttl": tier * 1000,
|
"x-dead-letter-routing-key": MAIN_QUEUE},
|
||||||
"x-dead-letter-exchange": "", # default exchange
|
|
||||||
"x-dead-letter-routing-key": MAIN_QUEUE, # после TTL -> в основную очередь
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
await q.bind(retry_ex, routing_key=name)
|
await q.bind(retry_ex, routing_key=name)
|
||||||
|
|
||||||
await channel.declare_queue(
|
await channel.declare_queue(
|
||||||
MAIN_QUEUE,
|
MAIN_QUEUE, durable=True,
|
||||||
durable=True,
|
arguments={"x-dead-letter-exchange": DLX_NAME,
|
||||||
arguments={
|
"x-dead-letter-routing-key": DLQ_NAME},
|
||||||
"x-dead-letter-exchange": DLX_NAME,
|
|
||||||
"x-dead-letter-routing-key": DLQ_NAME,
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
logger.info("RabbitMQ topology ready: main=%s, retry tiers=%s, dlq=%s", MAIN_QUEUE, RETRY_TIERS, DLQ_NAME)
|
logger.info("RabbitMQ topology ready: main=%s, retry tiers=%s, dlq=%s", MAIN_QUEUE, RETRY_TIERS, DLQ_NAME)
|
||||||
|
|
||||||
|
|
||||||
async def get_channel() -> aio_pika.Channel:
|
async def get_channel() -> aio_pika.Channel:
|
||||||
"""Канал с publisher confirms (aio-pika по умолчанию publisher_confirms=True)."""
|
|
||||||
global _connection, _channel
|
global _connection, _channel
|
||||||
if _connection is None or _connection.is_closed or _channel is None or _channel.is_closed:
|
if _connection is None or _connection.is_closed or _channel is None or _channel.is_closed:
|
||||||
_connection = await aio_pika.connect_robust(BROKER_URL)
|
_connection = await aio_pika.connect_robust(BROKER_URL)
|
||||||
_channel = await _connection.channel() # publisher_confirms=True
|
_channel = await _connection.channel()
|
||||||
await declare_topology(_channel)
|
await declare_topology(_channel)
|
||||||
return _channel
|
return _channel
|
||||||
|
|
||||||
|
|
||||||
async def publish_retry(payload: dict, tier: int):
|
async def publish_retry(payload: dict, tier: int):
|
||||||
"""Отложенная повторная доставка: сообщение полежит tier секунд и вернётся в main."""
|
|
||||||
channel = await get_channel()
|
channel = await get_channel()
|
||||||
retry_ex = await channel.get_exchange(RETRY_EXCHANGE)
|
retry_ex = await channel.get_exchange(RETRY_EXCHANGE)
|
||||||
await retry_ex.publish(
|
await retry_ex.publish(
|
||||||
aio_pika.Message(
|
aio_pika.Message(body=json.dumps(payload).encode(),
|
||||||
body=json.dumps(payload).encode(),
|
delivery_mode=aio_pika.DeliveryMode.PERSISTENT),
|
||||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
|
||||||
),
|
|
||||||
routing_key=retry_queue_name(tier),
|
routing_key=retry_queue_name(tier),
|
||||||
)
|
)
|
||||||
logger.info("Scheduled retry in %ss for job %s (attempt %s)", tier, payload.get("job_id"), payload.get("attempt"))
|
logger.info("Scheduled retry in %ss for job %s (attempt %s)", tier, payload.get("job_id"), payload.get("attempt"))
|
||||||
|
|
||||||
|
|
||||||
async def publish_main(payload: dict):
|
async def publish_main(payload: dict):
|
||||||
|
"""PRODUCER span, наследующий traceparent из payload outbox (W3C API->broker)."""
|
||||||
channel = await get_channel()
|
channel = await get_channel()
|
||||||
|
|
||||||
|
# Извлекаем сохранённый traceparent/tracestate из payload
|
||||||
|
parent_ctx = propagate.extract({k: payload[k] for k in ("traceparent", "tracestate") if k in payload})
|
||||||
|
|
||||||
|
with _tracer.start_as_current_span(
|
||||||
|
"attachment.publish",
|
||||||
|
context=parent_ctx,
|
||||||
|
kind=trace.SpanKind.PRODUCER,
|
||||||
|
attributes={"messaging.system": "rabbitmq",
|
||||||
|
"messaging.destination.name": MAIN_QUEUE,
|
||||||
|
"messaging.operation.type": "publish"},
|
||||||
|
):
|
||||||
|
carrier = {}
|
||||||
|
propagate.inject(carrier)
|
||||||
|
# Кладём traceparent в заголовки сообщения -> worker извлечёт (W3C broker->worker)
|
||||||
|
headers = {k: v for k, v in carrier.items() if k in ("traceparent", "tracestate")}
|
||||||
await channel.default_exchange.publish(
|
await channel.default_exchange.publish(
|
||||||
aio_pika.Message(
|
aio_pika.Message(body=json.dumps(payload).encode(),
|
||||||
body=json.dumps(payload).encode(),
|
|
||||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||||
),
|
headers=headers),
|
||||||
routing_key=MAIN_QUEUE,
|
routing_key=MAIN_QUEUE,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def relay_outbox(db: AsyncSession):
|
async def relay_outbox(db: AsyncSession):
|
||||||
"""Transactional outbox: publish + confirm, только потом published_at."""
|
# suppress_instrumentation: фоновый claim не плодит SQL-трейсы-шум в Tempo
|
||||||
|
with suppress_instrumentation():
|
||||||
stmt = select(JobOutbox).where(JobOutbox.published_at.is_(None)).limit(10)
|
stmt = select(JobOutbox).where(JobOutbox.published_at.is_(None)).limit(10)
|
||||||
result = await db.execute(stmt)
|
result = await db.execute(stmt)
|
||||||
for record in result.scalars().all():
|
records = result.scalars().all()
|
||||||
|
|
||||||
|
for record in records:
|
||||||
try:
|
try:
|
||||||
await publish_main(record.payload) # ждём publisher confirm
|
await publish_main(record.payload) # ждём publisher confirm
|
||||||
record.published_at = datetime.now(timezone.utc)
|
record.published_at = datetime.now(timezone.utc)
|
||||||
|
|||||||
+60
-48
@@ -1,93 +1,105 @@
|
|||||||
import os
|
import os
|
||||||
import uuid
|
import uuid
|
||||||
import logging
|
import logging
|
||||||
import traceback
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
# 1. Инициализируем телеметрию и ПОЛУЧАЕМ провайдеры
|
|
||||||
from app.telemetry import setup_telemetry
|
from app.telemetry import setup_telemetry
|
||||||
tracer_provider, meter_provider, logger_provider = setup_telemetry()
|
tracer_provider, meter_provider, logger_provider = setup_telemetry()
|
||||||
|
|
||||||
|
from app.queue_metrics import collect_queue_metrics
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.exceptions import RequestValidationError
|
from fastapi.exceptions import RequestValidationError
|
||||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
from opentelemetry import trace, propagate
|
||||||
# 2. Импортируем инструментаторы
|
from opentelemetry.trace import SpanKind, StatusCode
|
||||||
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
|
||||||
from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
|
from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
|
||||||
from opentelemetry.instrumentation.logging import LoggingInstrumentor
|
from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor
|
||||||
|
|
||||||
from app.routers import auth, chats, attachments
|
from app.routers import auth, chats, attachments
|
||||||
from app.broker import run_relay
|
from app.broker import run_relay
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
tracer = trace.get_tracer("messenger-api")
|
||||||
|
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8])
|
||||||
|
|
||||||
|
|
||||||
|
class OtelASGIMiddleware:
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app = app
|
||||||
|
|
||||||
|
async def __call__(self, scope, receive, send):
|
||||||
|
if scope["type"] != "http":
|
||||||
|
await self.app(scope, receive, send)
|
||||||
|
return
|
||||||
|
method = scope.get("method", "?")
|
||||||
|
path = scope.get("path", "?")
|
||||||
|
carrier = {k.decode().lower(): v.decode() for k, v in scope.get("headers", [])}
|
||||||
|
parent_ctx = propagate.extract(carrier)
|
||||||
|
with tracer.start_as_current_span(
|
||||||
|
name=f"{method} {path}", context=parent_ctx, kind=SpanKind.SERVER,
|
||||||
|
attributes={"http.method": method, "http.target": path},
|
||||||
|
) as span:
|
||||||
|
tid = format(span.get_span_context().trace_id, "032x")
|
||||||
|
print(f"!!! MW SPAN: {method} {path} trace_id={tid}", flush=True)
|
||||||
|
out = {}
|
||||||
|
propagate.inject(out)
|
||||||
|
scope.setdefault("state", {})["trace_carrier"] = out
|
||||||
|
scope["state"]["request_id"] = carrier.get("x-request-id") or str(uuid.uuid4())
|
||||||
|
|
||||||
|
async def send_wrapper(message):
|
||||||
|
if message["type"] == "http.response.start":
|
||||||
|
span.set_attribute("http.status_code", message.get("status", 0))
|
||||||
|
if message.get("status", 0) >= 500:
|
||||||
|
span.set_status(StatusCode.ERROR)
|
||||||
|
h = list(message.get("headers", []))
|
||||||
|
h.append((b"x-request-id", scope["state"]["request_id"].encode()))
|
||||||
|
h.append((b"x-instance-id", INSTANCE_ID.encode()))
|
||||||
|
message["headers"] = h
|
||||||
|
await send(message)
|
||||||
|
await self.app(scope, receive, send_wrapper)
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
task = asyncio.create_task(run_relay())
|
task = asyncio.create_task(run_relay())
|
||||||
|
queue_task = asyncio.create_task(collect_queue_metrics())
|
||||||
yield
|
yield
|
||||||
# Принудительно сбрасываем спаны при завершении, чтобы они точно ушли в Collector
|
|
||||||
tracer_provider.force_flush(timeout_millis=5000)
|
tracer_provider.force_flush(timeout_millis=5000)
|
||||||
task.cancel()
|
task.cancel()
|
||||||
|
queue_task.cancel()
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(lifespan=lifespan)
|
app = FastAPI(lifespan=lifespan)
|
||||||
|
|
||||||
# 3. ЯВНО передаем tracer_provider и meter_provider в инструментацию!
|
|
||||||
FastAPIInstrumentor().instrument_app(app, tracer_provider=tracer_provider, meter_provider=meter_provider)
|
|
||||||
AsyncPGInstrumentor().instrument(tracer_provider=tracer_provider)
|
|
||||||
LoggingInstrumentor().instrument()
|
|
||||||
|
|
||||||
app.include_router(auth.router)
|
app.include_router(auth.router)
|
||||||
app.include_router(chats.router)
|
app.include_router(chats.router)
|
||||||
app.include_router(attachments.router)
|
app.include_router(attachments.router)
|
||||||
|
AsyncPGInstrumentor().instrument(tracer_provider=tracer_provider)
|
||||||
|
AioPikaInstrumentor().instrument(tracer_provider=tracer_provider)
|
||||||
|
app.add_middleware(OtelASGIMiddleware)
|
||||||
|
|
||||||
INSTANCE_ID = os.getenv("INSTANCE_ID", str(uuid.uuid4())[:8])
|
|
||||||
|
|
||||||
@app.middleware("http")
|
|
||||||
async def add_instance_and_request_id(request: Request, call_next):
|
|
||||||
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
|
||||||
request.state.request_id = request_id
|
|
||||||
try:
|
|
||||||
response = await call_next(request)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Unhandled exception: {e}")
|
|
||||||
traceback.print_exc()
|
|
||||||
return JSONResponse(
|
|
||||||
status_code=500,
|
|
||||||
content={"error": {"code": "internal_error", "message": "Unexpected error", "request_id": request_id}},
|
|
||||||
headers={"X-Request-Id": request_id, "X-Instance-Id": INSTANCE_ID}
|
|
||||||
)
|
|
||||||
response.headers["X-Request-Id"] = request.state.request_id
|
|
||||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
|
||||||
return response
|
|
||||||
|
|
||||||
@app.exception_handler(StarletteHTTPException)
|
@app.exception_handler(StarletteHTTPException)
|
||||||
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
async def http_exception_handler(request: Request, exc: StarletteHTTPException):
|
||||||
detail = exc.detail
|
detail = exc.detail
|
||||||
if isinstance(detail, dict):
|
code = detail.get("code", "internal_error") if isinstance(detail, dict) else "internal_error"
|
||||||
code = detail.get("code", "internal_error")
|
message = detail.get("message", str(detail)) if isinstance(detail, dict) else str(detail)
|
||||||
message = detail.get("message", str(detail))
|
return JSONResponse(status_code=exc.status_code,
|
||||||
else:
|
content={"error": {"code": code, "message": message,
|
||||||
code = "internal_error"
|
"request_id": getattr(request.state, "request_id", "")}}, headers=exc.headers)
|
||||||
message = str(detail)
|
|
||||||
return JSONResponse(
|
|
||||||
status_code=exc.status_code,
|
|
||||||
content={"error": {"code": code, "message": message, "request_id": request.state.request_id}},
|
|
||||||
headers=exc.headers
|
|
||||||
)
|
|
||||||
|
|
||||||
@app.exception_handler(RequestValidationError)
|
@app.exception_handler(RequestValidationError)
|
||||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
return JSONResponse(
|
return JSONResponse(status_code=400,
|
||||||
status_code=400,
|
content={"error": {"code": "invalid_request", "message": "Validation error",
|
||||||
content={"error": {"code": "invalid_request", "message": "Validation error", "request_id": request.state.request_id}},
|
"request_id": getattr(request.state, "request_id", "")}},
|
||||||
headers={"X-Request-Id": request.state.request_id, "X-Instance-Id": INSTANCE_ID}
|
headers={"X-Request-Id": getattr(request.state, "request_id", ""), "X-Instance-Id": INSTANCE_ID})
|
||||||
)
|
|
||||||
|
|
||||||
@app.get("/health/live")
|
@app.get("/health/live")
|
||||||
async def health_live():
|
async def health_live():
|
||||||
|
cur = trace.get_current_span().get_span_context()
|
||||||
|
print(f"!!! ENDPOINT trace_id={format(cur.trace_id,'032x')}", flush=True)
|
||||||
return {"status": "ok"}
|
return {"status": "ok"}
|
||||||
|
|
||||||
@app.get("/health/ready")
|
@app.get("/health/ready")
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import os
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from sqlalchemy import select, func
|
||||||
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from opentelemetry import metrics
|
||||||
|
|
||||||
|
from app.models import Attachment, AttachmentJob
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_meter = metrics.get_meter("messenger.queue")
|
||||||
|
_queue_state = {"active": 0, "oldest_age": 0.0}
|
||||||
|
|
||||||
|
_meter.create_observable_gauge(
|
||||||
|
"messenger.queue.active_jobs",
|
||||||
|
callbacks=[lambda opts: [metrics.Observation(_queue_state["active"])]],
|
||||||
|
description="Queued+processing jobs",
|
||||||
|
)
|
||||||
|
_meter.create_observable_gauge(
|
||||||
|
"messenger.queue.oldest_job_age_seconds",
|
||||||
|
callbacks=[lambda opts: [metrics.Observation(_queue_state["oldest_age"])]],
|
||||||
|
unit="s",
|
||||||
|
description="Age of the oldest unfinished job",
|
||||||
|
)
|
||||||
|
|
||||||
|
async def collect_queue_metrics():
|
||||||
|
engine = create_async_engine(os.environ["DATABASE_URL"], echo=False)
|
||||||
|
Session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
async with Session() as db:
|
||||||
|
cnt = (await db.execute(
|
||||||
|
select(func.count()).select_from(AttachmentJob)
|
||||||
|
.where(AttachmentJob.status.in_(["queued", "processing"]))
|
||||||
|
)).scalar() or 0
|
||||||
|
oldest = (await db.execute(
|
||||||
|
select(func.min(Attachment.created_at))
|
||||||
|
.join(AttachmentJob, AttachmentJob.attachment_id == Attachment.id)
|
||||||
|
.where(AttachmentJob.status.in_(["queued", "processing"]))
|
||||||
|
)).scalar()
|
||||||
|
_queue_state["active"] = cnt
|
||||||
|
_queue_state["oldest_age"] = (
|
||||||
|
(datetime.now(timezone.utc) - oldest).total_seconds() if oldest else 0.0
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
logger.exception("queue metrics collector error")
|
||||||
|
await asyncio.sleep(5)
|
||||||
|
finally:
|
||||||
|
await engine.dispose()
|
||||||
@@ -3,6 +3,7 @@ import uuid
|
|||||||
import hashlib
|
import hashlib
|
||||||
import magic
|
import magic
|
||||||
import tempfile
|
import tempfile
|
||||||
|
from opentelemetry import propagate
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from fastapi import APIRouter, Depends, HTTPException, status, Query, Request
|
from fastapi import APIRouter, Depends, HTTPException, status, Query, Request
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
@@ -106,6 +107,14 @@ async def upload_attachment(
|
|||||||
"attempt": 1
|
"attempt": 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Добавляем traceparent для W3C propagation через outbox
|
||||||
|
carrier = {}
|
||||||
|
propagate.inject(carrier)
|
||||||
|
if "traceparent" in carrier:
|
||||||
|
outbox_payload["traceparent"] = carrier["traceparent"]
|
||||||
|
if "tracestate" in carrier:
|
||||||
|
outbox_payload["tracestate"] = carrier["tracestate"]
|
||||||
|
|
||||||
new_outbox = JobOutbox(
|
new_outbox = JobOutbox(
|
||||||
job_id=job_id,
|
job_id=job_id,
|
||||||
payload=outbox_payload,
|
payload=outbox_payload,
|
||||||
|
|||||||
+18
-9
@@ -6,7 +6,7 @@ from opentelemetry.sdk.trace.export import BatchSpanProcessor, SimpleSpanProcess
|
|||||||
from opentelemetry.sdk.metrics import MeterProvider
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
from opentelemetry.sdk._logs.export import SimpleLogRecordProcessor, ConsoleLogExporter
|
||||||
from opentelemetry.sdk.resources import Resource
|
from opentelemetry.sdk.resources import Resource
|
||||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
||||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
||||||
@@ -20,7 +20,6 @@ def setup_telemetry():
|
|||||||
"deployment.environment": os.getenv("OTEL_ENVIRONMENT", "lab")
|
"deployment.environment": os.getenv("OTEL_ENVIRONMENT", "lab")
|
||||||
})
|
})
|
||||||
|
|
||||||
# Используем gRPC порт 4317
|
|
||||||
otlp_endpoint = "otel-collector:4317"
|
otlp_endpoint = "otel-collector:4317"
|
||||||
|
|
||||||
# 1. Traces
|
# 1. Traces
|
||||||
@@ -28,15 +27,13 @@ def setup_telemetry():
|
|||||||
trace.set_tracer_provider(tracer_provider)
|
trace.set_tracer_provider(tracer_provider)
|
||||||
|
|
||||||
span_exporter = OTLPSpanExporter(endpoint=otlp_endpoint, insecure=True)
|
span_exporter = OTLPSpanExporter(endpoint=otlp_endpoint, insecure=True)
|
||||||
# Быстрый batch для тестов (отправка каждые 2 секунды или по 512 спанов)
|
|
||||||
tracer_provider.add_span_processor(BatchSpanProcessor(
|
tracer_provider.add_span_processor(BatchSpanProcessor(
|
||||||
span_exporter,
|
span_exporter,
|
||||||
max_queue_size=2048,
|
max_queue_size=2048,
|
||||||
max_export_batch_size=512,
|
max_export_batch_size=512,
|
||||||
schedule_delay_millis=2000
|
schedule_delay_millis=2000
|
||||||
))
|
))
|
||||||
# Консольный экспортер для 100% видимости в логах приложения
|
# tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
|
||||||
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
|
|
||||||
|
|
||||||
# 2. Metrics
|
# 2. Metrics
|
||||||
metric_reader = PeriodicExportingMetricReader(
|
metric_reader = PeriodicExportingMetricReader(
|
||||||
@@ -50,13 +47,25 @@ def setup_telemetry():
|
|||||||
logger_provider = LoggerProvider(resource=resource)
|
logger_provider = LoggerProvider(resource=resource)
|
||||||
_logs.set_logger_provider(logger_provider)
|
_logs.set_logger_provider(logger_provider)
|
||||||
log_exporter = OTLPLogExporter(endpoint=otlp_endpoint, insecure=True)
|
log_exporter = OTLPLogExporter(endpoint=otlp_endpoint, insecure=True)
|
||||||
logger_provider.add_log_record_processor(BatchLogRecordProcessor(log_exporter))
|
logger_provider.add_log_record_processor(SimpleLogRecordProcessor(log_exporter))
|
||||||
|
# logger_provider.add_log_record_processor(SimpleLogRecordProcessor(ConsoleLogExporter()))
|
||||||
|
|
||||||
|
# 4. Handler для логов
|
||||||
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||||
logging.getLogger().addHandler(handler)
|
root_logger = logging.getLogger()
|
||||||
logging.getLogger().setLevel(logging.INFO)
|
root_logger.addHandler(handler)
|
||||||
|
root_logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
uvicorn_error_logger = logging.getLogger("uvicorn.error")
|
||||||
|
uvicorn_error_logger.addHandler(handler)
|
||||||
|
uvicorn_error_logger.setLevel(logging.INFO)
|
||||||
|
uvicorn_error_logger.propagate = True
|
||||||
|
|
||||||
|
uvicorn_access_logger = logging.getLogger("uvicorn.access")
|
||||||
|
uvicorn_access_logger.addHandler(handler)
|
||||||
|
uvicorn_access_logger.setLevel(logging.INFO)
|
||||||
|
uvicorn_access_logger.propagate = True
|
||||||
|
|
||||||
logging.info(f"OpenTelemetry fully initialized (gRPC) for {service_name} at {otlp_endpoint}")
|
logging.info(f"OpenTelemetry fully initialized (gRPC) for {service_name} at {otlp_endpoint}")
|
||||||
|
|
||||||
# Возвращаем провайдеры для явной передачи в инструментацию
|
|
||||||
return tracer_provider, meter_provider, logger_provider
|
return tracer_provider, meter_provider, logger_provider
|
||||||
+20
-8
@@ -16,9 +16,10 @@ from sqlalchemy import select, update, func
|
|||||||
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
||||||
from sqlalchemy.orm import sessionmaker
|
from sqlalchemy.orm import sessionmaker
|
||||||
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
from sqlalchemy.dialects.postgresql import insert as pg_insert
|
||||||
|
from opentelemetry import trace, propagate
|
||||||
|
|
||||||
from app.telemetry import setup_telemetry
|
from app.telemetry import setup_telemetry
|
||||||
setup_telemetry()
|
tracer_provider, meter_provider, logger_provider = setup_telemetry()
|
||||||
|
|
||||||
from app.models import Attachment, AttachmentJob, AttachmentVariant
|
from app.models import Attachment, AttachmentJob, AttachmentVariant
|
||||||
from app.broker import (
|
from app.broker import (
|
||||||
@@ -47,7 +48,8 @@ engine = create_async_engine(DATABASE_URL, echo=False)
|
|||||||
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||||
s3_client = Minio(S3_ENDPOINT, access_key=S3_ACCESS_KEY, secret_key=S3_SECRET_KEY, secure=False)
|
s3_client = Minio(S3_ENDPOINT, access_key=S3_ACCESS_KEY, secret_key=S3_SECRET_KEY, secure=False)
|
||||||
|
|
||||||
# === OTel метрики worker ===
|
tracer = trace.get_tracer("messenger-worker")
|
||||||
|
|
||||||
from opentelemetry import metrics
|
from opentelemetry import metrics
|
||||||
_meter = metrics.get_meter("messenger.worker")
|
_meter = metrics.get_meter("messenger.worker")
|
||||||
_jobs_completed = _meter.create_counter("messenger.worker.jobs.completed", description="Completed jobs")
|
_jobs_completed = _meter.create_counter("messenger.worker.jobs.completed", description="Completed jobs")
|
||||||
@@ -55,7 +57,6 @@ _jobs_failed = _meter.create_counter("messenger.worker.jobs.failed", description
|
|||||||
_job_duration = _meter.create_histogram("messenger.worker.job.duration", unit="s", description="Job processing duration")
|
_job_duration = _meter.create_histogram("messenger.worker.job.duration", unit="s", description="Job processing duration")
|
||||||
_active_jobs = _meter.create_up_down_counter("messenger.worker.jobs.active", description="In-flight jobs")
|
_active_jobs = _meter.create_up_down_counter("messenger.worker.jobs.active", description="In-flight jobs")
|
||||||
|
|
||||||
# Кэш очереди, обновляется sweeper'ом; observable-gauge читает из него
|
|
||||||
_queue_state = {"active": 0, "oldest_age": 0.0}
|
_queue_state = {"active": 0, "oldest_age": 0.0}
|
||||||
_meter.create_observable_gauge(
|
_meter.create_observable_gauge(
|
||||||
"messenger.queue.active_jobs",
|
"messenger.queue.active_jobs",
|
||||||
@@ -294,6 +295,11 @@ async def schedule_retry(job_id: str, payload: dict) -> int:
|
|||||||
|
|
||||||
|
|
||||||
async def process_message(message: aio_pika.IncomingMessage):
|
async def process_message(message: aio_pika.IncomingMessage):
|
||||||
|
"""Обработка сообщения с W3C trace propagation."""
|
||||||
|
# Извлекаем traceparent из заголовков сообщения
|
||||||
|
headers = message.headers or {}
|
||||||
|
parent_context = propagate.extract(headers)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
data = json.loads(message.body)
|
data = json.loads(message.body)
|
||||||
job_id, att_id, attempt = data["job_id"], data["attachment_id"], int(data["attempt"])
|
job_id, att_id, attempt = data["job_id"], data["attachment_id"], int(data["attempt"])
|
||||||
@@ -303,6 +309,17 @@ async def process_message(message: aio_pika.IncomingMessage):
|
|||||||
await message.nack(requeue=False)
|
await message.nack(requeue=False)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# Создаём CONSUMER span с извлечённым контекстом
|
||||||
|
with tracer.start_as_current_span(
|
||||||
|
"attachment.process",
|
||||||
|
context=parent_context,
|
||||||
|
kind=trace.SpanKind.CONSUMER,
|
||||||
|
attributes={
|
||||||
|
"messaging.system": "rabbitmq",
|
||||||
|
"messaging.operation": "process",
|
||||||
|
"messaging.message.id": message.message_id or "",
|
||||||
|
},
|
||||||
|
) as span:
|
||||||
try:
|
try:
|
||||||
outcome, code = await handle_job(job_id, att_id, attempt)
|
outcome, code = await handle_job(job_id, att_id, attempt)
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -336,15 +353,10 @@ async def sweeper():
|
|||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
async with AsyncSessionLocal() as db:
|
async with AsyncSessionLocal() as db:
|
||||||
now = datetime.now(timezone.utc)
|
now = datetime.now(timezone.utc)
|
||||||
# Обновляем кэш очереди для observable-gauge
|
|
||||||
cnt = (await db.execute(
|
cnt = (await db.execute(
|
||||||
select(func.count()).select_from(AttachmentJob)
|
select(func.count()).select_from(AttachmentJob)
|
||||||
.where(AttachmentJob.status.in_(["queued", "processing"]))
|
.where(AttachmentJob.status.in_(["queued", "processing"]))
|
||||||
)).scalar() or 0
|
)).scalar() or 0
|
||||||
oldest = (await db.execute(
|
|
||||||
select(func.min(AttachmentJob.lease_until)).where(AttachmentJob.status == "queued")
|
|
||||||
)).scalar()
|
|
||||||
# возраст = время с создания самой старой незавершённой job
|
|
||||||
oldest_created = (await db.execute(
|
oldest_created = (await db.execute(
|
||||||
select(func.min(Attachment.created_at))
|
select(func.min(Attachment.created_at))
|
||||||
.join(AttachmentJob, AttachmentJob.attachment_id == Attachment.id)
|
.join(AttachmentJob, AttachmentJob.attachment_id == Attachment.id)
|
||||||
|
|||||||
+14
-13
@@ -3,23 +3,24 @@ groups:
|
|||||||
rules:
|
rules:
|
||||||
- alert: HighErrorRate
|
- alert: HighErrorRate
|
||||||
expr: |
|
expr: |
|
||||||
(
|
sum(rate(http_server_duration_milliseconds_count{http_status_code=~"5.."}[5m]))
|
||||||
sum(rate(http_server_duration_milliseconds_count{http_status_code=~"5.."}[5m])) or vector(0)
|
|
||||||
)
|
|
||||||
/
|
/
|
||||||
sum(rate(http_server_duration_milliseconds_count[5m]))
|
sum(rate(http_server_duration_milliseconds_count[5m]))
|
||||||
for: 1m
|
> 0.05
|
||||||
labels:
|
for: 2m
|
||||||
severity: critical
|
labels: { severity: critical }
|
||||||
annotations:
|
annotations:
|
||||||
summary: "API error rate > 5% (SLO 99%)"
|
summary: "API error rate > 5% (SLO 99%)"
|
||||||
description: "Доля 5xx за 5-минутное окно превысила 5%. SLI из histogram-метрик API."
|
description: "Доля 5xx за 5-минутное окно превысила 5%. SLI из histogram-метрик API."
|
||||||
|
- alert: WorkerQueueLagging
|
||||||
- alert: QueueLagGrowing
|
|
||||||
expr: messenger_queue_oldest_job_age_seconds > 60
|
expr: messenger_queue_oldest_job_age_seconds > 60
|
||||||
for: 2m
|
for: 1m
|
||||||
labels:
|
labels: { severity: warning }
|
||||||
severity: warning
|
|
||||||
annotations:
|
annotations:
|
||||||
summary: "Очередь задач растёт (возраст старейшей job > 60s)"
|
summary: "Старейшая job в очереди > 60 с"
|
||||||
description: "Worker не успевает дренировать очередь."
|
- alert: QueueGrowing
|
||||||
|
expr: messenger_queue_active_jobs > 10
|
||||||
|
for: 2m
|
||||||
|
labels: { severity: warning }
|
||||||
|
annotations:
|
||||||
|
summary: "Очередь растёт (> 10 задач)"
|
||||||
@@ -25,8 +25,7 @@ exporters:
|
|||||||
otlp_http/tempo:
|
otlp_http/tempo:
|
||||||
endpoint: "http://tempo:4318"
|
endpoint: "http://tempo:4318"
|
||||||
otlp_http/loki:
|
otlp_http/loki:
|
||||||
endpoint: "http://loki:3100"
|
endpoint: "http://loki:3100/otlp"
|
||||||
logs_path: "/otlp"
|
|
||||||
prometheus:
|
prometheus:
|
||||||
endpoint: "0.0.0.0:8889"
|
endpoint: "0.0.0.0:8889"
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user