trace_context.go 4.7 KB

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