2020-07-26 17:09:05 +08:00
|
|
|
package serverinterceptors
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
2020-08-08 16:40:10 +08:00
|
|
|
"github.com/tal-tech/go-zero/core/trace"
|
2020-07-26 17:09:05 +08:00
|
|
|
"google.golang.org/grpc"
|
|
|
|
"google.golang.org/grpc/metadata"
|
|
|
|
)
|
|
|
|
|
2021-09-07 22:33:02 +08:00
|
|
|
// UnaryTracingInterceptor returns a grpc.UnaryServerInterceptor
|
|
|
|
// that handles tracing with given service name.
|
2020-07-26 17:09:05 +08:00
|
|
|
func UnaryTracingInterceptor(serviceName string) grpc.UnaryServerInterceptor {
|
|
|
|
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,
|
|
|
|
handler grpc.UnaryHandler) (resp interface{}, err error) {
|
|
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
carrier, err := trace.Extract(trace.GrpcFormat, md)
|
|
|
|
if err != nil {
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, span := trace.StartServerSpan(ctx, carrier, serviceName, info.FullMethod)
|
|
|
|
defer span.Finish()
|
|
|
|
return handler(ctx, req)
|
|
|
|
}
|
|
|
|
}
|
2021-09-07 17:58:22 +08:00
|
|
|
|
2021-09-07 22:33:02 +08:00
|
|
|
// StreamTracingInterceptor returns a grpc.StreamServerInterceptor
|
|
|
|
// that handles tracing with given service name.
|
2021-09-07 17:58:22 +08:00
|
|
|
func StreamTracingInterceptor(serviceName string) grpc.StreamServerInterceptor {
|
|
|
|
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo,
|
|
|
|
handler grpc.StreamHandler) error {
|
|
|
|
ctx := ss.Context()
|
|
|
|
md, ok := metadata.FromIncomingContext(ctx)
|
|
|
|
if !ok {
|
|
|
|
return handler(srv, ss)
|
|
|
|
}
|
|
|
|
|
|
|
|
carrier, err := trace.Extract(trace.GrpcFormat, md)
|
|
|
|
if err != nil {
|
|
|
|
return handler(srv, ss)
|
|
|
|
}
|
|
|
|
|
2021-09-29 13:09:20 +08:00
|
|
|
_, span := trace.StartServerSpan(ctx, carrier, serviceName, info.FullMethod)
|
2021-09-07 17:58:22 +08:00
|
|
|
defer span.Finish()
|
|
|
|
return handler(srv, ss)
|
|
|
|
}
|
|
|
|
}
|