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
@@ -0,0 +1,68 @@
package datadog.trace.instrumentation.jedis30;

import static datadog.trace.agent.tooling.bytebuddy.matcher.ClassLoaderMatchers.hasClassNamed;
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.blackholeSpan;
import static net.bytebuddy.matcher.ElementMatchers.not;

import com.google.auto.service.AutoService;
import datadog.context.ContextScope;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.agent.tooling.InstrumenterModule;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.matcher.ElementMatcher;

/**
* Stops Jedis 3.x pool liveness checks from producing spans.
*
* <p>The pool checks a connection by sending {@code PING} on borrow, on return and from the idle
* evictor, which {@code JedisPoolConfig} turns on by default. The evictor's checks run with no
* active trace, so each became a standalone root span. The advice runs each check under a
* black-hole span, so the {@code PING} creates no span.
*
* <p>Jedis 4.x needs no equivalent: its pool sends {@code PING} through {@code sendCommand}, which
* that integration does not trace.
*/
@AutoService(InstrumenterModule.class)
public final class PoolValidationInstrumentation extends InstrumenterModule.Tracing
implements Instrumenter.ForKnownTypes, Instrumenter.HasMethodAdvice {

public PoolValidationInstrumentation() {
super("jedis", "redis", "redis-pool-validation");
}

@Override
public ElementMatcher.Junction<ClassLoader> classLoaderMatcher() {
// Jedis 3.x only: ProtocolCommand arrived in 3.0, CommandObject in 4.0
return hasClassNamed("redis.clients.jedis.commands.ProtocolCommand")
.and(not(hasClassNamed("redis.clients.jedis.CommandObject")));
}

@Override
public String[] knownMatchingTypes() {
return new String[] {
"redis.clients.jedis.JedisFactory", "redis.clients.jedis.ShardedJedisPool$ShardedJedisFactory"
};
}

@Override
public void methodAdvice(MethodTransformer transformer) {
transformer.applyAdvice(
named("validateObject"), PoolValidationInstrumentation.class.getName() + "$MuteAdvice");
}
Comment on lines +49 to +53

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 Honor the pool-validation opt-out with selective integrations

With DD_INTEGRATIONS_ENABLED=false and DD_TRACE_JEDIS_ENABLED=true, setting DD_TRACE_REDIS_POOL_VALIDATION_ENABLED=false does not restore validation spans. InstrumenterModule ORs these integration settings when integrations default to disabled, so the enabled Jedis setting overrides the explicit suppression opt-out. Pool-validation PING spans remain suppressed despite the documented switch.

Suggested change
@Override
public void methodAdvice(MethodTransformer transformer) {
transformer.applyAdvice(
named("validateObject"), PoolValidationInstrumentation.class.getName() + "$MuteAdvice");
}
@Override
public void methodAdvice(MethodTransformer transformer) {
datadog.trace.api.InstrumenterConfig config = datadog.trace.api.InstrumenterConfig.get();
if (config.isIntegrationEnabled(
java.util.Collections.singletonList("redis-pool-validation"),
config.isIntegrationsEnabled())) {
transformer.applyAdvice(
named("validateObject"), PoolValidationInstrumentation.class.getName() + "$MuteAdvice");
}
}

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session


public static class MuteAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static ContextScope onEnter() {
return activateSpan(blackholeSpan());
}

@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void onExit(@Advice.Enter final ContextScope scope) {
if (scope != null) {
scope.close();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package datadog.trace.instrumentation.jedis30;

import static datadog.trace.agent.test.utils.TraceUtils.runUnderTrace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.agent.test.utils.PortUtils;
import datadog.trace.core.DDSpan;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.embedded.RedisServer;

/**
* Assertions look for specific spans rather than whole trace shapes: the server-side {@code PING}
* count is read with a traced client.
*/
class PoolValidationInstrumentationTest extends AbstractInstrumentationTest {
private static final Pattern PING_CALLS = Pattern.compile("cmdstat_ping:calls=(\\d+)");

private static int port;
private static RedisServer redisServer;

@BeforeAll
static void startRedis() throws Exception {
port = PortUtils.randomOpenPort();
redisServer =
RedisServer.newRedisServer()
// bind to localhost to avoid a firewall popup
.setting("bind 127.0.0.1")
.setting("maxmemory 128M")
.port(port)
.build();
redisServer.start();
}

@AfterAll
static void stopRedis() throws Exception {
redisServer.stop();
}

@Test
void validationPingCreatesNoSpans() throws Exception {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(1);
config.setTestOnBorrow(true);
long pingsBefore;
try (JedisPool pool = new JedisPool(config, "localhost", port)) {
// warm up so the traced borrow reuses an idle connection, which the pool validates
pool.getResource().close();

pingsBefore = serverPingCount();
runUnderTrace(
"parent",
() -> {
try (Jedis jedis = pool.getResource()) {
jedis.set("foo", "bar");
}
return null;
});
}
assertTrue(serverPingCount() > pingsBefore, "the pool didn't validate on borrow");

blockUntilTracesMatch(traces -> find("SET") != null);
assertEquals(find("parent").getSpanId(), find("SET").getParentId());
for (DDSpan span : allSpans()) {
assertFalse("PING".contentEquals(span.getResourceName()), "validation traced: " + span);
}
}

/** Reads how many {@code PING}s the server has handled, so validation can't pass vacuously. */
private static long serverPingCount() {
try (Jedis jedis = new Jedis("localhost", port)) {
Matcher matcher = PING_CALLS.matcher(jedis.info("commandstats"));
return matcher.find() ? Long.parseLong(matcher.group(1)) : 0;
}
}

private DDSpan find(String resource) {
for (DDSpan span : allSpans()) {
if (resource.contentEquals(span.getResourceName())) {
return span;
}
}
return null;
}

private List<DDSpan> allSpans() {
List<DDSpan> spans = new ArrayList<>();
for (List<DDSpan> trace : writer) {
spans.addAll(trace);
}
return spans;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

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.blackholeSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.startSpan;
import static java.util.Collections.singletonList;
import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;
Expand All @@ -11,6 +14,7 @@
import datadog.context.ContextScope;
import datadog.trace.agent.tooling.Instrumenter;
import datadog.trace.agent.tooling.InstrumenterModule;
import datadog.trace.api.InstrumenterConfig;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import java.util.ArrayList;
import java.util.List;
Expand All @@ -23,15 +27,19 @@

@AutoService(InstrumenterModule.class)
public final class RedissonInstrumentation extends InstrumenterModule.Tracing
implements Instrumenter.ForSingleType, Instrumenter.HasMethodAdvice {
implements Instrumenter.ForKnownTypes, Instrumenter.HasMethodAdvice {

private static final String REDIS_CONNECTION = "org.redisson.client.RedisConnection";
private static final String PING_CONNECTION_HANDLER =
"org.redisson.client.handler.PingConnectionHandler";

public RedissonInstrumentation() {
super("redisson", "redis");
}

@Override
public String instrumentedType() {
return "org.redisson.client.RedisConnection";
public String[] knownMatchingTypes() {
return new String[] {REDIS_CONNECTION, PING_CONNECTION_HANDLER};
}

@Override
Expand All @@ -40,15 +48,51 @@ public void methodAdvice(MethodTransformer transformer) {
isMethod()
.and(isPublic())
.and(named("send"))
.and(takesArgument(0, named("org.redisson.client.protocol.CommandData"))),
.and(takesArgument(0, named("org.redisson.client.protocol.CommandData")))
.and(isDeclaredBy(named(REDIS_CONNECTION))),
RedissonInstrumentation.class.getName() + "$RedissonCommandAdvice");

transformer.applyAdvice(
isMethod()
.and(isPublic())
.and(named("send"))
.and(takesArgument(0, named("org.redisson.client.protocol.CommandsData"))),
.and(takesArgument(0, named("org.redisson.client.protocol.CommandsData")))
.and(isDeclaredBy(named(REDIS_CONNECTION))),
RedissonInstrumentation.class.getName() + "$RedissonCommandsAdvice");

// Lives in this module, rather than its own, so muzzle limits it to the same versions.
// Gated on its own switch, read once here rather than in the advice.
InstrumenterConfig config = InstrumenterConfig.get();
if (config.isIntegrationEnabled(
singletonList("redis-pool-validation"), config.isIntegrationsEnabled())) {
transformer.applyAdvice(
named("sendPing").and(isDeclaredBy(named(PING_CONNECTION_HANDLER))),
RedissonInstrumentation.class.getName() + "$MutePingAdvice");
}
}

/**
* Stops the keepalive {@code PING} from producing spans.
*
* <p>Redisson pings every pooled connection on a timer, every 30 seconds by default. Those pings
* run with no active trace, so each became a standalone root span. The advice runs each ping
* under a black-hole span, so the command it sends creates no span.
*
* <p>The {@code PING} sent once while setting up a connection stays traced, along with the other
* setup commands.
*/
public static class MutePingAdvice {
@Advice.OnMethodEnter(suppress = Throwable.class)
public static ContextScope onEnter() {
return activateSpan(blackholeSpan());
}

@Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
public static void onExit(@Advice.Enter final ContextScope scope) {
if (scope != null) {
scope.close();
}
}
}

public static class RedissonCommandAdvice {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
package datadog.trace.instrumentation.redisson30;

import static datadog.trace.agent.test.utils.TraceUtils.runUnderTrace;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import com.redis.testcontainers.RedisContainer;
import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.core.DDSpan;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.utility.DockerImageName;

class PingSuppressionTest extends AbstractInstrumentationTest {
private static final Pattern PING_CALLS = Pattern.compile("cmdstat_ping:calls=(\\d+)");

private static RedisContainer redis;

@BeforeAll
static void startRedis() {
redis =
new RedisContainer(DockerImageName.parse(System.getProperty("test.redis.image")))
.waitingFor(Wait.forListeningPort());
redis.start();
}

@AfterAll
static void stopRedis() {
redis.stop();
}

@Test
void keepalivePingCreatesNoSpans() throws Exception {
Config config = new Config();
config
.useSingleServer()
.setAddress(redis.getRedisURI())
.setConnectionMinimumIdleSize(1)
.setConnectionPoolSize(1)
.setSubscriptionConnectionMinimumIdleSize(1)
.setSubscriptionConnectionPoolSize(1)
.setPingConnectionInterval(50);
config.setUseScriptCache(false);

RedissonClient client = Redisson.create(config);
try {
// setting up a connection sends one traced PING, and newer versions finish setup after
// create() returns, so let it settle and only count PING spans from then on
Thread.sleep(200);
int setupPingSpans = pingSpanCount();
long pingsBefore = serverPingCount();

runUnderTrace(
"parent",
() -> {
client.getBucket("foo").set("bar");
return null;
});
// several ping intervals
Thread.sleep(500);
assertTrue(serverPingCount() > pingsBefore, "Redisson didn't ping");
assertEquals(setupPingSpans, pingSpanCount(), "keepalive PING traced");
} finally {
client.shutdown();
}

blockUntilTracesMatch(traces -> find("SET") != null);
assertEquals(find("parent").getSpanId(), find("SET").getParentId());
}

private int pingSpanCount() {
int count = 0;
for (DDSpan span : allSpans()) {
if ("PING".contentEquals(span.getResourceName())) {
count++;
}
}
return count;
}

/** Reads the server's {@code PING} count without a traced client. */
private static long serverPingCount() throws Exception {
String info = redis.execInContainer("redis-cli", "info", "commandstats").getStdout();
Matcher matcher = PING_CALLS.matcher(info);
return matcher.find() ? Long.parseLong(matcher.group(1)) : 0;
}

private DDSpan find(String resource) {
for (DDSpan span : allSpans()) {
if (resource.contentEquals(span.getResourceName())) {
return span;
}
}
return null;
}

private List<DDSpan> allSpans() {
List<DDSpan> spans = new ArrayList<>();
for (List<DDSpan> trace : writer) {
spans.addAll(trace);
}
return spans;
}
}
8 changes: 8 additions & 0 deletions metadata/supported-configurations.json
Original file line number Diff line number Diff line change
Expand Up @@ -9644,6 +9644,14 @@
"aliases": ["DD_TRACE_INTEGRATION_REDIS_ENABLED", "DD_INTEGRATION_REDIS_ENABLED"]
}
],
"DD_TRACE_REDIS_POOL_VALIDATION_ENABLED": [
{
"version": "A",
"type": "boolean",
"default": "true",
"aliases": ["DD_TRACE_INTEGRATION_REDIS_POOL_VALIDATION_ENABLED", "DD_INTEGRATION_REDIS_POOL_VALIDATION_ENABLED"]
}
],
"DD_TRACE_REJECTED_EXECUTION_HANDLER_ENABLED": [
{
"version": "A",
Expand Down
Loading