Skip to content

Commit

Permalink
cache SqlStatementInfos based on the raw sql to prevent duplicate san…
Browse files Browse the repository at this point in the history
…itization/extraction.
  • Loading branch information
breedx-splk committed Jan 22, 2021
1 parent 73ea04c commit 3ab7896
Showing 1 changed file with 25 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@

import static io.opentelemetry.javaagent.instrumentation.api.db.QueryNormalizationConfig.isQueryNormalizationEnabled;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.opentelemetry.javaagent.instrumentation.api.db.SqlStatementInfo;
import io.opentelemetry.javaagent.instrumentation.api.db.sanitizer.ParseException;
import io.opentelemetry.javaagent.instrumentation.api.db.sanitizer.SqlSanitizer;
import io.opentelemetry.javaagent.instrumentation.api.db.sanitizer.SqlStatementInfoExtractor;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.Statement;
import java.util.concurrent.ExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -24,6 +27,8 @@ public abstract class JdbcUtils {
private static final boolean NORMALIZATION_ENABLED = isQueryNormalizationEnabled("jdbc");

private static Field c3poField = null;
private static final Cache<String, SqlStatementInfo> sqlToStatementInfoCache =
CacheBuilder.newBuilder().maximumSize(5000).build();

/** Returns the unwrapped connection or null if exception was thrown. */
public static Connection connectionFromStatement(Statement statement) {
Expand Down Expand Up @@ -69,8 +74,27 @@ public static Connection connectionFromStatement(Statement statement) {
return connection;
}

public static SqlStatementInfo sanitizeAndExtractInfo(String sql) {
try {
return sqlToStatementInfoCache.get(
sql,
() -> {
log.debug("SQL statement cache miss");
try {
return SqlStatementInfoExtractor.extract(sanitizeSql(sql));
} catch (ParseException e) {
log.debug("Could not extract sql info", e);
return new SqlStatementInfo(null, null, null);
}
});
} catch (ExecutionException e) {
log.info("Sql statement cache error", e);
return new SqlStatementInfo(null, null, null);
}
}

/** Returns null if the sql could not be sanitized for any reason. */
public static String sanitizeSql(String sql) {
private static String sanitizeSql(String sql) {
if (!NORMALIZATION_ENABLED) {
return sql;
}
Expand All @@ -81,13 +105,4 @@ public static String sanitizeSql(String sql) {
return null;
}
}

public static SqlStatementInfo sanitizeAndExtractInfo(String sql) {
try {
return SqlStatementInfoExtractor.extract(sanitizeSql(sql));
} catch (ParseException e) {
log.debug("Could not extract sql info", e);
return new SqlStatementInfo(null, null, null);
}
}
}

0 comments on commit 3ab7896

Please sign in to comment.