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 @@ -11,10 +11,12 @@
import static datadog.trace.api.datastreams.DataStreamsTags.create;
import static datadog.trace.api.datastreams.DataStreamsTags.createWithExchange;
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.bootstrap.instrumentation.api.AgentTracer.traceConfig;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.currentContext;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.rootContext;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.spanFromContext;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.spanFromScope;
import static datadog.trace.instrumentation.rabbitmq.amqp.RabbitDecorator.CLIENT_DECORATE;
import static datadog.trace.instrumentation.rabbitmq.amqp.RabbitDecorator.CONSUMER_DECORATE;
Expand Down Expand Up @@ -199,13 +201,20 @@ public static void onEnter(
@Advice.Argument(1) final String routingKey,
@Advice.Argument(value = 4, readOnly = false) AMQP.BasicProperties props,
@Advice.Argument(5) final byte[] body) {
AgentSpan span = activeSpan();
if (span == null) return;
Context context = currentContext();
if (context == rootContext()) {
return;
}
AgentSpan span = spanFromContext(context);
Config config = Config.get();
final boolean isDefaultExchange = exchange == null || exchange.isEmpty();
final String destination = isDefaultExchange ? routingKey : exchange;
if (!config.isRabbitPropagationEnabled()
|| config.isRabbitPropagationDisabledForDestination(destination)) return;
// Use the invalid span alone to suppress caller baggage while preserving any DSM pathway.
if (span != null && !span.isValid()) {
context = span;
}
// This is the internal behavior when props are null. We're just doing it earlier now.
if (props == null) {
props = MessageProperties.MINIMAL_BASIC;
Expand All @@ -217,16 +226,15 @@ public static void onEnter(
RabbitDecorator.injectTimeInQueueStart(headers);
}
// With DSM off the DSM propagator injects nothing, so skip building its tags and context.
Context context = span;
if (traceConfig().isDataStreamsEnabled()) {
if (span != null && traceConfig().isDataStreamsEnabled()) {
final boolean hasRoutingKey = routingKey != null && !routingKey.isEmpty();
DataStreamsTags tags;
if (isDefaultExchange && hasRoutingKey) {
tags = create("rabbitmq", OUTBOUND, routingKey);
} else {
tags = createWithExchange("rabbitmq", OUTBOUND, exchange, hasRoutingKey);
}
context = span.with(DataStreamsContext.fromTags(tags));
context = context.with(DataStreamsContext.fromTags(tags));
}
defaultPropagator().inject(context, headers, SETTER);
props =
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package datadog.trace.instrumentation.rabbitmq.amqp;

import static datadog.context.propagation.Propagators.defaultPropagator;
import static datadog.trace.api.datastreams.DataStreamsContext.create;
import static datadog.trace.api.datastreams.DataStreamsTags.Direction.INBOUND;
import static datadog.trace.api.datastreams.DataStreamsTags.create;
import static datadog.trace.bootstrap.instrumentation.api.AgentPropagation.extractContextAndGetSpanContext;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.traceConfig;
import static datadog.trace.bootstrap.instrumentation.api.InstrumentationTags.AMQP_COMMAND;
Expand All @@ -19,6 +18,7 @@
import com.rabbitmq.client.Command;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.Envelope;
import datadog.context.Context;
import datadog.context.ContextScope;
import datadog.trace.api.Config;
import datadog.trace.api.datastreams.DataStreamsTags;
Expand Down Expand Up @@ -206,10 +206,13 @@ public static ContextScope startReceivingSpan(
String queue) {
final Map<String, Object> headers =
propagate && null != properties ? properties.getHeaders() : null;
AgentSpanContext parentSpanContext =
Context context =
null != headers
? extractContextAndGetSpanContext(headers, ContextVisitors.objectValuesMap())
: null;
? defaultPropagator()
.extract(Context.root(), headers, ContextVisitors.objectValuesMap())
: Context.root();
AgentSpan extractedSpan = AgentSpan.fromContext(context);
AgentSpanContext parentSpanContext = extractedSpan == null ? null : extractedSpan.spanContext();
// TODO: check dynamically bound queues -
// https://github.com/DataDog/dd-trace-java/pull/2955#discussion_r677787875

Expand Down Expand Up @@ -263,7 +266,7 @@ public static ContextScope startReceivingSpan(
}

CONSUMER_DECORATE.afterStart(span);
ContextScope scope = activateSpan(span);
ContextScope scope = context.with(span).attach();
if (null != queueSpan) {
queueSpan.finish(spanStartMicros);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package datadog.trace.instrumentation.rabbitmq.amqp;

import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.Java8BytecodeBridge.spanFromScope;
import static datadog.trace.instrumentation.rabbitmq.amqp.RabbitDecorator.CONSUMER_DECORATE;

Expand Down Expand Up @@ -71,7 +70,6 @@ public void handleDelivery(
scope = RabbitDecorator.startReceivingSpan(propagate, 0, properties, body, queue);
AgentSpan span = spanFromScope(scope);
CONSUMER_DECORATE.onDeliver(span, queue, envelope);
scope = activateSpan(span);
} catch (final Exception e) {
log.debug("Instrumentation error in tracing consumer", e);
} finally {
Expand All @@ -86,7 +84,6 @@ public void handleDelivery(
} finally {
if (scope != null) {
CONSUMER_DECORATE.beforeFinish(scope);
scope.close();
RabbitDecorator.finishReceivingSpan(scope);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,237 @@
import static datadog.trace.api.config.GeneralConfig.DATA_STREAMS_ENABLED;
import static datadog.trace.api.config.TraceInstrumentationConfig.LEGACY_CONTEXT_MANAGER_ENABLED;
import static datadog.trace.api.config.TraceInstrumentationConfig.RABBIT_PROPAGATION_DISABLED_EXCHANGES;
import static datadog.trace.api.config.TraceInstrumentationConfig.RABBIT_PROPAGATION_DISABLED_QUEUES;
import static datadog.trace.api.config.TracerConfig.TRACE_PROPAGATION_STYLE;
import static datadog.trace.api.datastreams.PathwayContext.PROPAGATION_KEY_BASE64;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Collections.singletonMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.GetResponse;
import datadog.context.Context;
import datadog.context.ContextScope;
import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.api.Config;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.bootstrap.instrumentation.api.AgentTracer;
import datadog.trace.bootstrap.instrumentation.api.Baggage;
import datadog.trace.test.junit.utils.config.WithConfig;
import datadog.trace.test.util.PollingConditions;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.testcontainers.containers.RabbitMQContainer;
import org.testcontainers.utility.DockerImageName;

@WithConfig(key = TRACE_PROPAGATION_STYLE, value = "tracecontext,baggage")
abstract class RabbitMQBaggagePropagationTest extends AbstractInstrumentationTest {
private static final int ASYNC_TIMEOUT_SECONDS = 15;
private static final String USER_KEY = "user.id";
private static final String BAGGAGE_HEADER = "baggage";
private static final String VALUE = "abc 123,+/%é";
private static final String HEADER = USER_KEY + "=abc%20123%2C+/%25%C3%A9";
private static final String DISABLED_QUEUE = "rabbitmq-baggage-disabled";
private static final String DISABLED_EXCHANGE = "rabbitmq-baggage-exchange";
private static RabbitMQContainer broker;
private Connection connection;
private Channel channel;

@BeforeAll
static void startBroker() {
broker =
new RabbitMQContainer(
DockerImageName.parse(System.getProperty("test.rabbitmq.image"))
.asCompatibleSubstituteFor("rabbitmq"));
broker.withStartupTimeout(Duration.ofSeconds(120));
broker.start();
}

@AfterAll
static void stopBroker() {
if (broker != null) {
broker.stop();
}
}

@BeforeEach
void connect() throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(broker.getHost());
factory.setPort(broker.getMappedPort(5672));
connection = factory.newConnection();
channel = connection.createChannel();
}

@AfterEach
void closeConnection() throws Exception {
try {
if (channel != null && channel.isOpen()) {
channel.close();
}
} finally {
if (connection != null && connection.isOpen()) {
connection.close();
}
}
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
void baggageReachesConsumerAndDownstreamPublish(boolean withParent) throws Exception {
String inbound = channel.queueDeclare().getQueue();
String outbound = channel.queueDeclare().getQueue();
CompletableFuture<String> handled = new CompletableFuture<>();
channel.basicConsume(
inbound,
true,
new DefaultConsumer(channel) {
@Override
public void handleDelivery(
String tag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
try {
assertEquals(VALUE, currentUser());
assertEquals(HEADER, properties.getHeaders().get(BAGGAGE_HEADER).toString());
AgentSpan received = AgentSpan.current();
assertNotNull(received);
channel.basicPublish("", outbound, null, body);
assertSame(received, AgentSpan.current());
handled.complete(currentUser());
} catch (Throwable failure) {
handled.completeExceptionally(failure);
}
}
});
AgentSpan parent = withParent ? AgentTracer.startSpan("test", "parent") : null;
Baggage baggage = Baggage.create(singletonMap(USER_KEY, VALUE));
Map<String, Object> originalHeaders = singletonMap("application", "kept");
AMQP.BasicProperties original =
new AMQP.BasicProperties.Builder()
.contentType("text/plain")
.headers(originalHeaders)
.build();
try (ContextScope ignored = Context.root().with(baggage).with(parent).attach()) {
channel.basicPublish("", inbound, original, "hello".getBytes(UTF_8));
assertSame(baggage, Baggage.fromContext(Context.current()));
assertSame(parent, AgentSpan.current());
} finally {
if (parent != null) {
parent.finish();
}
}
assertEquals(VALUE, handled.get(ASYNC_TIMEOUT_SECONDS, TimeUnit.SECONDS));
assertEquals(originalHeaders, original.getHeaders());
GetResponse response = receive(outbound);
assertEquals("hello", new String(response.getBody(), UTF_8));
assertEquals(HEADER, response.getProps().getHeaders().get(BAGGAGE_HEADER).toString());
if (Config.get().isDataStreamsEnabled()) {
assertNotNull(response.getProps().getHeaders().get(PROPAGATION_KEY_BASE64));
}
assertNull(currentUser());
}

@Test
void existingBaggageAndImmutableHeadersSurviveResend() throws Exception {
String queue = channel.queueDeclare().getQueue();
Map<String, Object> headers = singletonMap(BAGGAGE_HEADER, HEADER);
AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().headers(headers).build();
for (int send = 0; send < 2; send++) {
channel.basicPublish("", queue, properties, "existing".getBytes(UTF_8));
assertEquals(HEADER, receive(queue).getProps().getHeaders().get(BAGGAGE_HEADER).toString());
assertEquals(headers, properties.getHeaders());
assertNull(currentUser());
}
}

@Test
void blackholeSpanDoesNotInjectCallerBaggage() throws Exception {
String queue = channel.queueDeclare().getQueue();
AgentSpan span = AgentTracer.blackholeSpan();
Baggage baggage = Baggage.create(singletonMap(USER_KEY, VALUE));
try (ContextScope ignored = Context.root().with(span).with(baggage).attach()) {
channel.basicPublish("", queue, null, "suppressed".getBytes(UTF_8));
assertSame(span, AgentSpan.current());
assertSame(baggage, Baggage.fromContext(Context.current()));
}
Map<String, Object> headers = receive(queue).getProps().getHeaders();
assertNull(headers == null ? null : headers.get(BAGGAGE_HEADER));
assertNull(currentUser());
}

@Test
@WithConfig(key = "rabbit.propagation.enabled", value = "false")
void disabledPropagationDoesNotInjectBaggage() throws Exception {
assertBaggageNotInjected("", channel.queueDeclare().getQueue());
}

@Test
@WithConfig(key = RABBIT_PROPAGATION_DISABLED_QUEUES, value = DISABLED_QUEUE)
void disabledQueueDoesNotInjectBaggage() throws Exception {
channel.queueDeclare(DISABLED_QUEUE, false, true, true, null);
assertBaggageNotInjected("", DISABLED_QUEUE);
}

@Test
@WithConfig(key = RABBIT_PROPAGATION_DISABLED_EXCHANGES, value = DISABLED_EXCHANGE)
void disabledExchangeDoesNotInjectBaggage() throws Exception {
String queue = channel.queueDeclare().getQueue();
channel.exchangeDeclare(DISABLED_EXCHANGE, "direct", false, true, null);
channel.queueBind(queue, DISABLED_EXCHANGE, queue);
assertBaggageNotInjected(DISABLED_EXCHANGE, queue);
}

private void assertBaggageNotInjected(String exchange, String queue) throws Exception {
try (ContextScope ignored =
Context.root().with(Baggage.create(singletonMap(USER_KEY, VALUE))).attach()) {
channel.basicPublish(exchange, queue, null, "disabled".getBytes(UTF_8));
}
Map<String, Object> headers = receive(queue).getProps().getHeaders();
assertNull(headers == null ? null : headers.get(BAGGAGE_HEADER));
assertNull(currentUser());
}

private GetResponse receive(String queue) {
AtomicReference<GetResponse> response = new AtomicReference<>();
new PollingConditions(ASYNC_TIMEOUT_SECONDS)
.delay(0)
.eventually(() -> {
response.set(channel.basicGet(queue, true));
assertNotNull(response.get());
});
return response.get();
}

private static String currentUser() {
Baggage baggage = Baggage.fromContext(Context.current());
return baggage == null ? null : baggage.asMap().get(USER_KEY);
}
}

class RabbitMQBaggagePropagationForkedTest extends RabbitMQBaggagePropagationTest {}

@WithConfig(key = LEGACY_CONTEXT_MANAGER_ENABLED, value = "false")
class RabbitMQBaggageSwapPropagationForkedTest extends RabbitMQBaggagePropagationTest {}

@WithConfig(key = DATA_STREAMS_ENABLED, value = "true")
@WithConfig(key = "rabbitmq.time-in-queue.enabled", value = "true")
class RabbitMQBaggageDataStreamsForkedTest extends RabbitMQBaggagePropagationTest {}
Loading
Loading