forked from mtusi2026/mtusi2026lab6
Реализация на 5
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/go-chi/chi/v5"
|
||||
mw "github.com/go-chi/chi/v5/middleware"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
func HTTP(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, sp := Start(Extract(r.Context(), r.Header.Get("traceparent"), r.Header.Get("tracestate")), "HTTP", trace.SpanKindServer)
|
||||
start := time.Now()
|
||||
ww := mw.NewWrapResponseWriter(w, r.ProtoMajor)
|
||||
defer func() {
|
||||
route := chi.RouteContext(ctx).RoutePattern()
|
||||
if route == "" {
|
||||
route = "unmatched"
|
||||
}
|
||||
method := r.Method
|
||||
switch method {
|
||||
case "GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS":
|
||||
default:
|
||||
method = "OTHER"
|
||||
}
|
||||
status := ww.Status()
|
||||
if status == 0 {
|
||||
status = 200
|
||||
}
|
||||
sp.SetName(method + " " + route)
|
||||
sp.SetAttributes(attribute.String("http.route", route), attribute.String("http.request.method", method), attribute.Int("http.response.status_code", status))
|
||||
if status >= 500 {
|
||||
sp.SetStatus(codes.Error, "server_error")
|
||||
}
|
||||
a := []attribute.KeyValue{attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", strconv.Itoa(status/100)+"xx")}
|
||||
Count(ctx, "messenger.http.requests", 1, a...)
|
||||
Duration(ctx, "messenger.http.duration", time.Since(start), a[:2]...)
|
||||
slog.InfoContext(ctx, "http_request", "method", method, "route", route, "status", status, "request_id", w.Header().Get("X-Request-Id"))
|
||||
sp.End()
|
||||
}()
|
||||
next.ServeHTTP(ww, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// RegisterRoute publishes zero counters before any outcome, preserving the first spike.
|
||||
func RegisterRoute(method, route string) {
|
||||
for _, class := range []string{"1xx", "2xx", "3xx", "4xx", "5xx"} {
|
||||
Count(context.Background(), "messenger.http.requests", 0, attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", class))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var QueueDepth atomic.Int64
|
||||
var observationMu sync.RWMutex
|
||||
|
||||
type observationSnapshot struct {
|
||||
Queued, Outbox, Good, Bad int64
|
||||
Locked int64
|
||||
Oldest float64
|
||||
}
|
||||
|
||||
var snapshot observationSnapshot
|
||||
var observed time.Time
|
||||
|
||||
func PublishObservation(queued, outbox, good, bad int64, oldest float64, locked int64) {
|
||||
s := observationSnapshot{Queued: queued, Outbox: outbox, Good: good, Bad: bad, Oldest: oldest, Locked: locked}
|
||||
observationMu.Lock()
|
||||
snapshot = s
|
||||
observed = time.Now()
|
||||
observationMu.Unlock()
|
||||
}
|
||||
func RegisterObservation() {
|
||||
locks, _ := meter.Int64ObservableGauge("messenger.db.locks.waiting")
|
||||
pending, _ := meter.Int64ObservableGauge("messenger.jobs.pending")
|
||||
outbox, _ := meter.Int64ObservableGauge("messenger.outbox.pending")
|
||||
queue, _ := meter.Int64ObservableGauge("messenger.queue.depth")
|
||||
age, _ := meter.Float64ObservableGauge("messenger.queue.oldest.age", metric.WithUnit("s"))
|
||||
fresh, _ := meter.Float64ObservableGauge("messenger.observation.timestamp")
|
||||
slo, _ := meter.Int64ObservableCounter("messenger.ready.slo")
|
||||
_, _ = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
observationMu.RLock()
|
||||
s, t := snapshot, observed
|
||||
observationMu.RUnlock()
|
||||
if t.IsZero() {
|
||||
return nil
|
||||
}
|
||||
o.ObserveInt64(locks, s.Locked)
|
||||
o.ObserveInt64(pending, s.Queued)
|
||||
o.ObserveInt64(outbox, s.Outbox)
|
||||
o.ObserveInt64(queue, QueueDepth.Load(), metric.WithAttributes(attribute.String("queue", "attachments.v1")))
|
||||
o.ObserveFloat64(age, s.Oldest, metric.WithAttributes(attribute.String("queue", "attachments.v1")))
|
||||
o.ObserveFloat64(fresh, float64(t.Unix()))
|
||||
o.ObserveInt64(slo, s.Good, metric.WithAttributes(attribute.String("outcome", "good")))
|
||||
o.ObserveInt64(slo, s.Bad, metric.WithAttributes(attribute.String("outcome", "bad")))
|
||||
return nil
|
||||
}, locks, pending, outbox, queue, age, fresh, slo)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/shirou/gopsutil/v4/process"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
var waiting atomic.Int64
|
||||
|
||||
func ObservePool(pool *pgxpool.Pool, capacity int) {
|
||||
names := []string{"messenger.db.pool.used", "messenger.db.pool.capacity", "messenger.db.pool.waiting", "messenger.worker.busy", "messenger.worker.capacity", "messenger.process.memory", "messenger.process.cpu", "messenger.telemetry.export_errors"}
|
||||
instruments := make([]metric.Float64ObservableGauge, len(names))
|
||||
for i, n := range names {
|
||||
instruments[i], _ = meter.Float64ObservableGauge(n)
|
||||
}
|
||||
p, _ := process.NewProcess(int32(os.Getpid()))
|
||||
obs := make([]metric.Observable, len(instruments))
|
||||
for i, g := range instruments {
|
||||
obs[i] = g
|
||||
}
|
||||
_, _ = meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {
|
||||
st := pool.Stat()
|
||||
v := []float64{float64(st.AcquiredConns()), float64(st.MaxConns()), float64(waiting.Load()), float64(Busy.Load()), float64(capacity), 0, 0, float64(ExportErrors.Load())}
|
||||
if p != nil {
|
||||
if m, e := p.MemoryInfoWithContext(ctx); e == nil {
|
||||
v[5] = float64(m.RSS)
|
||||
}
|
||||
if t, e := p.TimesWithContext(ctx); e == nil {
|
||||
v[6] = t.User + t.System
|
||||
}
|
||||
}
|
||||
for i, g := range instruments {
|
||||
o.ObserveFloat64(g, v[i])
|
||||
}
|
||||
return nil
|
||||
}, obs...)
|
||||
}
|
||||
|
||||
type DBTracer struct{}
|
||||
type acquireKey struct{}
|
||||
|
||||
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
|
||||
op := "OTHER"
|
||||
f := strings.Fields(d.SQL)
|
||||
if len(f) > 0 {
|
||||
switch strings.ToUpper(f[0]) {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
||||
op = strings.ToUpper(f[0])
|
||||
}
|
||||
}
|
||||
ctx, sp := Start(ctx, "postgresql "+op, trace.SpanKindClient)
|
||||
sp.SetAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op))
|
||||
return ctx
|
||||
}
|
||||
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
|
||||
End(trace.SpanFromContext(ctx), d.Err)
|
||||
}
|
||||
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
waiting.Add(1)
|
||||
return context.WithValue(ctx, acquireKey{}, time.Now())
|
||||
}
|
||||
func (DBTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, d pgxpool.TraceAcquireEndData) {
|
||||
waiting.Add(-1)
|
||||
if t, ok := ctx.Value(acquireKey{}).(time.Time); ok {
|
||||
Duration(ctx, "messenger.db.acquire.duration", time.Since(t))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Package telemetry owns signal export and safe, low-cardinality instrumentation.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"go.opentelemetry.io/contrib/bridges/otelslog"
|
||||
"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"
|
||||
"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 InstanceID = uuid.NewString()
|
||||
var Busy atomic.Int64
|
||||
var meter = otel.Meter("messenger")
|
||||
var tracer = otel.Tracer("messenger")
|
||||
|
||||
// A fanout retains local JSON and exports the same structured event over OTLP.
|
||||
type handler struct{ local, remote slog.Handler }
|
||||
|
||||
func (h handler) Enabled(c context.Context, l slog.Level) bool { return h.local.Enabled(c, l) }
|
||||
func (h handler) Handle(c context.Context, r slog.Record) error {
|
||||
// Errors can contain SQL values, credentials or invalid request content.
|
||||
safe := slog.NewRecord(r.Time, r.Level, r.Message, r.PC)
|
||||
r.Attrs(func(a slog.Attr) bool {
|
||||
key := strings.ToLower(a.Key)
|
||||
switch key {
|
||||
case "authorization", "password", "token", "session_token", "body", "filename", "url":
|
||||
return true
|
||||
case "error":
|
||||
a = slog.String("error.type", "operation_failed")
|
||||
}
|
||||
safe.AddAttrs(a)
|
||||
return true
|
||||
})
|
||||
r = safe
|
||||
sc := trace.SpanContextFromContext(c)
|
||||
r.AddAttrs(slog.String("event", r.Message))
|
||||
if sc.IsValid() {
|
||||
r.AddAttrs(slog.String("trace_id", sc.TraceID().String()), slog.String("span_id", sc.SpanID().String()))
|
||||
}
|
||||
_ = h.remote.Handle(c, r)
|
||||
return h.local.Handle(c, r)
|
||||
}
|
||||
func (h handler) WithAttrs(a []slog.Attr) slog.Handler {
|
||||
return handler{h.local.WithAttrs(a), h.remote.WithAttrs(a)}
|
||||
}
|
||||
func (h handler) WithGroup(g string) slog.Handler {
|
||||
return handler{h.local.WithGroup(g), h.remote.WithGroup(g)}
|
||||
}
|
||||
|
||||
func Init(ctx context.Context, name string) (func(), error) {
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
if os.Getenv("OTEL_SDK_DISABLED") == "true" {
|
||||
return func() {}, nil
|
||||
}
|
||||
res := resource.NewWithAttributes("", attribute.String("service.name", name), attribute.String("service.version", "lab6"), attribute.String("service.instance.id", InstanceID), attribute.String("deployment.environment.name", "lab"))
|
||||
te, e := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(time.Second))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())), sdktrace.WithBatcher(te, sdktrace.WithMaxQueueSize(1024), sdktrace.WithMaxExportBatchSize(128), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(time.Second)))
|
||||
me, e := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(time.Second))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res), sdkmetric.WithReader(sdkmetric.NewPeriodicReader(me, sdkmetric.WithInterval(5*time.Second), sdkmetric.WithTimeout(time.Second))))
|
||||
le, e := otlploghttp.New(ctx, otlploghttp.WithTimeout(time.Second))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res), sdklog.WithProcessor(sdklog.NewBatchProcessor(le, sdklog.WithMaxQueueSize(1024), sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(time.Second))))
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetMeterProvider(mp)
|
||||
if name == "messenger-worker" {
|
||||
for _, outcome := range []string{"ready", "retry", "failed", "duplicate"} {
|
||||
Count(ctx, "messenger.jobs", 0, attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
||||
}
|
||||
}
|
||||
local := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}).WithAttrs([]slog.Attr{slog.String("service.name", name), slog.String("service.instance.id", InstanceID)})
|
||||
slog.SetDefault(slog.New(handler{local, otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(lp))}))
|
||||
// Export failures are summarized safely and never include payloads or endpoints.
|
||||
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) { ExportErrors.Add(1) }))
|
||||
return func() {
|
||||
c, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
_ = mp.Shutdown(c)
|
||||
_ = lp.Shutdown(c)
|
||||
_ = tp.Shutdown(c)
|
||||
}, nil
|
||||
}
|
||||
|
||||
var ExportErrors atomic.Int64
|
||||
|
||||
func Start(ctx context.Context, name string, kind trace.SpanKind) (context.Context, trace.Span) {
|
||||
return tracer.Start(ctx, name, trace.WithSpanKind(kind))
|
||||
}
|
||||
func End(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "operation_failed")
|
||||
span.SetAttributes(attribute.String("error.type", "dependency_or_processing"))
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
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, p, s string) context.Context {
|
||||
return otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": p, "tracestate": s})
|
||||
}
|
||||
func Count(ctx context.Context, name string, n int64, a ...attribute.KeyValue) {
|
||||
c, _ := meter.Int64Counter(name)
|
||||
c.Add(ctx, n, metric.WithAttributes(a...))
|
||||
}
|
||||
func Duration(ctx context.Context, name string, d time.Duration, a ...attribute.KeyValue) {
|
||||
h, _ := meter.Float64Histogram(name, metric.WithUnit("s"), metric.WithExplicitBucketBoundaries(.005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 30, 60, 120, 300))
|
||||
h.Record(ctx, d.Seconds(), metric.WithAttributes(a...))
|
||||
}
|
||||
Reference in New Issue
Block a user