zipkintracer

package module
v0.2.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 21, 2017 License: MIT Imports: 29 Imported by: 0

README

zipkin-go-opentracing

Travis CI CircleCI GoDoc Go Report Card Sourcegraph

OpenTracing Tracer implementation for Zipkin in Go.

Notes

This package is a low level tracing "driver" to allow OpenTracing API consumers to use Zipkin as their tracing backend. For details on how to work with spans and traces we suggest looking at the documentation and README from the OpenTracing API.

For developers interested in adding Zipkin tracing to their Go services we suggest looking at Go kit which is an excellent toolkit to instrument your distributed system with Zipkin and much more with clean separation of domains like transport, middleware / instrumentation and business logic.

Examples

For more information on zipkin-go-opentracing, please see the examples directory for usage examples as well as documentation at go doc.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Delegator delegatorType

Delegator is the format to use for DelegatingCarrier.

View Source
var ErrInvalidEndpoint = errors.New("Invalid Endpoint. Please check hostPort parameter")

ErrInvalidEndpoint will be thrown if hostPort parameter is corrupted or host can't be resolved

View Source
var ErrMissingValue = errors.New("(MISSING)")

ErrMissingValue adds a Missing Value Error when the Logging Parameters are not even in number

View Source
var (
	// SpanKindResource will be regarded as a SA annotation by Zipkin.
	SpanKindResource = otext.SpanKindEnum("resource")
)

Functions

func MaterializeWithJSON

func MaterializeWithJSON(logFields []log.Field) ([]byte, error)

MaterializeWithJSON converts log Fields into JSON string

func MaterializeWithLogFmt added in v0.2.2

func MaterializeWithLogFmt(logFields []log.Field) ([]byte, error)

MaterializeWithLogFmt converts log Fields into LogFmt string

func NewTracer

func NewTracer(recorder SpanRecorder, options ...TracerOption) (opentracing.Tracer, error)

NewTracer creates a new OpenTracing compatible Zipkin Tracer.

func StrictZipkinMaterializer added in v0.2.2

func StrictZipkinMaterializer(logFields []log.Field) ([]byte, error)

StrictZipkinMaterializer will only record a log.Field of type "event".

Types

type CollectionError

type CollectionError interface {
	Error() string
	GetErrors() []error
}

CollectionError represents an array of errors returned by one or more failed Collector methods.

type Collector

type Collector interface {
	Collect(*zipkincore.Span) error
	Close() error
}

Collector represents a Zipkin trace collector, which is probably a set of remote endpoints.

func NewHTTPCollector

func NewHTTPCollector(url string, options ...HTTPOption) (Collector, error)

NewHTTPCollector returns a new HTTP-backend Collector. url should be a http url for handle post request. timeout is passed to http client. queueSize control the maximum size of buffer of async queue. The logger is used to log errors, such as send failures;

func NewKafkaCollector

func NewKafkaCollector(addrs []string, options ...KafkaOption) (Collector, error)

NewKafkaCollector returns a new Kafka-backed Collector. addrs should be a slice of TCP endpoints of the form "host:port".

func NewScribeCollector

func NewScribeCollector(addr string, timeout time.Duration, options ...ScribeOption) (Collector, error)

NewScribeCollector returns a new Scribe-backed Collector. addr should be a TCP endpoint of the form "host:port". timeout is passed to the Thrift dial function NewTSocketFromAddrTimeout. batchSize and batchInterval control the maximum size and interval of a batch of spans; as soon as either limit is reached, the batch is sent. The logger is used to log errors, such as batch send failures; users should provide an appropriate context, if desired.

type DelegatingCarrier

type DelegatingCarrier interface {
	SetState(traceID types.TraceID, spanID uint64, parentSpanID *uint64, sampled bool, flags flag.Flags)
	State() (traceID types.TraceID, spanID uint64, parentSpanID *uint64, sampled bool, flags flag.Flags)
	SetBaggageItem(key, value string)
	GetBaggage(func(key, value string))
}

