Skip to content

Commit 2c52d5e

Browse files
fix(spanner): disable built-in Cloud Monitoring metrics for custom non-default hosts without an explicit target (#15252)
## Problem Statement - When configuring a custom non-`*.googleapis.com` Spanner host via `SpannerOptions.Builder.setHost(...)` or a JDBC/Connection URL host or `endpoint` property without setting `universeDomain`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `monitoringHost`, or `SPANNER_MONITORING_HOST`, default-on built-in Cloud Monitoring metrics remained enabled and exported telemetry and credentials to `monitoring.googleapis.com:443`. ## Solution - Automatically disable built-in Cloud Monitoring metrics when a custom non-`*.googleapis.com` host (including malformed or scheme-less hosts) is configured without an explicit `universeDomain`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `monitoringHost`, or `SPANNER_MONITORING_HOST`, logging a warning for non-plaintext, non-emulator clients. - Preserve `toBuilder()` re-evaluation when a caller later sets a universe domain, sets a monitoring host, or clears the custom host, and leave caller-owned `CustomOpenTelemetryMetricsProvider` sinks unaffected.
1 parent 1d01c6c commit 2c52d5e

9 files changed

Lines changed: 599 additions & 23 deletions

File tree

‎java-spanner/.readme-partials.yaml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ custom_content: |
6767
6868
You can also disable the default Cloud Monitoring export by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. These controls affect only the Cloud Monitoring export. They do not affect a caller-owned client-metrics export configured with `CustomOpenTelemetryMetricsProvider`.
6969
70+
When a custom non-`*.googleapis.com` host is configured via `SpannerOptions.Builder.setHost(...)` (or a JDBC/Connection URL host or `endpoint` property) without setting `setUniverseDomain(...)`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `setMonitoringHost(...)`, or `SPANNER_MONITORING_HOST`, the default Cloud Monitoring export is automatically disabled so telemetry and credentials are not sent to `monitoring.googleapis.com`.
71+
7072
> Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data to Cloud Monitoring. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project.
7173
7274
#### Exporting client metrics to OpenTelemetry

‎java-spanner/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ SpannerOptions options = SpannerOptions.newBuilder()
165165

166166
You can also disable the default Cloud Monitoring export by setting `SPANNER_DISABLE_BUILTIN_METRICS` to `true`. These controls affect only the Cloud Monitoring export. They do not affect a caller-owned client-metrics export configured with `CustomOpenTelemetryMetricsProvider`.
167167

168+
When a custom non-`*.googleapis.com` host is configured via `SpannerOptions.Builder.setHost(...)` (or a JDBC/Connection URL host or `endpoint` property) without setting `setUniverseDomain(...)`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, `setMonitoringHost(...)`, or `SPANNER_MONITORING_HOST`, the default Cloud Monitoring export is automatically disabled so telemetry and credentials are not sent to `monitoring.googleapis.com`.
169+
168170
> Note: Client-side metrics needs `monitoring.timeSeries.create` IAM permission to export metrics data to Cloud Monitoring. Ask your administrator to grant your service account the [Monitoring Metric Writer](https://cloud.google.com/iam/docs/roles-permissions/monitoring#monitoring.metricWriter) (roles/monitoring.metricWriter) IAM role on the project.
169171
170172
#### Exporting client metrics to OpenTelemetry

‎java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerOptions.java‎

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
import com.google.cloud.spanner.v1.SpannerSettings;
6666
import com.google.cloud.spanner.v1.stub.SpannerStubSettings;
6767
import com.google.common.annotations.VisibleForTesting;
68+
import com.google.common.base.Ascii;
6869
import com.google.common.base.MoreObjects;
6970
import com.google.common.base.Preconditions;
7071
import com.google.common.base.Strings;
@@ -1118,6 +1119,26 @@ protected SpannerOptions(Builder builder) {
11181119
resolved = NoopMetricsProvider.INSTANCE;
11191120
}
11201121
enableBuiltInMetrics = false;
1122+
} else if (isEmulatorEnabled()) {
1123+
// The emulator has no Cloud Monitoring sink; report GCM as off so isEnableBuiltInMetrics()
1124+
// is truthful.
1125+
enableBuiltInMetrics = false;
1126+
} else if (builder.enableBuiltInMetrics
1127+
&& !isDefaultUniverseHost(configuredHost)
1128+
&& isBlank(getUniverseDomain())
1129+
&& isBlank(environment.getUniverseDomain())
1130+
&& isBlank(builder.monitoringHost)) {
1131+
// Fail closed for custom non-default hosts without an explicit metrics target so default-on
1132+
// Cloud Monitoring export never leaks credentials or telemetry to monitoring.googleapis.com.
1133+
enableBuiltInMetrics = false;
1134+
if (!builder.usePlainText) {
1135+
logger.log(
1136+
Level.WARNING,
1137+
"Disabling built-in Cloud Monitoring metrics because custom host {0} is configured"
1138+
+ " without an explicit universeDomain, GOOGLE_CLOUD_UNIVERSE_DOMAIN, or"
1139+
+ " monitoringHost.",
1140+
configuredHost);
1141+
}
11211142
} else {
11221143
enableBuiltInMetrics = builder.enableBuiltInMetrics;
11231144
}
@@ -1143,6 +1164,34 @@ protected SpannerOptions(Builder builder) {
11431164
autoTaggingTracerLimit = builder.autoTaggingTracerLimit;
11441165
}
11451166

1167+
/**
1168+
* Returns {@code true} if {@code host} is unset (meaning the default endpoint will be used) or is
1169+
* a valid URL targeting a subdomain of {@code googleapis.com} (for example, {@code
1170+
* https://spanner.googleapis.com}).
1171+
*
1172+
* <p>Returns {@code false} for any custom host, bare {@code googleapis.com}, or URL without a
1173+
* valid scheme/hostname (for example, {@code spanner.googleapis.com:443}), so built-in Cloud
1174+
* Monitoring export is safely disabled unless a monitoring target is explicitly configured.
1175+
*/
1176+
private static boolean isDefaultUniverseHost(@Nullable String host) {
1177+
if (Strings.isNullOrEmpty(host)) {
1178+
return true;
1179+
}
1180+
try {
1181+
String normalized = Ascii.toLowerCase(new URL(host).getHost());
1182+
String defaultUniverseSuffix = "." + GOOGLE_DEFAULT_UNIVERSE;
1183+
return normalized.length() > defaultUniverseSuffix.length()
1184+
&& normalized.endsWith(defaultUniverseSuffix);
1185+
} catch (MalformedURLException e) {
1186+
return false;
1187+
}
1188+
}
1189+
1190+
/** Returns {@code true} if {@code value} is null or contains only whitespace characters. */
1191+
private static boolean isBlank(@Nullable String value) {
1192+
return value == null || value.trim().isEmpty();
1193+
}
1194+
11461195
/**
11471196
* Validates that a non-empty universe domain is a valid RFC 1123 DNS domain name so it cannot
11481197
* inject URL components (such as userinfo, port, path, query, or fragment) into constructed
@@ -3106,7 +3155,8 @@ public ApiTracerFactory getApiTracerFactory() {
31063155

31073156
/**
31083157
* Returns the internal OpenTelemetry instance used for built-in metrics, or {@code null} when
3109-
* Cloud Monitoring built-in metrics are disabled or no credentials are configured.
3158+
* Cloud Monitoring built-in metrics are disabled, no credentials are configured, or it could not
3159+
* be initialized.
31103160
*/
31113161
@InternalApi
31123162
@Nullable
@@ -3289,9 +3339,13 @@ public boolean isEnableApiTracing() {
32893339

32903340
/**
32913341
* Returns true if built-in metrics are exported to the default Cloud Monitoring (GCM)
3292-
* destination. Always false for {@link InstanceType#OMNI} clients, where the GCM sink is
3293-
* unavailable. This flag does not affect a caller-owned client-metrics destination configured
3294-
* with {@link Builder#setClientMetricsProvider(MetricsProvider)}.
3342+
* destination. Always false for {@link InstanceType#OMNI} clients and when the emulator is
3343+
* enabled, where the GCM sink is unavailable, and automatically disabled when a custom non-{@code
3344+
* *.googleapis.com} host (including a scheme-less host) is configured via {@link
3345+
* Builder#setHost(String)} without an explicit {@code universeDomain}, {@code
3346+
* GOOGLE_CLOUD_UNIVERSE_DOMAIN}, or {@code monitoringHost}. This flag does not affect a
3347+
* caller-owned client-metrics destination configured with {@link
3348+
* Builder#setClientMetricsProvider(MetricsProvider)}.
32953349
*/
32963350
public boolean isEnableBuiltInMetrics() {
32973351
return enableBuiltInMetrics;

‎java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsBothSinksTest.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818

1919
import static com.google.common.truth.Truth.assertThat;
2020

21+
import com.google.auth.Credentials;
2122
import com.google.cloud.NoCredentials;
2223
import com.google.cloud.spanner.connection.AbstractMockServerTest;
2324
import io.grpc.ManagedChannelBuilder;
@@ -88,6 +89,7 @@ private Spanner createSpanner(OpenTelemetry customSink) {
8889
return SpannerOptions.newBuilder()
8990
.setProjectId("my-project")
9091
.setHost(String.format("http://localhost:%d", getPort()))
92+
.setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE)
9193
.setChannelConfigurator(ManagedChannelBuilder::usePlaintext)
9294
.setCredentials(NoCredentials.getInstance())
9395
.setSessionPoolOption(SessionPoolOptions.newBuilder().setFailOnSessionLeak().build())

‎java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/BuiltInMetricsCustomOpenTelemetryTest.java‎

Lines changed: 80 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -177,31 +177,87 @@ public boolean isEnableGRPCBuiltInMetrics() {
177177
});
178178
BuiltInMetricsProvider.INSTANCE.reset();
179179

180-
// Default provider with NoCredentials and built-in metrics enabled must not initialize GCM.
181-
try (Spanner defaultSpanner =
182-
spannerBuilder(DefaultMetricsProvider.INSTANCE)
183-
.setEmulatorHost(null)
184-
.setBuiltInMetricsEnabled(true)
185-
.build()
186-
.getService()) {
187-
executeSelect1(defaultSpanner);
180+
try {
181+
// Default provider with NoCredentials and built-in metrics enabled must not initialize GCM.
182+
try (Spanner defaultSpanner =
183+
spannerBuilder(DefaultMetricsProvider.INSTANCE)
184+
.setEmulatorHost(null)
185+
.setBuiltInMetricsEnabled(true)
186+
.build()
187+
.getService()) {
188+
executeSelect1(defaultSpanner);
189+
}
190+
assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry());
191+
192+
// Custom provider with NoCredentials and built-in metrics enabled still records custom
193+
// metrics while leaving the GCM singleton uninitialized.
194+
InMemoryMetricReader metricReader = InMemoryMetricReader.create();
195+
OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader);
196+
try {
197+
try (Spanner customSpanner =
198+
spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry))
199+
.setEmulatorHost(null)
200+
.setBuiltInMetricsEnabled(true)
201+
.build()
202+
.getService()) {
203+
executeSelect1(customSpanner);
204+
}
205+
assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry());
206+
assertNotNull(
207+
getMetric(
208+
metricReader,
209+
BuiltInMetricsConstant.CUSTOM_EXPORT_METER_NAME
210+
+ "/"
211+
+ BuiltInMetricsConstant.OPERATION_COUNT_NAME));
212+
} finally {
213+
customOpenTelemetry.close();
214+
}
215+
} finally {
216+
BuiltInMetricsProvider.INSTANCE.reset();
217+
SpannerOptions.useDefaultEnvironment();
188218
}
189-
assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry());
219+
}
190220

