span.go 16 KB

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