449 lines
14 KiB
Python
449 lines
14 KiB
Python
"""OpenTelemetry: traces, metrics, structured logs. Секреты и тела сообщений не экспортируются."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
import os
|
|
import socket
|
|
import time
|
|
from contextlib import contextmanager
|
|
|
|
from opentelemetry import metrics, 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.metrics import CallbackOptions, Observation
|
|
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 ALWAYS_ON, ParentBased, TraceIdRatioBased
|
|
from opentelemetry.trace import Link, SpanKind, Status, StatusCode
|
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
|
|
|
SERVICE_VERSION = "lab6"
|
|
PROPAGATOR = TraceContextTextMapPropagator()
|
|
_CONFIGURED = False
|
|
_TRACER = None
|
|
_METER = None
|
|
_STATE = {
|
|
"queue_depth": {},
|
|
"oldest_job_age": {},
|
|
"db_pool_used": 0.0,
|
|
"db_pool_waiting": 0.0,
|
|
"worker_busy": 0.0,
|
|
"worker_capacity": 0.0,
|
|
"process_cpu": 0.0,
|
|
"process_rss": 0.0,
|
|
}
|
|
|
|
http_requests = None
|
|
http_duration = None
|
|
jobs_processed = None
|
|
job_duration = None
|
|
e2e_ready = None
|
|
|
|
|
|
def _endpoint():
|
|
return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
|
|
|
|
|
def _headers():
|
|
raw = os.environ.get("OTEL_EXPORTER_OTLP_HEADERS", "")
|
|
if not raw:
|
|
return {}
|
|
out = {}
|
|
for part in raw.split(","):
|
|
if "=" not in part:
|
|
continue
|
|
key, value = part.split("=", 1)
|
|
out[key.strip()] = value.strip()
|
|
return out
|
|
|
|
|
|
def _sampler():
|
|
ratio = os.environ.get("OTEL_TRACES_SAMPLER_ARG", "1.0")
|
|
try:
|
|
value = float(ratio)
|
|
except ValueError:
|
|
value = 1.0
|
|
if value >= 1.0:
|
|
return ParentBased(ALWAYS_ON)
|
|
if value <= 0.0:
|
|
return ParentBased(TraceIdRatioBased(0.0))
|
|
return ParentBased(TraceIdRatioBased(value))
|
|
|
|
|
|
def _resource(service_name):
|
|
attrs = {
|
|
"service.name": service_name,
|
|
"service.version": os.environ.get("SERVICE_VERSION", SERVICE_VERSION),
|
|
"service.instance.id": socket.gethostname(),
|
|
"deployment.environment.name": os.environ.get("APP_ENV", "lab"),
|
|
}
|
|
extra = os.environ.get("OTEL_RESOURCE_ATTRIBUTES", "")
|
|
for part in extra.split(","):
|
|
if "=" not in part:
|
|
continue
|
|
key, value = part.split("=", 1)
|
|
key = key.strip()
|
|
value = value.strip()
|
|
if key and value and key not in attrs:
|
|
attrs[key] = value
|
|
return Resource.create(attrs)
|
|
|
|
|
|
def _obs_queue_depth(_options: CallbackOptions):
|
|
for name, value in list(_STATE["queue_depth"].items()):
|
|
yield Observation(float(value), {"messaging.destination.name": name})
|
|
|
|
|
|
def _obs_oldest(_options: CallbackOptions):
|
|
for name, value in list(_STATE["oldest_job_age"].items()):
|
|
yield Observation(float(value), {"messaging.destination.name": name})
|
|
|
|
|
|
def _obs_db_used(_options: CallbackOptions):
|
|
yield Observation(float(_STATE["db_pool_used"]))
|
|
|
|
|
|
def _obs_db_waiting(_options: CallbackOptions):
|
|
yield Observation(float(_STATE["db_pool_waiting"]))
|
|
|
|
|
|
def _obs_worker_busy(_options: CallbackOptions):
|
|
yield Observation(float(_STATE["worker_busy"]))
|
|
|
|
|
|
def _obs_worker_capacity(_options: CallbackOptions):
|
|
yield Observation(float(_STATE["worker_capacity"]))
|
|
|
|
|
|
def _obs_cpu(_options: CallbackOptions):
|
|
yield Observation(float(_STATE["process_cpu"]))
|
|
|
|
|
|
def _obs_rss(_options: CallbackOptions):
|
|
yield Observation(float(_STATE["process_rss"]))
|
|
|
|
|
|
def attach_log_handler(logger_provider):
|
|
handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
|
root = logging.getLogger()
|
|
root.setLevel(logging.INFO)
|
|
if not any(isinstance(item, LoggingHandler) for item in root.handlers):
|
|
root.addHandler(handler)
|
|
for name in ("messenger", "worker", "uvicorn", "uvicorn.error", "uvicorn.access"):
|
|
logging.getLogger(name).setLevel(logging.INFO)
|
|
|
|
|
|
def setup(service_name):
|
|
global _CONFIGURED, _TRACER, _METER
|
|
global http_requests, http_duration, jobs_processed, job_duration, e2e_ready
|
|
if _CONFIGURED:
|
|
# uvicorn мог переустановить handlers после импорта модуля
|
|
provider = getattr(setup, "_logger_provider", None)
|
|
if provider is not None:
|
|
attach_log_handler(provider)
|
|
return
|
|
if os.environ.get("OTEL_SDK_DISABLED", "").lower() in ("1", "true", "yes"):
|
|
_CONFIGURED = True
|
|
return
|
|
|
|
resource = _resource(service_name)
|
|
base = _endpoint()
|
|
hdr = _headers()
|
|
|
|
provider = TracerProvider(resource=resource, sampler=_sampler())
|
|
provider.add_span_processor(
|
|
BatchSpanProcessor(
|
|
OTLPSpanExporter(endpoint=f"{base}/v1/traces", headers=hdr, timeout=5),
|
|
max_queue_size=512,
|
|
max_export_batch_size=128,
|
|
schedule_delay_millis=2000,
|
|
export_timeout_millis=5000,
|
|
)
|
|
)
|
|
trace.set_tracer_provider(provider)
|
|
_TRACER = trace.get_tracer("messenger", SERVICE_VERSION)
|
|
|
|
reader = PeriodicExportingMetricReader(
|
|
OTLPMetricExporter(endpoint=f"{base}/v1/metrics", headers=hdr, timeout=5),
|
|
export_interval_millis=10000,
|
|
export_timeout_millis=5000,
|
|
)
|
|
views = (
|
|
View(
|
|
instrument_name="messenger.http.duration",
|
|
aggregation=ExplicitBucketHistogramAggregation(
|
|
[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0]
|
|
),
|
|
),
|
|
View(
|
|
instrument_name="messenger.jobs.duration",
|
|
aggregation=ExplicitBucketHistogramAggregation(
|
|
[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 15.0, 30.0, 60.0]
|
|
),
|
|
),
|
|
View(
|
|
instrument_name="messenger.attachment.time_to_ready",
|
|
aggregation=ExplicitBucketHistogramAggregation(
|
|
[0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0]
|
|
),
|
|
),
|
|
)
|
|
meter_provider = MeterProvider(resource=resource, metric_readers=[reader], views=views)
|
|
metrics.set_meter_provider(meter_provider)
|
|
_METER = metrics.get_meter("messenger", SERVICE_VERSION)
|
|
|
|
logger_provider = LoggerProvider(resource=resource)
|
|
logger_provider.add_log_record_processor(
|
|
BatchLogRecordProcessor(
|
|
OTLPLogExporter(endpoint=f"{base}/v1/logs", headers=hdr, timeout=5),
|
|
max_queue_size=512,
|
|
max_export_batch_size=128,
|
|
schedule_delay_millis=2000,
|
|
export_timeout_millis=5000,
|
|
)
|
|
)
|
|
set_logger_provider(logger_provider)
|
|
setup._logger_provider = logger_provider
|
|
attach_log_handler(logger_provider)
|
|
|
|
http_requests = _METER.create_counter(
|
|
"messenger.http.requests",
|
|
unit="1",
|
|
description="HTTP requests by method, route template and status class",
|
|
)
|
|
http_duration = _METER.create_histogram(
|
|
"messenger.http.duration",
|
|
unit="s",
|
|
description="HTTP request duration in seconds",
|
|
)
|
|
jobs_processed = _METER.create_counter(
|
|
"messenger.jobs.processed",
|
|
unit="1",
|
|
description="Jobs finished by type and outcome",
|
|
)
|
|
job_duration = _METER.create_histogram(
|
|
"messenger.jobs.duration",
|
|
unit="s",
|
|
description="Job processing duration in seconds",
|
|
)
|
|
e2e_ready = _METER.create_histogram(
|
|
"messenger.attachment.time_to_ready",
|
|
unit="s",
|
|
description="Seconds from durable acceptance to ready",
|
|
)
|
|
_METER.create_observable_up_down_counter(
|
|
"messenger.queue.depth",
|
|
callbacks=[_obs_queue_depth],
|
|
unit="1",
|
|
description="Approximate broker queue depth",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.queue.oldest_job_age",
|
|
callbacks=[_obs_oldest],
|
|
unit="s",
|
|
description="Age of the oldest unfinished job",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.db.pool.used",
|
|
callbacks=[_obs_db_used],
|
|
unit="1",
|
|
description="Checked-out DB pool connections",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.db.pool.waiting",
|
|
callbacks=[_obs_db_waiting],
|
|
unit="1",
|
|
description="Waiters for a DB pool connection",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.worker.busy",
|
|
callbacks=[_obs_worker_busy],
|
|
unit="1",
|
|
description="Busy worker slots",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.worker.capacity",
|
|
callbacks=[_obs_worker_capacity],
|
|
unit="1",
|
|
description="Configured worker concurrency",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.process.cpu_seconds",
|
|
callbacks=[_obs_cpu],
|
|
unit="s",
|
|
description="Process user+system CPU seconds",
|
|
)
|
|
_METER.create_observable_gauge(
|
|
"messenger.process.rss_bytes",
|
|
callbacks=[_obs_rss],
|
|
unit="By",
|
|
description="Process RSS bytes",
|
|
)
|
|
_CONFIGURED = True
|
|
|
|
|
|
def tracer():
|
|
return _TRACER or trace.get_tracer("messenger", SERVICE_VERSION)
|
|
|
|
|
|
def status_class(code):
|
|
return f"{int(code) // 100}xx"
|
|
|
|
|
|
def route_template(path):
|
|
if path in ("/health/live", "/health/ready"):
|
|
return path
|
|
parts = [p for p in path.strip("/").split("/") if p]
|
|
if len(parts) >= 3 and parts[0] == "api" and parts[1] == "v1":
|
|
if parts[2] == "users" and len(parts) == 3:
|
|
return "/api/v1/users"
|
|
if parts[2] == "users" and len(parts) == 4 and parts[3] == "me":
|
|
return "/api/v1/users/me"
|
|
if parts[2] == "auth" and len(parts) >= 4 and parts[3] == "sessions":
|
|
if len(parts) == 4:
|
|
return "/api/v1/auth/sessions"
|
|
return "/api/v1/auth/sessions/current"
|
|
if parts[2] == "chats" and len(parts) == 3:
|
|
return "/api/v1/chats"
|
|
if parts[2] == "chats" and len(parts) == 4:
|
|
return "/api/v1/chats/{chat_id}"
|
|
if parts[2] == "chats" and len(parts) == 5 and parts[4] == "messages":
|
|
return "/api/v1/chats/{chat_id}/messages"
|
|
if parts[2] == "chats" and len(parts) == 5 and parts[4] == "attachments":
|
|
return "/api/v1/chats/{chat_id}/attachments"
|
|
if parts[2] == "attachments" and len(parts) == 4:
|
|
return "/api/v1/attachments/{attachment_id}"
|
|
if parts[2] == "attachments" and len(parts) == 5 and parts[4] == "content":
|
|
return "/api/v1/attachments/{attachment_id}/content"
|
|
return "other"
|
|
|
|
|
|
def record_http(method, path, status, duration_s):
|
|
if http_requests is None:
|
|
return
|
|
if path in ("/health/live", "/health/ready"):
|
|
return
|
|
route = route_template(path)
|
|
attrs = {
|
|
"http.request.method": method,
|
|
"http.route": route,
|
|
"http.response.status_class": status_class(status),
|
|
}
|
|
http_requests.add(1, attrs)
|
|
http_duration.record(duration_s, attrs)
|
|
|
|
|
|
def inject_trace(carrier):
|
|
PROPAGATOR.inject(carrier)
|
|
return carrier
|
|
|
|
|
|
def extract_context(carrier):
|
|
return PROPAGATOR.extract(carrier)
|
|
|
|
|
|
def current_trace_fields():
|
|
span = trace.get_current_span()
|
|
ctx = span.get_span_context()
|
|
if not ctx.is_valid:
|
|
return {}, None, None
|
|
carrier = {}
|
|
inject_trace(carrier)
|
|
return carrier, format(ctx.trace_id, "032x"), format(ctx.span_id, "016x")
|
|
|
|
|
|
def structured_log(logger, event, level=logging.INFO, **fields):
|
|
_carrier, trace_id, span_id = current_trace_fields()
|
|
payload = {
|
|
"event": event,
|
|
"service.name": os.environ.get("OTEL_SERVICE_NAME", "messenger"),
|
|
}
|
|
if trace_id:
|
|
payload["trace_id"] = trace_id
|
|
if span_id:
|
|
payload["span_id"] = span_id
|
|
for key, value in fields.items():
|
|
if value is None:
|
|
continue
|
|
if key in ("password", "token", "authorization", "body", "text", "bytes"):
|
|
continue
|
|
payload[key] = value
|
|
logger.log(level, json.dumps(payload, ensure_ascii=False, sort_keys=True))
|
|
|
|
|
|
@contextmanager
|
|
def start_span(name, kind=SpanKind.INTERNAL, attributes=None, links=None, context=None):
|
|
attrs = dict(attributes or {})
|
|
span = tracer().start_span(name, context=context, kind=kind, attributes=attrs, links=links or [])
|
|
token = trace.use_span(span, end_on_exit=True)
|
|
token.__enter__()
|
|
try:
|
|
yield span
|
|
except Exception as exc:
|
|
span.record_exception(exc)
|
|
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
|
raise
|
|
finally:
|
|
token.__exit__(None, None, None)
|
|
|
|
|
|
def link_from_carrier(carrier):
|
|
ctx = extract_context(carrier)
|
|
span_ctx = trace.get_current_span(ctx).get_span_context()
|
|
if span_ctx.is_valid:
|
|
return [Link(span_ctx)]
|
|
return []
|
|
|
|
|
|
def observe_process():
|
|
try:
|
|
import resource
|
|
|
|
usage = resource.getrusage(resource.RUSAGE_SELF)
|
|
_STATE["process_rss"] = float(usage.ru_maxrss) * 1024.0
|
|
_STATE["process_cpu"] = float(usage.ru_utime + usage.ru_stime)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def set_pool_stats(used, waiting):
|
|
_STATE["db_pool_used"] = float(used)
|
|
_STATE["db_pool_waiting"] = float(waiting)
|
|
|
|
|
|
def set_worker_stats(busy, capacity):
|
|
_STATE["worker_busy"] = float(busy)
|
|
_STATE["worker_capacity"] = float(capacity)
|
|
|
|
|
|
def set_queue_stats(name, depth, oldest_age_s):
|
|
_STATE["queue_depth"][name] = int(depth)
|
|
_STATE["oldest_job_age"][name] = float(oldest_age_s)
|
|
|
|
|
|
def record_job(outcome, duration_s, job_type="attachment.process.v1"):
|
|
if jobs_processed is None:
|
|
return
|
|
attrs = {"job.type": job_type, "job.outcome": outcome}
|
|
jobs_processed.add(1, attrs)
|
|
job_duration.record(duration_s, attrs)
|
|
|
|
|
|
def record_time_to_ready(seconds):
|
|
if e2e_ready is None:
|
|
return
|
|
e2e_ready.record(float(seconds), {"job.type": "attachment.process.v1"})
|
|
|
|
|
|
def now_monotonic():
|
|
return time.perf_counter()
|