Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions opentracing-api/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,20 @@
<version>1.10.19</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.23</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.23</version>
</dependency>
</dependencies>
</project>
60 changes: 60 additions & 0 deletions opentracing-mdc-demo/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--

Copyright 2016-2017 The OpenTracing Authors

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.

-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>io.opentracing</groupId>
<artifactId>parent</artifactId>
<version>0.20.11-SNAPSHOT</version>
</parent>

<artifactId>opentracing-mdc-demo</artifactId>
<name>OpenTracing-mdc-demo</name>
<description>OpenTracing MDC Demo</description>

<properties>
<main.basedir>${project.basedir}/..</main.basedir>
</properties>

<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>opentracing-api</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>opentracing-mock</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.23</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.23</version>
</dependency>
</dependencies>

</project>
113 changes: 113 additions & 0 deletions opentracing-mdc-demo/src/main/java/io/opentracing/mdcdemo/MDCDemo.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package io.opentracing.mdcdemo;

import io.opentracing.Scheduler;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.mock.MockSpan;
import io.opentracing.mock.MockTracer;
import org.slf4j.Logger;
import org.slf4j.MDC;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class MDCDemo {
Tracer tracer;

private MDCDemo(Tracer tracer) {
this.tracer = tracer;
}

public void trivialSpan() {
Span span = this.tracer.buildSpan("trivial").start();
span.finish();
}

public void trivialChild() throws Exception {
try (Scheduler.Continuation c = this.tracer.buildSpan("trivialParent").startAndActivate(true)) {
// The child will automatically know about the parent.
Span child = this.tracer.buildSpan("trivialChild").start();
child.finish();
}
}

public void asyncSpans() throws Exception {
final Tracer tracer = this.tracer; // save typing

// Create an ExecutorService and wrap it in a TracedExecutorService.
ExecutorService realExecutor = Executors.newFixedThreadPool(500);
final ExecutorService otExecutor = new TracedExecutorService(realExecutor, tracer.scheduler());

// Hacky lists of futures we wait for before exiting async Spans.
final List<Future<?>> futures = new ArrayList<>();
final List<Future<?>> subfutures = new ArrayList<>();

// Create a parent Continuation for all of the async activity.
try (final Scheduler.Continuation parentContinuation = tracer.buildSpan("parent").startAndActivate(true);) {

// Create 10 async children.
for (int i = 0; i < 10; i++) {
final int j = i;
futures.add(otExecutor.submit(new Runnable() {
@Override
public void run() {
// START child body

try (final Scheduler.Continuation childContinuation =
tracer.buildSpan("child_" + j).startAndActivate(false);) {
Thread.currentThread().sleep(1000);
tracer.scheduler().active().log("awoke");
Runnable r = new Runnable() {
@Override
public void run() {
Span active = tracer.scheduler().active();
active.log("awoke again");
// Create a grandchild for each child.
Span grandchild = tracer.buildSpan("grandchild_" + j).start();
grandchild.finish();
active.finish();
}
};
subfutures.add(otExecutor.submit(r));
} catch (Exception e) { }

// END child body
}
}));
}
for (Future<?> f : futures) {
f.get();
}
for (Future<?> f : subfutures) {
f.get();
}
}

otExecutor.shutdown();
otExecutor.awaitTermination(3, TimeUnit.SECONDS);
}

public static void main(String[] args) throws Exception {
org.apache.log4j.BasicConfigurator.configure();
final Logger logger = org.slf4j.LoggerFactory.getLogger("hack");
MDC.put("mdcKey", "mdcVal");

final MockTracer tracer = new MockTracer(new MDCScheduler());

// Do stuff with the MockTracer.
{
MDCDemo demo = new MDCDemo(tracer);
demo.trivialSpan();
demo.trivialChild();
demo.asyncSpans();
}

// Print out all mock-Spans
List<MockSpan> finishedSpans = tracer.finishedSpans();
for (MockSpan span : finishedSpans) {
logger.info("finished Span '{}'. trace={}, span={}, parent={}", span.operationName(), span.context().traceId(), span.context().spanId(), span.parentId());
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package io.opentracing.mdcdemo;

import io.opentracing.Span;
import io.opentracing.SpanContext;
import io.opentracing.Scheduler;
import org.slf4j.MDC;

import java.util.Map;

/**
* MDCScheduler illustrates the core Scheduler concepts and capabilities to a first approximation. Not
* production-quality code.
*/
public class MDCScheduler implements Scheduler {
Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's the MDC+Scheduler coupling. Seems to work, FWIW!

<<<<<<< Updated upstream
private final ThreadLocal<MDCSnapshot> tlsSnapshot = new ThreadLocal<MDCSnapshot>();

class MDCSnapshot implements Continuation {
private final Map<String, String> mdcContext;
private final Span span;
private boolean finishOnDeactivate;
private MDCSnapshot toRestore = null;

MDCSnapshot(Span span) {
=======
private final ThreadLocal<MDCContinuation> tlsSnapshot = new ThreadLocal<MDCContinuation>();

class MDCContinuation implements Continuation {
private final Map<String, String> mdcContext;
private final Span span;
private boolean finishOnDeactivate;
private MDCContinuation toRestore = null;

MDCContinuation(Span span) {
>>>>>>> Stashed changes
this.mdcContext = MDC.getCopyOfContextMap();
this.span = span;
}

@Override
public Span activate(boolean finishOnDeactivate) {
this.finishOnDeactivate = finishOnDeactivate;
toRestore = tlsSnapshot.get();
tlsSnapshot.set(this);
return span;
}

@Override
public void close() {
this.doDeactivate(this.finishOnDeactivate);
}

@Override
public void deactivate() {
doDeactivate(this.finishOnDeactivate);
}

private void doDeactivate(boolean finishSpan) {
if (span != null && finishSpan) {
span.finish();
}

if (tlsSnapshot.get() != this) {
// This shouldn't happen if users call methods in the expected order. Bail out.
return;
}
tlsSnapshot.set(toRestore);
}
}

@Override
<<<<<<< Updated upstream
public MDCSnapshot captureActive() {
return new MDCSnapshot(active());
}

@Override
public MDCSnapshot capture(Span span) {
return new MDCSnapshot(span);
=======
public MDCContinuation captureActive() {
return new MDCContinuation(active());
}

@Override
public MDCContinuation capture(Span span) {
return new MDCContinuation(span);
>>>>>>> Stashed changes
}

@Override
public Span active() {
<<<<<<< Updated upstream
MDCSnapshot snapshot = tlsSnapshot.get();
=======
MDCContinuation snapshot = tlsSnapshot.get();
>>>>>>> Stashed changes
if (snapshot == null) {
return null;
}
return snapshot.span;
}

@Override
public SpanContext activeContext() {
Span active = this.active();
if (active == null) return null;
return active.context();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package io.opentracing.mdcdemo;

import io.opentracing.Scheduler;
import io.opentracing.Span;

import java.util.concurrent.Callable;

public class TracedCallable<T> implements Callable<T> {
private Scheduler.Continuation continuation;
private Scheduler scheduler;
private Callable<T> callable;

public TracedCallable(Callable<T> callable, Scheduler scheduler) {
this(callable, scheduler.active(), scheduler);
}

public TracedCallable(Callable<T> callable, Span span, Scheduler scheduler) {
if (callable == null) throw new NullPointerException("Callable is <null>.");
this.callable = callable;
this.scheduler = scheduler;
this.continuation = scheduler.captureActive();
}

public T call() throws Exception {
<<<<<<< Updated upstream
final Span span = continuation.activate(true);
=======
// NOTE: There's no way to be sure about the finishOnDeactivate parameter to activate(), so we play it safe.
final Span span = continuation.activate(false);
>>>>>>> Stashed changes
try {
return callable.call();
} finally {
continuation.deactivate();
}
}
}
Loading