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 @@ -275,7 +275,11 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
.put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, this.connectionId)
.build();
this.otelContext = Context.current().with(baggage);
boolean initialized = false;
ExecutorService createdQueryExecutor = null;
ExecutorService createdMetadataExecutor = null;
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) {
BigQueryJdbcRootLogger.registerConnection(this.connectionId);
this.connectionUrl = url;
if (LOG.isLoggable(Level.CONFIG)) {
Properties connectionProps = ds.createProperties();
Expand Down Expand Up @@ -413,11 +417,27 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
this.bigQuery = getBigQueryConnection();
// Cached pool executes queries immediately without queueing and reclaims all idle threads
// when inactive, minimizing resources.
this.queryExecutor =
createdQueryExecutor =
BigQueryJdbcMdc.newCachedThreadPool(String.format("BQ-Query-%s", connectionId));
this.metadataExecutor =
this.queryExecutor = createdQueryExecutor;
createdMetadataExecutor =
BigQueryJdbcMdc.newFixedThreadPool(
String.format("BQ-Metadata-%s", connectionId), this.metadataFetchThreadCount);
this.metadataExecutor = createdMetadataExecutor;
initialized = true;
} finally {
if (!initialized) {
if (createdQueryExecutor != null) {
createdQueryExecutor.shutdownNow();
}
if (createdMetadataExecutor != null) {
createdMetadataExecutor.shutdownNow();
}
BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId);
BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId);
BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
this.openTelemetry = null;
}
}
}

Expand Down Expand Up @@ -1329,6 +1349,7 @@ private OpenTelemetry getOpenTelemetryInstance() {
effectiveProjectId,
this.credentials,
this.proxyProperties);
this.openTelemetry = openTelemetry;

boolean hasExternalOtel = this.customOpenTelemetry != null || this.useGlobalOpenTelemetry;
Logging localLoggingClient = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,12 @@ public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz, String conne
if (connectionId == null || connectionId.isEmpty()) {
return getLogger(clazz, (ConnectionLogContext) null);
}
return getLogger(clazz, new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE));
ConnectionLogContext active = BigQueryJdbcRootLogger.findActiveContext(connectionId);
ConnectionLogContext context =
active != null
? active
: new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE);
return getLogger(clazz, context);
Comment on lines +78 to +83

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.

medium

When a connection is inactive or has been closed, BigQueryJdbcRootLogger.findActiveContext(connectionId) returns null. Currently, a new ConnectionLogContext is created with ConnectionLogContext.ALL_VALUE. This causes any subsequent logging calls (e.g., from post-close ResultSet or Statement operations) to proceed with formatting and publishing the log records, only for them to be discarded later by the handler's canOpenSlotFor check.

By defaulting to ConnectionLogContext.OFF_VALUE instead, we can completely avoid the overhead of the logging pipeline for inactive or closed connections.

Suggested change
ConnectionLogContext active = BigQueryJdbcRootLogger.findActiveContext(connectionId);
ConnectionLogContext context =
active != null
? active
: new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE);
return getLogger(clazz, context);
ConnectionLogContext active = BigQueryJdbcRootLogger.findActiveContext(connectionId);
ConnectionLogContext context =
active != null
? active
: new ConnectionLogContext(connectionId, ConnectionLogContext.OFF_VALUE);
return getLogger(clazz, context);

}

