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
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public static ContextScope activateScope(@Advice.Argument(0) final ChannelFuture
- To capture scope only in case of error.
*/
final Throwable cause = future.cause();
if (cause == null) {
if (cause == null || !future.channel().hasAttr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY)) {
return null;
}
final ContextContinuation continuation =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public void operationComplete(final ChannelFuture future) {
}

public static void cancel(final Channel channel) {
if (channel == null) {
if (channel == null || !channel.hasAttr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY)) {
return;
}
final ContextContinuation continuation =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@
import static datadog.trace.agent.tooling.bytebuddy.matcher.HierarchyMatchers.implementsInterface;
import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.nameStartsWith;
import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.currentContext;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.spanFromContext;
import static datadog.trace.instrumentation.netty41.AttributeKeys.CLIENT_CALLBACK_SPAN_KEY;
import static datadog.trace.instrumentation.netty41.AttributeKeys.CONTEXT_ATTRIBUTE_KEY;
import static datadog.trace.instrumentation.netty41.NettyChannelPipelineInstrumentation.ADDITIONAL_INSTRUMENTATION_NAMES;
import static datadog.trace.instrumentation.netty41.NettyChannelPipelineInstrumentation.INSTRUMENTATION_NAME;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;

import com.google.auto.service.AutoService;
import datadog.context.Context;
import datadog.context.ContextScope;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.agent.tooling.InstrumenterModule;
Expand Down Expand Up @@ -71,13 +72,24 @@ public void methodAdvice(MethodTransformer transformer) {
public static class FireAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static ContextScope scopeSpan(@Advice.This final ChannelHandlerContext ctx) {
final AgentSpan channelSpan =
spanFromContext(ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).get());
if (channelSpan == null || channelSpan == activeSpan()) {
final Context channelContext = ctx.channel().attr(CONTEXT_ATTRIBUTE_KEY).get();
final AgentSpan channelSpan = spanFromContext(channelContext);
if (channelSpan == null) {
return null;
}
final Context current = currentContext();
if (channelSpan == spanFromContext(current)
|| channelSpan == current.get(CLIENT_CALLBACK_SPAN_KEY)) {
// don't modify the scope
return null;
}
return activateSpan(channelSpan);
if (ServerRequestContext.currentRequest(ctx.channel()) != null) {

Copy link
Copy Markdown
Contributor

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, currentRequest reads the server request queue through attr(key).get(). On a fresh client-only channel, Netty creates an entry even though there is no server request. I checked hasAttr(AttributeKey.valueOf("datadog.server.request.contexts")) before and after forwarding the first client response. It changed from false to true in both Netty test and latestDepTest.

Could we check hasAttr before looking up the server request queue so the client path avoids creating the empty attribute?

--- found with Codex

// Keep baggage added by server handlers when restoring the server span.
return channelSpan.attachWithContext();
}
// Client events such as TLS completion may arrive without request context.
// Restore the captured context so subsequent requests inherit its baggage.
return channelContext.attach();
Comment thread
mcculls marked this conversation as resolved.
Resolved
}

@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@

import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activeSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.noopSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan;
import static datadog.trace.instrumentation.netty41.AttributeKeys.CLIENT_PARENT_ATTRIBUTE_KEY;
import static datadog.trace.instrumentation.netty41.AttributeKeys.CONNECT_PARENT_CONTINUATION_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 datadog.trace.instrumentation.netty41.client.NettyHttpClientDecorator.DECORATE_SECURE;
import static datadog.trace.instrumentation.netty41.client.NettyHttpClientDecorator.NETTY_CLIENT;
Expand Down Expand Up @@ -53,10 +55,22 @@ public void write(final ChannelHandlerContext ctx, final Object msg, final Chann
return;
}

// A new HTTP request can follow CONNECT or a rejected WebSocket handshake.
if (ctx.channel().hasAttr(HTTP_CLIENT_UPGRADED_ATTRIBUTE_KEY)) {
ctx.channel().attr(HTTP_CLIENT_UPGRADED_ATTRIBUTE_KEY).remove();
}

ContextScope parentScope = null;
final ContextContinuation continuation = takeConnectParentContinuation(ctx);
if (continuation != null) {
parentScope = continuation.resume();
// Root and a bare noop span carry no caller data, so use the connection context.
// Otherwise, keep the current context and release the unused continuation.
final Context current = Context.current();
if (current == Context.root() || current == noopSpan()) {
parentScope = continuation.resume();
} else {
continuation.release();
}
}

final HttpRequest request = (HttpRequest) msg;
Expand Down Expand Up @@ -114,9 +128,13 @@ public void write(final ChannelHandlerContext ctx, final Object msg, final Chann
private static ContextContinuation takeConnectParentContinuation(
final ChannelHandlerContext ctx) {
final Channel channel = ctx.channel();
ContextContinuation continuation =
channel.attr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY).getAndRemove();
if (continuation == null && channel.parent() != null) {
ContextContinuation continuation = null;
if (channel.hasAttr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY)) {
continuation = channel.attr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY).getAndRemove();
}
if (continuation == null
&& channel.parent() != null
&& channel.parent().hasAttr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY)) {
continuation =
channel.parent().attr(CONNECT_PARENT_CONTINUATION_ATTRIBUTE_KEY).getAndRemove();
}
Expand Down
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;
Expand All @@ -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
Expand All @@ -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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The 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 channelInactive. In both Netty test and latestDepTest, all three callbacks saw the expected noop span but read null for baggage.

Could we use Context.current().with(parent) when storedContext is absent, here and in finishExchange? That preserves the caller's baggage and still gives a bare noop span when the current context is root.

--- 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) {
Comment thread
mcculls marked this conversation as resolved.
Resolved
// Keep the parent context for body chunks arriving after the client span finishes.
contextAttr.set(callbackContext);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 · Preserve handler-added baggage when forwarding streamed responses

When a 200 OK arrives as separate headers and body, this stores the request-parent context on the channel. A downstream handler can then add baggage, activate a child span, and forward the headers:

try (ContextScope ignored = Context.current().with(baggage).with(child).attach()) {
  ctx.fireChannelRead(msg);
}

FireAdvice sees the child span differ from the stored parent and attaches the entire saved context. The next handler sees no baggage added by the forwarding handler. This reproduced in both Netty test and latestDepTest with a DefaultHttpResponse followed by LastHttpContent. Could we preserve the live context while handlers forward a response, while still restoring the captured context for events such as TLS completion?

--- 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);
}
}
Loading
Loading