forked from mtusi2026/mtusi2026lab6
feat(storage): lab6 add PostgreSQL, Redis and S3 tracing and DB pool metrics
This commit is contained in:
@@ -47,6 +47,12 @@ func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
}
|
||||
poolCfg.HealthCheckPeriod = 10 * time.Second
|
||||
|
||||
tracer, err := newPoolTracer()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("метрики пула: %w", err)
|
||||
}
|
||||
poolCfg.ConnConfig.Tracer = tracer
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("создание пула: %w", err)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
type poolTracer struct {
|
||||
tracer trace.Tracer
|
||||
duration metric.Float64Histogram
|
||||
waiting metric.Int64UpDownCounter
|
||||
}
|
||||
|
||||
func newPoolTracer() (*poolTracer, error) {
|
||||
meter := telemetry.Meter("storage.postgres")
|
||||
duration, err := meter.Float64Histogram("db_pool_acquire_duration_seconds",
|
||||
metric.WithUnit("s"),
|
||||
metric.WithExplicitBucketBoundaries(0.0001, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
waiting, err := meter.Int64UpDownCounter("db_pool_waiting",
|
||||
metric.WithDescription("Число незавершённых вызовов Acquire"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &poolTracer{tracer: telemetry.Tracer("storage.postgres"), duration: duration, waiting: waiting}, nil
|
||||
}
|
||||
|
||||
type acquireStartKey struct{}
|
||||
|
||||
func (t *poolTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
||||
ctx, _ = t.tracer.Start(ctx, "postgresql.acquire")
|
||||
t.waiting.Add(ctx, 1)
|
||||
return context.WithValue(ctx, acquireStartKey{}, time.Now())
|
||||
}
|
||||
|
||||
func (t *poolTracer) TraceAcquireEnd(ctx context.Context, _ *pgxpool.Pool, data pgxpool.TraceAcquireEndData) {
|
||||
t.waiting.Add(ctx, -1)
|
||||
t.duration.Record(ctx, time.Since(ctx.Value(acquireStartKey{}).(time.Time)).Seconds())
|
||||
endSpan(ctx, data.Err)
|
||||
}
|
||||
|
||||
func (t *poolTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
|
||||
// Передаём только известный SQL-глагол, без текста запроса и параметров.
|
||||
op := "QUERY"
|
||||
sql := strings.TrimSpace(data.SQL)
|
||||
if i := strings.IndexAny(sql, " \r\n\t;("); i >= 0 {
|
||||
sql = sql[:i]
|
||||
}
|
||||
switch verb := strings.ToUpper(sql); verb {
|
||||
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK", "WITH":
|
||||
op = verb
|
||||
}
|
||||
ctx, _ = t.tracer.Start(ctx, "postgresql."+op, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op)))
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (t *poolTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
|
||||
endSpan(ctx, data.Err)
|
||||
}
|
||||
|
||||
func endSpan(ctx context.Context, err error) {
|
||||
span := trace.SpanFromContext(ctx)
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "операция PostgreSQL не выполнена")
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
|
||||
func ObservePool(pool *pgxpool.Pool) (metric.Registration, error) {
|
||||
meter := telemetry.Meter("storage.postgres")
|
||||
connections, err := meter.Int64ObservableGauge("db_pool_connections")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return meter.RegisterCallback(func(_ context.Context, observer metric.Observer) error {
|
||||
stat := pool.Stat()
|
||||
observe := func(state string, count int32) {
|
||||
observer.ObserveInt64(connections, int64(count), metric.WithAttributes(attribute.String("state", state)))
|
||||
}
|
||||
observe("used", stat.AcquiredConns())
|
||||
observe("idle", stat.IdleConns())
|
||||
observe("max", stat.MaxConns())
|
||||
return nil
|
||||
}, connections)
|
||||
}
|
||||
Reference in New Issue
Block a user