rpcx_client.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2020 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. /**
  4. * @Author: mac
  5. * @Description: rpcx opentracing clientInterceptor
  6. * @Date: 2020/3/25 10:20
  7. */
  8. package trace
  9. import (
  10. "context"
  11. "github.com/opentracing/opentracing-go/log"
  12. "github.com/opentracing/opentracing-go"
  13. "github.com/opentracing/opentracing-go/ext"
  14. "github.com/smallnest/rpcx/share"
  15. )
  16. type RpcxOpenTracingClientPlugin struct{}
  17. func (p *RpcxOpenTracingClientPlugin) DoPreCall(ctx context.Context, servicePath, serviceMethod string, args interface{}) error {
  18. var span1 opentracing.Span
  19. // if it is called in rpc service in case that a service calls antoher service,
  20. // we uses the span in the service context as the parent span.
  21. parentSpan := ctx.Value(share.OpentracingSpanServerKey)
  22. if parentSpan != nil {
  23. span1 = opentracing.StartSpan(
  24. "rpcx.client."+servicePath+"."+serviceMethod,
  25. opentracing.ChildOf(parentSpan.(opentracing.Span).Context()))
  26. } else {
  27. wireContext, err := share.GetSpanContextFromContext(ctx)
  28. if err == nil && wireContext != nil { //try to parse span from request
  29. span1 = opentracing.StartSpan(
  30. "rpcx.client."+servicePath+"."+serviceMethod,
  31. ext.RPCServerOption(wireContext))
  32. } else { // parse span from context or create root context
  33. span1, _ = opentracing.StartSpanFromContext(ctx, "rpcx.client."+servicePath+"."+serviceMethod)
  34. }
  35. }
  36. if rpcxContext, ok := ctx.(*share.Context); ok {
  37. rpcxContext.SetValue(share.OpentracingSpanClientKey, span1)
  38. }
  39. return nil
  40. }
  41. func (p *RpcxOpenTracingClientPlugin) DoPostCall(ctx context.Context, servicePath, serviceMethod string, args interface{}, reply interface{}, err error) error {
  42. if rpcxContext, ok := ctx.(*share.Context); ok {
  43. span1 := rpcxContext.Value(share.OpentracingSpanClientKey)
  44. if span1 != nil {
  45. sp := span1.(opentracing.Span)
  46. if err != nil {
  47. sp.SetTag("error", true)
  48. sp.LogFields(
  49. log.Object("request", args),
  50. log.Object("reply", reply),
  51. log.Error(err))
  52. }
  53. sp.Finish()
  54. }
  55. }
  56. return nil
  57. }