forked from mtusi2026/mtusi2026lab6
217 lines
8.4 KiB
Go
217 lines
8.4 KiB
Go
package telemetry
|
|
|
|
import (
|
|
"backend/internal/domain/model"
|
|
"context"
|
|
"fmt"
|
|
"github.com/go-chi/chi/v5"
|
|
chimiddleware "github.com/go-chi/chi/v5/middleware"
|
|
"github.com/google/uuid"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp"
|
|
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
|
logapi "go.opentelemetry.io/otel/log"
|
|
"go.opentelemetry.io/otel/metric"
|
|
"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"
|
|
"go.opentelemetry.io/otel/trace"
|
|
"math"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
type Telemetry struct {
|
|
traces *sdktrace.TracerProvider
|
|
meters *sdkmetric.MeterProvider
|
|
logs *sdklog.LoggerProvider
|
|
logger logapi.Logger
|
|
requests metric.Int64Counter
|
|
durations metric.Float64Histogram
|
|
jobs metric.Int64Counter
|
|
jobDuration metric.Float64Histogram
|
|
readyDuration metric.Float64Histogram
|
|
busy atomic.Int64
|
|
poolPending atomic.Int64
|
|
observationFailures atomic.Int64
|
|
dbAcquire metric.Float64Histogram
|
|
worker bool
|
|
}
|
|
|
|
var current atomic.Pointer[Telemetry]
|
|
|
|
func Setup(ctx context.Context, service string) (*Telemetry, error) {
|
|
endpoint := os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT")
|
|
if endpoint == "" || os.Getenv("OTEL_SDK_DISABLED") == "true" {
|
|
return nil, nil
|
|
}
|
|
ratio := 1.0
|
|
if s := os.Getenv("OTEL_TRACES_SAMPLER_ARG"); s != "" {
|
|
parsed, err := strconv.ParseFloat(s, 64)
|
|
ratio = parsed
|
|
if err != nil || math.IsNaN(ratio) || math.IsInf(ratio, 0) || ratio < 0 || ratio > 1 {
|
|
return nil, fmt.Errorf("invalid sampling ratio")
|
|
}
|
|
}
|
|
resource := resource.NewWithAttributes("", attribute.String("service.name", service), attribute.String("service.version", "lab6-v1"), attribute.String("service.instance.id", uuid.NewString()), attribute.String("deployment.environment.name", "lab"))
|
|
tx, e := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(time.Second), otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
mx, e := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(time.Second), otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
lx, e := otlploghttp.New(ctx, otlploghttp.WithTimeout(time.Second), otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
t := &Telemetry{
|
|
worker: service == "messenger-worker",
|
|
traces: sdktrace.NewTracerProvider(sdktrace.WithResource(resource), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio))), sdktrace.WithBatcher(tx, sdktrace.WithMaxQueueSize(128), sdktrace.WithMaxExportBatchSize(32), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(time.Second))),
|
|
meters: sdkmetric.NewMeterProvider(sdkmetric.WithResource(resource), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(mx, sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(time.Second)))),
|
|
logs: sdklog.NewLoggerProvider(sdklog.WithResource(resource), sdklog.WithProcessor(sdklog.NewBatchProcessor(lx, sdklog.WithMaxQueueSize(128), sdklog.WithExportMaxBatchSize(32), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(time.Second)))),
|
|
}
|
|
otel.SetTracerProvider(t.traces)
|
|
otel.SetMeterProvider(t.meters)
|
|
otel.SetTextMapPropagator(propagation.TraceContext{})
|
|
t.logger = t.logs.Logger("messenger")
|
|
meter := t.meters.Meter("messenger")
|
|
t.requests, e = meter.Int64Counter("http_requests", metric.WithDescription("Business HTTP requests"))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
t.durations, e = meter.Float64Histogram("http_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.005, .01, .025, .05, .1, .25, .5, 1, 2, 5))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
t.jobs, e = meter.Int64Counter("jobs_processed", metric.WithDescription("Owned processing attempts by result"))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
t.jobDuration, e = meter.Float64Histogram("job_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.01, .05, .1, .25, .5, 1, 2, 5, 10, 20))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
t.dbAcquire, e = meter.Float64Histogram("db_pool_acquire_duration", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.001, .005, .01, .025, .05, .1, .25, .5, 1, 2))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
t.readyDuration, e = meter.Float64Histogram("time_to_ready", metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.1, .5, 1, 2, 5, 10, 30, 60, 120))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
current.Store(t)
|
|
return t, nil
|
|
}
|
|
func (t *Telemetry) Shutdown(ctx context.Context) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
_ = t.traces.Shutdown(ctx)
|
|
_ = t.meters.Shutdown(ctx)
|
|
_ = t.logs.Shutdown(ctx)
|
|
}
|
|
func (t *Telemetry) Event(ctx context.Context, event, outcome string, extra ...attribute.KeyValue) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
var record logapi.Record
|
|
record.SetTimestamp(time.Now())
|
|
record.SetSeverity(logapi.SeverityInfo)
|
|
record.SetSeverityText("INFO")
|
|
record.SetBody(attribute.StringValue(event))
|
|
record.SetEventName(event)
|
|
record.AddAttributes(attribute.String("event", event), attribute.String("outcome", outcome))
|
|
record.AddAttributes(extra...)
|
|
t.logger.Emit(ctx, record)
|
|
}
|
|
func HTTP(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
t := current.Load()
|
|
if t == nil {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
ctx := otel.GetTextMapPropagator().Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
|
ctx, span := otel.Tracer("messenger").Start(ctx, "HTTP", trace.WithSpanKind(trace.SpanKindServer))
|
|
defer span.End()
|
|
carrier := propagation.MapCarrier{}
|
|
otel.GetTextMapPropagator().Inject(ctx, carrier)
|
|
ctx = model.WithTrace(ctx, carrier.Get("traceparent"), carrier.Get("tracestate"))
|
|
ww := chimiddleware.NewWrapResponseWriter(w, r.ProtoMajor)
|
|
start := time.Now()
|
|
next.ServeHTTP(ww, r.WithContext(ctx))
|
|
route := chi.RouteContext(r.Context()).RoutePattern()
|
|
if route == "" {
|
|
route = "unmatched"
|
|
}
|
|
code := ww.Status()
|
|
if code == 0 {
|
|
code = 200
|
|
}
|
|
outcome := fmt.Sprintf("%dxx", code/100)
|
|
method := r.Method
|
|
switch method {
|
|
case "GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS", "HEAD":
|
|
default:
|
|
method = "OTHER"
|
|
}
|
|
attrs := []attribute.KeyValue{attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", outcome)}
|
|
span.SetName(r.Method + " " + route)
|
|
span.SetAttributes(attrs...)
|
|
if code >= 500 {
|
|
span.SetStatus(codes.Error, "server_error")
|
|
}
|
|
if route != "/health/ready" && route != "/health/live" {
|
|
t.requests.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
t.durations.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(attrs...))
|
|
}
|
|
if id := ww.Header().Get("X-Request-Id"); id != "" {
|
|
t.Event(ctx, "http.request", outcome, attribute.String("request_id", id))
|
|
} else {
|
|
t.Event(ctx, "http.request", outcome)
|
|
}
|
|
})
|
|
}
|
|
func (t *Telemetry) Worker(next func(context.Context, model.Job) error) func(context.Context, model.Job) error {
|
|
return func(ctx context.Context, j model.Job) error {
|
|
if t == nil {
|
|
return next(ctx, j)
|
|
}
|
|
t.busy.Add(1)
|
|
defer t.busy.Add(-1)
|
|
ctx = otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": j.Traceparent, "tracestate": j.Tracestate})
|
|
ctx, span := otel.Tracer("messenger").Start(ctx, "attachment.process", trace.WithSpanKind(trace.SpanKindConsumer))
|
|
defer span.End()
|
|
e := next(ctx, j)
|
|
outcome := "processed"
|
|
if e != nil {
|
|
outcome = "dependency_error"
|
|
span.SetStatus(codes.Error, outcome)
|
|
}
|
|
t.Event(ctx, "worker.delivery", outcome)
|
|
return e
|
|
}
|
|
}
|
|
func (t *Telemetry) JobResult(ctx context.Context, j model.Job, outcome string, d time.Duration) {
|
|
if t == nil {
|
|
return
|
|
}
|
|
attrs := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
|
t.jobs.Add(ctx, 1, attrs)
|
|
t.jobDuration.Record(ctx, d.Seconds(), attrs)
|
|
if outcome == "ready" {
|
|
t.readyDuration.Record(ctx, time.Since(j.CreatedAt).Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process.v1")))
|
|
}
|
|
t.Event(ctx, "worker.job", outcome)
|
|
}
|