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,7 +1,9 @@
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;
Expand All @@ -16,18 +18,36 @@
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 java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
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;
/**
* p6spy shares one listener across all datasources of the JVM, so details are cached per
* connection URL. Bounded; URLs beyond the bound are parsed on every query. The keys are full
* connection URLs and may contain credentials: never log them.
*/
private static final int MAX_CACHED_DATABASE_DETAILS = 64;

private final @NotNull Map<String, DatabaseUtils.DatabaseDetails> databaseDetailsByUrl =
new ConcurrentHashMap<>();

/** Guards insertion into the details cache. */
protected final @NotNull AutoClosableReentrantLock databaseDetailsLock =
new AutoClosableReentrantLock();

Expand All @@ -47,7 +67,21 @@ 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 =
getOrComputeDatabaseDetails(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());
queryData.applyTo(span);
}

@Override
Expand Down Expand Up @@ -133,13 +167,35 @@ 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 ISpan parent = getActiveParent();
if (parent != null) {
startChild(parent, spanHolder, operation, description);
}
}

/**
* 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 @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(
Expand Down Expand Up @@ -171,25 +227,47 @@ private void applyDatabaseDetailsToSpan(
final @NotNull DatabaseUtils.DatabaseDetails databaseDetails =
getOrComputeDatabaseDetails(connectionInformation);

if (databaseDetails.getDbSystem() != null) {
span.setData(DB_SYSTEM_KEY, databaseDetails.getDbSystem());
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);
}
}

if (databaseDetails.getDbName() != null) {
span.setData(DB_NAME_KEY, databaseDetails.getDbName());
final @Nullable String dbName = databaseDetails.getDbName();
if (dbName != null) {
span.setData(DB_NAME_KEY, dbName);
span.setData(DB_NAMESPACE_KEY, dbName);
}
}

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 @Nullable String url =
connectionInformation == null ? null : connectionInformation.getUrl();
if (url == null) {
return DatabaseUtils.readFrom(connectionInformation);
}
final @Nullable DatabaseUtils.DatabaseDetails cached = databaseDetailsByUrl.get(url);
if (cached != null) {
return cached;
}
if (databaseDetailsByUrl.size() >= MAX_CACHED_DATABASE_DETAILS) {
return DatabaseUtils.readFrom(connectionInformation);
}
try (final @NotNull ISentryLifecycleToken ignored = databaseDetailsLock.acquire()) {
final @Nullable DatabaseUtils.DatabaseDetails existing = databaseDetailsByUrl.get(url);
if (existing != null) {
return existing;
}
final @NotNull DatabaseUtils.DatabaseDetails details =
DatabaseUtils.readFrom(connectionInformation);
if (databaseDetailsByUrl.size() < MAX_CACHED_DATABASE_DETAILS) {
databaseDetailsByUrl.put(url, details);
}
return details;
}

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