forked from mtusi2026/mtusi2026lab6
Реализовать наблюдаемость мессенджера для ЛР 6 на четыре
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
)
|
||||
|
||||
func WatchPool(pool *pgxpool.Pool, waiting *atomic.Int64) {
|
||||
connections := instrument(meter.Int64ObservableGauge("messenger_db_pool_connections"))
|
||||
acquiring := instrument(meter.Int64ObservableGauge("messenger_db_pool_waiting"))
|
||||
waitTime := instrument(meter.Float64ObservableCounter("messenger_db_pool_wait", metric.WithUnit("s")))
|
||||
_, _ = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
stats := pool.Stat()
|
||||
o.ObserveInt64(connections, int64(stats.AcquiredConns()), metric.WithAttributes(attribute.String("state", "used")))
|
||||
o.ObserveInt64(connections, int64(stats.MaxConns()), metric.WithAttributes(attribute.String("state", "capacity")))
|
||||
o.ObserveInt64(acquiring, waiting.Load())
|
||||
o.ObserveFloat64(waitTime, stats.EmptyAcquireWaitTime().Seconds())
|
||||
return nil
|
||||
}, connections, acquiring, waitTime)
|
||||
}
|
||||
|
||||
type QueueSample struct {
|
||||
Depth int64
|
||||
OldestSeconds float64
|
||||
At time.Time
|
||||
}
|
||||
|
||||
func WatchQueue(queue string) func(QueueSample) {
|
||||
depth := instrument(meter.Int64ObservableGauge("messenger_queue_depth"))
|
||||
age := instrument(meter.Float64ObservableGauge("messenger_queue_oldest_age", metric.WithUnit("s")))
|
||||
freshness := instrument(meter.Float64ObservableGauge("messenger_queue_sample_age", metric.WithUnit("s")))
|
||||
var current atomic.Pointer[QueueSample]
|
||||
attrs := metric.WithAttributes(attribute.String("queue", queue))
|
||||
_, _ = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
if sample := current.Load(); sample != nil {
|
||||
o.ObserveInt64(depth, sample.Depth, attrs)
|
||||
o.ObserveFloat64(age, sample.OldestSeconds, attrs)
|
||||
o.ObserveFloat64(freshness, time.Since(sample.At).Seconds(), attrs)
|
||||
}
|
||||
return nil
|
||||
}, depth, age, freshness)
|
||||
return func(sample QueueSample) { current.Store(&sample) }
|
||||
}
|
||||
|
||||
var workerBusy atomic.Int64
|
||||
|
||||
func WatchWorker(lanes int) {
|
||||
busy := instrument(meter.Int64ObservableGauge("messenger_worker_busy"))
|
||||
capacity := instrument(meter.Int64ObservableGauge("messenger_worker_capacity"))
|
||||
_, _ = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error {
|
||||
o.ObserveInt64(busy, workerBusy.Load())
|
||||
o.ObserveInt64(capacity, int64(lanes))
|
||||
return nil
|
||||
}, busy, capacity)
|
||||
}
|
||||
|
||||
func WorkerAttempt() func() {
|
||||
workerBusy.Add(1)
|
||||
return func() { workerBusy.Add(-1) }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
)
|
||||
|
||||
func Carrier(ctx context.Context) propagation.MapCarrier {
|
||||
carrier := propagation.MapCarrier{}
|
||||
(propagation.TraceContext{}).Inject(ctx, carrier)
|
||||
return carrier
|
||||
}
|
||||
|
||||
func JobContext(ctx context.Context, traceparent, tracestate string) context.Context {
|
||||
return (propagation.TraceContext{}).Extract(ctx, propagation.MapCarrier{
|
||||
"traceparent": traceparent, "tracestate": tracestate,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"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"
|
||||
"go.opentelemetry.io/otel/log/global"
|
||||
"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"
|
||||
)
|
||||
|
||||
const scope = "highload/messenger"
|
||||
const exportTimeout = 1500 * time.Millisecond
|
||||
|
||||
var W3C = propagation.TraceContext{}
|
||||
|
||||
// Start initializes all three signals. Export failures are asynchronous and
|
||||
// telemetry configuration is independent of business readiness.
|
||||
func Start(ctx context.Context, fallbackName string) func() {
|
||||
if os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == "" {
|
||||
return func() {}
|
||||
}
|
||||
// Exporter errors can contain endpoints. Suppress the raw error and limit
|
||||
// stderr noise to one message per second for a broken telemetry sink.
|
||||
otel.SetErrorHandler(otel.ErrorHandlerFunc(func(error) {
|
||||
reportExportError()
|
||||
}))
|
||||
shutdown, err := start(ctx, fallbackName)
|
||||
if err != nil {
|
||||
slog.Warn("OpenTelemetry initialization failed")
|
||||
return func() {}
|
||||
}
|
||||
return func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
|
||||
defer cancel()
|
||||
if err := shutdown(ctx); err != nil {
|
||||
slog.Warn("OpenTelemetry shutdown could not flush every signal")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func start(ctx context.Context, fallbackName string) (func(context.Context) error, error) {
|
||||
serviceName := os.Getenv("OTEL_SERVICE_NAME")
|
||||
if serviceName == "" {
|
||||
serviceName = fallbackName
|
||||
}
|
||||
version := os.Getenv("OTEL_SERVICE_VERSION")
|
||||
if version == "" {
|
||||
version = "lab6"
|
||||
}
|
||||
instance, err := os.Hostname()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res := resource.NewSchemaless(
|
||||
attribute.String("service.name", serviceName),
|
||||
attribute.String("service.version", version),
|
||||
attribute.String("service.instance.id", instance),
|
||||
attribute.String("deployment.environment.name", "lab"),
|
||||
)
|
||||
traces, err := otlptracehttp.New(ctx, otlptracehttp.WithTimeout(exportTimeout),
|
||||
otlptracehttp.WithRetry(otlptracehttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metrics, err := otlpmetrichttp.New(ctx, otlpmetrichttp.WithTimeout(exportTimeout),
|
||||
otlpmetrichttp.WithRetry(otlpmetrichttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
_ = traces.Shutdown(ctx)
|
||||
return nil, err
|
||||
}
|
||||
logs, err := otlploghttp.New(ctx, otlploghttp.WithTimeout(exportTimeout),
|
||||
otlploghttp.WithRetry(otlploghttp.RetryConfig{Enabled: false}))
|
||||
if err != nil {
|
||||
_ = metrics.Shutdown(ctx)
|
||||
_ = traces.Shutdown(ctx)
|
||||
return nil, err
|
||||
}
|
||||
tp := sdktrace.NewTracerProvider(sdktrace.WithResource(res),
|
||||
sdktrace.WithSampler(sdktrace.ParentBased(sdktrace.AlwaysSample())),
|
||||
sdktrace.WithBatcher(traces, sdktrace.WithMaxQueueSize(512), sdktrace.WithMaxExportBatchSize(128),
|
||||
sdktrace.WithBatchTimeout(500*time.Millisecond), sdktrace.WithExportTimeout(exportTimeout)))
|
||||
mp := sdkmetric.NewMeterProvider(sdkmetric.WithResource(res),
|
||||
sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metrics,
|
||||
sdkmetric.WithInterval(2*time.Second), sdkmetric.WithTimeout(exportTimeout))))
|
||||
lp := sdklog.NewLoggerProvider(sdklog.WithResource(res),
|
||||
sdklog.WithProcessor(sdklog.NewBatchProcessor(logs, sdklog.WithMaxQueueSize(512),
|
||||
sdklog.WithExportMaxBatchSize(128), sdklog.WithExportInterval(500*time.Millisecond),
|
||||
sdklog.WithExportTimeout(exportTimeout))))
|
||||
otel.SetTracerProvider(tp)
|
||||
otel.SetMeterProvider(mp)
|
||||
global.SetLoggerProvider(lp)
|
||||
otel.SetTextMapPropagator(W3C)
|
||||
observeProcess(mp.Meter(scope))
|
||||
return func(ctx context.Context) error {
|
||||
return errors.Join(tp.Shutdown(ctx), mp.Shutdown(ctx), lp.Shutdown(ctx))
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package observability
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/log"
|
||||
"go.opentelemetry.io/otel/log/global"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
var Tracer = otel.Tracer(scope)
|
||||
var meter = otel.Meter(scope)
|
||||
|
||||
var (
|
||||
httpRequests = instrument(meter.Int64Counter("messenger_http_requests"))
|
||||
httpLatency = instrument(meter.Float64Histogram("messenger_http_request_duration", metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.001, .003, .005, .01, .025, .05, .1, .25, .5, 1, 2, 5, 10)))
|
||||
jobs = instrument(meter.Int64Counter("messenger_jobs"))
|
||||
jobLatency = instrument(meter.Float64Histogram("messenger_job_duration", metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.01, .025, .05, .1, .25, .5, 1, 2, 5, 10, 20, 40, 60, 120)))
|
||||
readyLatency = instrument(meter.Float64Histogram("messenger_attachment_time_to_ready", metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(.05, .1, .25, .5, 1, 2, 5, 10, 20, 40, 60, 120, 300)))
|
||||
lastExportError atomic.Int64
|
||||
)
|
||||
|
||||
func instrument[T any](value T, err error) T {
|
||||
if err != nil {
|
||||
panic(err) // All instrument names and descriptors are code constants.
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func reportExportError() {
|
||||
now := time.Now().Unix()
|
||||
last := lastExportError.Load()
|
||||
if last != now && lastExportError.CompareAndSwap(last, now) {
|
||||
slog.Warn("OpenTelemetry export failed")
|
||||
}
|
||||
}
|
||||
|
||||
func ObserveHTTP(ctx context.Context, method, route string, code int, duration time.Duration) {
|
||||
attrs := metric.WithAttributes(attribute.String("method", method), attribute.String("route", route),
|
||||
attribute.String("status_class", strconv.Itoa(code/100)+"xx"))
|
||||
httpRequests.Add(ctx, 1, attrs)
|
||||
httpLatency.Record(ctx, duration.Seconds(), attrs)
|
||||
}
|
||||
|
||||
func ObserveJob(ctx context.Context, outcome string, duration time.Duration) {
|
||||
attrs := metric.WithAttributes(attribute.String("job_type", "attachment.process"), attribute.String("outcome", outcome))
|
||||
jobs.Add(ctx, 1, attrs)
|
||||
jobLatency.Record(ctx, duration.Seconds(), attrs)
|
||||
}
|
||||
|
||||
func ObserveReady(ctx context.Context, acceptedAt time.Time) {
|
||||
readyLatency.Record(ctx, max(time.Since(acceptedAt).Seconds(), 0),
|
||||
metric.WithAttributes(attribute.String("job_type", "attachment.process")))
|
||||
}
|
||||
|
||||
// Log exports only deliberate operational fields, never arbitrary slog values.
|
||||
// The JSON body allows LogQL queries and Grafana's trace link to use the same IDs.
|
||||
func Log(ctx context.Context, event string, level log.Severity, fields ...attribute.KeyValue) {
|
||||
values := make(map[string]any, len(fields)+3)
|
||||
values["event"] = event
|
||||
for _, field := range fields {
|
||||
values[string(field.Key)] = field.Value.AsInterface()
|
||||
}
|
||||
if span := trace.SpanContextFromContext(ctx); span.IsValid() {
|
||||
values["trace_id"], values["span_id"] = span.TraceID().String(), span.SpanID().String()
|
||||
}
|
||||
if requestID := RequestID(ctx); requestID != "" {
|
||||
values["request_id"] = requestID
|
||||
}
|
||||
body, err := json.Marshal(values)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var record log.Record
|
||||
record.SetTimestamp(time.Now())
|
||||
record.SetSeverity(level)
|
||||
record.SetSeverityText(level.String())
|
||||
record.SetBody(log.StringValue(string(body)))
|
||||
global.GetLoggerProvider().Logger(scope).Emit(ctx, record)
|
||||
}
|
||||
|
||||
type requestIDKey struct{}
|
||||
|
||||
func WithRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey{}, id)
|
||||
}
|
||||
|
||||
func RequestID(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey{}).(string)
|
||||
return id
|
||||
}
|
||||
|
||||
func End(span trace.Span, err error) {
|
||||
if err != nil {
|
||||
kind := "operation_failed"
|
||||
switch {
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
kind = "deadline_exceeded"
|
||||
case errors.Is(err, context.Canceled):
|
||||
kind = "canceled"
|
||||
}
|
||||
span.SetAttributes(attribute.String("error.type", kind))
|
||||
span.SetStatus(codes.Error, kind)
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func observeProcess(m metric.Meter) {
|
||||
cpu := instrument(m.Float64ObservableCounter("messenger_process_cpu_time", metric.WithUnit("s")))
|
||||
rss := instrument(m.Int64ObservableGauge("messenger_process_memory", metric.WithUnit("By")))
|
||||
_, _ = m.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
|
||||
var usage syscall.Rusage
|
||||
if err := syscall.Getrusage(syscall.RUSAGE_SELF, &usage); err == nil {
|
||||
seconds := float64(usage.Utime.Sec+usage.Stime.Sec) + float64(usage.Utime.Usec+usage.Stime.Usec)/1e6
|
||||
observer.ObserveFloat64(cpu, seconds)
|
||||
}
|
||||
// The production binaries run on Linux. statm reports resident pages.
|
||||
if raw, err := os.ReadFile("/proc/self/statm"); err == nil {
|
||||
if fields := strings.Fields(string(raw)); len(fields) > 1 {
|
||||
if pages, err := strconv.ParseInt(fields[1], 10, 64); err == nil {
|
||||
observer.ObserveInt64(rss, pages*int64(os.Getpagesize()))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}, cpu, rss)
|
||||
}
|
||||
Reference in New Issue
Block a user