191-
// Custom provider with NoCredentials and built-in metrics enabled still records custom metrics
192-
// while leaving the GCM singleton uninitialized.
221+
@Test
222+
public void customHostDisablesGcmEndToEndWhileKeepingCustomSink() {
223+
String previousJmhEnabled = System.getProperty("jmh.enabled");
224+
// Lift the NoCredentials guard (same pattern as BuiltInMetricsBothSinksTest) because gRPC
225+
// rejects OAuth2 CallCredentials on a plaintext mock-server channel.
226+
System.setProperty("jmh.enabled", "true");
227+
SpannerOptions.useEnvironment(
228+
new SpannerOptions.SpannerEnvironment() {
229+
@Override
230+
public boolean isEnableGRPCBuiltInMetrics() {
231+
return true;
232+
}
233+
});
234+
BuiltInMetricsProvider.INSTANCE.reset();
193235
InMemoryMetricReader metricReader = InMemoryMetricReader.create();
194236
OpenTelemetrySdk customOpenTelemetry = createOpenTelemetry(metricReader);
195237
try {
196-
try (Spanner customSpanner =
197-
spannerBuilder(CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry))
238+
SpannerOptions options =
239+
SpannerOptions.newBuilder()
240+
.setProjectId("my-project")
198241
.setEmulatorHost(null)
199-
.setBuiltInMetricsEnabled(true)
200-
.build()
201-
.getService()) {
202-
executeSelect1(customSpanner);
242+
.setHost(String.format("http://localhost:%d", getPort()))
243+
.setChannelConfigurator(ManagedChannelBuilder::usePlaintext)
244+
.setCredentials(NoCredentials.getInstance())
245+
.setSessionPoolOption(SessionPoolOptions.newBuilder().setFailOnSessionLeak().build())
246+
.setClientMetricsProvider(
247+
CustomOpenTelemetryMetricsProvider.create(customOpenTelemetry))
248+
.build();
249+
assertFalse(options.isEnableBuiltInMetrics());
250+
251+
try (Spanner spanner = options.getService()) {
252+
executeSelect1(spanner);
203253
}
254+
255+
// Even with the NoCredentials guard lifted and gRPC built-in metrics enabled, the custom host
256+
// must NOT initialize the GCM singleton.
204257
assertNull(BuiltInMetricsProvider.INSTANCE.getOpenTelemetry());
258+
assertNull(BuiltInMetricsProvider.INSTANCE.getProjectId());
259+
260+
// Caller-owned CustomOpenTelemetryMetricsProvider still records metrics end-to-end.
205261
assertNotNull(
206262
getMetric(
207263
metricReader,
@@ -210,6 +266,13 @@ public boolean isEnableGRPCBuiltInMetrics() {
210266
+ BuiltInMetricsConstant.OPERATION_COUNT_NAME));
211267
} finally {
212268
customOpenTelemetry.close();
269+
BuiltInMetricsProvider.INSTANCE.reset();
270+
SpannerOptions.useDefaultEnvironment();
271+
if (previousJmhEnabled == null) {
272+
System.clearProperty("jmh.enabled");
273+
} else {
274+
System.setProperty("jmh.enabled", previousJmhEnabled);
275+
}
213276
}
214277
}
215278
}

‎java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/ChannelPoolBuiltInMetricsTest.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
import com.google.api.gax.grpc.GrpcCallContext;
2323
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
2424
import com.google.api.gax.rpc.ApiCallContext;
25+
import com.google.auth.Credentials;
2526
import com.google.cloud.NoCredentials;
2627
import com.google.cloud.grpc.GcpManagedChannel;
2728
import com.google.cloud.spanner.SpannerOptions.CallContextConfigurator;
@@ -349,6 +350,7 @@ public void dynamicPoolReportsDynamicPoolModeAndChannelLoad() {
349350
SpannerOptions.newBuilder()
350351
.setProjectId("my-project")
351352
.setHost(String.format("http://localhost:%d", getPort()))
353+
.setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE)
352354
.setChannelConfigurator(ManagedChannelBuilder::usePlaintext)
353355
.setCredentials(NoCredentials.getInstance())
354356
.enableGrpcGcpExtension()
@@ -420,6 +422,7 @@ private SpannerOptions.Builder createOptions() {
420422
return SpannerOptions.newBuilder()
421423
.setProjectId("my-project")
422424
.setHost(String.format("http://localhost:%d", getPort()))
425+
.setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE)
423426
.setChannelConfigurator(ManagedChannelBuilder::usePlaintext)
424427
.setCredentials(NoCredentials.getInstance())
425428
.enableGrpcGcpExtension()
@@ -432,6 +435,7 @@ private SpannerOptions createDirectPathFallbackOptions() {
432435
.setProjectId("my-project")
433436
.setEnableDirectAccess(true)
434437
.setHost("http://localhost:1")
438+
.setUniverseDomain(Credentials.GOOGLE_DEFAULT_UNIVERSE)
435439
.setCredentials(NoCredentials.getInstance())
436440
.enableGrpcGcpExtension()
437441
.disableDynamicChannelPool()

‎java-spanner/google-cloud-spanner/src/test/java/com/google/cloud/spanner/MetricsProviderTest.java‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ public void reset() {
6767
private static SpannerOptions.Builder cloudBuilder() {
6868
return SpannerOptions.newBuilder()
6969
.setProjectId("test-project")
70+
.setEmulatorHost(null)
7071
.setCredentials(NoCredentials.getInstance());
7172
}
7273

0 commit comments

Comments
 (0)