trace_context.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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. "regexp"
  20. "go.opentelemetry.io/otel/trace"
  21. )
  22. const (
  23. supportedVersion = 0
  24. maxVersion = 254
  25. traceparentHeader = "traceparent"
  26. tracestateHeader = "tracestate"
  27. )
  28. // TraceContext is a propagator that supports the W3C Trace Context format
  29. // (https://www.w3.org/TR/trace-context/)
  30. //
  31. // This propagator will propagate the traceparent and tracestate headers to
  32. // guarantee traces are not broken. It is up to the users of this propagator
  33. // to choose if they want to participate in a trace by modifying the
  34. // traceparent header and relevant parts of the tracestate header containing
  35. // their proprietary information.
  36. type TraceContext struct{}
  37. var _ TextMapPropagator = TraceContext{}
  38. var traceCtxRegExp = regexp.MustCompile("^(?P<version>[0-9a-f]{2})-(?P<traceID>[a-f0-9]{32})-(?P<spanID>[a-f0-9]{16})-(?P<traceFlags>[a-f0-9]{2})(?:-.*)?$")
  39. // Inject set tracecontext from the Context into the carrier.
  40. func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) {
  41. sc := trace.SpanContextFromContext(ctx)
  42. if !sc.IsValid() {
  43. return
  44. }
  45. if ts := sc.TraceState().String(); ts != "" {
  46. carrier.Set(tracestateHeader, ts)
  47. }
  48. // Clear all flags other than the trace-context supported sampling bit.
  49. flags := sc.TraceFlags() & trace.FlagsSampled
  50. h := fmt.Sprintf("%.2x-%s-%s-%s",
  51. supportedVersion,
  52. sc.TraceID(),
  53. sc.SpanID(),
  54. flags)
  55. carrier.Set(traceparentHeader, h)
  56. }
  57. // Extract reads tracecontext from the carrier into a returned Context.
  58. //
  59. // The returned Context will be a copy of ctx and contain the extracted
  60. // tracecontext as the remote SpanContext. If the extracted tracecontext is
  61. // invalid, the passed ctx will be returned directly instead.
  62. func (tc TraceContext) Extract(ctx context.Context, carrier TextMapCarrier) context.Context {
  63. sc := tc.extract(carrier)
  64. if !sc.IsValid() {
  65. return ctx
  66. }
  67. return trace.ContextWithRemoteSpanContext(ctx, sc)
  68. }
  69. func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
  70. h := carrier.Get(traceparentHeader)
  71. if h == "" {
  72. return trace.SpanContext{}
  73. }
  74. matches := traceCtxRegExp.FindStringSubmatch(h)
  75. if len(matches) == 0 {
  76. return trace.SpanContext{}
  77. }
  78. if len(matches) < 5 { // four subgroups plus the overall match
  79. return trace.SpanContext{}
  80. }
  81. if len(matches[1]) != 2 {
  82. return trace.SpanContext{}
  83. }
  84. ver, err := hex.DecodeString(matches[1])
  85. if err != nil {
  86. return trace.SpanContext{}
  87. }
  88. version := int(ver[0])
  89. if version > maxVersion {
  90. return trace.SpanContext{}
  91. }
  92. if version == 0 && len(matches) != 5 { // four subgroups plus the overall match
  93. return trace.SpanContext{}
  94. }
  95. if len(matches[2]) != 32 {
  96. return trace.SpanContext{}
  97. }
  98. var scc trace.SpanContextConfig
  99. scc.TraceID, err = trace.TraceIDFromHex(matches[2][:32])
  100. if err != nil {
  101. return trace.SpanContext{}
  102. }
  103. if len(matches[3]) != 16 {
  104. return trace.SpanContext{}
  105. }
  106. scc.SpanID, err = trace.SpanIDFromHex(matches[3])
  107. if err != nil {
  108. return trace.SpanContext{}
  109. }
  110. if len(matches[4]) != 2 {
  111. return trace.SpanContext{}
  112. }
  113. opts, err := hex.DecodeString(matches[4])
  114. if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) {
  115. return trace.SpanContext{}
  116. }
  117. // Clear all flags other than the trace-context supported sampling bit.
  118. scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled
  119. // Ignore the error returned here. Failure to parse tracestate MUST NOT
  120. // affect the parsing of traceparent according to the W3C tracecontext
  121. // specification.
  122. scc.TraceState, _ = trace.ParseTraceState(carrier.Get(tracestateHeader))
  123. scc.Remote = true
  124. sc := trace.NewSpanContext(scc)
  125. if !sc.IsValid() {
  126. return trace.SpanContext{}
  127. }
  128. return sc
  129. }
  130. // Fields returns the keys who's values are set with Inject.
  131. func (tc TraceContext) Fields() []string {
  132. return []string{traceparentHeader, tracestateHeader}
  133. }