context.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Unless explicitly stated otherwise all files in this repository are licensed
  2. // under the Apache License Version 2.0.
  3. // This product includes software developed at Datadog (https://www.datadoghq.com/).
  4. // Copyright 2016 Datadog, Inc.
  5. package tracer
  6. import (
  7. "context"
  8. "gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
  9. "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/internal"
  10. )
  11. type contextKey struct{}
  12. var activeSpanKey = contextKey{}
  13. // ContextWithSpan returns a copy of the given context which includes the span s.
  14. func ContextWithSpan(ctx context.Context, s Span) context.Context {
  15. return context.WithValue(ctx, activeSpanKey, s)
  16. }
  17. // SpanFromContext returns the span contained in the given context. A second return
  18. // value indicates if a span was found in the context. If no span is found, a no-op
  19. // span is returned.
  20. func SpanFromContext(ctx context.Context) (Span, bool) {
  21. if ctx == nil {
  22. return &internal.NoopSpan{}, false
  23. }
  24. v := ctx.Value(activeSpanKey)
  25. if s, ok := v.(ddtrace.Span); ok {
  26. return s, true
  27. }
  28. return &internal.NoopSpan{}, false
  29. }
  30. // StartSpanFromContext returns a new span with the given operation name and options. If a span
  31. // is found in the context, it will be used as the parent of the resulting span. If the ChildOf
  32. // option is passed, it will only be used as the parent if there is no span found in `ctx`.
  33. func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context) {
  34. // copy opts in case the caller reuses the slice in parallel
  35. // we will add at least 1, at most 2 items
  36. optsLocal := make([]StartSpanOption, len(opts), len(opts)+2)
  37. copy(optsLocal, opts)
  38. if ctx == nil {
  39. // default to context.Background() to avoid panics on Go >= 1.15
  40. ctx = context.Background()
  41. } else if s, ok := SpanFromContext(ctx); ok {
  42. optsLocal = append(optsLocal, ChildOf(s.Context()))
  43. }
  44. optsLocal = append(optsLocal, withContext(ctx))
  45. s := StartSpan(operationName, optsLocal...)
  46. if span, ok := s.(*span); ok && span.pprofCtxActive != nil {
  47. // If pprof labels were applied for this span, use the derived ctx that
  48. // includes them. Otherwise a child of this span wouldn't be able to
  49. // correctly restore the labels of its parent when it finishes.
  50. ctx = span.pprofCtxActive
  51. }
  52. return s, ContextWithSpan(ctx, s)
  53. }