forked from mtusi2026/mtusi2026lab6
Подключить OpenTelemetry, Collector и Grafana для оценки 5.
API и worker отдают метрики, логи и трассы. Правила SLO записаны, прогон инцидентов ещё впереди.
This commit is contained in:
+27
-13
@@ -8,7 +8,7 @@ import logging
|
||||
|
||||
import aio_pika
|
||||
|
||||
from app import config
|
||||
from app import config, telemetry
|
||||
|
||||
logger = logging.getLogger("messenger.broker")
|
||||
|
||||
@@ -49,19 +49,33 @@ async def _ensure() -> tuple[aio_pika.RobustChannel, aio_pika.Exchange]:
|
||||
return _channel, _exchange
|
||||
|
||||
|
||||
async def publish_job(payload: dict) -> None:
|
||||
async def publish_job(payload: dict, traceparent: str | None = None, tracestate: str | None = None) -> None:
|
||||
channel, exchange = await _ensure()
|
||||
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
await exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=body,
|
||||
content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=payload["job_id"],
|
||||
),
|
||||
routing_key=ROUTING_KEY,
|
||||
mandatory=True,
|
||||
)
|
||||
parent = telemetry.remote_context(traceparent, tracestate)
|
||||
with telemetry.span(
|
||||
"attachment.job.publish",
|
||||
context=parent,
|
||||
kind="producer",
|
||||
attributes={
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": QUEUE,
|
||||
"messaging.operation": "publish",
|
||||
"job.id": payload.get("job_id"),
|
||||
},
|
||||
):
|
||||
headers = telemetry.current_carrier() or None
|
||||
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
|
||||
await exchange.publish(
|
||||
aio_pika.Message(
|
||||
body=body,
|
||||
content_type="application/json",
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
message_id=payload["job_id"],
|
||||
headers=headers,
|
||||
),
|
||||
routing_key=ROUTING_KEY,
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
|
||||
async def publish_delay(payload: dict, delay_seconds: float) -> None:
|
||||
|
||||
@@ -56,6 +56,11 @@ JOB_BACKOFF_BASE_SECONDS = float(_env("JOB_BACKOFF_BASE_SECONDS", "0.5"))
|
||||
JOB_BACKOFF_CAP_SECONDS = float(_env("JOB_BACKOFF_CAP_SECONDS", "30"))
|
||||
STAGING_RETENTION_SECONDS = int(_env("STAGING_RETENTION_SECONDS", "86400"))
|
||||
WORKER_CRASH_POINT = _env("WORKER_CRASH_POINT", "")
|
||||
TELEMETRY_ENABLED = _env("TELEMETRY_ENABLED", "1") == "1"
|
||||
OTEL_SERVICE_NAME = _env("OTEL_SERVICE_NAME", "messenger-api")
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT = _env("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318")
|
||||
TRACE_SAMPLE_RATIO = float(_env("TRACE_SAMPLE_RATIO", "1"))
|
||||
SERVICE_VERSION = _env("SERVICE_VERSION", "lab6")
|
||||
|
||||
|
||||
def lab_mode() -> bool:
|
||||
|
||||
+50
-18
@@ -7,10 +7,11 @@ import hashlib
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app import broker, config, db, pipeline, s3
|
||||
from app import broker, config, db, pipeline, s3, telemetry
|
||||
from app.errors import AppError
|
||||
from app.pipeline import PermanentJobError, TransientJobError
|
||||
from app.store import format_ts
|
||||
@@ -37,19 +38,27 @@ def backoff_seconds(attempt: int) -> float:
|
||||
return base * random.uniform(0.5, 1.5)
|
||||
|
||||
|
||||
def _trace_columns() -> tuple[str | None, str | None]:
|
||||
carrier = telemetry.current_carrier()
|
||||
return carrier.get("traceparent") or None, carrier.get("tracestate") or None
|
||||
|
||||
|
||||
async def insert_job(conn, attachment_id: UUID, created: datetime) -> UUID:
|
||||
job_id = uuid4()
|
||||
traceparent, tracestate = _trace_columns()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, pipeline_version, attempt, status,
|
||||
next_attempt_at, created_at, updated_at
|
||||
next_attempt_at, created_at, updated_at, traceparent, tracestate
|
||||
)
|
||||
VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3)
|
||||
VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3, $4, $5)
|
||||
""",
|
||||
job_id,
|
||||
attachment_id,
|
||||
created,
|
||||
traceparent,
|
||||
tracestate,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -78,7 +87,8 @@ async def publish_pending(limit: int = 20) -> int:
|
||||
async with conn.transaction():
|
||||
rows = await conn.fetch(
|
||||
"""
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at,
|
||||
traceparent, tracestate
|
||||
FROM attachment_jobs
|
||||
WHERE published_at IS NULL
|
||||
AND status = 'queued'
|
||||
@@ -90,7 +100,11 @@ async def publish_pending(limit: int = 20) -> int:
|
||||
limit,
|
||||
)
|
||||
for row in rows:
|
||||
await broker.publish_job(message_of(row))
|
||||
await broker.publish_job(
|
||||
message_of(row),
|
||||
traceparent=row["traceparent"],
|
||||
tracestate=row["tracestate"],
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE attachment_jobs SET published_at = now() WHERE job_id = $1",
|
||||
row["job_id"],
|
||||
@@ -445,6 +459,7 @@ async def load_attachment(attachment_id: UUID):
|
||||
|
||||
|
||||
async def process(job_id: UUID, pipeline_version: int) -> str:
|
||||
started = time.perf_counter()
|
||||
state, row = await claim(job_id, pipeline_version)
|
||||
if state != "claimed":
|
||||
return state
|
||||
@@ -452,15 +467,23 @@ async def process(job_id: UUID, pipeline_version: int) -> str:
|
||||
lease = row["lease_token"]
|
||||
try:
|
||||
await asyncio.wait_for(_effect(row, lease), config.JOB_TIMEOUT_SECONDS)
|
||||
outcome = "ready"
|
||||
except PermanentJobError as exc:
|
||||
await fail_job(job_id, lease, exc.code)
|
||||
return "failed"
|
||||
outcome = "failed"
|
||||
except (TransientJobError, asyncio.TimeoutError, AppError):
|
||||
return await schedule_retry(job_id, lease, "processing_failed")
|
||||
outcome = await schedule_retry(job_id, lease, "processing_failed")
|
||||
except Exception:
|
||||
logger.warning("job processing failed job_id=%s", job_id)
|
||||
return await schedule_retry(job_id, lease, "processing_failed")
|
||||
return "ready"
|
||||
outcome = await schedule_retry(job_id, lease, "processing_failed")
|
||||
elapsed = time.perf_counter() - started
|
||||
if outcome in ("ready", "failed", "retry", "lost"):
|
||||
telemetry.record_job(outcome, elapsed)
|
||||
if outcome == "ready":
|
||||
created = _aware(row["created_at"])
|
||||
if created is not None:
|
||||
telemetry.record_time_to_ready((datetime.now(timezone.utc) - created).total_seconds())
|
||||
return outcome
|
||||
|
||||
|
||||
async def _effect(row, lease: UUID) -> None:
|
||||
@@ -479,20 +502,24 @@ async def _effect(row, lease: UUID) -> None:
|
||||
os._exit(1)
|
||||
if fault == "fail_once":
|
||||
raise PermanentJobError("processing_failed")
|
||||
data = await s3.get_bytes(attachment["object_key"])
|
||||
with telemetry.span("s3.get", kind="client", attributes={"s3.operation": "get"}):
|
||||
data = await s3.get_bytes(attachment["object_key"])
|
||||
if len(data) != attachment["size_bytes"] or hashlib.sha256(data).hexdigest() != attachment["sha256"]:
|
||||
raise PermanentJobError("invalid_image")
|
||||
final_key = f"originals/{attachment['id']}"
|
||||
if attachment["object_key"] != final_key:
|
||||
await _intent(final_key)
|
||||
await s3.put_bytes(final_key, data, attachment["content_type"])
|
||||
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
|
||||
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": "original"}):
|
||||
await s3.put_bytes(final_key, data, attachment["content_type"])
|
||||
with telemetry.span("image.render"):
|
||||
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
|
||||
stored = []
|
||||
for name, (payload, content_type, width, height) in rendered.items():
|
||||
suffix = "webp" if content_type == "image/webp" else "jpg"
|
||||
key = f"variants/{attachment['id']}/v{version}/{name}.{suffix}"
|
||||
await _intent(key)
|
||||
await s3.put_bytes(key, payload, content_type)
|
||||
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": name}):
|
||||
await s3.put_bytes(key, payload, content_type)
|
||||
stored.append(
|
||||
{
|
||||
"name": name,
|
||||
@@ -511,7 +538,8 @@ async def _effect(row, lease: UUID) -> None:
|
||||
if fresh is not None and int(fresh["applied_pipeline_version"]) > version:
|
||||
stored = []
|
||||
final_key = ""
|
||||
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
|
||||
with telemetry.span("db.complete", kind="client"):
|
||||
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
|
||||
if not committed:
|
||||
raise TransientJobError("processing_failed")
|
||||
if stored and attachment["object_key"] != final_key and final_key:
|
||||
@@ -571,18 +599,21 @@ async def bump_pipeline(attachment_id: UUID) -> dict:
|
||||
return {"result": "missing"}
|
||||
version = int(current) + 1
|
||||
job_id = uuid4()
|
||||
traceparent, tracestate = _trace_columns()
|
||||
await conn.execute(
|
||||
"""
|
||||
INSERT INTO attachment_jobs (
|
||||
job_id, attachment_id, pipeline_version, attempt, status,
|
||||
next_attempt_at, created_at, updated_at
|
||||
next_attempt_at, created_at, updated_at, traceparent, tracestate
|
||||
)
|
||||
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4)
|
||||
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4, $5, $6)
|
||||
""",
|
||||
job_id,
|
||||
attachment_id,
|
||||
version,
|
||||
created,
|
||||
traceparent,
|
||||
tracestate,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
@@ -600,7 +631,8 @@ async def redeliver(job_id: UUID) -> dict:
|
||||
async with db.require().acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status
|
||||
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status,
|
||||
traceparent, tracestate
|
||||
FROM attachment_jobs
|
||||
WHERE job_id = $1
|
||||
""",
|
||||
@@ -608,7 +640,7 @@ async def redeliver(job_id: UUID) -> dict:
|
||||
)
|
||||
if row is None:
|
||||
return {"result": "missing"}
|
||||
await broker.publish_job(message_of(row))
|
||||
await broker.publish_job(message_of(row), traceparent=row["traceparent"], tracestate=row["tracestate"])
|
||||
return {
|
||||
"result": "published",
|
||||
"job_id": str(row["job_id"]),
|
||||
|
||||
+5
-7
@@ -1,7 +1,6 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
@@ -12,7 +11,7 @@ from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
from starlette.routing import Route
|
||||
|
||||
from app import attachments, config, db, jobs, rediscli
|
||||
from app import attachments, config, db, jobs, rediscli, telemetry
|
||||
from app.docs import openapi_json, swagger_ui
|
||||
from app.errors import AppError, error_response, from_app_error
|
||||
from app.middleware import RequestContextMiddleware
|
||||
@@ -76,13 +75,16 @@ async def startup() -> None:
|
||||
await rediscli.connect()
|
||||
attachments.start_sweeper()
|
||||
jobs.start_outbox()
|
||||
telemetry.start_probes()
|
||||
|
||||
|
||||
async def shutdown() -> None:
|
||||
await telemetry.stop_probes()
|
||||
await attachments.stop_sweeper()
|
||||
await jobs.stop_outbox()
|
||||
await rediscli.close()
|
||||
await db.close()
|
||||
telemetry.shutdown()
|
||||
|
||||
|
||||
def build_app() -> Starlette:
|
||||
@@ -125,11 +127,7 @@ def build_app() -> Starlette:
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, config.LOG_LEVEL.upper(), logging.INFO),
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
telemetry.configure_logging()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
+51
-21
@@ -1,11 +1,13 @@
|
||||
import logging
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import nullcontext
|
||||
|
||||
from starlette.datastructures import MutableHeaders
|
||||
from starlette.responses import Response
|
||||
from starlette.types import ASGIApp, Message, Receive, Scope, Send
|
||||
|
||||
from app import telemetry
|
||||
from app.config import INSTANCE_ID
|
||||
from app.errors import AppError, error_response, from_app_error
|
||||
|
||||
@@ -30,34 +32,62 @@ class RequestContextMiddleware:
|
||||
scope["state"] = raw_state
|
||||
raw_state["request_id"] = request_id
|
||||
path = scope.get("path", "")
|
||||
method = scope.get("method", "")
|
||||
started = time.perf_counter()
|
||||
status_code = 500
|
||||
record = telemetry.observe_http(path)
|
||||
route = telemetry.route_template(path)
|
||||
|
||||
async def send_wrapper(message: Message) -> None:
|
||||
nonlocal status_code
|
||||
if message["type"] == "http.response.start":
|
||||
status_code = int(message["status"])
|
||||
response_headers = MutableHeaders(scope=message)
|
||||
response_headers["X-Request-Id"] = request_id
|
||||
response_headers["X-Instance-Id"] = INSTANCE_ID
|
||||
await send(message)
|
||||
|
||||
app = scope.get("app")
|
||||
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
|
||||
if shutting_down and path not in ("/health/live", "/health/ready"):
|
||||
response: Response = error_response(503, "service is shutting down", request_id)
|
||||
await response(scope, receive, send_wrapper)
|
||||
return
|
||||
try:
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
except AppError as exc:
|
||||
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
|
||||
except Exception:
|
||||
logger.exception("request_id=%s unhandled error path=%s", request_id, path)
|
||||
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
|
||||
return
|
||||
elapsed_ms = (time.perf_counter() - started) * 1000
|
||||
logger.info(
|
||||
"request_id=%s method=%s path=%s duration_ms=%.2f",
|
||||
request_id,
|
||||
scope.get("method", ""),
|
||||
path,
|
||||
elapsed_ms,
|
||||
parent = telemetry.remote_context(headers.get("traceparent"), headers.get("tracestate"))
|
||||
span_cm = (
|
||||
telemetry.span(
|
||||
"%s %s" % (method, route),
|
||||
context=parent,
|
||||
kind="server",
|
||||
attributes={
|
||||
"http.request.method": method,
|
||||
"http.route": route,
|
||||
"http.request_id": request_id,
|
||||
},
|
||||
)
|
||||
if record
|
||||
else nullcontext(None)
|
||||
)
|
||||
with span_cm as current:
|
||||
app = scope.get("app")
|
||||
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
|
||||
try:
|
||||
if shutting_down and path not in ("/health/live", "/health/ready"):
|
||||
response: Response = error_response(503, "service is shutting down", request_id)
|
||||
await response(scope, receive, send_wrapper)
|
||||
else:
|
||||
await self.app(scope, receive, send_wrapper)
|
||||
except AppError as exc:
|
||||
status_code = exc.status
|
||||
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
|
||||
except Exception:
|
||||
status_code = 500
|
||||
logger.exception("request failed request_id=%s route=%s", request_id, route)
|
||||
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
|
||||
finally:
|
||||
if record:
|
||||
telemetry.finish_http_span(current, status_code)
|
||||
telemetry.record_http(method, route, status_code, time.perf_counter() - started)
|
||||
if record:
|
||||
logger.info(
|
||||
"request completed request_id=%s method=%s route=%s status=%s duration_ms=%.2f",
|
||||
request_id,
|
||||
method,
|
||||
route,
|
||||
status_code,
|
||||
(time.perf_counter() - started) * 1000,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
"""OTLP telemetry for the API and the worker.
|
||||
|
||||
Metric labels stay low-cardinality: method, route template, status class,
|
||||
job type, outcome, queue name. User, chat, message and attachment ids are
|
||||
never metric labels. Trace and log records may carry a job id so one upload
|
||||
can be found; passwords, tokens, message text and image bytes are not exported.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
|
||||
import psutil
|
||||
from opentelemetry import metrics, propagate, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
from app import config
|
||||
|
||||
logger = logging.getLogger("messenger.telemetry")
|
||||
|
||||
_HTTP_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
|
||||
_JOB_BUCKETS = (0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60)
|
||||
_READY_BUCKETS = (0.5, 1, 2, 5, 10, 30, 60, 120, 300)
|
||||
_JOB_TYPE = "attachment.process.v1"
|
||||
_QUEUE = "attachment.jobs"
|
||||
|
||||
_ROUTES = (
|
||||
(re.compile(r"^/api/v1/chats/[^/]+/messages$"), "/api/v1/chats/{chat_id}/messages"),
|
||||
(re.compile(r"^/api/v1/chats/[^/]+/attachments$"), "/api/v1/chats/{chat_id}/attachments"),
|
||||
(re.compile(r"^/api/v1/chats/[^/]+/uploads$"), "/api/v1/chats/{chat_id}/uploads"),
|
||||
(re.compile(r"^/api/v1/chats/[^/]+$"), "/api/v1/chats/{chat_id}"),
|
||||
(re.compile(r"^/api/v1/uploads/[^/]+/complete$"), "/api/v1/uploads/{upload_id}/complete"),
|
||||
(re.compile(r"^/api/v1/attachments/[^/]+/content$"), "/api/v1/attachments/{attachment_id}/content"),
|
||||
(re.compile(r"^/api/v1/attachments/[^/]+$"), "/api/v1/attachments/{attachment_id}"),
|
||||
(re.compile(r"^/api/v1/_lab/attachments/[^/]+/jobs$"), "/api/v1/_lab/attachments/{attachment_id}/jobs"),
|
||||
(re.compile(r"^/api/v1/_lab/attachments/[^/]+/pipelines$"), "/api/v1/_lab/attachments/{attachment_id}/pipelines"),
|
||||
(re.compile(r"^/api/v1/_lab/attachments/[^/]+/replay$"), "/api/v1/_lab/attachments/{attachment_id}/replay"),
|
||||
(re.compile(r"^/api/v1/_lab/jobs/[^/]+/redeliver$"), "/api/v1/_lab/jobs/{job_id}/redeliver"),
|
||||
)
|
||||
_SECRET = re.compile(r"(?i)(authorization|password|token|secret|session)([\"']?\s*[:=]\s*[\"']?)(\S+)")
|
||||
|
||||
_ready = False
|
||||
_tracer = None
|
||||
_http_requests = None
|
||||
_http_duration = None
|
||||
_jobs = None
|
||||
_job_duration = None
|
||||
_time_to_ready = None
|
||||
_log_handler = None
|
||||
_providers = []
|
||||
_process = psutil.Process()
|
||||
_process.cpu_percent(interval=None)
|
||||
_inflight = 0
|
||||
_queue_depth = 0
|
||||
_queue_oldest = 0.0
|
||||
_probe_task: asyncio.Task | None = None
|
||||
|
||||
_KIND = {
|
||||
"internal": SpanKind.INTERNAL,
|
||||
"server": SpanKind.SERVER,
|
||||
"client": SpanKind.CLIENT,
|
||||
"producer": SpanKind.PRODUCER,
|
||||
"consumer": SpanKind.CONSUMER,
|
||||
}
|
||||
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def __init__(self, service_name: str) -> None:
|
||||
super().__init__()
|
||||
self.service_name = service_name
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
span = trace.get_current_span()
|
||||
ctx = span.get_span_context()
|
||||
payload = {
|
||||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime(record.created)),
|
||||
"severity": record.levelname,
|
||||
"service.name": self.service_name,
|
||||
"event": _SECRET.sub(r"\1\2[redacted]", record.getMessage()),
|
||||
"logger": record.name,
|
||||
}
|
||||
if ctx.is_valid:
|
||||
payload["trace_id"] = format(ctx.trace_id, "032x")
|
||||
payload["span_id"] = format(ctx.span_id, "016x")
|
||||
if record.exc_info:
|
||||
payload["exception"] = _SECRET.sub(r"\1\2[redacted]", self.formatException(record.exc_info))
|
||||
return json.dumps(payload, ensure_ascii=False)
|
||||
|
||||
|
||||
def route_template(path: str) -> str:
|
||||
for pattern, template in _ROUTES:
|
||||
if pattern.match(path):
|
||||
return template
|
||||
return path
|
||||
|
||||
|
||||
def observe_http(path: str) -> bool:
|
||||
return path not in ("/health/live", "/health/ready", "/docs", "/openapi.json")
|
||||
|
||||
|
||||
def status_class(code: int) -> str:
|
||||
return "%sxx" % (int(code) // 100)
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
setup()
|
||||
root = logging.getLogger()
|
||||
root.handlers.clear()
|
||||
root.setLevel(getattr(logging, config.LOG_LEVEL.upper(), logging.INFO))
|
||||
stream = logging.StreamHandler(sys.stdout)
|
||||
stream.setFormatter(JsonFormatter(config.OTEL_SERVICE_NAME))
|
||||
root.addHandler(stream)
|
||||
if _log_handler is not None:
|
||||
root.addHandler(_log_handler)
|
||||
logging.getLogger("opentelemetry").setLevel(logging.ERROR)
|
||||
|
||||
|
||||
def setup() -> None:
|
||||
global _ready, _tracer, _http_requests, _http_duration, _jobs, _job_duration, _time_to_ready, _log_handler
|
||||
if _ready:
|
||||
return
|
||||
_ready = True
|
||||
if not config.TELEMETRY_ENABLED:
|
||||
logger.info("telemetry disabled")
|
||||
return
|
||||
resource = Resource.create(
|
||||
{
|
||||
"service.name": config.OTEL_SERVICE_NAME,
|
||||
"service.version": config.SERVICE_VERSION,
|
||||
"service.instance.id": config.INSTANCE_ID,
|
||||
"deployment.environment.name": "lab",
|
||||
}
|
||||
)
|
||||
ratio = min(1.0, max(0.0, config.TRACE_SAMPLE_RATIO))
|
||||
tracer_provider = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased(ratio)))
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(
|
||||
OTLPSpanExporter(endpoint=_signal_endpoint("traces"), timeout=5),
|
||||
max_queue_size=2048,
|
||||
schedule_delay_millis=5000,
|
||||
max_export_batch_size=512,
|
||||
export_timeout_millis=5000,
|
||||
)
|
||||
)
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
_tracer = trace.get_tracer("messenger", config.SERVICE_VERSION)
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=_signal_endpoint("metrics"), timeout=5),
|
||||
export_interval_millis=10000,
|
||||
export_timeout_millis=5000,
|
||||
)
|
||||
meter_provider = MeterProvider(
|
||||
resource=resource,
|
||||
metric_readers=[reader],
|
||||
views=[
|
||||
View(
|
||||
instrument_name="messenger.http.request.duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(_HTTP_BUCKETS),
|
||||
),
|
||||
View(
|
||||
instrument_name="messenger.job.duration",
|
||||
aggregation=ExplicitBucketHistogramAggregation(_JOB_BUCKETS),
|
||||
),
|
||||
View(
|
||||
instrument_name="messenger.time_to_ready",
|
||||
aggregation=ExplicitBucketHistogramAggregation(_READY_BUCKETS),
|
||||
),
|
||||
],
|
||||
)
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
meter = metrics.get_meter("messenger", config.SERVICE_VERSION)
|
||||
_http_requests = meter.create_counter("messenger.http.requests", unit="1")
|
||||
_http_duration = meter.create_histogram("messenger.http.request.duration", unit="s")
|
||||
_jobs = meter.create_counter("messenger.jobs", unit="1")
|
||||
_job_duration = meter.create_histogram("messenger.job.duration", unit="s")
|
||||
_time_to_ready = meter.create_histogram("messenger.time_to_ready", unit="s")
|
||||
meter.create_observable_gauge("messenger.db.pool.used", callbacks=[_pool_used])
|
||||
meter.create_observable_gauge("messenger.db.pool.waiting", callbacks=[_pool_waiting])
|
||||
meter.create_observable_gauge("process.cpu.percent", callbacks=[_cpu])
|
||||
meter.create_observable_gauge("process.memory.rss", unit="By", callbacks=[_rss])
|
||||
if config.OTEL_SERVICE_NAME == "messenger-api":
|
||||
meter.create_observable_gauge("messenger.queue.depth", callbacks=[_depth])
|
||||
meter.create_observable_gauge("messenger.queue.oldest_age", unit="s", callbacks=[_oldest])
|
||||
if config.OTEL_SERVICE_NAME == "messenger-worker":
|
||||
meter.create_observable_gauge("messenger.worker.busy", callbacks=[_busy])
|
||||
meter.create_observable_gauge("messenger.worker.capacity", callbacks=[_capacity])
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(
|
||||
BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=_signal_endpoint("logs"), timeout=5),
|
||||
max_queue_size=2048,
|
||||
schedule_delay_millis=5000,
|
||||
max_export_batch_size=512,
|
||||
export_timeout_millis=5000,
|
||||
)
|
||||
)
|
||||
set_logger_provider(logger_provider)
|
||||
_log_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||
_providers.extend([tracer_provider, meter_provider, logger_provider])
|
||||
|
||||
|
||||
def shutdown() -> None:
|
||||
for provider in _providers:
|
||||
try:
|
||||
provider.shutdown()
|
||||
except Exception:
|
||||
logger.warning("telemetry shutdown failed")
|
||||
_providers.clear()
|
||||
|
||||
|
||||
def _signal_endpoint(signal: str) -> str:
|
||||
base = config.OTEL_EXPORTER_OTLP_ENDPOINT.rstrip("/")
|
||||
return "%s/v1/%s" % (base, signal)
|
||||
|
||||
|
||||
def current_carrier() -> dict:
|
||||
if _tracer is None:
|
||||
return {}
|
||||
carrier: dict = {}
|
||||
propagate.inject(carrier)
|
||||
return carrier
|
||||
|
||||
|
||||
def remote_context(traceparent: str | None, tracestate: str | None = None):
|
||||
carrier = {}
|
||||
if traceparent:
|
||||
carrier["traceparent"] = traceparent
|
||||
if tracestate:
|
||||
carrier["tracestate"] = tracestate
|
||||
if not carrier:
|
||||
return None
|
||||
return propagate.extract(carrier)
|
||||
|
||||
|
||||
def carrier_from_headers(headers) -> dict:
|
||||
carrier = {}
|
||||
if not headers:
|
||||
return carrier
|
||||
for key in ("traceparent", "tracestate"):
|
||||
value = headers.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, bytes):
|
||||
value = value.decode("latin1")
|
||||
carrier[key] = str(value)
|
||||
return carrier
|
||||
|
||||
|
||||
@contextmanager
|
||||
def span(name: str, context=None, kind: str = "internal", attributes: dict | None = None):
|
||||
if _tracer is None:
|
||||
yield None
|
||||
return
|
||||
kwargs = {"kind": _KIND.get(kind, SpanKind.INTERNAL)}
|
||||
if context is not None:
|
||||
kwargs["context"] = context
|
||||
with _tracer.start_as_current_span(name, **kwargs) as current:
|
||||
if attributes:
|
||||
for key, value in attributes.items():
|
||||
if value is not None:
|
||||
current.set_attribute(key, value)
|
||||
yield current
|
||||
|
||||
|
||||
def finish_http_span(current, status_code: int) -> None:
|
||||
if current is None:
|
||||
return
|
||||
current.set_attribute("http.response.status_code", int(status_code))
|
||||
if status_code >= 500:
|
||||
current.set_status(Status(StatusCode.ERROR))
|
||||
else:
|
||||
current.set_status(Status(StatusCode.OK))
|
||||
|
||||
|
||||
def record_http(method: str, route: str, status_code: int, duration_seconds: float) -> None:
|
||||
if _http_requests is None:
|
||||
return
|
||||
attributes = {
|
||||
"method": method,
|
||||
"route": route,
|
||||
"status_class": status_class(status_code),
|
||||
}
|
||||
_http_requests.add(1, attributes)
|
||||
_http_duration.record(max(0.0, duration_seconds), attributes)
|
||||
|
||||
|
||||
def record_job(outcome: str, duration_seconds: float) -> None:
|
||||
if _jobs is None:
|
||||
return
|
||||
attributes = {"job_type": _JOB_TYPE, "outcome": outcome}
|
||||
_jobs.add(1, attributes)
|
||||
_job_duration.record(max(0.0, duration_seconds), attributes)
|
||||
|
||||
|
||||
def record_time_to_ready(duration_seconds: float) -> None:
|
||||
if _time_to_ready is None:
|
||||
return
|
||||
_time_to_ready.record(max(0.0, duration_seconds), {"job_type": _JOB_TYPE})
|
||||
|
||||
|
||||
def worker_enter() -> None:
|
||||
global _inflight
|
||||
_inflight += 1
|
||||
|
||||
|
||||
def worker_leave() -> None:
|
||||
global _inflight
|
||||
_inflight = max(0, _inflight - 1)
|
||||
|
||||
|
||||
def start_probes() -> None:
|
||||
global _probe_task
|
||||
if _tracer is None or config.OTEL_SERVICE_NAME != "messenger-api":
|
||||
return
|
||||
if _probe_task is None or _probe_task.done():
|
||||
_probe_task = asyncio.create_task(_probe_loop())
|
||||
|
||||
|
||||
async def stop_probes() -> None:
|
||||
global _probe_task
|
||||
task = _probe_task
|
||||
_probe_task = None
|
||||
if task is None:
|
||||
return
|
||||
task.cancel()
|
||||
try:
|
||||
await task
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
|
||||
|
||||
async def _probe_loop() -> None:
|
||||
from app import db
|
||||
|
||||
global _queue_depth, _queue_oldest
|
||||
while True:
|
||||
try:
|
||||
async with db.require().acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
SELECT
|
||||
count(*) FILTER (WHERE status IN ('queued', 'processing')) AS depth,
|
||||
COALESCE(
|
||||
EXTRACT(EPOCH FROM (now() - min(created_at) FILTER (WHERE status = 'queued'))),
|
||||
0
|
||||
) AS oldest
|
||||
FROM attachment_jobs
|
||||
"""
|
||||
)
|
||||
_queue_depth = int(row["depth"] or 0)
|
||||
_queue_oldest = float(row["oldest"] or 0)
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except Exception:
|
||||
logger.warning("queue probe failed")
|
||||
await asyncio.sleep(5)
|
||||
|
||||
|
||||
def _observation(value, attributes=None):
|
||||
from opentelemetry.metrics import Observation
|
||||
|
||||
return [Observation(value, attributes or {})]
|
||||
|
||||
|
||||
def _pool_used(_options):
|
||||
from app import db
|
||||
|
||||
pool = db.pool
|
||||
if pool is None:
|
||||
return _observation(0)
|
||||
return _observation(max(0, pool.get_size() - pool.get_idle_size()))
|
||||
|
||||
|
||||
def _pool_waiting(_options):
|
||||
from app import db
|
||||
|
||||
pool = db.pool
|
||||
if pool is None:
|
||||
return _observation(0)
|
||||
waiters = getattr(pool, "_waiters", None)
|
||||
if waiters is not None:
|
||||
return _observation(len(waiters))
|
||||
queue = getattr(pool, "_queue", None)
|
||||
getters = getattr(queue, "_getters", None)
|
||||
if getters is not None:
|
||||
return _observation(len(getters))
|
||||
return _observation(0)
|
||||
|
||||
|
||||
def _depth(_options):
|
||||
return _observation(_queue_depth, {"queue": _QUEUE})
|
||||
|
||||
|
||||
def _oldest(_options):
|
||||
return _observation(_queue_oldest, {"queue": _QUEUE})
|
||||
|
||||
|
||||
def _busy(_options):
|
||||
return _observation(_inflight)
|
||||
|
||||
|
||||
def _capacity(_options):
|
||||
return _observation(config.WORKER_CONCURRENCY)
|
||||
|
||||
|
||||
def _cpu(_options):
|
||||
return _observation(_process.cpu_percent(interval=None))
|
||||
|
||||
|
||||
def _rss(_options):
|
||||
return _observation(_process.memory_info().rss)
|
||||
+45
-30
@@ -5,50 +5,64 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
from uuid import UUID
|
||||
|
||||
import aio_pika
|
||||
|
||||
from app import broker, config, db, jobs
|
||||
from app import broker, config, db, jobs, telemetry
|
||||
from app.broker import payload_from
|
||||
|
||||
logger = logging.getLogger("messenger.worker")
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, config.LOG_LEVEL.upper(), logging.INFO),
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
telemetry.configure_logging()
|
||||
|
||||
|
||||
async def _settle(message: aio_pika.IncomingMessage) -> None:
|
||||
try:
|
||||
payload = payload_from(message.body)
|
||||
job_id = UUID(payload["job_id"])
|
||||
pipeline_version = int(payload["pipeline_version"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
logger.warning("dropping a job message that does not match the schema")
|
||||
await message.ack()
|
||||
return
|
||||
try:
|
||||
waits = 0
|
||||
while True:
|
||||
state = await jobs.process(job_id, pipeline_version)
|
||||
if state == "busy":
|
||||
waits += 1
|
||||
if waits > config.JOB_LEASE_SECONDS + 5:
|
||||
await message.reject(requeue=True)
|
||||
carrier = telemetry.carrier_from_headers(message.headers)
|
||||
parent = telemetry.remote_context(carrier.get("traceparent"), carrier.get("tracestate"))
|
||||
with telemetry.span(
|
||||
"attachment.job.consume",
|
||||
context=parent,
|
||||
kind="consumer",
|
||||
attributes={
|
||||
"messaging.system": "rabbitmq",
|
||||
"messaging.destination.name": broker.QUEUE,
|
||||
"messaging.operation": "consume",
|
||||
},
|
||||
) as current:
|
||||
telemetry.worker_enter()
|
||||
try:
|
||||
try:
|
||||
payload = payload_from(message.body)
|
||||
job_id = UUID(payload["job_id"])
|
||||
pipeline_version = int(payload["pipeline_version"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
logger.warning("dropping a job message that does not match the schema")
|
||||
await message.ack()
|
||||
return
|
||||
if current is not None:
|
||||
current.set_attribute("job.id", str(job_id))
|
||||
try:
|
||||
waits = 0
|
||||
while True:
|
||||
state = await jobs.process(job_id, pipeline_version)
|
||||
if state == "busy":
|
||||
waits += 1
|
||||
if waits > config.JOB_LEASE_SECONDS + 5:
|
||||
await message.reject(requeue=True)
|
||||
return
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
logger.info("job settled job_id=%s state=%s", job_id, state)
|
||||
await message.ack()
|
||||
return
|
||||
await asyncio.sleep(1)
|
||||
continue
|
||||
await message.ack()
|
||||
return
|
||||
except Exception:
|
||||
logger.warning("job settle failed job_id=%s", payload.get("job_id"))
|
||||
await message.reject(requeue=True)
|
||||
except Exception:
|
||||
logger.warning("job settle failed job_id=%s", payload.get("job_id"))
|
||||
await message.reject(requeue=True)
|
||||
finally:
|
||||
telemetry.worker_leave()
|
||||
|
||||
|
||||
async def _reap_loop(stop: asyncio.Event) -> None:
|
||||
@@ -86,6 +100,7 @@ async def serve() -> None:
|
||||
pass
|
||||
await broker.close()
|
||||
await db.close()
|
||||
telemetry.shutdown()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
|
||||
Reference in New Issue
Block a user