Remove getCurrentContext and withSpan from Tracer (#1809)

* Remove getCurrentContext and withSpan from Tracer

Signed-off-by: Bogdan Drutu <bogdandrutu@gmail.com>

* Remove old java7 example

Signed-off-by: Bogdan Drutu <bogdandrutu@gmail.com>
This commit is contained in:
Bogdan Drutu 2020-10-15 10:58:41 -07:00 committed by GitHub
parent 2d0f91b538
commit b73a063901
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 140 additions and 279 deletions

View File

@ -51,7 +51,7 @@ To create a basic span, you only need to specify the name of the span.
The start and end time of the span is automatically set by the OpenTelemetry SDK. The start and end time of the span is automatically set by the OpenTelemetry SDK.
```java ```java
Span span = tracer.spanBuilder("my span").startSpan(); Span span = tracer.spanBuilder("my span").startSpan();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
// your use case // your use case
... ...
} catch (Throwable t) { } catch (Throwable t) {
@ -87,7 +87,7 @@ The OpenTelemetry API offers also an automated way to propagate the `parentSpan`
```java ```java
void a() { void a() {
Span parentSpan = tracer.spanBuilder("a").startSpan(); Span parentSpan = tracer.spanBuilder("a").startSpan();
try(Scope scope = tracer.withSpan(parentSpan)) { try(Scope scope = TracingContextUtils.currentContextWith(parentSpan)) {
b(); b();
} finally { } finally {
parentSpan.end(); parentSpan.end();
@ -96,9 +96,9 @@ void a() {
void b() { void b() {
Span childSpan = tracer.spanBuilder("b") Span childSpan = tracer.spanBuilder("b")
// NOTE: setParent(parentSpan) is not required; // NOTE: setParent(parentSpan) is not required;
// `tracer.getCurrentSpan()` is automatically added as parent // `TracingContextUtils.getCurrentSpan()` is automatically added as parent
.startSpan(); .startSpan();
try(Scope scope = tracer.withSpan(childSpan)) { try(Scope scope = TracingContextUtils.currentContextWith(childSpan)) {
// do stuff // do stuff
} finally { } finally {
childSpan.end(); childSpan.end();
@ -185,7 +185,7 @@ TextMapPropagator.Setter<HttpURLConnection> setter =
URL url = new URL("http://127.0.0.1:8080/resource"); URL url = new URL("http://127.0.0.1:8080/resource");
Span outGoing = tracer.spanBuilder("/resource").setSpanKind(Span.Kind.CLIENT).startSpan(); Span outGoing = tracer.spanBuilder("/resource").setSpanKind(Span.Kind.CLIENT).startSpan();
try (Scope scope = tracer.withSpan(outGoing)) { try (Scope scope = TracingContextUtils.currentContextWith(outGoing)) {
// Semantic Convention. // Semantic Convention.
// (Observe that to set these, Span does not *need* to be the current instance.) // (Observe that to set these, Span does not *need* to be the current instance.)
outGoing.setAttribute("http.method", "GET"); outGoing.setAttribute("http.method", "GET");

View File

@ -34,7 +34,7 @@ public class DefaultTracerBenchmarks {
@Warmup(iterations = 5, time = 1) @Warmup(iterations = 5, time = 1)
public void measureFullSpanLifecycle() { public void measureFullSpanLifecycle() {
span = tracer.spanBuilder("span").startSpan(); span = tracer.spanBuilder("span").startSpan();
try (io.opentelemetry.context.Scope ignored = tracer.withSpan(span)) { try (io.opentelemetry.context.Scope ignored = TracingContextUtils.currentContextWith(span)) {
// no-op // no-op
} finally { } finally {
span.end(); span.end();
@ -59,7 +59,7 @@ public class DefaultTracerBenchmarks {
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1) @Warmup(iterations = 5, time = 1)
public void measureScopeLifecycle() { public void measureScopeLifecycle() {
try (io.opentelemetry.context.Scope ignored = tracer.withSpan(span)) { try (io.opentelemetry.context.Scope ignored = TracingContextUtils.currentContextWith(span)) {
// no-op // no-op
} }
} }
@ -71,7 +71,7 @@ public class DefaultTracerBenchmarks {
@OutputTimeUnit(TimeUnit.NANOSECONDS) @OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 1) @Warmup(iterations = 5, time = 1)
public void measureGetCurrentSpan() { public void measureGetCurrentSpan() {
tracer.getCurrentSpan(); TracingContextUtils.getCurrentSpan();
} }
@TearDown(Level.Iteration) @TearDown(Level.Iteration)

View File

@ -8,7 +8,6 @@ package io.opentelemetry.trace;
import io.opentelemetry.common.AttributeKey; import io.opentelemetry.common.AttributeKey;
import io.opentelemetry.common.Attributes; import io.opentelemetry.common.Attributes;
import io.opentelemetry.context.Context; import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.internal.Utils; import io.opentelemetry.internal.Utils;
import java.util.Objects; import java.util.Objects;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -28,16 +27,6 @@ public final class DefaultTracer implements Tracer {
return INSTANCE; return INSTANCE;
} }
@Override
public Span getCurrentSpan() {
return TracingContextUtils.getCurrentSpan();
}
@Override
public Scope withSpan(Span span) {
return TracingContextUtils.currentContextWith(span);
}
@Override @Override
public Span.Builder spanBuilder(String spanName) { public Span.Builder spanBuilder(String spanName) {
return NoopSpanBuilder.create(spanName); return NoopSpanBuilder.create(spanName);

View File

@ -299,8 +299,8 @@ public interface Span {
* void doWork { * void doWork {
* // Create a Span as a child of the current Span. * // Create a Span as a child of the current Span.
* Span span = tracer.spanBuilder("MyChildSpan").startSpan(); * Span span = tracer.spanBuilder("MyChildSpan").startSpan();
* try (Scope ss = tracer.withSpan(span)) { * try (Scope ss = TracingContextUtils.currentContextWith(span)) {
* tracer.getCurrentSpan().addEvent("my event"); * TracingContextUtils.getCurrentSpan().addEvent("my event");
* doSomeWork(); // Here the new span is in the current Context, so it can be used * doSomeWork(); // Here the new span is in the current Context, so it can be used
* // implicitly anywhere down the stack. * // implicitly anywhere down the stack.
* } finally { * } finally {
@ -327,8 +327,8 @@ public interface Span {
* } * }
* *
* public void onExecuteHandler(ServerCallHandler serverCallHandler) { * public void onExecuteHandler(ServerCallHandler serverCallHandler) {
* try (Scope ws = tracer.withSpan(mySpan)) { * try (Scope ws = TracingContextUtils.currentContextWith(mySpan)) {
* tracer.getCurrentSpan().addEvent("Start rpc execution."); * TracingContextUtils.getCurrentSpan().addEvent("Start rpc execution.");
* serverCallHandler.run(); // Here the new span is in the current Context, so it can be * serverCallHandler.run(); // Here the new span is in the current Context, so it can be
* // used implicitly anywhere down the stack. * // used implicitly anywhere down the stack.
* } * }

View File

@ -5,8 +5,6 @@
package io.opentelemetry.trace; package io.opentelemetry.trace;
import com.google.errorprone.annotations.MustBeClosed;
import io.opentelemetry.context.Scope;
import javax.annotation.concurrent.ThreadSafe; import javax.annotation.concurrent.ThreadSafe;
/** /**
@ -27,10 +25,10 @@ import javax.annotation.concurrent.ThreadSafe;
* private static final Tracer tracer = OpenTelemetry.getTracer(); * private static final Tracer tracer = OpenTelemetry.getTracer();
* void doWork() { * void doWork() {
* Span span = tracer.spanBuilder("MyClass.DoWork").startSpan(); * Span span = tracer.spanBuilder("MyClass.DoWork").startSpan();
* try(Scope ss = tracer.withSpan(span)) { * try(Scope ss = TracingContextUtils.currentContextWith(span)) {
* tracer.getCurrentSpan().addEvent("Starting the work."); * TracingContextUtils.getCurrentSpan().addEvent("Starting the work.");
* doWorkInternal(); * doWorkInternal();
* tracer.getCurrentSpan().addEvent("Finished working."); * TracingContextUtils.getCurrentSpan().addEvent("Finished working.");
* } finally { * } finally {
* span.end(); * span.end();
* } * }
@ -59,72 +57,6 @@ import javax.annotation.concurrent.ThreadSafe;
*/ */
@ThreadSafe @ThreadSafe
public interface Tracer { public interface Tracer {
/**
* Gets the current Span from the current Context.
*
* <p>To install a {@link Span} to the current Context use {@link #withSpan(Span)}.
*
* <p>startSpan methods do NOT modify the current Context {@code Span}.
*
* @return a default {@code Span} that does nothing and has an invalid {@link SpanContext} if no
* {@code Span} is associated with the current Context, otherwise the current {@code Span}
* from the Context.
*/
Span getCurrentSpan();
/**
* Enters the scope of code where the given {@link Span} is in the current Context, and returns an
* object that represents that scope. The scope is exited when the returned object is closed.
*
* <p>Supports try-with-resource idiom.
*
* <p>Can be called with {@code Span.getPropagated(span.getContext())} to enter a scope of code
* where tracing is stopped.
*
* <p>Example of usage:
*
* <pre>{@code
* private static Tracer tracer = OpenTelemetry.getTracer();
* void doWork() {
* // Create a Span as a child of the current Span.
* Span span = tracer.spanBuilder("my span").startSpan();
* try (Scope ws = tracer.withSpan(span)) {
* tracer.getCurrentSpan().addEvent("my event");
* doSomeOtherWork(); // Here "span" is the current Span.
* }
* span.end();
* }
* }</pre>
*
* <p>Prior to Java SE 7, you can use a finally block to ensure that a resource is closed
* regardless of whether the try statement completes normally or abruptly.
*
* <p>Example of usage prior to Java SE7:
*
* <pre>{@code
* private static Tracer tracer = OpenTelemetry.getTracer();
* void doWork() {
* // Create a Span as a child of the current Span.
* Span span = tracer.spanBuilder("my span").startSpan();
* Scope ws = tracer.withSpan(span);
* try {
* tracer.getCurrentSpan().addEvent("my event");
* doSomeOtherWork(); // Here "span" is the current Span.
* } finally {
* ws.close();
* }
* span.end();
* }
* }</pre>
*
* @param span The {@link Span} to be set to the current Context.
* @return an object that defines a scope where the given {@link Span} will be set to the current
* Context.
* @throws NullPointerException if {@code span} is {@code null}.
*/
@MustBeClosed
Scope withSpan(Span span);
/** /**
* Returns a {@link Span.Builder} to create and start a new {@link Span}. * Returns a {@link Span.Builder} to create and start a new {@link Span}.
* *

View File

@ -5,6 +5,7 @@
package io.opentelemetry.trace; package io.opentelemetry.trace;
import com.google.errorprone.annotations.MustBeClosed;
import io.opentelemetry.context.Context; import io.opentelemetry.context.Context;
import io.opentelemetry.context.ContextKey; import io.opentelemetry.context.ContextKey;
import io.opentelemetry.context.Scope; import io.opentelemetry.context.Scope;
@ -66,9 +67,25 @@ public final class TracingContextUtils {
* Returns a new {@link Scope} encapsulating the provided {@link Span} added to the current {@code * Returns a new {@link Scope} encapsulating the provided {@link Span} added to the current {@code
* Context}. * Context}.
* *
* <p>Example of usage:
*
* <pre>{@code
* private static Tracer tracer = OpenTelemetry.getTracer();
* void doWork() {
* // Create a Span as a child of the current Span.
* Span span = tracer.spanBuilder("my span").startSpan();
* try (Scope ws = TracingContextUtils.currentContextWith(span)) {
* TracingContextUtils.getCurrentSpan().addEvent("my event");
* doSomeOtherWork(); // Here "span" is the current Span.
* }
* span.end();
* }
* }</pre>
*
* @param span the {@link Span} to be added to the current {@code Context}. * @param span the {@link Span} to be added to the current {@code Context}.
* @return the {@link Scope} for the updated {@code Context}. * @return the {@link Scope} for the updated {@code Context}.
*/ */
@MustBeClosed
public static Scope currentContextWith(Span span) { public static Scope currentContextWith(Span span) {
return withSpan(span, io.opentelemetry.context.Context.current()).makeCurrent(); return withSpan(span, io.opentelemetry.context.Context.current()).makeCurrent();
} }

View File

@ -246,18 +246,6 @@ class OpenTelemetryTest {
return get(instrumentationName); return get(instrumentationName);
} }
@Nullable
@Override
public Span getCurrentSpan() {
return null;
}
@Nullable
@Override
public Scope withSpan(Span span) {
return null;
}
@Nullable @Nullable
@Override @Override
public Span.Builder spanBuilder(String spanName) { public Span.Builder spanBuilder(String spanName) {

View File

@ -9,7 +9,6 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertThrows;
import io.opentelemetry.context.Context; import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
/** Unit tests for {@link DefaultTracer}. */ /** Unit tests for {@link DefaultTracer}. */
@ -29,20 +28,6 @@ class DefaultTracerTest {
TraceFlags.getDefault(), TraceFlags.getDefault(),
TraceState.getDefault()); TraceState.getDefault());
@Test
void defaultGetCurrentSpan() {
assertThat(defaultTracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test
void getCurrentSpan_WithSpan() {
assertThat(defaultTracer.getCurrentSpan().getContext().isValid()).isFalse();
try (Scope ws = defaultTracer.withSpan(Span.getInvalid())) {
assertThat(defaultTracer.getCurrentSpan().getContext().isValid()).isFalse();
}
assertThat(defaultTracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test @Test
void spanBuilderWithName_NullName() { void spanBuilderWithName_NullName() {
assertThrows(NullPointerException.class, () -> defaultTracer.spanBuilder(null)); assertThrows(NullPointerException.class, () -> defaultTracer.spanBuilder(null));
@ -53,21 +38,6 @@ class DefaultTracerTest {
assertThat(defaultTracer.spanBuilder(SPAN_NAME).startSpan().getContext().isValid()).isFalse(); assertThat(defaultTracer.spanBuilder(SPAN_NAME).startSpan().getContext().isValid()).isFalse();
} }
@Test
void testInProcessContext() {
Span span = defaultTracer.spanBuilder(SPAN_NAME).startSpan();
try (Scope scope = defaultTracer.withSpan(span)) {
assertThat(defaultTracer.getCurrentSpan()).isEqualTo(span);
Span secondSpan = defaultTracer.spanBuilder(SPAN_NAME).startSpan();
try (Scope secondScope = defaultTracer.withSpan(secondSpan)) {
assertThat(defaultTracer.getCurrentSpan()).isEqualTo(secondSpan);
} finally {
assertThat(defaultTracer.getCurrentSpan()).isEqualTo(span);
}
}
assertThat(defaultTracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test @Test
void testSpanContextPropagationExplicitParent() { void testSpanContextPropagationExplicitParent() {
Span span = Span span =
@ -99,8 +69,7 @@ class DefaultTracerTest {
@Test @Test
void testSpanContextPropagation_nullContext() { void testSpanContextPropagation_nullContext() {
assertThrows( assertThrows(
NullPointerException.class, NullPointerException.class, () -> defaultTracer.spanBuilder(SPAN_NAME).setParent(null));
() -> defaultTracer.spanBuilder(SPAN_NAME).setParent((Context) null));
} }
@Test @Test
@ -126,22 +95,4 @@ class DefaultTracerTest {
Span span = defaultTracer.spanBuilder(SPAN_NAME).setParent(context).setNoParent().startSpan(); Span span = defaultTracer.spanBuilder(SPAN_NAME).setParent(context).setNoParent().startSpan();
assertThat(span.getContext()).isEqualTo(SpanContext.getInvalid()); assertThat(span.getContext()).isEqualTo(SpanContext.getInvalid());
} }
@Test
void testSpanContextPropagationCurrentSpan() {
Span parent = Span.wrap(spanContext);
try (Scope scope = defaultTracer.withSpan(parent)) {
Span span = defaultTracer.spanBuilder(SPAN_NAME).startSpan();
assertThat(span.getContext()).isSameAs(spanContext);
}
}
@Test
void testSpanContextPropagationCurrentSpanContext() {
Context context = TracingContextUtils.withSpan(Span.wrap(spanContext), Context.current());
try (Scope scope = context.makeCurrent()) {
Span span = defaultTracer.spanBuilder(SPAN_NAME).startSpan();
assertThat(span.getContext()).isSameAs(spanContext);
}
}
} }

View File

@ -12,7 +12,6 @@ import io.opentelemetry.context.Scope;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class TracingContextUtilsTest { class TracingContextUtilsTest {
@Test @Test
void testGetCurrentSpan_Default() { void testGetCurrentSpan_Default() {
Span span = TracingContextUtils.getCurrentSpan(); Span span = TracingContextUtils.getCurrentSpan();
@ -52,4 +51,19 @@ class TracingContextUtilsTest {
Context context = TracingContextUtils.withSpan(span, Context.current()); Context context = TracingContextUtils.withSpan(span, Context.current());
assertThat(TracingContextUtils.getSpanWithoutDefault(context)).isSameAs(span); assertThat(TracingContextUtils.getSpanWithoutDefault(context)).isSameAs(span);
} }
@Test
void testInProcessContext() {
Span span = Span.wrap(SpanContext.getInvalid());
try (Scope scope = TracingContextUtils.currentContextWith(span)) {
assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(span);
Span secondSpan = Span.wrap(SpanContext.getInvalid());
try (Scope secondScope = TracingContextUtils.currentContextWith(secondSpan)) {
assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(secondSpan);
} finally {
assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(span);
}
}
assertThat(TracingContextUtils.getCurrentSpan().getContext().isValid()).isFalse();
}
} }

View File

@ -13,7 +13,7 @@ import io.opentelemetry.context.ThreadLocalContextStorage.NoopScope;
* you use this class with a {@code try-with-resources} block: * you use this class with a {@code try-with-resources} block:
* *
* <pre>{@code * <pre>{@code
* try (Scope ignored = tracer.withSpan(span)) { * try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
* ... * ...
* } * }
* }</pre> * }</pre>

View File

@ -22,7 +22,7 @@ import javax.annotation.concurrent.ThreadSafe;
* <pre>{@code * <pre>{@code
* private static final Tracer tracer = OpenTelemetry.getTracer(); * private static final Tracer tracer = OpenTelemetry.getTracer();
* void onSendRequest() { * void onSendRequest() {
* try (Scope scope = tracer.withSpan(span)) { * try (Scope scope = TracingContextUtils.currentContextWith(span)) {
* ContextPropagators propagators = OpenTelemetry.getPropagators(); * ContextPropagators propagators = OpenTelemetry.getPropagators();
* TextMapPropagator textMapPropagator = propagators.getTextMapPropagator(); * TextMapPropagator textMapPropagator = propagators.getTextMapPropagator();
* *
@ -59,7 +59,7 @@ import javax.annotation.concurrent.ThreadSafe;
* Span span = tracer.spanBuilder("MyRequest") * Span span = tracer.spanBuilder("MyRequest")
* .setParent(context) * .setParent(context)
* .setSpanKind(Span.Kind.SERVER).startSpan(); * .setSpanKind(Span.Kind.SERVER).startSpan();
* try (Scope ss = tracer.withSpan(span)) { * try (Scope ss = TracingContextUtils.currentContextWith(span)) {
* // Handle request and send response back. * // Handle request and send response back.
* } finally { * } finally {
* span.end(); * span.end();

View File

@ -13,7 +13,7 @@ which try-with-resources does not allow. Take this example:
```java ```java
Span span = tracer.spanBuilder("someWork").startSpan(); Span span = tracer.spanBuilder("someWork").startSpan();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
// Do things. // Do things.
} catch (Exception ex) { } catch (Exception ex) {
span.recordException(ex); span.recordException(ex);

View File

@ -90,7 +90,7 @@ public class HelloWorldClient {
span.setAttribute("net.peer.port", this.serverPort); span.setAttribute("net.peer.port", this.serverPort);
// Set the context with the current span // Set the context with the current span
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build(); HelloRequest request = HelloRequest.newBuilder().setName(name).build();
try { try {
HelloReply response = blockingStub.sayHello(request); HelloReply response = blockingStub.sayHello(request);

View File

@ -95,7 +95,7 @@ public class HelloWorldClientStream {
StreamObserver<HelloRequest> requestObserver; StreamObserver<HelloRequest> requestObserver;
// Set the context with the current span // Set the context with the current span
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
HelloReplyStreamObserver replyObserver = new HelloReplyStreamObserver(); HelloReplyStreamObserver replyObserver = new HelloReplyStreamObserver();
requestObserver = asyncStub.sayHelloStream(replyObserver); requestObserver = asyncStub.sayHelloStream(replyObserver);
for (String name : names) { for (String name : names) {
@ -126,14 +126,14 @@ public class HelloWorldClientStream {
@Override @Override
public void onNext(HelloReply value) { public void onNext(HelloReply value) {
Span span = tracer.getCurrentSpan(); Span span = TracingContextUtils.getCurrentSpan();
span.addEvent("Data received: " + value.getMessage()); span.addEvent("Data received: " + value.getMessage());
logger.info(value.getMessage()); logger.info(value.getMessage());
} }
@Override @Override
public void onError(Throwable t) { public void onError(Throwable t) {
Span span = tracer.getCurrentSpan(); Span span = TracingContextUtils.getCurrentSpan();
logger.log(Level.WARNING, "RPC failed: {0}", t.getMessage()); logger.log(Level.WARNING, "RPC failed: {0}", t.getMessage());
span.setStatus(StatusCanonicalCode.ERROR, "gRPC status: " + t.getMessage()); span.setStatus(StatusCanonicalCode.ERROR, "gRPC status: " + t.getMessage());
} }

View File

@ -55,7 +55,7 @@ public class HttpClient {
// Name convention for the Span is not yet defined. // Name convention for the Span is not yet defined.
// See: https://github.com/open-telemetry/opentelemetry-specification/issues/270 // See: https://github.com/open-telemetry/opentelemetry-specification/issues/270
Span span = tracer.spanBuilder("/").setSpanKind(Span.Kind.CLIENT).startSpan(); Span span = tracer.spanBuilder("/").setSpanKind(Span.Kind.CLIENT).startSpan();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
// TODO provide semantic convention attributes to Span.Builder // TODO provide semantic convention attributes to Span.Builder
span.setAttribute("component", "http"); span.setAttribute("component", "http");
span.setAttribute("http.method", "GET"); span.setAttribute("http.method", "GET");

View File

@ -43,7 +43,7 @@ public class HttpServer {
Span span = Span span =
tracer.spanBuilder("/").setParent(context).setSpanKind(Span.Kind.SERVER).startSpan(); tracer.spanBuilder("/").setParent(context).setSpanKind(Span.Kind.SERVER).startSpan();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
// Set the Semantic Convention // Set the Semantic Convention
span.setAttribute("component", "http"); span.setAttribute("component", "http");
span.setAttribute("http.method", "GET"); span.setAttribute("http.method", "GET");

View File

@ -36,7 +36,7 @@ public class DoubleCounterExample {
public static void main(String[] args) { public static void main(String[] args) {
Span span = tracer.spanBuilder("calculate space").setSpanKind(Kind.INTERNAL).startSpan(); Span span = tracer.spanBuilder("calculate space").setSpanKind(Kind.INTERNAL).startSpan();
DoubleCounterExample example = new DoubleCounterExample(); DoubleCounterExample example = new DoubleCounterExample();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
List<String> extensionsToFind = new ArrayList<>(); List<String> extensionsToFind = new ArrayList<>();
extensionsToFind.add("dll"); extensionsToFind.add("dll");
extensionsToFind.add("png"); extensionsToFind.add("png");

View File

@ -37,7 +37,7 @@ public class LongCounterExample {
public static void main(String[] args) { public static void main(String[] args) {
Span span = tracer.spanBuilder("workflow").setSpanKind(Kind.INTERNAL).startSpan(); Span span = tracer.spanBuilder("workflow").setSpanKind(Kind.INTERNAL).startSpan();
LongCounterExample example = new LongCounterExample(); LongCounterExample example = new LongCounterExample();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
homeDirectoryCounter.add(1); // count root directory homeDirectoryCounter.add(1); // count root directory
example.findFile("file_to_find.txt", homeDirectory); example.findFile("file_to_find.txt", homeDirectory);
} catch (Exception e) { } catch (Exception e) {

View File

@ -55,7 +55,7 @@ public class OtlpExporterExample {
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
Span exampleSpan = tracer.spanBuilder("exampleSpan").startSpan(); Span exampleSpan = tracer.spanBuilder("exampleSpan").startSpan();
try (Scope scope = tracer.withSpan(exampleSpan)) { try (Scope scope = TracingContextUtils.currentContextWith(exampleSpan)) {
counter.add(1); counter.add(1);
exampleSpan.setAttribute("good", "true"); exampleSpan.setAttribute("good", "true");
exampleSpan.setAttribute("exampleNumber", i); exampleSpan.setAttribute("exampleNumber", i);

View File

@ -5,6 +5,7 @@
package io.opentelemetry.opentracingshim; package io.opentelemetry.opentracingshim;
import io.opentelemetry.trace.TracingContextUtils;
import io.opentracing.Scope; import io.opentracing.Scope;
import io.opentracing.ScopeManager; import io.opentracing.ScopeManager;
import io.opentracing.Span; import io.opentracing.Span;
@ -20,7 +21,7 @@ final class ScopeManagerShim extends BaseShimObject implements ScopeManager {
public Span activeSpan() { public Span activeSpan() {
// As OpenTracing simply returns null when no active instance is available, // As OpenTracing simply returns null when no active instance is available,
// we need to do map an invalid OpenTelemetry span to null here. // we need to do map an invalid OpenTelemetry span to null here.
io.opentelemetry.trace.Span span = tracer().getCurrentSpan(); io.opentelemetry.trace.Span span = TracingContextUtils.getCurrentSpan();
if (!span.getContext().isValid()) { if (!span.getContext().isValid()) {
return null; return null;
} }
@ -33,7 +34,7 @@ final class ScopeManagerShim extends BaseShimObject implements ScopeManager {
@SuppressWarnings("MustBeClosedChecker") @SuppressWarnings("MustBeClosedChecker")
public Scope activate(Span span) { public Scope activate(Span span) {
io.opentelemetry.trace.Span actualSpan = getActualSpan(span); io.opentelemetry.trace.Span actualSpan = getActualSpan(span);
return new ScopeShim(tracer().withSpan(actualSpan)); return new ScopeShim(TracingContextUtils.currentContextWith(actualSpan));
} }
static io.opentelemetry.trace.Span getActualSpan(Span span) { static io.opentelemetry.trace.Span getActualSpan(Span span) {

View File

@ -15,6 +15,7 @@ import io.opentelemetry.exporters.inmemory.InMemoryTracing;
import io.opentelemetry.opentracingshim.TraceShim; import io.opentelemetry.opentracingshim.TraceShim;
import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.TracingContextUtils;
import io.opentracing.Scope; import io.opentracing.Scope;
import io.opentracing.Span; import io.opentracing.Span;
import io.opentracing.Tracer; import io.opentracing.Tracer;
@ -45,7 +46,7 @@ class OpenTelemetryInteroperabilityTest {
} finally { } finally {
otSpan.finish(); otSpan.finish();
} }
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse(); assertThat(TracingContextUtils.getCurrentSpan().getContext().isValid()).isFalse();
assertNull(otTracer.activeSpan()); assertNull(otTracer.activeSpan());
List<SpanData> finishedSpans = inMemoryTracing.getSpanExporter().getFinishedSpanItems(); List<SpanData> finishedSpans = inMemoryTracing.getSpanExporter().getFinishedSpanItems();
@ -56,13 +57,13 @@ class OpenTelemetryInteroperabilityTest {
@Test @Test
void openTracingContinuesSdkTrace() { void openTracingContinuesSdkTrace() {
io.opentelemetry.trace.Span otelSpan = tracer.spanBuilder("otel_span").startSpan(); io.opentelemetry.trace.Span otelSpan = tracer.spanBuilder("otel_span").startSpan();
try (io.opentelemetry.context.Scope scope = tracer.withSpan(otelSpan)) { try (io.opentelemetry.context.Scope scope = TracingContextUtils.currentContextWith(otelSpan)) {
otTracer.buildSpan("ot_span").start().finish(); otTracer.buildSpan("ot_span").start().finish();
} finally { } finally {
otelSpan.end(); otelSpan.end();
} }
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse(); assertThat(TracingContextUtils.getCurrentSpan().getContext().isValid()).isFalse();
assertNull(otTracer.activeSpan()); assertNull(otTracer.activeSpan());
List<SpanData> finishedSpans = inMemoryTracing.getSpanExporter().getFinishedSpanItems(); List<SpanData> finishedSpans = inMemoryTracing.getSpanExporter().getFinishedSpanItems();

View File

@ -22,6 +22,7 @@ import io.opentelemetry.sdk.metrics.export.MetricExporter;
import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; import io.opentelemetry.sdk.trace.export.BatchSpanProcessor;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
@ -104,7 +105,7 @@ public class OtlpPipelineDriver {
: i < numberOfSpans) { : i < numberOfSpans) {
// for (int i = 0; i < 10000; i++) { // for (int i = 0; i < 10000; i++) {
Span exampleSpan = tracer.spanBuilder("exampleSpan").startSpan(); Span exampleSpan = tracer.spanBuilder("exampleSpan").startSpan();
try (Scope scope = tracer.withSpan(exampleSpan)) { try (Scope scope = TracingContextUtils.currentContextWith(exampleSpan)) {
exampleSpan.setAttribute("exampleNumber", i++); exampleSpan.setAttribute("exampleNumber", i++);
exampleSpan.setAttribute("attribute0", "attvalue-0"); exampleSpan.setAttribute("attribute0", "attvalue-0");
exampleSpan.setAttribute("attribute1", "attvalue-1"); exampleSpan.setAttribute("attribute1", "attvalue-1");

View File

@ -5,12 +5,10 @@
package io.opentelemetry.sdk.trace; package io.opentelemetry.sdk.trace;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationLibraryInfo;
import io.opentelemetry.trace.DefaultTracer; import io.opentelemetry.trace.DefaultTracer;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
/** {@link TracerSdk} is SDK implementation of {@link Tracer}. */ /** {@link TracerSdk} is SDK implementation of {@link Tracer}. */
final class TracerSdk implements Tracer { final class TracerSdk implements Tracer {
@ -22,16 +20,6 @@ final class TracerSdk implements Tracer {
this.instrumentationLibraryInfo = instrumentationLibraryInfo; this.instrumentationLibraryInfo = instrumentationLibraryInfo;
} }
@Override
public Span getCurrentSpan() {
return TracingContextUtils.getCurrentSpan();
}
@Override
public Scope withSpan(Span span) {
return TracingContextUtils.currentContextWith(span);
}
@Override @Override
public Span.Builder spanBuilder(String spanName) { public Span.Builder spanBuilder(String spanName) {
if (sharedState.isStopped()) { if (sharedState.isStopped()) {

View File

@ -613,7 +613,7 @@ class SpanBuilderSdkTest {
@Test @Test
void noParent() { void noParent() {
Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan(); Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan();
try (Scope ignored = tracerSdk.withSpan(parent)) { try (Scope ignored = TracingContextUtils.currentContextWith(parent)) {
Span span = tracerSdk.spanBuilder(SPAN_NAME).setNoParent().startSpan(); Span span = tracerSdk.spanBuilder(SPAN_NAME).setNoParent().startSpan();
try { try {
assertThat(span.getContext().getTraceIdAsHexString()) assertThat(span.getContext().getTraceIdAsHexString())
@ -760,7 +760,7 @@ class SpanBuilderSdkTest {
@Test @Test
void parentCurrentSpan() { void parentCurrentSpan() {
Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan(); Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan();
try (Scope ignored = tracerSdk.withSpan(parent)) { try (Scope ignored = TracingContextUtils.currentContextWith(parent)) {
final Context implicitParent = Context.current(); final Context implicitParent = Context.current();
RecordEventsReadableSpan span = RecordEventsReadableSpan span =
(RecordEventsReadableSpan) tracerSdk.spanBuilder(SPAN_NAME).startSpan(); (RecordEventsReadableSpan) tracerSdk.spanBuilder(SPAN_NAME).startSpan();
@ -809,7 +809,7 @@ class SpanBuilderSdkTest {
@Test @Test
void parent_clockIsSame() { void parent_clockIsSame() {
Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan(); Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan();
try (Scope scope = tracerSdk.withSpan(parent)) { try (Scope scope = TracingContextUtils.currentContextWith(parent)) {
RecordEventsReadableSpan span = RecordEventsReadableSpan span =
(RecordEventsReadableSpan) tracerSdk.spanBuilder(SPAN_NAME).startSpan(); (RecordEventsReadableSpan) tracerSdk.spanBuilder(SPAN_NAME).startSpan();
@ -822,7 +822,7 @@ class SpanBuilderSdkTest {
@Test @Test
void parentCurrentSpan_clockIsSame() { void parentCurrentSpan_clockIsSame() {
Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan(); Span parent = tracerSdk.spanBuilder(SPAN_NAME).startSpan();
try (Scope ignored = tracerSdk.withSpan(parent)) { try (Scope ignored = TracingContextUtils.currentContextWith(parent)) {
RecordEventsReadableSpan span = RecordEventsReadableSpan span =
(RecordEventsReadableSpan) tracerSdk.spanBuilder(SPAN_NAME).startSpan(); (RecordEventsReadableSpan) tracerSdk.spanBuilder(SPAN_NAME).startSpan();

View File

@ -49,44 +49,11 @@ class TracerSdkTest {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
} }
@Test
void defaultGetCurrentSpan() {
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test @Test
void defaultSpanBuilder() { void defaultSpanBuilder() {
assertThat(tracer.spanBuilder(SPAN_NAME)).isInstanceOf(SpanBuilderSdk.class); assertThat(tracer.spanBuilder(SPAN_NAME)).isInstanceOf(SpanBuilderSdk.class);
} }
@Test
void getCurrentSpan() {
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
// Make sure context is detached even if test fails.
try (Scope ignored = TracingContextUtils.withSpan(span, Context.current()).makeCurrent()) {
assertThat(tracer.getCurrentSpan()).isSameAs(span);
}
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test
void withSpan_NullSpan() {
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
try (Scope ignored = tracer.withSpan(null)) {
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
}
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test
void getCurrentSpan_WithSpan() {
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
try (Scope ignored = tracer.withSpan(span)) {
assertThat(tracer.getCurrentSpan()).isSameAs(span);
}
assertThat(tracer.getCurrentSpan().getContext().isValid()).isFalse();
}
@Test @Test
void getInstrumentationLibraryInfo() { void getInstrumentationLibraryInfo() {
assertThat(tracer.getInstrumentationLibraryInfo()).isEqualTo(instrumentationLibraryInfo); assertThat(tracer.getInstrumentationLibraryInfo()).isEqualTo(instrumentationLibraryInfo);
@ -194,7 +161,7 @@ class TracerSdkTest {
@Override @Override
public void update() { public void update() {
Span span = tracer.spanBuilder("testSpan").startSpan(); Span span = tracer.spanBuilder("testSpan").startSpan();
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
span.setAttribute("testAttribute", "testValue"); span.setAttribute("testAttribute", "testValue");
} finally { } finally {
span.end(); span.end();

View File

@ -18,6 +18,7 @@ import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.SpanId; import io.opentelemetry.trace.SpanId;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -37,7 +38,7 @@ class ActiveSpanReplacementTest {
void test() { void test() {
// Start an isolated task and query for its result in another task/thread // Start an isolated task and query for its result in another task/thread
Span span = tracer.spanBuilder("initial").startSpan(); Span span = tracer.spanBuilder("initial").startSpan();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
// Explicitly pass a Span to be finished once a late calculation is done. // Explicitly pass a Span to be finished once a late calculation is done.
submitAnotherTask(span); submitAnotherTask(span);
} }
@ -60,7 +61,7 @@ class ActiveSpanReplacementTest {
assertThat(spans.get(0).getTraceId()).isNotEqualTo(spans.get(1).getTraceId()); assertThat(spans.get(0).getTraceId()).isNotEqualTo(spans.get(1).getTraceId());
assertThat(spans.get(0).getParentSpanId()).isEqualTo(SpanId.getInvalid()); assertThat(spans.get(0).getParentSpanId()).isEqualTo(SpanId.getInvalid());
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
private void submitAnotherTask(final Span initialSpan) { private void submitAnotherTask(final Span initialSpan) {
@ -69,11 +70,11 @@ class ActiveSpanReplacementTest {
() -> { () -> {
// Create a new Span for this task // Create a new Span for this task
Span taskSpan = tracer.spanBuilder("task").startSpan(); Span taskSpan = tracer.spanBuilder("task").startSpan();
try (Scope scope = tracer.withSpan(taskSpan)) { try (Scope scope = TracingContextUtils.currentContextWith(taskSpan)) {
// Simulate work strictly related to the initial Span // Simulate work strictly related to the initial Span
// and finish it. // and finish it.
try (Scope initialScope = tracer.withSpan(initialSpan)) { try (Scope initialScope = TracingContextUtils.currentContextWith(initialSpan)) {
sleep(50); sleep(50);
} finally { } finally {
initialSpan.end(); initialSpan.end();
@ -81,7 +82,7 @@ class ActiveSpanReplacementTest {
// Restore the span for this task and create a subspan // Restore the span for this task and create a subspan
Span subTaskSpan = tracer.spanBuilder("subtask").startSpan(); Span subTaskSpan = tracer.spanBuilder("subtask").startSpan();
try (Scope subTaskScope = tracer.withSpan(subTaskSpan)) { try (Scope subTaskScope = TracingContextUtils.currentContextWith(subTaskSpan)) {
sleep(50); sleep(50);
} finally { } finally {
subTaskSpan.end(); subTaskSpan.end();

View File

@ -10,6 +10,7 @@ import io.opentelemetry.context.Scope;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -44,7 +45,7 @@ final class Actor implements AutoCloseable {
.setParent(parent) .setParent(parent)
.setSpanKind(Kind.CONSUMER) .setSpanKind(Kind.CONSUMER)
.startSpan(); .startSpan();
try (Scope ignored = tracer.withSpan(child)) { try (Scope ignored = TracingContextUtils.currentContextWith(child)) {
phaser.arriveAndAwaitAdvance(); // child tracer started phaser.arriveAndAwaitAdvance(); // child tracer started
child.addEvent("received " + message); child.addEvent("received " + message);
phaser.arriveAndAwaitAdvance(); // assert size phaser.arriveAndAwaitAdvance(); // assert size

View File

@ -15,6 +15,7 @@ import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -48,7 +49,7 @@ class ActorPropagationTest {
phaser.register(); phaser.register();
Span parent = tracer.spanBuilder("actorTell").setSpanKind(Kind.PRODUCER).startSpan(); Span parent = tracer.spanBuilder("actorTell").setSpanKind(Kind.PRODUCER).startSpan();
parent.setAttribute("component", "example-actor"); parent.setAttribute("component", "example-actor");
try (Scope ignored = tracer.withSpan(parent)) { try (Scope ignored = TracingContextUtils.currentContextWith(parent)) {
actor.tell("my message 1"); actor.tell("my message 1");
actor.tell("my message 2"); actor.tell("my message 2");
} finally { } finally {
@ -72,7 +73,7 @@ class ActorPropagationTest {
assertThat(TestUtils.getByKind(finished, Span.Kind.CONSUMER)).hasSize(2); assertThat(TestUtils.getByKind(finished, Span.Kind.CONSUMER)).hasSize(2);
assertThat(TestUtils.getOneByKind(finished, Span.Kind.PRODUCER)).isNotNull(); assertThat(TestUtils.getOneByKind(finished, Span.Kind.PRODUCER)).isNotNull();
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
} }
@ -85,7 +86,7 @@ class ActorPropagationTest {
Span span = tracer.spanBuilder("actorAsk").setSpanKind(Kind.PRODUCER).startSpan(); Span span = tracer.spanBuilder("actorAsk").setSpanKind(Kind.PRODUCER).startSpan();
span.setAttribute("component", "example-actor"); span.setAttribute("component", "example-actor");
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
future1 = actor.ask("my message 1"); future1 = actor.ask("my message 1");
future2 = actor.ask("my message 2"); future2 = actor.ask("my message 2");
} finally { } finally {
@ -113,7 +114,7 @@ class ActorPropagationTest {
assertThat(TestUtils.getByKind(finished, Span.Kind.CONSUMER)).hasSize(2); assertThat(TestUtils.getByKind(finished, Span.Kind.CONSUMER)).hasSize(2);
assertThat(TestUtils.getOneByKind(finished, Span.Kind.PRODUCER)).isNotNull(); assertThat(TestUtils.getOneByKind(finished, Span.Kind.PRODUCER)).isNotNull();
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
} }
} }

View File

@ -11,6 +11,7 @@ import io.opentelemetry.context.Scope;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
final class Client { final class Client {
@ -29,7 +30,7 @@ final class Client {
Span span = tracer.spanBuilder("send").setSpanKind(Kind.CLIENT).startSpan(); Span span = tracer.spanBuilder("send").setSpanKind(Kind.CLIENT).startSpan();
span.setAttribute("component", "example-client"); span.setAttribute("component", "example-client");
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
OpenTelemetry.getPropagators() OpenTelemetry.getPropagators()
.getTextMapPropagator() .getTextMapPropagator()
.inject(Context.current(), message, Message::put); .inject(Context.current(), message, Message::put);

View File

@ -12,6 +12,7 @@ import io.opentelemetry.context.propagation.TextMapPropagator.Getter;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import javax.annotation.Nullable; import javax.annotation.Nullable;
@ -43,9 +44,9 @@ final class Server extends Thread {
tracer.spanBuilder("receive").setSpanKind(Kind.SERVER).setParent(context).startSpan(); tracer.spanBuilder("receive").setSpanKind(Kind.SERVER).setParent(context).startSpan();
span.setAttribute("component", "example-server"); span.setAttribute("component", "example-server");
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
// Simulate work. // Simulate work.
tracer.getCurrentSpan().addEvent("DoWork"); TracingContextUtils.getCurrentSpan().addEvent("DoWork");
} finally { } finally {
span.end(); span.end();
} }

View File

@ -17,6 +17,7 @@ import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -62,6 +63,6 @@ class TestClientServerTest {
assertThat(finished.get(0).getKind()).isEqualTo(Kind.CLIENT); assertThat(finished.get(0).getKind()).isEqualTo(Kind.CLIENT);
assertThat(finished.get(1).getKind()).isEqualTo(Kind.SERVER); assertThat(finished.get(1).getKind()).isEqualTo(Kind.SERVER);
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
} }

View File

@ -60,14 +60,14 @@ class HandlerTest {
assertThat(finished.get(0).getParentSpanId()).isEqualTo(SpanId.getInvalid()); assertThat(finished.get(0).getParentSpanId()).isEqualTo(SpanId.getInvalid());
assertThat(finished.get(1).getParentSpanId()).isEqualTo(SpanId.getInvalid()); assertThat(finished.get(1).getParentSpanId()).isEqualTo(SpanId.getInvalid());
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
/** Active parent is not picked up by child. */ /** Active parent is not picked up by child. */
@Test @Test
void parent_not_picked_up() throws Exception { void parent_not_picked_up() throws Exception {
Span parentSpan = tracer.spanBuilder("parent").startSpan(); Span parentSpan = tracer.spanBuilder("parent").startSpan();
try (Scope ignored = tracer.withSpan(parentSpan)) { try (Scope ignored = TracingContextUtils.currentContextWith(parentSpan)) {
String response = client.send("no_parent").get(15, TimeUnit.SECONDS); String response = client.send("no_parent").get(15, TimeUnit.SECONDS);
assertThat(response).isEqualTo("no_parent:response"); assertThat(response).isEqualTo("no_parent:response");
} finally { } finally {
@ -97,7 +97,7 @@ class HandlerTest {
void bad_solution_to_set_parent() throws Exception { void bad_solution_to_set_parent() throws Exception {
Client client; Client client;
Span parentSpan = tracer.spanBuilder("parent").startSpan(); Span parentSpan = tracer.spanBuilder("parent").startSpan();
try (Scope ignored = tracer.withSpan(parentSpan)) { try (Scope ignored = TracingContextUtils.currentContextWith(parentSpan)) {
client = client =
new Client( new Client(
new RequestHandler( new RequestHandler(

View File

@ -19,6 +19,7 @@ import io.opentelemetry.sdk.trace.data.SpanData.Event;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.StatusCanonicalCode; import io.opentelemetry.trace.StatusCanonicalCode;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -38,7 +39,7 @@ public final class ErrorReportingTest {
@Test @Test
void testSimpleError() { void testSimpleError() {
Span span = tracer.spanBuilder("one").startSpan(); Span span = tracer.spanBuilder("one").startSpan();
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
throw new RuntimeException("Invalid state"); throw new RuntimeException("Invalid state");
} catch (Exception e) { } catch (Exception e) {
span.setStatus(StatusCanonicalCode.ERROR); span.setStatus(StatusCanonicalCode.ERROR);
@ -46,7 +47,7 @@ public final class ErrorReportingTest {
span.end(); span.end();
} }
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
List<SpanData> spans = inMemoryTracing.getSpanExporter().getFinishedSpanItems(); List<SpanData> spans = inMemoryTracing.getSpanExporter().getFinishedSpanItems();
assertThat(spans).hasSize(1); assertThat(spans).hasSize(1);
@ -59,7 +60,7 @@ public final class ErrorReportingTest {
final Span span = tracer.spanBuilder("one").startSpan(); final Span span = tracer.spanBuilder("one").startSpan();
executor.submit( executor.submit(
() -> { () -> {
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
throw new RuntimeException("Invalid state"); throw new RuntimeException("Invalid state");
} catch (Exception exc) { } catch (Exception exc) {
span.setStatus(StatusCanonicalCode.ERROR); span.setStatus(StatusCanonicalCode.ERROR);
@ -84,7 +85,7 @@ public final class ErrorReportingTest {
final int maxRetries = 1; final int maxRetries = 1;
int retries = 0; int retries = 0;
Span span = tracer.spanBuilder("one").startSpan(); Span span = tracer.spanBuilder("one").startSpan();
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
while (retries++ < maxRetries) { while (retries++ < maxRetries) {
try { try {
throw new RuntimeException("No url could be fetched"); throw new RuntimeException("No url could be fetched");
@ -97,7 +98,7 @@ public final class ErrorReportingTest {
span.setStatus(StatusCanonicalCode.ERROR); // Could not fetch anything. span.setStatus(StatusCanonicalCode.ERROR); // Could not fetch anything.
span.end(); span.end();
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
List<SpanData> spans = inMemoryTracing.getSpanExporter().getFinishedSpanItems(); List<SpanData> spans = inMemoryTracing.getSpanExporter().getFinishedSpanItems();
assertThat(spans).hasSize(1); assertThat(spans).hasSize(1);
@ -113,7 +114,7 @@ public final class ErrorReportingTest {
@Test @Test
void testInstrumentationLayer() { void testInstrumentationLayer() {
Span span = tracer.spanBuilder("one").startSpan(); Span span = tracer.spanBuilder("one").startSpan();
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
// ScopedRunnable captures the active Span at this time. // ScopedRunnable captures the active Span at this time.
executor.submit( executor.submit(
new ScopedRunnable( new ScopedRunnable(
@ -121,9 +122,9 @@ public final class ErrorReportingTest {
try { try {
throw new RuntimeException("Invalid state"); throw new RuntimeException("Invalid state");
} catch (Exception exc) { } catch (Exception exc) {
tracer.getCurrentSpan().setStatus(StatusCanonicalCode.ERROR); TracingContextUtils.getCurrentSpan().setStatus(StatusCanonicalCode.ERROR);
} finally { } finally {
tracer.getCurrentSpan().end(); TracingContextUtils.getCurrentSpan().end();
} }
}, },
tracer)); tracer));
@ -146,13 +147,13 @@ public final class ErrorReportingTest {
private ScopedRunnable(Runnable runnable, Tracer tracer) { private ScopedRunnable(Runnable runnable, Tracer tracer) {
this.runnable = runnable; this.runnable = runnable;
this.tracer = tracer; this.tracer = tracer;
this.span = tracer.getCurrentSpan(); this.span = TracingContextUtils.getCurrentSpan();
} }
@Override @Override
public void run() { public void run() {
// No error reporting is done, as we are a simple wrapper. // No error reporting is done, as we are a simple wrapper.
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
runnable.run(); runnable.run();
} }
} }

View File

@ -14,6 +14,7 @@ import io.opentelemetry.sdk.trace.TracerSdkProvider;
import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -50,7 +51,7 @@ public final class LateSpanFinishTest {
TestUtils.assertSameTrace(spans); TestUtils.assertSameTrace(spans);
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
/* /*
@ -63,9 +64,9 @@ public final class LateSpanFinishTest {
() -> { () -> {
/* Alternative to calling activate() is to pass it manually to asChildOf() for each /* Alternative to calling activate() is to pass it manually to asChildOf() for each
* created Span. */ * created Span. */
try (Scope scope = tracer.withSpan(parentSpan)) { try (Scope scope = TracingContextUtils.currentContextWith(parentSpan)) {
Span childSpan = tracer.spanBuilder("task1").startSpan(); Span childSpan = tracer.spanBuilder("task1").startSpan();
try (Scope childScope = tracer.withSpan(childSpan)) { try (Scope childScope = TracingContextUtils.currentContextWith(childSpan)) {
TestUtils.sleep(55); TestUtils.sleep(55);
} finally { } finally {
childSpan.end(); childSpan.end();
@ -75,9 +76,9 @@ public final class LateSpanFinishTest {
executor.submit( executor.submit(
() -> { () -> {
try (Scope scope = tracer.withSpan(parentSpan)) { try (Scope scope = TracingContextUtils.currentContextWith(parentSpan)) {
Span childSpan = tracer.spanBuilder("task2").startSpan(); Span childSpan = tracer.spanBuilder("task2").startSpan();
try (Scope childScope = tracer.withSpan(childSpan)) { try (Scope childScope = TracingContextUtils.currentContextWith(childSpan)) {
TestUtils.sleep(85); TestUtils.sleep(85);
} finally { } finally {
childSpan.end(); childSpan.end();

View File

@ -13,6 +13,7 @@ import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -33,6 +34,6 @@ class ListenerTest {
assertThat(finished).hasSize(1); assertThat(finished).hasSize(1);
assertThat(finished.get(0).getKind()).isEqualTo(Kind.CLIENT); assertThat(finished.get(0).getKind()).isEqualTo(Kind.CLIENT);
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
} }

View File

@ -9,6 +9,7 @@ import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope; import io.opentelemetry.context.Scope;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -30,7 +31,7 @@ class Client {
return executor.submit( return executor.submit(
() -> { () -> {
Span span = tracer.spanBuilder("subtask").setParent(parent).startSpan(); Span span = tracer.spanBuilder("subtask").setParent(parent).startSpan();
try (Scope subtaskScope = tracer.withSpan(span)) { try (Scope subtaskScope = TracingContextUtils.currentContextWith(span)) {
// Simulate work - make sure we finish *after* the parent Span. // Simulate work - make sure we finish *after* the parent Span.
parentDoneLatch.await(); parentDoneLatch.await();
} finally { } finally {

View File

@ -16,6 +16,7 @@ import io.opentelemetry.sdk.trace.TracerSdkProvider;
import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -40,7 +41,7 @@ class MultipleCallbacksTest {
Client client = new Client(tracer, parentDoneLatch); Client client = new Client(tracer, parentDoneLatch);
Span span = tracer.spanBuilder("parent").startSpan(); Span span = tracer.spanBuilder("parent").startSpan();
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
client.send("task1"); client.send("task1");
client.send("task2"); client.send("task2");
client.send("task3"); client.send("task3");
@ -63,6 +64,6 @@ class MultipleCallbacksTest {
assertThat(spans.get(i).getParentSpanId()).isEqualTo(parentSpan.getSpanId()); assertThat(spans.get(i).getParentSpanId()).isEqualTo(parentSpan.getSpanId());
} }
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
} }

View File

@ -18,6 +18,7 @@ import io.opentelemetry.sdk.trace.TracerSdkProvider;
import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -53,24 +54,24 @@ public final class NestedCallbacksTest {
assertThat(attrs.get(stringKey("key" + i))).isEqualTo(Integer.toString(i)); assertThat(attrs.get(stringKey("key" + i))).isEqualTo(Integer.toString(i));
} }
assertThat(tracer.getCurrentSpan()).isSameAs(Span.getInvalid()); assertThat(TracingContextUtils.getCurrentSpan()).isSameAs(Span.getInvalid());
} }
private void submitCallbacks(final Span span) { private void submitCallbacks(final Span span) {
executor.submit( executor.submit(
() -> { () -> {
try (Scope ignored = tracer.withSpan(span)) { try (Scope ignored = TracingContextUtils.currentContextWith(span)) {
span.setAttribute("key1", "1"); span.setAttribute("key1", "1");
executor.submit( executor.submit(
() -> { () -> {
try (Scope ignored12 = tracer.withSpan(span)) { try (Scope ignored12 = TracingContextUtils.currentContextWith(span)) {
span.setAttribute("key2", "2"); span.setAttribute("key2", "2");
executor.submit( executor.submit(
() -> { () -> {
try (Scope ignored1 = tracer.withSpan(span)) { try (Scope ignored1 = TracingContextUtils.currentContextWith(span)) {
span.setAttribute("key3", "3"); span.setAttribute("key3", "3");
} finally { } finally {
span.end(); span.end();

View File

@ -9,6 +9,7 @@ import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope; import io.opentelemetry.context.Scope;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
@ -43,7 +44,7 @@ final class Promise<T> {
() -> { () -> {
Span childSpan = tracer.spanBuilder("success").setParent(parent).startSpan(); Span childSpan = tracer.spanBuilder("success").setParent(parent).startSpan();
childSpan.setAttribute("component", "success"); childSpan.setAttribute("component", "success");
try (Scope ignored = tracer.withSpan(childSpan)) { try (Scope ignored = TracingContextUtils.currentContextWith(childSpan)) {
callback.accept(result); callback.accept(result);
} finally { } finally {
childSpan.end(); childSpan.end();
@ -60,7 +61,7 @@ final class Promise<T> {
() -> { () -> {
Span childSpan = tracer.spanBuilder("error").setParent(parent).startSpan(); Span childSpan = tracer.spanBuilder("error").setParent(parent).startSpan();
childSpan.setAttribute("component", "error"); childSpan.setAttribute("component", "error");
try (Scope ignored = tracer.withSpan(childSpan)) { try (Scope ignored = TracingContextUtils.currentContextWith(childSpan)) {
callback.accept(error); callback.accept(error);
} finally { } finally {
childSpan.end(); childSpan.end();

View File

@ -17,6 +17,7 @@ import io.opentelemetry.sdk.trace.data.SpanData;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.SpanId; import io.opentelemetry.trace.SpanId;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
import java.util.List; import java.util.List;
import java.util.concurrent.Phaser; import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
@ -53,18 +54,18 @@ class PromisePropagationTest {
Span parentSpan = tracer.spanBuilder("promises").startSpan(); Span parentSpan = tracer.spanBuilder("promises").startSpan();
parentSpan.setAttribute("component", "example-promises"); parentSpan.setAttribute("component", "example-promises");
try (Scope ignored = tracer.withSpan(parentSpan)) { try (Scope ignored = TracingContextUtils.currentContextWith(parentSpan)) {
Promise<String> successPromise = new Promise<>(context, tracer); Promise<String> successPromise = new Promise<>(context, tracer);
successPromise.onSuccess( successPromise.onSuccess(
s -> { s -> {
tracer.getCurrentSpan().addEvent("Promised 1 " + s); TracingContextUtils.getCurrentSpan().addEvent("Promised 1 " + s);
successResult1.set(s); successResult1.set(s);
phaser.arriveAndAwaitAdvance(); // result set phaser.arriveAndAwaitAdvance(); // result set
}); });
successPromise.onSuccess( successPromise.onSuccess(
s -> { s -> {
tracer.getCurrentSpan().addEvent("Promised 2 " + s); TracingContextUtils.getCurrentSpan().addEvent("Promised 2 " + s);
successResult2.set(s); successResult2.set(s);
phaser.arriveAndAwaitAdvance(); // result set phaser.arriveAndAwaitAdvance(); // result set
}); });

View File

@ -9,6 +9,7 @@ import io.opentelemetry.context.Scope;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Span.Kind; import io.opentelemetry.trace.Span.Kind;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
/** /**
* One instance per Client. 'beforeRequest' and 'afterResponse' are executed in the same thread for * One instance per Client. 'beforeRequest' and 'afterResponse' are executed in the same thread for
@ -30,13 +31,13 @@ final class RequestHandler {
/** beforeRequest handler....... */ /** beforeRequest handler....... */
public void beforeRequest(Object request) { public void beforeRequest(Object request) {
Span span = tracer.spanBuilder(OPERATION_NAME).setSpanKind(Kind.SERVER).startSpan(); Span span = tracer.spanBuilder(OPERATION_NAME).setSpanKind(Kind.SERVER).startSpan();
tlsScope.set(tracer.withSpan(span)); tlsScope.set(TracingContextUtils.currentContextWith(span));
} }
/** afterResponse handler....... */ /** afterResponse handler....... */
public void afterResponse(Object response) { public void afterResponse(Object response) {
// Finish the Span // Finish the Span
tracer.getCurrentSpan().end(); TracingContextUtils.getCurrentSpan().end();
// Deactivate the Span // Deactivate the Span
tlsScope.get().close(); tlsScope.get().close();

View File

@ -8,24 +8,21 @@ package io.opentelemetry.sdk.extensions.trace.testbed.suspendresumepropagation;
import io.opentelemetry.context.Scope; import io.opentelemetry.context.Scope;
import io.opentelemetry.trace.Span; import io.opentelemetry.trace.Span;
import io.opentelemetry.trace.Tracer; import io.opentelemetry.trace.Tracer;
import io.opentelemetry.trace.TracingContextUtils;
final class SuspendResume { final class SuspendResume {
private final Tracer tracer;
private final Span span; private final Span span;
public SuspendResume(int id, Tracer tracer) { public SuspendResume(int id, Tracer tracer) {
// Passed along here for testing. Normally should be referenced via GlobalTracer.get().
this.tracer = tracer;
Span span = tracer.spanBuilder("job " + id).startSpan(); Span span = tracer.spanBuilder("job " + id).startSpan();
span.setAttribute("component", "suspend-resume"); span.setAttribute("component", "suspend-resume");
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
this.span = span; this.span = span;
} }
} }
public void doPart(String name) { public void doPart(String name) {
try (Scope scope = tracer.withSpan(span)) { try (Scope scope = TracingContextUtils.currentContextWith(span)) {
span.addEvent("part: " + name); span.addEvent("part: " + name);
} }
} }