Skip to content

Commit e137414

Browse files
committed
fix(bigquery-jdbc): gate log writer lifecycle, mask URL secrets, and add open-retry backoff
1 parent 3026a0d commit e137414

15 files changed

Lines changed: 1662 additions & 224 deletions

‎java-bigquery-jdbc/docs/USER_GUIDE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -704,6 +704,7 @@ Log files are generated inside the specified `LogPath` directory with per-connec
704704
- **Per-connection log file**: `BQ-JDBC-<yyyyMMddHHmmss>-<shortId>.log` (with a numeric collision suffix if needed).
705705
- **File permissions**: Created directories and log files enforce owner-only permissions (`0700` on directories, `0600` on files) on POSIX filesystems and reject symbolic links.
706706
- **Size cap & rotation**: Each active log file is capped at `1 GiB` by default (configurable via `-Dcom.google.cloud.bigquery.jdbc.maxLogFileBytes=<bytes>`) and rotates onto a single `.1.log` backup file (falling back to in-place truncation if rotation is blocked).
707+
- **URL `LogPath` restriction**: Set `-Dcom.google.cloud.bigquery.jdbc.allowUrlLogPath=false` to ignore `LogPath` values supplied via JDBC URLs or connection `Properties` and restrict file logging to `BIGQUERY_JDBC_LOG_PATH`.
707708
708709
**Standard Log Record Format**:
709710
```text

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryConnection.java‎

Lines changed: 64 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,6 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
155155
BigQueryJdbcUrlUtility.HTTP_CONNECT_TIMEOUT_PROPERTY_NAME,
156156
BigQueryJdbcUrlUtility.HTTP_READ_TIMEOUT_PROPERTY_NAME,
157157
BigQueryJdbcUrlUtility.BYOID_AUDIENCE_URI_PROPERTY_NAME,
158-
BigQueryJdbcUrlUtility.BYOID_CREDENTIAL_SOURCE_PROPERTY_NAME,
159158
BigQueryJdbcUrlUtility.BYOID_POOL_USER_PROJECT_PROPERTY_NAME,
160159
BigQueryJdbcUrlUtility.BYOID_SA_IMPERSONATION_URI_PROPERTY_NAME,
161160
BigQueryJdbcUrlUtility.BYOID_SUBJECT_TOKEN_TYPE_PROPERTY_NAME,
@@ -264,6 +263,35 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
264263
private final AtomicReference<SessionState> sessionState =
265264
new AtomicReference<>(new SessionState(null, Collections.emptyList(), false));
266265

266+
static String sanitizeForLog(String value) {
267+
if (value == null) {
268+
return null;
269+
}
270+
StringBuilder sb = null;
271+
for (int i = 0; i < value.length(); i++) {
272+
char c = value.charAt(i);
273+
if (c < 0x20 || c == 0x7F) {
274+
if (sb == null) {
275+
sb = new StringBuilder(value.length()).append(value, 0, i);
276+
}
277+
sb.append('?');
278+
} else if (sb != null) {
279+
sb.append(c);
280+
}
281+
}
282+
return sb == null ? value : sb.toString();
283+
}
284+
285+
static String maskPropertyValue(String key, Object value) {
286+
if (value == null) {
287+
return null;
288+
}
289+
if (key == null || !SAFE_TO_LOG_PROPERTIES.contains(key)) {
290+
return "*****";
291+
}
292+
return sanitizeForLog(String.valueOf(value));
293+
}
294+
267295
BigQueryConnection(String url) throws SQLException {
268296
this(url, DataSource.fromUrl(url));
269297
}
@@ -279,32 +307,37 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
279307
if (rawLogLevel == null) {
280308
rawLogLevel = System.getenv(BigQueryJdbcUrlUtility.LOG_LEVEL_ENV_VAR);
281309
}
282-
String connLogPath = ds.getLogPath();
283-
if (connLogPath == null) {
284-
connLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
285-
}
286-
if (connLogPath == null && rawLogLevel != null && !ds.getEnableGcpLogExporter()) {
287-
connLogPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH;
288-
}
310+
String connLogPath =
311+
BigQueryJdbcUrlUtility.resolveEffectiveLogPath(
312+
ds.getLogPath(),
313+
System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR),
314+
rawLogLevel != null && !ds.getEnableGcpLogExporter());
289315
BigQueryJdbcRootLogger.registerConnection(this.connectionId, rawLogLevel, connLogPath);
290316
boolean initialized = false;
317+
ExecutorService createdQueryExecutor = null;
318+
ExecutorService createdMetadataExecutor = null;
291319
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(this.connectionId)) {
292320
this.connectionUrl = url;
293321
if (LOG.isLoggable(Level.CONFIG)) {
294322
Properties connectionProps = ds.createProperties();
295323
Properties maskedProps = new Properties();
296324
for (String name : connectionProps.stringPropertyNames()) {
297-
String value = connectionProps.getProperty(name);
298-
if (!SAFE_TO_LOG_PROPERTIES.contains(name)) {
299-
value = "*****";
300-
}
301-
maskedProps.setProperty(name, value);
325+
maskedProps.setProperty(
326+
sanitizeForLog(name), maskPropertyValue(name, connectionProps.getProperty(name)));
302327
}
303328
LOG.config("Connection properties: %s", maskedProps.toString());
304329
}
305330
this.openStatements = ConcurrentHashMap.newKeySet();
306331
this.autoCommit = true;
307332
this.sqlWarnings = new ArrayList<>();
333+
if (ds.getLogPath() != null && !BigQueryJdbcUrlUtility.isUrlLogPathAllowed()) {
334+
this.sqlWarnings.add(
335+
new SQLWarning(
336+
String.format(
337+
"Ignoring URL/Properties %s because system property %s is false.",
338+
BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME,
339+
BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY)));
340+
}
308341
this.transactionStarted = false;
309342
this.isClosed = false;
310343

@@ -429,15 +462,27 @@ public class BigQueryConnection extends BigQueryNoOpsConnection {
429462
this.bigQuery = getBigQueryConnection();
430463
// Cached pool executes queries immediately without queueing and reclaims all idle threads
431464
// when inactive, minimizing resources.
432-
this.queryExecutor =
465+
createdQueryExecutor =
433466
BigQueryJdbcMdc.newCachedThreadPool(String.format("BQ-Query-%s", connectionId));
434-
this.metadataExecutor =
467+
this.queryExecutor = createdQueryExecutor;
468+
createdMetadataExecutor =
435469
BigQueryJdbcMdc.newFixedThreadPool(
436470
String.format("BQ-Metadata-%s", connectionId), this.metadataFetchThreadCount);
471+
this.metadataExecutor = createdMetadataExecutor;
472+
BigQueryJdbcRootLogger.trackConnectionLifecycle(this, this.connectionId);
437473
initialized = true;
438474
} finally {
439475
if (!initialized) {
476+
if (createdQueryExecutor != null) {
477+
createdQueryExecutor.shutdownNow();
478+
}
479+
if (createdMetadataExecutor != null) {
480+
createdMetadataExecutor.shutdownNow();
481+
}
440482
BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId);
483+
BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId);
484+
BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
485+
this.openTelemetry = null;
441486
}
442487
}
443488
}
@@ -1237,7 +1282,9 @@ private void closeImpl() throws SQLException {
12371282
} catch (ConcurrentModificationException ex) {
12381283
throw new BigQueryJdbcException("Concurrent modification during close", ex);
12391284
} finally {
1240-
BigQueryJdbcMdc.clear();
1285+
if (this.connectionId.equals(BigQueryJdbcMdc.getConnectionId())) {
1286+
BigQueryJdbcMdc.clear();
1287+
}
12411288
BigQueryJdbcRootLogger.closeConnectionHandler(this.connectionId);
12421289
BigQueryJdbcOpenTelemetry.unregisterConnection(this.connectionId);
12431290
BigQueryJdbcOpenTelemetry.releaseSdk(this.openTelemetry);
@@ -1354,6 +1401,7 @@ private OpenTelemetry getOpenTelemetryInstance() {
13541401
effectiveProjectId,
13551402
this.credentials,
13561403
this.proxyProperties);
1404+
this.openTelemetry = openTelemetry;
13571405

13581406
boolean hasExternalOtel = this.customOpenTelemetry != null || this.useGlobalOpenTelemetry;
13591407
Logging localLoggingClient = null;

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryDriver.java‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ public Connection connect(String url, Properties info) throws SQLException {
150150

151151
Level logLevel;
152152
String logPath;
153+
boolean ignoredUrlLogPath;
153154
try {
154155
// LogLevel
155156
String logLevelStr =
@@ -161,14 +162,11 @@ public Connection connect(String url, Properties info) throws SQLException {
161162
logLevel = BigQueryJdbcUrlUtility.parseLogLevel(logLevelStr);
162163

163164
// LogPath
164-
logPath =
165+
String urlLogPath =
165166
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
166167
connectionUri, BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME);
167-
if (logPath == null) {
168-
logPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
169-
}
168+
String envLogPath = System.getenv(BigQueryJdbcUrlUtility.LOG_PATH_ENV_VAR);
170169

171-
// Fallback to default path only if not specified and not in Cloud-Only mode
172170
String enableGcpLogExporterStr =
173171
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
174172
connectionUri, BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
@@ -179,9 +177,10 @@ public Connection connect(String url, Properties info) throws SQLException {
179177
enableGcpLogExporterStr,
180178
BigQueryJdbcUrlUtility.ENABLE_GCP_LOG_EXPORTER_PROPERTY_NAME);
181179
}
182-
if (logPath == null && !enableGcpLogExporter) {
183-
logPath = BigQueryJdbcUrlUtility.DEFAULT_LOG_PATH;
184-
}
180+
ignoredUrlLogPath = !BigQueryJdbcUrlUtility.isUrlLogPathAllowed() && urlLogPath != null;
181+
logPath =
182+
BigQueryJdbcUrlUtility.resolveEffectiveLogPath(
183+
urlLogPath, envLogPath, !enableGcpLogExporter);
185184

186185
BigQueryJdbcRootLogger.setLevel(logLevel, logPath);
187186
} catch (RuntimeException e) {
@@ -193,6 +192,12 @@ public Connection connect(String url, Properties info) throws SQLException {
193192
BigQueryConnection connection;
194193
try (BigQueryJdbcMdc.MdcCloseable preConnect =
195194
BigQueryJdbcRootLogger.openPreConnectScope(logLevel, logPath)) {
195+
if (ignoredUrlLogPath) {
196+
LOG.warning(
197+
"Ignoring URL/Properties %s because system property %s is false.",
198+
BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME,
199+
BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY);
200+
}
196201
DataSource ds;
197202
try {
198203
ds = DataSource.fromUrl(connectionUri);

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcContextProxy.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,13 @@ class BigQueryJdbcContextProxy implements InvocationHandler {
3535

3636
private final Object target;
3737
private final String connectionId;
38+
private final ConnectionLogContext connectionContext;
3839
private final Class<?> interfaceType;
3940

4041
private BigQueryJdbcContextProxy(Object target, String connectionId, Class<?> interfaceType) {
4142
this.target = target;
4243
this.connectionId = connectionId;
44+
this.connectionContext = BigQueryJdbcRootLogger.resolveContext(connectionId);
4345
this.interfaceType = interfaceType;
4446
}
4547

@@ -132,7 +134,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
132134
}
133135

134136
// Wrap execution in the context of the active connection for all non-bypassed methods
135-
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
137+
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.withContext(connectionContext)) {
136138
boolean isFinerLoggable = LOG.isLoggable(Level.FINER);
137139
String targetClassName = null;
138140
if (isFinerLoggable) {
@@ -173,7 +175,7 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
173175

174176
// Unified Context Logger: Captures and logs every exception exactly once with the Connection
175177
// context
176-
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.registerInstance(connectionId)) {
178+
try (BigQueryJdbcMdc.MdcCloseable mdc = BigQueryJdbcMdc.withContext(connectionContext)) {
177179
String errMsg = cause.getMessage() != null ? cause.getMessage() : cause.toString();
178180
LOG.severe("Exception occurred during " + methodName + ": " + errMsg, cause);
179181
}

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcCustomLogger.java‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,13 @@
1717
package com.google.cloud.bigquery.jdbc;
1818

1919
import java.util.function.Supplier;
20+
import java.util.logging.Handler;
2021
import java.util.logging.Level;
2122
import java.util.logging.LogRecord;
2223
import java.util.logging.Logger;
2324

2425
public class BigQueryJdbcCustomLogger extends Logger {
26+
private volatile boolean hasOwnHandlers;
2527

2628
protected BigQueryJdbcCustomLogger(String name, String resourceBundleName) {
2729
super(name, resourceBundleName);
@@ -32,19 +34,40 @@ public BigQueryJdbcCustomLogger(String name) {
3234
this(name, null);
3335
}
3436

37+
@Override
38+
public synchronized void addHandler(Handler handler) throws SecurityException {
39+
super.addHandler(handler);
40+
this.hasOwnHandlers = getHandlers().length > 0;
41+
}
42+
43+
@Override
44+
public synchronized void removeHandler(Handler handler) throws SecurityException {
45+
super.removeHandler(handler);
46+
this.hasOwnHandlers = getHandlers().length > 0;
47+
}
48+
3549
@Override
3650
public boolean isLoggable(Level level) {
37-
if (level == null || level == Level.OFF) {
51+
if (!isSuperLoggable(level)) {
3852
return false;
3953
}
40-
if (this.getLevel() != null) {
41-
return super.isLoggable(level);
54+
return isLoggableAfterSuper(level, BigQueryJdbcMdc.getConnectionContext());
55+
}
56+
57+
boolean isSuperLoggable(Level level) {
58+
return level != null && super.isLoggable(level);
59+
}
60+
61+
boolean isLoggableAfterSuper(Level level, ConnectionLogContext context) {
62+
if (this.getLevel() != null
63+
|| this.hasOwnHandlers
64+
|| BigQueryJdbcRootLogger.hasExternalHandler()) {
65+
return true;
4266
}
43-
ConnectionLogContext context = BigQueryJdbcMdc.getConnectionContext();
4467
if (context != null && context.hasExplicitLevel()) {
4568
return context.isLoggable(level);
4669
}
47-
return super.isLoggable(level);
70+
return true;
4871
}
4972

5073
private void logWithCaller(Level level, Supplier<String> msgSupplier) {

‎java-bigquery-jdbc/src/main/java/com/google/cloud/bigquery/jdbc/BigQueryJdbcResultSetLogger.java‎

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,7 @@ public static BigQueryJdbcResultSetLogger getLogger(Class<?> clazz, String conne
7474
if (connectionId == null || connectionId.isEmpty()) {
7575
return getLogger(clazz, (ConnectionLogContext) null);
7676
}
77-
ConnectionLogContext context = BigQueryJdbcRootLogger.getConnectionContext(connectionId);
78-
if (context == null) {
79-
context = ConnectionLogContext.unregistered(connectionId);
80-
}
81-
return getLogger(clazz, context);
77+
return getLogger(clazz, BigQueryJdbcRootLogger.resolveContext(connectionId));
8278
}
8379

8480
static BigQueryJdbcResultSetLogger getLogger(
@@ -103,16 +99,12 @@ BigQueryJdbcCustomLogger delegate() {
10399
}
104100

105101
public boolean isLoggable(Level level) {
106-
if (level == null || level == Level.OFF) {
102+
if (!delegate.isSuperLoggable(level)) {
107103
return false;
108104
}
109-
if (delegate.getLevel() != null) {
110-
return delegate.isLoggable(level);
111-
}
112-
if (connectionContext != null && connectionContext.hasExplicitLevel()) {
113-
return connectionContext.isLoggable(level);
114-
}
115-
return delegate.isLoggable(level);
105+
ConnectionLogContext ctx =
106+
connectionContext != null ? connectionContext : BigQueryJdbcMdc.getConnectionContext();
107+
return delegate.isLoggableAfterSuper(level, ctx);
116108
}
117109

118110
public BigQueryJdbcResultSetLogger getArrowStructLogger() {
@@ -163,10 +155,13 @@ public void log(LogRecord record) {
163155
System.arraycopy(existingParams, 0, newParams, 1, existingParams.length);
164156
record.setParameters(newParams);
165157
}
166-
try (BigQueryJdbcMdc.MdcCloseable ignored = BigQueryJdbcMdc.withContext(connectionContext)) {
167-
delegate.log(record);
158+
if (BigQueryJdbcMdc.getConnectionContext() != connectionContext) {
159+
try (BigQueryJdbcMdc.MdcCloseable ignored =
160+
BigQueryJdbcMdc.withContext(connectionContext)) {
161+
delegate.log(record);
162+
}
163+
return;
168164
}
169-
return;
170165
}
171166
delegate.log(record);
172167
}
@@ -185,7 +180,10 @@ private void logTrace(Level level, String methodName, Supplier<String> msgSuppli
185180
if (!isLoggable(level)) {
186181
return;
187182
}
188-
logTrace(level, methodName, msgSupplier.get());
183+
LogRecord record = new LogRecord(level, msgSupplier.get());
184+
record.setSourceClassName(targetClassName);
185+
record.setSourceMethodName(methodName);
186+
log(record);
189187
}
190188

191189
/** Cold path: builds a record whose caller is inferred lazily by the formatter. */
@@ -258,7 +256,7 @@ public void fine(Supplier<String> msgSupplier) {
258256
}
259257

260258
public void warning(String format, Object... args) {
261-
if (!delegate.isLoggable(Level.WARNING)) {
259+
if (!isLoggable(Level.WARNING)) {
262260
return;
263261
}
264262
String message = (args == null || args.length == 0) ? format : String.format(format, args);

0 commit comments

Comments
 (0)