forked from mtusi2026/mtusi2026lab6
feat: add bounded observability and verified SLO incident alerts
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
type instruments struct {
|
||||
httpRequests metric.Int64Counter
|
||||
httpDuration metric.Float64Histogram
|
||||
jobs metric.Int64Counter
|
||||
jobDuration metric.Float64Histogram
|
||||
ready metric.Float64Histogram
|
||||
busy atomic.Int64
|
||||
waiting atomic.Int64
|
||||
}
|
||||
|
||||
// newInstruments defines stable names and units once for every provider instance.
|
||||
func newInstruments(meter metric.Meter) instruments {
|
||||
requests, _ := meter.Int64Counter("messenger_http_requests")
|
||||
duration, _ := meter.Float64Histogram("messenger_http_duration_seconds", metric.WithUnit("s"))
|
||||
jobs, _ := meter.Int64Counter("messenger_jobs")
|
||||
jobDuration, _ := meter.Float64Histogram("messenger_job_duration_seconds", metric.WithUnit("s"))
|
||||
ready, _ := meter.Float64Histogram("messenger_ready_duration_seconds", metric.WithUnit("s"))
|
||||
return instruments{httpRequests: requests, httpDuration: duration, jobs: jobs, jobDuration: jobDuration, ready: ready}
|
||||
}
|
||||
|
||||
// recordHTTP avoids raw URLs and identifiers in metric attributes.
|
||||
func (r *Runtime) recordHTTP(ctx context.Context, method, route, class string, seconds float64) {
|
||||
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route), attribute.String("status_class", class))
|
||||
r.instruments.httpRequests.Add(ctx, 1, attrs)
|
||||
r.instruments.httpDuration.Record(ctx, seconds, attrs)
|
||||
}
|
||||
|
||||
// JobStarted records occupancy independently from queue length.
|
||||
func (r *Runtime) JobStarted() {
|
||||
r.instruments.busy.Add(1)
|
||||
}
|
||||
|
||||
// JobFinished records a real attempt's result and releases its occupancy gauge.
|
||||
func (r *Runtime) JobFinished(ctx context.Context, elapsed time.Duration, err error) {
|
||||
r.instruments.busy.Add(-1)
|
||||
outcome := "ok"
|
||||
if err != nil {
|
||||
outcome = "error"
|
||||
}
|
||||
attrs := metric.WithAttributes(attribute.String("job_type", "attachment.process.v1"), attribute.String("outcome", outcome))
|
||||
r.instruments.jobs.Add(ctx, 1, attrs)
|
||||
r.instruments.jobDuration.Record(ctx, elapsed.Seconds(), attrs)
|
||||
}
|
||||
|
||||
// Ready records end-to-end latency only after a confirmed durable publication.
|
||||
func (r *Runtime) Ready(ctx context.Context, accepted time.Time) {
|
||||
r.instruments.ready.Record(ctx, time.Since(accepted).Seconds())
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type queryEndKey struct{}
|
||||
|
||||
type acquireEndKey struct{}
|
||||
|
||||
// TraceQueryStart creates a SQL client span without recording SQL text or arguments.
|
||||
func (r *Runtime) TraceQueryStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceQueryStartData) context.Context {
|
||||
ctx, end := r.Start(ctx, "postgres.query", "client")
|
||||
return context.WithValue(ctx, queryEndKey{}, end)
|
||||
}
|
||||
|
||||
// TraceQueryEnd closes the actual driver operation and records only success or failure.
|
||||
func (r *Runtime) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
if end, ok := ctx.Value(queryEndKey{}).(func(error)); ok {
|
||||
end(data.Err)
|
||||
}
|
||||
}
|
||||
|
||||
// TraceAcquireStart counts acquisition attempts still waiting for a pool result.
|
||||
func (r *Runtime) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
r.instruments.waiting.Add(1)
|
||||
ctx, end := r.Start(ctx, "postgres.acquire", "client")
|
||||
return context.WithValue(ctx, acquireEndKey{}, end)
|
||||
}
|
||||
|
||||
// TraceAcquireEnd releases the acquisition gauge on either success or failure.
|
||||
func (r *Runtime) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
||||
r.instruments.waiting.Add(-1)
|
||||
if end, ok := ctx.Value(acquireEndKey{}).(func(error)); ok {
|
||||
end(data.Err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// Package telemetry owns bounded OpenTelemetry providers and safe instrumentation.
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"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"
|
||||
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"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
)
|
||||
|
||||
// Runtime owns providers; Shutdown is called once by the application lifecycle.
|
||||
type Runtime struct {
|
||||
traces *sdktrace.TracerProvider
|
||||
metrics *sdkmetric.MeterProvider
|
||||
logs *sdklog.LoggerProvider
|
||||
tracer trace.Tracer
|
||||
logger otellog.Logger
|
||||
meter metric.Meter
|
||||
instruments instruments
|
||||
enabled bool
|
||||
}
|
||||
|
||||
// New builds nonblocking bounded exporters; backend availability is never a startup dependency.
|
||||
func New(ctx context.Context, cfg *config.Telemetry) (*Runtime, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("telemetry configuration is required")
|
||||
}
|
||||
if math.IsNaN(cfg.SampleRatio) || cfg.SampleRatio < 0 || cfg.SampleRatio > 1 {
|
||||
return nil, fmt.Errorf("telemetry sampling ratio must be in [0,1]")
|
||||
}
|
||||
if cfg.Endpoint != "" {
|
||||
endpoint, err := url.Parse(cfg.Endpoint)
|
||||
if err != nil || endpoint.Host == "" || (endpoint.Scheme != "http" && endpoint.Scheme != "https") || endpoint.User != nil {
|
||||
return nil, fmt.Errorf("invalid telemetry endpoint")
|
||||
}
|
||||
}
|
||||
res := resource.NewSchemaless(attribute.String("service.name", cfg.Service), attribute.String("service.version", cfg.Version), attribute.String("service.instance.id", cfg.Instance), attribute.String("deployment.environment.name", "lab"))
|
||||
traceOptions := []sdktrace.TracerProviderOption{sdktrace.WithResource(res), sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.TraceIDRatioBased(cfg.SampleRatio)))}
|
||||
metricOptions := []sdkmetric.Option{sdkmetric.WithResource(res), 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}}}))}
|
||||
logOptions := []sdklog.LoggerProviderOption{sdklog.WithResource(res)}
|
||||
if cfg.Endpoint != "" {
|
||||
traces, err := otlptracehttp.New(ctx, otlptracehttp.WithEndpointURL(strings.TrimRight(cfg.Endpoint, "/")+"/v1/traces"), otlptracehttp.WithTimeout(time.Second), otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metrics, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithEndpointURL(strings.TrimRight(cfg.Endpoint, "/")+"/v1/metrics"), otlpmetrichttp.WithTimeout(time.Second), otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, traces.Shutdown(ctx))
|
||||
}
|
||||
logs, err := otlploghttp.New(ctx, otlploghttp.WithEndpointURL(strings.TrimRight(cfg.Endpoint, "/")+"/v1/logs"), otlploghttp.WithTimeout(time.Second), otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, errors.Join(err, traces.Shutdown(ctx), metrics.Shutdown(ctx))
|
||||
}
|
||||
traceOptions = append(traceOptions, sdktrace.WithBatcher(traces, sdktrace.WithMaxQueueSize(256), sdktrace.WithMaxExportBatchSize(64), sdktrace.WithBatchTimeout(time.Second), sdktrace.WithExportTimeout(time.Second)))
|
||||
metricOptions = append(metricOptions, sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metrics, sdkmetric.WithInterval(5*time.Second), sdkmetric.WithTimeout(time.Second))))
|
||||
logOptions = append(logOptions, sdklog.WithProcessor(sdklog.NewBatchProcessor(logs, sdklog.WithMaxQueueSize(256), sdklog.WithExportMaxBatchSize(64), sdklog.WithExportInterval(time.Second), sdklog.WithExportTimeout(time.Second), sdklog.WithExportBufferSize(1))))
|
||||
}
|
||||
r := &Runtime{traces: sdktrace.NewTracerProvider(traceOptions...), metrics: sdkmetric.NewMeterProvider(metricOptions...), logs: sdklog.NewLoggerProvider(logOptions...), enabled: cfg.Endpoint != ""}
|
||||
r.tracer = r.traces.Tracer("messenger")
|
||||
r.meter = r.metrics.Meter("messenger")
|
||||
r.logger = r.logs.Logger("messenger")
|
||||
r.instruments = newInstruments(r.meter)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// Shutdown flushes all providers under the lifecycle's bounded deadline.
|
||||
func (r *Runtime) Shutdown(ctx context.Context) error {
|
||||
return errors.Join(r.traces.Shutdown(ctx), r.metrics.Shutdown(ctx), r.logs.Shutdown(ctx))
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
collectorlogs "go.opentelemetry.io/proto/otlp/collector/logs/v1"
|
||||
collectormetrics "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
|
||||
collectortrace "go.opentelemetry.io/proto/otlp/collector/trace/v1"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/config"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/observation"
|
||||
)
|
||||
|
||||
type capture struct {
|
||||
mu sync.Mutex
|
||||
traces []*collectortrace.ExportTraceServiceRequest
|
||||
logs []*collectorlogs.ExportLogsServiceRequest
|
||||
metrics []*collectormetrics.ExportMetricsServiceRequest
|
||||
}
|
||||
|
||||
// serve captures actual OTLP requests without relying on SDK implementation internals.
|
||||
func (c *capture) serve(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "read failed", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
switch r.URL.Path {
|
||||
case "/v1/traces":
|
||||
message := &collectortrace.ExportTraceServiceRequest{}
|
||||
if err := proto.Unmarshal(data, message); err != nil {
|
||||
http.Error(w, "invalid OTLP", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
c.traces = append(c.traces, message)
|
||||
case "/v1/logs":
|
||||
message := &collectorlogs.ExportLogsServiceRequest{}
|
||||
if err := proto.Unmarshal(data, message); err != nil {
|
||||
http.Error(w, "invalid OTLP", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
c.logs = append(c.logs, message)
|
||||
case "/v1/metrics":
|
||||
message := &collectormetrics.ExportMetricsServiceRequest{}
|
||||
if err := proto.Unmarshal(data, message); err != nil {
|
||||
http.Error(w, "invalid OTLP", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
c.metrics = append(c.metrics, message)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/x-protobuf")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
type snapshotFixture struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// Snapshot supplies safe bounded saturation data for the exporter integration test.
|
||||
func (s snapshotFixture) Snapshot(context.Context) (observation.Snapshot, error) {
|
||||
return observation.Snapshot{QueueDepth: 2, OldestSeconds: 12, PoolUsed: 1}, s.err
|
||||
}
|
||||
|
||||
// TestOTLPSignalsShareContext verifies real HTTP export, parentage, metrics and structured-log correlation.
|
||||
func TestOTLPSignalsShareContext(t *testing.T) {
|
||||
capture := &capture{}
|
||||
server := httptest.NewServer(http.HandlerFunc(capture.serve))
|
||||
defer server.Close()
|
||||
r, err := New(t.Context(), &config.Telemetry{Endpoint: server.URL, Service: "messenger-worker", Version: "test", Instance: "synthetic", SampleRatio: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.ObserveSaturation(snapshotFixture{}, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, finish := r.Start(t.Context(), "http.request", "server")
|
||||
r.HTTP(ctx, "POST", "/api/v1/chats/:chat_id/attachments", 202, time.Millisecond, "synthetic-request")
|
||||
parent, state := r.Inject(ctx)
|
||||
producer, endProducer := r.Start(r.Extract(t.Context(), parent, state), "attachment.publish", "producer")
|
||||
parent, state = r.Inject(producer)
|
||||
consumer, endConsumer := r.Start(r.Extract(t.Context(), parent, state), "attachment.process", "consumer")
|
||||
r.JobStarted()
|
||||
r.JobFinished(consumer, time.Millisecond, nil)
|
||||
r.Ready(consumer, time.Now().Add(-time.Second))
|
||||
query := r.TraceQueryStart(consumer, nil, pgx.TraceQueryStartData{SQL: "secret SQL that must not be exported"})
|
||||
r.TraceQueryEnd(query, nil, pgx.TraceQueryEndData{Err: errors.New("secret database password")})
|
||||
acquire := r.TraceAcquireStart(consumer, nil, pgxpool.TraceAcquireStartData{})
|
||||
r.TraceAcquireEnd(acquire, nil, pgxpool.TraceAcquireEndData{})
|
||||
endConsumer(nil)
|
||||
endProducer(nil)
|
||||
finish(nil)
|
||||
if err := r.Shutdown(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
capture.mu.Lock()
|
||||
defer capture.mu.Unlock()
|
||||
if len(capture.traces) == 0 || len(capture.logs) == 0 || len(capture.metrics) == 0 {
|
||||
t.Fatal("one OTLP signal is absent")
|
||||
}
|
||||
spans := 0
|
||||
correlatedLogs := 0
|
||||
for _, request := range capture.traces {
|
||||
if strings.Contains(request.String(), "secret") {
|
||||
t.Fatal("trace leaked dependency payload")
|
||||
}
|
||||
for _, resource := range request.ResourceSpans {
|
||||
for _, scope := range resource.ScopeSpans {
|
||||
spans += len(scope.Spans)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, request := range capture.logs {
|
||||
if strings.Contains(request.String(), "secret") {
|
||||
t.Fatal("log leaked dependency payload")
|
||||
}
|
||||
for _, resource := range request.ResourceLogs {
|
||||
for _, scope := range resource.ScopeLogs {
|
||||
for _, record := range scope.LogRecords {
|
||||
if len(record.TraceId) == 16 && len(record.SpanId) == 8 {
|
||||
correlatedLogs++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if spans < 4 || correlatedLogs < 4 {
|
||||
t.Fatal("causal operations or correlated logs missing")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTTPBoundedDimensions covers status classes and rejects arbitrary method labels.
|
||||
func TestHTTPBoundedDimensions(t *testing.T) {
|
||||
r, err := New(t.Context(), &config.Telemetry{Service: "api", SampleRatio: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, finish := r.Start(t.Context(), "request", "internal")
|
||||
for _, status := range []int{200, 302, 401, 503} {
|
||||
r.HTTP(ctx, "custom-method", "bad-route", status, time.Millisecond, "")
|
||||
}
|
||||
r.JobStarted()
|
||||
r.JobFinished(ctx, time.Millisecond, errors.New("safe error"))
|
||||
r.TraceQueryEnd(ctx, nil, pgx.TraceQueryEndData{})
|
||||
finish(errors.New("safe error"))
|
||||
if err := r.ObserveSaturation(snapshotFixture{err: errors.New("unavailable")}, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := r.Shutdown(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnavailableBackendDoesNotBlockBusinessWork bounds exporter failures independently of requests.
|
||||
func TestUnavailableBackendDoesNotBlockBusinessWork(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusServiceUnavailable) }))
|
||||
defer server.Close()
|
||||
r, err := New(t.Context(), &config.Telemetry{Endpoint: server.URL, Service: "api", SampleRatio: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
start := time.Now()
|
||||
for i := 0; i < 2000; i++ {
|
||||
ctx, end := r.Start(t.Context(), "safe-operation", "client")
|
||||
r.HTTP(ctx, "GET", "/api/v1/chats", 200, time.Millisecond, "synthetic")
|
||||
end(nil)
|
||||
}
|
||||
if time.Since(start) > 2*time.Second {
|
||||
t.Fatal("business path blocked on unavailable exporter")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := r.Shutdown(ctx); err == nil {
|
||||
t.Fatal("backend outage was not visible at exporter shutdown")
|
||||
}
|
||||
}
|
||||
|
||||
// TestExporterInvalidPort rejects an unusable exporter URL without starting the application.
|
||||
func TestExporterInvalidPort(t *testing.T) {
|
||||
runtime, err := New(t.Context(), &config.Telemetry{Endpoint: "http://localhost:invalid", SampleRatio: 1})
|
||||
if err == nil {
|
||||
_ = runtime.Shutdown(t.Context())
|
||||
t.Fatal("invalid exporter port accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMissingRuntimeConfiguration returns an error instead of dereferencing a missing section.
|
||||
func TestMissingRuntimeConfiguration(t *testing.T) {
|
||||
if _, err := New(t.Context(), nil); err == nil {
|
||||
t.Fatal("missing configuration accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestInvalidRuntimeSampling prevents an SDK sampler panic for out-of-range ratios.
|
||||
func TestInvalidRuntimeSampling(t *testing.T) {
|
||||
if _, err := New(t.Context(), &config.Telemetry{SampleRatio: -1}); err == nil {
|
||||
t.Fatal("invalid sampling accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"syscall"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/observation"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
// Snapshotter supplies metrics independently of the application's request path.
|
||||
type Snapshotter interface {
|
||||
// Snapshot returns queue and pool state within its own timeout.
|
||||
Snapshot(context.Context) (observation.Snapshot, error)
|
||||
}
|
||||
|
||||
// ObserveSaturation registers bounded periodic observations; database failure skips only DB gauges.
|
||||
func (r *Runtime) ObserveSaturation(source Snapshotter, worker bool) error {
|
||||
depth, _ := r.meter.Int64ObservableGauge("messenger_queue_depth")
|
||||
age, _ := r.meter.Float64ObservableGauge("messenger_queue_oldest_seconds")
|
||||
used, _ := r.meter.Int64ObservableGauge("messenger_db_pool_used")
|
||||
waiting, _ := r.meter.Int64ObservableGauge("messenger_db_pool_waiting")
|
||||
busy, _ := r.meter.Int64ObservableGauge("messenger_worker_busy")
|
||||
capacity, _ := r.meter.Int64ObservableGauge("messenger_worker_capacity")
|
||||
cpu, _ := r.meter.Float64ObservableCounter("messenger_process_cpu_seconds")
|
||||
memory, _ := r.meter.Int64ObservableGauge("messenger_process_peak_rss_bytes")
|
||||
_, err := r.meter.RegisterCallback(func(ctx context.Context, observer metric.Observer) error {
|
||||
observer.ObserveInt64(waiting, r.instruments.waiting.Load())
|
||||
if worker {
|
||||
observer.ObserveInt64(busy, r.instruments.busy.Load())
|
||||
observer.ObserveInt64(capacity, 1)
|
||||
}
|
||||
snapshot, err := source.Snapshot(ctx)
|
||||
if err == nil {
|
||||
observer.ObserveInt64(depth, snapshot.QueueDepth)
|
||||
observer.ObserveFloat64(age, snapshot.OldestSeconds)
|
||||
observer.ObserveInt64(used, snapshot.PoolUsed)
|
||||
}
|
||||
var usage syscall.Rusage
|
||||
if syscall.Getrusage(syscall.RUSAGE_SELF, &usage) == nil {
|
||||
seconds := float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1e6
|
||||
rss := usage.Maxrss
|
||||
if runtime.GOOS != "darwin" {
|
||||
rss *= 1024
|
||||
}
|
||||
observer.ObserveFloat64(cpu, seconds)
|
||||
observer.ObserveInt64(memory, rss)
|
||||
}
|
||||
return nil
|
||||
}, depth, age, used, waiting, busy, capacity, cpu, memory)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package telemetry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
otellog "go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Start records a real operation without copying error text, credentials or business data.
|
||||
func (r *Runtime) Start(ctx context.Context, name, kind string) (context.Context, func(error)) {
|
||||
spanKind := trace.SpanKindInternal
|
||||
switch kind {
|
||||
case "server":
|
||||
spanKind = trace.SpanKindServer
|
||||
case "producer":
|
||||
spanKind = trace.SpanKindProducer
|
||||
case "consumer":
|
||||
spanKind = trace.SpanKindConsumer
|
||||
case "client":
|
||||
spanKind = trace.SpanKindClient
|
||||
}
|
||||
ctx, span := r.tracer.Start(ctx, name, trace.WithSpanKind(spanKind))
|
||||
return ctx, func(err error) {
|
||||
outcome := "ok"
|
||||
if err != nil {
|
||||
outcome = "error"
|
||||
span.SetStatus(codes.Error, "operation failed")
|
||||
}
|
||||
r.event(ctx, name, outcome, "")
|
||||
span.End()
|
||||
}
|
||||
}
|
||||
|
||||
// Extract restores only W3C trace headers, never arbitrary baggage.
|
||||
func (r *Runtime) Extract(ctx context.Context, parent, state string) context.Context {
|
||||
return propagation.TraceContext{}.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state})
|
||||
}
|
||||
|
||||
// Inject returns the bounded W3C carrier for a durable asynchronous handoff.
|
||||
func (r *Runtime) Inject(ctx context.Context) (string, string) {
|
||||
carrier := propagation.MapCarrier{}
|
||||
propagation.TraceContext{}.Inject(ctx, carrier)
|
||||
return carrier["traceparent"], carrier["tracestate"]
|
||||
}
|
||||
|
||||
// HTTP records one completed request with bounded attributes and a correlated log event.
|
||||
func (r *Runtime) HTTP(ctx context.Context, method, route string, status int, elapsed time.Duration, requestID string) {
|
||||
if len(route) > 128 || !strings.HasPrefix(route, "/") {
|
||||
route = "unmatched"
|
||||
}
|
||||
switch method {
|
||||
case "GET", "POST", "DELETE", "HEAD", "OPTIONS":
|
||||
default:
|
||||
method = "other"
|
||||
}
|
||||
class := "5xx"
|
||||
switch status / 100 {
|
||||
case 2:
|
||||
class = "2xx"
|
||||
case 3:
|
||||
class = "3xx"
|
||||
case 4:
|
||||
class = "4xx"
|
||||
}
|
||||
span := trace.SpanFromContext(ctx)
|
||||
span.SetName(method + " " + route)
|
||||
span.SetAttributes(attribute.String("http.route", route), attribute.String("http.request.method", method), attribute.Int("http.response.status_code", status))
|
||||
if status >= 500 {
|
||||
span.SetStatus(codes.Error, "server error")
|
||||
}
|
||||
r.recordHTTP(ctx, method, route, class, elapsed.Seconds())
|
||||
r.event(ctx, "http.request", class, requestID)
|
||||
}
|
||||
|
||||
// event emits only an allowlisted technical record; SDK attaches trace/span IDs from context.
|
||||
func (r *Runtime) event(ctx context.Context, event, outcome, requestID string) {
|
||||
var record otellog.Record
|
||||
record.SetTimestamp(time.Now())
|
||||
record.SetSeverity(otellog.SeverityInfo)
|
||||
record.SetBody(otellog.StringValue(event))
|
||||
record.AddAttributes(otellog.String("event", event), otellog.String("outcome", outcome))
|
||||
if requestID != "" {
|
||||
record.AddAttributes(otellog.String("request_id", requestID))
|
||||
}
|
||||
r.logger.Emit(ctx, record)
|
||||
}
|
||||
Reference in New Issue
Block a user