blob: 3f15f48e29a07b5965aa645fc683ca531549e020 [file] [log] [blame]
serkant.uluderyae5afeff2021-02-23 18:00:23 +03001// Copyright The OpenTelemetry Authors
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
15package trace
16
17import (
18 "context"
19 "time"
20
21 "go.opentelemetry.io/otel/codes"
22 "go.opentelemetry.io/otel/label"
23)
24
25// TracerProvider provides access to instrumentation Tracers.
26type TracerProvider interface {
27 // Tracer creates an implementation of the Tracer interface.
28 // The instrumentationName must be the name of the library providing
29 // instrumentation. This name may be the same as the instrumented code
30 // only if that code provides built-in instrumentation. If the
31 // instrumentationName is empty, then a implementation defined default
32 // name will be used instead.
33 Tracer(instrumentationName string, opts ...TracerOption) Tracer
34}
35
36// TracerConfig is a group of options for a Tracer.
37//
38// Most users will use the tracer options instead.
39type TracerConfig struct {
40 // InstrumentationVersion is the version of the instrumentation library.
41 InstrumentationVersion string
42}
43
44// NewTracerConfig applies all the options to a returned TracerConfig.
45// The default value for all the fields of the returned TracerConfig are the
46// default zero value of the type. Also, this does not perform any validation
47// on the returned TracerConfig (e.g. no uniqueness checking or bounding of
48// data), instead it is left to the implementations of the SDK to perform this
49// action.
50func NewTracerConfig(opts ...TracerOption) *TracerConfig {
51 config := new(TracerConfig)
52 for _, option := range opts {
53 option.Apply(config)
54 }
55 return config
56}
57
58// TracerOption applies an options to a TracerConfig.
59type TracerOption interface {
60 Apply(*TracerConfig)
61}
62
63type instVersionTracerOption string
64
65func (o instVersionTracerOption) Apply(c *TracerConfig) { c.InstrumentationVersion = string(o) }
66
67// WithInstrumentationVersion sets the instrumentation version for a Tracer.
68func WithInstrumentationVersion(version string) TracerOption {
69 return instVersionTracerOption(version)
70}
71
72type Tracer interface {
73 // Start a span.
74 Start(ctx context.Context, spanName string, opts ...SpanOption) (context.Context, Span)
75}
76
77// ErrorConfig provides options to set properties of an error
78// event at the time it is recorded.
79//
80// Most users will use the error options instead.
81type ErrorConfig struct {
82 Timestamp time.Time
83 StatusCode codes.Code
84}
85
86// ErrorOption applies changes to ErrorConfig that sets options when an error event is recorded.
87type ErrorOption func(*ErrorConfig)
88
89// WithErrorTime sets the time at which the error event should be recorded.
90func WithErrorTime(t time.Time) ErrorOption {
91 return func(c *ErrorConfig) {
92 c.Timestamp = t
93 }
94}
95
96// WithErrorStatus indicates the span status that should be set when recording an error event.
97func WithErrorStatus(s codes.Code) ErrorOption {
98 return func(c *ErrorConfig) {
99 c.StatusCode = s
100 }
101}
102
103type Span interface {
104 // Tracer returns tracer used to create this span. Tracer cannot be nil.
105 Tracer() Tracer
106
107 // End completes the span. No updates are allowed to span after it
108 // ends. The only exception is setting status of the span.
109 End(options ...SpanOption)
110
111 // AddEvent adds an event to the span.
112 AddEvent(ctx context.Context, name string, attrs ...label.KeyValue)
113 // AddEventWithTimestamp adds an event with a custom timestamp
114 // to the span.
115 AddEventWithTimestamp(ctx context.Context, timestamp time.Time, name string, attrs ...label.KeyValue)
116
117 // IsRecording returns true if the span is active and recording events is enabled.
118 IsRecording() bool
119
120 // RecordError records an error as a span event.
121 RecordError(ctx context.Context, err error, opts ...ErrorOption)
122
123 // SpanContext returns span context of the span. Returned SpanContext is usable
124 // even after the span ends.
125 SpanContext() SpanContext
126
127 // SetStatus sets the status of the span in the form of a code
128 // and a message. SetStatus overrides the value of previous
129 // calls to SetStatus on the Span.
130 //
131 // The default span status is OK, so it is not necessary to
132 // explicitly set an OK status on successful Spans unless it
133 // is to add an OK message or to override a previous status on the Span.
134 SetStatus(code codes.Code, msg string)
135
136 // SetName sets the name of the span.
137 SetName(name string)
138
139 // Set span attributes
140 SetAttributes(kv ...label.KeyValue)
141}
142
143// SpanConfig is a group of options for a Span.
144//
145// Most users will use span options instead.
146type SpanConfig struct {
147 // Attributes describe the associated qualities of a Span.
148 Attributes []label.KeyValue
149 // Timestamp is a time in a Span life-cycle.
150 Timestamp time.Time
151 // Links are the associations a Span has with other Spans.
152 Links []Link
153 // Record is the recording state of a Span.
154 Record bool
155 // NewRoot identifies a Span as the root Span for a new trace. This is
156 // commonly used when an existing trace crosses trust boundaries and the
157 // remote parent span context should be ignored for security.
158 NewRoot bool
159 // SpanKind is the role a Span has in a trace.
160 SpanKind SpanKind
161}
162
163// NewSpanConfig applies all the options to a returned SpanConfig.
164// The default value for all the fields of the returned SpanConfig are the
165// default zero value of the type. Also, this does not perform any validation
166// on the returned SpanConfig (e.g. no uniqueness checking or bounding of
167// data). Instead, it is left to the implementations of the SDK to perform this
168// action.
169func NewSpanConfig(opts ...SpanOption) *SpanConfig {
170 c := new(SpanConfig)
171 for _, option := range opts {
172 option.Apply(c)
173 }
174 return c
175}
176
177// SpanOption applies an option to a SpanConfig.
178type SpanOption interface {
179 Apply(*SpanConfig)
180}
181
182type attributeSpanOption []label.KeyValue
183
184func (o attributeSpanOption) Apply(c *SpanConfig) {
185 c.Attributes = append(c.Attributes, []label.KeyValue(o)...)
186}
187
188// WithAttributes adds the attributes to a span. These attributes are meant to
189// provide additional information about the work the Span represents. The
190// attributes are added to the existing Span attributes, i.e. this does not
191// overwrite.
192func WithAttributes(attributes ...label.KeyValue) SpanOption {
193 return attributeSpanOption(attributes)
194}
195
196type timestampSpanOption time.Time
197
198func (o timestampSpanOption) Apply(c *SpanConfig) { c.Timestamp = time.Time(o) }
199
200// WithTimestamp sets the time of a Span life-cycle moment (e.g. started or
201// stopped).
202func WithTimestamp(t time.Time) SpanOption {
203 return timestampSpanOption(t)
204}
205
206type linksSpanOption []Link
207
208func (o linksSpanOption) Apply(c *SpanConfig) { c.Links = append(c.Links, []Link(o)...) }
209
210// WithLinks adds links to a Span. The links are added to the existing Span
211// links, i.e. this does not overwrite.
212func WithLinks(links ...Link) SpanOption {
213 return linksSpanOption(links)
214}
215
216type recordSpanOption bool
217
218func (o recordSpanOption) Apply(c *SpanConfig) { c.Record = bool(o) }
219
220// WithRecord specifies that the span should be recorded. It is important to
221// note that implementations may override this option, i.e. if the span is a
222// child of an un-sampled trace.
223func WithRecord() SpanOption {
224 return recordSpanOption(true)
225}
226
227type newRootSpanOption bool
228
229func (o newRootSpanOption) Apply(c *SpanConfig) { c.NewRoot = bool(o) }
230
231// WithNewRoot specifies that the Span should be treated as a root Span. Any
232// existing parent span context will be ignored when defining the Span's trace
233// identifiers.
234func WithNewRoot() SpanOption {
235 return newRootSpanOption(true)
236}
237
238type spanKindSpanOption SpanKind
239
240func (o spanKindSpanOption) Apply(c *SpanConfig) { c.SpanKind = SpanKind(o) }
241
242// WithSpanKind sets the SpanKind of a Span.
243func WithSpanKind(kind SpanKind) SpanOption {
244 return spanKindSpanOption(kind)
245}
246
247// Link is used to establish relationship between two spans within the same Trace or
248// across different Traces. Few examples of Link usage.
249// 1. Batch Processing: A batch of elements may contain elements associated with one
250// or more traces/spans. Since there can only be one parent SpanContext, Link is
251// used to keep reference to SpanContext of all elements in the batch.
252// 2. Public Endpoint: A SpanContext in incoming client request on a public endpoint
253// is untrusted from service provider perspective. In such case it is advisable to
254// start a new trace with appropriate sampling decision.
255// However, it is desirable to associate incoming SpanContext to new trace initiated
256// on service provider side so two traces (from Client and from Service Provider) can
257// be correlated.
258type Link struct {
259 SpanContext
260 Attributes []label.KeyValue
261}
262
263// SpanKind represents the role of a Span inside a Trace. Often, this defines how a Span
264// will be processed and visualized by various backends.
265type SpanKind int
266
267const (
268 // As a convenience, these match the proto definition, see
269 // opentelemetry/proto/trace/v1/trace.proto
270 //
271 // The unspecified value is not a valid `SpanKind`. Use
272 // `ValidateSpanKind()` to coerce a span kind to a valid
273 // value.
274 SpanKindUnspecified SpanKind = 0
275 SpanKindInternal SpanKind = 1
276 SpanKindServer SpanKind = 2
277 SpanKindClient SpanKind = 3
278 SpanKindProducer SpanKind = 4
279 SpanKindConsumer SpanKind = 5
280)
281
282// ValidateSpanKind returns a valid span kind value. This will coerce
283// invalid values into the default value, SpanKindInternal.
284func ValidateSpanKind(spanKind SpanKind) SpanKind {
285 switch spanKind {
286 case SpanKindInternal,
287 SpanKindServer,
288 SpanKindClient,
289 SpanKindProducer,
290 SpanKindConsumer:
291 // valid
292 return spanKind
293 default:
294 return SpanKindInternal
295 }
296}
297
298// String returns the specified name of the SpanKind in lower-case.
299func (sk SpanKind) String() string {
300 switch sk {
301 case SpanKindInternal:
302 return "internal"
303 case SpanKindServer:
304 return "server"
305 case SpanKindClient:
306 return "client"
307 case SpanKindProducer:
308 return "producer"
309 case SpanKindConsumer:
310 return "consumer"
311 default:
312 return "unspecified"
313 }
314}