grpc_server.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2020 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. /**
  4. * @Author: mac
  5. * @Description: grpc opentracing serverInterceptor
  6. * @Date: 2020/3/25 10:08
  7. */
  8. package trace
  9. import (
  10. "context"
  11. "github.com/opentracing/opentracing-go"
  12. "github.com/opentracing/opentracing-go/ext"
  13. "github.com/uber/jaeger-client-go"
  14. "google.golang.org/grpc"
  15. "google.golang.org/grpc/grpclog"
  16. "google.golang.org/grpc/metadata"
  17. )
  18. // grpc服务端启动选项
  19. func ServerOption() grpc.ServerOption {
  20. return grpc.UnaryInterceptor(serverInterceptor(opentracing.GlobalTracer()))
  21. }
  22. // grpc服务端拦截器
  23. func serverInterceptor(tracer opentracing.Tracer) grpc.UnaryServerInterceptor {
  24. return func(ctx context.Context,
  25. req interface{},
  26. info *grpc.UnaryServerInfo,
  27. handler grpc.UnaryHandler) (resp interface{}, err error) {
  28. var parentContext context.Context
  29. md, ok := metadata.FromIncomingContext(ctx)
  30. if !ok {
  31. md = metadata.New(nil)
  32. }
  33. spanContext, err := tracer.Extract(opentracing.TextMap, MDReaderWriter{md})
  34. if err != nil && err != opentracing.ErrSpanContextNotFound {
  35. grpclog.Errorf("extract from metadata err: %v", err)
  36. } else {
  37. span := tracer.StartSpan(
  38. "GRPC server "+info.FullMethod,
  39. ext.RPCServerOption(spanContext),
  40. opentracing.Tag{Key: string(ext.Component), Value: "GRPC"},
  41. ext.SpanKindRPCServer,
  42. )
  43. defer span.Finish()
  44. parentContext = opentracing.ContextWithSpan(ctx, span)
  45. // 设置 request ID,可用于日志记录, 使用ctx.Value("RequestId")可以取出
  46. if sc, ok := span.Context().(jaeger.SpanContext); ok {
  47. traceId := sc.TraceID().String()
  48. parentContext = context.WithValue(parentContext, "RequestId", traceId)
  49. }
  50. }
  51. return handler(parentContext, req)
  52. }
  53. }