tracing.go 7.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
// Copyright 2020 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package tracing

import (
	"bufio"
	"bytes"
	"context"
	"errors"
	"io"
13
	"net/http"
14 15
	"time"

16
	"github.com/ethersphere/bee/pkg/logging"
17 18
	"github.com/ethersphere/bee/pkg/p2p"
	"github.com/opentracing/opentracing-go"
19
	"github.com/sirupsen/logrus"
20 21 22 23 24 25 26 27 28 29 30 31 32
	"github.com/uber/jaeger-client-go"
	"github.com/uber/jaeger-client-go/config"
)

var (
	// ErrContextNotFound is returned when tracing context is not present
	// in p2p Headers or context.
	ErrContextNotFound = errors.New("tracing context not found")

	// noopTracer is the tracer that does nothing to handle a nil Tracer usage.
	noopTracer = &Tracer{tracer: new(opentracing.NoopTracer)}
)

acud's avatar
acud committed
33 34 35
// contextKey is used to reference a tracing context span as context value.
type contextKey struct{}

36
// LogField is the key in log message field that holds tracing id value.
37
const LogField = "traceID"
38

39 40 41 42 43 44 45 46
const (
	// TraceContextHeaderName is the http header name used to propagate tracing context.
	TraceContextHeaderName = "swarm-trace-id"

	// TraceBaggageHeaderPrefix is the prefix for http headers used to propagate baggage.
	TraceBaggageHeaderPrefix = "swarmctx-"
)

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
// Tracer connect to a tracing server and handles tracing spans and contexts
// by using opentracing Tracer.
type Tracer struct {
	tracer opentracing.Tracer
}

// Options are optional parameters for Tracer constructor.
type Options struct {
	Enabled     bool
	Endpoint    string
	ServiceName string
}

// NewTracer creates a new Tracer and returns a closer which needs to be closed
// when the Tracer is no longer used to flush remaining traces.
func NewTracer(o *Options) (*Tracer, io.Closer, error) {
	if o == nil {
		o = new(Options)
	}

	cfg := config.Configuration{
		Disabled:    !o.Enabled,
		ServiceName: o.ServiceName,
		Sampler: &config.SamplerConfig{
			Type:  jaeger.SamplerTypeConst,
			Param: 1,
		},
		Reporter: &config.ReporterConfig{
			LogSpans:            true,
			BufferFlushInterval: 1 * time.Second,
			LocalAgentHostPort:  o.Endpoint,
		},
79 80 81 82
		Headers: &jaeger.HeadersConfig{
			TraceContextHeaderName:   TraceContextHeaderName,
			TraceBaggageHeaderPrefix: TraceBaggageHeaderPrefix,
		},
83 84 85 86 87 88 89 90 91 92
	}

	t, closer, err := cfg.NewTracer()
	if err != nil {
		return nil, nil, err
	}
	return &Tracer{tracer: t}, closer, nil
}

// StartSpanFromContext starts a new tracing span that is either a root one or a
93
// child of existing one from the provided Context. If logger is provided, a new
94
// log Entry will be returned with "traceID" log field.
95
func (t *Tracer) StartSpanFromContext(ctx context.Context, operationName string, l logging.Logger, opts ...opentracing.StartSpanOption) (opentracing.Span, *logrus.Entry, context.Context) {
96 97 98 99 100 101 102 103 104 105 106
	if t == nil {
		t = noopTracer
	}

	var span opentracing.Span
	if parentContext := FromContext(ctx); parentContext != nil {
		opts = append(opts, opentracing.ChildOf(parentContext))
		span = t.tracer.StartSpan(operationName, opts...)
	} else {
		span = t.tracer.StartSpan(operationName, opts...)
	}
107 108
	sc := span.Context()
	return span, loggerWithTraceID(sc, l), WithContext(ctx, sc)
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
}

// AddContextHeader adds a tracing span context to provided p2p Headers from
// the go context. If the tracing span context is not present in go context,
// ErrContextNotFound is returned.
func (t *Tracer) AddContextHeader(ctx context.Context, headers p2p.Headers) error {
	if t == nil {
		t = noopTracer
	}

	c := FromContext(ctx)
	if c == nil {
		return ErrContextNotFound
	}

	var b bytes.Buffer
	w := bufio.NewWriter(&b)
	if err := t.tracer.Inject(c, opentracing.Binary, w); err != nil {
		return err
	}
	if err := w.Flush(); err != nil {
		return err
	}

	headers[p2p.HeaderNameTracingSpanContext] = b.Bytes()

	return nil
}

