From 32bdf3d3477bae3ebd4847de1a1ab9bcb9dc8e07 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Fri, 20 Nov 2026 18:12:49 -0500 Subject: [PATCH 1/7] fix(bigquery-jdbc): use NIO channel with 0700/0600 permissions for log files PR 1 of 6 in the diagnostic logging series (b/584840147, part 1 of 3). Replaces java.util.logging.FileHandler inside PerConnectionFileHandler with an NIO SeekableByteChannel writer enforcing 0700/0600 POSIX permissions, symlink rejection, collision-safe exclusive creation, literal % path handling, and graceful ErrorManager degradation. --- .../jdbc/BigQueryJdbcCustomLogger.java | 1 + .../jdbc/PerConnectionFileHandler.java | 449 +++++++++++++++--- .../jdbc/PerConnectionFileHandlerTest.java | 207 +++++++- 3 files changed, 597 insertions(+), 60 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java index 0acea77e5bf6..2fac95132b28 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java @@ -116,6 +116,7 @@ private static boolean isLoggerClass(String className) { || className.equals("com.google.cloud.bigquery.jdbc.BigQueryJdbcResultSetLogger") || className.startsWith("com.google.cloud.bigquery.jdbc.BigQueryJdbcRootLogger") || className.equals("com.google.cloud.bigquery.jdbc.PerConnectionFileHandler") + || className.startsWith("com.google.cloud.bigquery.jdbc.PerConnectionFileHandler$") || className.equals(BigQueryJdbcLogRecord.class.getName()); } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index 0b5279cf6bf0..ae2f4c8d5348 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java @@ -17,75 +17,324 @@ package com.google.cloud.bigquery.jdbc; import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.channels.OverlappingFileLockException; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; +import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.EnumSet; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.FileHandler; +import java.util.logging.ErrorManager; +import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; +import javax.annotation.concurrent.GuardedBy; /** - * Custom logging handler that dynamically creates and routes log records to per-connection specific - * log files using the connection ID retrieved from BigQueryJdbcMdc. + * Custom logging handler that dynamically creates and routes log records to per-connection log + * files using NIO {@link SeekableByteChannel} writers with owner-only POSIX permissions and + * graceful {@link ErrorManager} degradation. */ class PerConnectionFileHandler extends Handler { + private static final String DEFAULT_HANDLER_ID = "Jdbc-default"; + private static final int MAX_COLLISION_ATTEMPTS = 64; + private static final DateTimeFormatter TIMESTAMP_FORMATTER = + DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); + private static final Set OWNER_DIR_PERMS = + PosixFilePermissions.fromString("rwx------"); + private static final Set OWNER_FILE_PERMS = + PosixFilePermissions.fromString("rw-------"); + private static final Set ACTIVE_GLOBAL_PATHS = ConcurrentHashMap.newKeySet(); + private final Path baseLogPath; private final Level level; - private final ConcurrentHashMap handlers = new ConcurrentHashMap<>(); - private FileHandler defaultHandler; + private final Formatter logFormatter; + private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); + private final ChannelLogWriter defaultWriter; + private volatile boolean handlerClosed = false; PerConnectionFileHandler(String baseLogPath, Level level) { - this.baseLogPath = Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath(); this.level = level; + this.logFormatter = BigQueryJdbcRootLogger.getFormatter(); + setLevel(level); + setFormatter(this.logFormatter); + Path verifiedDir = null; + ChannelLogWriter initializedDefault = null; try { - if (!Files.exists(this.baseLogPath)) { - Files.createDirectories(this.baseLogPath); + verifiedDir = + ensureSecureDirectory(Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath()); + initializedDefault = createLogWriter(DEFAULT_HANDLER_ID, verifiedDir, this.level); + } catch (Exception e) { + reportError("Failed to initialize default log file", e, ErrorManager.OPEN_FAILURE); + } + this.baseLogPath = verifiedDir; + this.defaultWriter = initializedDefault; + } + + private static boolean isPosixFileSystem(Path path) { + return path.getFileSystem().supportedFileAttributeViews().contains("posix"); + } + + static void verifyPosixOwner(Path file) throws IOException { + if (isPosixFileSystem(file)) { + String currentUser = System.getProperty("user.name"); + String ownerName = Files.getOwner(file, LinkOption.NOFOLLOW_LINKS).getName(); + if (currentUser == null || currentUser.isEmpty() || !currentUser.equals(ownerName)) { + throw new FileAlreadyExistsException( + file.toString(), null, "Log file owner could not be verified: " + ownerName); } + } + } - this.defaultHandler = createFileHandler("Jdbc-default"); - } catch (IOException e) { - reportError( - "Failed to initialize default log file", e, java.util.logging.ErrorManager.OPEN_FAILURE); + /** Creates missing directories with {@code 0700} on POSIX and rejects nested symlinks. */ + static Path ensureSecureDirectory(Path dir) throws IOException { + Path absPath = dir.toAbsolutePath(); + Path root = absPath.getRoot(); + if (root == null) { + throw new IOException("Log path has no filesystem root: " + dir); + } + boolean isPosix = isPosixFileSystem(absPath); + FileAttribute[] attrs = + isPosix + ? new FileAttribute[] {PosixFilePermissions.asFileAttribute(OWNER_DIR_PERMS)} + : new FileAttribute[0]; + + Path current = root; + int depth = 0; + for (Path segment : absPath) { + String part = segment.toString(); + if (".".equals(part) || part.isEmpty()) { + continue; + } + if ("..".equals(part)) { + Path parent = current.getParent(); + if (parent != null) { + current = parent; + depth = Math.max(0, depth - 1); + } + continue; + } + depth++; + current = current.resolve(segment); + if (Files.isSymbolicLink(current)) { + if (depth == 1 && Files.isDirectory(current)) { + current = current.toRealPath(); + depth = current.getNameCount(); + continue; + } + throw new IOException("Refusing to traverse symbolic link in log path: " + current); + } + if (Files.exists(current, LinkOption.NOFOLLOW_LINKS)) { + if (!Files.isDirectory(current, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Log path component is not a directory: " + current); + } + } else { + try { + Files.createDirectory(current, attrs); + if (isPosix) { + Files.setPosixFilePermissions(current, OWNER_DIR_PERMS); + } + } catch (FileAlreadyExistsException e) { + if (Files.isSymbolicLink(current) + || !Files.isDirectory(current, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Log path component is not a regular directory: " + current, e); + } + } + } + } + return current; + } + + /** Opens or creates {@code file} with {@code 0600} permissions, rejecting symlinks/non-files. */ + static SeekableByteChannel openSecureAppendChannel(Path file) throws IOException { + return openSecureAppendChannel(file, true); + } + + private static SeekableByteChannel openSecureAppendChannel(Path file, boolean tightenOnOpen) + throws IOException { + if (Files.isSymbolicLink(file)) { + throw new IOException("Refusing to write logs to symbolic link: " + file); + } + try { + return openExclusiveNewChannel(file); + } catch (FileAlreadyExistsException existsEx) { + if (Files.isSymbolicLink(file) || !Files.isRegularFile(file, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Refusing to write logs to non-regular file: " + file, existsEx); + } + verifyPosixOwner(file); + if (tightenOnOpen && isPosixFileSystem(file)) { + Files.setPosixFilePermissions(file, OWNER_FILE_PERMS); + } + SeekableByteChannel channel = + Files.newByteChannel(file, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); + try { + if (tightenOnOpen) { + channel.position(channel.size()); + } + return channel; + } catch (IOException | RuntimeException posEx) { + closeQuietlyWithSuppressed(channel, posEx); + throw posEx; + } } } - private String getLogFilePath(String id) { - if ("Jdbc-default".equals(id)) { - return baseLogPath.resolve("BQ-JDBC-GLOBAL.log").toString(); + private static SeekableByteChannel configureNewChannel( + SeekableByteChannel channel, Path file, boolean isPosix) throws IOException { + try { + if (isPosix) { + Files.setPosixFilePermissions(file, OWNER_FILE_PERMS); + } + return channel; + } catch (IOException | RuntimeException ex) { + closeQuietlyWithSuppressed(channel, ex); + throw ex; } - String uuid = id; - if (id.startsWith("BQ-JDBC-")) { - uuid = id.substring("BQ-JDBC-".length()); + } + + private static void closeQuietlyWithSuppressed(SeekableByteChannel channel, Throwable primary) { + try { + channel.close(); + } catch (IOException closeEx) { + primary.addSuppressed(closeEx); } - String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")); - String shortUuid = uuid.length() >= 4 ? uuid.substring(0, 4) : uuid; - return baseLogPath.resolve("BQ-JDBC-" + timestamp + "-" + shortUuid + ".log").toString(); } - private FileHandler createFileHandler(String id) { + private static OpenedChannel openLockedGlobalChannel(Path file) throws IOException { + Path claim = file.toAbsolutePath().normalize(); + if (!ACTIVE_GLOBAL_PATHS.add(claim)) { + throw new FileAlreadyExistsException( + file.toString(), null, "Global log file is already open in this JVM"); + } + SeekableByteChannel channel = null; + boolean transferred = false; try { - String filePath = getLogFilePath(id); - FileHandler fh = new FileHandler(filePath, 0, 1, true); - fh.setLevel(level); - fh.setFormatter(BigQueryJdbcRootLogger.getFormatter()); - return fh; - } catch (IOException e) { - reportError( - "Failed to create log file for connection " + id, - e, - java.util.logging.ErrorManager.OPEN_FAILURE); + channel = openSecureAppendChannel(file, false); + if (channel instanceof FileChannel) { + FileLock lock = null; + boolean lockSupported = true; + try { + lock = ((FileChannel) channel).tryLock(); + } catch (OverlappingFileLockException ignored) { + // Another handler holds the lock on this global log file. + } catch (IOException lockEx) { + lockSupported = false; + } + if (lockSupported && lock == null) { + channel.close(); + channel = null; + throw new FileAlreadyExistsException( + file.toString(), null, "Global log file is already locked by another process"); + } + } + if (isPosixFileSystem(file)) { + Files.setPosixFilePermissions(file, OWNER_FILE_PERMS); + } + channel.position(channel.size()); + transferred = true; + return new OpenedChannel(claim, channel); + } finally { + if (!transferred) { + ACTIVE_GLOBAL_PATHS.remove(claim); + if (channel != null) { + try { + channel.close(); + } catch (IOException ignored) { + } + } + } + } + } + + private static SeekableByteChannel openExclusiveNewChannel(Path file) throws IOException { + boolean isPosix = isPosixFileSystem(file); + FileAttribute[] attrs = + isPosix + ? new FileAttribute[] {PosixFilePermissions.asFileAttribute(OWNER_FILE_PERMS)} + : new FileAttribute[0]; + return configureNewChannel( + Files.newByteChannel( + file, EnumSet.of(StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE), attrs), + file, + isPosix); + } + + private ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel) { + if (logDir == null) { + return null; + } + try { + OpenedChannel opened = allocateChannel(ensureSecureDirectory(logDir), id); + try { + return new ChannelLogWriter(opened, writerLevel, logFormatter, this); + } catch (Exception initEx) { + opened.releaseOnFailure(initEx); + throw initEx; + } + } catch (Exception e) { + reportError("Failed to create log file for connection " + id, e, ErrorManager.OPEN_FAILURE); return null; } } + private static OpenedChannel allocateChannel(Path logDir, String id) throws IOException { + if (DEFAULT_HANDLER_ID.equals(id)) { + FileAlreadyExistsException lastEx = null; + for (int attempt = 0; attempt <= MAX_COLLISION_ATTEMPTS; attempt++) { + String name = + attempt == 0 + ? "BQ-JDBC-GLOBAL.log" + : attempt == 1 + ? "BQ-JDBC-GLOBAL-" + BigQueryJdbcRootLogger.PROCESS_ID + ".log" + : "BQ-JDBC-GLOBAL-" + + BigQueryJdbcRootLogger.PROCESS_ID + + "-" + + (attempt - 1) + + ".log"; + try { + return openLockedGlobalChannel(logDir.resolve(name)); + } catch (FileAlreadyExistsException ex) { + lastEx = ex; + } + } + throw lastEx; + } + + String uuid = id.startsWith("BQ-JDBC-") ? id.substring("BQ-JDBC-".length()) : id; + String timestamp = LocalDateTime.now().format(TIMESTAMP_FORMATTER); + String shortUuid = uuid.length() >= 4 ? uuid.substring(0, 4) : uuid; + for (int attempt = 0; attempt < MAX_COLLISION_ATTEMPTS; attempt++) { + String fileName = + attempt == 0 + ? "BQ-JDBC-" + timestamp + "-" + shortUuid + ".log" + : "BQ-JDBC-" + timestamp + "-" + attempt + "-" + shortUuid + ".log"; + try { + return new OpenedChannel(null, openExclusiveNewChannel(logDir.resolve(fileName))); + } catch (FileAlreadyExistsException e) { + // Same-second prefix collision or pre-existing file; retry with collision counter. + } + } + throw new IOException("Unable to allocate unique log file for connection " + id); + } + @Override public void publish(LogRecord record) { - if (!isLoggable(record)) { + if (handlerClosed || !isLoggable(record)) { return; } @@ -96,50 +345,142 @@ public void publish(LogRecord record) { connectionId = (String) params[0]; } } - FileHandler handler = defaultHandler; if (connectionId != null && !connectionId.isEmpty()) { - handler = handlers.computeIfAbsent(connectionId, this::createFileHandler); - if (handler == null) { - handler = defaultHandler; + ChannelLogWriter writer = + writers.computeIfAbsent( + connectionId, id -> handlerClosed ? null : createLogWriter(id, baseLogPath, level)); + if (writer != null) { + if (handlerClosed) { + writers.remove(connectionId, writer); + writer.close(); + return; + } + writer.publish(record); + return; } } - if (handler != null) { - handler.publish(record); + if (!handlerClosed && defaultWriter != null) { + defaultWriter.publish(record); } } @Override public void flush() { - if (defaultHandler != null) { - defaultHandler.flush(); + if (defaultWriter != null) { + defaultWriter.flush(); } - for (FileHandler h : handlers.values()) { - h.flush(); + for (ChannelLogWriter writer : writers.values()) { + writer.flush(); } } @Override public void close() throws SecurityException { - for (FileHandler h : handlers.values()) { - try { - h.close(); - } catch (Exception e) { + handlerClosed = true; + for (String id : writers.keySet()) { + ChannelLogWriter removed = writers.remove(id); + if (removed != null) { + removed.close(); } } - try { - if (defaultHandler != null) defaultHandler.close(); - } finally { - handlers.clear(); + if (defaultWriter != null) { + defaultWriter.close(); } } public void closeHandler(String connectionId) { if (connectionId != null) { - FileHandler handler = handlers.remove(connectionId); - if (handler != null) { - handler.close(); + ChannelLogWriter writer = writers.remove(connectionId); + if (writer != null) { + writer.close(); + } + } + } + + private static final class OpenedChannel { + final Path claimedGlobalPath; + final SeekableByteChannel channel; + + OpenedChannel(Path claimedGlobalPath, SeekableByteChannel channel) { + this.claimedGlobalPath = claimedGlobalPath; + this.channel = channel; + } + + void releaseOnFailure(Throwable primary) { + if (claimedGlobalPath != null) { + ACTIVE_GLOBAL_PATHS.remove(claimedGlobalPath); + } + closeQuietlyWithSuppressed(channel, primary); + } + } + + private static final class ChannelLogWriter { + private final Path claimedGlobalPath; + private final SeekableByteChannel channel; + private final Level writerLevel; + private final Formatter formatter; + private final PerConnectionFileHandler owner; + + @GuardedBy("this") + private boolean closed; + + ChannelLogWriter( + OpenedChannel opened, + Level writerLevel, + Formatter formatter, + PerConnectionFileHandler owner) { + this.claimedGlobalPath = opened.claimedGlobalPath; + this.channel = opened.channel; + this.writerLevel = writerLevel; + this.formatter = formatter; + this.owner = owner; + } + + synchronized void publish(LogRecord record) { + if (closed || record.getLevel().intValue() < writerLevel.intValue()) { + return; + } + String formatted; + try { + formatted = formatter.format(record); + } catch (Exception ex) { + owner.reportError("Failed to format log record", ex, ErrorManager.FORMAT_FAILURE); + return; + } + try { + ByteBuffer buffer = ByteBuffer.wrap(formatted.getBytes(StandardCharsets.UTF_8)); + while (buffer.hasRemaining()) { + channel.write(buffer); + } + } catch (Exception ex) { + owner.reportError("Failed to write log record", ex, ErrorManager.WRITE_FAILURE); + } + } + + synchronized void flush() { + if (!closed && channel instanceof FileChannel) { + try { + ((FileChannel) channel).force(false); + } catch (Exception ex) { + owner.reportError("Failed to flush log file", ex, ErrorManager.FLUSH_FAILURE); + } + } + } + + synchronized void close() { + if (!closed) { + closed = true; + try { + channel.close(); + } catch (Exception ex) { + owner.reportError("Failed to close log file", ex, ErrorManager.CLOSE_FAILURE); + } finally { + if (claimedGlobalPath != null) { + ACTIVE_GLOBAL_PATHS.remove(claimedGlobalPath); + } + } } } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java index cbc4dec030c8..22381978da23 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java @@ -16,6 +16,8 @@ package com.google.cloud.bigquery.jdbc; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -26,17 +28,26 @@ import com.google.cloud.bigquery.FieldList; import com.google.cloud.bigquery.StandardSQLTypeName; import java.io.IOException; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.PosixFilePermissions; import java.sql.SQLException; import java.sql.Statement; +import java.util.List; import java.util.Optional; import java.util.concurrent.Future; import java.util.logging.Level; import java.util.logging.LogRecord; +import java.util.stream.Collectors; +import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; @@ -66,13 +77,19 @@ public void tearDown() { BigQueryJdbcRootLogger.getRootLogger().setLevel(originalLevel); } + private Optional findLogFile(Path dir, String suffix) throws IOException { + try (Stream files = Files.list(dir)) { + return files + .filter( + p -> + p.getFileName().toString().startsWith("BQ-JDBC-") + && p.getFileName().toString().endsWith(suffix)) + .findFirst(); + } + } + private Optional findLogFile(String suffix) throws IOException { - return Files.list(tempDir) - .filter( - p -> - p.getFileName().toString().startsWith("BQ-JDBC-") - && p.getFileName().toString().endsWith(suffix)) - .findFirst(); + return findLogFile(tempDir, suffix); } @Test @@ -221,4 +238,182 @@ public void testResultSetExceptionLogRouting() throws Exception { rootLogger.removeHandler(handler); } } + + private static void assertMode(Path path, String expected) throws IOException { + assertEquals(expected, PosixFilePermissions.toString(Files.getPosixFilePermissions(path))); + } + + private static String readUtf8(Path path) throws IOException { + return new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + } + + @Test + @EnabledOnOs({OS.LINUX, OS.MAC}) + public void testPosixOwnerOnlyPermissionsOnCreatedDirsAndFiles() throws IOException { + Path nestedDir = tempDir.resolve("parent_logs/child_logs"); + PerConnectionFileHandler posixHandler = + new PerConnectionFileHandler(nestedDir.toString(), Level.FINEST); + try { + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance("p999")) { + posixHandler.publish(new LogRecord(Level.INFO, "Query log entry")); + } + posixHandler.flush(); + + assertMode(nestedDir.getParent(), "rwx------"); + assertMode(nestedDir, "rwx------"); + assertMode(nestedDir.resolve("BQ-JDBC-GLOBAL.log"), "rw-------"); + + Optional connLog = findLogFile(nestedDir, "-p999.log"); + assertTrue(connLog.isPresent()); + assertMode(connLog.get(), "rw-------"); + } finally { + posixHandler.close(); + } + } + + @Test + @EnabledOnOs({OS.LINUX, OS.MAC}) + public void testExistingSharedDirectoryAndPermissiveFileHandling() throws IOException { + Path sharedDir = Files.createDirectory(tempDir.resolve("shared_dir")); + Files.setPosixFilePermissions(sharedDir, PosixFilePermissions.fromString("rwxr-xr-x")); + + Path existingGlobal = + Files.write( + sharedDir.resolve("BQ-JDBC-GLOBAL.log"), + "Prior entry\n".getBytes(StandardCharsets.UTF_8)); + Files.setPosixFilePermissions(existingGlobal, PosixFilePermissions.fromString("rw-r--r--")); + + PerConnectionFileHandler sharedHandler = + new PerConnectionFileHandler(sharedDir.toString(), Level.INFO); + try { + sharedHandler.publish(new LogRecord(Level.INFO, "Appended entry")); + try (BigQueryJdbcMdc.MdcCloseable badIdMdc = BigQueryJdbcMdc.registerInstance("a/bc")) { + sharedHandler.publish(new LogRecord(Level.INFO, "Fallback to global entry")); + } + sharedHandler.flush(); + assertMode(sharedDir, "rwxr-xr-x"); + assertMode(existingGlobal, "rw-------"); + String combined = readUtf8(existingGlobal); + assertTrue(combined.contains("Prior entry") && combined.contains("Appended entry")); + assertTrue(combined.contains("Fallback to global entry")); + + PerConnectionFileHandler secondHandler = + new PerConnectionFileHandler(sharedDir.toString(), Level.INFO); + try { + secondHandler.publish(new LogRecord(Level.INFO, "Isolated PID entry")); + secondHandler.flush(); + Path pidGlobal = + sharedDir.resolve("BQ-JDBC-GLOBAL-" + BigQueryJdbcRootLogger.PROCESS_ID + ".log"); + assertTrue(Files.exists(pidGlobal)); + assertMode(pidGlobal, "rw-------"); + } finally { + secondHandler.close(); + } + } finally { + sharedHandler.close(); + } + + String origUser = System.getProperty("user.name"); + try { + System.setProperty("user.name", ""); + assertThrows( + IOException.class, + () -> PerConnectionFileHandler.openSecureAppendChannel(existingGlobal)); + System.setProperty("user.name", "other_user"); + assertThrows( + IOException.class, + () -> PerConnectionFileHandler.openSecureAppendChannel(existingGlobal)); + } finally { + if (origUser != null) { + System.setProperty("user.name", origUser); + } else { + System.clearProperty("user.name"); + } + } + + assertNotNull(PerConnectionFileHandler.ensureSecureDirectory(Paths.get("/tmp"))); + } + + @Test + @EnabledOnOs({OS.LINUX, OS.MAC}) + public void testSymbolicLinksAndNonRegularPathsAreRejected() throws IOException { + Path targetFile = + Files.write(tempDir.resolve("target.txt"), "keep".getBytes(StandardCharsets.UTF_8)); + Path fileSymlink = tempDir.resolve("symlink.log"); + Files.createSymbolicLink(fileSymlink, targetFile); + + assertThrows( + IOException.class, () -> PerConnectionFileHandler.openSecureAppendChannel(fileSymlink)); + assertEquals("keep", readUtf8(targetFile)); + + Path subDir = Files.createDirectory(tempDir.resolve("not_a_regular_file")); + assertThrows(IOException.class, () -> PerConnectionFileHandler.openSecureAppendChannel(subDir)); + assertThrows( + IOException.class, () -> PerConnectionFileHandler.ensureSecureDirectory(targetFile)); + + Path realTargetDir = Files.createDirectory(tempDir.resolve("real_target_dir")); + Path dirSymlink = tempDir.resolve("dir_symlink"); + Files.createSymbolicLink(dirSymlink, realTargetDir); + assertThrows( + IOException.class, () -> PerConnectionFileHandler.ensureSecureDirectory(dirSymlink)); + assertThrows( + IOException.class, + () -> PerConnectionFileHandler.ensureSecureDirectory(dirSymlink.resolve("nested_child"))); + PerConnectionFileHandler rejectedHandler = + new PerConnectionFileHandler(dirSymlink.toString(), Level.INFO); + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance("sym-conn")) { + rejectedHandler.publish(new LogRecord(Level.INFO, "Should not write through symlink")); + } + rejectedHandler.close(); + assertFalse(Files.exists(realTargetDir.resolve("BQ-JDBC-GLOBAL.log"))); + + PerConnectionFileHandler badSyntaxHandler = + new PerConnectionFileHandler("bad\0path", Level.INFO); + badSyntaxHandler.publish(new LogRecord(Level.INFO, "Gracefully ignored on invalid path")); + badSyntaxHandler.close(); + + try (SeekableByteChannel ch = + PerConnectionFileHandler.openSecureAppendChannel(tempDir.resolve("owned.log"))) { + assertNotNull(ch); + } + } + + @Test + public void testPercentTokensAndCollisionIsolation() throws IOException { + Path literalPercentDir = tempDir.resolve("dir_%t_%h_%g_%u"); + PerConnectionFileHandler percentHandler = + new PerConnectionFileHandler(literalPercentDir.toString(), Level.INFO); + BigQueryJdbcCustomLogger customLogger = + new BigQueryJdbcCustomLogger(PerConnectionFileHandlerTest.class.getName()); + customLogger.setLevel(Level.ALL); + customLogger.addHandler(percentHandler); + try { + customLogger.info("Literal percent dir log %s", "ok"); + try (BigQueryJdbcMdc.MdcCloseable m1 = BigQueryJdbcMdc.registerInstance("abcd-1111")) { + percentHandler.publish(new LogRecord(Level.INFO, "First abcd connection")); + } + try (BigQueryJdbcMdc.MdcCloseable m2 = BigQueryJdbcMdc.registerInstance("abcd-2222")) { + percentHandler.publish(new LogRecord(Level.INFO, "Second abcd connection")); + } + percentHandler.flush(); + String content = readUtf8(literalPercentDir.resolve("BQ-JDBC-GLOBAL.log")); + assertTrue(content.contains("Literal percent dir log ok")); + assertTrue(content.contains("PerConnectionFileHandlerTest")); + } finally { + customLogger.removeHandler(percentHandler); + percentHandler.close(); + } + + try (BigQueryJdbcMdc.MdcCloseable m3 = BigQueryJdbcMdc.registerInstance("after-close")) { + percentHandler.publish(new LogRecord(Level.INFO, "Ignored after handler close")); + } + + try (Stream stream = Files.list(literalPercentDir)) { + List files = stream.collect(Collectors.toList()); + assertTrue(files.stream().noneMatch(p -> p.getFileName().toString().endsWith(".lck"))); + assertTrue(files.stream().noneMatch(p -> p.getFileName().toString().endsWith("-afte.log"))); + assertEquals( + 2L, files.stream().filter(p -> p.getFileName().toString().endsWith("-abcd.log")).count()); + } + } } From 234730818d70498143f452b037549ed19ccc3d04 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 23 Nov 2026 11:35:24 -0500 Subject: [PATCH 2/7] fix(bigquery-jdbc): add 1 GiB .1.log backup rotation and typed ConnectionLogContext PR 2 of 6 in the diagnostic logging series (b/584840147, part 2 of 3). Adds bounded 1 GiB two-file (.log + .1.log 0600 backup) rotation with graceful ErrorManager fallback to PerConnectionFileHandler, and replaces raw String LogRecord parameter stamping with typed ConnectionLogContext across BigQueryJdbcResultSetLogger and OpenTelemetryJulHandler. --- .../jdbc/BigQueryJdbcResultSetLogger.java | 56 +++-- .../bigquery/jdbc/BigQueryJdbcRootLogger.java | 6 +- .../bigquery/jdbc/ConnectionLogContext.java | 66 +++++ .../jdbc/OpenTelemetryJulHandler.java | 47 +++- .../jdbc/PerConnectionFileHandler.java | 225 +++++++++++++++--- .../jdbc/BigQueryJdbcCustomLoggerTest.java | 15 +- .../jdbc/OpenTelemetryJulHandlerTest.java | 58 ++++- .../jdbc/PerConnectionFileHandlerTest.java | 126 ++++++++++ 8 files changed, 522 insertions(+), 77 deletions(-) create mode 100644 java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java index 2e5753fa2c46..9632d599edfa 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java @@ -31,10 +31,11 @@ * plus the connection ID of the ResultSet it serves. * *

Hot-path methods ({@code finestTrace} etc.) set the source class and method explicitly, so no - * stack-trace walking (caller inference) happens for them. The connection ID is stamped into {@code - * LogRecord.getParameters()[0]} on every record so {@code PerConnectionFileHandler} can route the - * record even when the thread-local MDC (mapped diagnostic context — the per-thread connection ID - * set by the JDBC proxy) is empty, which is the normal case for un-proxied ResultSet calls. + * stack-trace walking (caller inference) happens for them. A typed {@link ConnectionLogContext} is + * stamped into {@code LogRecord.getParameters()[0]} on every record so {@code + * PerConnectionFileHandler} can route the record even when the thread-local MDC (mapped diagnostic + * context — the per-thread connection ID set by the JDBC proxy) is empty, which is the normal case + * for un-proxied ResultSet calls. */ public final class BigQueryJdbcResultSetLogger { @@ -49,6 +50,7 @@ public final class BigQueryJdbcResultSetLogger { private final BigQueryJdbcCustomLogger delegate; private final String targetClassName; private final String connectionId; + private final ConnectionLogContext connectionContext; private volatile BigQueryJdbcResultSetLogger arrowStructLogger; private volatile BigQueryJdbcResultSetLogger jsonStructLogger; @@ -56,25 +58,36 @@ public final class BigQueryJdbcResultSetLogger { private volatile BigQueryJdbcResultSetLogger jsonArrayLogger; private BigQueryJdbcResultSetLogger( - BigQueryJdbcCustomLogger delegate, String targetClassName, String connectionId) { + BigQueryJdbcCustomLogger delegate, + String targetClassName, + ConnectionLogContext connectionContext) { this.delegate = delegate; this.targetClassName = targetClassName; - this.connectionId = connectionId; + this.connectionContext = connectionContext; + this.connectionId = connectionContext != null ? connectionContext.connectionId() : null; } public static BigQueryJdbcResultSetLogger getLogger(Class clazz) { - return getLogger(clazz, null); + return getLogger(clazz, (ConnectionLogContext) null); } public static BigQueryJdbcResultSetLogger getLogger(Class clazz, String connectionId) { + if (connectionId == null || connectionId.isEmpty()) { + return getLogger(clazz, (ConnectionLogContext) null); + } + return getLogger(clazz, new ConnectionLogContext(connectionId, ConnectionLogContext.ALL_VALUE)); + } + + static BigQueryJdbcResultSetLogger getLogger( + Class clazz, ConnectionLogContext connectionContext) { String className = clazz.getName(); BigQueryJdbcCustomLogger delegate = DELEGATES.computeIfAbsent(className, BigQueryJdbcCustomLogger::new); - if (connectionId == null) { + if (connectionContext == null) { return GLOBAL_FACADES.computeIfAbsent( className, k -> new BigQueryJdbcResultSetLogger(delegate, k, null)); } - return new BigQueryJdbcResultSetLogger(delegate, className, connectionId); + return new BigQueryJdbcResultSetLogger(delegate, className, connectionContext); } public String getConnectionId() { @@ -92,46 +105,49 @@ public boolean isLoggable(Level level) { public BigQueryJdbcResultSetLogger getArrowStructLogger() { if (arrowStructLogger == null) { - arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionId); + arrowStructLogger = getLogger(BigQueryArrowStruct.class, connectionContext); } return arrowStructLogger; } public BigQueryJdbcResultSetLogger getJsonStructLogger() { if (jsonStructLogger == null) { - jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionId); + jsonStructLogger = getLogger(BigQueryJsonStruct.class, connectionContext); } return jsonStructLogger; } public BigQueryJdbcResultSetLogger getArrowArrayLogger() { if (arrowArrayLogger == null) { - arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionId); + arrowArrayLogger = getLogger(BigQueryArrowArray.class, connectionContext); } return arrowArrayLogger; } public BigQueryJdbcResultSetLogger getJsonArrayLogger() { if (jsonArrayLogger == null) { - jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionId); + jsonArrayLogger = getLogger(BigQueryJsonArray.class, connectionContext); } return jsonArrayLogger; } /** - * Stamps the connection ID into {@code params[0]} and forwards to the shared logger. Does not - * touch the record's source class/method: hot-path callers set them explicitly, and cold-path - * callers ({@code severe}, {@code warning}) rely on {@link + * Stamps the {@link ConnectionLogContext} into {@code params[0]} and forwards to the shared + * logger. Does not touch the record's source class/method: hot-path callers set them explicitly, + * and cold-path callers ({@code severe}, {@code warning}) rely on {@link * BigQueryJdbcCustomLogger.BigQueryJdbcLogRecord} to infer them lazily. */ public void log(LogRecord record) { - if (connectionId != null) { + if (record == null) { + return; + } + if (connectionContext != null) { Object[] existingParams = record.getParameters(); if (existingParams == null || existingParams.length == 0) { - record.setParameters(new Object[] {connectionId}); - } else { + record.setParameters(new Object[] {connectionContext}); + } else if (!(existingParams[0] instanceof ConnectionLogContext)) { Object[] newParams = new Object[existingParams.length + 1]; - newParams[0] = connectionId; + newParams[0] = connectionContext; System.arraycopy(existingParams, 0, newParams, 1, existingParams.length); record.setParameters(newParams); } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java index b6e1b13afc7e..0f1c7ab269e4 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java @@ -104,9 +104,9 @@ public String format(LogRecord record) { String date = DATE_FORMATTER.format(Instant.ofEpochMilli(record.getMillis())); String connectionId = BigQueryJdbcMdc.getConnectionId(); if (connectionId == null || connectionId.isEmpty()) { - Object[] params = record.getParameters(); - if (params != null && params.length > 0 && params[0] instanceof String) { - connectionId = (String) params[0]; + ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); + if (context != null) { + connectionId = context.connectionId(); } } String connStr = diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java new file mode 100644 index 000000000000..073b2333a72b --- /dev/null +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/ConnectionLogContext.java @@ -0,0 +1,66 @@ +/* + * Copyright 2026 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.bigquery.jdbc; + +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.LogRecord; + +/** + * Carries per-connection logging identity and threshold across threads and unproxied {@code + * ResultSet} log records without colliding with user or library {@code String} log parameters. + */ +final class ConnectionLogContext { + static final int OFF_VALUE = Level.OFF.intValue(); + static final int ALL_VALUE = Level.ALL.intValue(); + + private final String connectionId; + private volatile int levelValue; + + ConnectionLogContext(String connectionId, int levelValue) { + this.connectionId = Objects.requireNonNull(connectionId, "connectionId cannot be null"); + this.levelValue = levelValue; + } + + String connectionId() { + return connectionId; + } + + int levelValue() { + return levelValue; + } + + void setLevelValue(int levelValue) { + this.levelValue = levelValue; + } + + static ConnectionLogContext extractFromParameters(LogRecord record) { + if (record == null) { + return null; + } + Object[] params = record.getParameters(); + if (params != null && params.length > 0 && params[0] instanceof ConnectionLogContext) { + return (ConnectionLogContext) params[0]; + } + return null; + } + + @Override + public String toString() { + return connectionId; + } +} diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java index 79874f7d085a..fbd7a5c844be 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandler.java @@ -28,7 +28,9 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.context.Context; +import java.text.MessageFormat; import java.time.Instant; +import java.util.Arrays; import java.util.Collections; import java.util.logging.ErrorManager; import java.util.logging.Handler; @@ -63,6 +65,13 @@ public void publish(LogRecord record) { connectionId = BigQueryJdbcMdc.getConnectionId(); } + if (connectionId == null || connectionId.isEmpty()) { + ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); + if (context != null) { + connectionId = context.connectionId(); + } + } + if (connectionId == null || connectionId.isEmpty()) { return; } @@ -97,8 +106,9 @@ private void publishToGcp(LogRecord record, String connectionId, Logging logging logId = UNSAFE_LOG_CHARACTERS.matcher(logId).replaceAll("_"); } + String formattedBody = formatMessage(record); LogEntry.Builder builder = - LogEntry.newBuilder(Payload.StringPayload.of(formatMessage(record))) + LogEntry.newBuilder(Payload.StringPayload.of(formattedBody != null ? formattedBody : "")) .setSeverity(mapGcpSeverity(record.getLevel())) .setTimestamp(Instant.ofEpochMilli(record.getMillis())) .setLogName(logId); @@ -135,13 +145,16 @@ private void publishToOTel(LogRecord record, String connectionId, OpenTelemetry ? loggerName : BigQueryJdbcOpenTelemetry.INSTRUMENTATION_SCOPE_NAME); + String formattedBody = formatMessage(record); LogRecordBuilder builder = logger .logRecordBuilder() - .setBody(formatMessage(record)) .setSeverity(mapSeverity(record.getLevel())) .setTimestamp(Instant.ofEpochMilli(record.getMillis())) .setContext(Context.current()); + if (formattedBody != null) { + builder.setBody(formattedBody); + } if (connectionId != null) { builder.setAttribute( @@ -165,15 +178,33 @@ private Severity mapSeverity(Level level) { private String formatMessage(LogRecord record) { String message = record.getMessage(); + if (message == null) { + return null; + } Object[] params = record.getParameters(); - if (params != null && params.length > 0) { - try { - return java.text.MessageFormat.format(message, params); - } catch (IllegalArgumentException e) { - return message; + if (params == null || params.length == 0) { + return message; + } + int startIndex = (params[0] instanceof ConnectionLogContext) ? 1 : 0; + if (params.length <= startIndex || !hasPositionalPlaceholder(message)) { + return message; + } + Object[] messageParams = + startIndex == 0 ? params : Arrays.copyOfRange(params, startIndex, params.length); + try { + return MessageFormat.format(message, messageParams); + } catch (IllegalArgumentException e) { + return message; + } + } + + private static boolean hasPositionalPlaceholder(String message) { + for (int i = 0; i <= 9; i++) { + if (message.indexOf("{" + i) >= 0) { + return true; } } - return message; + return false; } @Override diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index ae2f4c8d5348..54b26a1458e6 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java @@ -16,6 +16,7 @@ package com.google.cloud.bigquery.jdbc; +import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; @@ -28,6 +29,7 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; @@ -46,39 +48,51 @@ /** * Custom logging handler that dynamically creates and routes log records to per-connection log - * files using NIO {@link SeekableByteChannel} writers with owner-only POSIX permissions and - * graceful {@link ErrorManager} degradation. + * files using NIO {@link SeekableByteChannel} writers with owner-only POSIX permissions, bounded + * two-file ({@code .log} + {@code .1.log}) rotation, and graceful {@link ErrorManager} degradation. */ class PerConnectionFileHandler extends Handler { + static final long DEFAULT_MAX_LOG_FILE_BYTES = 1024L * 1024L * 1024L; + static final String MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY = + "com.google.cloud.bigquery.jdbc.maxLogFileBytes"; + private static final String DEFAULT_HANDLER_ID = "Jdbc-default"; private static final int MAX_COLLISION_ATTEMPTS = 64; private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss"); private static final Set OWNER_DIR_PERMS = PosixFilePermissions.fromString("rwx------"); - private static final Set OWNER_FILE_PERMS = + static final Set OWNER_FILE_PERMS = PosixFilePermissions.fromString("rw-------"); - private static final Set ACTIVE_GLOBAL_PATHS = ConcurrentHashMap.newKeySet(); + static final Set ACTIVE_GLOBAL_PATHS = ConcurrentHashMap.newKeySet(); private final Path baseLogPath; private final Level level; + private final long maxFileBytes; private final Formatter logFormatter; - private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); - private final ChannelLogWriter defaultWriter; + private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); + private final BoundedLogFileWriter defaultWriter; private volatile boolean handlerClosed = false; PerConnectionFileHandler(String baseLogPath, Level level) { + this(baseLogPath, level, resolveMaxLogFileBytes()); + } + + @VisibleForTesting + PerConnectionFileHandler(String baseLogPath, Level level, long maxFileBytes) { this.level = level; + this.maxFileBytes = maxFileBytes > 0 ? maxFileBytes : DEFAULT_MAX_LOG_FILE_BYTES; this.logFormatter = BigQueryJdbcRootLogger.getFormatter(); setLevel(level); setFormatter(this.logFormatter); Path verifiedDir = null; - ChannelLogWriter initializedDefault = null; + BoundedLogFileWriter initializedDefault = null; try { verifiedDir = ensureSecureDirectory(Paths.get(baseLogPath != null ? baseLogPath : "").toAbsolutePath()); - initializedDefault = createLogWriter(DEFAULT_HANDLER_ID, verifiedDir, this.level); + initializedDefault = + createLogWriter(DEFAULT_HANDLER_ID, verifiedDir, this.level, this.maxFileBytes); } catch (Exception e) { reportError("Failed to initialize default log file", e, ErrorManager.OPEN_FAILURE); } @@ -86,7 +100,12 @@ class PerConnectionFileHandler extends Handler { this.defaultWriter = initializedDefault; } - private static boolean isPosixFileSystem(Path path) { + static long resolveMaxLogFileBytes() { + Long configured = Long.getLong(MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY); + return (configured != null && configured > 0) ? configured : DEFAULT_MAX_LOG_FILE_BYTES; + } + + static boolean isPosixFileSystem(Path path) { return path.getFileSystem().supportedFileAttributeViews().contains("posix"); } @@ -207,7 +226,7 @@ private static SeekableByteChannel configureNewChannel( } } - private static void closeQuietlyWithSuppressed(SeekableByteChannel channel, Throwable primary) { + static void closeQuietlyWithSuppressed(SeekableByteChannel channel, Throwable primary) { try { channel.close(); } catch (IOException closeEx) { @@ -215,7 +234,7 @@ private static void closeQuietlyWithSuppressed(SeekableByteChannel channel, Thro } } - private static OpenedChannel openLockedGlobalChannel(Path file) throws IOException { + static OpenedChannel openLockedGlobalChannel(Path file) throws IOException { Path claim = file.toAbsolutePath().normalize(); if (!ACTIVE_GLOBAL_PATHS.add(claim)) { throw new FileAlreadyExistsException( @@ -247,7 +266,7 @@ private static OpenedChannel openLockedGlobalChannel(Path file) throws IOExcepti } channel.position(channel.size()); transferred = true; - return new OpenedChannel(claim, channel); + return new OpenedChannel(file, claim, channel); } finally { if (!transferred) { ACTIVE_GLOBAL_PATHS.remove(claim); @@ -274,14 +293,17 @@ private static SeekableByteChannel openExclusiveNewChannel(Path file) throws IOE isPosix); } - private ChannelLogWriter createLogWriter(String id, Path logDir, Level writerLevel) { + private BoundedLogFileWriter createLogWriter( + String id, Path logDir, Level writerLevel, long limitBytes) { if (logDir == null) { return null; } try { - OpenedChannel opened = allocateChannel(ensureSecureDirectory(logDir), id); + Path verifiedDir = ensureSecureDirectory(logDir); + OpenedChannel opened = allocateChannel(verifiedDir, id); try { - return new ChannelLogWriter(opened, writerLevel, logFormatter, this); + return new BoundedLogFileWriter( + id, verifiedDir, opened, writerLevel, limitBytes, logFormatter, this); } catch (Exception initEx) { opened.releaseOnFailure(initEx); throw initEx; @@ -323,8 +345,9 @@ private static OpenedChannel allocateChannel(Path logDir, String id) throws IOEx attempt == 0 ? "BQ-JDBC-" + timestamp + "-" + shortUuid + ".log" : "BQ-JDBC-" + timestamp + "-" + attempt + "-" + shortUuid + ".log"; + Path candidate = logDir.resolve(fileName); try { - return new OpenedChannel(null, openExclusiveNewChannel(logDir.resolve(fileName))); + return new OpenedChannel(candidate, null, openExclusiveNewChannel(candidate)); } catch (FileAlreadyExistsException e) { // Same-second prefix collision or pre-existing file; retry with collision counter. } @@ -332,6 +355,23 @@ private static OpenedChannel allocateChannel(Path logDir, String id) throws IOEx throw new IOException("Unable to allocate unique log file for connection " + id); } + static OpenedChannel reopenOrAllocate(Path logDir, String id, Path preferred) throws IOException { + try { + return DEFAULT_HANDLER_ID.equals(id) + ? openLockedGlobalChannel(preferred) + : new OpenedChannel(preferred, null, openExclusiveNewChannel(preferred)); + } catch (FileAlreadyExistsException ex) { + return allocateChannel(logDir, id); + } + } + + static Path deriveBackupPath(Path activePath) { + String name = activePath.getFileName().toString(); + String backup = + name.endsWith(".log") ? name.substring(0, name.length() - 4) + ".1.log" : name + ".1"; + return activePath.resolveSibling(backup); + } + @Override public void publish(LogRecord record) { if (handlerClosed || !isLoggable(record)) { @@ -340,24 +380,30 @@ public void publish(LogRecord record) { String connectionId = BigQueryJdbcMdc.getConnectionId(); if (connectionId == null || connectionId.isEmpty()) { - Object[] params = record.getParameters(); - if (params != null && params.length > 0 && params[0] instanceof String) { - connectionId = (String) params[0]; + ConnectionLogContext context = ConnectionLogContext.extractFromParameters(record); + if (context != null) { + connectionId = context.connectionId(); } } if (connectionId != null && !connectionId.isEmpty()) { - ChannelLogWriter writer = + BoundedLogFileWriter writer = writers.computeIfAbsent( - connectionId, id -> handlerClosed ? null : createLogWriter(id, baseLogPath, level)); + connectionId, + id -> + handlerClosed + ? null + : createLogWriter(id, baseLogPath, this.level, this.maxFileBytes)); if (writer != null) { if (handlerClosed) { writers.remove(connectionId, writer); writer.close(); return; } - writer.publish(record); - return; + if (writer.publish(record)) { + return; + } + writers.remove(connectionId, writer); } } @@ -371,7 +417,7 @@ public void flush() { if (defaultWriter != null) { defaultWriter.flush(); } - for (ChannelLogWriter writer : writers.values()) { + for (BoundedLogFileWriter writer : writers.values()) { writer.flush(); } } @@ -380,7 +426,7 @@ public void flush() { public void close() throws SecurityException { handlerClosed = true; for (String id : writers.keySet()) { - ChannelLogWriter removed = writers.remove(id); + BoundedLogFileWriter removed = writers.remove(id); if (removed != null) { removed.close(); } @@ -392,7 +438,7 @@ public void close() throws SecurityException { public void closeHandler(String connectionId) { if (connectionId != null) { - ChannelLogWriter writer = writers.remove(connectionId); + BoundedLogFileWriter writer = writers.remove(connectionId); if (writer != null) { writer.close(); } @@ -400,10 +446,12 @@ public void closeHandler(String connectionId) { } private static final class OpenedChannel { + final Path path; final Path claimedGlobalPath; final SeekableByteChannel channel; - OpenedChannel(Path claimedGlobalPath, SeekableByteChannel channel) { + OpenedChannel(Path path, Path claimedGlobalPath, SeekableByteChannel channel) { + this.path = path; this.claimedGlobalPath = claimedGlobalPath; this.channel = channel; } @@ -416,47 +464,142 @@ void releaseOnFailure(Throwable primary) { } } - private static final class ChannelLogWriter { - private final Path claimedGlobalPath; - private final SeekableByteChannel channel; + private static final class BoundedLogFileWriter { + private final String id; + private final Path logDir; private final Level writerLevel; + private final long maxBytes; private final Formatter formatter; private final PerConnectionFileHandler owner; + @GuardedBy("this") + private Path activePath; + + @GuardedBy("this") + private Path claimedGlobalPath; + + @GuardedBy("this") + private SeekableByteChannel channel; + + @GuardedBy("this") + private long writtenBytes; + @GuardedBy("this") private boolean closed; - ChannelLogWriter( + BoundedLogFileWriter( + String id, + Path logDir, OpenedChannel opened, Level writerLevel, + long maxBytes, Formatter formatter, - PerConnectionFileHandler owner) { + PerConnectionFileHandler owner) + throws IOException { + this.id = id; + this.logDir = logDir; + this.activePath = opened.path; this.claimedGlobalPath = opened.claimedGlobalPath; this.channel = opened.channel; this.writerLevel = writerLevel; + this.maxBytes = maxBytes; this.formatter = formatter; this.owner = owner; + this.writtenBytes = opened.channel.size(); + } + + @GuardedBy("this") + private void rotate() throws IOException { + Path backupPath = deriveBackupPath(activePath); + if (Files.isSymbolicLink(backupPath)) { + Files.deleteIfExists(backupPath); + } else if (Files.exists(backupPath, LinkOption.NOFOLLOW_LINKS)) { + if (!Files.isRegularFile(backupPath, LinkOption.NOFOLLOW_LINKS)) { + throw new IOException("Refusing to rotate onto non-regular backup path: " + backupPath); + } + verifyPosixOwner(backupPath); + } + channel.close(); + channel = null; + if (claimedGlobalPath != null) { + ACTIVE_GLOBAL_PATHS.remove(claimedGlobalPath); + claimedGlobalPath = null; + } + try { + Files.move(activePath, backupPath, StandardCopyOption.REPLACE_EXISTING); + } catch (Exception moveEx) { + try { + OpenedChannel recovered = + DEFAULT_HANDLER_ID.equals(id) + ? openLockedGlobalChannel(activePath) + : new OpenedChannel(activePath, null, openSecureAppendChannel(activePath)); + activePath = recovered.path; + claimedGlobalPath = recovered.claimedGlobalPath; + channel = recovered.channel; + writtenBytes = channel.size(); + } catch (Exception recoverEx) { + moveEx.addSuppressed(recoverEx); + } + if (moveEx instanceof IOException) { + throw (IOException) moveEx; + } + throw new IOException("Failed to move active log file to backup", moveEx); + } + if (isPosixFileSystem(backupPath)) { + try { + Files.setPosixFilePermissions(backupPath, OWNER_FILE_PERMS); + } catch (Exception permEx) { + owner.reportError( + "Failed to set permissions on rotated log file", permEx, ErrorManager.WRITE_FAILURE); + } + } + OpenedChannel reopened = reopenOrAllocate(logDir, id, activePath); + activePath = reopened.path; + claimedGlobalPath = reopened.claimedGlobalPath; + channel = reopened.channel; + writtenBytes = channel.size(); } - synchronized void publish(LogRecord record) { - if (closed || record.getLevel().intValue() < writerLevel.intValue()) { - return; + synchronized boolean publish(LogRecord record) { + if (closed || channel == null) { + return false; + } + if (record.getLevel().intValue() < writerLevel.intValue()) { + return true; } String formatted; try { formatted = formatter.format(record); } catch (Exception ex) { owner.reportError("Failed to format log record", ex, ErrorManager.FORMAT_FAILURE); - return; + return true; } + byte[] bytes = formatted.getBytes(StandardCharsets.UTF_8); try { - ByteBuffer buffer = ByteBuffer.wrap(formatted.getBytes(StandardCharsets.UTF_8)); + if (maxBytes > 0 + && writtenBytes > 0 + && (writtenBytes >= maxBytes || bytes.length > maxBytes - writtenBytes)) { + try { + rotate(); + } catch (Exception rotEx) { + owner.reportError("Failed to rotate log file", rotEx, ErrorManager.WRITE_FAILURE); + if (channel == null) { + closed = true; + return false; + } + channel.truncate(0); + channel.position(0); + writtenBytes = 0; + } + } + ByteBuffer buffer = ByteBuffer.wrap(bytes); while (buffer.hasRemaining()) { - channel.write(buffer); + writtenBytes += channel.write(buffer); } } catch (Exception ex) { owner.reportError("Failed to write log record", ex, ErrorManager.WRITE_FAILURE); } + return true; } synchronized void flush() { @@ -473,12 +616,16 @@ synchronized void close() { if (!closed) { closed = true; try { - channel.close(); + if (channel != null) { + channel.close(); + } } catch (Exception ex) { owner.reportError("Failed to close log file", ex, ErrorManager.CLOSE_FAILURE); } finally { + channel = null; if (claimedGlobalPath != null) { ACTIVE_GLOBAL_PATHS.remove(claimedGlobalPath); + claimedGlobalPath = null; } } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java index c4a6d576f91c..d097b32334a2 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLoggerTest.java @@ -335,7 +335,10 @@ public void testResultSetLoggerCachingBehavior() { BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class); BigQueryJdbcResultSetLogger globalLogger2 = BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class); + BigQueryJdbcResultSetLogger emptyIdLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, ""); assertSame(globalLogger1, globalLogger2); + assertSame(globalLogger1, emptyIdLogger); // Connection-scoped facades are distinct lightweight objects, but they all forward to the // single registered logger for the class — that is what prevents the registration leak. BigQueryJdbcResultSetLogger connLogger1 = @@ -360,14 +363,16 @@ public void testResultSetLoggerParameterPreservation() { LogRecord record = new LogRecord(Level.INFO, "Processing job {0}"); record.setParameters(new Object[] {"job-999"}); rsLogger.log(record); + rsLogger.log(record); List records = rsHandler.getRecords(); - assertEquals(1, records.size()); - LogRecord loggedRecord = records.get(0); + assertEquals(2, records.size()); + LogRecord loggedRecord = records.get(1); Object[] params = loggedRecord.getParameters(); assertEquals(2, params.length); - assertEquals("conn-123", params[0]); + assertTrue(params[0] instanceof ConnectionLogContext); + assertEquals("conn-123", ((ConnectionLogContext) params[0]).connectionId()); assertEquals("job-999", params[1]); } finally { rsLogger.delegate().removeHandler(rsHandler); @@ -394,7 +399,9 @@ private void assertConnectionIdPropagated( capturedLogs.clear(); action.run(); assertEquals(1, capturedLogs.size()); - assertEquals(connectionId, capturedLogs.get(0).getParameters()[0]); + Object firstParam = capturedLogs.get(0).getParameters()[0]; + assertTrue(firstParam instanceof ConnectionLogContext); + assertEquals(connectionId, ((ConnectionLogContext) firstParam).connectionId()); assertTrue(assertLogContains(expectedMessage)); } finally { BigQueryJdbcRootLogger.getRootLogger().setLevel(originalRootLevel); diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java index e923dd011778..eb8cc7e58f92 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/OpenTelemetryJulHandlerTest.java @@ -17,8 +17,10 @@ package com.google.cloud.bigquery.jdbc; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import com.google.cloud.logging.LogEntry; @@ -31,6 +33,8 @@ import io.opentelemetry.sdk.logs.data.LogRecordData; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; import java.util.List; +import java.util.logging.Level; +import java.util.logging.LogRecord; import java.util.logging.Logger; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -120,15 +124,63 @@ public void testPublishToGcp() { try (Scope scope = baggage.makeCurrent(); BigQueryJdbcMdc.MdcCloseable mdcScope = BigQueryJdbcMdc.registerInstance("gcp-uuid")) { logger.info("Test message"); + logger.log(new LogRecord(Level.INFO, null)); } ArgumentCaptor> captor = ArgumentCaptor.forClass(Iterable.class); - verify(loggingClient).write(captor.capture()); + verify(loggingClient, times(2)).write(captor.capture()); - Iterable entries = captor.getValue(); - LogEntry entry = entries.iterator().next(); + List> allWrites = captor.getAllValues(); + LogEntry entry = allWrites.get(0).iterator().next(); + LogEntry nullEntry = allWrites.get(1).iterator().next(); assertEquals("Test message", ((Payload.StringPayload) entry.getPayload()).getData()); assertEquals(com.google.cloud.logging.Severity.INFO, entry.getSeverity()); + assertEquals("", ((Payload.StringPayload) nullEntry.getPayload()).getData()); + } + + @Test + public void testResultSetLoggerRoutingAndMessageFormatting() { + BigQueryJdbcOpenTelemetry.registerConnection( + "test-uuid", otelTesting.getOpenTelemetry(), null, false); + BigQueryJdbcMdc.clear(); + + BigQueryJdbcResultSetLogger rsLogger = + BigQueryJdbcResultSetLogger.getLogger(BigQueryBaseResultSet.class, "test-uuid"); + rsLogger.fineTrace("getObject", "Column 'user_id' has unparsed {json}"); + + LogRecord parameterized = new LogRecord(Level.INFO, "Processing job {0}"); + parameterized.setParameters(new Object[] {"job-999"}); + rsLogger.log(parameterized); + + Baggage baggage = + Baggage.builder() + .put(BigQueryJdbcOpenTelemetry.CONNECTION_ID_BAGGAGE_KEY, "test-uuid") + .build(); + try (Scope scope = baggage.makeCurrent()) { + LogRecord retryStyle = new LogRecord(Level.INFO, "Retrying 'getQueryResults'"); + retryStyle.setParameters(new Object[] {"attempt=1"}); + logger.log(retryStyle); + + LogRecord directPositional = new LogRecord(Level.INFO, "Direct {0} ok"); + directPositional.setParameters(new Object[] {"param0"}); + logger.log(directPositional); + + LogRecord malformedPattern = new LogRecord(Level.INFO, "Broken {0"); + malformedPattern.setParameters(new Object[] {"param0"}); + logger.log(malformedPattern); + + LogRecord nullMessage = new LogRecord(Level.INFO, null); + logger.log(nullMessage); + } + + List logs = otelTesting.getLogRecords(); + assertEquals(6, logs.size()); + assertEquals("Column 'user_id' has unparsed {json}", logs.get(0).getBodyValue().asString()); + assertEquals("Processing job job-999", logs.get(1).getBodyValue().asString()); + assertEquals("Retrying 'getQueryResults'", logs.get(2).getBodyValue().asString()); + assertEquals("Direct param0 ok", logs.get(3).getBodyValue().asString()); + assertEquals("Broken {0", logs.get(4).getBodyValue().asString()); + assertNull(logs.get(5).getBodyValue()); } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java index 22381978da23..e4496b08d7ea 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java @@ -416,4 +416,130 @@ public void testPercentTokensAndCollisionIsolation() throws IOException { 2L, files.stream().filter(p -> p.getFileName().toString().endsWith("-abcd.log")).count()); } } + + @Test + public void testOneGibDefaultAndBackupFileRotationAndTypedParams() throws IOException { + assertEquals(1024L * 1024L * 1024L, PerConnectionFileHandler.DEFAULT_MAX_LOG_FILE_BYTES); + String prop = PerConnectionFileHandler.MAX_LOG_FILE_BYTES_SYSTEM_PROPERTY; + String prev = System.getProperty(prop); + try { + System.setProperty(prop, "3000000000"); + assertEquals(3_000_000_000L, PerConnectionFileHandler.resolveMaxLogFileBytes()); + System.setProperty(prop, "-5"); + assertEquals( + PerConnectionFileHandler.DEFAULT_MAX_LOG_FILE_BYTES, + PerConnectionFileHandler.resolveMaxLogFileBytes()); + } finally { + if (prev == null) { + System.clearProperty(prop); + } else { + System.setProperty(prop, prev); + } + } + + Path boundedDir = tempDir.resolve("bounded"); + long maxBytes = 1024L; + PerConnectionFileHandler defaultMaxHandler = + new PerConnectionFileHandler(tempDir.resolve("def_max").toString(), Level.INFO, 0L); + defaultMaxHandler.close(); + + ConnectionLogContext connCtx = + new ConnectionLogContext("rotc-uuid", ConnectionLogContext.ALL_VALUE); + assertEquals(ConnectionLogContext.ALL_VALUE, connCtx.levelValue()); + connCtx.setLevelValue(ConnectionLogContext.OFF_VALUE); + assertEquals(ConnectionLogContext.OFF_VALUE, connCtx.levelValue()); + assertEquals("rotc-uuid", connCtx.toString()); + assertNull(ConnectionLogContext.extractFromParameters(null)); + + PerConnectionFileHandler boundedHandler = + new PerConnectionFileHandler(boundedDir.toString(), Level.FINEST, maxBytes); + try { + for (int i = 0; i < 40; i++) { + boundedHandler.publish( + new LogRecord(Level.INFO, "Padding log line to exceed 1 KiB limit #" + i)); + } + // Route via ConnectionLogContext in params[0] with empty MDC and trigger per-conn .1.log + BigQueryJdbcMdc.clear(); + for (int i = 0; i < 15; i++) { + LogRecord ctxRec = new LogRecord(Level.INFO, "Per-conn ctx rotation line #" + i); + ctxRec.setParameters(new Object[] {connCtx}); + boundedHandler.publish(ctxRec); + } + // Plain String in params[0] with empty MDC routes to global log instead of "-BigQ.log" + LogRecord retryRecord = new LogRecord(Level.FINEST, "Retrying RPC"); + retryRecord.setParameters(new Object[] {"BigQuery retried method: getQueryResults"}); + boundedHandler.publish(retryRecord); + assertTrue(BigQueryJdbcRootLogger.getFormatter().format(retryRecord).contains("[NO_CONN]")); + boundedHandler.flush(); + } finally { + boundedHandler.close(); + } + + Path boundedGlobal = boundedDir.resolve("BQ-JDBC-GLOBAL.log"); + Path boundedBackup = boundedDir.resolve("BQ-JDBC-GLOBAL.1.log"); + assertTrue(Files.size(boundedGlobal) > 0 && Files.size(boundedGlobal) <= maxBytes); + assertTrue(Files.size(boundedBackup) > 0 && Files.size(boundedBackup) <= maxBytes); + assertFalse(Files.exists(boundedDir.resolve("BQ-JDBC-GLOBAL.2.log"))); + assertTrue(findLogFile(boundedDir, "-rotc.log").isPresent()); + assertTrue(findLogFile(boundedDir, "-rotc.1.log").isPresent()); + assertFalse(findLogFile(boundedDir, "-BigQ.log").isPresent()); + if (boundedBackup.getFileSystem().supportedFileAttributeViews().contains("posix")) { + assertMode(boundedBackup, "rw-------"); + assertMode(boundedGlobal, "rw-------"); + assertMode(findLogFile(boundedDir, "-rotc.1.log").get(), "rw-------"); + + // Symlink at .1.log is deleted safely without modifying target; foreign owner falls back + Path symDir = tempDir.resolve("sym_rot"); + Files.createDirectories(symDir); + Path untouchedTarget = + Files.write(tempDir.resolve("untouched.txt"), "safe".getBytes(StandardCharsets.UTF_8)); + Files.createSymbolicLink(symDir.resolve("BQ-JDBC-GLOBAL.1.log"), untouchedTarget); + PerConnectionFileHandler symRotHandler = + new PerConnectionFileHandler(symDir.toString(), Level.INFO, maxBytes); + String origUser = System.getProperty("user.name"); + try { + for (int i = 0; i < 12; i++) { + symRotHandler.publish(new LogRecord(Level.INFO, "Symlink backup rotation line #" + i)); + } + assertEquals("safe", readUtf8(untouchedTarget)); + assertFalse(Files.isSymbolicLink(symDir.resolve("BQ-JDBC-GLOBAL.1.log"))); + System.setProperty("user.name", "other_user"); + for (int i = 0; i < 12; i++) { + symRotHandler.publish(new LogRecord(Level.INFO, "Foreign backup fallback line #" + i)); + } + symRotHandler.flush(); + assertTrue(readUtf8(symDir.resolve("BQ-JDBC-GLOBAL.log")).contains("fallback line #11")); + } finally { + if (origUser != null) { + System.setProperty("user.name", origUser); + } else { + System.clearProperty("user.name"); + } + symRotHandler.close(); + } + } + String backupContent = readUtf8(boundedBackup); + String activeContent = readUtf8(boundedGlobal); + assertFalse(backupContent.contains("limit #0") || activeContent.contains("limit #0")); + assertTrue(backupContent.contains("Padding log line")); + assertTrue(activeContent.contains("Retrying RPC")); + + // Non-regular directory blocking .1.log falls back gracefully to in-place truncation + Path fallbackDir = tempDir.resolve("fallback_rot"); + Files.createDirectories(fallbackDir.resolve("BQ-JDBC-GLOBAL.1.log")); + PerConnectionFileHandler fallbackHandler = + new PerConnectionFileHandler(fallbackDir.toString(), Level.INFO, maxBytes); + try { + for (int i = 0; i < 20; i++) { + fallbackHandler.publish( + new LogRecord(Level.INFO, "Fallback line exceeding 1 KiB cap #" + i)); + } + fallbackHandler.flush(); + } finally { + fallbackHandler.close(); + } + Path fallbackGlobal = fallbackDir.resolve("BQ-JDBC-GLOBAL.log"); + assertTrue(Files.size(fallbackGlobal) > 0 && Files.size(fallbackGlobal) <= maxBytes); + assertTrue(readUtf8(fallbackGlobal).contains("cap #19")); + } } From 3b6153a54417b1612e358382e6d7ea93ca3f7298 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 23 Nov 2026 11:43:00 -0500 Subject: [PATCH 3/7] fix(bigquery-jdbc): gate per-connection log writers on active connection lifecycle PR 3 of 6 in the diagnostic logging series (b/584840147, part 3 of 3). Tracks active connections in BigQueryJdbcRootLogger with BigQueryConnection constructor finally cleanup and wraps per-connection writers in synchronized ConnectionFileSlot entries so post-close ResultSet/Struct calls and concurrent close() vs publish() calls do not reopen closed writers. --- .../bigquery/jdbc/BigQueryConnection.java | 25 ++- .../jdbc/BigQueryJdbcResultSetLogger.java | 7 +- .../bigquery/jdbc/BigQueryJdbcRootLogger.java | 52 +++++- .../jdbc/PerConnectionFileHandler.java | 130 +++++++++++--- .../jdbc/PerConnectionFileHandlerTest.java | 159 ++++++++++++++++++ 5 files changed, 340 insertions(+), 33 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java index f26751102db7..6fc7dd168d24 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java @@ -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(); @@ -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; + } } } @@ -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; diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java index 9632d599edfa..b87b07edfc3d 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java @@ -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); } static BigQueryJdbcResultSetLogger getLogger( diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java index 0f1c7ab269e4..7e401722b726 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcRootLogger.java @@ -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; @@ -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 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]; @@ -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); @@ -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 = ""; @@ -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); } } } diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index 54b26a1458e6..eb5df779caa8 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java @@ -70,9 +70,10 @@ class PerConnectionFileHandler extends Handler { private final Level level; private final long maxFileBytes; private final Formatter logFormatter; - private final ConcurrentHashMap writers = new ConcurrentHashMap<>(); + final Set registeredConnections = ConcurrentHashMap.newKeySet(); + private final ConcurrentHashMap 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()); @@ -293,7 +294,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; @@ -372,6 +373,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)) { @@ -387,23 +401,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; + }); + 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); } } @@ -417,18 +432,19 @@ public void flush() { if (defaultWriter != null) { defaultWriter.flush(); } - for (BoundedLogFileWriter writer : writers.values()) { - writer.flush(); + for (ConnectionFileSlot slot : slots.values()) { + slot.flushSlot(); } } @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) { @@ -438,9 +454,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(); } } } @@ -631,4 +648,69 @@ 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 flushSlot() { + if (!closed && writer != null) { + writer.flush(); + } + } + + synchronized void closeSlot() { + if (!closed) { + closed = true; + if (writer != null) { + try { + writer.close(); + } finally { + writer = null; + } + } + } + } + } } diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java index e4496b08d7ea..d82f3a08e901 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandlerTest.java @@ -26,7 +26,10 @@ import com.google.cloud.bigquery.Field; import com.google.cloud.bigquery.FieldList; +import com.google.cloud.bigquery.Schema; import com.google.cloud.bigquery.StandardSQLTypeName; +import com.google.cloud.bigquery.jdbc.utils.TestUtilities; +import com.google.cloud.bigquery.jdbc.utils.URIBuilder; import java.io.IOException; import java.nio.channels.SeekableByteChannel; import java.nio.charset.StandardCharsets; @@ -38,9 +41,15 @@ import java.sql.Statement; import java.util.List; import java.util.Optional; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.logging.Formatter; import java.util.logging.Level; import java.util.logging.LogRecord; +import java.util.logging.Logger; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.jupiter.api.AfterEach; @@ -112,6 +121,7 @@ public void testPublishDefault() throws IOException { @Test public void testPublishConnectionSpecific() throws IOException { + handler.registerConnection("c123"); BigQueryJdbcMdc.registerInstance("c123"); LogRecord record = new LogRecord(Level.INFO, "Test message connection 123"); @@ -124,6 +134,7 @@ public void testPublishConnectionSpecific() throws IOException { @Test public void testCloseHandler() throws IOException { + handler.registerConnection("c123"); BigQueryJdbcMdc.registerInstance("c123"); LogRecord record = new LogRecord(Level.INFO, "Test message connection 123"); @@ -149,6 +160,7 @@ public void testCloseHandler() throws IOException { public void testProxyExceptionLogRouting() throws Exception { // Register the temp file handler to the root logger so proxy logs are routed to it java.util.logging.Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + handler.registerConnection("c456"); rootLogger.addHandler(handler); try { @@ -200,6 +212,7 @@ public void testProxyExceptionLogRouting() throws Exception { public void testResultSetExceptionLogRouting() throws Exception { // Register the temp file handler to the root logger so ResultSet logs are captured java.util.logging.Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + handler.registerConnection("c789"); rootLogger.addHandler(handler); try { @@ -254,6 +267,7 @@ public void testPosixOwnerOnlyPermissionsOnCreatedDirsAndFiles() throws IOExcept PerConnectionFileHandler posixHandler = new PerConnectionFileHandler(nestedDir.toString(), Level.FINEST); try { + posixHandler.registerConnection("p999"); try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance("p999")) { posixHandler.publish(new LogRecord(Level.INFO, "Query log entry")); } @@ -389,6 +403,8 @@ public void testPercentTokensAndCollisionIsolation() throws IOException { customLogger.addHandler(percentHandler); try { customLogger.info("Literal percent dir log %s", "ok"); + percentHandler.registerConnection("abcd-1111"); + percentHandler.registerConnection("abcd-2222"); try (BigQueryJdbcMdc.MdcCloseable m1 = BigQueryJdbcMdc.registerInstance("abcd-1111")) { percentHandler.publish(new LogRecord(Level.INFO, "First abcd connection")); } @@ -404,6 +420,7 @@ public void testPercentTokensAndCollisionIsolation() throws IOException { percentHandler.close(); } + percentHandler.registerConnection("after-close"); try (BigQueryJdbcMdc.MdcCloseable m3 = BigQueryJdbcMdc.registerInstance("after-close")) { percentHandler.publish(new LogRecord(Level.INFO, "Ignored after handler close")); } @@ -459,6 +476,7 @@ public void testOneGibDefaultAndBackupFileRotationAndTypedParams() throws IOExce new LogRecord(Level.INFO, "Padding log line to exceed 1 KiB limit #" + i)); } // Route via ConnectionLogContext in params[0] with empty MDC and trigger per-conn .1.log + boundedHandler.registerConnection("rotc-uuid"); BigQueryJdbcMdc.clear(); for (int i = 0; i < 15; i++) { LogRecord ctxRec = new LogRecord(Level.INFO, "Per-conn ctx rotation line #" + i); @@ -542,4 +560,145 @@ public void testOneGibDefaultAndBackupFileRotationAndTypedParams() throws IOExce assertTrue(Files.size(fallbackGlobal) > 0 && Files.size(fallbackGlobal) <= maxBytes); assertTrue(readUtf8(fallbackGlobal).contains("cap #19")); } + + @Test + public void testConcurrentCloseAndPublishLeavesNoOpenConnectionFiles() throws Exception { + Path raceDir = tempDir.resolve("race"); + for (int round = 0; round < 15; round++) { + PerConnectionFileHandler raceHandler = + new PerConnectionFileHandler(raceDir.resolve("r" + round).toString(), Level.INFO); + String connId = "race-" + round; + raceHandler.registerConnection(connId); + CountDownLatch start = new CountDownLatch(1); + ExecutorService pool = Executors.newFixedThreadPool(3); + Runnable publishLoop = + () -> { + try (BigQueryJdbcMdc.MdcCloseable m = BigQueryJdbcMdc.registerInstance(connId)) { + start.await(); + for (int i = 0; i < 10; i++) { + raceHandler.publish(new LogRecord(Level.INFO, "race msg " + i)); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }; + try { + Future pubTask1 = pool.submit(publishLoop); + Future pubTask2 = pool.submit(publishLoop); + Future closeTask = + pool.submit( + () -> { + try { + start.await(); + raceHandler.close(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + start.countDown(); + pubTask1.get(5, TimeUnit.SECONDS); + pubTask2.get(5, TimeUnit.SECONDS); + closeTask.get(5, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + Path roundDir = raceDir.resolve("r" + round); + try (Stream before = Files.list(roundDir)) { + long countAfterClose = before.count(); + try (BigQueryJdbcMdc.MdcCloseable m = BigQueryJdbcMdc.registerInstance(connId)) { + raceHandler.publish(new LogRecord(Level.INFO, "post-close")); + } + try (Stream after = Files.list(roundDir)) { + assertEquals(countAfterClose, after.count()); + } + } + } + } + + @Test + public void testPostCloseResultSetAndStringParamsDoNotResurrectHandlers() throws Exception { + Path leakDir = tempDir.resolve("no_leak"); + PerConnectionFileHandler finestHandler = + new PerConnectionFileHandler(leakDir.toString(), Level.FINEST); + Logger rootLogger = BigQueryJdbcRootLogger.getRootLogger(); + rootLogger.addHandler(finestHandler); + + try { + String connId = "dead-conn-uuid"; + ConnectionLogContext activeCtx = BigQueryJdbcRootLogger.registerConnection(connId); + assertNotNull(activeCtx); + assertEquals(ConnectionLogContext.ALL_VALUE, activeCtx.levelValue()); + finestHandler.registerConnection(connId); + + BigQueryStatement mockStmt = mock(BigQueryStatement.class); + mockStmt.connectionId = connId; + Schema schema = Schema.of(FieldList.of(Field.of("col", StandardSQLTypeName.INT64))); + BigQueryJsonResultSet rs = + BigQueryJsonResultSet.of(schema, 0, null, mockStmt, new Future[0]); + BigQueryJdbcResultSetLogger activeStructLogger = rs.LOG.getArrowStructLogger(); + + try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connId)) { + finestHandler.publish(new LogRecord(Level.INFO, "Before close")); + } + finestHandler.flush(); + Optional initialLog = findLogFile(leakDir, "-dead.log"); + assertTrue(initialLog.isPresent()); + + rs.close(); + BigQueryJdbcRootLogger.closeConnectionHandler(connId); + finestHandler.closeHandler(connId); + assertEquals(ConnectionLogContext.OFF_VALUE, activeCtx.levelValue()); + Files.delete(initialLog.get()); + + assertThrows(SQLException.class, () -> rs.getShort(1)); + assertThrows(SQLException.class, () -> rs.findColumn(null)); + + activeStructLogger.finestTrace("getAttributes"); + BigQueryJdbcResultSetLogger.getLogger(BigQueryArrowStruct.class, connId) + .finestTrace("getAttributes"); + + BigQueryJdbcMdc.clear(); + LogRecord retryRecord = new LogRecord(Level.FINEST, "Retrying RPC"); + retryRecord.setParameters(new Object[] {"BigQuery retried method: getQueryResults"}); + finestHandler.publish(retryRecord); + finestHandler.flush(); + + assertFalse(findLogFile(leakDir, "-dead.log").isPresent()); + assertFalse(findLogFile(leakDir, "-BigQ.log").isPresent()); + + Formatter formatter = BigQueryJdbcRootLogger.getFormatter(); + String formattedRetry = formatter.format(retryRecord); + assertTrue(formattedRetry.contains("[NO_CONN]")); + assertNull(BigQueryJdbcRootLogger.registerConnection(null)); + assertNull(BigQueryJdbcRootLogger.registerConnection("")); + BigQueryJdbcRootLogger.closeConnectionHandler(null); + } finally { + rootLogger.removeHandler(finestHandler); + finestHandler.close(); + } + } + + @Test + public void testFailedConnectionConstructorCleansUpActiveRegistration() throws IOException { + Path failLogDir = tempDir.resolve("failed_conn_logs"); + int baselineActive = BigQueryJdbcRootLogger.activeConnectionCount(); + String invalidAuthUrl = + new URIBuilder(TestUtilities.getBaseConnectionUrl()) + .append("ProjectId", "test-proj") + .append("OAuthType", 99) + .toString(); + + BigQueryJdbcRootLogger.setLevel(Level.CONFIG, failLogDir.toString()); + try { + assertThrows(RuntimeException.class, () -> new BigQueryConnection(invalidAuthUrl)); + assertEquals(baselineActive, BigQueryJdbcRootLogger.activeConnectionCount()); + try (Stream files = Files.list(failLogDir)) { + List created = files.collect(Collectors.toList()); + assertTrue(created.stream().anyMatch(p -> !p.endsWith("BQ-JDBC-GLOBAL.log"))); + assertTrue(created.stream().noneMatch(p -> p.getFileName().toString().endsWith(".lck"))); + } + } finally { + BigQueryJdbcRootLogger.setLevel(Level.OFF, null); + } + } } From 846a0ef417775b3857325f6b6cb01b86a25195ad Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 23 Nov 2026 14:52:00 -0500 Subject: [PATCH 4/7] docs(bigquery-jdbc): document maxLogFileBytes system property in README --- java-bigquery-jdbc/README.MD | 10 ++++++++++ java-bigquery-jdbc/docs/USER_GUIDE.md | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/java-bigquery-jdbc/README.MD b/java-bigquery-jdbc/README.MD index 34bbb7b38c54..0e7093c3ee91 100644 --- a/java-bigquery-jdbc/README.MD +++ b/java-bigquery-jdbc/README.MD @@ -102,6 +102,16 @@ To configure these properties, you can use the following keys: * Environment Variable: `BIGQUERY_JDBC_TELEMETRY_ENABLED=false` * System Property: `-DBIGQUERY_JDBC_TELEMETRY_ENABLED=false` +## Diagnostic logging configuration + +Diagnostic logging can be configured per connection via JDBC URL or connection properties (`LogLevel`, `LogPath`), globally via environment variables, or tuned at the JVM level via Java system properties: + +* Environment Variables: + * `BIGQUERY_JDBC_LOG_LEVEL`: Default log verbosity level (`0` = `OFF` to `7` = `FINEST`, or `8` = `ALL`) when `LogLevel` is not specified on the connection. + * `BIGQUERY_JDBC_LOG_PATH`: Default directory path for driver log files when `LogPath` is not specified on the connection. +* Java System Properties: + * `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=`: Maximum size in bytes of an active driver `.log` file before rotating onto a `.1.log` backup file (default: `1073741824`, or 1 GiB). + ## Developer Guide ### Prerequisites diff --git a/java-bigquery-jdbc/docs/USER_GUIDE.md b/java-bigquery-jdbc/docs/USER_GUIDE.md index 1549d1b5fb4a..537cfbd25c18 100644 --- a/java-bigquery-jdbc/docs/USER_GUIDE.md +++ b/java-bigquery-jdbc/docs/USER_GUIDE.md @@ -684,6 +684,12 @@ Logging can also be configured globally across all driver connections using envi | **`BIGQUERY_JDBC_LOG_LEVEL`** | `LogLevel` | Global default log verbosity level (`0`–`7` or `OFF`–`FINEST`). Overridden by `LogLevel` URL parameter. | `export BIGQUERY_JDBC_LOG_LEVEL=5` | | **`BIGQUERY_JDBC_LOG_PATH`** | `LogPath` | Global output directory for driver log files. Overridden by `LogPath` URL parameter. | `export BIGQUERY_JDBC_LOG_PATH=/var/log/bigquery-jdbc` | +#### JVM System Properties for Logging: + +| System Property | Default Value | Description | Example | +| :--- | :---: | :--- | :--- | +| **`com.google.cloud.bigquery.jdbc.maxLogFileBytes`** | `1073741824` (1 GiB) | Maximum size (in bytes) of an active `.log` file before rotating onto a `.1.log` backup file. | `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=536870912` | + #### Log Level Reference: | Integer Value | String Constant | `java.util.logging` Level | Description | From 5b55b06c5b1587e3040560c58bd0b004a6d3b89e Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 23 Nov 2026 15:44:12 -0500 Subject: [PATCH 5/7] perf(bigquery-jdbc): make PerConnectionFileHandler.flush() a no-op --- .../jdbc/PerConnectionFileHandler.java | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index ae2f4c8d5348..184ae54dc08d 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java @@ -368,12 +368,8 @@ public void publish(LogRecord record) { @Override public void flush() { - if (defaultWriter != null) { - defaultWriter.flush(); - } - for (ChannelLogWriter writer : writers.values()) { - writer.flush(); - } + // No-op: ChannelLogWriter writes directly to SeekableByteChannel (OS page cache) + // without any JVM-level buffering. } @Override @@ -459,16 +455,6 @@ synchronized void publish(LogRecord record) { } } - synchronized void flush() { - if (!closed && channel instanceof FileChannel) { - try { - ((FileChannel) channel).force(false); - } catch (Exception ex) { - owner.reportError("Failed to flush log file", ex, ErrorManager.FLUSH_FAILURE); - } - } - } - synchronized void close() { if (!closed) { closed = true; From 77ae50ef2c17d4e3aa797d8e010c429cf4ca01c5 Mon Sep 17 00:00:00 2001 From: Neenu1995 Date: Mon, 23 Nov 2026 19:51:01 -0500 Subject: [PATCH 6/7] use string comparison for owner --- .../jdbc/PerConnectionFileHandler.java | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java index 184ae54dc08d..7145870c6cdb 100644 --- a/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java +++ b/java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/PerConnectionFileHandler.java @@ -32,6 +32,8 @@ import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermission; import java.nio.file.attribute.PosixFilePermissions; +import java.nio.file.attribute.UserPrincipal; +import java.nio.file.attribute.UserPrincipalNotFoundException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.EnumSet; @@ -93,10 +95,21 @@ private static boolean isPosixFileSystem(Path path) { static void verifyPosixOwner(Path file) throws IOException { if (isPosixFileSystem(file)) { String currentUser = System.getProperty("user.name"); - String ownerName = Files.getOwner(file, LinkOption.NOFOLLOW_LINKS).getName(); - if (currentUser == null || currentUser.isEmpty() || !currentUser.equals(ownerName)) { + UserPrincipal fileOwner = Files.getOwner(file, LinkOption.NOFOLLOW_LINKS); + UserPrincipal currentOwner = null; + if (currentUser != null && !currentUser.isEmpty()) { + try { + currentOwner = + file.getFileSystem() + .getUserPrincipalLookupService() + .lookupPrincipalByName(currentUser); + } catch (UserPrincipalNotFoundException ignored) { + // Leave currentOwner null so FileAlreadyExistsException is thrown below. + } + } + if (!fileOwner.equals(currentOwner)) { throw new FileAlreadyExistsException( - file.toString(), null, "Log file owner could not be verified: " + ownerName); + file.toString(), null, "Log file owner could not be verified: " + fileOwner.getName()); } } } @@ -208,6 +221,9 @@ private static SeekableByteChannel configureNewChannel( } private static void closeQuietlyWithSuppressed(SeekableByteChannel channel, Throwable primary) { + if (channel == null) { + return; + } try { channel.close(); } catch (IOException closeEx) { From 8e67b02b4f29acd73a2151826986d0b06e2ad485 Mon Sep 17 00:00:00 2001 From: Neenu Shaji Date: Tue, 24 Nov 2026 10:11:53 -0500 Subject: [PATCH 7/7] Remove README.MD update --- java-bigquery-jdbc/README.MD | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/java-bigquery-jdbc/README.MD b/java-bigquery-jdbc/README.MD index 0e7093c3ee91..34bbb7b38c54 100644 --- a/java-bigquery-jdbc/README.MD +++ b/java-bigquery-jdbc/README.MD @@ -102,16 +102,6 @@ To configure these properties, you can use the following keys: * Environment Variable: `BIGQUERY_JDBC_TELEMETRY_ENABLED=false` * System Property: `-DBIGQUERY_JDBC_TELEMETRY_ENABLED=false` -## Diagnostic logging configuration - -Diagnostic logging can be configured per connection via JDBC URL or connection properties (`LogLevel`, `LogPath`), globally via environment variables, or tuned at the JVM level via Java system properties: - -* Environment Variables: - * `BIGQUERY_JDBC_LOG_LEVEL`: Default log verbosity level (`0` = `OFF` to `7` = `FINEST`, or `8` = `ALL`) when `LogLevel` is not specified on the connection. - * `BIGQUERY_JDBC_LOG_PATH`: Default directory path for driver log files when `LogPath` is not specified on the connection. -* Java System Properties: - * `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=`: Maximum size in bytes of an active driver `.log` file before rotating onto a `.1.log` backup file (default: `1073741824`, or 1 GiB). - ## Developer Guide ### Prerequisites