Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,7 @@ static String maskPropertyValue(String key, Object value) {
this.reqGoogleDriveScope,
httpTransportFactory,
this.connectionClassName);
BigQueryJdbcDiagnosticTelemetry.initializeOrDisable(ds, this.credentials);
this.defaultDataset = BigQueryJdbcUrlUtility.parseDefaultDataset(ds.getDefaultDataset());
this.location = ds.getLocation();
this.enableHighThroughputAPI = ds.getEnableHighThroughputAPI();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -130,25 +130,17 @@ public static BigQueryDriver getRegisteredDriver() throws IllegalStateException
public Connection connect(String url, Properties info) throws SQLException {
LOG.finest("++enter++");
AuthenticationType authType = AuthenticationType.AUTHENTICATION_TYPE_UNSPECIFIED;
String connectionUri = null;
DataSource ds = null;
try {
if (acceptsURL(url)) {
Properties connectInfo = info == null ? new Properties() : (Properties) info.clone();
Object customOpenTelemetryObj = connectInfo.remove("customOpenTelemetry");

String connectionUri =
connectionUri =
BigQueryJdbcUrlUtility.appendPropertiesToURL(
url.substring(5), this.toString(), connectInfo);

String telemetryOptOut =
BigQueryJdbcUrlUtility.parseUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME);

if (telemetryOptOut != null) {
connectInfo.setProperty(
BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME, telemetryOptOut);
}
TelemetryManager.getInstance(connectInfo);

Level logLevel;
String logPath;
boolean ignoredUrlLogPath;
Expand Down Expand Up @@ -199,7 +191,6 @@ public Connection connect(String url, Properties info) throws SQLException {
BigQueryJdbcUrlUtility.LOG_PATH_PROPERTY_NAME,
BigQueryJdbcUrlUtility.ALLOW_URL_LOG_PATH_SYSTEM_PROPERTY);
}
DataSource ds;
try {
ds = DataSource.fromUrl(connectionUri);
} catch (BigQueryJdbcRuntimeException e) {
Expand Down Expand Up @@ -240,12 +231,10 @@ public Connection connect(String url, Properties info) throws SQLException {
return null;
}
} catch (IOException e) {
TelemetryManager.recordConnectionAttempt(
Status.STATUS_ERROR, TelemetryManager.extractErrorCode(e), authType);
BigQueryJdbcDiagnosticTelemetry.recordFailedConnection(connectionUri, ds, authType, e);
throw new BigQueryJdbcException("Failed to establish connection", e);
} catch (Throwable t) {
TelemetryManager.recordConnectionAttempt(
Status.STATUS_ERROR, TelemetryManager.extractErrorCode(t), authType);
BigQueryJdbcDiagnosticTelemetry.recordFailedConnection(connectionUri, ds, authType, t);
throw t;
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
/*
* 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
*
* https://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 com.google.auth.Credentials;
import com.google.auth.oauth2.ComputeEngineCredentials;
import com.google.auth.oauth2.ImpersonatedCredentials;
import com.google.cloud.bigquery.jdbc.telemetry.v1.AuthenticationType;
import com.google.cloud.bigquery.jdbc.telemetry.v1.Status;
import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager;
import java.io.IOException;

/**
* Coordinates Clearcut diagnostic telemetry eligibility and lifecycle transitions for BigQuery JDBC
* connections.
*/
final class BigQueryJdbcDiagnosticTelemetry {

private BigQueryJdbcDiagnosticTelemetry() {}

/**
* Initializes Clearcut diagnostic telemetry for an eligible connection, or permanently disables
* it if the connection opts out or targets a non-default universe or endpoint override.
*/
static void initializeOrDisable(DataSource ds, Credentials credentials) {
if (TelemetryManager.isGloballyDisabled()) {
return;
}
TelemetryManager.runSafely(
() -> {
if (isSuppressed(ds, credentials)) {
TelemetryManager.disableGlobally("non-default universe or endpoint override");
return;
}
TelemetryManager.initializeForConnection(ds.getEnableDiagnosticTelemetry());
});
}

/**
* Enforces suppression and opt-out rules on failed {@link BigQueryDriver#connect} calls and
* records a failed connection attempt when diagnostic telemetry is eligible.
*/
static void recordFailedConnection(
String connectionUri, DataSource ds, AuthenticationType authType, Throwable failure) {
if (connectionUri == null || TelemetryManager.isGloballyDisabled()) {
return;
}
TelemetryManager.runSafely(
() -> {
TelemetryManager manager =
ds != null
? initializeOrDisableForFailedDataSource(ds)
: initializeOrDisableFromRawUri(connectionUri);
if (manager != null) {
TelemetryManager.recordConnectionAttempt(
Status.STATUS_ERROR, TelemetryManager.extractErrorCode(failure), authType);
}
});
}

private static TelemetryManager initializeOrDisableForFailedDataSource(DataSource ds) {
if (isSuppressed(ds, null)) {
TelemetryManager.disableGlobally("non-default universe or endpoint override");
return null;
}
return TelemetryManager.initializeForConnection(ds.getEnableDiagnosticTelemetry());
}

private static TelemetryManager initializeOrDisableFromRawUri(String connectionUri) {
if (isSuppressedFromRawUri(connectionUri)) {
TelemetryManager.disableGlobally("non-default universe or endpoint override");
return null;
}
String rawEnable;
try {
rawEnable =
BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENABLE_DIAGNOSTIC_TELEMETRY_PROPERTY_NAME);
} catch (RuntimeException e) {
TelemetryManager.disableGlobally("malformed EnableDiagnosticTelemetry value");
return null;
}
Boolean explicitEnabled = null;
if (rawEnable != null && !rawEnable.trim().isEmpty()) {
explicitEnabled = parseStrictBoolean(rawEnable);
if (explicitEnabled == null) {
TelemetryManager.disableGlobally("invalid EnableDiagnosticTelemetry value");
return null;
}
}
return TelemetryManager.initializeForConnection(explicitEnabled);
}

private static Boolean parseStrictBoolean(String rawValue) {
String trimmed = rawValue.trim();
if ("true".equalsIgnoreCase(trimmed) || "1".equals(trimmed)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase(trimmed) || "0".equals(trimmed)) {
return Boolean.FALSE;
}
return null;
}

static boolean isSuppressed(DataSource ds, Credentials credentials) {
if (isNonBlank(ds.getEndpointOverrides()) || isNonBlank(ds.getPrivateServiceConnect())) {
return true;
}
if (isNonDefaultUniverse(ds.resolveUniverseDomain())) {
return true;
}
return isNonDefaultCredentialUniverse(credentials);
}

private static boolean isSuppressedFromRawUri(String connectionUri) {
try {
String endpointOverrides =
BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.ENDPOINT_OVERRIDES_PROPERTY_NAME);
if (isNonBlank(endpointOverrides)) {
return true;
}
String privateServiceConnect =
BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.PRIVATE_SERVICE_CONNECT_PROPERTY_NAME);
if (isNonBlank(privateServiceConnect)) {
return true;
}
String rawUniverse =
BigQueryJdbcUrlUtility.parseLastUriPropertyWithoutValidation(
connectionUri, BigQueryJdbcUrlUtility.UNIVERSE_DOMAIN_OVERRIDE_PROPERTY_NAME);
String explicitUniverse = BigQueryJdbcUrlUtility.normalizeUniverseDomain(rawUniverse);
String resolvedUniverse =
explicitUniverse != null
? explicitUniverse
: BigQueryJdbcUrlUtility.getEnvUniverseDomain();
return isNonDefaultUniverse(resolvedUniverse);
} catch (RuntimeException e) {
return true;
}
}

