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 @@ -1585,9 +1585,14 @@ private OpenTelemetry getOpenTelemetryInstance() {
? this.gcpTelemetryCredentials
: resolveEffectiveCredentials());

boolean isApplicationDefaultCredentials =
BigQueryJdbcOAuthUtility.AuthType.APPLICATION_DEFAULT_CREDENTIALS
.name()
.equals(this.authProperties.get(BigQueryJdbcUrlUtility.OAUTH_TYPE_PROPERTY_NAME));
BigQueryJdbcOpenTelemetry.TelemetryTransportConfig telemetryTransportConfig =
BigQueryJdbcOpenTelemetry.TelemetryTransportConfig.builder()
.setUniverseDomain(this.universeDomain)
.setApplicationDefaultCredentials(isApplicationDefaultCredentials)
.setOverrideProperties(this.overrideProperties)
.setProxyProperties(this.proxyProperties)
.setSslTrustStore(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import com.google.cloud.bigquery.exception.BigQueryJdbcRuntimeException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.hash.Hashing;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.baggage.Baggage;
Expand All @@ -42,21 +41,23 @@
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder;
import io.opentelemetry.sdk.common.CompletableResultCode;
import io.opentelemetry.sdk.common.export.ProxyOptions;
import io.opentelemetry.sdk.resources.Resource;
import io.opentelemetry.sdk.trace.export.SpanExporter;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
Expand Down Expand Up @@ -103,11 +104,13 @@ class BigQueryJdbcOpenTelemetry {
private static final String DEFAULT_ATTRIBUTE_LENGTH_LIMIT = "32768";
private static final String CLOUD_PLATFORM_SCOPE =
"https://www.googleapis.com/auth/cloud-platform";
private static final long SHUTDOWN_TIMEOUT_SECONDS = 10L;
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcOpenTelemetry.class.getName());

static final class TelemetryTransportConfig {
final String universeDomain;
final boolean applicationDefaultCredentials;
final Map<String, String> overrideProperties;
final Map<String, String> proxyProperties;
final String sslTrustStorePath;
Expand All @@ -119,6 +122,7 @@ static final class TelemetryTransportConfig {

private TelemetryTransportConfig(Builder builder) {
this.universeDomain = builder.universeDomain;
this.applicationDefaultCredentials = builder.applicationDefaultCredentials;
this.overrideProperties =
builder.overrideProperties != null ? builder.overrideProperties : Collections.emptyMap();
this.proxyProperties =
Expand All @@ -137,6 +141,7 @@ static Builder builder() {

static final class Builder {
private String universeDomain;
private boolean applicationDefaultCredentials;
private Map<String, String> overrideProperties;
private Map<String, String> proxyProperties;
private String sslTrustStorePath;
Expand All @@ -151,6 +156,11 @@ Builder setUniverseDomain(String universeDomain) {
return this;
}

Builder setApplicationDefaultCredentials(boolean applicationDefaultCredentials) {
this.applicationDefaultCredentials = applicationDefaultCredentials;
return this;
}

Builder setOverrideProperties(Map<String, String> overrideProperties) {
this.overrideProperties = overrideProperties;
return this;
Expand Down Expand Up @@ -185,49 +195,6 @@ TelemetryTransportConfig build() {
}
}

private static final class SdkCacheKey {
private final String projectId;
private final String credentialsHashOrPath;
private final boolean enableTrace;
private final String proxyHost;
private final String proxyPort;

SdkCacheKey(
String projectId,
String credentialsHashOrPath,
boolean enableTrace,
Map<String, String> proxyProperties) {
this.projectId = projectId;
this.credentialsHashOrPath = credentialsHashOrPath;
this.enableTrace = enableTrace;
this.proxyHost =
proxyProperties != null
? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME)
: null;
this.proxyPort =
proxyProperties != null
? proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME)
: null;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SdkCacheKey that = (SdkCacheKey) o;
return enableTrace == that.enableTrace
&& Objects.equals(projectId, that.projectId)
&& Objects.equals(credentialsHashOrPath, that.credentialsHashOrPath)
&& Objects.equals(proxyHost, that.proxyHost)
&& Objects.equals(proxyPort, that.proxyPort);
}

@Override
public int hashCode() {
return Objects.hash(projectId, credentialsHashOrPath, enableTrace, proxyHost, proxyPort);
}
}

private static final class CachedSdk {
final OpenTelemetrySdk sdk;
final AtomicInteger refCount = new AtomicInteger(1);
Expand All @@ -237,7 +204,7 @@ private static final class CachedSdk {
}
}

private static final ConcurrentHashMap<SdkCacheKey, CachedSdk> sdkCache =
private static final ConcurrentHashMap<TelemetrySdkCacheKey, CachedSdk> sdkCache =
new ConcurrentHashMap<>();

static class TelemetryConfig {
Expand All @@ -256,12 +223,54 @@ static class TelemetryConfig {
private static final ConcurrentHashMap<String, TelemetryConfig> connectionConfigs =
new ConcurrentHashMap<>();

private static final AtomicBoolean shutdownHookRegistered = new AtomicBoolean(false);

private BigQueryJdbcOpenTelemetry() {}

static {
ensureGlobalHandlerAttached();
}

private static void ensureShutdownHookRegistered() {
if (!shutdownHookRegistered.compareAndSet(false, true)) {
return;
}
try {
Runtime.getRuntime()
.addShutdownHook(
new Thread(
BigQueryJdbcOpenTelemetry::shutdownAllSdks, "bigquery-jdbc-otel-shutdown"));
} catch (IllegalStateException | SecurityException e) {
// JVM is already shutting down or runtime policy prohibits shutdown hooks.
LOG.fine("Unable to register OpenTelemetry shutdown hook: %s", e.getMessage());
}
}

@VisibleForTesting
static void shutdownAllSdks() {
List<CompletableResultCode> shutdownResults = new ArrayList<>();
for (TelemetrySdkCacheKey cacheKey : new ArrayList<>(sdkCache.keySet())) {
CachedSdk removed = sdkCache.remove(cacheKey);
if (removed != null) {
shutdownResults.add(removed.sdk.shutdown());
}
}
if (shutdownResults.isEmpty()) {
return;
}
CompletableResultCode.ofAll(shutdownResults).join(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS);
}

@VisibleForTesting
static int getSdkCacheSizeForTest() {
return sdkCache.size();
}

@VisibleForTesting
static Set<TelemetrySdkCacheKey> getSdkCacheKeysForTest() {
return Collections.unmodifiableSet(sdkCache.keySet());
}

public static synchronized void ensureGlobalHandlerAttached() {
Logger logger = Logger.getLogger(BIGQUERY_NAMESPACE);
boolean present = false;
Expand Down Expand Up @@ -302,7 +311,7 @@ public static void releaseSdk(OpenTelemetry openTelemetry) {
}

AtomicBoolean shouldClose = new AtomicBoolean(false);
for (Map.Entry<SdkCacheKey, CachedSdk> entry : sdkCache.entrySet()) {
for (Map.Entry<TelemetrySdkCacheKey, CachedSdk> entry : sdkCache.entrySet()) {
if (entry.getValue().sdk == openTelemetry) {
sdkCache.computeIfPresent(
entry.getKey(),
Expand All @@ -321,14 +330,17 @@ public static void releaseSdk(OpenTelemetry openTelemetry) {
}

if (shouldClose.get() && openTelemetry instanceof OpenTelemetrySdk) {
try {
((OpenTelemetrySdk) openTelemetry).close();
} catch (Exception e) {
// Swallow exceptions so that telemetry shutdown failures (e.g. flush timeouts)
// do not propagate and disrupt the core BigQueryConnection.close() logic.
// Throwing here could prevent the core connection from cleaning up correctly.
LOG.warning("Failed to close OpenTelemetry SDK: %s", e.getMessage());
}
closeSdkQuietly((OpenTelemetrySdk) openTelemetry);
}
}

private static void closeSdkQuietly(OpenTelemetrySdk sdk) {
try {
sdk.close();
} catch (Exception e) {
// Swallow exceptions so that telemetry shutdown failures (e.g. flush timeouts)
// do not propagate and disrupt the core BigQueryConnection.close() logic.
LOG.warning("Failed to close OpenTelemetry SDK: %s", e.getMessage());
}
}

Expand Down Expand Up @@ -467,17 +479,6 @@ private static Map<String, String> getAuthHeaders(Credentials credentials, Strin
}
}

private static String getCredentialsIdentifier(String credentials) {
if (credentials == null) {
return "";
}
byte[] credsBytes = credentials.getBytes(StandardCharsets.UTF_8);
if (BigQueryJdbcOAuthUtility.isJson(credsBytes)) {
return Hashing.sha256().hashString(credentials, StandardCharsets.UTF_8).toString();
}
return credentials;
}

/**
* Initializes or returns the OpenTelemetry instance based on hybrid logic. Prefer
* customOpenTelemetry if provided; fallback to an auto-configured GCP exporter if requested.
Expand Down Expand Up @@ -522,12 +523,15 @@ static OpenTelemetry getOpenTelemetry(
: null;
String targetUniverseDomain = resolveTargetUniverseDomain(validatedUniverse);

SdkCacheKey key =
new SdkCacheKey(
TelemetrySdkCacheKey key =
TelemetrySdkCacheKey.create(
gcpTelemetryProjectId,
getCredentialsIdentifier(gcpTelemetryCredentials),
enableGcpTraceExporter,
transportConfig.proxyProperties);
targetUniverseDomain,
gcpTelemetryCredentials,
fallbackCredentials,
transportConfig);

CachedSdk fastCheck = sdkCache.get(key);
if (fastCheck != null) {
CachedSdk result =
Expand Down Expand Up @@ -595,6 +599,7 @@ static OpenTelemetry getOpenTelemetry(

AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder =
AutoConfiguredOpenTelemetrySdk.builder()
.disableShutdownHook()
.addPropertiesSupplier(() -> props)
.addResourceCustomizer(
(resource, configProperties) -> {
Expand Down Expand Up @@ -624,18 +629,23 @@ static OpenTelemetry getOpenTelemetry(
}

OpenTelemetrySdk newSdk = sdkBuilder.build().getOpenTelemetrySdk();
ensureShutdownHookRegistered();

return sdkCache.compute(
CachedSdk computed =
sdkCache.compute(
key,
(k, cachedSdk) -> {
if (cachedSdk != null) {
cachedSdk.refCount.incrementAndGet();
newSdk.close(); // Clean up the duplicate we just made
return cachedSdk;
(k, existingSdk) -> {
if (existingSdk != null) {
existingSdk.refCount.incrementAndGet();
return existingSdk;
}
return new CachedSdk(newSdk);
})
.sdk;
});

if (computed.sdk != newSdk) {
closeSdkQuietly(newSdk);
}
return computed.sdk;
}

@VisibleForTesting
Expand Down Expand Up @@ -680,6 +690,13 @@ static SpanExporter customizeSpanExporter(
return spanExporter;
}

private static ProxyOptions createProxyOptions(Map<String, String> proxyProperties) {
String host = proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME);
int port =
Integer.parseInt(proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME));
return ProxyOptions.create(InetSocketAddress.createUnresolved(host, port));
}

/** Gets a Tracer for the JDBC driver instrumentation scope. */
public static Tracer getTracer(OpenTelemetry openTelemetry) {
return openTelemetry.getTracer(INSTRUMENTATION_SCOPE_NAME);
Expand Down Expand Up @@ -733,11 +750,4 @@ public static <T> T withTracing(
span.end();
}
}

private static ProxyOptions createProxyOptions(Map<String, String> proxyProperties) {
String host = proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_HOST_PROPERTY_NAME);
int port =
Integer.parseInt(proxyProperties.get(BigQueryJdbcUrlUtility.PROXY_PORT_PROPERTY_NAME));
return ProxyOptions.create(InetSocketAddress.createUnresolved(host, port));
}
}
Loading
Loading