otlp

package
v1.0.521 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 12 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package otlp exports metrics and request spans to any OpenTelemetry Collector via the OTLP/HTTP JSON protocol (POST /v1/metrics, /v1/traces). No SDK dependency — plain net/http and encoding/json keep the binary self-contained. Extracted from package main's otlp.go / otlp_traces.go per a recorded ADR-0002-style design (post-program extraction).

The package owns the transport (push loops, SSRF-guarded client, endpoint validation) and the OTLP JSON schema. What each METRIC contains is the caller's business: package main wires a snapshot func into NewMetrics that reads its stat singletons and returns []Metric — the engine never imports main's state.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParseTraceparent

func ParseTraceparent(tp string) (traceID, spanID string)

ParseTraceparent extracts the trace-id and span-id from a W3C Traceparent header value: "00-{traceID}-{spanID}-{flags}"

Types

type AnyValue

type AnyValue struct {
	StringValue string `json:"stringValue,omitempty"`
}

AnyValue is an attribute value (string-only — all Culvert attributes are strings).

type ExportRequest

type ExportRequest struct {
	ResourceMetrics []ResourceMetrics `json:"resourceMetrics"`
}

ExportRequest is the top-level /v1/metrics payload.

func Envelope

func Envelope(metrics []Metric) ExportRequest

Envelope wraps a metric set in the standard Culvert resource/scope envelope. Exported so main's payload tests can assert the full shape.

type Gauge

type Gauge struct {
	DataPoints []NumberDataPoint `json:"dataPoints"`
}

Gauge is a point-in-time value.

type Hist

type Hist struct {
	DataPoints             []HistDataPoint `json:"dataPoints"`
	AggregationTemporality int             `json:"aggregationTemporality"`
}

Hist is a cumulative histogram.

type HistDataPoint

type HistDataPoint struct {
	TimeUnixNano   string    `json:"timeUnixNano"`
	Count          int64     `json:"count,string"`
	Sum            float64   `json:"sum"`
	BucketCounts   []string  `json:"bucketCounts"`
	ExplicitBounds []float64 `json:"explicitBounds"`
}

HistDataPoint is one histogram sample.

type KeyValue

type KeyValue struct {
	Key   string   `json:"key"`
	Value AnyValue `json:"value"`
}

KeyValue is one attribute.

type Metric

type Metric struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Unit        string `json:"unit,omitempty"`
	Sum         *Sum   `json:"sum,omitempty"`
	Gauge       *Gauge `json:"gauge,omitempty"`
	Histogram   *Hist  `json:"histogram,omitempty"`
}

Metric is one named metric with exactly one of Sum/Gauge/Histogram set.

type MetricsExporter

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

MetricsExporter pushes metrics to an OTLP/HTTP endpoint.

func NewMetrics

func NewMetrics(snapshot SnapshotFunc) *MetricsExporter

NewMetrics builds a metrics exporter over the given snapshot source (nil = export an empty metric set; useful for tests).

func (*MetricsExporter) Configure

func (o *MetricsExporter) Configure(endpoint string, headers map[string]string)

Configure sets the OTLP endpoint and starts the push loop.

func (*MetricsExporter) Enabled

func (o *MetricsExporter) Enabled() bool

Enabled returns whether OTLP export is active.

func (*MetricsExporter) Endpoint

func (o *MetricsExporter) Endpoint() string

Endpoint returns the current endpoint URL.

func (*MetricsExporter) Flush added in v1.0.518

func (o *MetricsExporter) Flush(ctx context.Context) error

Flush makes one bounded delivery attempt for the current metric snapshot. The shutdown sequence calls it alongside the span exporter's Flush: a cumulative counter's TERMINAL value is the one an operator wants at a restart boundary, and the next process starts those counters at zero, so the last interval's increments are otherwise unobservable for good (CHAOS-126). A no-op when export is disabled.

func (*MetricsExporter) Headers

func (o *MetricsExporter) Headers() map[string]string

Headers returns a copy of the configured custom headers (nil when none).

func (*MetricsExporter) Health added in v1.0.155

func (o *MetricsExporter) Health() PushHealth

Health returns the current push-loop diagnostic snapshot.

func (*MetricsExporter) Stop

func (o *MetricsExporter) Stop()

Stop halts the push loop.

type NumberDataPoint

type NumberDataPoint struct {
	Attributes   []KeyValue `json:"attributes,omitempty"`
	TimeUnixNano string     `json:"timeUnixNano"`
	AsInt        *int64     `json:"asInt,omitempty"`
	AsDouble     *float64   `json:"asDouble,omitempty"`
}

NumberDataPoint is one numeric sample.

type PushHealth added in v1.0.155

