hook.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. package redis
  2. import (
  3. "context"
  4. "io"
  5. "net"
  6. "strings"
  7. "time"
  8. red "github.com/go-redis/redis/v8"
  9. "github.com/zeromicro/go-zero/core/breaker"
  10. "github.com/zeromicro/go-zero/core/errorx"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. "github.com/zeromicro/go-zero/core/mapping"
  13. "github.com/zeromicro/go-zero/core/timex"
  14. "github.com/zeromicro/go-zero/core/trace"
  15. "go.opentelemetry.io/otel/attribute"
  16. "go.opentelemetry.io/otel/codes"
  17. oteltrace "go.opentelemetry.io/otel/trace"
  18. )
  19. // spanName is the span name of the redis calls.
  20. const spanName = "redis"
  21. var (
  22. startTimeKey = contextKey("startTime")
  23. durationHook = hook{}
  24. redisCmdsAttributeKey = attribute.Key("redis.cmds")
  25. )
  26. type (
  27. contextKey string
  28. hook struct{}
  29. )
  30. func (h hook) BeforeProcess(ctx context.Context, cmd red.Cmder) (context.Context, error) {
  31. return h.startSpan(context.WithValue(ctx, startTimeKey, timex.Now()), cmd), nil
  32. }
  33. func (h hook) AfterProcess(ctx context.Context, cmd red.Cmder) error {
  34. err := cmd.Err()
  35. h.endSpan(ctx, err)
  36. val := ctx.Value(startTimeKey)
  37. if val == nil {
  38. return nil
  39. }
  40. start, ok := val.(time.Duration)
  41. if !ok {
  42. return nil
  43. }
  44. duration := timex.Since(start)
  45. if duration > slowThreshold.Load() {
  46. logDuration(ctx, []red.Cmder{cmd}, duration)
  47. }
  48. metricReqDur.Observe(duration.Milliseconds(), cmd.Name())
  49. if msg := formatError(err); len(msg) > 0 {
  50. metricReqErr.Inc(cmd.Name(), msg)
  51. }
  52. return nil
  53. }
  54. func (h hook) BeforeProcessPipeline(ctx context.Context, cmds []red.Cmder) (context.Context, error) {
  55. if len(cmds) == 0 {
  56. return ctx, nil
  57. }
  58. return h.startSpan(context.WithValue(ctx, startTimeKey, timex.Now()), cmds...), nil
  59. }
  60. func (h hook) AfterProcessPipeline(ctx context.Context, cmds []red.Cmder) error {
  61. if len(cmds) == 0 {
  62. return nil
  63. }
  64. batchError := errorx.BatchError{}
  65. for _, cmd := range cmds {
  66. err := cmd.Err()
  67. if err == nil {
  68. continue
  69. }
  70. batchError.Add(err)
  71. }
  72. h.endSpan(ctx, batchError.Err())
  73. val := ctx.Value(startTimeKey)
  74. if val == nil {
  75. return nil
  76. }
  77. start, ok := val.(time.Duration)
  78. if !ok {
  79. return nil
  80. }
  81. duration := timex.Since(start)
  82. if duration > slowThreshold.Load()*time.Duration(len(cmds)) {
  83. logDuration(ctx, cmds, duration)
  84. }
  85. metricReqDur.Observe(duration.Milliseconds(), "Pipeline")
  86. if msg := formatError(batchError.Err()); len(msg) > 0 {
  87. metricReqErr.Inc("Pipeline", msg)
  88. }
  89. return nil
  90. }
  91. func formatError(err error) string {
  92. if err == nil || err == red.Nil {
  93. return ""
  94. }
  95. opErr, ok := err.(*net.OpError)
  96. if ok && opErr.Timeout() {
  97. return "timeout"
  98. }
  99. switch err {
  100. case io.EOF:
  101. return "eof"
  102. case context.DeadlineExceeded:
  103. return "context deadline"
  104. case breaker.ErrServiceUnavailable:
  105. return "breaker"
  106. default:
  107. return "unexpected error"
  108. }
  109. }
  110. func logDuration(ctx context.Context, cmds []red.Cmder, duration time.Duration) {
  111. var buf strings.Builder
  112. for k, cmd := range cmds {
  113. if k > 0 {
  114. buf.WriteByte('\n')
  115. }
  116. var build strings.Builder
  117. for i, arg := range cmd.Args() {
  118. if i > 0 {
  119. build.WriteByte(' ')
  120. }
  121. build.WriteString(mapping.Repr(arg))
  122. }
  123. buf.WriteString(build.String())
  124. }
  125. logx.WithContext(ctx).WithDuration(duration).Slowf("[REDIS] slowcall on executing: %s", buf.String())
  126. }
  127. func (h hook) startSpan(ctx context.Context, cmds ...red.Cmder) context.Context {
  128. tracer := trace.TracerFromContext(ctx)
  129. ctx, span := tracer.Start(ctx,
  130. spanName,
  131. oteltrace.WithSpanKind(oteltrace.SpanKindClient),
  132. )
  133. cmdStrs := make([]string, 0, len(cmds))
  134. for _, cmd := range cmds {
  135. cmdStrs = append(cmdStrs, cmd.Name())
  136. }
  137. span.SetAttributes(redisCmdsAttributeKey.StringSlice(cmdStrs))
  138. return ctx
  139. }
  140. func (h hook) endSpan(ctx context.Context, err error) {
  141. span := oteltrace.SpanFromContext(ctx)
  142. defer span.End()
  143. if err == nil || err == red.Nil {
  144. span.SetStatus(codes.Ok, "")
  145. return
  146. }
  147. span.SetStatus(codes.Error, err.Error())
  148. span.RecordError(err)
  149. }