DelegatingCarrier is a flexible carrier interface which can be implemented by types which have a means of storing the trace metadata and already know how to serialize themselves (for example, protocol buffers).

type EventBaggage

type EventBaggage struct {
	Key, Value string
}

EventBaggage is received when SetBaggageItem is called.

type EventCreate

type EventCreate struct{ OperationName string }

EventCreate is emitted when a Span is created.

type EventFinish

type EventFinish RawSpan

EventFinish is received when Finish is called.

type EventLog

type EventLog opentracing.LogData

EventLog is received when Log (or one of its derivatives) is called.

DEPRECATED

type EventLogFields

type EventLogFields opentracing.LogRecord

EventLogFields is received when LogFields or LogKV is called.

type EventTag

type EventTag struct {
	Key   string
	Value interface{}
}

EventTag is received when SetTag is called.

type HTTPCollector

type HTTPCollector struct {
	// contains filtered or unexported fields
}

HTTPCollector implements Collector by forwarding spans to a http server.

func (*HTTPCollector) Close

func (c *HTTPCollector) Close() error

Close implements Collector.

func (*HTTPCollector) Collect

func (c *HTTPCollector) Collect(s *zipkincore.Span) error

Collect implements Collector.

type HTTPOption

type HTTPOption func(c *HTTPCollector)

HTTPOption sets a parameter for the HttpCollector

func HTTPBatchInterval

func HTTPBatchInterval(d time.Duration) HTTPOption

HTTPBatchInterval sets the maximum duration we will buffer traces before emitting them to the collector. The default batch interval is 1 second.

func HTTPBatchSize

func HTTPBatchSize(n int) HTTPOption

HTTPBatchSize sets the maximum batch size, after which a collect will be triggered. The default batch size is 100 traces.

func HTTPClient added in v0.2.4

func HTTPClient(client *http.Client) HTTPOption

HTTPClient sets a custom http client to use.

func HTTPLogger

func HTTPLogger(logger Logger) HTTPOption

HTTPLogger sets the logger used to report errors in the collection process. By default, a no-op logger is used, i.e. no errors are logged anywhere. It's important to set this option in a production service.

func HTTPMaxBacklog added in v0.2.3

func HTTPMaxBacklog(n int) HTTPOption

HTTPMaxBacklog sets the maximum backlog size, when batch size reaches this threshold, spans from the beginning of the batch will be disposed

func HTTPRequestCallback added in v0.2.4

func HTTPRequestCallback(rc RequestCallback) HTTPOption

HTTPRequestCallback registers a callback function to adjust the collector *http.Request before it sends the request to Zipkin.

func HTTPTimeout

func HTTPTimeout(duration time.Duration) HTTPOption

HTTPTimeout sets maximum timeout for http request.

type InMemorySpanRecorder

type InMemorySpanRecorder struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

InMemorySpanRecorder is a simple thread-safe implementation of SpanRecorder that stores all reported spans in memory, accessible via reporter.GetSpans(). It is primarily intended for testing purposes.

func NewInMemoryRecorder

func NewInMemoryRecorder() *InMemorySpanRecorder

NewInMemoryRecorder creates new InMemorySpanRecorder

func (*InMemorySpanRecorder) GetSampledSpans

func (r *InMemorySpanRecorder) GetSampledSpans() []RawSpan

GetSampledSpans returns a slice of spans accumulated so far which were sampled.

func (*InMemorySpanRecorder) GetSpans

func (r *InMemorySpanRecorder) GetSpans() []RawSpan

GetSpans returns a copy of the array of spans accumulated so far.

func (*InMemorySpanRecorder) RecordSpan

func (r *InMemorySpanRecorder) RecordSpan(span RawSpan)

RecordSpan implements the respective method of SpanRecorder.

func (*InMemorySpanRecorder) Reset

func (r *InMemorySpanRecorder) Reset()

