Repository navigation
Fix Netty HTTP client context propagation on pooled connections #13862
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: master
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 |
|---|---|---|
| @@ -1,10 +1,13 @@ | ||
| package datadog.trace.instrumentation.netty41.client; | ||
|
|
||
| import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan; | ||
| import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.noopSpan; | ||
| import static datadog.trace.bootstrap.instrumentation.api.Tags.HTTP_METHOD; | ||
| import static datadog.trace.instrumentation.netty41.AttributeKeys.CLIENT_CALLBACK_SPAN_KEY; | ||
| import static datadog.trace.instrumentation.netty41.AttributeKeys.CLIENT_PARENT_ATTRIBUTE_KEY; | ||
| import static datadog.trace.instrumentation.netty41.AttributeKeys.CONTEXT_ATTRIBUTE_KEY; | ||
| import static datadog.trace.instrumentation.netty41.AttributeKeys.HTTP_CLIENT_UPGRADED_ATTRIBUTE_KEY; | ||
| import static datadog.trace.instrumentation.netty41.client.NettyHttpClientDecorator.DECORATE; | ||
| import static io.netty.handler.codec.http.HttpMethod.CONNECT; | ||
|
|
||
| import datadog.context.Context; | ||
| import datadog.context.ContextScope; | ||
|
|
@@ -13,8 +16,10 @@ | |
| import io.netty.channel.ChannelHandlerContext; | ||
| import io.netty.channel.ChannelInboundHandlerAdapter; | ||
| import io.netty.handler.codec.http.HttpHeaderNames; | ||
| import io.netty.handler.codec.http.HttpHeaderValues; | ||
| import io.netty.handler.codec.http.HttpResponse; | ||
| import io.netty.handler.codec.http.HttpResponseStatus; | ||
| import io.netty.handler.codec.http.LastHttpContent; | ||
| import io.netty.util.Attribute; | ||
|
|
||
| @ChannelHandler.Sharable | ||
|
|
@@ -25,91 +30,98 @@ public class HttpClientResponseTracingHandler extends ChannelInboundHandlerAdapt | |
| @Override | ||
| public void channelRead(final ChannelHandlerContext ctx, final Object msg) { | ||
| final Attribute<AgentSpan> parentAttr = ctx.channel().attr(CLIENT_PARENT_ATTRIBUTE_KEY); | ||
| parentAttr.setIfAbsent(noopSpan()); | ||
| final AgentSpan parent = parentAttr.get(); | ||
| final Context storedContext = ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).get(); | ||
| final AgentSpan storedParent = parentAttr.get(); | ||
| final AgentSpan parent = storedParent == null ? noopSpan() : storedParent; | ||
| final Attribute<Context> contextAttr = ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY); | ||
| final Context storedContext = contextAttr.get(); | ||
| final AgentSpan span = AgentSpan.fromContext(storedContext); | ||
| final boolean hasClientSpan = span != null && span != parent; | ||
| final Context callbackContext = storedContext == null ? parent : storedContext.with(parent); | ||
|
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. P3 · Preserve active baggage when the channel has no stored exchange With no stored exchange, attaching the fallback span as the entire context drops baggage already active on the caller. On a fresh client channel, I attached baggage and separately delivered an untracked response, fired an exception, and fired Could we use --- found with Codex |
||
|
|
||
| // Set parent context back to maintain the same functionality as getAndSet(parent) | ||
| if (storedContext != null) { | ||
| ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).set(storedContext.with(parent)); | ||
| final HttpResponse response = msg instanceof HttpResponse ? (HttpResponse) msg : null; | ||
| final int status = response == null ? 0 : response.status().code(); | ||
| final boolean websocketUpgrade = | ||
| status == HttpResponseStatus.SWITCHING_PROTOCOLS.code() | ||
| && response | ||
| .headers() | ||
| .containsValue(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET, true); | ||
| final boolean upgraded = | ||
| websocketUpgrade | ||
| || (hasClientSpan | ||
| && status >= 200 | ||
| && status < 300 | ||
| && CONNECT.name().equals(span.getTag(HTTP_METHOD))); | ||
| if (upgraded) { | ||
| // WebSocket and CONNECT retain context until the next HTTP request or channel close. | ||
| ctx.channel().attr(HTTP_CLIENT_UPGRADED_ATTRIBUTE_KEY).set(Boolean.TRUE); | ||
| } | ||
| final boolean finishSpan = hasClientSpan && (status >= 200 || upgraded); | ||
|
|
||
| if (span != null) { | ||
| final boolean finishSpan = | ||
| msg instanceof HttpResponse | ||
| && (!HttpResponseStatus.SWITCHING_PROTOCOLS.equals(((HttpResponse) msg).status()) | ||
| || "websocket" | ||
| .equals(((HttpResponse) msg).headers().get(HttpHeaderNames.UPGRADE))); | ||
| if (finishSpan) { | ||
| try (final ContextScope scope = activateSpan(span)) { | ||
| DECORATE.onResponse(span, (HttpResponse) msg); | ||
| DECORATE.beforeFinish(span); | ||
| span.finish(); | ||
| } | ||
| } else { | ||
| if (storedContext != null) { | ||
| ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).set(storedContext); | ||
| } | ||
| if (finishSpan) { | ||
|
mcculls marked this conversation as resolved.
Resolved
|
||
| // Keep the parent context for body chunks arriving after the client span finishes. | ||
| contextAttr.set(callbackContext); | ||
|
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. P2 · Preserve handler-added baggage when forwarding streamed responses When a try (ContextScope ignored = Context.current().with(baggage).with(child).attach()) {
ctx.fireChannelRead(msg);
}
--- found with Codex |
||
| try (final ContextScope scope = storedContext.attach()) { | ||
| DECORATE.onResponse(span, response); | ||
| DECORATE.beforeFinish(span); | ||
| span.finish(); | ||
| } | ||
| } | ||
|
|
||
| // We want the callback in the scope of the parent, not the client span | ||
| try (final ContextScope scope = activateSpan(parent)) { | ||
| // Informational responses retain the client span for completion, but fire-method advice must | ||
| // leave their callbacks under the parent, including when downstream handlers forward again. | ||
| final Context deliveryContext = | ||
| hasClientSpan && !finishSpan | ||
| ? callbackContext.with(CLIENT_CALLBACK_SPAN_KEY, span) | ||
| : callbackContext; | ||
| try (final ContextScope scope = deliveryContext.attach()) { | ||
| // Clear completed HTTP exchanges before callbacks can start the next request. | ||
| // The attached scope keeps this response's context active during delivery. | ||
| if (msg instanceof LastHttpContent | ||
| && (finishSpan || span == parent) | ||
| && !ctx.channel().hasAttr(HTTP_CLIENT_UPGRADED_ATTRIBUTE_KEY)) { | ||
| contextAttr.set(null); | ||
| parentAttr.set(null); | ||
| } | ||
| ctx.fireChannelRead(msg); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { | ||
| final Attribute<AgentSpan> parentAttr = ctx.channel().attr(CLIENT_PARENT_ATTRIBUTE_KEY); | ||
| parentAttr.setIfAbsent(noopSpan()); | ||
| final AgentSpan parent = parentAttr.get(); | ||
| final Context storedContext = ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).get(); | ||
| final AgentSpan span = AgentSpan.fromContext(storedContext); | ||
|
|
||
| // Set parent context back to maintain the same functionality as getAndSet(parent) | ||
| if (storedContext != null) { | ||
| ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).set(storedContext.with(parent)); | ||
| } | ||
|
|
||
| if (span != null) { | ||
| // If an exception is passed to this point, it likely means it was unhandled and the | ||
| // client span won't be finished with a proper response, so we should finish the span here. | ||
| try (final ContextScope scope = activateSpan(span)) { | ||
| DECORATE.onError(span, cause); | ||
| DECORATE.beforeFinish(span); | ||
| span.finish(); | ||
| } | ||
| } | ||
| // We want the callback in the scope of the parent, not the client span | ||
| try (final ContextScope scope = activateSpan(parent)) { | ||
| // Upgraded protocols can recover from errors, so retain context until the channel closes. | ||
| final Context callbackContext = | ||
| finishExchange(ctx, cause, !ctx.channel().hasAttr(HTTP_CLIENT_UPGRADED_ATTRIBUTE_KEY)); | ||
| try (final ContextScope scope = callbackContext.attach()) { | ||
| super.exceptionCaught(ctx, cause); | ||
| } | ||
| } | ||
|
|
||
| @Override | ||
| public void channelInactive(ChannelHandlerContext ctx) throws Exception { | ||
| final Context callbackContext = finishExchange(ctx, null, true); | ||
| try (final ContextScope scope = callbackContext.attach()) { | ||
| super.channelInactive(ctx); | ||
| } | ||
| } | ||
|
|
||
| private static Context finishExchange(ChannelHandlerContext ctx, Throwable cause, boolean clear) { | ||
| // Clear HTTP exchange state before callbacks can start the next request. | ||
| final Attribute<AgentSpan> parentAttr = ctx.channel().attr(CLIENT_PARENT_ATTRIBUTE_KEY); | ||
| parentAttr.setIfAbsent(noopSpan()); | ||
| final AgentSpan parent = parentAttr.get(); | ||
| final Context storedContext = ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).get(); | ||
| final AgentSpan storedParent = clear ? parentAttr.getAndSet(null) : parentAttr.get(); | ||
| final AgentSpan parent = storedParent == null ? noopSpan() : storedParent; | ||
| final Attribute<Context> contextAttr = ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY); | ||
| final Context storedContext = clear ? contextAttr.getAndSet(null) : contextAttr.get(); | ||
| final AgentSpan span = AgentSpan.fromContext(storedContext); | ||
|
|
||
| // Set parent context back to maintain the same functionality as getAndSet(parent) | ||
| if (storedContext != null) { | ||
| ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).set(storedContext.with(parent)); | ||
| } | ||
|
|
||
| if (span != null && span != parent) { | ||
| try (final ContextScope scope = activateSpan(span)) { | ||
| try (final ContextScope scope = storedContext.attach()) { | ||
| if (cause != null) { | ||
| DECORATE.onError(span, cause); | ||
| } | ||
| DECORATE.beforeFinish(span); | ||
| span.finish(); | ||
| } | ||
| } | ||
| // We want the callback in the scope of the parent, not the client span | ||
| try (final ContextScope scope = activateSpan(parent)) { | ||
| super.channelInactive(ctx); | ||
| } | ||
| return storedContext == null ? parent : storedContext.with(parent); | ||
| } | ||
| } | ||
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.
Performance · Avoid allocating a server request attribute on client channels
When a client event reaches this branch,
currentRequestreads the server request queue throughattr(key).get(). On a fresh client-only channel, Netty creates an entry even though there is no server request. I checkedhasAttr(AttributeKey.valueOf("datadog.server.request.contexts"))before and after forwarding the first client response. It changed fromfalsetotruein both NettytestandlatestDepTest.Could we check
hasAttrbefore looking up the server request queue so the client path avoids creating the empty attribute?--- found with Codex