static BigQueryJdbcResultSetLogger getLogger(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
Expand All @@ -43,8 +44,10 @@ class BigQueryJdbcRootLogger {

private static final Logger storageLogger = Logger.getLogger("com.google.cloud.bigquery.storage");
private static final boolean isTest = Boolean.getBoolean("JDBC_TESTS");
private static final ConcurrentHashMap<String, ConnectionLogContext> ACTIVE_CONNECTIONS =
new ConcurrentHashMap<>();

private static Handler fileHandler = null;
private static volatile Handler fileHandler = null;

static final String PROCESS_ID = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];

Expand Down Expand Up @@ -162,7 +165,7 @@ public static Logger getRootLogger() {
return logger;
}

public static void setLevel(Level level, String logPath) throws IOException {
public static synchronized void setLevel(Level level, String logPath) throws IOException {
if (level != Level.OFF) {
if (logPath != null) {
setPath(logPath, level);
Expand All @@ -177,7 +180,7 @@ public static void setLevel(Level level, String logPath) throws IOException {
logger.setLevel(level);
}

static void setPath(String logPath, Level level) {
static synchronized void setPath(String logPath, Level level) {
try {
if (logPath == null) {
logPath = "";
Expand All @@ -201,9 +204,46 @@ static void setPath(String logPath, Level level) {
}
}

public static void closeConnectionHandler(String connectionId) {
if (fileHandler instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) fileHandler).closeHandler(connectionId);
static ConnectionLogContext registerConnection(String connectionId) {
if (connectionId == null || connectionId.isEmpty()) {
return null;
}
ConnectionLogContext context =
ACTIVE_CONNECTIONS.computeIfAbsent(
connectionId, id -> new ConnectionLogContext(id, ConnectionLogContext.ALL_VALUE));
Handler currentHandler = fileHandler;
if (currentHandler instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) currentHandler).registerConnection(connectionId);
}
return context;
}

static ConnectionLogContext findActiveContext(String connectionId) {
if (connectionId == null || connectionId.isEmpty()) {
return null;
}
return ACTIVE_CONNECTIONS.get(connectionId);
}

static boolean isConnectionActive(String connectionId) {
return connectionId != null && ACTIVE_CONNECTIONS.containsKey(connectionId);
}

static int activeConnectionCount() {
return ACTIVE_CONNECTIONS.size();
}

public static synchronized void closeConnectionHandler(String connectionId) {
if (connectionId == null) {
return;
}
ConnectionLogContext removed = ACTIVE_CONNECTIONS.remove(connectionId);
if (removed != null) {
removed.setLevelValue(ConnectionLogContext.OFF_VALUE);
}
Handler currentHandler = fileHandler;
if (currentHandler instanceof PerConnectionFileHandler) {
((PerConnectionFileHandler) currentHandler).closeHandler(connectionId);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ class PerConnectionFileHandler extends Handler {
private final Level level;
private final long maxFileBytes;
private final Formatter logFormatter;
private final ConcurrentHashMap<String, BoundedLogFileWriter> writers = new ConcurrentHashMap<>();
final Set<String> registeredConnections = ConcurrentHashMap.newKeySet();
private final ConcurrentHashMap<String, ConnectionFileSlot> slots = new ConcurrentHashMap<>();
private final BoundedLogFileWriter defaultWriter;
private volatile boolean handlerClosed = false;
volatile boolean handlerClosed = false;

PerConnectionFileHandler(String baseLogPath, Level level) {
this(baseLogPath, level, resolveMaxLogFileBytes());
Expand Down Expand Up @@ -309,7 +310,7 @@ private static SeekableByteChannel openExclusiveNewChannel(Path file) throws IOE
isPosix);
}

private BoundedLogFileWriter createLogWriter(
BoundedLogFileWriter createLogWriter(
String id, Path logDir, Level writerLevel, long limitBytes) {
if (logDir == null) {
return null;
Expand Down Expand Up @@ -388,6 +389,19 @@ static Path deriveBackupPath(Path activePath) {
return activePath.resolveSibling(backup);
}

void registerConnection(String connectionId) {
if (connectionId != null && !connectionId.isEmpty() && !handlerClosed) {
registeredConnections.add(connectionId);
}
}

private boolean canOpenSlotFor(String connectionId) {
return !handlerClosed
&& baseLogPath != null
&& (registeredConnections.contains(connectionId)
|| BigQueryJdbcRootLogger.isConnectionActive(connectionId));
}

@Override
public void publish(LogRecord record) {
if (handlerClosed || !isLoggable(record)) {
Expand All @@ -403,23 +417,24 @@ public void publish(LogRecord record) {
}

if (connectionId != null && !connectionId.isEmpty()) {
BoundedLogFileWriter writer =
writers.computeIfAbsent(
ConnectionFileSlot slot =
slots.compute(
connectionId,
id ->
handlerClosed
? null
: createLogWriter(id, baseLogPath, this.level, this.maxFileBytes));
if (writer != null) {
if (handlerClosed) {
writers.remove(connectionId, writer);
writer.close();
(id, existing) -> {
if (existing != null) {
return existing.isClosed() ? null : existing;
}
return canOpenSlotFor(id)
? new ConnectionFileSlot(baseLogPath, level, maxFileBytes)
: null;
});
Comment on lines +420 to +430

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.

high

In slots.compute, if an existing slot is found but is closed (existing.isClosed() is true), the current implementation returns null. This removes the mapping from the map, but also causes the compute call itself to return null. As a result, the current thread's publish call will skip writing the log record, even if the connection is still active and a new slot could have been successfully opened.

To prevent silent loss of log records, we should check if the connection is still active when the existing slot is closed, and if so, instantiate and return a new ConnectionFileSlot immediately.

Suggested change
ConnectionFileSlot slot =
slots.compute(
connectionId,
id ->
handlerClosed
? null
: createLogWriter(id, baseLogPath, this.level, this.maxFileBytes));
if (writer != null) {
if (handlerClosed) {
writers.remove(connectionId, writer);
writer.close();
(id, existing) -> {
if (existing != null) {
return existing.isClosed() ? null : existing;
}
return canOpenSlotFor(id)
? new ConnectionFileSlot(baseLogPath, level, maxFileBytes)
: null;
});
ConnectionFileSlot slot =
slots.compute(
connectionId,
(id, existing) -> {
if (existing != null && !existing.isClosed()) {
return existing;
}
return canOpenSlotFor(id)
? new ConnectionFileSlot(baseLogPath, level, maxFileBytes)
: null;
});

if (slot != null) {
if (slot.publishIfOpen(record, connectionId, this)) {
return;
}
if (writer.publish(record)) {
return;
if (slot.isClosed()) {
slots.remove(connectionId, slot);
}
writers.remove(connectionId, writer);
}
}

Expand All @@ -437,10 +452,11 @@ public void flush() {
@Override
public void close() throws SecurityException {
handlerClosed = true;
for (String id : writers.keySet()) {
BoundedLogFileWriter removed = writers.remove(id);
registeredConnections.clear();
for (String id : slots.keySet()) {
ConnectionFileSlot removed = slots.remove(id);
if (removed != null) {
removed.close();
removed.closeSlot();
}
}
if (defaultWriter != null) {
Expand All @@ -450,9 +466,10 @@ public void close() throws SecurityException {

public void closeHandler(String connectionId) {
if (connectionId != null) {
BoundedLogFileWriter writer = writers.remove(connectionId);
if (writer != null) {
writer.close();
registeredConnections.remove(connectionId);
ConnectionFileSlot slot = slots.remove(connectionId);
if (slot != null) {
slot.closeSlot();
}
}
}
Expand Down Expand Up @@ -633,4 +650,63 @@ synchronized void close() {
}
}
}

private static final class ConnectionFileSlot {
private final Path logPath;
private final Level level;
private final long maxFileBytes;

@GuardedBy("this")
private BoundedLogFileWriter writer;

private volatile boolean closed;

ConnectionFileSlot(Path logPath, Level level, long maxFileBytes) {
this.logPath = logPath;
this.level = level;
this.maxFileBytes = maxFileBytes;
}

boolean isClosed() {
return closed;
}

synchronized boolean publishIfOpen(
LogRecord record, String connectionId, PerConnectionFileHandler owner) {
if (closed
|| owner.handlerClosed
|| (!owner.registeredConnections.contains(connectionId)
&& !BigQueryJdbcRootLogger.isConnectionActive(connectionId))) {
closeSlot();
return false;
}
if (record.getLevel().intValue() < level.intValue()) {
return true;
}
if (writer == null) {
writer = owner.createLogWriter(connectionId, logPath, level, maxFileBytes);
if (writer == null) {
return false;
}
}
if (!writer.publish(record)) {
closeSlot();
return false;
}
return true;
}

synchronized void closeSlot() {
if (!closed) {
closed = true;
if (writer != null) {
try {
writer.close();
} finally {
writer = null;
}
}
}
}
}
}
Loading
Loading