span.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package telemetry // import "go.opentelemetry.io/otel/trace/internal/telemetry"
  4. import (
  5. "bytes"
  6. "encoding/hex"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "math"
  12. "time"
  13. )
  14. // A Span represents a single operation performed by a single component of the
  15. // system.
  16. type Span struct {
  17. // A unique identifier for a trace. All spans from the same trace share
  18. // the same `trace_id`. The ID is a 16-byte array. An ID with all zeroes OR
  19. // of length other than 16 bytes is considered invalid (empty string in OTLP/JSON
  20. // is zero-length and thus is also invalid).
  21. //
  22. // This field is required.
  23. TraceID TraceID `json:"traceId,omitempty"`
  24. // A unique identifier for a span within a trace, assigned when the span
  25. // is created. The ID is an 8-byte array. An ID with all zeroes OR of length
  26. // other than 8 bytes is considered invalid (empty string in OTLP/JSON
  27. // is zero-length and thus is also invalid).
  28. //
  29. // This field is required.
  30. SpanID SpanID `json:"spanId,omitempty"`
  31. // trace_state conveys information about request position in multiple distributed tracing graphs.
  32. // It is a trace_state in w3c-trace-context format: https://www.w3.org/TR/trace-context/#tracestate-header
  33. // See also https://github.com/w3c/distributed-tracing for more details about this field.
  34. TraceState string `json:"traceState,omitempty"`
  35. // The `span_id` of this span's parent span. If this is a root span, then this
  36. // field must be empty. The ID is an 8-byte array.
  37. ParentSpanID SpanID `json:"parentSpanId,omitempty"`
  38. // Flags, a bit field.
  39. //
  40. // Bits 0-7 (8 least significant bits) are the trace flags as defined in W3C Trace
  41. // Context specification. To read the 8-bit W3C trace flag, use
  42. // `flags & SPAN_FLAGS_TRACE_FLAGS_MASK`.
  43. //
  44. // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
  45. //
  46. // Bits 8 and 9 represent the 3 states of whether a span's parent
  47. // is remote. The states are (unknown, is not remote, is remote).
  48. // To read whether the value is known, use `(flags & SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK) != 0`.
  49. // To read whether the span is remote, use `(flags & SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK) != 0`.
  50. //
  51. // When creating span messages, if the message is logically forwarded from another source
  52. // with an equivalent flags fields (i.e., usually another OTLP span message), the field SHOULD
  53. // be copied as-is. If creating from a source that does not have an equivalent flags field
  54. // (such as a runtime representation of an OpenTelemetry span), the high 22 bits MUST
  55. // be set to zero.
  56. // Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero.
  57. //
  58. // [Optional].
  59. Flags uint32 `json:"flags,omitempty"`
  60. // A description of the span's operation.
  61. //
  62. // For example, the name can be a qualified method name or a file name
  63. // and a line number where the operation is called. A best practice is to use
  64. // the same display name at the same call point in an application.
  65. // This makes it easier to correlate spans in different traces.
  66. //
  67. // This field is semantically required to be set to non-empty string.
  68. // Empty value is equivalent to an unknown span name.
  69. //
  70. // This field is required.
  71. Name string `json:"name"`
  72. // Distinguishes between spans generated in a particular context. For example,
  73. // two spans with the same name may be distinguished using `CLIENT` (caller)
  74. // and `SERVER` (callee) to identify queueing latency associated with the span.
  75. Kind SpanKind `json:"kind,omitempty"`
  76. // start_time_unix_nano is the start time of the span. On the client side, this is the time
  77. // kept by the local machine where the span execution starts. On the server side, this
  78. // is the time when the server's application handler starts running.
  79. // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970.
  80. //
  81. // This field is semantically required and it is expected that end_time >= start_time.
  82. StartTime time.Time `json:"startTimeUnixNano,omitempty"`
  83. // end_time_unix_nano is the end time of the span. On the client side, this is the time
  84. // kept by the local machine where the span execution ends. On the server side, this
  85. // is the time when the server application handler stops running.
  86. // Value is UNIX Epoch time in nanoseconds since 00:00:00 UTC on 1 January 1970.
  87. //
  88. // This field is semantically required and it is expected that end_time >= start_time.
  89. EndTime time.Time `json:"endTimeUnixNano,omitempty"`
  90. // attributes is a collection of key/value pairs. Note, global attributes
  91. // like server name can be set using the resource API. Examples of attributes:
  92. //
  93. // "/http/user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
  94. // "/http/server_latency": 300
  95. // "example.com/myattribute": true
  96. // "example.com/score": 10.239
  97. //
  98. // The OpenTelemetry API specification further restricts the allowed value types:
  99. // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/README.md#attribute
  100. // Attribute keys MUST be unique (it is not allowed to have more than one
  101. // attribute with the same key).
  102. Attrs []Attr `json:"attributes,omitempty"`
  103. // dropped_attributes_count is the number of attributes that were discarded. Attributes
  104. // can be discarded because their keys are too long or because there are too many
  105. // attributes. If this value is 0, then no attributes were dropped.
  106. DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
  107. // events is a collection of Event items.
  108. Events []*SpanEvent `json:"events,omitempty"`
  109. // dropped_events_count is the number of dropped events. If the value is 0, then no
  110. // events were dropped.
  111. DroppedEvents uint32 `json:"droppedEventsCount,omitempty"`
  112. // links is a collection of Links, which are references from this span to a span
  113. // in the same or different trace.
  114. Links []*SpanLink `json:"links,omitempty"`
  115. // dropped_links_count is the number of dropped links after the maximum size was
  116. // enforced. If this value is 0, then no links were dropped.
  117. DroppedLinks uint32 `json:"droppedLinksCount,omitempty"`
  118. // An optional final status for this span. Semantically when Status isn't set, it means
  119. // span's status code is unset, i.e. assume STATUS_CODE_UNSET (code = 0).
  120. Status *Status `json:"status,omitempty"`
  121. }
  122. // MarshalJSON encodes s into OTLP formatted JSON.
  123. func (s Span) MarshalJSON() ([]byte, error) {
  124. startT := s.StartTime.UnixNano()
  125. if s.StartTime.IsZero() || startT < 0 {
  126. startT = 0
  127. }
  128. endT := s.EndTime.UnixNano()
  129. if s.EndTime.IsZero() || endT < 0 {
  130. endT = 0
  131. }
  132. // Override non-empty default SpanID marshal and omitempty.
  133. var parentSpanId string
  134. if !s.ParentSpanID.IsEmpty() {
  135. b := make([]byte, hex.EncodedLen(spanIDSize))
  136. hex.Encode(b, s.ParentSpanID[:])
  137. parentSpanId = string(b)
  138. }
  139. type Alias Span
  140. return json.Marshal(struct {
  141. Alias
  142. ParentSpanID string `json:"parentSpanId,omitempty"`
  143. StartTime uint64 `json:"startTimeUnixNano,omitempty"`
  144. EndTime uint64 `json:"endTimeUnixNano,omitempty"`
  145. }{
  146. Alias: Alias(s),
  147. ParentSpanID: parentSpanId,
  148. StartTime: uint64(startT), // nolint:gosec // >0 checked above.
  149. EndTime: uint64(endT), // nolint:gosec // >0 checked above.
  150. })
  151. }
  152. // UnmarshalJSON decodes the OTLP formatted JSON contained in data into s.
  153. func (s *Span) UnmarshalJSON(data []byte) error {
  154. decoder := json.NewDecoder(bytes.NewReader(data))
  155. t, err := decoder.Token()
  156. if err != nil {
  157. return err
  158. }
  159. if t != json.Delim('{') {
  160. return errors.New("invalid Span type")
  161. }
  162. for decoder.More() {
  163. keyIface, err := decoder.Token()
  164. if err != nil {
  165. if errors.Is(err, io.EOF) {
  166. // Empty.
  167. return nil
  168. }
  169. return err
  170. }
  171. key, ok := keyIface.(string)
  172. if !ok {
  173. return fmt.Errorf("invalid Span field: %#v", keyIface)
  174. }
  175. switch key {
  176. case "traceId", "trace_id":
  177. err = decoder.Decode(&s.TraceID)
  178. case "spanId", "span_id":
  179. err = decoder.Decode(&s.SpanID)
  180. case "traceState", "trace_state":
  181. err = decoder.Decode(&s.TraceState)
  182. case "parentSpanId", "parent_span_id":
  183. err = decoder.Decode(&s.ParentSpanID)
  184. case "flags":
  185. err = decoder.Decode(&s.Flags)
  186. case "name":
  187. err = decoder.Decode(&s.Name)
  188. case "kind":
  189. err = decoder.Decode(&s.Kind)
  190. case "startTimeUnixNano", "start_time_unix_nano":
  191. var val protoUint64
  192. err = decoder.Decode(&val)
  193. v := int64(min(val.Uint64(), math.MaxInt64)) // nolint: gosec // Overflow checked.
  194. s.StartTime = time.Unix(0, v)
  195. case "endTimeUnixNano", "end_time_unix_nano":
  196. var val protoUint64
  197. err = decoder.Decode(&val)
  198. v := int64(min(val.Uint64(), math.MaxInt64)) // nolint: gosec // Overflow checked.
  199. s.EndTime = time.Unix(0, v)
  200. case "attributes":
  201. err = decoder.Decode(&s.Attrs)
  202. case "droppedAttributesCount", "dropped_attributes_count":
  203. err = decoder.Decode(&s.DroppedAttrs)
  204. case "events":
  205. err = decoder.Decode(&s.Events)
  206. case "droppedEventsCount", "dropped_events_count":
  207. err = decoder.Decode(&s.DroppedEvents)
  208. case "links":
  209. err = decoder.Decode(&s.Links)
  210. case "droppedLinksCount", "dropped_links_count":
  211. err = decoder.Decode(&s.DroppedLinks)
  212. case "status":
  213. err = decoder.Decode(&s.Status)
  214. default:
  215. // Skip unknown.
  216. }
  217. if err != nil {
  218. return err
  219. }
  220. }
  221. return nil
  222. }
  223. // SpanFlags represents constants used to interpret the
  224. // Span.flags field, which is protobuf 'fixed32' type and is to
  225. // be used as bit-fields. Each non-zero value defined in this enum is
  226. // a bit-mask. To extract the bit-field, for example, use an
  227. // expression like:
  228. //
  229. // (span.flags & SPAN_FLAGS_TRACE_FLAGS_MASK)
  230. //
  231. // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
  232. //
  233. // Note that Span flags were introduced in version 1.1 of the
  234. // OpenTelemetry protocol. Older Span producers do not set this
  235. // field, consequently consumers should not rely on the absence of a
  236. // particular flag bit to indicate the presence of a particular feature.
  237. type SpanFlags int32
  238. const (
  239. // Bits 0-7 are used for trace flags.
  240. SpanFlagsTraceFlagsMask SpanFlags = 255
  241. // Bits 8 and 9 are used to indicate that the parent span or link span is remote.
  242. // Bit 8 (`HAS_IS_REMOTE`) indicates whether the value is known.
  243. // Bit 9 (`IS_REMOTE`) indicates whether the span or link is remote.
  244. SpanFlagsContextHasIsRemoteMask SpanFlags = 256
  245. // SpanFlagsContextHasIsRemoteMask indicates the Span is remote.
  246. SpanFlagsContextIsRemoteMask SpanFlags = 512
  247. )
  248. // SpanKind is the type of span. Can be used to specify additional relationships between spans
  249. // in addition to a parent/child relationship.
  250. type SpanKind int32
  251. const (
  252. // Indicates that the span represents an internal operation within an application,
  253. // as opposed to an operation happening at the boundaries. Default value.
  254. SpanKindInternal SpanKind = 1
  255. // Indicates that the span covers server-side handling of an RPC or other
  256. // remote network request.
  257. SpanKindServer SpanKind = 2
  258. // Indicates that the span describes a request to some remote service.
  259. SpanKindClient SpanKind = 3
  260. // Indicates that the span describes a producer sending a message to a broker.
  261. // Unlike CLIENT and SERVER, there is often no direct critical path latency relationship
  262. // between producer and consumer spans. A PRODUCER span ends when the message was accepted
  263. // by the broker while the logical processing of the message might span a much longer time.
  264. SpanKindProducer SpanKind = 4
  265. // Indicates that the span describes consumer receiving a message from a broker.
  266. // Like the PRODUCER kind, there is often no direct critical path latency relationship
  267. // between producer and consumer spans.
  268. SpanKindConsumer SpanKind = 5
  269. )
  270. // Event is a time-stamped annotation of the span, consisting of user-supplied
  271. // text description and key-value pairs.
  272. type SpanEvent struct {
  273. // time_unix_nano is the time the event occurred.
  274. Time time.Time `json:"timeUnixNano,omitempty"`
  275. // name of the event.
  276. // This field is semantically required to be set to non-empty string.
  277. Name string `json:"name,omitempty"`
  278. // attributes is a collection of attribute key/value pairs on the event.
  279. // Attribute keys MUST be unique (it is not allowed to have more than one
  280. // attribute with the same key).
  281. Attrs []Attr `json:"attributes,omitempty"`
  282. // dropped_attributes_count is the number of dropped attributes. If the value is 0,
  283. // then no attributes were dropped.
  284. DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
  285. }
  286. // MarshalJSON encodes e into OTLP formatted JSON.
  287. func (e SpanEvent) MarshalJSON() ([]byte, error) {
  288. t := e.Time.UnixNano()
  289. if e.Time.IsZero() || t < 0 {
  290. t = 0
  291. }
  292. type Alias SpanEvent
  293. return json.Marshal(struct {
  294. Alias
  295. Time uint64 `json:"timeUnixNano,omitempty"`
  296. }{
  297. Alias: Alias(e),
  298. Time: uint64(t), // nolint: gosec // >0 checked above
  299. })
  300. }
  301. // UnmarshalJSON decodes the OTLP formatted JSON contained in data into se.
  302. func (se *SpanEvent) UnmarshalJSON(data []byte) error {
  303. decoder := json.NewDecoder(bytes.NewReader(data))
  304. t, err := decoder.Token()
  305. if err != nil {
  306. return err
  307. }
  308. if t != json.Delim('{') {
  309. return errors.New("invalid SpanEvent type")
  310. }
  311. for decoder.More() {
  312. keyIface, err := decoder.Token()
  313. if err != nil {
  314. if errors.Is(err, io.EOF) {
  315. // Empty.
  316. return nil
  317. }
  318. return err
  319. }
  320. key, ok := keyIface.(string)
  321. if !ok {
  322. return fmt.Errorf("invalid SpanEvent field: %#v", keyIface)
  323. }
  324. switch key {
  325. case "timeUnixNano", "time_unix_nano":
  326. var val protoUint64
  327. err = decoder.Decode(&val)
  328. v := int64(min(val.Uint64(), math.MaxInt64)) // nolint: gosec // Overflow checked.
  329. se.Time = time.Unix(0, v)
  330. case "name":
  331. err = decoder.Decode(&se.Name)
  332. case "attributes":
  333. err = decoder.Decode(&se.Attrs)
  334. case "droppedAttributesCount", "dropped_attributes_count":
  335. err = decoder.Decode(&se.DroppedAttrs)
  336. default:
  337. // Skip unknown.
  338. }
  339. if err != nil {
  340. return err
  341. }
  342. }
  343. return nil
  344. }
  345. // A pointer from the current span to another span in the same trace or in a
  346. // different trace. For example, this can be used in batching operations,
  347. // where a single batch handler processes multiple requests from different
  348. // traces or when the handler receives a request from a different project.
  349. type SpanLink struct {
  350. // A unique identifier of a trace that this linked span is part of. The ID is a
  351. // 16-byte array.
  352. TraceID TraceID `json:"traceId,omitempty"`
  353. // A unique identifier for the linked span. The ID is an 8-byte array.
  354. SpanID SpanID `json:"spanId,omitempty"`
  355. // The trace_state associated with the link.
  356. TraceState string `json:"traceState,omitempty"`
  357. // attributes is a collection of attribute key/value pairs on the link.
  358. // Attribute keys MUST be unique (it is not allowed to have more than one
  359. // attribute with the same key).
  360. Attrs []Attr `json:"attributes,omitempty"`
  361. // dropped_attributes_count is the number of dropped attributes. If the value is 0,
  362. // then no attributes were dropped.
  363. DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
  364. // Flags, a bit field.
  365. //
  366. // Bits 0-7 (8 least significant bits) are the trace flags as defined in W3C Trace
  367. // Context specification. To read the 8-bit W3C trace flag, use
  368. // `flags & SPAN_FLAGS_TRACE_FLAGS_MASK`.
  369. //
  370. // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
  371. //
  372. // Bits 8 and 9 represent the 3 states of whether the link is remote.
  373. // The states are (unknown, is not remote, is remote).
  374. // To read whether the value is known, use `(flags & SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK) != 0`.
  375. // To read whether the link is remote, use `(flags & SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK) != 0`.
  376. //
  377. // Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero.
  378. // When creating new spans, bits 10-31 (most-significant 22-bits) MUST be zero.
  379. //
  380. // [Optional].
  381. Flags uint32 `json:"flags,omitempty"`
  382. }
  383. // UnmarshalJSON decodes the OTLP formatted JSON contained in data into sl.
  384. func (sl *SpanLink) UnmarshalJSON(data []byte) error {
  385. decoder := json.NewDecoder(bytes.NewReader(data))
  386. t, err := decoder.Token()
  387. if err != nil {
  388. return err
  389. }
  390. if t != json.Delim('{') {
  391. return errors.New("invalid SpanLink type")
  392. }
  393. for decoder.More() {
  394. keyIface, err := decoder.Token()
  395. if err != nil {
  396. if errors.Is(err, io.EOF) {
  397. // Empty.
  398. return nil
  399. }
  400. return err
  401. }
  402. key, ok := keyIface.(string)
  403. if !ok {
  404. return fmt.Errorf("invalid SpanLink field: %#v", keyIface)
  405. }
  406. switch key {
  407. case "traceId", "trace_id":
  408. err = decoder.Decode(&sl.TraceID)
  409. case "spanId", "span_id":
  410. err = decoder.Decode(&sl.SpanID)
  411. case "traceState", "trace_state":
  412. err = decoder.Decode(&sl.TraceState)
  413. case "attributes":
  414. err = decoder.Decode(&sl.Attrs)
  415. case "droppedAttributesCount", "dropped_attributes_count":
  416. err = decoder.Decode(&sl.DroppedAttrs)
  417. case "flags":
  418. err = decoder.Decode(&sl.Flags)
  419. default:
  420. // Skip unknown.
  421. }
  422. if err != nil {
  423. return err
  424. }
  425. }
  426. return nil
  427. }