type PushHealth struct {
	FailureCount  int64  `json:"failureCount"`
	LastError     string `json:"lastError,omitempty"`
	LastErrorAt   string `json:"lastErrorAt,omitempty"`   // RFC3339 UTC; empty = never
	LastSuccessAt string `json:"lastSuccessAt,omitempty"` // RFC3339 UTC; empty = never
	DroppedSpans  int64  `json:"droppedSpans,omitempty"`  // trace exporter only: spans never delivered
}

PushHealth reports an OTLP push loop's diagnostic state for the admin API — purely observational, computed from counters already maintained in-process.

type Resource

type Resource struct {
	Attributes []KeyValue `json:"attributes"`
}

Resource carries the resource-identifying attributes.

type ResourceMetrics

type ResourceMetrics struct {
	Resource     Resource      `json:"resource"`
	ScopeMetrics []ScopeMetric `json:"scopeMetrics"`
}

ResourceMetrics groups metrics under one resource.

type Scope

type Scope struct {
	Name    string `json:"name"`
	Version string `json:"version"`
}

Scope identifies the instrumentation scope.

type ScopeMetric

type ScopeMetric struct {
	Scope   Scope    `json:"scope"`
	Metrics []Metric `json:"metrics"`
}

ScopeMetric groups metrics under one instrumentation scope.

type SnapshotFunc

type SnapshotFunc func(nowUnixNano string) []Metric

SnapshotFunc returns the current metric set, stamped with the given UnixNano timestamp string. package main's implementation reads the culvert_* stat singletons.

type SpanExporter

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

SpanExporter collects spans and pushes them to an OTLP/HTTP endpoint.

func NewSpans

func NewSpans() *SpanExporter

NewSpans builds a span exporter.

func (*SpanExporter) Configure

func (e *SpanExporter) Configure(endpoint string, headers map[string]string)

Configure sets the OTLP endpoint and starts the push loop.

func (*SpanExporter) Enabled

func (e *SpanExporter) Enabled() bool

Enabled returns whether trace export is active (lock-free fast path).

func (*SpanExporter) Flush added in v1.0.518

func (e *SpanExporter) Flush(ctx context.Context) error

Flush makes ONE bounded delivery attempt for everything buffered right now. The shutdown sequence calls it (main_shutdown.go, shutdownOrderOTLPTracesFlush) because nothing else can: no caller cancels the push loop at process exit, so the loop's own ctx.Done() flush — the one its comment called "Final flush on shutdown" — has never run on a shutdown in this binary's life (CHAOS-126). A no-op when export is disabled.

func (*SpanExporter) FlushFinal added in v1.0.518

func (e *SpanExporter) FlushFinal(ctx context.Context) error

FlushFinal is Flush for a process that is going away: one bounded attempt, and then whatever is still held is ENDED — counted, and logged WITH ITS SIZE, because that log line is the only form in which the number survives the exit. Retention is the right answer for a failure with a next interval ahead of it and the wrong answer here: a retained batch would die in RAM having moved no counter and named no quantity, which is the silent loss this round exists to remove, merely relocated to the last second of the process's life.

A batch another push still holds (this flush timed out waiting for the slot) is named in the same line, and finalized makes sure that if its POST then fails it is counted as dropped instead of being requeued into a ring nobody will read again. Its outcome is not known here, so it is reported as in flight rather than counted.

func (*SpanExporter) Health added in v1.0.155

func (e *SpanExporter) Health() PushHealth

Health returns the current push-loop diagnostic snapshot, including spans that were never delivered (DroppedSpans — see the field's comment for what ends a span's life).

func (*SpanExporter) RecordSpan

func (e *SpanExporter) RecordSpan(s SpanRecord)

RecordSpan appends a span to the ring buffer. Callers should check Enabled() first to avoid constructing the SpanRecord at all when tracing is off.

func (*SpanExporter) Stop

func (e *SpanExporter) Stop()

Stop halts the push loop and clears the endpoint.

type SpanRecord

type SpanRecord struct {
	TraceID   string // 32 hex chars from Traceparent
	SpanID    string // 16 hex chars from Traceparent
	Name      string // "proxy_request"
	Method    string // GET, CONNECT, etc.
	Host      string // target host
	Status    string // OK, BLOCKED, FILE_BLOCKED, etc.
	Rule      string // matched policy rule name (may be empty)
	ClientIP  string // net.SplitHostPort(r.RemoteAddr)
	SSLAction string // "inspect", "bypass", or ""
	StartNano int64  // time.Now().UnixNano() at request start
	EndNano   int64  // time.Now().UnixNano() at request end
}

SpanRecord holds the data collected per proxied request. Allocated on the stack in handleRequest and copied into the ring buffer — no heap escape for the common no-OTLP case because RecordSpan callers check Enabled() first.

type Sum

type Sum struct {
	DataPoints             []NumberDataPoint `json:"dataPoints"`
	AggregationTemporality int               `json:"aggregationTemporality"` // 2 = cumulative
	IsMonotonic            bool              `json:"isMonotonic"`
}

Sum is a monotonic or non-monotonic cumulative counter.

Jump to

Keyboard shortcuts

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