Reset clears the internal array of spans.

type KafkaCollector

type KafkaCollector struct {
	// contains filtered or unexported fields
}

KafkaCollector implements Collector by publishing spans to a Kafka broker.

func (*KafkaCollector) Close

func (c *KafkaCollector) Close() error

Close implements Collector.

func (*KafkaCollector) Collect

func (c *KafkaCollector) Collect(s *zipkincore.Span) error

Collect implements Collector.

type KafkaOption

type KafkaOption func(c *KafkaCollector)

KafkaOption sets a parameter for the KafkaCollector

func KafkaLogger

func KafkaLogger(logger Logger) KafkaOption

KafkaLogger sets the logger used to report errors in the collection process. By default, a no-op logger is used, i.e. no errors are logged anywhere. It's important to set this option.

func KafkaProducer

func KafkaProducer(p sarama.AsyncProducer) KafkaOption

KafkaProducer sets the producer used to produce to Kafka.

func KafkaTopic

func KafkaTopic(t string) KafkaOption

KafkaTopic sets the kafka topic to attach the collector producer on.

type Logger

type Logger interface {
	Log(keyvals ...interface{}) error
}

Logger interface used by this package. This means that we accept Go kit Log compatible loggers

func LogWrapper

func LogWrapper(l *log.Logger) Logger

LogWrapper wraps a standard library logger into a Logger compatible with this package.

func NewNopLogger

func NewNopLogger() Logger

NewNopLogger provides a Logger that discards all Log data sent to it.

type LoggerFunc

type LoggerFunc func(...interface{}) error

LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If f is a function with the appropriate signature, LoggerFunc(f) is a Logger object that calls f.

func (LoggerFunc) Log

func (f LoggerFunc) Log(keyvals ...interface{}) error

Log implements Logger by calling f(keyvals...).

type MultiCollector

type MultiCollector []Collector

MultiCollector implements Collector by sending spans to all collectors.

func (MultiCollector) Close

func (c MultiCollector) Close() error

Close implements Collector.

func (MultiCollector) Collect

func (c MultiCollector) Collect(s *zipkincore.Span) error

Collect implements Collector.

type NopCollector

type NopCollector struct{}

NopCollector implements Collector but performs no work.

func (NopCollector) Close

func (NopCollector) Close() error

Close implements Collector.

func (NopCollector) Collect

func (NopCollector) Collect(*zipkincore.Span) error

Collect implements Collector.

type RawSpan

type RawSpan struct {
	// Those recording the RawSpan should also record the contents of its
	// SpanContext.
	Context SpanContext

	// The name of the "operation" this span is an instance of. (Called a "span
	// name" in some implementations)
	Operation string

	// We store <start, duration> rather than <start, end> so that only
	// one of the timestamps has global clock uncertainty issues.
	Start    time.Time
	Duration time.Duration

	// Essentially an extension mechanism. Can be used for many purposes,
	// not to be enumerated here.
	Tags opentracing.Tags

	// The span's "microlog".
	Logs []opentracing.LogRecord
}

RawSpan encapsulates all state associated with a (finished) Span.

type Recorder

type Recorder struct {
	// contains filtered or unexported fields
}

Recorder implements the SpanRecorder interface.

func (*Recorder) RecordSpan

func (r *Recorder) RecordSpan(sp RawSpan)

RecordSpan converts a RawSpan into the Zipkin representation of a span and records it to the underlying collector.

type RecorderOption added in v0.2.2

type RecorderOption func(r *Recorder)

RecorderOption allows for functional options.

func WithJSONMaterializer added in v0.2.2

func WithJSONMaterializer() RecorderOption

WithJSONMaterializer will convert OpenTracing Log fields to a JSON representation.

func WithLogFmtMaterializer added in v0.2.2

func WithLogFmtMaterializer() RecorderOption

WithLogFmtMaterializer will convert OpenTracing Log fields to a LogFmt representation.

