Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,13 @@ CONSERVER_START_METHOD=


# ── OpenTelemetry ─────────────────────────────────────────────────────────────
# Leave OTEL_EXPORTER_OTLP_ENDPOINT blank to disable tracing.
# Leave OTEL_EXPORTER_OTLP_ENDPOINT blank to disable all export (traces and metrics).
# OTEL_EXPORTER_OTLP_PROTOCOL is honored by both: grpc or http/protobuf. When it is unset the
# server uses grpc. With http/protobuf the server appends /v1/traces and /v1/metrics to the
# endpoint; set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT or OTEL_EXPORTER_OTLP_METRICS_ENDPOINT to
# override either full URL. Langfuse accepts traces only, so use a collector to also send metrics.
# Spans carry tenant.id and call.session_id on the chain span only, never on metrics. JSON logs
# carry trace_id and span_id inside a span. No vCon content is added to spans or logs.
#
# Local Langfuse (add 'langfuse' to COMPOSE_PROFILES, then use pre-seeded creds):
# OTEL_EXPORTER_OTLP_ENDPOINT=http://langfuse-server:3000/api/public/otel
Expand Down
34 changes: 34 additions & 0 deletions common/lib/json_log_formatter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""JSON log formatter that carries the active trace and span ids."""

import os

from pythonjsonlogger.jsonlogger import JsonFormatter


def _is_set(hex_id):
"""The instrumentation writes "0" (or all zeros) when no span is active."""
try:
return bool(hex_id) and int(hex_id, 16) != 0
except (TypeError, ValueError):
return False


class TraceJsonFormatter(JsonFormatter):
"""JsonFormatter plus ``trace_id`` and ``span_id``.

The ids come from the OpenTelemetry logging instrumentation, which stamps ``otelTraceID`` and
``otelSpanID`` on every record (see ``lib.logging_utils``). Outside a span, with no
OTEL_EXPORTER_OTLP_ENDPOINT set, or with the instrumentation off, the two fields are left out and every other field is unchanged.
"""

def add_fields(self, log_record, record, message_dict):
super().add_fields(log_record, record, message_dict)
trace_id = getattr(record, "otelTraceID", None)
span_id = getattr(record, "otelSpanID", None)
# The instrumentation's own attributes would otherwise appear as extra keys.
for key in ("otelTraceID", "otelSpanID", "otelTraceSampled", "otelServiceName"):
log_record.pop(key, None)
# Telemetry off (no endpoint) leaves the log format exactly as it was.
if os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT") and _is_set(trace_id) and _is_set(span_id):
log_record["trace_id"] = trace_id
log_record["span_id"] = span_id
9 changes: 9 additions & 0 deletions common/lib/logging_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@

logging.config.fileConfig(LOGGING_CONFIG_FILE)

try:
# Stamp otelTraceID and otelSpanID on every log record so the JSON formatter can emit
# trace_id and span_id. set_logging_format=False leaves our own format alone.
from opentelemetry.instrumentation.logging import LoggingInstrumentor

LoggingInstrumentor().instrument(set_logging_format=False)
except Exception: # pragma: no cover - logging must never fail to start
logging.getLogger(__name__).warning("OpenTelemetry log correlation unavailable", exc_info=True)


def init_logger(name):
return logging.getLogger(name)
40 changes: 36 additions & 4 deletions common/lib/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,26 @@

from opentelemetry import metrics
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter as OTLPHttpMetricExporter
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.resources import Resource

from lib.otlp_config import (
EXPORT_TIMEOUT_S,
HTTP_PROTOBUF,
METRIC_SHUTDOWN_BUDGET_S,
http_signal_url,
otlp_protocol,
run_bounded,
)

OTEL_EXPORTER_OTLP_ENDPOINT = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
OTEL_SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "vcon-server")
OTEL_METRIC_EXPORT_INTERVAL = int(os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", "5000"))

meter = None
_meter_provider = None
counter_metrics = {}
histogram_metrics = {}
observable_gauges = {}
Expand Down Expand Up @@ -80,7 +91,7 @@ def _init_otel_metrics():
CONSERVER_VCON_CONCURRENCY=128, peak in-flight should reach ~256 per
pod, but the collapsed series only shows one worker's count (≤128).
"""
global meter, _otel_initialized_pid
global meter, _meter_provider, _otel_initialized_pid
current_pid = os.getpid()

# Already initialized in this process — bail.
Expand All @@ -104,9 +115,16 @@ def _init_otel_metrics():
"service.instance.id": instance_id,
})

otlp_exporter = OTLPMetricExporter(
endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
)
if otlp_protocol("metrics") == HTTP_PROTOBUF:
otlp_exporter = OTLPHttpMetricExporter(
endpoint=http_signal_url("metrics", OTEL_EXPORTER_OTLP_ENDPOINT),
timeout=EXPORT_TIMEOUT_S,
)
else:
otlp_exporter = OTLPMetricExporter(
endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
timeout=EXPORT_TIMEOUT_S,
)

