From 7d98edd8e805939308b58b278c639d07a45b6683 Mon Sep 17 00:00:00 2001 From: Keshav Dandeva Date: Tue, 1 Dec 2026 23:19:30 +0000 Subject: [PATCH] test(bigquery-jdbc): align ITOpenTelemetryTest with per-connection proxy, TrustStore, and GAPIC Logging --- .../bigquery/jdbc/it/ITOpenTelemetryTest.java | 361 +++++++++++++----- 1 file changed, 269 insertions(+), 92 deletions(-) diff --git a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java index d70de10f04ab..6e451a47c291 100644 --- a/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java +++ b/java-bigquery-jdbc/src/test/java/com/google/cloud/bigquery/jdbc/it/ITOpenTelemetryTest.java @@ -22,46 +22,70 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import com.google.api.client.http.HttpTransport; +import com.google.api.client.http.apache.v5.Apache5HttpTransport; import com.google.api.gax.core.FixedCredentialsProvider; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; -import com.google.api.gax.paging.Page; import com.google.api.gax.rpc.TransportChannelProvider; +import com.google.auth.http.HttpTransportFactory; import com.google.auth.oauth2.GoogleCredentials; +import com.google.auth.oauth2.ServiceAccountCredentials; import com.google.cloud.ServiceOptions; import com.google.cloud.bigquery.jdbc.BigQueryConnection; import com.google.cloud.bigquery.jdbc.DataSource; -import com.google.cloud.logging.LogEntry; -import com.google.cloud.logging.Logging; -import com.google.cloud.logging.LoggingOptions; +import com.google.cloud.logging.v2.LoggingClient; +import com.google.cloud.logging.v2.LoggingSettings; import com.google.cloud.trace.v1.TraceServiceClient; import com.google.cloud.trace.v1.TraceServiceSettings; import com.google.devtools.cloudtrace.v1.Trace; import com.google.devtools.cloudtrace.v1.TraceSpan; import com.google.gson.JsonObject; +import com.google.logging.v2.ListLogEntriesRequest; +import com.google.logging.v2.LogEntry; import io.grpc.HttpConnectProxiedSocketAddress; import io.grpc.ProxiedSocketAddress; import io.grpc.ProxyDetector; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContext; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.trace.IdGenerator; +import java.io.ByteArrayInputStream; import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.security.GeneralSecurityException; +import java.security.KeyStore; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; import java.util.ArrayList; -import java.util.HashMap; +import java.util.Collections; import java.util.List; -import java.util.Map; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManagerFactory; +import org.apache.hc.client5.http.auth.AuthScope; +import org.apache.hc.client5.http.auth.UsernamePasswordCredentials; +import org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy; +import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.classic.HttpClients; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner; +import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory; +import org.apache.hc.core5.http.HttpHost; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; @@ -70,35 +94,8 @@ public class ITOpenTelemetryTest extends ITBase { private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId(); private static final String CONNECTION_URL = connectionUrl; - private static final String[] PROXY_SYS_PROPS = { - "https.proxyHost", "https.proxyPort", "http.proxyHost", "http.proxyPort" - }; - private static final Map originalSystemProperties = new HashMap<>(); - - @BeforeAll - public static void setUpProxyProperties() { - DataSource ds = DataSource.fromUrl(CONNECTION_URL); - if (ds.getProxyHost() != null && ds.getProxyPort() != null) { - for (String prop : PROXY_SYS_PROPS) { - originalSystemProperties.put(prop, System.getProperty(prop)); - } - System.setProperty("https.proxyHost", ds.getProxyHost()); - System.setProperty("https.proxyPort", ds.getProxyPort()); - System.setProperty("http.proxyHost", ds.getProxyHost()); - System.setProperty("http.proxyPort", ds.getProxyPort()); - } - } - - @AfterAll - public static void tearDownProxyProperties() { - for (Map.Entry entry : originalSystemProperties.entrySet()) { - if (entry.getValue() != null) { - System.setProperty(entry.getKey(), entry.getValue()); - } else { - System.clearProperty(entry.getKey()); - } - } - } + private static final String CLOUD_PLATFORM_SCOPE = + "https://www.googleapis.com/auth/cloud-platform"; @Test public void testExecute_withOpenTelemetryGcpExporter() throws Exception { @@ -329,39 +326,158 @@ private void verifyTraceDelivery(DataSource ds) throws Exception { assertNotNull(trace, "Trace must be found"); } - private String verifyAndFetchLogs(String connectionUuid) throws Exception { - GoogleCredentials credentials = getCredentials(); - - try (Logging logging = - LoggingOptions.newBuilder() - .setProjectId(PROJECT_ID) - .setCredentials(credentials) - .build() - .getService()) { - String filter = "labels.\"jdbc.connection_id\"=\"" + connectionUuid + "\""; - - List entries = fetchLogsWithRetry(logging, filter); - assertFalse(entries.isEmpty(), "Telemetry logs should be exported to GCP"); - - String traceId = null; - String hexSpanId = null; - for (LogEntry entry : entries) { - if (entry.getTrace() != null) { - traceId = entry.getTrace(); - hexSpanId = entry.getSpanId(); - break; - } + private static final class VerificationCredentials implements AutoCloseable { + final GoogleCredentials credentials; + private final CloseableHttpClient httpClient; + + private VerificationCredentials(GoogleCredentials credentials, CloseableHttpClient httpClient) { + this.credentials = credentials; + this.httpClient = httpClient; + } + + @Override + public void close() throws IOException { + if (httpClient != null) { + httpClient.close(); } + } + } + + private VerificationCredentials getVerificationCredentials(DataSource ds) throws Exception { + JsonObject authJson = getAuthJson(); + ByteArrayInputStream stream = + new ByteArrayInputStream(authJson.toString().getBytes(StandardCharsets.UTF_8)); + CloseableHttpClient httpClient = createVerificationHttpClient(ds); + try { + GoogleCredentials credentials; + if (httpClient != null) { + final HttpTransport httpTransport = new Apache5HttpTransport(httpClient); + HttpTransportFactory transportFactory = () -> httpTransport; + credentials = ServiceAccountCredentials.fromStream(stream, transportFactory); + } else { + credentials = ServiceAccountCredentials.fromStream(stream); + } + if (credentials.createScopedRequired()) { + credentials = credentials.createScoped(Collections.singletonList(CLOUD_PLATFORM_SCOPE)); + } + return new VerificationCredentials(credentials, httpClient); + } catch (Exception e) { + if (httpClient != null) { + httpClient.close(); + } + throw e; + } + } - assertNotNull(traceId, "Log entry must contain TraceId"); - assertNotNull(hexSpanId, "Log entry must contain SpanId"); + private CloseableHttpClient createVerificationHttpClient(DataSource ds) + throws IOException, GeneralSecurityException { + String proxyHost = ds.getProxyHost() != null ? ds.getProxyHost().trim() : null; + String proxyPortStr = ds.getProxyPort(); + boolean hasProxy = proxyHost != null && !proxyHost.isEmpty() && proxyPortStr != null; + boolean hasTrustStore = + ds.getSSLTrustStorePath() != null && !ds.getSSLTrustStorePath().trim().isEmpty(); + if (!hasProxy && !hasTrustStore) { + return null; + } - // Verify Connection UUID label correlation on all entries - for (LogEntry entry : entries) { - assertEquals(connectionUuid, entry.getLabels().get("jdbc.connection_id")); + HttpClientBuilder httpClientBuilder = HttpClients.custom(); + if (hasProxy) { + int port = Integer.parseInt(proxyPortStr); + httpClientBuilder.setRoutePlanner( + new DefaultProxyRoutePlanner(new HttpHost(proxyHost, port))); + if (ds.getProxyUid() != null && ds.getProxyPwd() != null) { + BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials( + new AuthScope(proxyHost, port), + new UsernamePasswordCredentials(ds.getProxyUid(), ds.getProxyPwd().toCharArray())); + httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); + httpClientBuilder.setProxyAuthenticationStrategy(DefaultAuthenticationStrategy.INSTANCE); } + } + if (hasTrustStore) { + TrustManagerFactory tmf = + loadTrustManagerFactory( + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider()); + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, tmf.getTrustManagers(), null); + httpClientBuilder.setConnectionManager( + PoolingHttpClientConnectionManagerBuilder.create() + .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)) + .build()); + } + return httpClientBuilder.build(); + } + + private TrustManagerFactory loadTrustManagerFactory( + String sslTrustStorePath, + String sslTrustStorePassword, + String sslTrustStoreType, + String sslTrustStoreProvider) + throws IOException, GeneralSecurityException { + try (FileInputStream stream = new FileInputStream(sslTrustStorePath)) { + String type = + (sslTrustStoreType != null && !sslTrustStoreType.trim().isEmpty()) + ? sslTrustStoreType.trim() + : KeyStore.getDefaultType(); + KeyStore trustStore = + (sslTrustStoreProvider != null && !sslTrustStoreProvider.trim().isEmpty()) + ? KeyStore.getInstance(type, sslTrustStoreProvider.trim()) + : KeyStore.getInstance(type); + char[] password = sslTrustStorePassword != null ? sslTrustStorePassword.toCharArray() : null; + trustStore.load(stream, password); + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(trustStore); + return tmf; + } + } + + private String verifyAndFetchLogs(String connectionUuid) throws Exception { + DataSource ds = DataSource.fromUrl(CONNECTION_URL); + String universeDomain = ds.getUniverseDomain(); + + try (VerificationCredentials verificationCreds = getVerificationCredentials(ds)) { + LoggingSettings.Builder settingsBuilder = + LoggingSettings.newBuilder() + .setCredentialsProvider( + FixedCredentialsProvider.create(verificationCreds.credentials)); + if (universeDomain != null) { + settingsBuilder.setUniverseDomain(universeDomain); + } + TransportChannelProvider channelProvider = createVerificationTransportChannelProvider(ds); + if (channelProvider != null) { + settingsBuilder.setTransportChannelProvider(channelProvider); + } + + try (LoggingClient loggingClient = LoggingClient.create(settingsBuilder.build())) { + String filter = "labels.\"jdbc.connection_id\"=\"" + connectionUuid + "\""; + + List entries = fetchLogsWithRetry(loggingClient, filter); + assertFalse(entries.isEmpty(), "Telemetry logs should be exported to GCP"); + + String traceId = null; + String hexSpanId = null; + for (LogEntry entry : entries) { + if (!entry.getTrace().isEmpty()) { + traceId = entry.getTrace(); + hexSpanId = entry.getSpanId().isEmpty() ? null : entry.getSpanId(); + break; + } + } + + assertNotNull(traceId, "Log entry must contain TraceId"); + assertNotNull(hexSpanId, "Log entry must contain SpanId"); + + // Verify Connection UUID label correlation on all entries + for (LogEntry entry : entries) { + assertEquals(connectionUuid, entry.getLabelsMap().get("jdbc.connection_id")); + } - return traceId; + return traceId; + } } } @@ -371,41 +487,97 @@ private Trace verifyAndFetchTrace(String traceId) throws Exception { hexTraceId = traceId.substring(traceId.lastIndexOf("/traces/") + 8); } - GoogleCredentials credentials = getCredentials(); - - TraceServiceSettings.Builder settingsBuilder = - TraceServiceSettings.newBuilder() - .setCredentialsProvider(FixedCredentialsProvider.create(credentials)); - DataSource ds = DataSource.fromUrl(CONNECTION_URL); - String proxyHost = ds.getProxyHost(); - String proxyPortStr = ds.getProxyPort(); - if (proxyHost != null && proxyPortStr != null) { - settingsBuilder.setTransportChannelProvider( - createProxyTransportChannelProvider(proxyHost, Integer.parseInt(proxyPortStr))); + String universeDomain = ds.getUniverseDomain(); + + try (VerificationCredentials verificationCreds = getVerificationCredentials(ds)) { + TraceServiceSettings.Builder settingsBuilder = + TraceServiceSettings.newBuilder() + .setCredentialsProvider( + FixedCredentialsProvider.create(verificationCreds.credentials)); + if (universeDomain != null) { + settingsBuilder.setUniverseDomain(universeDomain); + } + TransportChannelProvider channelProvider = createVerificationTransportChannelProvider(ds); + if (channelProvider != null) { + settingsBuilder.setTransportChannelProvider(channelProvider); + } + + try (TraceServiceClient traceClient = TraceServiceClient.create(settingsBuilder.build())) { + Trace trace = fetchTraceWithRetry(traceClient, PROJECT_ID, hexTraceId); + assertNotNull(trace, "Trace must be found in Cloud Trace API: " + hexTraceId); + return trace; + } } + } - try (TraceServiceClient traceClient = TraceServiceClient.create(settingsBuilder.build())) { - Trace trace = fetchTraceWithRetry(traceClient, PROJECT_ID, hexTraceId); - assertNotNull(trace, "Trace must be found in Cloud Trace API: " + hexTraceId); - return trace; + private TransportChannelProvider createVerificationTransportChannelProvider(DataSource ds) { + String proxyHost = ds.getProxyHost() != null ? ds.getProxyHost().trim() : null; + String proxyPortStr = ds.getProxyPort(); + boolean hasProxy = proxyHost != null && !proxyHost.isEmpty() && proxyPortStr != null; + boolean hasTrustStore = + ds.getSSLTrustStorePath() != null && !ds.getSSLTrustStorePath().trim().isEmpty(); + if (!hasProxy && !hasTrustStore) { + return null; } + return createTransportChannelProvider( + hasProxy ? proxyHost : null, + hasProxy ? Integer.valueOf(proxyPortStr) : null, + ds.getProxyUid(), + ds.getProxyPwd(), + ds.getSSLTrustStorePath(), + ds.getSSLTrustStorePassword(), + ds.getSSLTrustStoreType(), + ds.getSSLTrustStoreProvider()); } - private TransportChannelProvider createProxyTransportChannelProvider(String host, int port) { + private TransportChannelProvider createTransportChannelProvider( + String host, + Integer port, + String proxyUid, + String proxyPwd, + String sslTrustStorePath, + String sslTrustStorePassword, + String sslTrustStoreType, + String sslTrustStoreProvider) { return InstantiatingGrpcChannelProvider.newBuilder() .setChannelConfigurator( - builder -> + builder -> { + if (host != null && port != null) { builder.proxyDetector( new ProxyDetector() { @Override public ProxiedSocketAddress proxyFor(SocketAddress socketAddress) { - return HttpConnectProxiedSocketAddress.newBuilder() - .setProxyAddress(new InetSocketAddress(host, port)) - .setTargetAddress((InetSocketAddress) socketAddress) - .build(); + HttpConnectProxiedSocketAddress.Builder proxyBuilder = + HttpConnectProxiedSocketAddress.newBuilder() + .setProxyAddress(new InetSocketAddress(host, port)) + .setTargetAddress((InetSocketAddress) socketAddress); + if (proxyUid != null && proxyPwd != null) { + proxyBuilder.setUsername(proxyUid); + proxyBuilder.setPassword(proxyPwd); + } + return proxyBuilder.build(); } - })) + }); + } + if (sslTrustStorePath != null + && !sslTrustStorePath.trim().isEmpty() + && builder instanceof NettyChannelBuilder) { + try { + TrustManagerFactory tmf = + loadTrustManagerFactory( + sslTrustStorePath, + sslTrustStorePassword, + sslTrustStoreType, + sslTrustStoreProvider); + SslContext sslContext = GrpcSslContexts.forClient().trustManager(tmf).build(); + ((NettyChannelBuilder) builder).sslContext(sslContext); + } catch (IOException | GeneralSecurityException e) { + throw new IllegalStateException("Failed to configure test SSL TrustStore", e); + } + } + return builder; + }) .build(); } @@ -438,16 +610,21 @@ private T pollWithRetry(java.util.concurrent.Callable task) throws Interr return null; } - private List fetchLogsWithRetry(Logging logging, String filter) + private List fetchLogsWithRetry(LoggingClient loggingClient, String filter) throws InterruptedException { + String boundedFilter = + filter + " AND timestamp >= \"" + Instant.now().minus(Duration.ofHours(24)) + "\""; List result = pollWithRetry( () -> { - Page entriesPage = - logging.listLogEntries( - Logging.EntryListOption.filter(filter), Logging.EntryListOption.pageSize(50)); + ListLogEntriesRequest request = + ListLogEntriesRequest.newBuilder() + .addResourceNames("projects/" + PROJECT_ID) + .setFilter(boundedFilter) + .setPageSize(50) + .build(); List entries = new ArrayList<>(); - entriesPage.iterateAll().forEach(entries::add); + loggingClient.listLogEntries(request).iterateAll().forEach(entries::add); return entries.isEmpty() ? null : entries; }); return result != null ? result : new ArrayList<>();