forked from mtusi2026/mtusi2026lab6
206 lines
8.9 KiB
Go
206 lines
8.9 KiB
Go
// Package observability exports bounded, content-free OTLP signals.
|
|
package observability
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
"os"
|
|
"runtime"
|
|
"strings"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/labstack/echo/v4"
|
|
"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"
|
|
otellog "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"
|
|
)
|
|
|
|
var service string
|
|
var logger otellog.Logger
|
|
var busy atomic.Int64
|
|
var requests metric.Int64Counter
|
|
var duration, jobsDuration, readyDuration metric.Float64Histogram
|
|
var jobs metric.Int64Counter
|
|
var telemetryErrors atomic.Int64
|
|
|
|
func Init(ctx context.Context, name string) (func(), error) {
|
|
service = name
|
|
otel.SetTextMapPropagator(propagation.TraceContext{})
|
|
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { telemetryErrors.Add(1) }))
|
|
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
|
|
return func() {}, nil
|
|
}
|
|
instance, _ := os.Hostname()
|
|
res := resource.NewWithAttributes("", attribute.String("service.name", name), attribute.String("service.version", "lab6"), attribute.String("service.instance.id", instance), attribute.String("deployment.environment.name", "lab"))
|
|
te, err := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(2*time.Second))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithBatcher(te, sdktrace.WithMaxQueueSize(512), sdktrace.WithMaxExportBatchSize(128), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(2*time.Second)))
|
|
otel.SetTracerProvider(tp)
|
|
me, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(2*time.Second))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(me, sdkmetric.WithInterval(5*time.Second), sdkmetric.WithTimeout(2*time.Second))), sdkmetric.WithView(sdkmetric.NewView(sdkmetric.Instrument{Kind: sdkmetric.InstrumentKindHistogram}, sdkmetric.Stream{Aggregation: sdkmetric.AggregationExplicitBucketHistogram{Boundaries: []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 30, 60, 120}}})))
|
|
otel.SetMeterProvider(mp)
|
|
le, err := otlploghttp.New(ctx, otlploghttp.WithTimeout(2*time.Second))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(le, sdklog.WithMaxQueueSize(512), sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(2*time.Second))))
|
|
logger = lp.Logger("messenger")
|
|
m := otel.Meter("messenger")
|
|
requests, _ = m.Int64Counter("messenger_http_requests")
|
|
duration, _ = m.Float64Histogram("messenger_http_duration_seconds", metric.WithUnit("s"))
|
|
jobs, _ = m.Int64Counter("messenger_jobs")
|
|
jobsDuration, _ = m.Float64Histogram("messenger_job_duration_seconds", metric.WithUnit("s"))
|
|
readyDuration, _ = m.Float64Histogram("messenger_attachment_ready_seconds", metric.WithUnit("s"))
|
|
return func() {
|
|
c, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
_ = lp.Shutdown(c)
|
|
_ = mp.Shutdown(c)
|
|
_ = tp.Shutdown(c)
|
|
}, nil
|
|
}
|
|
|
|
func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) {
|
|
return otel.Tracer("messenger").Start(ctx, name, trace.WithSpanKind(kind))
|
|
}
|
|
func Result(span trace.Span, err error) {
|
|
if err != nil {
|
|
span.SetStatus(codes.Error, "dependency unavailable")
|
|
} else {
|
|
span.SetStatus(codes.Ok, "")
|
|
}
|
|
}
|
|
func Inject(ctx context.Context) (string, string) {
|
|
c := propagation.MapCarrier{}
|
|
otel.GetTextMapPropagator().Inject(ctx, c)
|
|
return c.Get("traceparent"), c.Get("tracestate")
|
|
}
|
|
func Extract(ctx context.Context, parent, state string) context.Context {
|
|
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
|
}
|
|
func Log(ctx context.Context, event string, fields map[string]any) {
|
|
sc := trace.SpanContextFromContext(ctx)
|
|
values := map[string]any{"timestamp": time.Now().UTC().Format(time.RFC3339Nano), "severity": "INFO", "service.name": service, "event": event, "trace_id": sc.TraceID().String(), "span_id": sc.SpanID().String()}
|
|
for k, v := range fields {
|
|
values[k] = v
|
|
}
|
|
raw, _ := json.Marshal(values)
|
|
log.Print(string(raw))
|
|
if logger != nil {
|
|
var rec otellog.Record
|
|
rec.SetTimestamp(time.Now())
|
|
rec.SetSeverity(otellog.SeverityInfo)
|
|
rec.SetBody(otellog.StringValue(string(raw)))
|
|
logger.Emit(ctx, rec)
|
|
}
|
|
}
|
|
func Middleware(next echo.HandlerFunc) echo.HandlerFunc {
|
|
return func(c echo.Context) error {
|
|
route := c.Path()
|
|
if route == "" {
|
|
route = "unmatched"
|
|
}
|
|
route = strings.ReplaceAll(strings.ReplaceAll(route, ":chat_id", "{chat_id}"), ":attachment_id", "{attachment_id}")
|
|
ctx, span := Start(otel.GetTextMapPropagator().Extract(c.Request().Context(), propagation.HeaderCarrier(c.Request().Header)), c.Request().Method+" "+route, trace.SpanKindServer)
|
|
defer span.End()
|
|
c.Response().Header().Set("X-Trace-Id", span.SpanContext().TraceID().String())
|
|
c.SetRequest(c.Request().WithContext(ctx))
|
|
start := time.Now()
|
|
err := next(c)
|
|
if err != nil {
|
|
c.Error(err)
|
|
}
|
|
status := c.Response().Status
|
|
class := string(rune('0'+status/100)) + "xx"
|
|
attrs := []attribute.KeyValue{attribute.String("method", c.Request().Method), attribute.String("route", route), attribute.String("status_class", class)}
|
|
span.SetAttributes(append(attrs, attribute.Int("http.response.status_code", status))...)
|
|
if status >= 500 {
|
|
span.SetStatus(codes.Error, "server error")
|
|
}
|
|
if !strings.HasPrefix(route, "/health/") && !strings.HasPrefix(route, "/swagger") && requests != nil {
|
|
requests.Add(ctx, 1, metric.WithAttributes(attrs...))
|
|
duration.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(attrs...))
|
|
}
|
|
Log(ctx, "http.request", map[string]any{"method": c.Request().Method, "route": route, "status": status, "duration_seconds": time.Since(start).Seconds(), "request_id": c.Response().Header().Get("X-Request-Id")})
|
|
return nil
|
|
}
|
|
}
|
|
func JobStart() { busy.Add(1) }
|
|
func JobEnd(ctx context.Context, start, accepted time.Time, outcome string) {
|
|
busy.Add(-1)
|
|
if jobs == nil {
|
|
return
|
|
}
|
|
a := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
|
jobs.Add(ctx, 1, a)
|
|
jobsDuration.Record(ctx, time.Since(start).Seconds(), a)
|
|
if outcome == "ready" {
|
|
readyDuration.Record(ctx, time.Since(accepted).Seconds(), metric.WithAttributes(attribute.String("job_type", "attachment.process.v1")))
|
|
}
|
|
}
|
|
|
|
func ObservePool(pool *pgxpool.Pool, capacity int) {
|
|
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
|
|
return
|
|
}
|
|
m := otel.Meter("messenger")
|
|
names := []string{"messenger_db_pool_used", "messenger_db_pool_waiting", "messenger_db_pool_max", "messenger_worker_busy", "messenger_worker_capacity", "messenger_queue_depth", "messenger_queue_oldest_age_seconds", "messenger_process_memory_bytes", "messenger_process_cpu_seconds_total", "messenger_telemetry_export_errors"}
|
|
gauges := make([]metric.Float64ObservableGauge, len(names))
|
|
for i, n := range names {
|
|
gauges[i], _ = m.Float64ObservableGauge(n)
|
|
}
|
|
_, _ = m.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
|
stat := pool.Stat()
|
|
vals := []float64{float64(stat.AcquiredConns()), float64(waiting.Load()), float64(stat.MaxConns()), float64(busy.Load()), float64(capacity)}
|
|
for i, v := range vals {
|
|
o.ObserveFloat64(gauges[i], v)
|
|
}
|
|
// Only API replicas report the authoritative queue. Sum counts would duplicate it; dashboards use max.
|
|
c, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
|
defer cancel()
|
|
var depth int64
|
|
var age float64
|
|
if pool.QueryRow(c, `SELECT count(*),coalesce(extract(epoch FROM clock_timestamp()-min(created_at)),0) FROM attachment_jobs WHERE state IN ('queued','processing')`).Scan(&depth, &age) == nil {
|
|
a := metric.WithAttributes(attribute.String("queue", "attachments"))
|
|
o.ObserveFloat64(gauges[5], float64(depth), a)
|
|
o.ObserveFloat64(gauges[6], age, a)
|
|
}
|
|
var mem runtime.MemStats
|
|
runtime.ReadMemStats(&mem)
|
|
o.ObserveFloat64(gauges[7], float64(mem.Sys))
|
|
var usage syscall.Rusage
|
|
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
|
|
o.ObserveFloat64(gauges[8], float64(usage.Utime.Sec+usage.Stime.Sec)+float64(usage.Utime.Usec+usage.Stime.Usec)/1e6)
|
|
}
|
|
o.ObserveFloat64(gauges[9], float64(telemetryErrors.Load()))
|
|
return nil
|
|
}, observable(gauges)...)
|
|
}
|
|
func observable(gs []metric.Float64ObservableGauge) []metric.Observable {
|
|
r := make([]metric.Observable, len(gs))
|
|
for i, g := range gs {
|
|
r[i] = g
|
|
}
|
|
return r
|
|
}
|