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)
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"high-loud-apps-labs/internal/telemetry"
|
||||
)
|
||||
|
||||
func NewClient(url string) (*redis.Client, error) {
|
||||
@@ -22,6 +24,7 @@ func NewClient(url string) (*redis.Client, error) {
|
||||
opt.ConnMaxIdleTime = time.Minute
|
||||
|
||||
client := redis.NewClient(opt)
|
||||
client.AddHook(tracingHook{tracer: telemetry.Tracer("storage.redis")})
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type tracingHook struct{ tracer trace.Tracer }
|
||||
|
||||
func (h tracingHook) DialHook(next redis.DialHook) redis.DialHook { return next }
|
||||
|
||||
func (h tracingHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
|
||||
return func(ctx context.Context, cmd redis.Cmder) error {
|
||||
return h.run(ctx, cmd.Name(), func(ctx context.Context) error { return next(ctx, cmd) })
|
||||
}
|
||||
}
|
||||
|
||||
func (h tracingHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(ctx context.Context, cmds []redis.Cmder) error {
|
||||
return h.run(ctx, "pipeline", func(ctx context.Context) error { return next(ctx, cmds) })
|
||||
}
|
||||
}
|
||||
|
||||
func (h tracingHook) run(ctx context.Context, op string, call func(context.Context) error) error {
|
||||
ctx, span := h.tracer.Start(ctx, "redis."+op, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("db.system.name", "redis"), attribute.String("db.operation.name", op)))
|
||||
defer span.End()
|
||||
err := call(ctx)
|
||||
if err != nil && !errors.Is(err, redis.Nil) {
|
||||
span.SetStatus(codes.Error, "операция Redis не выполнена")
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package s3
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
|
||||
|
||||
"high-loud-apps-labs/internal/domain"
|
||||
)
|
||||
@@ -25,10 +27,25 @@ type MinioStorage struct {
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg Config) (*MinioStorage, error) {
|
||||
base, err := minio.DefaultTransport(cfg.UseSSL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Оборачиваем базовый транспорт в otelhttp.
|
||||
// Опция WithSpanNameFormatter задаёт красивое имя спана (s3.PUT, s3.GET),
|
||||
// чтобы в Grafana не смотреть на дефолтное "HTTP PUT".
|
||||
tracedTransport := otelhttp.NewTransport(base,
|
||||
otelhttp.WithSpanNameFormatter(func(operation string, r *http.Request) string {
|
||||
return "s3." + r.Method
|
||||
}),
|
||||
)
|
||||
|
||||
client, err := minio.New(cfg.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
Transport: tracedTransport,
|
||||
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
|
||||
Secure: cfg.UseSSL,
|
||||
Region: cfg.Region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// Один span на HTTP-попытку MinIO до получения заголовков ответа.
|
||||
type tracingTransport struct {
|
||||
next http.RoundTripper
|
||||
tracer trace.Tracer
|
||||
}
|
||||
|
||||
func (t tracingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
ctx, span := t.tracer.Start(req.Context(), "s3."+req.Method, trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(attribute.String("http.request.method", req.Method)))
|
||||
defer span.End()
|
||||
|
||||
resp, err := t.next.RoundTrip(req.WithContext(ctx))
|
||||
if err != nil {
|
||||
span.SetStatus(codes.Error, "ошибка соединения с S3")
|
||||
} else {
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode))
|
||||
if resp.StatusCode >= 400 {
|
||||
span.SetStatus(codes.Error, http.StatusText(resp.StatusCode))
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
Reference in New Issue
Block a user