span.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package 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. // SpanFlagsTraceFlagsMask is a mask for trace-flags.
  240. //
  241. // Bits 0-7 are used for trace flags.
  242. SpanFlagsTraceFlagsMask SpanFlags = 255
  243. // SpanFlagsContextHasIsRemoteMask is a mask for HAS_IS_REMOTE status.
  244. //
  245. // Bits 8 and 9 are used to indicate that the parent span or link span is
  246. // remote. Bit 8 (`HAS_IS_REMOTE`) indicates whether the value is known.
  247. SpanFlagsContextHasIsRemoteMask SpanFlags = 256
  248. // SpanFlagsContextIsRemoteMask is a mask for IS_REMOTE status.
  249. //
  250. // Bits 8 and 9 are used to indicate that the parent span or link span is
  251. // remote. Bit 9 (`IS_REMOTE`) indicates whether the span or link is
  252. // remote.
  253. SpanFlagsContextIsRemoteMask SpanFlags = 512
  254. )
  255. // SpanKind is the type of span. Can be used to specify additional relationships between spans
  256. // in addition to a parent/child relationship.
  257. type SpanKind int32
  258. const (
  259. // SpanKindInternal indicates that the span represents an internal
  260. // operation within an application, as opposed to an operation happening at
  261. // the boundaries.
  262. SpanKindInternal SpanKind = 1
  263. // SpanKindServer indicates that the span covers server-side handling of an
  264. // RPC or other remote network request.
  265. SpanKindServer SpanKind = 2
  266. // SpanKindClient indicates that the span describes a request to some
  267. // remote service.
  268. SpanKindClient SpanKind = 3
  269. // SpanKindProducer indicates that the span describes a producer sending a
  270. // message to a broker. Unlike SpanKindClient and SpanKindServer, there is
  271. // often no direct critical path latency relationship between producer and
  272. // consumer spans. A SpanKindProducer span ends when the message was
  273. // accepted by the broker while the logical processing of the message might
  274. // span a much longer time.
  275. SpanKindProducer SpanKind = 4
  276. // SpanKindConsumer indicates that the span describes a consumer receiving
  277. // a message from a broker. Like SpanKindProducer, there is often no direct
  278. // critical path latency relationship between producer and consumer spans.
  279. SpanKindConsumer SpanKind = 5
  280. )
  281. // SpanEvent is a time-stamped annotation of the span, consisting of user-supplied
  282. // text description and key-value pairs.
  283. type SpanEvent struct {
  284. // time_unix_nano is the time the event occurred.
  285. Time time.Time `json:"timeUnixNano,omitempty"`
  286. // name of the event.
  287. // This field is semantically required to be set to non-empty string.
  288. Name string `json:"name,omitempty"`
  289. // attributes is a collection of attribute key/value pairs on the event.
  290. // Attribute keys MUST be unique (it is not allowed to have more than one
  291. // attribute with the same key).
  292. Attrs []Attr `json:"attributes,omitempty"`
  293. // dropped_attributes_count is the number of dropped attributes. If the value is 0,
  294. // then no attributes were dropped.
  295. DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
  296. }
  297. // MarshalJSON encodes e into OTLP formatted JSON.
  298. func (e SpanEvent) MarshalJSON() ([]byte, error) {
  299. t := e.Time.UnixNano()
  300. if e.Time.IsZero() || t < 0 {
  301. t = 0
  302. }
  303. type Alias SpanEvent
  304. return json.Marshal(struct {
  305. Alias
  306. Time uint64 `json:"timeUnixNano,omitempty"`
  307. }{
  308. Alias: Alias(e),
  309. Time: uint64(t), //nolint:gosec // >0 checked above
  310. })
  311. }
  312. // UnmarshalJSON decodes the OTLP formatted JSON contained in data into se.
  313. func (se *SpanEvent) UnmarshalJSON(data []byte) error {
  314. decoder := json.NewDecoder(bytes.NewReader(data))
  315. t, err := decoder.Token()
  316. if err != nil {
  317. return err
  318. }
  319. if t != json.Delim('{') {
  320. return errors.New("invalid SpanEvent type")
  321. }
  322. for decoder.More() {
  323. keyIface, err := decoder.Token()
  324. if err != nil {
  325. if errors.Is(err, io.EOF) {
  326. // Empty.
  327. return nil
  328. }
  329. return err
  330. }
  331. key, ok := keyIface.(string)
  332. if !ok {
  333. return fmt.Errorf("invalid SpanEvent field: %#v", keyIface)
  334. }
  335. switch key {
  336. case "timeUnixNano", "time_unix_nano":
  337. var val protoUint64
  338. err = decoder.Decode(&val)
  339. v := int64(min(val.Uint64(), math.MaxInt64)) //nolint:gosec // Overflow checked.
  340. se.Time = time.Unix(0, v)
  341. case "name":
  342. err = decoder.Decode(&se.Name)
  343. case "attributes":
  344. err = decoder.Decode(&se.Attrs)
  345. case "droppedAttributesCount", "dropped_attributes_count":
  346. err = decoder.Decode(&se.DroppedAttrs)
  347. default:
  348. // Skip unknown.
  349. }
  350. if err != nil {
  351. return err
  352. }
  353. }
  354. return nil
  355. }
  356. // SpanLink is a reference from the current span to another span in the same
  357. // trace or in a different trace. For example, this can be used in batching
  358. // operations, where a single batch handler processes multiple requests from
  359. // different traces or when the handler receives a request from a different
  360. // project.
  361. type SpanLink struct {
  362. // A unique identifier of a trace that this linked span is part of. The ID is a
  363. // 16-byte array.
  364. TraceID TraceID `json:"traceId,omitempty"`
  365. // A unique identifier for the linked span. The ID is an 8-byte array.
  366. SpanID SpanID `json:"spanId,omitempty"`
  367. // The trace_state associated with the link.
  368. TraceState string `json:"traceState,omitempty"`
  369. // attributes is a collection of attribute key/value pairs on the link.
  370. // Attribute keys MUST be unique (it is not allowed to have more than one
  371. // attribute with the same key).
  372. Attrs []Attr `json:"attributes,omitempty"`
  373. // dropped_attributes_count is the number of dropped attributes. If the value is 0,
  374. // then no attributes were dropped.
  375. DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
  376. // Flags, a bit field.
  377. //
  378. // Bits 0-7 (8 least significant bits) are the trace flags as defined in W3C Trace
  379. // Context specification. To read the 8-bit W3C trace flag, use
  380. // `flags & SPAN_FLAGS_TRACE_FLAGS_MASK`.
  381. //
  382. // See https://www.w3.org/TR/trace-context-2/#trace-flags for the flag definitions.
  383. //
  384. // Bits 8 and 9 represent the 3 states of whether the link is remote.
  385. // The states are (unknown, is not remote, is remote).
  386. // To read whether the value is known, use `(flags & SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK) != 0`.
  387. // To read whether the link is remote, use `(flags & SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK) != 0`.
  388. //
  389. // Readers MUST NOT assume that bits 10-31 (22 most significant bits) will be zero.
  390. // When creating new spans, bits 10-31 (most-significant 22-bits) MUST be zero.
  391. //
  392. // [Optional].
  393. Flags uint32 `json:"flags,omitempty"`
  394. }
  395. // UnmarshalJSON decodes the OTLP formatted JSON contained in data into sl.
  396. func (sl *SpanLink) UnmarshalJSON(data []byte) error {
  397. decoder := json.NewDecoder(bytes.NewReader(data))
  398. t, err := decoder.Token()
  399. if err != nil {
  400. return err
  401. }
  402. if t != json.Delim('{') {
  403. return errors.New("invalid SpanLink type")
  404. }
  405. for decoder.More() {
  406. keyIface, err := decoder.Token()
  407. if err != nil {
  408. if errors.Is(err, io.EOF) {
  409. // Empty.
  410. return nil
  411. }
  412. return err
  413. }
  414. key, ok := keyIface.(string)
  415. if !ok {
  416. return fmt.Errorf("invalid SpanLink field: %#v", keyIface)
  417. }
  418. switch key {
  419. case "traceId", "trace_id":
  420. err = decoder.Decode(&sl.TraceID)
  421. case "spanId", "span_id":
  422. err = decoder.Decode(&sl.SpanID)
  423. case "traceState", "trace_state":
  424. err = decoder.Decode(&sl.TraceState)
  425. case "attributes":
  426. err = decoder.Decode(&sl.Attrs)
  427. case "droppedAttributesCount", "dropped_attributes_count":
  428. err = decoder.Decode(&sl.DroppedAttrs)
  429. case "flags":
  430. err = decoder.Decode(&sl.Flags)
  431. default:
  432. // Skip unknown.
  433. }
  434. if err != nil {
  435. return err
  436. }
  437. }
  438. return nil
  439. }