func WithStrictMaterializer added in v0.2.2

func WithStrictMaterializer() RecorderOption

WithStrictMaterializer will only record event Log fields and discard the rest.

type RequestCallback added in v0.2.4

type RequestCallback func(*http.Request)

RequestCallback receives the initialized request from the Collector before sending it over the wire. This allows one to plug in additional headers or do other customization.

type Sampler

type Sampler func(id uint64) bool

Sampler functions return if a Zipkin span should be sampled, based on its traceID.

func ModuloSampler

func ModuloSampler(mod uint64) Sampler

ModuloSampler provides a typical OpenTracing type Sampler.

func NewBoundarySampler

func NewBoundarySampler(rate float64, salt int64) Sampler

NewBoundarySampler is appropriate for high-traffic instrumentation who provision random trace ids, and make the sampling decision only once. It defends against nodes in the cluster selecting exactly the same ids.

func NewCountingSampler

func NewCountingSampler(rate float64) Sampler

NewCountingSampler is appropriate for low-traffic instrumentation or those who do not provision random trace ids. It is not appropriate for collectors as the sampling decision isn't idempotent (consistent based on trace id).

type ScribeCollector

type ScribeCollector struct {
	// contains filtered or unexported fields
}

ScribeCollector implements Collector by forwarding spans to a Scribe service, in batches.

func (*ScribeCollector) Close

func (c *ScribeCollector) Close() error

Close implements Collector.

func (*ScribeCollector) Collect

func (c *ScribeCollector) Collect(s *zipkincore.Span) error

Collect implements Collector.

type ScribeOption

type ScribeOption func(s *ScribeCollector)

ScribeOption sets a parameter for the StdlibAdapter.

func ScribeBatchInterval

func ScribeBatchInterval(d time.Duration) ScribeOption

ScribeBatchInterval sets the maximum duration we will buffer traces before emitting them to the collector. The default batch interval is 1 second.

func ScribeBatchSize

func ScribeBatchSize(n int) ScribeOption

ScribeBatchSize sets the maximum batch size, after which a collect will be triggered. The default batch size is 100 traces.

func ScribeCategory

func ScribeCategory(category string) ScribeOption

ScribeCategory sets the Scribe category used to transmit the spans.

func ScribeLogger

func ScribeLogger(logger Logger) ScribeOption

ScribeLogger sets the logger used to report errors in the collection process. By default, a no-op logger is used, i.e. no errors are logged anywhere. It's important to set this option in a production service.

func ScribeMaxBacklog added in v0.2.3

func ScribeMaxBacklog(n int) ScribeOption

ScribeMaxBacklog sets the maximum backlog size, when batch size reaches this threshold, spans from the beginning of the batch will be disposed

type Span

type Span interface {
	opentracing.Span

	// Operation names the work done by this span instance
	Operation() string

	// Start indicates when the span began
	Start() time.Time
}

Span provides access to the essential details of the span, for use by zipkintracer consumers. These methods may only be called prior to (*opentracing.Span).Finish().

type SpanContext

type SpanContext struct {
	// A probabilistically unique identifier for a [multi-span] trace.
	TraceID types.TraceID

	// A probabilistically unique identifier for a span.
	SpanID uint64

	// Whether the trace is sampled.
	Sampled bool

	// The span's associated baggage.
	Baggage map[string]string // initialized on first use

	// The SpanID of this Context's parent, or nil if there is no parent.
	ParentSpanID *uint64

	// Flags provides the ability to create and communicate feature flags.
	Flags flag.Flags

	// Whether the span is owned by the current process
	Owner bool
}

SpanContext holds the basic Span metadata.

func (SpanContext) ForeachBaggageItem

func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool)

ForeachBaggageItem belongs to the opentracing.SpanContext interface

func (SpanContext) WithBaggageItem

func (c SpanContext) WithBaggageItem(key, val string) SpanContext

