Add HTTP and gRPC instrumentation
HTTP server middleware, HTTP client transport and gRPC server/client interceptors (unary and stream) providing spans, context propagation, RED metrics with uniform names and access logs. Labels are kept low-cardinality (route templates, normalized methods). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c710afb127
commit
8398e81bc7
6 files changed
+1309
No files matched your search
@@ -0,0 +1,383 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
otelcodes "go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/peer"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// GRPCConfig configures gRPC server and client instrumentation.
|
||||
type GRPCConfig struct {
|
||||
Metrics *Metrics // nil disables metrics
|
||||
Logger *slog.Logger // nil disables server access logs
|
||||
TracerProvider trace.TracerProvider // nil: global provider
|
||||
Propagator propagation.TextMapPropagator // nil: global propagator
|
||||
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
|
||||
|
||||
// Skip excludes methods from instrumentation by full name, e.g.
|
||||
// "/grpc.health.v1.Health/Check".
|
||||
Skip func(fullMethod string) bool
|
||||
}
|
||||
|
||||
func (c *GRPCConfig) defaults() {
|
||||
if c.TracerProvider == nil {
|
||||
c.TracerProvider = otel.GetTracerProvider()
|
||||
}
|
||||
if c.Propagator == nil {
|
||||
c.Propagator = otel.GetTextMapPropagator()
|
||||
}
|
||||
}
|
||||
|
||||
// GRPCInterceptors bundles instrumented gRPC interceptors.
|
||||
//
|
||||
// Server metrics: grpc_server_requests_total, grpc_server_request_duration_seconds
|
||||
// (labels service, method, code) and grpc_server_requests_in_flight.
|
||||
// Client metrics: grpc_client_requests_total, grpc_client_request_duration_seconds
|
||||
// (labels service, method, code).
|
||||
type GRPCInterceptors struct {
|
||||
UnaryServer grpc.UnaryServerInterceptor
|
||||
StreamServer grpc.StreamServerInterceptor
|
||||
UnaryClient grpc.UnaryClientInterceptor
|
||||
StreamClient grpc.StreamClientInterceptor
|
||||
}
|
||||
|
||||
// NewGRPCInterceptors creates server and client interceptors providing
|
||||
// tracing with metadata propagation, metrics and server access logs.
|
||||
func NewGRPCInterceptors(cfg GRPCConfig) *GRPCInterceptors {
|
||||
cfg.defaults()
|
||||
g := &grpcInstrumentation{
|
||||
cfg: cfg,
|
||||
tracer: cfg.TracerProvider.Tracer(tracerName),
|
||||
}
|
||||
if cfg.Metrics != nil {
|
||||
m := cfg.Metrics.base()
|
||||
g.serverRequests = m.Counter("grpc_server_requests_total",
|
||||
"Total number of gRPC calls handled by the server.", "service", "method", "code")
|
||||
g.serverDuration = m.Histogram("grpc_server_request_duration_seconds",
|
||||
"Duration of gRPC calls handled by the server.", cfg.Buckets, "service", "method", "code")
|
||||
g.serverInflight = m.Gauge("grpc_server_requests_in_flight",
|
||||
"Number of gRPC calls currently being handled by the server.").WithLabelValues()
|
||||
g.clientRequests = m.Counter("grpc_client_requests_total",
|
||||
"Total number of outgoing gRPC calls.", "service", "method", "code")
|
||||
g.clientDuration = m.Histogram("grpc_client_request_duration_seconds",
|
||||
"Duration of outgoing gRPC calls.", cfg.Buckets, "service", "method", "code")
|
||||
}
|
||||
return &GRPCInterceptors{
|
||||
UnaryServer: g.unaryServer,
|
||||
StreamServer: g.streamServer,
|
||||
UnaryClient: g.unaryClient,
|
||||
StreamClient: g.streamClient,
|
||||
}
|
||||
}
|
||||
|
||||
// ServerOptions returns grpc.NewServer options installing the server interceptors.
|
||||
func (i *GRPCInterceptors) ServerOptions() []grpc.ServerOption {
|
||||
return []grpc.ServerOption{
|
||||
grpc.ChainUnaryInterceptor(i.UnaryServer),
|
||||
grpc.ChainStreamInterceptor(i.StreamServer),
|
||||
}
|
||||
}
|
||||
|
||||
// DialOptions returns grpc.NewClient options installing the client interceptors.
|
||||
func (i *GRPCInterceptors) DialOptions() []grpc.DialOption {
|
||||
return []grpc.DialOption{
|
||||
grpc.WithChainUnaryInterceptor(i.UnaryClient),
|
||||
grpc.WithChainStreamInterceptor(i.StreamClient),
|
||||
}
|
||||
}
|
||||
|
||||
type grpcInstrumentation struct {
|
||||
cfg GRPCConfig
|
||||
tracer trace.Tracer
|
||||
|
||||
serverRequests *prometheus.CounterVec
|
||||
serverDuration *prometheus.HistogramVec
|
||||
serverInflight prometheus.Gauge
|
||||
clientRequests *prometheus.CounterVec
|
||||
clientDuration *prometheus.HistogramVec
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) skip(fullMethod string) bool {
|
||||
return g.cfg.Skip != nil && g.cfg.Skip(fullMethod)
|
||||
}
|
||||
|
||||
// startServer extracts the remote span context and starts a server span.
|
||||
func (g *grpcInstrumentation) startServer(ctx context.Context, fullMethod string) (context.Context, trace.Span) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
ctx = g.cfg.Propagator.Extract(ctx, metadataCarrier(md))
|
||||
|
||||
service, method := splitFullMethod(fullMethod)
|
||||
attrs := []attribute.KeyValue{
|
||||
attribute.String("rpc.system", "grpc"),
|
||||
attribute.String("rpc.service", service),
|
||||
attribute.String("rpc.method", method),
|
||||
}
|
||||
if p, ok := peer.FromContext(ctx); ok && p.Addr != nil {
|
||||
attrs = append(attrs, attribute.String("client.address", clientIP(p.Addr.String())))
|
||||
}
|
||||
ctx, span := g.tracer.Start(ctx, strings.TrimPrefix(fullMethod, "/"),
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(attrs...),
|
||||
)
|
||||
if g.serverInflight != nil {
|
||||
g.serverInflight.Inc()
|
||||
}
|
||||
return ctx, span
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) finishServer(ctx context.Context, span trace.Span, fullMethod string, start time.Time, err error) {
|
||||
defer span.End()
|
||||
|
||||
st, _ := status.FromError(err)
|
||||
code := st.Code()
|
||||
elapsed := time.Since(start)
|
||||
service, method := splitFullMethod(fullMethod)
|
||||
|
||||
span.SetAttributes(attribute.Int("rpc.grpc.status_code", int(code)))
|
||||
isServerErr := isServerError(code)
|
||||
if isServerErr {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(otelcodes.Error, st.Message())
|
||||
}
|
||||
|
||||
if g.serverRequests != nil {
|
||||
g.serverInflight.Dec()
|
||||
g.serverRequests.WithLabelValues(service, method, code.String()).Inc()
|
||||
observe(ctx, g.serverDuration.WithLabelValues(service, method, code.String()), elapsed.Seconds())
|
||||
}
|
||||
|
||||
if g.cfg.Logger != nil {
|
||||
level := slog.LevelInfo
|
||||
if isServerErr {
|
||||
level = slog.LevelError
|
||||
}
|
||||
attrs := []slog.Attr{
|
||||
slog.String("service", service),
|
||||
slog.String("method", method),
|
||||
slog.String("code", code.String()),
|
||||
durationAttr(elapsed),
|
||||
}
|
||||
if err != nil {
|
||||
attrs = append(attrs, slog.String("error", st.Message()))
|
||||
}
|
||||
g.cfg.Logger.LogAttrs(ctx, level, "grpc request", attrs...)
|
||||
}
|
||||
}
|
||||
|
||||
// recoverServer converts a handler panic into a recorded error and re-panics.
|
||||
func (g *grpcInstrumentation) recoverServer(ctx context.Context, span trace.Span, fullMethod string, start time.Time) {
|
||||
if rec := recover(); rec != nil {
|
||||
err := status.Error(codes.Internal, fmt.Sprintf("panic: %v", rec))
|
||||
g.finishServer(ctx, span, fullMethod, start, err)
|
||||
panic(rec)
|
||||
}
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) unaryServer(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if g.skip(info.FullMethod) {
|
||||
return handler(ctx, req)
|
||||
}
|
||||
start := time.Now()
|
||||
ctx, span := g.startServer(ctx, info.FullMethod)
|
||||
defer g.recoverServer(ctx, span, info.FullMethod, start)
|
||||
|
||||
resp, err := handler(ctx, req)
|
||||
g.finishServer(ctx, span, info.FullMethod, start, err)
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) streamServer(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
if g.skip(info.FullMethod) {
|
||||
return handler(srv, ss)
|
||||
}
|
||||
start := time.Now()
|
||||
ctx, span := g.startServer(ss.Context(), info.FullMethod)
|
||||
defer g.recoverServer(ctx, span, info.FullMethod, start)
|
||||
|
||||
err := handler(srv, &serverStream{ServerStream: ss, ctx: ctx})
|
||||
g.finishServer(ctx, span, info.FullMethod, start, err)
|
||||
return err
|
||||
}
|
||||
|
||||
// startClient starts a client span and injects its context into outgoing metadata.
|
||||
func (g *grpcInstrumentation) startClient(ctx context.Context, fullMethod, target string) (context.Context, trace.Span) {
|
||||
service, method := splitFullMethod(fullMethod)
|
||||
ctx, span := g.tracer.Start(ctx, strings.TrimPrefix(fullMethod, "/"),
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("rpc.system", "grpc"),
|
||||
attribute.String("rpc.service", service),
|
||||
attribute.String("rpc.method", method),
|
||||
attribute.String("server.address", target),
|
||||
),
|
||||
)
|
||||
|
||||
md, ok := metadata.FromOutgoingContext(ctx)
|
||||
if ok {
|
||||
md = md.Copy()
|
||||
} else {
|
||||
md = metadata.MD{}
|
||||
}
|
||||
g.cfg.Propagator.Inject(ctx, metadataCarrier(md))
|
||||
return metadata.NewOutgoingContext(ctx, md), span
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) finishClient(ctx context.Context, span trace.Span, fullMethod string, start time.Time, err error) {
|
||||
defer span.End()
|
||||
|
||||
st, _ := status.FromError(err)
|
||||
code := st.Code()
|
||||
span.SetAttributes(attribute.Int("rpc.grpc.status_code", int(code)))
|
||||
if code != codes.OK {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(otelcodes.Error, st.Message())
|
||||
}
|
||||
|
||||
if g.clientRequests != nil {
|
||||
service, method := splitFullMethod(fullMethod)
|
||||
g.clientRequests.WithLabelValues(service, method, code.String()).Inc()
|
||||
observe(ctx, g.clientDuration.WithLabelValues(service, method, code.String()), time.Since(start).Seconds())
|
||||
}
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) unaryClient(ctx context.Context, fullMethod string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
if g.skip(fullMethod) {
|
||||
return invoker(ctx, fullMethod, req, reply, cc, opts...)
|
||||
}
|
||||
start := time.Now()
|
||||
ctx, span := g.startClient(ctx, fullMethod, cc.Target())
|
||||
err := invoker(ctx, fullMethod, req, reply, cc, opts...)
|
||||
g.finishClient(ctx, span, fullMethod, start, err)
|
||||
return err
|
||||
}
|
||||
|
||||
func (g *grpcInstrumentation) streamClient(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, fullMethod string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
||||
if g.skip(fullMethod) {
|
||||
return streamer(ctx, desc, cc, fullMethod, opts...)
|
||||
}
|
||||
start := time.Now()
|
||||
ctx, span := g.startClient(ctx, fullMethod, cc.Target())
|
||||
cs, err := streamer(ctx, desc, cc, fullMethod, opts...)
|
||||
if err != nil {
|
||||
g.finishClient(ctx, span, fullMethod, start, err)
|
||||
return nil, err
|
||||
}
|
||||
return &clientStream{
|
||||
ClientStream: cs,
|
||||
desc: desc,
|
||||
finish: func(err error) {
|
||||
g.finishClient(ctx, span, fullMethod, start, err)
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// serverStream overrides the stream context with the traced one.
|
||||
type serverStream struct {
|
||||
grpc.ServerStream
|
||||
ctx context.Context
|
||||
}
|
||||
|
||||
func (s *serverStream) Context() context.Context { return s.ctx }
|
||||
|
||||
// clientStream finishes the span and metrics when the stream completes:
|
||||
// RecvMsg returns io.EOF or an error, or the single response of a
|
||||
// non-server-streaming call has been received.
|
||||
type clientStream struct {
|
||||
grpc.ClientStream
|
||||
desc *grpc.StreamDesc
|
||||
once sync.Once
|
||||
finish func(error)
|
||||
}
|
||||
|
||||
func (s *clientStream) done(err error) {
|
||||
s.once.Do(func() { s.finish(err) })
|
||||
}
|
||||
|
||||
func (s *clientStream) RecvMsg(m any) error {
|
||||
err := s.ClientStream.RecvMsg(m)
|
||||
switch {
|
||||
case errors.Is(err, io.EOF):
|
||||
s.done(nil)
|
||||
case err != nil:
|
||||
s.done(err)
|
||||
case !s.desc.ServerStreams:
|
||||
s.done(nil)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *clientStream) SendMsg(m any) error {
|
||||
err := s.ClientStream.SendMsg(m)
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
s.done(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *clientStream) Header() (metadata.MD, error) {
|
||||
md, err := s.ClientStream.Header()
|
||||
if err != nil {
|
||||
s.done(err)
|
||||
}
|
||||
return md, err
|
||||
}
|
||||
|
||||
// isServerError reports whether code indicates a server-side failure
|
||||
// (as opposed to a client error such as InvalidArgument or NotFound).
|
||||
func isServerError(c codes.Code) bool {
|
||||
switch c {
|
||||
case codes.Unknown, codes.DeadlineExceeded, codes.Unimplemented,
|
||||
codes.Internal, codes.Unavailable, codes.DataLoss:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// splitFullMethod splits "/pkg.Service/Method" into ("pkg.Service", "Method").
|
||||
func splitFullMethod(fullMethod string) (service, method string) {
|
||||
name := strings.TrimPrefix(fullMethod, "/")
|
||||
if i := strings.LastIndexByte(name, '/'); i >= 0 {
|
||||
return name[:i], name[i+1:]
|
||||
}
|
||||
return "unknown", name
|
||||
}
|
||||
|
||||
// metadataCarrier adapts gRPC metadata to propagation.TextMapCarrier.
|
||||
type metadataCarrier metadata.MD
|
||||
|
||||
func (c metadataCarrier) Get(key string) string {
|
||||
if v := metadata.MD(c).Get(key); len(v) > 0 {
|
||||
return v[0]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (c metadataCarrier) Set(key, value string) {
|
||||
metadata.MD(c).Set(key, value)
|
||||
}
|
||||
|
||||
func (c metadataCarrier) Keys() []string {
|
||||
keys := make([]string, 0, len(c))
|
||||
for k := range c {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
return keys
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"google.golang.org/grpc"
|
||||
grpccodes "google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
healthpb "google.golang.org/grpc/health/grpc_health_v1"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
)
|
||||
|
||||
// startGRPC serves a grpc.health.v1 service backed by h over an in-memory
|
||||
// connection, with both server and client instrumented by ic.
|
||||
func startGRPC(t *testing.T, h *Health, ic *GRPCInterceptors) healthpb.HealthClient {
|
||||
t.Helper()
|
||||
ln := bufconn.Listen(1 << 20)
|
||||
srv := grpc.NewServer(ic.ServerOptions()...)
|
||||
healthpb.RegisterHealthServer(srv, h.GRPCServer())
|
||||
go func() { _ = srv.Serve(ln) }()
|
||||
t.Cleanup(srv.Stop)
|
||||
|
||||
opts := append([]grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return ln.DialContext(ctx) }),
|
||||
}, ic.DialOptions()...)
|
||||
conn, err := grpc.NewClient("passthrough:///bufnet", opts...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return healthpb.NewHealthClient(conn)
|
||||
}
|
||||
|
||||
func TestGRPC_UnaryInstrumentation(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
var logs bytes.Buffer
|
||||
logger, _ := NewLogger(LogConfig{Output: &logs})
|
||||
|
||||
h := NewHealth(HealthConfig{})
|
||||
client := startGRPC(t, h, NewGRPCInterceptors(GRPCConfig{
|
||||
Metrics: m,
|
||||
Logger: logger,
|
||||
TracerProvider: tp,
|
||||
Propagator: testPropagator,
|
||||
}))
|
||||
|
||||
resp, err := client.Check(context.Background(), &healthpb.HealthCheckRequest{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Status != healthpb.HealthCheckResponse_SERVING {
|
||||
t.Errorf("status = %v, want SERVING", resp.Status)
|
||||
}
|
||||
|
||||
h.SetReady(false)
|
||||
resp, err = client.Check(context.Background(), &healthpb.HealthCheckRequest{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Status != healthpb.HealthCheckResponse_NOT_SERVING {
|
||||
t.Errorf("status = %v, want NOT_SERVING", resp.Status)
|
||||
}
|
||||
|
||||
body := scrape(t, m)
|
||||
for _, want := range []string{
|
||||
`grpc_server_requests_total{code="OK",method="Check",service="grpc.health.v1.Health"} 2`,
|
||||
`grpc_client_requests_total{code="OK",method="Check",service="grpc.health.v1.Health"} 2`,
|
||||
`grpc_server_request_duration_seconds_count{code="OK",method="Check",service="grpc.health.v1.Health"} 2`,
|
||||
`grpc_server_requests_in_flight 0`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics missing %q", want)
|
||||
}
|
||||
}
|
||||
|
||||
// Server span (ended first) must be a child of the client span.
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 4 {
|
||||
t.Fatalf("got %d spans, want 4", len(spans))
|
||||
}
|
||||
server, client0 := spans[0], spans[1]
|
||||
if server.SpanKind != trace.SpanKindServer || client0.SpanKind != trace.SpanKindClient {
|
||||
t.Fatalf("unexpected span kinds: %v, %v", server.SpanKind, client0.SpanKind)
|
||||
}
|
||||
if server.Name != "grpc.health.v1.Health/Check" {
|
||||
t.Errorf("span name = %q", server.Name)
|
||||
}
|
||||
if server.Parent.SpanID() != client0.SpanContext.SpanID() {
|
||||
t.Error("server span is not a child of the client span: metadata propagation failed")
|
||||
}
|
||||
|
||||
if !strings.Contains(logs.String(), `"msg":"grpc request"`) || !strings.Contains(logs.String(), `"code":"OK"`) {
|
||||
t.Errorf("missing gRPC access log: %s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGRPC_StreamInstrumentation(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
client := startGRPC(t, NewHealth(HealthConfig{}), NewGRPCInterceptors(GRPCConfig{
|
||||
Metrics: m,
|
||||
TracerProvider: tp,
|
||||
Propagator: testPropagator,
|
||||
}))
|
||||
|
||||
stream, err := client.Watch(context.Background(), &healthpb.HealthCheckRequest{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = stream.Recv()
|
||||
if status.Code(err) != grpccodes.Unimplemented {
|
||||
t.Fatalf("Recv error = %v, want Unimplemented", err)
|
||||
}
|
||||
if _, err := stream.Recv(); err == nil || err == io.EOF {
|
||||
t.Fatalf("second Recv error = %v", err)
|
||||
}
|
||||
|
||||
body := scrape(t, m)
|
||||
for _, want := range []string{
|
||||
`grpc_server_requests_total{code="Unimplemented",method="Watch",service="grpc.health.v1.Health"} 1`,
|
||||
`grpc_client_requests_total{code="Unimplemented",method="Watch",service="grpc.health.v1.Health"} 1`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics missing %q\n%s", want, body)
|
||||
}
|
||||
}
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 2 {
|
||||
t.Fatalf("got %d spans, want 2", len(spans))
|
||||
}
|
||||
for _, s := range spans {
|
||||
if s.Status.Code != codes.Error {
|
||||
t.Errorf("span %q (%v) status = %v, want Error", s.Name, s.SpanKind, s.Status.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGRPC_Skip(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
client := startGRPC(t, NewHealth(HealthConfig{}), NewGRPCInterceptors(GRPCConfig{
|
||||
Metrics: m,
|
||||
Skip: func(string) bool { return true },
|
||||
}))
|
||||
if _, err := client.Check(context.Background(), &healthpb.HealthCheckRequest{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(scrape(t, m), "grpc_server_requests_total{") {
|
||||
t.Error("skipped method was instrumented")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSplitFullMethod(t *testing.T) {
|
||||
tests := []struct{ in, service, method string }{
|
||||
{"/pkg.Service/Method", "pkg.Service", "Method"},
|
||||
{"/a.b.c.Svc/Do", "a.b.c.Svc", "Do"},
|
||||
{"bad", "unknown", "bad"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
s, m := splitFullMethod(tt.in)
|
||||
if s != tt.service || m != tt.method {
|
||||
t.Errorf("splitFullMethod(%q) = %q, %q", tt.in, s, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// HTTPClientConfig configures the instrumented HTTP client transport.
|
||||
type HTTPClientConfig struct {
|
||||
Metrics *Metrics // nil disables metrics
|
||||
TracerProvider trace.TracerProvider // nil: global provider
|
||||
Propagator propagation.TextMapPropagator // nil: global propagator
|
||||
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
|
||||
}
|
||||
|
||||
func (c *HTTPClientConfig) defaults() {
|
||||
if c.TracerProvider == nil {
|
||||
c.TracerProvider = otel.GetTracerProvider()
|
||||
}
|
||||
if c.Propagator == nil {
|
||||
c.Propagator = otel.GetTextMapPropagator()
|
||||
}
|
||||
}
|
||||
|
||||
type httpClientMetrics struct {
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
}
|
||||
|
||||
func newHTTPClientMetrics(m *Metrics, buckets []float64) *httpClientMetrics {
|
||||
m = m.base()
|
||||
return &httpClientMetrics{
|
||||
requests: m.Counter("http_client_requests_total",
|
||||
"Total number of outgoing HTTP requests.", "method", "host", "code"),
|
||||
duration: m.Histogram("http_client_request_duration_seconds",
|
||||
"Duration of outgoing HTTP requests until response headers are received.", buckets, "method", "host", "code"),
|
||||
}
|
||||
}
|
||||
|
||||
type clientTransport struct {
|
||||
base http.RoundTripper
|
||||
tracer trace.Tracer
|
||||
propagator propagation.TextMapPropagator
|
||||
metrics *httpClientMetrics
|
||||
}
|
||||
|
||||
// NewHTTPTransport wraps base (http.DefaultTransport when nil) with client
|
||||
// spans, trace context propagation and metrics:
|
||||
// http_client_requests_total and http_client_request_duration_seconds
|
||||
// (labels method, host, code; code is "error" for transport failures).
|
||||
func NewHTTPTransport(base http.RoundTripper, cfg HTTPClientConfig) http.RoundTripper {
|
||||
cfg.defaults()
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
}
|
||||
t := &clientTransport{
|
||||
base: base,
|
||||
tracer: cfg.TracerProvider.Tracer(tracerName),
|
||||
propagator: cfg.Propagator,
|
||||
}
|
||||
if cfg.Metrics != nil {
|
||||
t.metrics = newHTTPClientMetrics(cfg.Metrics, cfg.Buckets)
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// RoundTrip implements http.RoundTripper.
|
||||
func (t *clientTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
start := time.Now()
|
||||
method := normalizeMethod(req.Method)
|
||||
|
||||
ctx, span := t.tracer.Start(req.Context(), method,
|
||||
trace.WithSpanKind(trace.SpanKindClient),
|
||||
trace.WithAttributes(
|
||||
attribute.String("http.request.method", method),
|
||||
attribute.String("server.address", req.URL.Hostname()),
|
||||
attribute.String("url.full", redactURL(req)),
|
||||
),
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// RoundTrippers must not modify the caller's request.
|
||||
req = req.Clone(ctx)
|
||||
t.propagator.Inject(ctx, propagation.HeaderCarrier(req.Header))
|
||||
|
||||
resp, err := t.base.RoundTrip(req)
|
||||
|
||||
code := "error"
|
||||
if err != nil {
|
||||
failSpan(span, err)
|
||||
} else {
|
||||
code = strconv.Itoa(resp.StatusCode)
|
||||
span.SetAttributes(attribute.Int("http.response.status_code", resp.StatusCode))
|
||||
if resp.StatusCode >= 400 {
|
||||
span.SetStatus(codes.Error, http.StatusText(resp.StatusCode))
|
||||
}
|
||||
}
|
||||
|
||||
if t.metrics != nil {
|
||||
host := req.URL.Host
|
||||
t.metrics.requests.WithLabelValues(method, host, code).Inc()
|
||||
observe(ctx, t.metrics.duration.WithLabelValues(method, host, code), time.Since(start).Seconds())
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
// redactURL returns the request URL without user credentials.
|
||||
func redactURL(req *http.Request) string {
|
||||
if req.URL.User == nil {
|
||||
return req.URL.String()
|
||||
}
|
||||
u := *req.URL
|
||||
u.User = nil
|
||||
return u.String()
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func TestHTTPTransport_PropagationAndMetrics(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
|
||||
var gotTraceparent string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotTraceparent = r.Header.Get("traceparent")
|
||||
if r.URL.Path == "/missing" {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{
|
||||
Metrics: m,
|
||||
TracerProvider: tp,
|
||||
Propagator: testPropagator,
|
||||
})}
|
||||
|
||||
req, _ := http.NewRequest("GET", srv.URL+"/ok", nil)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if req.Header.Get("traceparent") != "" {
|
||||
t.Error("transport modified the caller's request headers")
|
||||
}
|
||||
|
||||
resp, err = client.Get(srv.URL + "/missing")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 2 {
|
||||
t.Fatalf("got %d spans, want 2", len(spans))
|
||||
}
|
||||
if spans[0].SpanKind != trace.SpanKindClient {
|
||||
t.Errorf("span kind = %v, want client", spans[0].SpanKind)
|
||||
}
|
||||
sc := spans[1].SpanContext
|
||||
if !strings.Contains(gotTraceparent, sc.TraceID().String()) || !strings.Contains(gotTraceparent, sc.SpanID().String()) {
|
||||
t.Errorf("traceparent %q does not reference client span %s/%s", gotTraceparent, sc.TraceID(), sc.SpanID())
|
||||
}
|
||||
|
||||
host := strings.TrimPrefix(srv.URL, "http://")
|
||||
body := scrape(t, m)
|
||||
for _, want := range []string{
|
||||
`http_client_requests_total{code="200",host="` + host + `",method="GET"} 1`,
|
||||
`http_client_requests_total{code="404",host="` + host + `",method="GET"} 1`,
|
||||
`http_client_request_duration_seconds_count{code="200",host="` + host + `",method="GET"} 1`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics missing %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPTransport_Error(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
client := &http.Client{Transport: NewHTTPTransport(nil, HTTPClientConfig{Metrics: m, TracerProvider: tp, Propagator: propagation.TraceContext{}})}
|
||||
|
||||
srv := httptest.NewServer(http.NotFoundHandler())
|
||||
addr := srv.URL
|
||||
srv.Close() // connection refused
|
||||
|
||||
if _, err := client.Get(addr); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !strings.Contains(scrape(t, m), `code="error"`) {
|
||||
t.Error("transport error not counted with code=error")
|
||||
}
|
||||
if spans := exp.GetSpans(); len(spans) != 1 || len(spans[0].Events) == 0 {
|
||||
t.Error("transport error not recorded on span")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactURL(t *testing.T) {
|
||||
u, _ := url.Parse("https://user:secret@example.com/path?q=1")
|
||||
got := redactURL(&http.Request{URL: u})
|
||||
if strings.Contains(got, "secret") || strings.Contains(got, "user") {
|
||||
t.Errorf("credentials not redacted: %s", got)
|
||||
}
|
||||
if got != "https://example.com/path?q=1" {
|
||||
t.Errorf("redactURL = %q", got)
|
||||
}
|
||||
}
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// routeUnmatched is the route label for requests whose route is unknown.
|
||||
// Raw paths are never used as labels to keep metric cardinality bounded.
|
||||
const routeUnmatched = "unmatched"
|
||||
|
||||
// HTTPServerConfig configures the HTTP server middleware.
|
||||
type HTTPServerConfig struct {
|
||||
Metrics *Metrics // nil disables metrics
|
||||
Logger *slog.Logger // nil disables access logs
|
||||
TracerProvider trace.TracerProvider // nil: global provider
|
||||
Propagator propagation.TextMapPropagator // nil: global propagator
|
||||
|
||||
// RouteFunc returns the low-cardinality route template of a request
|
||||
// (e.g. "/users/{id}"). It is called after the handler has run. The
|
||||
// default uses http.Request.Pattern set by http.ServeMux; when the
|
||||
// middleware wraps an *http.ServeMux directly the pattern is resolved even
|
||||
// if inner middleware replaced the request. Unknown routes are reported
|
||||
// as "unmatched".
|
||||
//
|
||||
// For chi: func(r *http.Request) string { return chi.RouteContext(r.Context()).RoutePattern() }
|
||||
RouteFunc func(r *http.Request) string
|
||||
|
||||
Skip func(r *http.Request) bool // requests for which Skip returns true are not instrumented
|
||||
Buckets []float64 // latency buckets in seconds, default: prometheus.DefBuckets
|
||||
TraceIDHeader string // if set, the trace ID is returned in this response header, e.g. "X-Trace-Id"
|
||||
}
|
||||
|
||||
func (c *HTTPServerConfig) defaults() {
|
||||
if c.TracerProvider == nil {
|
||||
c.TracerProvider = otel.GetTracerProvider()
|
||||
}
|
||||
if c.Propagator == nil {
|
||||
c.Propagator = otel.GetTextMapPropagator()
|
||||
}
|
||||
}
|
||||
|
||||
type httpServerMetrics struct {
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
inflight prometheus.Gauge
|
||||
}
|
||||
|
||||
func newHTTPServerMetrics(m *Metrics, buckets []float64) *httpServerMetrics {
|
||||
m = m.base()
|
||||
return &httpServerMetrics{
|
||||
requests: m.Counter("http_server_requests_total",
|
||||
"Total number of HTTP requests handled by the server.", "method", "route", "code"),
|
||||
duration: m.Histogram("http_server_request_duration_seconds",
|
||||
"Duration of HTTP requests handled by the server.", buckets, "method", "route", "code"),
|
||||
inflight: m.Gauge("http_server_requests_in_flight",
|
||||
"Number of HTTP requests currently being handled by the server.").WithLabelValues(),
|
||||
}
|
||||
}
|
||||
|
||||
// NewHTTPMiddleware returns middleware that instruments HTTP handlers with
|
||||
// tracing (incoming context extraction, server spans), RED metrics and access
|
||||
// logs. It is compatible with any router accepting func(http.Handler) http.Handler.
|
||||
//
|
||||
// Metrics: http_server_requests_total, http_server_request_duration_seconds
|
||||
// (labels method, route, code) and http_server_requests_in_flight.
|
||||
//
|
||||
// Panics are recorded as 500 responses and re-raised.
|
||||
func NewHTTPMiddleware(cfg HTTPServerConfig) func(http.Handler) http.Handler {
|
||||
cfg.defaults()
|
||||
|
||||
var metrics *httpServerMetrics
|
||||
if cfg.Metrics != nil {
|
||||
metrics = newHTTPServerMetrics(cfg.Metrics, cfg.Buckets)
|
||||
}
|
||||
tracer := cfg.TracerProvider.Tracer(tracerName)
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
routeFunc := cfg.RouteFunc
|
||||
if routeFunc == nil {
|
||||
mux, _ := next.(*http.ServeMux)
|
||||
routeFunc = func(r *http.Request) string { return patternRoute(r, mux) }
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if cfg.Skip != nil && cfg.Skip(r) {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
method := normalizeMethod(r.Method)
|
||||
|
||||
ctx := cfg.Propagator.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
ctx, span := tracer.Start(ctx, method,
|
||||
trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("http.request.method", method),
|
||||
attribute.String("url.path", r.URL.Path),
|
||||
attribute.String("url.scheme", requestScheme(r)),
|
||||
attribute.String("server.address", r.Host),
|
||||
attribute.String("client.address", clientIP(r.RemoteAddr)),
|
||||
attribute.String("user_agent.original", r.UserAgent()),
|
||||
),
|
||||
)
|
||||
|
||||
if cfg.TraceIDHeader != "" && span.SpanContext().HasTraceID() {
|
||||
w.Header().Set(cfg.TraceIDHeader, span.SpanContext().TraceID().String())
|
||||
}
|
||||
|
||||
if metrics != nil {
|
||||
metrics.inflight.Inc()
|
||||
}
|
||||
|
||||
rw := &responseWriter{ResponseWriter: w}
|
||||
r = r.WithContext(ctx)
|
||||
|
||||
defer func() {
|
||||
rec := recover()
|
||||
|
||||
status := rw.status
|
||||
switch {
|
||||
case rec != nil && !rw.wroteHeader:
|
||||
status = http.StatusInternalServerError
|
||||
case status == 0:
|
||||
status = http.StatusOK
|
||||
}
|
||||
|
||||
route := routeFunc(r)
|
||||
if route == "" {
|
||||
route = routeUnmatched
|
||||
}
|
||||
code := strconv.Itoa(status)
|
||||
elapsed := time.Since(start)
|
||||
|
||||
if route != routeUnmatched {
|
||||
span.SetName(method + " " + route)
|
||||
span.SetAttributes(attribute.String("http.route", route))
|
||||
}
|
||||
span.SetAttributes(
|
||||
attribute.Int("http.response.status_code", status),
|
||||
attribute.Int64("http.response.body.size", rw.size),
|
||||
)
|
||||
if rec != nil {
|
||||
span.RecordError(fmt.Errorf("panic: %v", rec), trace.WithStackTrace(true))
|
||||
}
|
||||
if status >= 500 {
|
||||
span.SetStatus(codes.Error, http.StatusText(status))
|
||||
}
|
||||
|
||||
if metrics != nil {
|
||||
metrics.inflight.Dec()
|
||||
metrics.requests.WithLabelValues(method, route, code).Inc()
|
||||
observe(ctx, metrics.duration.WithLabelValues(method, route, code), elapsed.Seconds())
|
||||
}
|
||||
|
||||
if cfg.Logger != nil {
|
||||
level := slog.LevelInfo
|
||||
if status >= 500 {
|
||||
level = slog.LevelError
|
||||
}
|
||||
attrs := []slog.Attr{
|
||||
slog.String("method", r.Method),
|
||||
slog.String("path", r.URL.Path),
|
||||
slog.String("route", route),
|
||||
slog.Int("status", status),
|
||||
durationAttr(elapsed),
|
||||
slog.Int64("size", rw.size),
|
||||
slog.String("remote", clientIP(r.RemoteAddr)),
|
||||
}
|
||||
if rec != nil {
|
||||
attrs = append(attrs, slog.Any("panic", rec))
|
||||
}
|
||||
cfg.Logger.LogAttrs(ctx, level, "http request", attrs...)
|
||||
}
|
||||
|
||||
span.End()
|
||||
|
||||
if rec != nil {
|
||||
panic(rec)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(rw, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// patternRoute derives the route from the ServeMux pattern ("GET /users/{id}"
|
||||
// becomes "/users/{id}"). If the request was copied by inner middleware the
|
||||
// pattern is resolved through mux, when known.
|
||||
func patternRoute(r *http.Request, mux *http.ServeMux) string {
|
||||
pattern := r.Pattern
|
||||
if pattern == "" && mux != nil {
|
||||
_, pattern = mux.Handler(r)
|
||||
}
|
||||
if pattern == "" {
|
||||
return routeUnmatched
|
||||
}
|
||||
if i := strings.IndexAny(pattern, " \t"); i >= 0 {
|
||||
pattern = strings.TrimLeft(pattern[i:], " \t")
|
||||
}
|
||||
return pattern
|
||||
}
|
||||
|
||||
// normalizeMethod maps non-standard methods to "OTHER" to bound cardinality.
|
||||
func normalizeMethod(m string) string {
|
||||
switch m {
|
||||
case http.MethodGet, http.MethodHead, http.MethodPost, http.MethodPut, http.MethodPatch,
|
||||
http.MethodDelete, http.MethodConnect, http.MethodOptions, http.MethodTrace:
|
||||
return m
|
||||
default:
|
||||
return "OTHER"
|
||||
}
|
||||
}
|
||||
|
||||
func requestScheme(r *http.Request) string {
|
||||
if r.TLS != nil {
|
||||
return "https"
|
||||
}
|
||||
return "http"
|
||||
}
|
||||
|
||||
func clientIP(remoteAddr string) string {
|
||||
if host, _, err := net.SplitHostPort(remoteAddr); err == nil {
|
||||
return host
|
||||
}
|
||||
return remoteAddr
|
||||
}
|
||||
|
||||
// responseWriter captures the status code and body size. It supports
|
||||
// http.Flusher, http.Hijacker, io.ReaderFrom and http.ResponseController
|
||||
// (via Unwrap).
|
||||
type responseWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
size int64
|
||||
wroteHeader bool
|
||||
}
|
||||
|
||||
func (w *responseWriter) WriteHeader(code int) {
|
||||
if !w.wroteHeader && code >= 200 {
|
||||
w.status = code
|
||||
w.wroteHeader = true
|
||||
}
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *responseWriter) Write(b []byte) (int, error) {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
n, err := w.ResponseWriter.Write(b)
|
||||
w.size += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *responseWriter) ReadFrom(src io.Reader) (int64, error) {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
n, err := io.Copy(w.ResponseWriter, src)
|
||||
w.size += n
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (w *responseWriter) Flush() {
|
||||
if !w.wroteHeader {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
_ = http.NewResponseController(w.ResponseWriter).Flush()
|
||||
}
|
||||
|
||||
func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
conn, rw, err := http.NewResponseController(w.ResponseWriter).Hijack()
|
||||
if err == nil && !w.wroteHeader {
|
||||
w.status = http.StatusSwitchingProtocols
|
||||
w.wroteHeader = true
|
||||
}
|
||||
return conn, rw, err
|
||||
}
|
||||
|
||||
func (w *responseWriter) Unwrap() http.ResponseWriter {
|
||||
return w.ResponseWriter
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package obsx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
func newTestProvider(t *testing.T) (*sdktrace.TracerProvider, *tracetest.InMemoryExporter) {
|
||||
t.Helper()
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp))
|
||||
t.Cleanup(func() { _ = tp.Shutdown(context.Background()) })
|
||||
return tp, exp
|
||||
}
|
||||
|
||||
var testPropagator = propagation.TraceContext{}
|
||||
|
||||
func TestHTTPMiddleware_MetricsAndSpans(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{Namespace: "ignored"})
|
||||
tp, exp := newTestProvider(t)
|
||||
var logs bytes.Buffer
|
||||
logger, _ := NewLogger(LogConfig{Output: &logs})
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("user"))
|
||||
})
|
||||
mux.HandleFunc("POST /fail", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
})
|
||||
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{
|
||||
Metrics: m,
|
||||
Logger: logger,
|
||||
TracerProvider: tp,
|
||||
Propagator: testPropagator,
|
||||
TraceIDHeader: "X-Trace-Id",
|
||||
})(mux)
|
||||
|
||||
for _, id := range []string{"1", "2"} {
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest("GET", "/users/"+id, nil))
|
||||
if w.Header().Get("X-Trace-Id") == "" {
|
||||
t.Error("missing X-Trace-Id response header")
|
||||
}
|
||||
}
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/fail", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/nope", nil))
|
||||
|
||||
body := scrape(t, m)
|
||||
for _, want := range []string{
|
||||
`http_server_requests_total{code="200",method="GET",route="/users/{id}"} 2`,
|
||||
`http_server_requests_total{code="502",method="POST",route="/fail"} 1`,
|
||||
`http_server_requests_total{code="404",method="GET",route="unmatched"} 1`,
|
||||
`http_server_request_duration_seconds_count{code="200",method="GET",route="/users/{id}"} 2`,
|
||||
`http_server_requests_in_flight 0`,
|
||||
} {
|
||||
if !strings.Contains(body, want) {
|
||||
t.Errorf("metrics missing %q", want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(body, "ignored_http") {
|
||||
t.Error("built-in metrics must not use the configured namespace")
|
||||
}
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 4 {
|
||||
t.Fatalf("got %d spans, want 4", len(spans))
|
||||
}
|
||||
if spans[0].Name != "GET /users/{id}" || spans[0].SpanKind != trace.SpanKindServer {
|
||||
t.Errorf("span = %q kind %v, want %q server", spans[0].Name, spans[0].SpanKind, "GET /users/{id}")
|
||||
}
|
||||
if spans[2].Status.Code != codes.Error {
|
||||
t.Errorf("5xx span status = %v, want Error", spans[2].Status.Code)
|
||||
}
|
||||
|
||||
lines := strings.Split(strings.TrimSpace(logs.String()), "\n")
|
||||
if len(lines) != 4 {
|
||||
t.Fatalf("got %d access log lines, want 4:\n%s", len(lines), logs.String())
|
||||
}
|
||||
var rec map[string]any
|
||||
if err := json.Unmarshal([]byte(lines[2]), &rec); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec["level"] != "ERROR" || rec["route"] != "/fail" || rec["status"] != float64(502) || rec["trace_id"] == nil {
|
||||
t.Errorf("unexpected access log record: %v", rec)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMiddleware_PropagatesParent(t *testing.T) {
|
||||
tp, exp := newTestProvider(t)
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{TracerProvider: tp, Propagator: testPropagator})(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||
|
||||
parentCtx, parent := tp.Tracer("client").Start(context.Background(), "client")
|
||||
req := httptest.NewRequest("GET", "/", nil)
|
||||
testPropagator.Inject(parentCtx, propagation.HeaderCarrier(req.Header))
|
||||
h.ServeHTTP(httptest.NewRecorder(), req)
|
||||
parent.End()
|
||||
|
||||
server := exp.GetSpans()[0]
|
||||
if server.Parent.SpanID() != parent.SpanContext().SpanID() {
|
||||
t.Errorf("server span parent = %s, want %s", server.Parent.SpanID(), parent.SpanContext().SpanID())
|
||||
}
|
||||
if server.SpanContext.TraceID() != parent.SpanContext().TraceID() {
|
||||
t.Error("server span not in the caller's trace")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMiddleware_RouteWithInnerMiddleware(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {})
|
||||
|
||||
// Inner middleware replaces the request, so r.Pattern is not visible to
|
||||
// the outer middleware; route must still be resolved.
|
||||
inner := func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), struct{}{}, 1)))
|
||||
})
|
||||
}
|
||||
mw := NewHTTPMiddleware(HTTPServerConfig{Metrics: m})
|
||||
|
||||
// Wrapping the mux directly resolves the route through r.Pattern.
|
||||
mw(mux).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/1", nil))
|
||||
// Through foreign middleware the route is unknown unless RouteFunc is set.
|
||||
mw(inner(mux)).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/2", nil))
|
||||
NewHTTPMiddleware(HTTPServerConfig{Metrics: m, RouteFunc: func(r *http.Request) string {
|
||||
_, p := mux.Handler(r)
|
||||
return strings.TrimPrefix(p, "GET ")
|
||||
}})(inner(mux)).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/items/3", nil))
|
||||
|
||||
body := scrape(t, m)
|
||||
if !strings.Contains(body, `http_server_requests_total{code="200",method="GET",route="/items/{id}"} 2`) {
|
||||
t.Errorf("expected 2 requests on /items/{id}:\n%s", body)
|
||||
}
|
||||
if !strings.Contains(body, `http_server_requests_total{code="200",method="GET",route="unmatched"} 1`) {
|
||||
t.Errorf("expected 1 unmatched request:\n%s", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMiddleware_Panic(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
tp, exp := newTestProvider(t)
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{Metrics: m, TracerProvider: tp})(
|
||||
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("boom") }))
|
||||
|
||||
func() {
|
||||
defer func() {
|
||||
if rec := recover(); rec != "boom" {
|
||||
t.Errorf("panic not re-raised, got %v", rec)
|
||||
}
|
||||
}()
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
|
||||
}()
|
||||
|
||||
if !strings.Contains(scrape(t, m), `http_server_requests_total{code="500",method="GET",route="unmatched"} 1`) {
|
||||
t.Error("panic not counted as 500")
|
||||
}
|
||||
if spans := exp.GetSpans(); len(spans) != 1 || spans[0].Status.Code != codes.Error {
|
||||
t.Errorf("expected one failed span, got %+v", spans)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPMiddleware_SkipAndMethodNormalization(t *testing.T) {
|
||||
m := NewMetrics(MetricsConfig{})
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{
|
||||
Metrics: m,
|
||||
Skip: func(r *http.Request) bool { return r.URL.Path == "/skip" },
|
||||
})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
|
||||
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/skip", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("PURGE", "/x", nil))
|
||||
|
||||
body := scrape(t, m)
|
||||
if strings.Contains(body, `method="GET"`) {
|
||||
t.Error("skipped request was instrumented")
|
||||
}
|
||||
if !strings.Contains(body, `method="OTHER"`) {
|
||||
t.Error("non-standard method not normalized to OTHER")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseWriter_Flush(t *testing.T) {
|
||||
h := NewHTTPMiddleware(HTTPServerConfig{})(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
f, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
t.Fatal("wrapped writer does not implement http.Flusher")
|
||||
}
|
||||
_, _ = w.Write([]byte("chunk"))
|
||||
f.Flush()
|
||||
}))
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, httptest.NewRequest("GET", "/", nil))
|
||||
if !w.Flushed {
|
||||
t.Error("Flush not propagated to the underlying writer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPatternRoute(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"GET /users/{id}": "/users/{id}",
|
||||
"/static/": "/static/",
|
||||
"example.com/": "example.com/",
|
||||
"POST /x": "/x",
|
||||
"": routeUnmatched,
|
||||
"DELETE example.com/": "example.com/",
|
||||
}
|
||||
for pattern, want := range tests {
|
||||
r := &http.Request{Pattern: pattern}
|
||||
if got := patternRoute(r, nil); got != want {
|
||||
t.Errorf("patternRoute(%q) = %q, want %q", pattern, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user