Skip to content

Commit 493a254

Browse files
fix(bigtable): auto-disable built-in Cloud Monitoring on custom endpoints and unauthenticated clients (#15294)
## Behavior Change (Release Notes) **User-visible behavior change for regional (REP), named PSC, and Private/Restricted VIP endpoints**: Previously, clients in `googleapis.com` configured with a regional endpoint (`*.rep.googleapis.com`), named Private Service Connect endpoint (`*.p.googleapis.com`), or `private.googleapis.com` / `restricted.googleapis.com` exported built-in Cloud Monitoring metrics to global `monitoring.googleapis.com:443` by default. With this change, built-in Cloud Monitoring export is automatically disabled (with a `WARNING` log) for those endpoints unless a Cloud Monitoring endpoint is explicitly configured via `setMetricsEndpoint(...)`. ## Problem 1. When a Bigtable client is configured with a non-standard data endpoint (such as a partner universe endpoint via `setEndpoint("bigtable.<universe>:443")` without setting `universeDomain` or `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, a regional endpoint `*.rep.<universe>`, a named PSC endpoint `*.p.<universe>`, `private.<universe>` / `restricted.<universe>`, or a proxy/emulator endpoint) and no explicit `metricsEndpoint`, default-on built-in Cloud Monitoring export still uses the defaulted `googleapis.com` universe domain and dials `monitoring.googleapis.com:443` with the client's credentials and telemetry. 2. When a client is configured with `NoCredentialsProvider` (and no explicit `metricsEndpoint` or legacy metrics credential override), built-in Cloud Monitoring export still sends unauthenticated telemetry to `monitoring.googleapis.com:443`. ## Solution - **`BigtableClientContext`**: Gate built-in Cloud Monitoring (`builtinOtel`) initialization on `shouldEnableBuiltinMetrics(settings, credentials)`: 1. Disabled silently when `!settings.areInternalMetricsEnabled()`. 2. Always enabled when an explicit `settings.getMetricsEndpoint()` or `-Dbigtable.test-monitoring-endpoint` override is set. 3. Disabled (logged at `FINE`) when effective metrics credentials are `null` (`NoCredentialsProvider`) and no explicit metrics endpoint is set. 4. Enabled only when `settings.getEndpoint()` is a valid port-443 (or omitted-port) subdomain of `settings.getUniverseDomain()`, excluding regional endpoints (`*.rep.<universeDomain>`), named PSC endpoints (`*.p.<universeDomain>`), and Private/Restricted Google Access VIPs (`private.<universeDomain>`, `restricted.<universeDomain>`). Otherwise, built-in Cloud Monitoring export is disabled with a targeted `WARNING` log: - Outside the configured universe: suggests configuring `setUniverseDomain()` / `GOOGLE_CLOUD_UNIVERSE_DOMAIN` or `setMetricsEndpoint(...)`. - Inside the universe but REP / named PSC / `private` / `restricted`: explains default export is not supported for that endpoint type and suggests `setMetricsEndpoint(...)`. - Note: `settings.getEndpoint()` reflects custom endpoints set on `InstantiatingGrpcChannelProvider`, but opaque `TransportChannelProvider`s (e.g., `FixedTransportChannelProvider` wrapping a prebuilt channel) cannot be inspected and remain enabled. - Caller-owned `CustomOpenTelemetryMetricsProvider` (`userOtel`) is unaffected. - **`BigtableCloudMonitoringExporter`**: Expose `@InternalApi getMonitoringEndpointOverride()` and ignore blank endpoint overrides consistently. ## Testing - Formatted with `fmt-maven-plugin:format`. - Expanded `BigtableClientContextTest` and `BigtableCloudMonitoringExporter2Test` in JUnit 5 covering same-universe subdomains, cross-universe/TPC, REP, named PSC, `private`/`restricted` (including targeted remediation warnings), malformed/non-443 endpoints, `InstantiatingGrpcChannelProvider` custom endpoints, `NoCredentialsProvider`, explicit `metricsEndpoint`, `disableInternalMetrics()`, `toBuilder()` re-evaluation, and `CustomOpenTelemetryMetricsProvider` isolation.
1 parent 3f117da commit 493a254

5 files changed

Lines changed: 889 additions & 21 deletions

File tree

‎java-bigtable/google-cloud-bigtable/pom.xml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,11 @@
354354
<artifactId>junit-jupiter-api</artifactId>
355355
<scope>test</scope>
356356
</dependency>
357+
<dependency>
358+
<groupId>org.junit.jupiter</groupId>
359+
<artifactId>junit-jupiter-params</artifactId>
360+
<scope>test</scope>
361+
</dependency>
357362
<dependency>
358363
<groupId>org.junit.jupiter</groupId>
359364
<artifactId>junit-jupiter</artifactId>

‎java-bigtable/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/internal/csm/exporter/BigtableCloudMonitoringExporter.java‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import com.google.api.core.ApiFuture;
1919
import com.google.api.core.ApiFutureCallback;
2020
import com.google.api.core.ApiFutures;
21+
import com.google.api.core.InternalApi;
2122
import com.google.api.gax.core.CredentialsProvider;
2223
import com.google.api.gax.core.FixedCredentialsProvider;
2324
import com.google.api.gax.core.NoCredentialsProvider;
@@ -88,6 +89,21 @@ private enum State {
8889
Closed
8990
}
9091

92+
@InternalApi
93+
@Nullable
94+
public static String getMonitoringEndpointOverride() {
95+
return trimToNull(MONITORING_ENDPOINT_OVERRIDE_SYS_PROP);
96+
}
97+
98+
@Nullable
99+
private static String trimToNull(@Nullable String value) {
100+
if (value == null) {
101+
return null;
102+
}
103+
String trimmed = value.trim();
104+
return trimmed.isEmpty() ? null : trimmed;
105+
}
106+
91107
public static BigtableCloudMonitoringExporter create(
92108
MetricRegistry metricRegistry,
93109
Supplier<EnvInfo> envInfo,
@@ -107,15 +123,17 @@ public static BigtableCloudMonitoringExporter create(
107123
.<CredentialsProvider>map(FixedCredentialsProvider::create)
108124
.orElse(NoCredentialsProvider.create()));
109125

110-
if (MONITORING_ENDPOINT_OVERRIDE_SYS_PROP != null) {
126+
String monitoringEndpointOverride = getMonitoringEndpointOverride();
127+
if (monitoringEndpointOverride != null) {
111128
LOGGER.warning(
112129
"Setting the monitoring endpoint through system variable will be removed in future"
113130
+ " versions");
114-
settingsBuilder.setEndpoint(MONITORING_ENDPOINT_OVERRIDE_SYS_PROP);
131+
settingsBuilder.setEndpoint(monitoringEndpointOverride);
115132
}
116133

117-
if (endpoint != null) {
118-
settingsBuilder.setEndpoint(endpoint);
134+
String normalizedEndpoint = trimToNull(endpoint);
135+
if (normalizedEndpoint != null) {
136+
settingsBuilder.setEndpoint(normalizedEndpoint);
119137
}
120138

121139
Duration timeout = Duration.ofMinutes(1);

‎java-bigtable/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/data/v2/stub/BigtableClientContext.java‎

Lines changed: 130 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import com.google.auth.Credentials;
2929
import com.google.auth.oauth2.GdchCredentials;
3030
import com.google.auth.oauth2.ServiceAccountJwtAccessCredentials;
31+
import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
3132
import com.google.cloud.bigtable.data.v2.internal.JwtCredentialsWithAudience;
3233
import com.google.cloud.bigtable.data.v2.internal.api.InstanceName;
3334
import com.google.cloud.bigtable.data.v2.internal.compat.DisabledShim;
@@ -37,6 +38,7 @@
3738
import com.google.cloud.bigtable.data.v2.internal.csm.Metrics;
3839
import com.google.cloud.bigtable.data.v2.internal.csm.MetricsImpl;
3940
import com.google.cloud.bigtable.data.v2.internal.csm.attributes.ClientInfo;
41+
import com.google.cloud.bigtable.data.v2.internal.csm.exporter.BigtableCloudMonitoringExporter;
4042
import com.google.cloud.bigtable.data.v2.internal.dp.AlwaysEnabledDirectAccessChecker;
4143
import com.google.cloud.bigtable.data.v2.internal.dp.ClassicDirectAccessChecker;
4244
import com.google.cloud.bigtable.data.v2.internal.dp.DirectAccessChecker;
@@ -45,6 +47,8 @@
4547
import com.google.cloud.bigtable.gaxx.grpc.BigtableTransportChannelProvider;
4648
import com.google.cloud.bigtable.gaxx.grpc.ChannelPrimer;
4749
import com.google.common.annotations.VisibleForTesting;
50+
import com.google.common.base.Ascii;
51+
import com.google.common.net.InternetDomainName;
4852
import io.grpc.ManagedChannelBuilder;
4953
import io.opencensus.stats.Stats;
5054
import io.opencensus.stats.StatsRecorder;
@@ -55,9 +59,12 @@
5559
import java.io.IOException;
5660
import java.net.URI;
5761
import java.net.URISyntaxException;
62+
import java.util.Objects;
63+
import java.util.Optional;
5864
import java.util.concurrent.ScheduledExecutorService;
5965
import java.util.logging.Level;
6066
import java.util.logging.Logger;
67+
import java.util.stream.Stream;
6168
import javax.annotation.Nullable;
6269

6370
/**
@@ -155,7 +162,7 @@ public static BigtableClientContext create(
155162

156163
@Nullable OpenTelemetrySdk builtinOtel = null;
157164
try {
158-
if (settings.areInternalMetricsEnabled()) {
165+
if (shouldEnableBuiltinMetrics(settings, credentials)) {
159166
builtinOtel =
160167
builtinOtelFactory.create(
161168
metricRegistry,
@@ -249,6 +256,128 @@ public static BigtableClientContext create(
249256
}
250257
}
251258

259+
@VisibleForTesting
260+
static boolean shouldEnableBuiltinMetrics(
261+
EnhancedBigtableStubSettings settings, @Nullable Credentials credentials) {
262+
if (!settings.areInternalMetricsEnabled()) {
263+
return false;
264+
}
265+
266+
Optional<String> effectiveMetricsEndpoint =
267+
Stream.of(
268+
settings.getMetricsEndpoint(),
269+
BigtableCloudMonitoringExporter.getMonitoringEndpointOverride())
270+
.filter(s -> !isBlank(s))
271+
.findFirst();
272+
if (effectiveMetricsEndpoint.isPresent()) {
273+
return true;
274+
}
275+
276+
Optional<Credentials> effectiveMetricsCredentials =
277+
Stream.of(BigtableDataSettings.getMetricsCredentials(), credentials)
278+
.filter(Objects::nonNull)
279+
.findFirst();
280+
if (!effectiveMetricsCredentials.isPresent()) {
281+
logger.log(
282+
Level.FINE,
283+
"Disabling built-in Cloud Monitoring metrics because no credentials are configured.");
284+
return false;
285+
}
286+
287+
// settings.getEndpoint() reflects explicit endpoints on InstantiatingGrpcChannelProvider, but
288+
// opaque providers (e.g. FixedTransportChannelProvider / prebuilt channels) hide the real
289+
// target, so built-in metrics remain enabled in that case.
290+
String endpoint = settings.getEndpoint();
291+
String universeDomain = settings.getUniverseDomain();
292+
switch (classifyEndpoint(endpoint, universeDomain)) {
293+
case SUPPORTED:
294+
return true;
295+
case UNSUPPORTED_IN_UNIVERSE:
296+
logger.log(
297+
Level.WARNING,
298+
String.format(
299+
"Disabling built-in Cloud Monitoring metrics because default Cloud Monitoring"
300+
+ " export is not supported for endpoint '%s' (regional, named PSC, or"
301+
+ " private/restricted VIP). To enable built-in metrics, explicitly set a"
302+
+ " Cloud Monitoring endpoint via setMetricsEndpoint().",
303+
endpoint));
304+
return false;
305+
case OUTSIDE_UNIVERSE:
306+
default:
307+
logger.log(
308+
Level.WARNING,
309+
String.format(
310+
"Disabling built-in Cloud Monitoring metrics because endpoint '%s' is not in"
311+
+ " universe domain '%s'. To enable built-in metrics, configure the universe"
312+
+ " domain via setUniverseDomain() or GOOGLE_CLOUD_UNIVERSE_DOMAIN, or"
313+
+ " explicitly set a Cloud Monitoring endpoint via setMetricsEndpoint().",
314+
endpoint, universeDomain));
315+
return false;
316+
}
317+
}
318+
319+
@VisibleForTesting
320+
enum EndpointStatus {
321+
// Valid port-443 subdomain of the configured universe; default Cloud Monitoring export is safe.
322+
SUPPORTED,
323+
// Different universe, custom proxy/emulator, non-443 port, or malformed endpoint.
324+
OUTSIDE_UNIVERSE,
325+
// Same universe, but REP (*.rep.*), named PSC (*.p.*), or private/restricted VIP with no
326+
// derived monitoring endpoint.
327+
UNSUPPORTED_IN_UNIVERSE
328+
}
329+
330+
@VisibleForTesting
331+
static EndpointStatus classifyEndpoint(
332+
@Nullable String endpoint, @Nullable String universeDomain) {
333+
if (isBlank(endpoint) || isBlank(universeDomain)) {
334+
return EndpointStatus.OUTSIDE_UNIVERSE;
335+
}
336+
337+
// Deliberately do not trim endpoint (unlike metricsEndpoint): surrounding whitespace on the
338+
// data endpoint is treated as malformed rather than normalized away.
339+
String normalizedEndpoint = Ascii.toLowerCase(endpoint);
340+
if (normalizedEndpoint.endsWith(":443")) {
341+
normalizedEndpoint = normalizedEndpoint.substring(0, normalizedEndpoint.length() - 4);
342+
}
343+
if (!InternetDomainName.isValid(normalizedEndpoint)) {
344+
return EndpointStatus.OUTSIDE_UNIVERSE;
345+
}
346+
347+
String universeSuffix = "." + Ascii.toLowerCase(universeDomain);
348+
if (!normalizedEndpoint.endsWith(universeSuffix)) {
349+
return EndpointStatus.OUTSIDE_UNIVERSE;
350+
}
351+
352+
// Strip the universe suffix and optional ".mtls" segment so mTLS variants (e.g.
353+
// *.rep.mtls.<universe>, *.p.mtls.<universe>, private.mtls.<universe>) are classified the same
354+
// as their non-mTLS counterparts.
355+
String hostPrefix =
356+
normalizedEndpoint.substring(0, normalizedEndpoint.length() - universeSuffix.length());
357+
if (hostPrefix.equals("mtls")) {
358+
return EndpointStatus.OUTSIDE_UNIVERSE;
359+
}
360+
if (hostPrefix.endsWith(".mtls")) {
361+
hostPrefix = hostPrefix.substring(0, hostPrefix.length() - ".mtls".length());
362+
}
363+
364+
// Built-in Cloud Monitoring has no endpoint derivation for REP, named PSC, or
365+
// Private/Restricted Google Access VIPs within the universe and would otherwise silently
366+
// dial global monitoring.<universeDomain>:443.
367+
if (hostPrefix.equals("private")
368+
|| hostPrefix.equals("restricted")
369+
|| hostPrefix.endsWith(".rep")
370+
|| hostPrefix.endsWith(".p")) {
371+
return EndpointStatus.UNSUPPORTED_IN_UNIVERSE;
372+
}
373+
374+
return EndpointStatus.SUPPORTED;
375+
}
376+
377+
private static boolean isBlank(@Nullable String value) {
378+
return value == null || value.trim().isEmpty();
379+
}
380+
252381
@SuppressWarnings("deprecation")
253382
private static boolean isRefreshingEnabled(EnhancedBigtableStubSettings.Builder b) {
254383
return b.isRefreshingChannel();

‎java-bigtable/google-cloud-bigtable/src/test/java/com/google/cloud/bigtable/data/v2/internal/csm/exporter/BigtableCloudMonitoringExporter2Test.java‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import com.google.api.core.ApiFutures;
2424
import com.google.api.gax.rpc.ApiCallContext;
2525
import com.google.api.gax.rpc.UnaryCallable;
26+
import com.google.auth.Credentials;
2627
import com.google.cloud.bigtable.data.v2.internal.api.TableName;
2728
import com.google.cloud.bigtable.data.v2.internal.csm.MetricRegistry;
2829
import com.google.cloud.bigtable.data.v2.internal.csm.attributes.ClientInfo;
@@ -51,6 +52,7 @@
5152
import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData;
5253
import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData;
5354
import io.opentelemetry.sdk.resources.Resource;
55+
import java.io.IOException;
5456
import java.util.ArrayList;
5557
import java.util.Arrays;
5658
import java.util.Collection;
@@ -505,6 +507,28 @@ public void testExportingToMultipleProjects() throws InterruptedException {
505507
assertThat(counts).containsExactly(3l, 15l);
506508
}
507509

510+
@Test
511+
public void testGetMonitoringEndpointOverrideUnsetReturnsNull() {
512+
assertThat(BigtableCloudMonitoringExporter.getMonitoringEndpointOverride()).isNull();
513+
}
514+
515+
@Test
516+
public void testCreateIgnoresBlankEndpoint() throws IOException {
517+
BigtableCloudMonitoringExporter created =
518+
BigtableCloudMonitoringExporter.create(
519+
new MetricRegistry(),
520+
Suppliers.ofInstance(envInfo),
521+
clientInfo,
522+
null,
523+
" ",
524+
Credentials.GOOGLE_DEFAULT_UNIVERSE);
525+
try {
526+
assertThat(created).isNotNull();
527+
} finally {
528+
created.close();
529+
}
530+
}
531+
508532
private static class FakeMetricServiceClient extends MetricServiceClient {
509533
protected FakeMetricServiceClient(MetricServiceStub stub) {
510534
super(stub);

0 commit comments

Comments
 (0)