context.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // Copyright (c) 2017 Uber Technologies, Inc.
  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 jaeger
  15. import (
  16. "errors"
  17. "fmt"
  18. "strconv"
  19. "strings"
  20. )
  21. const (
  22. flagSampled = byte(1)
  23. flagDebug = byte(2)
  24. )
  25. var (
  26. errEmptyTracerStateString = errors.New("Cannot convert empty string to tracer state")
  27. errMalformedTracerStateString = errors.New("String does not match tracer state format")
  28. emptyContext = SpanContext{}
  29. )
  30. // TraceID represents unique 128bit identifier of a trace
  31. type TraceID struct {
  32. High, Low uint64
  33. }
  34. // SpanID represents unique 64bit identifier of a span
  35. type SpanID uint64
  36. // SpanContext represents propagated span identity and state
  37. type SpanContext struct {
  38. // traceID represents globally unique ID of the trace.
  39. // Usually generated as a random number.
  40. traceID TraceID
  41. // spanID represents span ID that must be unique within its trace,
  42. // but does not have to be globally unique.
  43. spanID SpanID
  44. // parentID refers to the ID of the parent span.
  45. // Should be 0 if the current span is a root span.
  46. parentID SpanID
  47. // flags is a bitmap containing such bits as 'sampled' and 'debug'.
  48. flags byte
  49. // Distributed Context baggage. The is a snapshot in time.
  50. baggage map[string]string
  51. // debugID can be set to some correlation ID when the context is being
  52. // extracted from a TextMap carrier.
  53. //
  54. // See JaegerDebugHeader in constants.go
  55. debugID string
  56. }
  57. // ForeachBaggageItem implements ForeachBaggageItem() of opentracing.SpanContext
  58. func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
  59. for k, v := range c.baggage {
  60. if !handler(k, v) {
  61. break
  62. }
  63. }
  64. }
  65. // IsSampled returns whether this trace was chosen for permanent storage
  66. // by the sampling mechanism of the tracer.
  67. func (c SpanContext) IsSampled() bool {
  68. return (c.flags & flagSampled) == flagSampled
  69. }
  70. // IsDebug indicates whether sampling was explicitly requested by the service.
  71. func (c SpanContext) IsDebug() bool {
  72. return (c.flags & flagDebug) == flagDebug
  73. }
  74. // IsValid indicates whether this context actually represents a valid trace.
  75. func (c SpanContext) IsValid() bool {
  76. return c.traceID.IsValid() && c.spanID != 0
  77. }
  78. func (c SpanContext) String() string {
  79. if c.traceID.High == 0 {
  80. return fmt.Sprintf("%x:%x:%x:%x", c.traceID.Low, uint64(c.spanID), uint64(c.parentID), c.flags)
  81. }
  82. return fmt.Sprintf("%x%016x:%x:%x:%x", c.traceID.High, c.traceID.Low, uint64(c.spanID), uint64(c.parentID), c.flags)
  83. }
  84. // ContextFromString reconstructs the Context encoded in a string
  85. func ContextFromString(value string) (SpanContext, error) {
  86. var context SpanContext
  87. if value == "" {
  88. return emptyContext, errEmptyTracerStateString
  89. }
  90. parts := strings.Split(value, ":")
  91. if len(parts) != 4 {
  92. return emptyContext, errMalformedTracerStateString
  93. }
  94. var err error
  95. if context.traceID, err = TraceIDFromString(parts[0]); err != nil {
  96. return emptyContext, err
  97. }
  98. if context.spanID, err = SpanIDFromString(parts[1]); err != nil {
  99. return emptyContext, err
  100. }
  101. if context.parentID, err = SpanIDFromString(parts[2]); err != nil {
  102. return emptyContext, err
  103. }
  104. flags, err := strconv.ParseUint(parts[3], 10, 8)
  105. if err != nil {
  106. return emptyContext, err
  107. }
  108. context.flags = byte(flags)
  109. return context, nil
  110. }
  111. // TraceID returns the trace ID of this span context
  112. func (c SpanContext) TraceID() TraceID {
  113. return c.traceID
  114. }
  115. // SpanID returns the span ID of this span context
  116. func (c SpanContext) SpanID() SpanID {
  117. return c.spanID
  118. }
  119. // ParentID returns the parent span ID of this span context
  120. func (c SpanContext) ParentID() SpanID {
  121. return c.parentID
  122. }
  123. // NewSpanContext creates a new instance of SpanContext
  124. func NewSpanContext(traceID TraceID, spanID, parentID SpanID, sampled bool, baggage map[string]string) SpanContext {
  125. flags := byte(0)
  126. if sampled {
  127. flags = flagSampled
  128. }
  129. return SpanContext{
  130. traceID: traceID,
  131. spanID: spanID,
  132. parentID: parentID,
  133. flags: flags,
  134. baggage: baggage}
  135. }
  136. // CopyFrom copies data from ctx into this context, including span identity and baggage.
  137. // TODO This is only used by interop.go. Remove once TChannel Go supports OpenTracing.
  138. func (c *SpanContext) CopyFrom(ctx *SpanContext) {
  139. c.traceID = ctx.traceID
  140. c.spanID = ctx.spanID
  141. c.parentID = ctx.parentID
  142. c.flags = ctx.flags
  143. if l := len(ctx.baggage); l > 0 {
  144. c.baggage = make(map[string]string, l)
  145. for k, v := range ctx.baggage {
  146. c.baggage[k] = v
  147. }
  148. } else {
  149. c.baggage = nil
  150. }
  151. }
  152. // WithBaggageItem creates a new context with an extra baggage item.
  153. func (c SpanContext) WithBaggageItem(key, value string) SpanContext {
  154. var newBaggage map[string]string
  155. if c.baggage == nil {
  156. newBaggage = map[string]string{key: value}
  157. } else {
  158. newBaggage = make(map[string]string, len(c.baggage)+1)
  159. for k, v := range c.baggage {
  160. newBaggage[k] = v
  161. }
  162. newBaggage[key] = value
  163. }
  164. // Use positional parameters so the compiler will help catch new fields.
  165. return SpanContext{c.traceID, c.spanID, c.parentID, c.flags, newBaggage, ""}
  166. }
  167. // isDebugIDContainerOnly returns true when the instance of the context is only
  168. // used to return the debug/correlation ID from extract() method. This happens
  169. // in the situation when "jaeger-debug-id" header is passed in the carrier to
  170. // the extract() method, but the request otherwise has no span context in it.
  171. // Previously this would've returned opentracing.ErrSpanContextNotFound from the
  172. // extract method, but now it returns a dummy context with only debugID filled in.
  173. //
  174. // See JaegerDebugHeader in constants.go
  175. // See textMapPropagator#Extract
  176. func (c *SpanContext) isDebugIDContainerOnly() bool {
  177. return !c.traceID.IsValid() && c.debugID != ""
  178. }
  179. // ------- TraceID -------
  180. func (t TraceID) String() string {
  181. if t.High == 0 {
  182. return fmt.Sprintf("%x", t.Low)
  183. }
  184. return fmt.Sprintf("%x%016x", t.High, t.Low)
  185. }
  186. // TraceIDFromString creates a TraceID from a hexadecimal string
  187. func TraceIDFromString(s string) (TraceID, error) {
  188. var hi, lo uint64
  189. var err error
  190. if len(s) > 32 {
  191. return TraceID{}, fmt.Errorf("TraceID cannot be longer than 32 hex characters: %s", s)
  192. } else if len(s) > 16 {
  193. hiLen := len(s) - 16
  194. if hi, err = strconv.ParseUint(s[0:hiLen], 16, 64); err != nil {
  195. return TraceID{}, err
  196. }
  197. if lo, err = strconv.ParseUint(s[hiLen:], 16, 64); err != nil {
  198. return TraceID{}, err
  199. }
  200. } else {
  201. if lo, err = strconv.ParseUint(s, 16, 64); err != nil {
  202. return TraceID{}, err
  203. }
  204. }
  205. return TraceID{High: hi, Low: lo}, nil
  206. }
  207. // IsValid checks if the trace ID is valid, i.e. not zero.
  208. func (t TraceID) IsValid() bool {
  209. return t.High != 0 || t.Low != 0
  210. }
  211. // ------- SpanID -------
  212. func (s SpanID) String() string {
  213. return fmt.Sprintf("%x", uint64(s))
  214. }
  215. // SpanIDFromString creates a SpanID from a hexadecimal string
  216. func SpanIDFromString(s string) (SpanID, error) {
  217. if len(s) > 16 {
  218. return SpanID(0), fmt.Errorf("SpanID cannot be longer than 16 hex characters: %s", s)
  219. }
  220. id, err := strconv.ParseUint(s, 16, 64)
  221. if err != nil {
  222. return SpanID(0), err
  223. }
  224. return SpanID(id), nil
  225. }