WithBaggageItem returns an entirely new basictracer SpanContext with the given key:value baggage pair set.

type SpanEvent

type SpanEvent interface{}

A SpanEvent is emitted when a mutating command is called on a Span.

type SpanRecorder

type SpanRecorder interface {
	// Implementations must determine whether and where to store `span`.
	RecordSpan(span RawSpan)
}

A SpanRecorder handles all of the `RawSpan` data generated via an associated `Tracer` (see `NewStandardTracer`) instance. It also names the containing process and provides access to a straightforward tag map.

func NewRecorder

func NewRecorder(c Collector, debug bool, hostPort, serviceName string, options ...RecorderOption) SpanRecorder

NewRecorder creates a new Zipkin Recorder backed by the provided Collector.

hostPort and serviceName allow you to set the default Zipkin endpoint information which will be added to the application's standard core annotations. hostPort will be resolved into an IPv4 and/or IPv6 address and Port number, serviceName will be used as the application's service identifier.

If application does not listen for incoming requests or an endpoint Context does not involve network address and/or port these cases can be solved like this:

# port is not applicable:
NewRecorder(c, debug, "192.168.1.12:0", "ServiceA")

# network address and port are not applicable:
NewRecorder(c, debug, "0.0.0.0:0", "ServiceB")

type Tracer

type Tracer interface {
	opentracing.Tracer

	// Options gets the Options used in New() or NewWithOptions().
	Options() TracerOptions
}

Tracer extends the opentracing.Tracer interface with methods to probe implementation state, for use by zipkintracer consumers.

type TracerOption

type TracerOption func(opts *TracerOptions) error

TracerOption allows for functional options. See: http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

func ClientServerSameSpan

func ClientServerSameSpan(val bool) TracerOption

ClientServerSameSpan allows to place client-side and server-side annotations for a RPC call in the same span (Zipkin V1 behavior) or different spans (more in line with other tracing solutions). By default this Tracer uses shared host spans (so client-side and server-side in the same span). If using separate spans you might run into trouble with Zipkin V1 as clock skew issues can't be remedied at Zipkin server side.

func DebugAssertSingleGoroutine

func DebugAssertSingleGoroutine(val bool) TracerOption

DebugAssertSingleGoroutine option

func DebugAssertUseAfterFinish

func DebugAssertUseAfterFinish(val bool) TracerOption

DebugAssertUseAfterFinish option

func DebugMode

func DebugMode(val bool) TracerOption

DebugMode allows to set the tracer to Zipkin debug mode

func DropAllLogs

func DropAllLogs(dropAllLogs bool) TracerOption

DropAllLogs option

func EnableSpanPool

func EnableSpanPool(val bool) TracerOption

EnableSpanPool ...

func NewSpanEventListener

func NewSpanEventListener(f func() func(SpanEvent)) TracerOption

NewSpanEventListener option

func TraceID128Bit added in v0.2.0

func TraceID128Bit(val bool) TracerOption

TraceID128Bit option

func TrimUnsampledSpans

func TrimUnsampledSpans(trim bool) TracerOption

TrimUnsampledSpans option

func WithLogger

func WithLogger(logger Logger) TracerOption

WithLogger option

func WithMaxLogsPerSpan added in v0.2.2

func WithMaxLogsPerSpan(limit int) TracerOption

WithMaxLogsPerSpan option

func WithSampler

func WithSampler(sampler Sampler) TracerOption

WithSampler allows one to add a Sampler function

type TracerOptions

type TracerOptions struct {
	// contains filtered or unexported fields
}

TracerOptions allows creating a customized Tracer.

Directories

Path Synopsis
_thrift
examples
middleware
Package middleware provides some usable transport middleware to deal with propagating Zipkin traces across service boundaries.
Package middleware provides some usable transport middleware to deal with propagating Zipkin traces across service boundaries.
Package wire is a generated protocol buffer package.
Package wire is a generated protocol buffer package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL