Documentation ¶
Index ¶
- Variables
- func ContextWithSpan(ctx context.Context, span Span) context.Context
- func InitGlobalTracer(tracer Tracer)
- type BuiltinFormat
- type FinishOptions
- type HTTPHeadersCarrier
- type LogData
- type NoopTracer
- type Span
- type SpanContext
- type SpanReference
- type SpanReferenceType
- type StartSpanOption
- type StartSpanOptions
- type StartTime
- type Tag
- type Tags
- type TextMapCarrier
- type TextMapReader
- type TextMapWriter
- type Tracer
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnsupportedFormat occurs when the `format` passed to Tracer.Inject() or // Tracer.Extract() is not recognized by the Tracer implementation. ErrUnsupportedFormat = errors.New("opentracing: Unknown or unsupported Inject/Extract format") // ErrSpanContextNotFound occurs when the `carrier` passed to // Tracer.Extract() is valid and uncorrupted but has insufficient // information to extract a SpanContext. ErrSpanContextNotFound = errors.New("opentracing: SpanContext not found in Extract carrier") // ErrInvalidSpanContext errors occur when Tracer.Inject() is asked to // operate on a SpanContext which it is not prepared to handle (for // example, since it was created by a different tracer implementation). ErrInvalidSpanContext = errors.New("opentracing: SpanContext type incompatible with tracer") // ErrInvalidCarrier errors occur when Tracer.Inject() or Tracer.Extract() // implementations expect a different type of `carrier` than they are // given. ErrInvalidCarrier = errors.New("opentracing: Invalid Inject/Extract carrier") // ErrSpanContextCorrupted occurs when the `carrier` passed to // Tracer.Extract() is of the expected type but is corrupted. ErrSpanContextCorrupted = errors.New("opentracing: SpanContext data corrupted in Extract carrier") )
Functions ¶
func ContextWithSpan ¶
ContextWithSpan returns a new `context.Context` that holds a reference to `span`'s SpanContext.
func InitGlobalTracer ¶
func InitGlobalTracer(tracer Tracer)
InitGlobalTracer sets the [singleton] opentracing.Tracer returned by GlobalTracer(). Those who use GlobalTracer (rather than directly manage an opentracing.Tracer instance) should call InitGlobalTracer as early as possible in main(), prior to calling the `StartSpan` global func below. Prior to calling `InitGlobalTracer`, any Spans started via the `StartSpan` (etc) globals are noops.
Types ¶
type BuiltinFormat ¶
type BuiltinFormat byte
BuiltinFormat is used to demarcate the values within package `opentracing` that are intended for use with the Tracer.Inject() and Tracer.Extract() methods.
const ( // Binary represents SpanContexts as opaque binary data. // // For Tracer.Inject(): the carrier must be an `io.Writer`. // // For Tracer.Extract(): the carrier must be an `io.Reader`. Binary BuiltinFormat = iota // TextMap represents SpanContexts as key:value string pairs. // // Unlike HTTPHeaders, the TextMap format does not restrict the key or // value character sets in any way. // // For Tracer.Inject(): the carrier must be a `TextMapWriter`. // // For Tracer.Extract(): the carrier must be a `TextMapReader`. TextMap // HTTPHeaders represents SpanContexts as HTTP header string pairs. // // Unlike TextMap, the HTTPHeaders format requires that the keys and values // be valid as HTTP headers as-is (i.e., character casing may be unstable // and special characters are disallowed in keys, values should be // URL-escaped, etc). // // For Tracer.Inject(): the carrier must be a `TextMapWriter`. // // For Tracer.Extract(): the carrier must be a `TextMapReader`. // // See HTTPHeaderCarrier for an implementation of both TextMapWriter // and TextMapReader that defers to an http.Header instance for storage. // For example, Inject(): // // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) // err := span.Tracer().Inject( // span, opentracing.HTTPHeaders, carrier) // // Or Extract(): // // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) // span, err := tracer.Extract( // opentracing.HTTPHeaders, carrier) // HTTPHeaders )
type FinishOptions ¶
type FinishOptions struct { // FinishTime overrides the Span's finish time, or implicitly becomes // time.Now() if FinishTime.IsZero(). // // FinishTime must resolve to a timestamp that's >= the Span's StartTime // (per StartSpanOptions). FinishTime time.Time // BulkLogData allows the caller to specify the contents of many Log() // calls with a single slice. May be nil. // // None of the LogData.Timestamp values may be .IsZero() (i.e., they must // be set explicitly). Also, they must be >= the Span's start timestamp and // <= the FinishTime (or time.Now() if FinishTime.IsZero()). Otherwise the // behavior of FinishWithOptions() is undefined. // // If specified, the caller hands off ownership of BulkLogData at // FinishWithOptions() invocation time. BulkLogData []LogData }
FinishOptions allows Span.FinishWithOptions callers to override the finish timestamp and provide log data via a bulk interface.
type HTTPHeadersCarrier ¶
HTTPHeadersCarrier satisfies both TextMapWriter and TextMapReader.
Example usage for server side:
carrier := opentracing.HttpHeadersCarrier(httpReq.Header) spanContext, err := tracer.Extract(opentracing.HttpHeaders, carrier)
Example usage for client side:
carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) err := tracer.Inject( span.Context(), opentracing.HttpHeaders, carrier)
func (HTTPHeadersCarrier) ForeachKey ¶
func (c HTTPHeadersCarrier) ForeachKey(handler func(key, val string) error) error
ForeachKey conforms to the TextMapReader interface.
func (HTTPHeadersCarrier) Set ¶
func (c HTTPHeadersCarrier) Set(key, val string)
Set conforms to the TextMapWriter interface.
type LogData ¶
type LogData struct { // The timestamp of the log record; if set to the default value (the unix // epoch), implementations should use time.Now() implicitly. Timestamp time.Time // Event (if non-empty) should be the stable name of some notable moment in // the lifetime of a Span. For instance, a Span representing a browser page // load might add an Event for each of the Performance.timing moments // here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming // // While it is not a formal requirement, Event strings will be most useful // if they are *not* unique; rather, tracing systems should be able to use // them to understand how two similar Spans relate from an internal timing // perspective. Event string // Payload is a free-form potentially structured object which Tracer // implementations may retain and record all, none, or part of. // // If included, `Payload` should be restricted to data derived from the // instrumented application; in particular, it should not be used to pass // semantic flags to a Log() implementation. // // For example, an RPC system could log the wire contents in both // directions, or a SQL library could log the query (with or without // parameter bindings); tracing implementations may truncate or otherwise // record only a snippet of these payloads (or may strip out PII, etc, // etc). Payload interface{} }
LogData is data associated with a Span. Every LogData instance should specify at least one of Event and/or Payload.
type NoopTracer ¶
type NoopTracer struct{}
A NoopTracer is a trivial implementation of Tracer for which all operations are no-ops.
func (NoopTracer) Extract ¶
func (n NoopTracer) Extract(format interface{}, carrier interface{}) (SpanContext, error)
Extract belongs to the Tracer interface.
func (NoopTracer) Inject ¶
func (n NoopTracer) Inject(sp SpanContext, format interface{}, carrier interface{}) error
Inject belongs to the Tracer interface.
func (NoopTracer) StartSpan ¶
func (n NoopTracer) StartSpan(operationName string, opts ...StartSpanOption) Span
StartSpan belongs to the Tracer interface.
type Span ¶
type Span interface { // Sets the end timestamp and finalizes Span state. // // With the exception of calls to Context() (which are always allowed), // Finish() must be the last call made to any span instance, and to do // otherwise leads to undefined behavior. Finish() // FinishWithOptions is like Finish() but with explicit control over // timestamps and log data. FinishWithOptions(opts FinishOptions) // Context() yields the SpanContext for this Span. Note that the return // value of Context() is still valid after a call to Span.Finish(), as is // a call to Span.Context() after a call to Span.Finish(). Context() SpanContext // Sets or changes the operation name. SetOperationName(operationName string) Span // Adds a tag to the span. // // If there is a pre-existing tag set for `key`, it is overwritten. // // Tag values can be numeric types, strings, or bools. The behavior of // other tag value types is undefined at the OpenTracing level. If a // tracing system does not know how to handle a particular value type, it // may ignore the tag, but shall not panic. SetTag(key string, value interface{}) Span // LogEvent() is equivalent to // // Log(LogData{Event: event}) // LogEvent(event string) // LogEventWithPayload() is equivalent to // // Log(LogData{Event: event, Payload: payload0}) // LogEventWithPayload(event string, payload interface{}) // Log() records `data` to this Span. // // See LogData for semantic details. Log(data LogData) // SetBaggageItem sets a key:value pair on this Span and its SpanContext // that also propagates to descendants of this Span. // // SetBaggageItem() enables powerful functionality given a full-stack // opentracing integration (e.g., arbitrary application data from a mobile // app can make it, transparently, all the way into the depths of a storage // system), and with it some powerful costs: use this feature with care. // // IMPORTANT NOTE #1: SetBaggageItem() will only propagate baggage items to // *future* causal descendants of the associated Span. // // IMPORTANT NOTE #2: Use this thoughtfully and with care. Every key and // value is copied into every local *and remote* child of the associated // Span, and that can add up to a lot of network and cpu overhead. // // Returns a reference to this Span for chaining. SetBaggageItem(restrictedKey, value string) Span // Gets the value for a baggage item given its key. Returns the empty string // if the value isn't found in this Span. BaggageItem(restrictedKey string) string // Provides access to the Tracer that created this Span. Tracer() Tracer }
Span represents an active, un-finished span in the OpenTracing system.
Spans are created by the Tracer interface.
func SpanFromContext ¶
SpanFromContext returns the `Span` previously associated with `ctx`, or `nil` if no such `Span` could be found.
NOTE: context.Context != SpanContext: the former is Go's intra-process context propagation mechanism, and the latter houses OpenTracing's per-Span identity and baggage information.
func StartSpan ¶
func StartSpan(operationName string, opts ...StartSpanOption) Span
StartSpan defers to `Tracer.StartSpan`. See `GlobalTracer()`.
func StartSpanFromContext ¶
func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context)
StartSpanFromContext starts and returns a Span with `operationName`, using any Span found within `ctx` as a ChildOfRef. If no such parent could be found, StartSpanFromContext creates a root (parentless) Span.
The second return value is a context.Context object built around the returned Span.
Example usage:
SomeFunction(ctx context.Context, ...) { sp, ctx := opentracing.StartSpanFromContext(ctx, "SomeFunction") defer sp.Finish() ... }
type SpanContext ¶
type SpanContext interface { // ForeachBaggageItem grants access to all baggage items stored in the // SpanContext. // The handler function will be called for each baggage key/value pair. // The ordering of items is not guaranteed. // // The bool return value indicates if the handler wants to continue iterating // through the rest of the baggage items; for example if the handler is trying to // find some baggage item by pattern matching the name, it can return false // as soon as the item is found to stop further iterations. ForeachBaggageItem(handler func(k, v string) bool) }
SpanContext represents Span state that must propagate to descendant Spans and across process boundaries (e.g., a <trace_id, span_id, sampled> tuple).
type SpanReference ¶
type SpanReference struct { Type SpanReferenceType ReferencedContext SpanContext }
SpanReference is a StartSpanOption that pairs a SpanReferenceType and a referenced SpanContext. See the SpanReferenceType documentation for supported relationships. If SpanReference is created with ReferencedContext==nil, it has no effect. Thus it allows for a more concise syntax for starting spans:
sc, _ := tracer.Extract(someFormat, someCarrier) span := tracer.StartSpan("operation", opentracing.ChildOf(sc))
The `ChildOf(sc)` option above will not panic if sc == nil, it will just not add the parent span reference to the options.
func ChildOf ¶
func ChildOf(sc SpanContext) SpanReference
ChildOf returns a StartSpanOption pointing to a dependent parent span. If sc == nil, the option has no effect.
See ChildOfRef, SpanReference
func FollowsFrom ¶
func FollowsFrom(sc SpanContext) SpanReference
FollowsFrom returns a StartSpanOption pointing to a parent Span that caused the child Span but does not directly depend on its result in any way. If sc == nil, the option has no effect.
See FollowsFromRef, SpanReference
func (SpanReference) Apply ¶
func (r SpanReference) Apply(o *StartSpanOptions)
Apply satisfies the StartSpanOption interface.
type SpanReferenceType ¶
type SpanReferenceType int
SpanReferenceType is an enum type describing different categories of relationships between two Spans. If Span-2 refers to Span-1, the SpanReferenceType describes Span-1 from Span-2's perspective. For example, ChildOfRef means that Span-1 created Span-2.
NOTE: Span-1 and Span-2 do *not* necessarily depend on each other for completion; e.g., Span-2 may be part of a background job enqueued by Span-1, or Span-2 may be sitting in a distributed queue behind Span-1.
const ( // ChildOfRef refers to a parent Span that caused *and* somehow depends // upon the new child Span. Often (but not always), the parent Span cannot // finish until the child Span does. // // An timing diagram for a ChildOfRef that's blocked on the new Span: // // [-Parent Span---------] // [-Child Span----] // // See http://opentracing.io/spec/ // // See opentracing.ChildOf() ChildOfRef SpanReferenceType = iota // FollowsFromRef refers to a parent Span that does not depend in any way // on the result of the new child Span. For instance, one might use // FollowsFromRefs to describe pipeline stages separated by queues, // or a fire-and-forget cache insert at the tail end of a web request. // // A FollowsFromRef Span is part of the same logical trace as the new Span: // i.e., the new Span is somehow caused by the work of its FollowsFromRef. // // All of the following could be valid timing diagrams for children that // "FollowFrom" a parent. // // [-Parent Span-] [-Child Span-] // // // [-Parent Span--] // [-Child Span-] // // // [-Parent Span-] // [-Child Span-] // // See http://opentracing.io/spec/ // // See opentracing.FollowsFrom() FollowsFromRef )
type StartSpanOption ¶
type StartSpanOption interface {
Apply(*StartSpanOptions)
}
StartSpanOption instances (zero or more) may be passed to Tracer.StartSpan.
StartSpanOption borrows from the "functional options" pattern, per http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
type StartSpanOptions ¶
type StartSpanOptions struct { // Zero or more causal references to other Spans (via their SpanContext). // If empty, start a "root" Span (i.e., start a new trace). References []SpanReference // StartTime overrides the Span's start time, or implicitly becomes // time.Now() if StartTime.IsZero(). StartTime time.Time // Tags may have zero or more entries; the restrictions on map values are // identical to those for Span.SetTag(). May be nil. // // If specified, the caller hands off ownership of Tags at // StartSpan() invocation time. Tags map[string]interface{} }
StartSpanOptions allows Tracer.StartSpan() callers and implementors a mechanism to override the start timestamp, specify Span References, and make a single Tag or multiple Tags available at Span start time.
StartSpan() callers should look at the StartSpanOption interface and implementations available in this package.
Tracer implementations can convert a slice of `StartSpanOption` instances into a `StartSpanOptions` struct like so:
func StartSpan(opName string, opts ...opentracing.StartSpanOption) { sso := opentracing.StartSpanOptions{} for _, o := range opts { o.Apply(&sso) } ... }
type StartTime ¶
StartTime is a StartSpanOption that sets an explicit start timestamp for the new Span.
func (StartTime) Apply ¶
func (t StartTime) Apply(o *StartSpanOptions)
Apply satisfies the StartSpanOption interface.
type Tag ¶
type Tag struct { Key string Value interface{} }
Tag may be passed as a StartSpanOption to add a tag to new spans, or its Set method may be used to apply the tag to an existing Span, for example:
tracer.StartSpan("opName", Tag{"Key", value})
or
Tag{"key", value}.Set(span)
func (Tag) Apply ¶
func (t Tag) Apply(o *StartSpanOptions)
Apply satisfies the StartSpanOption interface.
type Tags ¶
type Tags map[string]interface{}
Tags are a generic map from an arbitrary string key to an opaque value type. The underlying tracing system is responsible for interpreting and serializing the values.
func (Tags) Apply ¶
func (t Tags) Apply(o *StartSpanOptions)
Apply satisfies the StartSpanOption interface.
type TextMapCarrier ¶
TextMapCarrier allows the use of regular map[string]string as both TextMapWriter and TextMapReader.
func (TextMapCarrier) ForeachKey ¶
func (c TextMapCarrier) ForeachKey(handler func(key, val string) error) error
ForeachKey conforms to the TextMapReader interface.
func (TextMapCarrier) Set ¶
func (c TextMapCarrier) Set(key, val string)
Set implements Set() of opentracing.TextMapWriter
type TextMapReader ¶
type TextMapReader interface { // ForeachKey returns TextMap contents via repeated calls to the `handler` // function. If any call to `handler` returns a non-nil error, ForeachKey // terminates and returns that error. // // NOTE: The backing store for the TextMapReader may contain data unrelated // to SpanContext. As such, Inject() and Extract() implementations that // call the TextMapWriter and TextMapReader interfaces must agree on a // prefix or other convention to distinguish their own key:value pairs. // // The "foreach" callback pattern reduces unnecessary copying in some cases // and also allows implementations to hold locks while the map is read. ForeachKey(handler func(key, val string) error) error }
TextMapReader is the Extract() carrier for the TextMap builtin format. With it, the caller can decode a propagated SpanContext as entries in a map of unicode strings.
type TextMapWriter ¶
type TextMapWriter interface { // Set a key:value pair to the carrier. Multiple calls to Set() for the // same key leads to undefined behavior. // // NOTE: The backing store for the TextMapWriter may contain data unrelated // to SpanContext. As such, Inject() and Extract() implementations that // call the TextMapWriter and TextMapReader interfaces must agree on a // prefix or other convention to distinguish their own key:value pairs. Set(key, val string) }
TextMapWriter is the Inject() carrier for the TextMap builtin format. With it, the caller can encode a SpanContext for propagation as entries in a map of unicode strings.
type Tracer ¶
type Tracer interface { // Create, start, and return a new Span with the given `operationName` and // incorporate the given StartSpanOption `opts`. (Note that `opts` borrows // from the "functional options" pattern, per // http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis) // // A Span with no SpanReference options (e.g., opentracing.ChildOf() or // opentracing.FollowsFrom()) becomes the root of its own trace. // // Examples: // // var tracer opentracing.Tracer = ... // // // The root-span case: // sp := tracer.StartSpan("GetFeed") // // // The vanilla child span case: // sp := tracer.StartSpan( // "GetFeed", // opentracing.ChildOf(parentSpan.Context())) // // // All the bells and whistles: // sp := tracer.StartSpan( // "GetFeed", // opentracing.ChildOf(parentSpan.Context()), // opentracing.Tag("user_agent", loggedReq.UserAgent), // opentracing.StartTime(loggedReq.Timestamp), // ) // StartSpan(operationName string, opts ...StartSpanOption) Span // Inject() takes the `sm` SpanContext instance and injects it for // propagation within `carrier`. The actual type of `carrier` depends on // the value of `format`. // // OpenTracing defines a common set of `format` values (see BuiltinFormat), // and each has an expected carrier type. // // Other packages may declare their own `format` values, much like the keys // used by `context.Context` (see // https://godoc.org/golang.org/x/net/context#WithValue). // // Example usage (sans error handling): // // carrier := opentracing.HTTPHeadersCarrier(httpReq.Header) // err := tracer.Inject( // span.Context(), // opentracing.HttpHeaders, // carrier) // // NOTE: All opentracing.Tracer implementations MUST support all // BuiltinFormats. // // Implementations may return opentracing.ErrUnsupportedFormat if `format` // is not supported by (or not known by) the implementation. // // Implementations may return opentracing.ErrInvalidCarrier or any other // implementation-specific error if the format is supported but injection // fails anyway. // // See Tracer.Extract(). Inject(sm SpanContext, format interface{}, carrier interface{}) error // Extract() returns a SpanContext instance given `format` and `carrier`. // // OpenTracing defines a common set of `format` values (see BuiltinFormat), // and each has an expected carrier type. // // Other packages may declare their own `format` values, much like the keys // used by `context.Context` (see // https://godoc.org/golang.org/x/net/context#WithValue). // // Example usage (with StartSpan): // // // carrier := opentracing.HttpHeadersCarrier(httpReq.Header) // clientContext, err := tracer.Extract(opentracing.HttpHeaders, carrier) // // // ... assuming the ultimate goal here is to resume the trace with a // // server-side Span: // var serverSpan opentracing.Span // if err == nil { // span = tracer.StartSpan( // rpcMethodName, ext.RPCServerOption(clientContext)) // } else { // span = tracer.StartSpan(rpcMethodName) // } // // // NOTE: All opentracing.Tracer implementations MUST support all // BuiltinFormats. // // Return values: // - A successful Extract returns a SpanContext instance and a nil error // - If there was simply no SpanContext to extract in `carrier`, Extract() // returns (nil, opentracing.ErrSpanContextNotFound) // - If `format` is unsupported or unrecognized, Extract() returns (nil, // opentracing.ErrUnsupportedFormat) // - If there are more fundamental problems with the `carrier` object, // Extract() may return opentracing.ErrInvalidCarrier, // opentracing.ErrSpanContextCorrupted, or implementation-specific // errors. // // See Tracer.Inject(). Extract(format interface{}, carrier interface{}) (SpanContext, error) }
Tracer is a simple, thin interface for Span creation and SpanContext propagation.
func GlobalTracer ¶
func GlobalTracer() Tracer
GlobalTracer returns the global singleton `Tracer` implementation. Before `InitGlobalTracer()` is called, the `GlobalTracer()` is a noop implementation that drops all data handed to it.