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 @@ -438,8 +438,12 @@ public long setContextInfo(Connection connection, JDBCConnectionContext connecti
DECORATE.afterStart(instrumentationSpan);
DECORATE.onConnection(instrumentationSpan, connectionContext);
try (ContextScope scope = activateSpan(instrumentationSpan)) {
final byte samplingDecision =
(byte) (instrumentationSpan.forceSamplingDecision() > 0 ? 1 : 0);
final Integer priority = instrumentationSpan.forceSamplingDecision();
if (priority == null) {
// no trace to correlate with, e.g. tracing is muted for this call
return spanID;
}
final byte samplingDecision = (byte) (priority > 0 ? 1 : 0);
final byte versionAndSamplingDecision =
(byte) ((VERSION << 4) & 0b11110000 | samplingDecision & 0b00000001);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package datadog.trace.instrumentation.jdbc;

import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.named;
import static datadog.trace.agent.tooling.bytebuddy.matcher.NameMatchers.namedOneOf;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.blackholeSpan;
import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;
import static net.bytebuddy.matcher.ElementMatchers.takesArgument;

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;

/**
* Stops connection pools' liveness checks from producing spans.
*
* <p>A pool checks that a connection is still usable by running a validation query, such as {@code
* SELECT 1 FROM DUAL}, or by calling {@link java.sql.Connection#isValid}. Those checks run on
* borrow, on return, and from keepalive timers, so they show up both inside application traces and
* as standalone root spans. The advice runs each check under a black-hole span: nothing it executes
* creates a span or injects trace context into the database.
*
* <p>Statements the pool runs on the application's behalf, such as connection init SQL, stay
* traced.
*/
@AutoService(InstrumenterModule.class)
public final class PoolValidationInstrumentation extends InstrumenterModule.Tracing
implements Instrumenter.ForKnownTypes, Instrumenter.HasMethodAdvice {

private static final String HIKARI_POOL_BASE = "com.zaxxer.hikari.pool.PoolBase";
private static final String HIKARI_POOL_ELF = "com.zaxxer.hikari.pool.PoolElf";
private static final String DBCP2_CONNECTION = "org.apache.commons.dbcp2.PoolableConnection";
private static final String TOMCAT_DBCP2_CONNECTION =
"org.apache.tomcat.dbcp.dbcp2.PoolableConnection";
private static final String TOMCAT_JDBC_CONNECTION =
"org.apache.tomcat.jdbc.pool.PooledConnection";
private static final String C3P0_POOL_MANAGER =
"com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager";

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

@Override
public String[] knownMatchingTypes() {
return new String[] {
HIKARI_POOL_BASE, // HikariCP 2.4.1+
HIKARI_POOL_ELF, // HikariCP 2.4.0
DBCP2_CONNECTION, // standalone
TOMCAT_DBCP2_CONNECTION, // bundled with Tomcat
TOMCAT_JDBC_CONNECTION,
C3P0_POOL_MANAGER
};
}

@Override
public void methodAdvice(MethodTransformer transformer) {
String muteAdvice = PoolValidationInstrumentation.class.getName() + "$MuteValidationAdvice";
// isConnectionAlive (isConnectionDead in 7.x) runs on borrow and from the keepalive timer;
// checkValidationSupport runs the test query once when a connection is created
transformer.applyAdvice(
namedOneOf("isConnectionAlive", "isConnectionDead", "checkValidationSupport")
.and(isDeclaredBy(namedOneOf(HIKARI_POOL_BASE, HIKARI_POOL_ELF))),
muteAdvice);
transformer.applyAdvice(
named("validate").and(isDeclaredBy(namedOneOf(DBCP2_CONNECTION, TOMCAT_DBCP2_CONNECTION))),
muteAdvice);
transformer.applyAdvice(
named("testPooledConnection").and(isDeclaredBy(named(C3P0_POOL_MANAGER))), muteAdvice);
transformer.applyAdvice(
named("validate")
.and(takesArgument(0, int.class))
.and(isDeclaredBy(named(TOMCAT_JDBC_CONNECTION))),
PoolValidationInstrumentation.class.getName() + "$TomcatValidateAdvice");
}

public static class MuteValidationAdvice {
@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();
}
}
}

/**
* Tomcat JDBC runs the user's init SQL through {@code validate(VALIDATE_INIT)}, so that action
* stays traced, along with the test-on-connect check that shares it.
*/
public static class TomcatValidateAdvice {
/** {@code org.apache.tomcat.jdbc.pool.PooledConnection.VALIDATE_INIT} */
public static final int VALIDATE_INIT = 4;

@Advice.OnMethodEnter(suppress = Throwable.class)
public static ContextScope onEnter(@Advice.Argument(0) final int validateAction) {
if (validateAction == VALIDATE_INIT) {
return null;
}
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,199 @@
package datadog.trace.instrumentation.jdbc;

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 com.mchange.v2.c3p0.ComboPooledDataSource;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.core.DDSpan;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

/**
* Public so H2 can call {@link #ping()}.
*
* <p>Assertions look for specific spans rather than whole trace shapes: other tests in the same JVM
* can leave pool classes transformed to emit connection spans.
*/
public class PoolValidationInstrumentationTest extends AbstractInstrumentationTest {
private static final String URL = "jdbc:h2:mem:pool_validation;DB_CLOSE_DELAY=-1";

/** Validation query whose calls are counted, so a test can't pass without validating. */
private static final String VALIDATION_QUERY = "SELECT PING()";

private static final AtomicInteger PINGS = new AtomicInteger();

/** Called by H2 for {@code PING()}. */
public static int ping() {
PINGS.incrementAndGet();
return 1;
}

@BeforeAll
static void setUpDatabase() throws Exception {
Class.forName("org.h2.Driver");
try (Connection connection = DriverManager.getConnection(URL);
Statement statement = connection.createStatement()) {
statement.execute(
"CREATE ALIAS IF NOT EXISTS PING FOR \""
+ PoolValidationInstrumentationTest.class.getName()
+ ".ping\"");
}
}

@ParameterizedTest
@ValueSource(strings = {"hikari", "dbcp2", "tomcat", "c3p0"})
void validationQueryCreatesNoSpans(String pool) throws Exception {
try (Pool p = createPool(pool)) {
DataSource ds = p.dataSource;
// warm up so the traced borrow reuses an idle connection, which the pool must validate
ds.getConnection().close();
// Hikari only re-validates once time has passed since the connection's last use, even with
// its bypass window at 0
Thread.sleep(10);

int pingsBefore = PINGS.get();
runUnderTrace(
"parent",
() -> {
try (Connection connection = ds.getConnection();
Statement statement = connection.createStatement()) {
statement.execute("SELECT 2 AS app_query");
}
return null;
});
assertTrue(PINGS.get() > pingsBefore, "the pool didn't validate on borrow");
}

// the pool is closed, so no validation from a background thread can arrive late
assertChildOfParent("SELECT ? AS app_query");
for (DDSpan span : allSpans()) {
assertFalse(
span.getResourceName().toString().contains("PING"), "validation query traced: " + span);
}
}

@Test
void tomcatInitSqlStaysTraced() throws Exception {
org.apache.tomcat.jdbc.pool.DataSource ds = tomcatDataSource();
ds.setInitSQL("SELECT 3 AS init_sql");
try {
runUnderTrace(
"parent",
() -> {
ds.getConnection().close();
return null;
});
} finally {
ds.close();
}

assertChildOfParent("SELECT ? AS init_sql");
}

/** Waits for the span with {@code resource} and checks it is a child of the test's parent. */
private void assertChildOfParent(String resource) {
blockUntilTracesMatch(traces -> find(resource) != null);
DDSpan parent = find("parent");
DDSpan span = find(resource);
assertEquals("sql", span.getSpanType());
assertEquals(parent.getSpanId(), span.getParentId(), "not a child of the parent: " + span);
}

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

private static Pool createPool(String pool) throws Exception {
switch (pool) {
case "hikari":
// Hikari skips the liveness check for a recently used connection; 2.4.0 reads the
// property without the Ms suffix. The test extension restores system properties.
System.setProperty("com.zaxxer.hikari.aliveBypassWindowMs", "0");
System.setProperty("com.zaxxer.hikari.aliveBypassWindow", "0");
HikariConfig config = new HikariConfig();
config.setJdbcUrl(URL);
config.setConnectionTestQuery(VALIDATION_QUERY);
config.setMaximumPoolSize(1);
HikariDataSource hikari = new HikariDataSource(config);
return new Pool(hikari, hikari::close);
case "dbcp2":
BasicDataSource dbcp2 = new BasicDataSource();
dbcp2.setUrl(URL);
dbcp2.setValidationQuery(VALIDATION_QUERY);
dbcp2.setTestOnBorrow(true);
dbcp2.setMaxTotal(1);
return new Pool(dbcp2, dbcp2::close);
case "tomcat":
org.apache.tomcat.jdbc.pool.DataSource tomcat = tomcatDataSource();
tomcat.setValidationQuery(VALIDATION_QUERY);
tomcat.setTestOnBorrow(true);
tomcat.setValidationInterval(0);
return new Pool(tomcat, tomcat::close);
case "c3p0":
ComboPooledDataSource c3p0 = new ComboPooledDataSource();
c3p0.setDriverClass("org.h2.Driver");
c3p0.setJdbcUrl(URL);
c3p0.setPreferredTestQuery(VALIDATION_QUERY);
c3p0.setTestConnectionOnCheckout(true);
c3p0.setMinPoolSize(1);
c3p0.setInitialPoolSize(1);
c3p0.setMaxPoolSize(1);
return new Pool(c3p0, c3p0::close);
default:
throw new IllegalArgumentException(pool);
}
}

private static org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource() {
org.apache.tomcat.jdbc.pool.DataSource ds = new org.apache.tomcat.jdbc.pool.DataSource();
ds.setUrl(URL);
ds.setDriverClassName("org.h2.Driver");
ds.setInitialSize(0);
ds.setMinIdle(0);
ds.setMaxActive(1);
return ds;
}

private static final class Pool implements AutoCloseable {
final DataSource dataSource;
final AutoCloseable closer;

Pool(DataSource dataSource, AutoCloseable closer) {
this.dataSource = dataSource;
this.closer = closer;
}

@Override
public void close() throws Exception {
closer.close();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package datadog.trace.instrumentation.jdbc;

import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.activateSpan;
import static datadog.trace.bootstrap.instrumentation.api.AgentTracer.blackholeSpan;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;

import datadog.context.ContextScope;
import datadog.trace.agent.test.AbstractInstrumentationTest;
import datadog.trace.bootstrap.instrumentation.jdbc.DBInfo;
import datadog.trace.bootstrap.instrumentation.jdbc.JDBCConnectionContext;
import java.lang.reflect.Field;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;

class SetContextInfoTest extends AbstractInstrumentationTest {

@Test
void skipsContextInfoWhenTracingIsMuted() throws Exception {
List<String> calls = new ArrayList<>();
Connection connection =
(Connection)
Proxy.newProxyInstance(
Connection.class.getClassLoader(),
new Class<?>[] {Connection.class},
(proxy, method, args) -> {
calls.add(method.getName());
throw new UnsupportedOperationException(method.getName());
});
JDBCDecorator decorator = new JDBCDecorator();

// as when a pool validates a connection: spans started here have no sampling decision
try (ContextScope scope = activateSpan(blackholeSpan())) {
decorator.setContextInfo(connection, new JDBCConnectionContext(DBInfo.DEFAULT));
}

assertEquals(new ArrayList<String>(), calls, "no round trip without a trace to correlate");
assertFalse(loggedInjectionError(decorator), "an injection error was logged");
}

/** The once-only warning flag: a spurious warning would hide later real injection failures. */
private static boolean loggedInjectionError(JDBCDecorator decorator) throws Exception {
Field field = JDBCDecorator.class.getDeclaredField("loggedInjectionError");
field.setAccessible(true);
return field.getBoolean(decorator);
}
}
8 changes: 8 additions & 0 deletions metadata/supported-configurations.json
Original file line number Diff line number Diff line change
Expand Up @@ -7508,6 +7508,14 @@
"aliases": ["DD_TRACE_INTEGRATION_JDBC_ENABLED", "DD_INTEGRATION_JDBC_ENABLED"]
}
],
"DD_TRACE_JDBC_POOL_VALIDATION_ENABLED": [
{
"version": "A",
"type": "boolean",
"default": "true",
"aliases": ["DD_TRACE_INTEGRATION_JDBC_POOL_VALIDATION_ENABLED", "DD_INTEGRATION_JDBC_POOL_VALIDATION_ENABLED"]
}
],
"DD_TRACE_JDBC_PREPARED_STATEMENT_CLASS_NAME": [
{
"version": "A",
Expand Down
Loading