otel

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package otel provides an OpenTelemetry adapter that implements the kernel/wrapper.Tracer interface using the OTel SDK.

It bridges GoCell's lightweight tracing abstraction to the full OpenTelemetry pipeline (OTLP/gRPC export, W3C TraceContext propagation, configurable sampling). Context keys (trace_id, span_id) are propagated via pkg/ctxkeys so that slog correlation works out of the box.

ref: go.opentelemetry.io/otel -- TracerProvider, Tracer, Span API Adopted: OTel SDK TracerProvider lifecycle, OTLP gRPC exporter. Deviated: wrapped behind kernel/wrapper.Tracer so cells remain decoupled from OTel imports.

Index

Constants

View Source
const (
	// ErrAdapterOTelConfig indicates an invalid OTel configuration.
	ErrAdapterOTelConfig errcode.Code = "ERR_ADAPTER_OTEL_CONFIG"

	// ErrAdapterOTelInit indicates a failure during OTel provider initialization.
	ErrAdapterOTelInit errcode.Code = "ERR_ADAPTER_OTEL_INIT"

	// ErrAdapterOTelShutdown indicates a failure during OTel provider shutdown.
	ErrAdapterOTelShutdown errcode.Code = "ERR_ADAPTER_OTEL_SHUTDOWN"
)

OTel adapter error codes.

View Source
const MessagingSystemRabbitMQ = messagingSystemRabbitMQ

MessagingSystemRabbitMQ is the canonical value for the `messaging.system` attribute emitted by this collector when the underlying statter comes from adapters/rabbitmq.

Variables

This section is empty.

Functions

func NewPoolMetricsResource

func NewPoolMetricsResource(meter otelmetric.Meter, statters []poolstats.Statter) (lifecycle.ManagedResource, error)

NewPoolMetricsResource registers db.client.connection.* OTel observable gauges driven by the supplied statters and returns the registration as a kernel/lifecycle.ManagedResource. Bootstrap registers the resource via bootstrap.WithManagedResource and the OTel callback is unregistered as part of LIFO shutdown.

Statter-less callers (len(statters) == 0) receive a no-op resource whose Close returns nil — callers can always wire the resource without a nil guard.

