Skip to content

Commit 79a33d7

Browse files
authored
Merge pull request #462 from DataDog/ark/root-span
Add getRootSpan() to MutableSpan
2 parents f833218 + bc105af commit 79a33d7

4 files changed

Lines changed: 31 additions & 0 deletions

File tree

dd-trace-api/src/main/java/datadog/trace/api/interceptor/MutableSpan.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,6 @@ public interface MutableSpan {
4141
Boolean isError();
4242

4343
MutableSpan setError(boolean value);
44+
45+
MutableSpan getRootSpan();
4446
}

dd-trace-ot/src/main/java/datadog/opentracing/DDSpan.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,11 @@ public DDSpan setError(final boolean error) {
125125
return this;
126126
}
127127

128+
@Override
129+
public MutableSpan getRootSpan() {
130+
return context().getTrace().getRootSpan();
131+
}
132+
128133
public void setErrorMeta(final Throwable error) {
129134
setError(true);
130135

dd-trace-ot/src/main/java/datadog/opentracing/PendingTrace.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,16 @@ public class PendingTrace extends ConcurrentLinkedDeque<DDSpan> {
4040
Collections.newSetFromMap(new ConcurrentHashMap<WeakReference<?>, Boolean>());
4141

4242
private final AtomicInteger pendingReferenceCount = new AtomicInteger(0);
43+
/**
44+
* During a trace there are cases where the root span must be accessed (e.g. priority sampling and
45+
* trace-search tags).
46+
*
47+
* <p>Use a weak ref because we still need to handle buggy cases where the root span is not
48+
* correctly closed (see SpanCleaner).
49+
*
50+
* <p>The root span will be available in non-buggy cases because it has either finished and
51+
* strongly ref'd in this queue or is unfinished and ref'd in a ContinuableScope.
52+
*/
4353
private final AtomicReference<WeakReference<DDSpan>> rootSpan = new AtomicReference<>();
4454

4555
/** Ensure a trace is never written multiple times */

dd-trace-ot/src/test/groovy/datadog/opentracing/DDSpanTest.groovy

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,4 +183,18 @@ class DDSpanTest extends Specification {
183183
child2.getMetrics().get(DDSpanContext.PRIORITY_SAMPLING_KEY) == null
184184
child2.getMetrics().get(DDSpanContext.SAMPLE_RATE_KEY) == null
185185
}
186+
187+
def "getRootSpan returns the root span"() {
188+
setup:
189+
def root = tracer.buildSpan("root").start()
190+
def child = tracer.buildSpan("child").asChildOf(root).start()
191+
192+
expect:
193+
root.getRootSpan() == root
194+
child.getRootSpan() == root
195+
196+
cleanup:
197+
child.finish()
198+
root.finish()
199+
}
186200
}

0 commit comments

Comments
 (0)