Skip to content
Draft
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
1 change: 1 addition & 0 deletions sentry-jdbc/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ dependencies {
testImplementation(projects.sentryTestSupport)
testImplementation(kotlin(Config.kotlinStdLib))
testImplementation(libs.awaitility.kotlin)
testImplementation(libs.google.truth)
testImplementation(libs.hsqldb)
testImplementation(libs.kotlin.test.junit)
testImplementation(libs.mockito.kotlin)
Expand Down
27 changes: 22 additions & 5 deletions sentry-jdbc/src/main/java/io/sentry/jdbc/DatabaseUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,10 @@ public static DatabaseDetails parse(final @Nullable String databaseConnectionUrl
return parseAsUri(dbSystem, StringUtils.removePrefix(urlString, dbSystem + ":"));
}
if (urlParts.length > 2) {
String dbNameAndMaybeMore = urlParts[2];
return new DatabaseDetails(dbSystem, StringUtils.substringBefore(dbNameAndMaybeMore, ";"));
return new DatabaseDetails(dbSystem, fileDbNameWithoutProperties(urlParts[2]));
}
if (urlParts.length > 1) {
String dbNameAndMaybeMore = urlParts[1];
return new DatabaseDetails(dbSystem, StringUtils.substringBefore(dbNameAndMaybeMore, ";"));
return new DatabaseDetails(dbSystem, fileDbNameWithoutProperties(urlParts[1]));
}
}
if ("mariadb".equalsIgnoreCase(dbSystem)
Expand Down Expand Up @@ -119,13 +117,32 @@ public static DatabaseDetails parse(final @Nullable String databaseConnectionUrl
return new DatabaseDetails(dbSystem, null);
}

private static final char[] FILE_DB_NAME_PROPERTY_SEPARATORS = {';', '?', '#'};

/**
* Cuts connection properties off a database name: {@code ;} (H2, HSQLDB, Derby) and {@code ?} or
* {@code #} (SQLite and HSQLDB URIs). The properties can hold a database key or password.
*/
private static @Nullable String fileDbNameWithoutProperties(
final @NotNull String dbNameAndMaybeMore) {
int end = dbNameAndMaybeMore.length();
for (final char separator : FILE_DB_NAME_PROPERTY_SEPARATORS) {
final int index = dbNameAndMaybeMore.indexOf(separator);
if (index >= 0 && index < end) {
end = index;
}
}
return end == 0 ? null : dbNameAndMaybeMore.substring(0, end);
}

private static @NotNull DatabaseDetails parseAsUri(
final @NotNull String dbSystem, final @NotNull String urlString) {
try {
final @NotNull URI url = new URI(urlString);
String path = StringUtils.removePrefix(url.getPath(), "/");
String pathWithoutProperties = StringUtils.substringBefore(path, ";");
return new DatabaseDetails(dbSystem, pathWithoutProperties);
return new DatabaseDetails(
dbSystem, pathWithoutProperties.isEmpty() ? null : pathWithoutProperties);
} catch (Throwable t) {
// ignore
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,33 +1,44 @@
package io.sentry.jdbc;

import static io.sentry.SpanDataConvention.DB_NAMESPACE_KEY;
import static io.sentry.SpanDataConvention.DB_NAME_KEY;
import static io.sentry.SpanDataConvention.DB_SYSTEM_KEY;
import static io.sentry.SpanDataConvention.DB_SYSTEM_NAME_KEY;

import com.jakewharton.nopen.annotation.Open;
import com.p6spy.engine.common.ConnectionInformation;
import com.p6spy.engine.common.StatementInformation;
import com.p6spy.engine.event.SimpleJdbcEventListener;
import io.sentry.IScopes;
import io.sentry.ISentryLifecycleToken;
import io.sentry.ISpan;
import io.sentry.ScopesAdapter;
import io.sentry.SentryIntegrationPackageStorage;
import io.sentry.SpanOptions;
import io.sentry.SpanStatus;
import io.sentry.util.AutoClosableReentrantLock;
import io.sentry.util.Objects;
import io.sentry.util.SpanUtils;
import io.sentry.util.sql.SqlSpanData;
import java.sql.SQLException;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

@Open
public class SentryJdbcEventListener extends SimpleJdbcEventListener {
private static final String TRACE_ORIGIN = "auto.db.jdbc";

/** Maximum length of the sanitized query text, OpenTelemetry Java's value. */
private static final int MAX_QUERY_TEXT_LENGTH = 32 * 1024;

private final @NotNull IScopes scopes;
private static final @NotNull ThreadLocal<ISpan> CURRENT_QUERY_SPAN = new ThreadLocal<>();
private static final @NotNull ThreadLocal<ISpan> CURRENT_TRANSACTION_SPAN = new ThreadLocal<>();

private volatile @Nullable DatabaseUtils.DatabaseDetails cachedDatabaseDetails = null;
/**
* No longer used: database details are parsed from the connection URL once per span, not cached,
* so no connection URL (which may contain credentials) is retained. Kept for binary compatibility
* with subclasses.
*/
protected final @NotNull AutoClosableReentrantLock databaseDetailsLock =
new AutoClosableReentrantLock();

Expand All @@ -47,15 +58,30 @@ public SentryJdbcEventListener() {

@Override
public void onBeforeAnyExecute(final @NotNull StatementInformation statementInformation) {
startSpan(CURRENT_QUERY_SPAN, "db.query", statementInformation.getSql());
final @Nullable ISpan parent = getActiveParent();
if (parent == null) {
return;
}
final @NotNull DatabaseUtils.DatabaseDetails databaseDetails =
DatabaseUtils.readFrom(statementInformation.getConnectionInformation());
final @NotNull SqlSpanData queryData =
SqlSpanData.analyze(
statementInformation.getSql(),
databaseDetails.getDbSystem(),
MAX_QUERY_TEXT_LENGTH,
scopes.getOptions().getLogger());
final @NotNull ISpan span =
startChild(parent, CURRENT_QUERY_SPAN, "db.query", queryData.getDescription());
applyDatabaseDetailsToSpan(databaseDetails, span);
queryData.applyTo(span);
}

@Override
public void onAfterAnyExecute(
final @NotNull StatementInformation statementInformation,
long timeElapsedNanos,
final @Nullable SQLException e) {
finishSpan(CURRENT_QUERY_SPAN, statementInformation.getConnectionInformation(), e);
finishSpan(CURRENT_QUERY_SPAN, e);
}

@Override
Expand All @@ -68,7 +94,8 @@ public void onBeforeSetAutoCommit(
}
final boolean isSwitchingToManualCommit = !newAutoCommit && currentAutoCommit;
if (isSwitchingToManualCommit) {
startSpan(CURRENT_TRANSACTION_SPAN, "db.sql.transaction.begin", "BEGIN");
startSpan(
CURRENT_TRANSACTION_SPAN, "db.sql.transaction.begin", "BEGIN", connectionInformation);
}
}

Expand All @@ -83,7 +110,7 @@ public void onAfterSetAutoCommit(
}
final boolean isSwitchingToManualCommit = !newAutoCommit && oldAutoCommit;
if (isSwitchingToManualCommit) {
finishSpan(CURRENT_TRANSACTION_SPAN, connectionInformation, e);
finishSpan(CURRENT_TRANSACTION_SPAN, e);
}
}

Expand All @@ -92,7 +119,8 @@ public void onBeforeCommit(final @NotNull ConnectionInformation connectionInform
if (!isDatabaseTransactionTracingEnabled()) {
return;
}
startSpan(CURRENT_TRANSACTION_SPAN, "db.sql.transaction.commit", "COMMIT");
startSpan(
CURRENT_TRANSACTION_SPAN, "db.sql.transaction.commit", "COMMIT", connectionInformation);
}

@Override
Expand All @@ -103,15 +131,16 @@ public void onAfterCommit(
if (!isDatabaseTransactionTracingEnabled()) {
return;
}
finishSpan(CURRENT_TRANSACTION_SPAN, connectionInformation, e);
finishSpan(CURRENT_TRANSACTION_SPAN, e);
}

@Override
public void onBeforeRollback(final @NotNull ConnectionInformation connectionInformation) {
if (!isDatabaseTransactionTracingEnabled()) {
return;
}
startSpan(CURRENT_TRANSACTION_SPAN, "db.sql.transaction.rollback", "ROLLBACK");
startSpan(
CURRENT_TRANSACTION_SPAN, "db.sql.transaction.rollback", "ROLLBACK", connectionInformation);
}

@Override
Expand All @@ -122,7 +151,7 @@ public void onAfterRollback(
if (!isDatabaseTransactionTracingEnabled()) {
return;
}
finishSpan(CURRENT_TRANSACTION_SPAN, connectionInformation, e);
finishSpan(CURRENT_TRANSACTION_SPAN, e);
}

private boolean isDatabaseTransactionTracingEnabled() {
Expand All @@ -132,25 +161,45 @@ private boolean isDatabaseTransactionTracingEnabled() {
private void startSpan(
final @NotNull ThreadLocal<ISpan> spanHolder,
final @NotNull String operation,
final @Nullable String description) {
final @Nullable ISpan parent = scopes.getSpan();
if (parent != null && !parent.isNoOp()) {
final @NotNull SpanOptions spanOptions = new SpanOptions();
spanOptions.setOrigin(TRACE_ORIGIN);
final @NotNull ISpan span = parent.startChild(operation, description, spanOptions);
spanHolder.set(span);
final @Nullable String description,
final @Nullable ConnectionInformation connectionInformation) {
final @Nullable ISpan parent = getActiveParent();
if (parent != null) {
final @NotNull ISpan span = startChild(parent, spanHolder, operation, description);
applyDatabaseDetailsToSpan(DatabaseUtils.readFrom(connectionInformation), span);
}
}

private void finishSpan(
/**
* Returns the parent for a JDBC span, or {@code null} if no span would be recorded: no active
* span, or our origin is ignored (the default under OpenTelemetry), which would only yield a
* no-op child after the statement was analyzed.
*/
private @Nullable ISpan getActiveParent() {
if (SpanUtils.isIgnored(scopes.getOptions().getIgnoredSpanOriginFilters(), TRACE_ORIGIN)) {
return null;
}
final @Nullable ISpan parent = scopes.getSpan();
return parent != null && !parent.isNoOp() ? parent : null;
}

private @NotNull ISpan startChild(
final @NotNull ISpan parent,
final @NotNull ThreadLocal<ISpan> spanHolder,
final @Nullable ConnectionInformation connectionInformation,
final @Nullable SQLException e) {
final @NotNull String operation,
final @Nullable String description) {
final @NotNull SpanOptions spanOptions = new SpanOptions();
spanOptions.setOrigin(TRACE_ORIGIN);
final @NotNull ISpan span = parent.startChild(operation, description, spanOptions);
spanHolder.set(span);
return span;
}

private void finishSpan(
final @NotNull ThreadLocal<ISpan> spanHolder, final @Nullable SQLException e) {
final @Nullable ISpan span = spanHolder.get();

if (span != null) {
applyDatabaseDetailsToSpan(connectionInformation, span);

if (e != null) {
span.setThrowable(e);
span.setStatus(SpanStatus.INTERNAL_ERROR);
Expand All @@ -167,29 +216,20 @@ private void addPackageAndIntegrationInfo() {
}

private void applyDatabaseDetailsToSpan(
final @Nullable ConnectionInformation connectionInformation, final @NotNull ISpan span) {
final @NotNull DatabaseUtils.DatabaseDetails databaseDetails =
getOrComputeDatabaseDetails(connectionInformation);

if (databaseDetails.getDbSystem() != null) {
span.setData(DB_SYSTEM_KEY, databaseDetails.getDbSystem());
}

if (databaseDetails.getDbName() != null) {
span.setData(DB_NAME_KEY, databaseDetails.getDbName());
}
}

private @NotNull DatabaseUtils.DatabaseDetails getOrComputeDatabaseDetails(
final @Nullable ConnectionInformation connectionInformation) {
if (cachedDatabaseDetails == null) {
try (final @NotNull ISentryLifecycleToken ignored = databaseDetailsLock.acquire()) {
if (cachedDatabaseDetails == null) {
cachedDatabaseDetails = DatabaseUtils.readFrom(connectionInformation);
}
final @NotNull DatabaseUtils.DatabaseDetails databaseDetails, final @NotNull ISpan span) {
final @Nullable String dbSystem = databaseDetails.getDbSystem();
if (dbSystem != null) {
span.setData(DB_SYSTEM_KEY, dbSystem);
final @Nullable String dbSystemName = SqlSpanData.toDbSystemName(dbSystem);
if (dbSystemName != null) {
span.setData(DB_SYSTEM_NAME_KEY, dbSystemName);
}
}

return cachedDatabaseDetails;
final @Nullable String dbName = databaseDetails.getDbName();
if (dbName != null) {
span.setData(DB_NAME_KEY, dbName);
span.setData(DB_NAMESPACE_KEY, dbName);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.sentry.jdbc

import com.google.common.truth.Truth.assertWithMessage
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
Expand Down Expand Up @@ -109,7 +110,14 @@ class DatabaseUtilsTest {
fun `detects db system for mongo no db`() {
val details = DatabaseUtils.parse("jdbc:mongo://some-server.com:1234")
assertEquals("mongo", details.dbSystem)
assertEquals("", details.dbName)
assertNull(details.dbName)
}

@Test
fun `detects db system for postgres without database`() {
val details = DatabaseUtils.parse("jdbc:postgresql://localhost:5432/")
assertEquals("postgresql", details.dbSystem)
assertNull(details.dbName)
}

@Test
Expand Down Expand Up @@ -264,4 +272,24 @@ class DatabaseUtilsTest {
assertEquals("sqlserver", details.dbSystem)
assertEquals("my_database", details.dbName)
}

@Test
fun `keeps connection properties out of file-based database names`() {
// url to expected db.name; the properties may hold the database key or password
val cases =
listOf(
"jdbc:sqlite:sample.db?journal_mode=WAL&password=secret" to "sample.db",
"jdbc:sqlite:/data/app.db?key=secret" to "/data/app.db",
"jdbc:sqlite:file:/data/app.db?key=secret#frag" to "/data/app.db",
"jdbc:sqlite:file:/data/app.db#secret" to "/data/app.db",
"jdbc:sqlite:file::memory:?cache=shared" to null,
"jdbc:p6spy:sqlite:sample.db?password=secret" to "sample.db",
"jdbc:hsqldb:file:db?password=secret" to "db",
"jdbc:h2:file:/data/app?key=secret" to "/data/app",
)

cases.forEach { (url, dbName) ->
assertWithMessage(url).that(DatabaseUtils.parse(url).dbName).isEqualTo(dbName)
}
}
}
Loading
Loading