span.go

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