lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/exaring/otelpgx"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
// NewPGXTracer returns a pgx tracer that records database spans without SQL
|
||||
// text or connection details (those can contain identifiers and DSNs).
|
||||
func NewPGXTracer() pgx.QueryTracer {
|
||||
return otelpgx.NewTracer(
|
||||
otelpgx.WithTracerProvider(otel.GetTracerProvider()),
|
||||
otelpgx.WithDisableSQLStatementInAttributes(),
|
||||
otelpgx.WithDisableConnectionDetailsInAttributes(),
|
||||
)
|
||||
}
|
||||
|
||||
// RegisterDBPool exposes pgxpool gauges. pgxpool has no current "waiting"
|
||||
// counter; EmptyAcquireCount/WaitTime are the observable contention signal.
|
||||
func RegisterDBPool(stats func() *pgxpool.Stat) error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
s := stats()
|
||||
if s == nil {
|
||||
return nil
|
||||
}
|
||||
o.ObserveInt64(dbUsed, int64(s.AcquiredConns()))
|
||||
o.ObserveInt64(dbIdle, int64(s.IdleConns()))
|
||||
o.ObserveInt64(dbMax, int64(s.MaxConns()))
|
||||
o.ObserveInt64(dbEmptyAcquire, s.EmptyAcquireCount())
|
||||
o.ObserveFloat64(dbEmptyWait, s.EmptyAcquireWaitTime().Seconds())
|
||||
return nil
|
||||
}, dbUsed, dbIdle, dbMax, dbEmptyAcquire, dbEmptyWait)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
|
||||
|
||||
// ValidTraceparent reports whether a broker-carried traceparent matches the
|
||||
// closed schema before it is trusted as a parent context.
|
||||
func ValidTraceparent(value string) bool {
|
||||
return value == "" || (len(value) <= 512 && traceparentPattern.MatchString(value))
|
||||
}
|
||||
|
||||
// Inject serializes the current span context for a durable outbox payload.
|
||||
func Inject(ctx context.Context) (traceparent, tracestate string) {
|
||||
carrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
||||
tracestate = carrier["tracestate"]
|
||||
if len(tracestate) > 512 {
|
||||
tracestate = ""
|
||||
}
|
||||
return carrier["traceparent"], tracestate
|
||||
}
|
||||
|
||||
// Extract restores a parent context from a broker payload. Invalid values are
|
||||
// ignored; the caller still gets a usable context.
|
||||
func Extract(ctx context.Context, traceparent, tracestate string) context.Context {
|
||||
if !ValidTraceparent(traceparent) || len(tracestate) > 512 {
|
||||
return ctx
|
||||
}
|
||||
carrier := propagation.MapCarrier{"traceparent": traceparent}
|
||||
if tracestate != "" {
|
||||
carrier["tracestate"] = tracestate
|
||||
}
|
||||
return otel.GetTextMapPropagator().Extract(ctx, carrier)
|
||||
}
|
||||
|
||||
// StartPublishSpan starts the producer span for an outbox publication. The
|
||||
// returned context carries the span that must be injected into the message.
|
||||
func StartPublishSpan(ctx context.Context, message domain.JobMessage) (context.Context, trace.Span) {
|
||||
parent := Extract(ctx, message.Traceparent, message.Tracestate)
|
||||
return otel.Tracer("messenger/queue").Start(parent, "job.publish",
|
||||
trace.WithSpanKind(trace.SpanKindProducer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.operation", "publish"),
|
||||
attribute.String("messaging.destination.name", message.Type),
|
||||
attribute.String("job.id", message.JobID.String()),
|
||||
attribute.String("job.type", message.Type),
|
||||
attribute.Int("job.attempt", message.Attempt),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// StartRequeueSpanForJob starts a per-job reaper/reconcile span. The durable
|
||||
// job keeps the original upload trace context, so a retry remains linked to
|
||||
// attempt 1 instead of the relay's batch-wide reaper span.
|
||||
func StartRequeueSpanForJob(ctx context.Context, job domain.Job) (context.Context, trace.Span) {
|
||||
parent := Extract(ctx, job.Traceparent, job.Tracestate)
|
||||
return otel.Tracer("messenger/relay").Start(parent, "job.requeue",
|
||||
trace.WithAttributes(
|
||||
attribute.String("job.id", job.ID.String()),
|
||||
attribute.String("job.type", domain.JobType),
|
||||
attribute.Int("job.attempt", job.Attempt),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// StartConsumerSpan starts the worker span as a child of the publish span.
|
||||
func StartConsumerSpan(ctx context.Context, message domain.JobMessage) (context.Context, trace.Span) {
|
||||
parent := Extract(ctx, message.Traceparent, message.Tracestate)
|
||||
return otel.Tracer("messenger/worker").Start(parent, "job.process",
|
||||
trace.WithSpanKind(trace.SpanKindConsumer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("messaging.system", "rabbitmq"),
|
||||
attribute.String("messaging.operation", "process"),
|
||||
attribute.String("messaging.destination.name", message.Type),
|
||||
attribute.String("job.id", message.JobID.String()),
|
||||
attribute.String("job.type", message.Type),
|
||||
attribute.Int("job.attempt", message.Attempt),
|
||||
attribute.Int("pipeline.version", message.PipelineVersion),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
// StartRequeueSpan covers the relay's lease reaper / reconciliation path.
|
||||
func StartRequeueSpan(ctx context.Context, operation string) (context.Context, trace.Span) {
|
||||
return otel.Tracer("messenger/relay").Start(ctx, "job."+operation,
|
||||
trace.WithAttributes(attribute.String("job.operation", operation)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/platform/instanceid"
|
||||
)
|
||||
|
||||
var (
|
||||
allowKeys = map[string]struct{}{
|
||||
"event": {}, "operation": {}, "route": {}, "method": {}, "status": {},
|
||||
"status_class": {}, "duration": {}, "error_code": {}, "job_type": {},
|
||||
"outcome": {}, "attempt": {}, "pipeline_version": {}, "queue": {},
|
||||
"count": {}, "bytes": {}, "size": {}, "job_id": {},
|
||||
"service.name": {}, "service.instance.id": {},
|
||||
"deployment.environment.name": {}, "trace_id": {}, "span_id": {},
|
||||
"request_id": {}, "error": {},
|
||||
}
|
||||
requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
jobIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||
redactPatterns = []*regexp.Regexp{
|
||||
regexp.MustCompile(`(?i)(X-Amz-(?:Signature|Credential|Security-Token)=)[^&\s"]+`),
|
||||
regexp.MustCompile(`(?i)(password|passwd|secret|token|authorization)=([^&\s"]+)`),
|
||||
regexp.MustCompile(`://[^/\s:@]+:[^@\s]+@`),
|
||||
regexp.MustCompile(`(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b`),
|
||||
regexp.MustCompile(`\b(?:attachments|staging|variants)/[^\s"']+`),
|
||||
}
|
||||
)
|
||||
|
||||
// WrapLogger returns a logger that writes sanitized JSON to stdout and, when
|
||||
// configured, also emits OTLP log records. The sanitizer is the boundary that
|
||||
// prevents raw paths, filenames, user ids and credentials from reaching any
|
||||
// telemetry backend.
|
||||
func WrapLogger(base *slog.Logger, serviceName string, minLevel slog.Level) *slog.Logger {
|
||||
if base == nil {
|
||||
base = slog.Default()
|
||||
}
|
||||
|
||||
var otelHandler slog.Handler
|
||||
if provider := GlobalLoggerProvider(); provider != nil {
|
||||
otelHandler = otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(provider))
|
||||
}
|
||||
|
||||
return slog.New(&sanitizeHandler{
|
||||
inner: &fanoutHandler{handlers: []slog.Handler{base.Handler(), otelHandler}},
|
||||
service: serviceName,
|
||||
instance: instanceid.FromEnvOrHostname(),
|
||||
minLevel: minLevel,
|
||||
})
|
||||
}
|
||||
|
||||
type fanoutHandler struct {
|
||||
handlers []slog.Handler
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
for _, handler := range h.handlers {
|
||||
if handler != nil && handler.Enabled(ctx, level) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||
for _, handler := range h.handlers {
|
||||
if handler == nil {
|
||||
continue
|
||||
}
|
||||
if err := handler.Handle(ctx, record.Clone()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
next := &fanoutHandler{handlers: make([]slog.Handler, 0, len(h.handlers))}
|
||||
for _, handler := range h.handlers {
|
||||
if handler == nil {
|
||||
next.handlers = append(next.handlers, nil)
|
||||
continue
|
||||
}
|
||||
next.handlers = append(next.handlers, handler.WithAttrs(attrs))
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
func (h *fanoutHandler) WithGroup(name string) slog.Handler {
|
||||
next := &fanoutHandler{handlers: make([]slog.Handler, 0, len(h.handlers))}
|
||||
for _, handler := range h.handlers {
|
||||
if handler == nil {
|
||||
next.handlers = append(next.handlers, nil)
|
||||
continue
|
||||
}
|
||||
next.handlers = append(next.handlers, handler.WithGroup(name))
|
||||
}
|
||||
return next
|
||||
}
|
||||
|
||||
type sanitizeHandler struct {
|
||||
inner slog.Handler
|
||||
service string
|
||||
instance string
|
||||
minLevel slog.Level
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
||||
return level >= h.minLevel && h.inner.Enabled(ctx, level)
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) Handle(ctx context.Context, record slog.Record) error {
|
||||
sanitized := slog.NewRecord(record.Time, record.Level, sanitizeText(record.Message), record.PC)
|
||||
|
||||
seenEvent := false
|
||||
record.Attrs(func(attr slog.Attr) bool {
|
||||
if attr.Key == "event" {
|
||||
seenEvent = true
|
||||
}
|
||||
if clean, ok := sanitizeAttr(attr); ok {
|
||||
sanitized.AddAttrs(clean)
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
if !seenEvent {
|
||||
event := sanitizeText(record.Message)
|
||||
if event == "" {
|
||||
event = "log"
|
||||
}
|
||||
sanitized.AddAttrs(slog.String("event", event))
|
||||
}
|
||||
if h.service != "" {
|
||||
sanitized.AddAttrs(slog.String("service.name", h.service))
|
||||
}
|
||||
if h.instance != "" {
|
||||
sanitized.AddAttrs(slog.String("service.instance.id", h.instance))
|
||||
}
|
||||
if spanContext := trace.SpanContextFromContext(ctx); spanContext.IsValid() {
|
||||
sanitized.AddAttrs(
|
||||
slog.String("trace_id", spanContext.TraceID().String()),
|
||||
slog.String("span_id", spanContext.SpanID().String()),
|
||||
)
|
||||
}
|
||||
|
||||
return h.inner.Handle(ctx, sanitized)
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
clean := make([]slog.Attr, 0, len(attrs))
|
||||
for _, attr := range attrs {
|
||||
if value, ok := sanitizeAttr(attr); ok {
|
||||
clean = append(clean, value)
|
||||
}
|
||||
}
|
||||
return &sanitizeHandler{inner: h.inner.WithAttrs(clean), service: h.service, instance: h.instance, minLevel: h.minLevel}
|
||||
}
|
||||
|
||||
func (h *sanitizeHandler) WithGroup(name string) slog.Handler {
|
||||
return &sanitizeHandler{inner: h.inner.WithGroup(name), service: h.service, instance: h.instance, minLevel: h.minLevel}
|
||||
}
|
||||
|
||||
func sanitizeAttr(attr slog.Attr) (slog.Attr, bool) {
|
||||
if _, ok := allowKeys[attr.Key]; !ok {
|
||||
return slog.Attr{}, false
|
||||
}
|
||||
|
||||
value := attr.Value.Resolve()
|
||||
switch attr.Key {
|
||||
case "error":
|
||||
return slog.String("error", Redact(value.String())), true
|
||||
case "request_id":
|
||||
id := value.String()
|
||||
if !requestIDPattern.MatchString(id) {
|
||||
id = "invalid"
|
||||
}
|
||||
return slog.String("request_id", id), true
|
||||
case "job_id":
|
||||
// job_id is an explicitly allowlisted synthetic/technical identifier.
|
||||
// Unlike free-form error text, it is safe to keep for queue correlation.
|
||||
id := value.String()
|
||||
if !jobIDPattern.MatchString(id) {
|
||||
id = "invalid"
|
||||
}
|
||||
return slog.String("job_id", id), true
|
||||
}
|
||||
|
||||
if value.Kind() == slog.KindGroup {
|
||||
return slog.Attr{}, false
|
||||
}
|
||||
if value.Kind() == slog.KindString {
|
||||
return slog.String(attr.Key, sanitizeText(value.String())), true
|
||||
}
|
||||
return slog.Attr{Key: attr.Key, Value: value}, true
|
||||
}
|
||||
|
||||
func sanitizeText(value string) string {
|
||||
return truncate(Redact(value), 1024)
|
||||
}
|
||||
|
||||
// Redact removes credentials, signed-URL parameters, UUIDs and object keys from
|
||||
// free-form error text before it reaches stdout, logs or trace exception events.
|
||||
func Redact(value string) string {
|
||||
for _, pattern := range redactPatterns {
|
||||
value = pattern.ReplaceAllString(value, "$1***")
|
||||
}
|
||||
return truncate(value, 1024)
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
if len(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return value[:limit] + "..."
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type captureHandler struct {
|
||||
attrs []slog.Attr
|
||||
}
|
||||
|
||||
func (h *captureHandler) Enabled(context.Context, slog.Level) bool { return true }
|
||||
func (h *captureHandler) Handle(_ context.Context, record slog.Record) error {
|
||||
record.Attrs(func(attr slog.Attr) bool {
|
||||
h.attrs = append(h.attrs, attr)
|
||||
return true
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *captureHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
return &captureHandler{attrs: append(h.attrs, attrs...)}
|
||||
}
|
||||
func (h *captureHandler) WithGroup(string) slog.Handler { return h }
|
||||
|
||||
func TestSanitizerDropsIdentifiersAndRedactsErrors(t *testing.T) {
|
||||
capture := &captureHandler{}
|
||||
handler := &sanitizeHandler{inner: capture, service: "messenger-api", instance: "instance-1", minLevel: slog.LevelDebug}
|
||||
record := slog.NewRecord(time.Now(), slog.LevelInfo, "request handled", 0)
|
||||
record.AddAttrs(
|
||||
slog.String("event", "http.request.completed"),
|
||||
slog.String("path", "/api/v1/chats/33333333-3333-4333-8333-333333333333/messages"),
|
||||
slog.String("query", "filename=secret.png"),
|
||||
slog.String("user_id", "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
|
||||
slog.String("object_key", "attachments/chat/attachment/original"),
|
||||
slog.String("error", `parse "postgres://user:pass@db:5432/x": X-Amz-Signature=abc attachments/33333333-3333-4333-8333-333333333333/44444444-4444-4444-8444-444444444444/original`),
|
||||
slog.String("request_id", "bad request id with spaces"),
|
||||
)
|
||||
if err := handler.Handle(context.Background(), record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
seen := map[string]string{}
|
||||
for _, attr := range capture.attrs {
|
||||
seen[attr.Key] = attr.Value.String()
|
||||
}
|
||||
for _, forbidden := range []string{"path", "query", "user_id", "object_key"} {
|
||||
if _, ok := seen[forbidden]; ok {
|
||||
t.Fatalf("forbidden attribute %q was exported", forbidden)
|
||||
}
|
||||
}
|
||||
if strings.Contains(seen["error"], "pass") || strings.Contains(seen["error"], "abc") {
|
||||
t.Fatalf("error was not redacted: %q", seen["error"])
|
||||
}
|
||||
if strings.Contains(seen["error"], "33333333") || strings.Contains(seen["error"], "attachments/") {
|
||||
t.Fatalf("object key/uuid was not redacted: %q", seen["error"])
|
||||
}
|
||||
if seen["request_id"] != "invalid" {
|
||||
t.Fatalf("request_id was not normalized: %q", seen["request_id"])
|
||||
}
|
||||
if seen["service.name"] != "messenger-api" || seen["service.instance.id"] != "instance-1" {
|
||||
t.Fatalf("service attributes missing: %#v", seen)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidTraceparent(t *testing.T) {
|
||||
if !ValidTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01") {
|
||||
t.Fatal("valid traceparent rejected")
|
||||
}
|
||||
if ValidTraceparent("not-a-traceparent") || ValidTraceparent("00-X") {
|
||||
t.Fatal("invalid traceparent accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectDropsOversizedTracestate(t *testing.T) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
ts, err := trace.ParseTraceState("a=" + strings.Repeat("a", 180) + ",b=" + strings.Repeat("b", 180) + ",c=" + strings.Repeat("c", 180))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceState: ts,
|
||||
})
|
||||
traceparent, tracestate := Inject(trace.ContextWithSpanContext(context.Background(), sc))
|
||||
if traceparent == "" {
|
||||
t.Fatal("traceparent missing")
|
||||
}
|
||||
if tracestate != "" {
|
||||
t.Fatalf("oversized tracestate was persisted: %d bytes", len(tracestate))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInjectPreservesValidTracestate(t *testing.T) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
small, err := trace.ParseTraceState("vendor=abc123")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sc := trace.NewSpanContext(trace.SpanContextConfig{
|
||||
TraceID: trace.TraceID{1},
|
||||
SpanID: trace.SpanID{1},
|
||||
TraceState: small,
|
||||
})
|
||||
_, kept := Inject(trace.ContextWithSpanContext(context.Background(), sc))
|
||||
if kept != "vendor=abc123" {
|
||||
t.Fatalf("valid tracestate dropped: %q", kept)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeKeepsAllowlistedJobID(t *testing.T) {
|
||||
const id = "11111111-1111-4111-8111-111111111111"
|
||||
attr := slog.String("job_id", id)
|
||||
clean, ok := sanitizeAttr(attr)
|
||||
if !ok || clean.Value.String() != id {
|
||||
t.Fatalf("job_id = %#v, want %q", clean, id)
|
||||
}
|
||||
if clean, ok := sanitizeAttr(slog.String("job_id", "not-a-uuid")); !ok || clean.Value.String() != "invalid" {
|
||||
t.Fatalf("invalid job_id = %#v", clean)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
var (
|
||||
metricsOnce sync.Once
|
||||
|
||||
httpDuration metric.Float64Histogram
|
||||
jobsProcessed metric.Int64Counter
|
||||
jobDuration metric.Float64Histogram
|
||||
jobsAccepted metric.Int64Counter
|
||||
timeToReady metric.Float64Histogram
|
||||
jobsReadyInBudget metric.Int64Counter
|
||||
ttrMissed metric.Int64Counter
|
||||
workerBusy metric.Int64ObservableGauge
|
||||
workerCapacity metric.Int64ObservableGauge
|
||||
dbUsed metric.Int64ObservableGauge
|
||||
dbIdle metric.Int64ObservableGauge
|
||||
dbMax metric.Int64ObservableGauge
|
||||
dbEmptyAcquire metric.Int64ObservableCounter
|
||||
dbEmptyWait metric.Float64ObservableCounter
|
||||
processCPU metric.Float64ObservableCounter
|
||||
processMemory metric.Int64ObservableGauge
|
||||
processMemLimit metric.Int64ObservableGauge
|
||||
oldestJobAge metric.Float64ObservableGauge
|
||||
oldestOutboxAge metric.Float64ObservableGauge
|
||||
jobsOverdue metric.Int64ObservableGauge
|
||||
)
|
||||
|
||||
func initMetrics() {
|
||||
metricsOnce.Do(func() {
|
||||
meter := otel.Meter("messenger")
|
||||
|
||||
httpDuration, _ = meter.Float64Histogram("http.server.request.duration",
|
||||
metric.WithDescription("HTTP server request duration"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10))
|
||||
jobsProcessed, _ = meter.Int64Counter("messenger.jobs.processed",
|
||||
metric.WithDescription("Attachment job attempts by outcome"))
|
||||
jobDuration, _ = meter.Float64Histogram("messenger.job.duration",
|
||||
metric.WithDescription("Attachment job processing duration"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120))
|
||||
jobsAccepted, _ = meter.Int64Counter("messenger.jobs.accepted",
|
||||
metric.WithDescription("Durable attachment jobs accepted with 202"))
|
||||
timeToReady, _ = meter.Float64Histogram("messenger.job.time_to_ready",
|
||||
metric.WithDescription("Time from durable acceptance to ready"),
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(1, 2.5, 5, 10, 20, 30, 60, 120, 300))
|
||||
jobsReadyInBudget, _ = meter.Int64Counter("messenger.jobs.ready_within_budget",
|
||||
metric.WithDescription("Jobs ready within the 30s TTR objective"))
|
||||
ttrMissed, _ = meter.Int64Counter("messenger.jobs.ttr_missed",
|
||||
metric.WithDescription("Jobs that missed or failed the 30s TTR objective"))
|
||||
workerBusy, _ = meter.Int64ObservableGauge("messenger.worker.busy",
|
||||
metric.WithDescription("Worker slots currently processing a job"))
|
||||
workerCapacity, _ = meter.Int64ObservableGauge("messenger.worker.capacity",
|
||||
metric.WithDescription("Configured worker concurrency"))
|
||||
dbUsed, _ = meter.Int64ObservableGauge("messenger.db.pool.used")
|
||||
dbIdle, _ = meter.Int64ObservableGauge("messenger.db.pool.idle")
|
||||
dbMax, _ = meter.Int64ObservableGauge("messenger.db.pool.max")
|
||||
dbEmptyAcquire, _ = meter.Int64ObservableCounter("messenger.db.pool.empty_acquire",
|
||||
metric.WithDescription("Acquisitions that had to wait for a free connection"))
|
||||
dbEmptyWait, _ = meter.Float64ObservableCounter("messenger.db.pool.empty_acquire_wait_seconds",
|
||||
metric.WithDescription("Cumulative wait time for empty pool acquisitions"),
|
||||
metric.WithUnit("s"))
|
||||
processCPU, _ = meter.Float64ObservableCounter("messenger.process.cpu_seconds",
|
||||
metric.WithDescription("Cumulative process CPU time from cgroup or /proc"),
|
||||
metric.WithUnit("s"))
|
||||
processMemory, _ = meter.Int64ObservableGauge("messenger.process.memory_usage_bytes",
|
||||
metric.WithDescription("Resident/current memory of this container"),
|
||||
metric.WithUnit("By"))
|
||||
processMemLimit, _ = meter.Int64ObservableGauge("messenger.process.memory_limit_bytes",
|
||||
metric.WithDescription("Container memory limit, 0 when unknown"),
|
||||
metric.WithUnit("By"))
|
||||
oldestJobAge, _ = meter.Float64ObservableGauge("messenger.queue.oldest_job_age",
|
||||
metric.WithDescription("Age of the oldest queued or processing job"),
|
||||
metric.WithUnit("s"))
|
||||
oldestOutboxAge, _ = meter.Float64ObservableGauge("messenger.outbox.oldest_unpublished_age",
|
||||
metric.WithDescription("Age of the oldest unpublished outbox intent"),
|
||||
metric.WithUnit("s"))
|
||||
jobsOverdue, _ = meter.Int64ObservableGauge("messenger.jobs.overdue",
|
||||
metric.WithDescription("Queued/processing jobs older than the 30s TTR objective"))
|
||||
})
|
||||
}
|
||||
|
||||
// RecordHTTP records one completed server request. route must be an OpenAPI
|
||||
// template, never a raw path.
|
||||
func RecordHTTP(ctx context.Context, method, route string, status int, duration time.Duration) {
|
||||
initMetrics()
|
||||
class := statusClass(status)
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("http.request.method", method),
|
||||
attribute.String("http.route", route),
|
||||
attribute.Int("http.response.status_code", status),
|
||||
attribute.String("http.response.status_class", class),
|
||||
)
|
||||
httpDuration.Record(ctx, duration.Seconds(), attrs)
|
||||
}
|
||||
|
||||
// RecordJobAccepted counts a durable 202 acceptance.
|
||||
func RecordJobAccepted(ctx context.Context, pipelineVersion int) {
|
||||
initMetrics()
|
||||
jobsAccepted.Add(ctx, 1, metric.WithAttributes(attribute.Int("pipeline.version", pipelineVersion)))
|
||||
}
|
||||
|
||||
// RecordJobAttempt records one processing attempt.
|
||||
func RecordJobAttempt(ctx context.Context, jobType, outcome string, duration time.Duration) {
|
||||
initMetrics()
|
||||
attrs := metric.WithAttributes(
|
||||
attribute.String("job.type", jobType),
|
||||
attribute.String("outcome", outcome),
|
||||
)
|
||||
jobsProcessed.Add(ctx, 1, attrs)
|
||||
jobDuration.Record(ctx, duration.Seconds(), attrs)
|
||||
}
|
||||
|
||||
// RecordJobReady records a terminal ready result and its time-to-ready.
|
||||
func RecordJobReady(ctx context.Context, pipelineVersion int, duration time.Duration) {
|
||||
initMetrics()
|
||||
attrs := metric.WithAttributes(attribute.Int("pipeline.version", pipelineVersion))
|
||||
timeToReady.Record(ctx, duration.Seconds(), attrs)
|
||||
if duration <= 30*time.Second {
|
||||
jobsReadyInBudget.Add(ctx, 1, attrs)
|
||||
}
|
||||
}
|
||||
|
||||
// RegisterWorkerMetrics exposes the worker's in-flight slots and capacity.
|
||||
// RegisterRelayMetrics exposes durable backlog age gauges computed in the relay.
|
||||
func RegisterRelayMetrics(oldestJob func(context.Context) (float64, error), oldestOutbox func(context.Context) (time.Duration, error), overdue func(context.Context) (int64, error)) error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
if oldestJob != nil {
|
||||
if seconds, err := oldestJob(ctx); err == nil {
|
||||
o.ObserveFloat64(oldestJobAge, seconds)
|
||||
}
|
||||
}
|
||||
if oldestOutbox != nil {
|
||||
if age, err := oldestOutbox(ctx); err == nil {
|
||||
o.ObserveFloat64(oldestOutboxAge, age.Seconds())
|
||||
}
|
||||
}
|
||||
if overdue != nil {
|
||||
if count, err := overdue(ctx); err == nil {
|
||||
o.ObserveInt64(jobsOverdue, count)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, oldestJobAge, oldestOutboxAge, jobsOverdue)
|
||||
return err
|
||||
}
|
||||
|
||||
// RecordTTRMissed records jobs marked as TTR misses by the relay sweeper.
|
||||
func RecordTTRMissed(ctx context.Context, count int64) {
|
||||
initMetrics()
|
||||
// Add zero at relay startup so the counter exists before the first miss;
|
||||
// otherwise the first rate() window loses the initial increment.
|
||||
ttrMissed.Add(ctx, count)
|
||||
}
|
||||
|
||||
func RegisterWorkerMetrics(busy func() int64, capacity int64) error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
o.ObserveInt64(workerBusy, busy())
|
||||
o.ObserveInt64(workerCapacity, capacity)
|
||||
return nil
|
||||
}, workerBusy, workerCapacity)
|
||||
return err
|
||||
}
|
||||
|
||||
func statusClass(status int) string {
|
||||
if status < 100 || status > 599 {
|
||||
return "unknown"
|
||||
}
|
||||
return strconv.Itoa(status/100) + "xx"
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
)
|
||||
|
||||
type tracedStore struct {
|
||||
inner objectstore.Store
|
||||
}
|
||||
|
||||
// WrapStore adds S3 client spans without recording object keys (keys contain
|
||||
// chat_id) or presigned URLs.
|
||||
func WrapStore(inner objectstore.Store) objectstore.Store {
|
||||
if inner == nil {
|
||||
return nil
|
||||
}
|
||||
return &tracedStore{inner: inner}
|
||||
}
|
||||
|
||||
func (s *tracedStore) start(ctx context.Context, operation string) (context.Context, trace.Span) {
|
||||
return otel.Tracer("messenger/s3").Start(ctx, "S3."+operation,
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("rpc.system", "aws.s3"),
|
||||
attribute.String("rpc.service", "S3"),
|
||||
attribute.String("rpc.method", operation),
|
||||
attribute.String("aws.s3.operation", operation),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Ping(ctx context.Context) error {
|
||||
ctx, span := s.start(ctx, "Ping")
|
||||
defer span.End()
|
||||
return s.inner.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error {
|
||||
ctx, span := s.start(ctx, "PutObject")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.Int64("aws.s3.object.size", size))
|
||||
return s.inner.Put(ctx, key, body, size, contentType, metadata)
|
||||
}
|
||||
|
||||
type spanReadCloser struct {
|
||||
inner io.ReadCloser
|
||||
span trace.Span
|
||||
}
|
||||
|
||||
func (r *spanReadCloser) Read(p []byte) (int, error) { return r.inner.Read(p) }
|
||||
func (r *spanReadCloser) Close() error {
|
||||
err := r.inner.Close()
|
||||
r.span.End()
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *tracedStore) Open(ctx context.Context, key string) (io.ReadCloser, objectstore.Object, error) {
|
||||
ctx, span := s.start(ctx, "GetObject")
|
||||
body, object, err := s.inner.Open(ctx, key)
|
||||
if err != nil {
|
||||
span.RecordError(errors.New(Redact(err.Error())))
|
||||
span.End()
|
||||
return nil, object, err
|
||||
}
|
||||
span.SetAttributes(attribute.Int64("aws.s3.object.size", object.Size))
|
||||
return &spanReadCloser{inner: body, span: span}, object, nil
|
||||
}
|
||||
|
||||
func (s *tracedStore) Head(ctx context.Context, key string) (objectstore.Object, error) {
|
||||
ctx, span := s.start(ctx, "HeadObject")
|
||||
defer span.End()
|
||||
return s.inner.Head(ctx, key)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error {
|
||||
ctx, span := s.start(ctx, "CopyObject")
|
||||
defer span.End()
|
||||
return s.inner.Copy(ctx, src, dst, contentType, metadata)
|
||||
}
|
||||
|
||||
func (s *tracedStore) Delete(ctx context.Context, key string) error {
|
||||
ctx, span := s.start(ctx, "DeleteObject")
|
||||
defer span.End()
|
||||
return s.inner.Delete(ctx, key)
|
||||
}
|
||||
|
||||
func (s *tracedStore) List(ctx context.Context, prefix string) ([]objectstore.Object, error) {
|
||||
ctx, span := s.start(ctx, "ListObjects")
|
||||
defer span.End()
|
||||
return s.inner.List(ctx, prefix)
|
||||
}
|
||||
|
||||
func (s *tracedStore) PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error) {
|
||||
ctx, span := s.start(ctx, "PresignPut")
|
||||
defer span.End()
|
||||
span.SetAttributes(attribute.Int64("aws.s3.object.size", size), attribute.String("aws.s3.presign.ttl", ttl.String()))
|
||||
return s.inner.PresignPut(ctx, key, size, ttl)
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
// RegisterProcessMetrics exposes this process/container CPU and memory. It
|
||||
// uses cgroup v2 when available and /proc as a fallback. The metrics are
|
||||
// intentionally process-scoped: no Docker socket or host root is required.
|
||||
func RegisterProcessMetrics() error {
|
||||
initMetrics()
|
||||
_, err := otel.Meter("messenger").RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
cpu, memory, limit := readProcessStats()
|
||||
o.ObserveFloat64(processCPU, cpu)
|
||||
o.ObserveInt64(processMemory, memory)
|
||||
o.ObserveInt64(processMemLimit, limit)
|
||||
return nil
|
||||
}, processCPU, processMemory, processMemLimit)
|
||||
return err
|
||||
}
|
||||
|
||||
func readProcessStats() (cpuSeconds float64, memoryBytes, memoryLimit int64) {
|
||||
if value, ok := readCgroupCPU(); ok {
|
||||
cpuSeconds = value
|
||||
} else {
|
||||
cpuSeconds = readProcCPU()
|
||||
}
|
||||
memoryBytes = readCgroupMemory()
|
||||
if memoryBytes == 0 {
|
||||
memoryBytes = readProcRSS()
|
||||
}
|
||||
memoryLimit = readCgroupMemoryLimit()
|
||||
return cpuSeconds, memoryBytes, memoryLimit
|
||||
}
|
||||
|
||||
func readCgroupCPU() (float64, bool) {
|
||||
raw, err := os.ReadFile("/sys/fs/cgroup/cpu.stat")
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
for _, line := range strings.Split(string(raw), "\n") {
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) == 2 && fields[0] == "usage_usec" {
|
||||
usec, err := strconv.ParseFloat(fields[1], 64)
|
||||
if err == nil {
|
||||
return usec / 1e6, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func readProcCPU() float64 {
|
||||
raw, err := os.ReadFile("/proc/self/stat")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
// comm may contain spaces; fields after the closing parenthesis are stable.
|
||||
end := strings.LastIndexByte(string(raw), ')')
|
||||
if end < 0 {
|
||||
return 0
|
||||
}
|
||||
fields := strings.Fields(string(raw)[end+1:])
|
||||
if len(fields) < 15 {
|
||||
return 0
|
||||
}
|
||||
utime, _ := strconv.ParseFloat(fields[11], 64)
|
||||
stime, _ := strconv.ParseFloat(fields[12], 64)
|
||||
return (utime + stime) / 100 // USER_HZ on Linux is 100 in the images used.
|
||||
}
|
||||
|
||||
func readCgroupMemory() int64 {
|
||||
for _, path := range []string{"/sys/fs/cgroup/memory.current", "/sys/fs/cgroup/memory/memory.usage_in_bytes"} {
|
||||
if raw, err := os.ReadFile(path); err == nil {
|
||||
if value, err := strconv.ParseInt(strings.TrimSpace(string(raw)), 10, 64); err == nil {
|
||||
return value
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func readCgroupMemoryLimit() int64 {
|
||||
for _, path := range []string{"/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"} {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
value := strings.TrimSpace(string(raw))
|
||||
if value == "max" {
|
||||
return 0
|
||||
}
|
||||
if parsed, err := strconv.ParseInt(value, 10, 64); err == nil {
|
||||
return parsed
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func readProcRSS() int64 {
|
||||
file, err := os.Open("/proc/self/status")
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
scanner := bufio.NewScanner(file)
|
||||
for scanner.Scan() {
|
||||
fields := strings.Fields(scanner.Text())
|
||||
if len(fields) >= 2 && fields[0] == "VmRSS:" {
|
||||
if kb, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
|
||||
return kb * 1024
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
// Package telemetry wires OpenTelemetry traces, metrics and logs to OTLP and
|
||||
// provides the small set of instruments used by the application. Telemetry is
|
||||
// best-effort: a missing Collector must never fail startup or readiness.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdklog "go.opentelemetry.io/otel/sdk/log"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.37.0"
|
||||
|
||||
"mtusi-messenger/internal/platform/instanceid"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
// Shutdown flushes and closes providers. It is safe to call once.
|
||||
type Shutdown func(context.Context) error
|
||||
|
||||
var globalLogProvider *sdklog.LoggerProvider
|
||||
|
||||
// Enabled reports whether TELEMETRY_ENABLED is not explicitly disabled.
|
||||
func Enabled() bool {
|
||||
return strings.ToLower(strings.TrimSpace(os.Getenv("TELEMETRY_ENABLED"))) != "0"
|
||||
}
|
||||
|
||||
// Setup configures global OTel providers. Exporters are asynchronous and do
|
||||
// not connect synchronously; an unreachable Collector only produces bounded
|
||||
// background export failures.
|
||||
func Setup(ctx context.Context, serviceName, version string) (Shutdown, error) {
|
||||
if !Enabled() {
|
||||
return func(context.Context) error { return nil }, nil
|
||||
}
|
||||
|
||||
traceEndpoint, err := telemetryEndpoint("TRACES")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metricEndpoint, err := telemetryEndpoint("METRICS")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
logEndpoint, err := telemetryEndpoint("LOGS")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
interval, err := metricInterval()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sampler, err := samplerFromEnv()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv("")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure telemetry tls: %w", err)
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSClientConfig: clientTLS,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 5 * time.Second,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
MaxIdleConnsPerHost: 4,
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Transport: transport,
|
||||
Timeout: 5 * time.Second,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("telemetry: redirects are not permitted")
|
||||
},
|
||||
}
|
||||
|
||||
// resource.Default carries the SDK's schema URL (currently 1.43.0); using a
|
||||
// different semconv schema in NewWithAttributes conflicts. The code resource
|
||||
// is schemaless, while the SDK still provides telemetry.sdk.* attributes.
|
||||
res, err := resource.Merge(
|
||||
resource.Default(),
|
||||
resource.NewSchemaless(
|
||||
semconv.ServiceName(serviceName),
|
||||
semconv.ServiceVersion(defaultVersion(version)),
|
||||
semconv.ServiceInstanceID(instanceid.FromEnvOrHostname()),
|
||||
semconv.DeploymentEnvironmentName("lab"),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build telemetry resource: %w", err)
|
||||
}
|
||||
|
||||
traceExporter, err := otlptracehttp.New(ctx,
|
||||
otlptracehttp.WithEndpointURL(traceEndpoint),
|
||||
otlptracehttp.WithHTTPClient(httpClient),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create trace exporter: %w", err)
|
||||
}
|
||||
metricExporter, err := otlpmetrichttp.New(ctx,
|
||||
otlpmetrichttp.WithEndpointURL(metricEndpoint),
|
||||
otlpmetrichttp.WithHTTPClient(httpClient),
|
||||
)
|
||||
if err != nil {
|
||||
transport.CloseIdleConnections()
|
||||
return nil, errors.Join(fmt.Errorf("create metric exporter: %w", err), traceExporter.Shutdown(ctx))
|
||||
}
|
||||
logExporter, err := otlploghttp.New(ctx,
|
||||
otlploghttp.WithEndpointURL(logEndpoint),
|
||||
otlploghttp.WithHTTPClient(httpClient),
|
||||
)
|
||||
if err != nil {
|
||||
transport.CloseIdleConnections()
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("create log exporter: %w", err),
|
||||
traceExporter.Shutdown(ctx),
|
||||
metricExporter.Shutdown(ctx),
|
||||
)
|
||||
}
|
||||
|
||||
tracerProvider := sdktrace.NewTracerProvider(
|
||||
sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sampler),
|
||||
sdktrace.WithBatcher(traceExporter,
|
||||
sdktrace.WithMaxQueueSize(2048),
|
||||
sdktrace.WithMaxExportBatchSize(512),
|
||||
sdktrace.WithBatchTimeout(5*time.Second),
|
||||
sdktrace.WithExportTimeout(5*time.Second),
|
||||
),
|
||||
)
|
||||
|
||||
meterProvider := sdkmetric.NewMeterProvider(
|
||||
sdkmetric.WithResource(res),
|
||||
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(
|
||||
metricExporter,
|
||||
sdkmetric.WithInterval(interval),
|
||||
sdkmetric.WithTimeout(5*time.Second),
|
||||
)),
|
||||
)
|
||||
|
||||
loggerProvider := sdklog.NewLoggerProvider(
|
||||
sdklog.WithResource(res),
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(
|
||||
logExporter,
|
||||
sdklog.WithExportInterval(5*time.Second),
|
||||
sdklog.WithExportTimeout(5*time.Second),
|
||||
sdklog.WithMaxQueueSize(2048),
|
||||
sdklog.WithExportMaxBatchSize(512),
|
||||
)),
|
||||
)
|
||||
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
otel.SetMeterProvider(meterProvider)
|
||||
otel.SetLoggerProvider(loggerProvider)
|
||||
otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(
|
||||
propagation.TraceContext{},
|
||||
propagation.Baggage{},
|
||||
))
|
||||
|
||||
globalLogProvider = loggerProvider
|
||||
initMetrics()
|
||||
|
||||
var shutdownOnce sync.Once
|
||||
var shutdownErr error
|
||||
return func(shutdownCtx context.Context) error {
|
||||
shutdownOnce.Do(func() {
|
||||
// Each flush is bounded by both a small budget and the caller's
|
||||
// overall shutdown deadline. Never revive a cancelled shutdown.
|
||||
flush := func(fn func(context.Context) error) error {
|
||||
ctx, cancel := context.WithTimeout(shutdownCtx, 2*time.Second)
|
||||
defer cancel()
|
||||
return fn(ctx)
|
||||
}
|
||||
shutdownErr = errors.Join(
|
||||
flush(tracerProvider.Shutdown),
|
||||
flush(meterProvider.Shutdown),
|
||||
flush(loggerProvider.Shutdown),
|
||||
)
|
||||
transport.CloseIdleConnections()
|
||||
})
|
||||
return shutdownErr
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GlobalLoggerProvider exposes the configured log provider for the slog fanout.
|
||||
func GlobalLoggerProvider() *sdklog.LoggerProvider {
|
||||
return globalLogProvider
|
||||
}
|
||||
|
||||
func defaultVersion(version string) string {
|
||||
if strings.TrimSpace(version) == "" {
|
||||
return "dev"
|
||||
}
|
||||
return version
|
||||
}
|
||||
|
||||
func metricInterval() (time.Duration, error) {
|
||||
raw := strings.TrimSpace(os.Getenv("OTEL_METRIC_EXPORT_INTERVAL"))
|
||||
if raw == "" {
|
||||
return 15 * time.Second, nil
|
||||
}
|
||||
ms, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || ms <= 0 || ms > math.MaxInt64/int64(time.Millisecond) {
|
||||
return 0, errors.New("telemetry: invalid otel_metric_export_interval")
|
||||
}
|
||||
return time.Duration(ms) * time.Millisecond, nil
|
||||
}
|
||||
|
||||
func samplerFromEnv() (sdktrace.Sampler, error) {
|
||||
name := strings.ToLower(strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER")))
|
||||
ratio := 1.0
|
||||
if raw := strings.TrimSpace(os.Getenv("OTEL_TRACES_SAMPLER_ARG")); raw != "" {
|
||||
parsed, err := strconv.ParseFloat(raw, 64)
|
||||
if err != nil || math.IsNaN(parsed) || parsed < 0 || parsed > 1 {
|
||||
return nil, errors.New("telemetry: invalid otel_traces_sampler_arg")
|
||||
}
|
||||
ratio = parsed
|
||||
}
|
||||
switch name {
|
||||
case "always_off":
|
||||
return sdktrace.NeverSample(), nil
|
||||
case "always_on":
|
||||
return sdktrace.AlwaysSample(), nil
|
||||
case "parentbased_always_off":
|
||||
return sdktrace.ParentBased(sdktrace.NeverSample()), nil
|
||||
case "traceidratio":
|
||||
return sdktrace.TraceIDRatioBased(ratio), nil
|
||||
case "parentbased_traceidratio":
|
||||
return sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio)), nil
|
||||
case "", "parentbased_always_on":
|
||||
return sdktrace.ParentBased(sdktrace.AlwaysSample()), nil
|
||||
default:
|
||||
return nil, errors.New("telemetry: invalid otel_traces_sampler")
|
||||
}
|
||||
}
|
||||
|
||||
// Signal-specific OTLP settings override the generic settings. Endpoint parsing
|
||||
// happens here because SDK environment parsing otherwise silently uses defaults.
|
||||
func telemetryEndpoint(signal string) (string, error) {
|
||||
prefix := "OTEL_EXPORTER_OTLP_" + signal + "_"
|
||||
setting := func(suffix string) string {
|
||||
if value := strings.TrimSpace(os.Getenv(prefix + suffix)); value != "" {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_" + suffix))
|
||||
}
|
||||
if raw := setting("INSECURE"); raw != "" {
|
||||
insecure, err := strconv.ParseBool(raw)
|
||||
if err != nil || insecure {
|
||||
return "", errors.New("telemetry: otlp insecure transport is not permitted")
|
||||
}
|
||||
}
|
||||
if protocol := setting("PROTOCOL"); protocol != "" && protocol != "http/protobuf" {
|
||||
return "", errors.New("telemetry: otlp protocol must be http/protobuf")
|
||||
}
|
||||
raw := strings.TrimSpace(os.Getenv(prefix + "ENDPOINT"))
|
||||
isSignalEndpoint := raw != ""
|
||||
if raw == "" {
|
||||
raw = strings.TrimSpace(os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"))
|
||||
}
|
||||
if raw == "" {
|
||||
raw = "https://otel-collector:4318"
|
||||
}
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
|
||||
return "", errors.New("telemetry: otlp endpoint must be an https url without credentials")
|
||||
}
|
||||
if u.RawQuery != "" || u.Fragment != "" {
|
||||
return "", errors.New("telemetry: otlp endpoint must not contain a query or fragment")
|
||||
}
|
||||
if !isSignalEndpoint || u.Path == "" {
|
||||
u.Path = strings.TrimRight(u.Path, "/") + "/v1/" + strings.ToLower(signal)
|
||||
u.RawPath = ""
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
Reference in New Issue
Block a user