Design note — why ManagedResource and not lifecycle.ContextCloser: bootstrap.WithManagedResource is the single bootstrap option that drives LIFO teardown for adapter-style components; using ContextCloser would require a separate bootstrap option just for this collector. The Checkers/Worker aspects are deliberately nil — OTel callback-based metric emission has no out-of-band health probe (the callback runs synchronously on every collect cycle; failures surface through OTel's own internal diagnostic handler) and no background goroutine.

ref: kernel/lifecycle/managed_resource.go — three-aspect bundle (Checkers/Worker/Close); pool collector uses only Close. ref: opentelemetry-go metric/meter.go@main Registration.Unregister — canonical callback teardown used inside Close; idempotent per OTel SDK.

func RegisterMessagingChannelMetrics

func RegisterMessagingChannelMetrics(meter otelmetric.Meter, statters []MessagingChannelStatter) (unregister func() error, err error)

RegisterMessagingChannelMetrics registers two observable gauges for messaging client channel pools and drives them from the given statters on every collection cycle:

gocell.messaging.channel.count{messaging.system, pool.name, state=idle|used}
gocell.messaging.channel.max{messaging.system, pool.name}

The caller supplies (System, Statter) tuples so one collector can track multiple brokers uniformly. Returns an unregister function that MUST be invoked at Stop to release the callback; a leaked callback would continue to read from snapshotters whose owning connections have been closed.

ref: adapters/otel/pool_resource.go — same Meter.RegisterCallback pattern; the split exists so each metric family carries correct semantic-convention metadata (db vs messaging).

Types

type MessagingChannelStatter

type MessagingChannelStatter struct {
	// System identifies the broker (e.g. "rabbitmq", "kafka"). Required.
	System string
	// Statter provides the snapshot. Required.
	Statter poolstats.Statter
}

MessagingChannelStatter pairs a poolstats.Statter with the messaging system it belongs to. messagingSystem becomes the `messaging.system` attribute on emitted metrics so dashboards can pivot across brokers.

type MetricProvider

type MetricProvider struct {
	// contains filtered or unexported fields
}

MetricProvider implements metrics.Provider backed by an OTel Meter.

ref: opentelemetry-go metric/meter.go@main — Int64Counter / Float64Histogram are the underlying instruments; our Counter/Histogram bind pre-computed label attributes and call Add / Record at record time. We expose a label-map abstraction on top because the kernel wants label *drift detection* (see kernel/observability/metrics.MustValidateLabels); OTel's native variadic attribute.KeyValue makes drift silent.

func NewMetricProvider

func NewMetricProvider(meter otelmetric.Meter) (*MetricProvider, error)

NewMetricProvider returns a Provider that registers instruments on the supplied Meter. Caller owns the MeterProvider (and exporter) lifecycle; this constructor does not spin up OTLP connections.

Errors:

  • ErrAdapterOTelConfig when meter is nil.

func (*MetricProvider) CounterVec

func (p *MetricProvider) CounterVec(opts metrics.CounterOpts) (metrics.CounterVec, error)

CounterVec creates a Float64Counter instrument. OTel counters are monotonic and support fractional increments (Add(delta)); the float choice matches metrics.Counter.Add(float64).

func (*MetricProvider) GaugeVec

func (p *MetricProvider) GaugeVec(opts metrics.GaugeOpts) (metrics.GaugeVec, error)

GaugeVec creates a Float64Gauge instrument (OTel v1.33+ synchronous gauge, LastValue / metricdata.Gauge export semantics) and wraps it in otelGaugeVec.

Set(v) calls Float64Gauge.Record(v) directly — Record takes an absolute value, so no delta arithmetic is needed for Set. Inc/Dec/Add maintain a per-label-set last-value slot (protected by sync.Mutex) to compute the new absolute value before calling Record:

Inc:  last++; Record(ctx, last)
Dec:  last--; Record(ctx, last)
Add:  last += delta; Record(ctx, last)

Each call to With() returns the *same* otelGauge for a given label set so that concurrent callers sharing a label set operate on the same last-value slot.

ref: opentelemetry-go metric.Meter.Float64Gauge (v1.33+)

func (*MetricProvider) HistogramVec

func (p *MetricProvider) HistogramVec(opts metrics.HistogramOpts) (metrics.HistogramVec, error)

HistogramVec creates a Float64Histogram. Explicit Buckets propagate to OTel as aggregation preferences; callers that want richer aggregation (exponential, quantile) must build their MeterProvider with the relevant views before handing a Meter to us.

func (*MetricProvider) Unregister

func (p *MetricProvider) Unregister(_ metrics.Collector) error

Unregister is a no-op for the OTel provider. OTel instruments are registered with the MeterProvider at SDK level; individual instrument deregistration is not part of the OTel API. Returns nil (idempotent, per the Unregister contract).

type Tracer

type Tracer struct {
	// contains filtered or unexported fields
}

Tracer implements wrapper.Tracer using the OpenTelemetry SDK.

func NewTracer

func NewTracer(ctx context.Context, cfg TracerConfig) (*Tracer, func(context.Context) error, error)

NewTracer creates an OTel-backed Tracer with an OTLP gRPC exporter. It returns the tracer, a shutdown function, and any initialization error. The shutdown function flushes pending spans and releases resources.

On success the constructed TracerProvider and a composite (W3C TraceContext + Baggage) propagator are registered as the OTel globals so that auto-instrumented libraries (otelgrpc / otelhttp / database/sql instrumentations) emit spans into the same provider. Registration is the last step before return; any earlier error path leaves the previous globals untouched.

ref: opentelemetry-go exporters/otlp/otlptrace/otlptracegrpc/example_test.go — canonical NewTracerProvider + SetTracerProvider + SetTextMapPropagator sequence for OTLP gRPC exporters.

func NewTracerFromTracerProvider

func NewTracerFromTracerProvider(tp oteltrace.TracerProvider, serviceName string) (*Tracer, error)

NewTracerFromTracerProvider wraps a caller-owned TracerProvider into a Tracer. The caller retains lifecycle ownership (no shutdown is returned).

This constructor exists so advanced callers can compose their own exporter stack (e.g. a fan-out to OTLP + a local in-memory exporter), and so tests can substitute `sdktrace/tracetest.InMemoryExporter` for deterministic assertions on emitted spans without reaching through the OTLP gRPC path.

ref: opentelemetry-go sdk/trace/tracetest/recorder.go@main — the SDK's own tests use tracetest.InMemoryExporter composed into a TracerProvider for the same reason.

func (*Tracer) Start

func (t *Tracer) Start(ctx context.Context, name string, attrs ...wrapper.Attr) (context.Context, wrapper.Span)

Start creates a new span with the given name. The returned context carries the span and its trace/span IDs propagated via ctxkeys. Accepts variadic wrapper.Attr so kernel/wrapper callers can hand attributes in at Start; attrs are applied on the returned Span immediately via SetAttributes.

type TracerConfig

type TracerConfig struct {
	// ServiceName identifies this service in traces (e.g. "accesscore").
	ServiceName string

	// ExporterEndpoint is the OTLP gRPC collector address (e.g. "localhost:4317").
	ExporterEndpoint string

	// Insecure disables TLS for the gRPC connection to the collector.
	Insecure bool

	// SampleRate is the probability of sampling a trace, in the range (0, 1].
	// Zero value means "use default" (1.0 = sample everything).
	// To disable sampling entirely, set DisableSampling=true.
	// Values outside (0, 1] (when non-zero) cause NewTracer to return an error.
	SampleRate float64

	// DisableSampling forces SampleRate to 0, dropping all traces.
	// Takes precedence over SampleRate.
	DisableSampling bool
}

TracerConfig holds settings for the OTel tracer adapter.

Directories

Path Synopsis
internal
otelwrap
Package otelwrap is the sole sanctioned funnel for invoking OpenTelemetry metric.Meter instrument constructors.
Package otelwrap is the sole sanctioned funnel for invoking OpenTelemetry metric.Meter instrument constructors.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL