trace_context.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package propagation // import "go.opentelemetry.io/otel/propagation"
  4. import (
  5. "context"
  6. "encoding/hex"
  7. "fmt"
  8. "strings"
  9. "go.opentelemetry.io/otel/trace"
  10. )
  11. const (
  12. supportedVersion = 0
  13. maxVersion = 254
  14. traceparentHeader = "traceparent"
  15. tracestateHeader = "tracestate"
  16. delimiter = "-"
  17. )
  18. // TraceContext is a propagator that supports the W3C Trace Context format
  19. // (https://www.w3.org/TR/trace-context/)
  20. //
  21. // This propagator will propagate the traceparent and tracestate headers to
  22. // guarantee traces are not broken. It is up to the users of this propagator
  23. // to choose if they want to participate in a trace by modifying the
  24. // traceparent header and relevant parts of the tracestate header containing
  25. // their proprietary information.
  26. type TraceContext struct{}
  27. var (
  28. _ TextMapPropagator = TraceContext{}
  29. versionPart = fmt.Sprintf("%.2X", supportedVersion)
  30. )
  31. // Inject injects the trace context from ctx into carrier.
  32. func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) {
  33. sc := trace.SpanContextFromContext(ctx)
  34. if !sc.IsValid() {
  35. return
  36. }
  37. if ts := sc.TraceState().String(); ts != "" {
  38. carrier.Set(tracestateHeader, ts)
  39. }
  40. // Clear all flags other than the trace-context supported sampling bit.
  41. flags := sc.TraceFlags() & trace.FlagsSampled
  42. var sb strings.Builder
  43. sb.Grow(2 + 32 + 16 + 2 + 3)
  44. _, _ = sb.WriteString(versionPart)
  45. traceID := sc.TraceID()
  46. spanID := sc.SpanID()
  47. flagByte := [1]byte{byte(flags)}
  48. var buf [32]byte
  49. for _, src := range [][]byte{traceID[:], spanID[:], flagByte[:]} {
  50. _ = sb.WriteByte(delimiter[0])
  51. n := hex.Encode(buf[:], src)
  52. _, _ = sb.Write(buf[:n])
  53. }
  54. carrier.Set(traceparentHeader, sb.String())
  55. }
  56. // Extract reads tracecontext from the carrier into a returned Context.
  57. //
  58. // The returned Context will be a copy of ctx and contain the extracted
  59. // tracecontext as the remote SpanContext. If the extracted tracecontext is
  60. // invalid, the passed ctx will be returned directly instead.
  61. func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context {
  62. sc := tc.extract(carrier)
  63. if !sc.IsValid() {
  64. return ctx
  65. }
  66. return trace.ContextWithRemoteSpanContext(ctx, sc)
  67. }
  68. func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
  69. h := carrier.Get(traceparentHeader)
  70. if h == "" {
  71. return trace.SpanContext{}
  72. }
  73. var ver [1]byte
  74. if !extractPart(ver[:], &h, 2) {
  75. return trace.SpanContext{}
  76. }
  77. version := int(ver[0])
  78. if version > maxVersion {
  79. return trace.SpanContext{}
  80. }
  81. var scc trace.SpanContextConfig
  82. if !extractPart(scc.TraceID[:], &h, 32) {
  83. return trace.SpanContext{}
  84. }
  85. if !extractPart(scc.SpanID[:], &h, 16) {
  86. return trace.SpanContext{}
  87. }
  88. var opts [1]byte
  89. if !extractPart(opts[:], &h, 2) {
  90. return trace.SpanContext{}
  91. }
  92. if version == 0 && (h != "" || opts[0] > 2) {
  93. // version 0 not allow extra
  94. // version 0 not allow other flag
  95. return trace.SpanContext{}
  96. }
  97. // Clear all flags other than the trace-context supported sampling bit.
  98. scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled
  99. // Ignore the error returned here. Failure to parse tracestate MUST NOT
  100. // affect the parsing of traceparent according to the W3C tracecontext
  101. // specification.
  102. scc.TraceState, _ = trace.ParseTraceState(carrier.Get(tracestateHeader))
  103. scc.Remote = true
  104. sc := trace.NewSpanContext(scc)
  105. if !sc.IsValid() {
  106. return trace.SpanContext{}
  107. }
  108. return sc
  109. }
  110. // upperHex detect hex is upper case Unicode characters.
  111. func upperHex(v string) bool {
  112. for _, c := range v {
  113. if c >= 'A' && c <= 'F' {
  114. return true
  115. }
  116. }
  117. return false
  118. }
  119. func extractPart(dst []byte, h *string, n int) bool {
  120. part, left, _ := strings.Cut(*h, delimiter)
  121. *h = left
  122. // hex.Decode decodes unsupported upper-case characters, so exclude explicitly.
  123. if len(part) != n || upperHex(part) {
  124. return false
  125. }
  126. if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 {
  127. return false
  128. }
  129. return true
  130. }
  131. // Fields returns the keys who's values are set with Inject.
  132. func (tc TraceContext) Fields() []string {
  133. return []string{traceparentHeader, tracestateHeader}
  134. }