reader = PeriodicExportingMetricReader(
exporter=otlp_exporter,
Expand Down Expand Up @@ -139,6 +157,7 @@ def _init_otel_metrics():
# metrics continue to flow through their own pipeline. Both end up
# at the OTel collector independently.
meter = provider.get_meter(__name__)
_meter_provider = provider

# Flush our provider's metric reader on process exit. The
# auto-instrumentation MeterProvider registers its own atexit
Expand Down Expand Up @@ -173,6 +192,19 @@ def _init_otel_metrics():
_otel_initialized_pid = current_pid


def shutdown_meter_provider():
"""Flush and shut down this process's own meter provider, waiting at most a couple of seconds.

A forked worker leaves through ``os._exit`` and never runs the ``atexit`` hook, so it calls this
before it returns. A provider inherited from another pid is left alone.
"""
global _meter_provider
provider = _meter_provider
if provider is not None and _otel_initialized_pid == os.getpid():
_meter_provider = None
run_bounded(provider.shutdown, METRIC_SHUTDOWN_BUDGET_S, "metrics")


def increment_counter(metric_name, value=1, attributes=None):
"""Increment a counter metric in OpenTelemetry.

Expand Down
76 changes: 76 additions & 0 deletions common/lib/otlp_config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Shared OTLP settings for the metrics and trace exporters."""

import logging
import os
import threading

logger = logging.getLogger(__name__)

GRPC = "grpc"
HTTP_PROTOBUF = "http/protobuf"


def otlp_protocol(signal):
"""Return ``grpc`` or ``http/protobuf`` for ``signal`` (``metrics`` or ``traces``).

Reads ``OTEL_EXPORTER_OTLP_<SIGNAL>_PROTOCOL`` first, then ``OTEL_EXPORTER_OTLP_PROTOCOL``.
Unset keeps the historic gRPC default. Any other value (``http/json``) falls back to gRPC
with a warning, since no exporter for it is installed.
"""
specific = {
"metrics": os.environ.get("OTEL_EXPORTER_OTLP_METRICS_PROTOCOL"),
"traces": os.environ.get("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL"),
}[signal]
raw = specific or os.environ.get("OTEL_EXPORTER_OTLP_PROTOCOL")
value = (raw or GRPC).strip().lower()
if value in (GRPC, HTTP_PROTOBUF):
return value
logger.warning("Unsupported OTEL_EXPORTER_OTLP_PROTOCOL %r for %s, using grpc", raw, signal)
return GRPC


def http_signal_url(signal, base_endpoint):
"""Full OTLP/HTTP URL for ``signal``.

An explicit endpoint passed to an HTTP exporter is used as given, with no path added, so the
``/v1/<signal>`` suffix has to be appended here. A per-signal endpoint variable is used as is.
"""
specific = {
"metrics": os.environ.get("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"),
"traces": os.environ.get("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"),
}[signal]
if specific:
return specific
return f"{base_endpoint.rstrip('/')}/v1/{signal}"


# Bounds on telemetry work at exit. A dead collector must not hold a worker for the SDK defaults,
# which add up to about a minute (30 s trace shutdown plus the metrics export timeout).
EXPORT_TIMEOUT_S = 2
TRACE_SHUTDOWN_BUDGET_S = 3.0
METRIC_SHUTDOWN_BUDGET_S = 2.0


def run_bounded(fn, budget_s, what):
"""Run ``fn`` on a daemon thread and give up waiting after ``budget_s`` seconds.

Returns True when ``fn`` finished in time. A late thread is abandoned: it is a daemon, so it
cannot keep the process alive, and whatever it had not exported is dropped.
"""
error = []

def target():
try:
fn()
except Exception as e: # noqa: BLE001
error.append(e)

thread = threading.Thread(target=target, name=f"otel-shutdown-{what}", daemon=True)
thread.start()
thread.join(budget_s)
if thread.is_alive():
logger.warning("OpenTelemetry %s shutdown still running after %.1f s, abandoning it", what, budget_s)
return False
if error:
logger.warning("Failed to shut down OpenTelemetry %s: %s", what, error[0])
return True
49 changes: 49 additions & 0 deletions common/lib/span_attributes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
"""Span attributes that tie a chain run to a tenant and a call.

These go on spans only. A per-call value on a metric creates one series per call.
"""

from typing import Optional

from vcon import Vcon

TELNYX_SESSION_TAG = "telnyx_call_session_id"
_MAX_LEN = 128


def _clean(value) -> Optional[str]:
if isinstance(value, bool) or not isinstance(value, (str, int)):
return None
text = str(value).strip()
return text[:_MAX_LEN] if text else None


def vcon_correlation_attributes(vcon_dict: Optional[dict]) -> dict:
"""Return ``tenant.id`` and ``call.session_id`` for a vCon dict, leaving out what is absent.

``tenant.id`` is the ``id`` in the body of the ``tenant`` attachment. ``call.session_id`` is
the value of the ``telnyx_call_session_id`` tag. Nothing else from the vCon is read, so no
dialog, transcript or other body content can reach a span through here.
"""
if not vcon_dict:
return {}
vcon = Vcon(vcon_dict)
attrs = {}

try:
tenant_body = Vcon.decoded_body(vcon.find_attachment_by_purpose("tenant"))
except Exception:
tenant_body = None
if isinstance(tenant_body, dict):
tenant_id = _clean(tenant_body.get("id"))
if tenant_id:
attrs["tenant.id"] = tenant_id

try:
session_id = _clean(vcon.get_tag(TELNYX_SESSION_TAG))
except Exception:
session_id = None
if session_id:
attrs["call.session_id"] = session_id

return attrs
Loading