static boolean isNonDefaultCredentialUniverse(Credentials credentials) {
if (credentials == null || isComputeEngineBacked(credentials)) {
return false;
}
try {
return isNonDefaultUniverse(credentials.getUniverseDomain());
} catch (IOException e) {
return true;
}
}

private static boolean isComputeEngineBacked(Credentials credentials) {
Credentials current = credentials;
while (current instanceof ImpersonatedCredentials) {
current = ((ImpersonatedCredentials) current).getSourceCredentials();
}
return current instanceof ComputeEngineCredentials;
}

private static boolean isNonDefaultUniverse(String universeDomain) {
if (!isNonBlank(universeDomain)) {
return false;
}
return !BigQueryJdbcUrlUtility.DEFAULT_UNIVERSE_DOMAIN_VALUE.equalsIgnoreCase(
universeDomain.trim());
}

private static boolean isNonBlank(String value) {
return value != null && !value.trim().isEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -768,9 +768,23 @@ static String parseUriProperty(String uri, String property) {
* @return The String value of the property, or null if the property is not found.
*/
static String parseUriPropertyWithoutValidation(String uri, String property) {
return parseUriPropertyWithoutValidation(uri, property, false);
}

/**
* Parses the last matching value for {@code property} from the URI without validating other
* properties, matching last-wins precedence when {@link Properties} are appended to the URL.
*/
static String parseLastUriPropertyWithoutValidation(String uri, String property) {
return parseUriPropertyWithoutValidation(uri, property, true);
}

private static String parseUriPropertyWithoutValidation(
String uri, String property, boolean lastWins) {
if (uri == null) {
return null;
}
String rawMatchedValue = null;
int start = 0;
int len = uri.length();
while (start < len) {
Expand All @@ -781,14 +795,19 @@ static String parseUriPropertyWithoutValidation(String uri, String property) {
if (eqIndex > start && eqIndex < end) {
String key = uri.substring(start, eqIndex).trim();
if (key.equalsIgnoreCase(property)) {
String value = uri.substring(eqIndex + 1, end);
return CharEscapers.decodeUriPath(value.replace("+", "%2B"));
rawMatchedValue = uri.substring(eqIndex + 1, end);
if (!lastWins) {
return CharEscapers.decodeUriPath(rawMatchedValue.replace("+", "%2B"));
}
}
}

start = end + 1;
}
return null;
if (rawMatchedValue == null) {
return null;
}
return CharEscapers.decodeUriPath(rawMatchedValue.replace("+", "%2B"));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,22 +166,39 @@ Builder setDriverEnvironment(DriverEnvironment driverEnvironment) {
return this;
}

/**
* Resolves the enabled state with precedence: JVM system property &gt; environment variable
* &gt; connection property.
*/
Builder resolveProperties(Properties connectionProperties) {
// 1. Connection Properties (lowest precedence)
if (connectionProperties != null) {
String enableStr = connectionProperties.getProperty("EnableDiagnosticTelemetry");
this.enabled = TelemetryPropertyUtility.convertStringToBoolean(enableStr, this.enabled);
}
return applyGlobalOverrides();
}

/**
* Resolves the enabled state with precedence: JVM system property &gt; environment variable
* &gt; explicit connection setting.
*/
Builder resolveEnabled(Boolean explicitEnabled) {
if (explicitEnabled != null) {
this.enabled = explicitEnabled;
}
return applyGlobalOverrides();
}

// 2. Environment Variables (overrides connection properties)
private Builder applyGlobalOverrides() {
// Environment variable overrides connection-level settings.
try {
String envEnabled = System.getenv("BIGQUERY_JDBC_TELEMETRY_ENABLED");
this.enabled = TelemetryPropertyUtility.convertStringToBoolean(envEnabled, enabled);
} catch (SecurityException e) {
// Ignore and proceed
}

// 3. JVM System Properties (highest precedence)
// JVM system property takes highest precedence over both connection and environment settings.
try {
String sysEnabled = System.getProperty("BIGQUERY_JDBC_TELEMETRY_ENABLED");
this.enabled = TelemetryPropertyUtility.convertStringToBoolean(sysEnabled, enabled);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.google.cloud.bigquery.jdbc.telemetry.v1;

import com.google.api.core.InternalApi;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
Expand Down Expand Up @@ -60,9 +61,26 @@ public static TelemetryManager getInstance(Properties properties) {
if (globallyDisabled) {
return null;
}

TelemetryConfiguration preliminaryConfig =
TelemetryConfiguration.builder().resolveProperties(properties).build();
return initializeWithConfig(preliminaryConfig);
}

/**
* Initializes or returns the shared {@link TelemetryManager} instance using a typed connection
* opt-out flag, or permanently disables diagnostic telemetry for the JVM when disabled.
*/
@InternalApi
public static TelemetryManager initializeForConnection(Boolean enabledOverride) {
if (globallyDisabled) {
return null;
}
TelemetryConfiguration preliminaryConfig =
TelemetryConfiguration.builder().resolveEnabled(enabledOverride).build();
return initializeWithConfig(preliminaryConfig);
}

private static TelemetryManager initializeWithConfig(TelemetryConfiguration preliminaryConfig) {
if (!preliminaryConfig.isEnabled()) {
disableGlobally("opt-out configuration");
return null;
Expand Down Expand Up @@ -103,7 +121,18 @@ public static TelemetryManager getInstance(Properties properties) {
return active;
}

static void disableGlobally(String reason) {
/** Returns {@code true} if diagnostic telemetry has been permanently disabled for this JVM. */
@InternalApi
public static boolean isGloballyDisabled() {
return globallyDisabled;
}

/**
* Permanently disables diagnostic telemetry for this JVM and closes any active instance without
* flushing buffered metrics.
*/
@InternalApi
public static void disableGlobally(String reason) {
TelemetryManager localRef;
boolean newlyDisabled;
synchronized (TelemetryManager.class) {
Expand Down
Loading
Loading