-
Notifications
You must be signed in to change notification settings - Fork 1.1k
fix(gax): Manage span scope in SpanTracer #12680
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -37,6 +37,8 @@ | |
| import io.opentelemetry.api.trace.SpanBuilder; | ||
| import io.opentelemetry.api.trace.SpanKind; | ||
| import io.opentelemetry.api.trace.Tracer; | ||
| import io.opentelemetry.context.Scope; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
| import java.util.concurrent.CancellationException; | ||
|
|
@@ -53,6 +55,7 @@ public class SpanTracer implements ApiTracer { | |
| private final String attemptSpanName; | ||
| private final ApiTracerContext apiTracerContext; | ||
| private Span attemptSpan; | ||
| private io.opentelemetry.context.Scope scope; | ||
|
|
||
| @Override | ||
| public void injectTraceContext(java.util.Map<String, String> carrier) { | ||
|
|
@@ -144,6 +147,7 @@ public void attemptStarted(Object request, int attemptNumber) { | |
| spanBuilder.setAllAttributes(ObservabilityUtils.toOtelAttributes(currentAttemptAttributes)); | ||
|
|
||
| this.attemptSpan = spanBuilder.startSpan(); | ||
| this.scope = attemptSpan.makeCurrent(); | ||
| } | ||
|
|
||
| @Override | ||
|
|
@@ -249,6 +253,7 @@ private void endAttempt() { | |
| return; | ||
| } | ||
|
|
||
| scope.close(); | ||
| attemptSpan.end(); | ||
| attemptSpan = null; | ||
|
Comment on lines
+256
to
258
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. To ensure exception safety and adhere to the LIFO rule for resource management, try {
if (scope != null) {
scope.close();
}
} finally {
scope = null;
attemptSpan.end();
attemptSpan = null;
}References
|
||
| } | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Managing an OpenTelemetry
Scopeas a class field is risky in asynchronous environments.Scopeis thread-local and must be closed on the same thread it was opened. Ingax-java,ApiTracermethods likeattemptStartedandendAttemptare frequently called on different threads (e.g., the request thread and the gRPC callback thread). Closing the scope on a different thread will lead to incorrect context restoration and potential state corruption in OpenTelemetry.