forked from mtusi2026/mtusi2026lab6
93 lines
2.0 KiB
Go
93 lines
2.0 KiB
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"go.opentelemetry.io/otel"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/codes"
|
|
"go.opentelemetry.io/otel/trace"
|
|
)
|
|
|
|
type pgxQueryTracer struct{}
|
|
|
|
func (pgxQueryTracer) TraceAcquireStart(
|
|
ctx context.Context,
|
|
_ *pgxpool.Pool,
|
|
_ pgxpool.TraceAcquireStartData,
|
|
) context.Context {
|
|
ctx, _ = otel.Tracer("mtusi2026lab6/postgresql").Start(
|
|
ctx,
|
|
"postgresql.acquire",
|
|
trace.WithSpanKind(trace.SpanKindClient),
|
|
trace.WithAttributes(
|
|
attribute.String("db.system.name", "postgresql"),
|
|
attribute.String("db.operation.name", "ACQUIRE"),
|
|
),
|
|
)
|
|
return ctx
|
|
}
|
|
|
|
func (pgxQueryTracer) TraceAcquireEnd(
|
|
ctx context.Context,
|
|
_ *pgxpool.Pool,
|
|
data pgxpool.TraceAcquireEndData,
|
|
) {
|
|
span := trace.SpanFromContext(ctx)
|
|
if data.Err != nil {
|
|
span.SetStatus(codes.Error, "database connection acquisition failed")
|
|
} else {
|
|
span.SetStatus(codes.Ok, "")
|
|
}
|
|
span.End()
|
|
}
|
|
|
|
func (pgxQueryTracer) TraceQueryStart(
|
|
ctx context.Context,
|
|
_ *pgx.Conn,
|
|
data pgx.TraceQueryStartData,
|
|
) context.Context {
|
|
operation := databaseOperation(data.SQL)
|
|
ctx, _ = otel.Tracer("mtusi2026lab6/postgresql").Start(
|
|
ctx,
|
|
"postgresql."+strings.ToLower(operation),
|
|
trace.WithSpanKind(trace.SpanKindClient),
|
|
trace.WithAttributes(
|
|
attribute.String("db.system.name", "postgresql"),
|
|
attribute.String("db.operation.name", operation),
|
|
),
|
|
)
|
|
return ctx
|
|
}
|
|
|
|
func (pgxQueryTracer) TraceQueryEnd(
|
|
ctx context.Context,
|
|
_ *pgx.Conn,
|
|
data pgx.TraceQueryEndData,
|
|
) {
|
|
span := trace.SpanFromContext(ctx)
|
|
if data.Err != nil {
|
|
span.SetStatus(codes.Error, "database operation failed")
|
|
} else {
|
|
span.SetStatus(codes.Ok, "")
|
|
}
|
|
span.End()
|
|
}
|
|
|
|
func databaseOperation(sql string) string {
|
|
fields := strings.Fields(sql)
|
|
if len(fields) == 0 {
|
|
return "QUERY"
|
|
}
|
|
operation := strings.ToUpper(fields[0])
|
|
switch operation {
|
|
case "SELECT", "INSERT", "UPDATE", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
|
return operation
|
|
default:
|
|
return "QUERY"
|
|
}
|
|
}
|