2020-03-24 07:41:10 +02:00
|
|
|
// Copyright The OpenTelemetry Authors
|
2019-06-14 22:09:41 +02:00
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2019-07-12 00:28:38 +02:00
|
|
|
package trace
|
2019-06-14 20:37:05 +02:00
|
|
|
|
2019-07-03 01:21:24 +02:00
|
|
|
import (
|
2019-07-12 00:28:38 +02:00
|
|
|
"context"
|
2019-07-03 01:21:24 +02:00
|
|
|
)
|
2019-06-14 20:37:05 +02:00
|
|
|
|
2020-02-04 18:55:03 +02:00
|
|
|
type traceContextKeyType int
|
2019-07-12 00:28:38 +02:00
|
|
|
|
2020-02-04 18:55:03 +02:00
|
|
|
const (
|
|
|
|
currentSpanKey traceContextKeyType = iota
|
|
|
|
remoteContextKey
|
|
|
|
)
|
2019-06-14 20:37:05 +02:00
|
|
|
|
2020-02-04 18:55:03 +02:00
|
|
|
// ContextWithSpan creates a new context with a current span set to
|
|
|
|
// the passed span.
|
2019-12-11 18:51:32 +02:00
|
|
|
func ContextWithSpan(ctx context.Context, span Span) context.Context {
|
2019-07-12 00:28:38 +02:00
|
|
|
return context.WithValue(ctx, currentSpanKey, span)
|
2019-07-03 01:21:24 +02:00
|
|
|
}
|
|
|
|
|
2020-02-04 18:55:03 +02:00
|
|
|
// SpanFromContext returns the current span stored in the context.
|
2019-12-11 18:51:32 +02:00
|
|
|
func SpanFromContext(ctx context.Context) Span {
|
2019-07-12 00:28:38 +02:00
|
|
|
if span, has := ctx.Value(currentSpanKey).(Span); has {
|
|
|
|
return span
|
|
|
|
}
|
2019-08-14 01:03:41 +02:00
|
|
|
return NoopSpan{}
|
2019-06-14 20:37:05 +02:00
|
|
|
}
|
2020-02-04 18:55:03 +02:00
|
|
|
|
|
|
|
// ContextWithRemoteSpanContext creates a new context with a remote
|
|
|
|
// span context set to the passed span context.
|
2020-05-02 14:17:11 +02:00
|
|
|
func ContextWithRemoteSpanContext(ctx context.Context, sc SpanContext) context.Context {
|
2020-02-04 18:55:03 +02:00
|
|
|
return context.WithValue(ctx, remoteContextKey, sc)
|
|
|
|
}
|
|
|
|
|
|
|
|
// RemoteSpanContextFromContext returns the remote span context stored
|
|
|
|
// in the context.
|
2020-05-02 14:17:11 +02:00
|
|
|
func RemoteSpanContextFromContext(ctx context.Context) SpanContext {
|
|
|
|
if sc, ok := ctx.Value(remoteContextKey).(SpanContext); ok {
|
2020-02-04 18:55:03 +02:00
|
|
|
return sc
|
|
|
|
}
|
2020-05-02 14:17:11 +02:00
|
|
|
return EmptySpanContext()
|
2020-02-04 18:55:03 +02:00
|
|
|
}
|