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 }