// FromHeaders returns tracing span context from p2p Headers. If the tracing
// span context is not present in go context, ErrContextNotFound is returned.
func (t *Tracer) FromHeaders(headers p2p.Headers) (opentracing.SpanContext, error) {
	if t == nil {
		t = noopTracer
	}

	v := headers[p2p.HeaderNameTracingSpanContext]
	if v == nil {
		return nil, ErrContextNotFound
	}
	c, err := t.tracer.Extract(opentracing.Binary, bytes.NewReader(v))
	if err != nil {
		if errors.Is(err, opentracing.ErrSpanContextNotFound) {
			return nil, ErrContextNotFound
		}
		return nil, err
	}

	return c, nil
}

// WithContextFromHeaders returns a new context with injected tracing span
// context if they are found in p2p Headers. If the tracing span context is not
// present in go context, ErrContextNotFound is returned.
func (t *Tracer) WithContextFromHeaders(ctx context.Context, headers p2p.Headers) (context.Context, error) {
	if t == nil {
		t = noopTracer
	}

	c, err := t.FromHeaders(headers)
	if err != nil {
		return ctx, err
	}
	return WithContext(ctx, c), nil
}

175 176 177 178 179 180 181 182 183 184 185 186 187 188
// AddContextHTTPHeader adds a tracing span context to provided HTTP headers
// from the go context. If the tracing span context is not present in
// go context, ErrContextNotFound is returned.
func (t *Tracer) AddContextHTTPHeader(ctx context.Context, headers http.Header) error {
	if t == nil {
		t = noopTracer
	}

	c := FromContext(ctx)
	if c == nil {
		return ErrContextNotFound
	}

	carrier := opentracing.HTTPHeadersCarrier(headers)
acud's avatar
acud committed
189
	return t.tracer.Inject(c, opentracing.HTTPHeaders, carrier)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
}

// FromHTTPHeaders returns tracing span context from HTTP headers. If the tracing
// span context is not present in go context, ErrContextNotFound is returned.
func (t *Tracer) FromHTTPHeaders(headers http.Header) (opentracing.SpanContext, error) {
	if t == nil {
		t = noopTracer
	}

	carrier := opentracing.HTTPHeadersCarrier(headers)
	c, err := t.tracer.Extract(opentracing.HTTPHeaders, carrier)
	if err != nil {
		if errors.Is(err, opentracing.ErrSpanContextNotFound) {
			return nil, ErrContextNotFound
		}
		return nil, err
	}

	return c, nil
}

// WithContextFromHTTPHeaders returns a new context with injected tracing span
// context if they are found in HTTP headers. If the tracing span context is not
// present in go context, ErrContextNotFound is returned.
func (t *Tracer) WithContextFromHTTPHeaders(ctx context.Context, headers http.Header) (context.Context, error) {
	if t == nil {
		t = noopTracer
	}

	c, err := t.FromHTTPHeaders(headers)
	if err != nil {
		return ctx, err
	}

	return WithContext(ctx, c), nil
}

227 228
// WithContext adds tracing span context to go context.
func WithContext(ctx context.Context, c opentracing.SpanContext) context.Context {
acud's avatar
acud committed
229
	return context.WithValue(ctx, contextKey{}, c)
230 231 232 233 234
}

// FromContext return tracing span context from go context. If the tracing span
// context is not present in go context, nil is returned.
func FromContext(ctx context.Context) opentracing.SpanContext {
acud's avatar
acud committed
235
	c, ok := ctx.Value(contextKey{}).(opentracing.SpanContext)
236 237 238 239 240
	if !ok {
		return nil
	}
	return c
}
241

242
// NewLoggerWithTraceID creates a new log Entry with "traceID" field added if it
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
// exists in tracing span context stored from go context.
func NewLoggerWithTraceID(ctx context.Context, l logging.Logger) *logrus.Entry {
	return loggerWithTraceID(FromContext(ctx), l)
}

func loggerWithTraceID(sc opentracing.SpanContext, l logging.Logger) *logrus.Entry {
	if l == nil {
		return nil
	}
	jsc, ok := sc.(jaeger.SpanContext)
	if !ok {
		return l.NewEntry()
	}
	traceID := jsc.TraceID()
	if !traceID.IsValid() {
		return l.NewEntry()
	}
	return l.WithField(LogField, traceID.String())
}