Skip to content
Merged
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
6 changes: 6 additions & 0 deletions docs/client-side-metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ For more information about granting roles, see [Manage access to projects, folde

You might also be able to get the required monitoring.timeSeries.create IAM permission through [custom roles](https://cloud.google.com/iam/docs/creating-custom-roles).

## Credentials, universe domain, and lifecycle

- **Credentials and universe domain**: Built-in metrics reuse the credentials configured on `SpannerCqlSessionBuilder` (falling back to Application Default Credentials when none are provided) and export to `monitoring.<universeDomain>:443`, derived from `setUniverseDomain(...)` / `globalClientConfigs.universeDomain` / `-DuniverseDomain`, `GOOGLE_CLOUD_UNIVERSE_DOMAIN`, or `googleapis.com`.
- **Automatically disabled modes**: Even when `enableBuiltInMetrics` is `true`, built-in metrics are automatically disabled (no-op with a warning log) when using plaintext connections (`usePlainText`), Spanner Omni (`InstanceType.OMNI` or `experimentalHostEndpoint`), `NoCredentials`, a custom `TransportChannelProvider`, or a custom non-default Spanner endpoint.
- **Shutdown and flushing**: Each enabled adapter owns an isolated metrics exporter that is flushed and shut down on `SpannerCqlSession.close()` / `Launcher.shutdown()`, waiting up to 2 seconds on the `SdkMeterProvider.shutdown()` result (in addition to any in-flight OpenTelemetry reader flush timeout). Always close `SpannerCqlSession` cleanly to flush the final reporting interval (up to 60 seconds).

## View metrics in the Metrics Explorer

1. In the Google Cloud console, go to the Metrics Explorer page.
Expand Down
6 changes: 6 additions & 0 deletions docs/config-options.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@ This file documents all the configuration options supported by the Spanner Cassa
```yaml
# [Optional] Global client configurations that apply to all listeners.
globalClientConfigs:
# [Optional] The Cloud universe domain (for example, "googleapis.com").
# Defaults to the GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variable, or "googleapis.com".
# Both default Spanner ("spanner.<universeDomain>:443") and built-in metrics
# ("monitoring.<universeDomain>:443") endpoints are derived from this value.
universeDomain: "googleapis.com"
# [Optional] Enables built-in metrics. Defaults to false. It is highly recommended to enable metrics in production environments for improved debuggability.
# Automatically disabled for plaintext, Spanner Omni, or custom non-default Spanner endpoints.
enableBuiltInMetrics: true
# [Optional] The endpoint for the health check server. If not specified, the health check server will not be started.
# To check the status, send a GET request to the '/debug/health' path on this endpoint.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import com.google.cloud.spanner.adapter.metrics.BuiltInMetricsRecorder;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import com.google.spanner.adapter.v1.AdapterClient;
import com.google.spanner.adapter.v1.AdapterSettings;
Expand Down Expand Up @@ -161,7 +162,14 @@ void start() {
options.getChannelProvider(), channelProviderBuilder.build()))
.setCredentialsProvider(credentialsProvider)
.setHeaderProvider(headerProvider);
settingsBuilder.setEndpoint(options.getSpannerEndpoint());
if (options.getUniverseDomain() != null) {
settingsBuilder.setUniverseDomain(options.getUniverseDomain());
}
// Only override endpoint when explicitly configured so GAX derives
// spanner.<universeDomain>:443 from the resolved universe domain.
if (!Strings.isNullOrEmpty(options.getSpannerEndpoint())) {
settingsBuilder.setEndpoint(options.getSpannerEndpoint());
}

AdapterSettings settings = settingsBuilder.build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,11 @@

/** Options for creating the {@link Adapter}. */
class AdapterOptions {
private static final String DEFAULT_SPANNER_ENDPOINT = "spanner.googleapis.com:443";
private static final int DEFAULT_NUM_GRPC_CHANNELS = 4;

/** Builder class for creating an instance of {@link AdapterOptions}. */
static class Builder {
String spannerEndpoint = DEFAULT_SPANNER_ENDPOINT;
String spannerEndpoint = null;
int tcpPort;
InetAddress inetAddress = InetAddress.getLoopbackAddress();
String databaseUri;
Expand All @@ -46,6 +45,7 @@ static class Builder {
private InstanceType instanceType = InstanceType.CLOUD;
private String clientCertPath = null;
private String clientKeyPath = null;
private String universeDomain = null;

/** The Cloud Spanner endpoint. */
Builder spannerEndpoint(String spannerEndpoint) {
Expand Down Expand Up @@ -131,6 +131,12 @@ Builder useClientCert(String clientCertPath, String clientKeyPath) {
return this;
}

/** (Optional) The Cloud universe domain. */
Builder universeDomain(String universeDomain) {
this.universeDomain = universeDomain;
return this;
}

AdapterOptions build() {
return new AdapterOptions(this);
}
Expand All @@ -150,6 +156,7 @@ AdapterOptions build() {
private InstanceType instanceType;
private String clientCertPath;
private String clientKeyPath;
private String universeDomain;

private AdapterOptions(Builder builder) {
this.spannerEndpoint = builder.spannerEndpoint;
Expand All @@ -166,6 +173,7 @@ private AdapterOptions(Builder builder) {
this.instanceType = builder.instanceType;
this.clientCertPath = builder.clientCertPath;
this.clientKeyPath = builder.clientKeyPath;
this.universeDomain = builder.universeDomain;
}

static Builder newBuilder() {
Expand Down Expand Up @@ -231,4 +239,8 @@ String getClientCertPath() {
String getClientKeyPath() {
return clientKeyPath;
}

String getUniverseDomain() {
return universeDomain;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
/*
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

http://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.spanner.adapter;

import com.google.api.gax.rpc.TransportChannelProvider;
import com.google.auth.Credentials;
import com.google.cloud.NoCredentials;
import com.google.cloud.spanner.adapter.SpannerCqlSessionBuilder.InstanceType;
import com.google.cloud.spanner.adapter.metrics.BuiltInMetricsProvider;
import com.google.cloud.spanner.adapter.metrics.BuiltInMetricsRecorder;
import com.google.spanner.adapter.v1.DatabaseName;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import java.util.function.Function;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* Package-private helper owning single-point {@code universeDomain} resolution and the built-in
* metrics eligibility gate shared by {@link SpannerCqlSessionBuilder} and {@link Launcher}.
*/
final class BuiltInMetricsSupport {

static final String ENV_GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN";
static final String DEFAULT_UNIVERSE_DOMAIN = "googleapis.com";

private static final Logger LOG = LoggerFactory.getLogger(BuiltInMetricsSupport.class);

private BuiltInMetricsSupport() {}

/**
* Resolves the Cloud universe domain with precedence {@code explicit >
* GOOGLE_CLOUD_UNIVERSE_DOMAIN > null}. Surrounding whitespace is trimmed; empty/blank values or
* values containing internal whitespace fail closed with {@link IllegalArgumentException}.
*/
@Nullable
static String resolveUniverseDomain(
@Nullable String explicitUniverseDomain, Function<String, String> envProvider) {
String raw =
explicitUniverseDomain != null
? explicitUniverseDomain
: envProvider.apply(ENV_GOOGLE_CLOUD_UNIVERSE_DOMAIN);
if (raw == null) {
return null;
}
String trimmed = raw.trim();
if (trimmed.isEmpty() || containsWhitespace(trimmed)) {
throw new IllegalArgumentException("universeDomain must not be empty or contain whitespace.");
}
return trimmed;
}

/**
* Creates a {@link BuiltInMetricsRecorder} when built-in metrics are enabled and the adapter
* targets a standard TLS Cloud Spanner endpoint for the resolved universe; otherwise returns a
* no-op recorder (with a warning log when metrics were requested).
*/
static BuiltInMetricsRecorder createMetricsRecorder(
BuiltInMetricsProvider provider,
boolean enabled,
DatabaseName databaseName,
@Nullable Credentials credentials,
@Nullable String spannerEndpoint,
@Nullable String universeDomain,
boolean usePlainText,
InstanceType instanceType,
@Nullable TransportChannelProvider channelProvider) {
if (!enabled) {
return createNoopRecorder();
}
if (usePlainText) {
LOG.warn("Built-in metrics are disabled when usePlainText is enabled.");
return createNoopRecorder();
}
if (instanceType == InstanceType.OMNI) {
LOG.warn("Built-in metrics are disabled for Spanner Omni instances.");
return createNoopRecorder();
}
if (credentials instanceof NoCredentials) {
LOG.warn("Built-in metrics are disabled when NoCredentials is configured.");
return createNoopRecorder();
}
if (channelProvider != null) {
LOG.warn("Built-in metrics are disabled when a custom TransportChannelProvider is set.");
return createNoopRecorder();
}
String effectiveUniverse = universeDomain != null ? universeDomain : DEFAULT_UNIVERSE_DOMAIN;
String expectedEndpoint = "spanner." + effectiveUniverse + ":443";
if (spannerEndpoint != null && !spannerEndpoint.equalsIgnoreCase(expectedEndpoint)) {
LOG.warn(
"Built-in metrics are disabled for custom Spanner endpoint '{}' (expected default '{}'"
+ " for universe '{}').",
spannerEndpoint,
expectedEndpoint,
effectiveUniverse);
return createNoopRecorder();
}
return provider.createMetricsRecorder(
databaseName.getProject(),
databaseName.getInstance(),
databaseName.getDatabase(),
credentials,
universeDomain);
}

private static BuiltInMetricsRecorder createNoopRecorder() {
return new BuiltInMetricsRecorder(OpenTelemetry.noop(), Attributes.empty());
}

private static boolean containsWhitespace(String value) {
for (int i = 0; i < value.length(); i++) {
if (Character.isWhitespace(value.charAt(i))) {
return true;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@
import com.google.cloud.spanner.adapter.metrics.BuiltInMetricsRecorder;
import com.google.common.annotations.VisibleForTesting;
import com.google.spanner.adapter.v1.DatabaseName;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.Attributes;
import java.io.IOException;
import java.net.InetAddress;
import java.time.Duration;
Expand Down Expand Up @@ -72,6 +70,9 @@
* optimize write throughput, in milliseconds. Defaults to none.
* <li>{@code healthCheckPort}: (Optional) The port number for the health check server. If
* unspecifed, health check server will NOT be started.
* <li>{@code universeDomain}: (Optional) The Cloud universe domain (for example, {@code
* googleapis.com}). Defaults to {@code GOOGLE_CLOUD_UNIVERSE_DOMAIN} or {@code
* googleapis.com}.
* </ul>
*
* <p><b>Example Usage:</b>
Expand All @@ -98,9 +99,11 @@
*/
public class Launcher {
private static final Logger LOG = LoggerFactory.getLogger(Launcher.class);

private static final String SPANNER_OMNI_ID = "default";
private final AdapterFactory adapterFactory;
private final BuiltInMetricsProvider builtInMetricsProvider;
private final Function<String, String> envProvider;
private final List<Adapter> adapters = new ArrayList<>();
private HealthCheckServer healthCheckServer;

Expand All @@ -124,13 +127,17 @@ public Launcher() {
}

public Launcher(AdapterFactory adapterFactory) {
this(adapterFactory, BuiltInMetricsProvider.INSTANCE);
this(adapterFactory, BuiltInMetricsProvider.INSTANCE, System::getenv);
}

@VisibleForTesting
Launcher(AdapterFactory adapterFactory, BuiltInMetricsProvider builtInMetricsProvider) {
Launcher(
AdapterFactory adapterFactory,
BuiltInMetricsProvider builtInMetricsProvider,
Function<String, String> envProvider) {
this.adapterFactory = adapterFactory;
this.builtInMetricsProvider = builtInMetricsProvider;
this.envProvider = envProvider;
}

public static void main(String[] args) throws Exception {
Expand Down Expand Up @@ -225,10 +232,13 @@ private void startHealthCheckServer(HealthCheckConfig config) throws IOException
}

private AdapterOptions buildAdapterOptions(
ListenerConfig config, BuiltInMetricsRecorder metricsRecorder) {
ListenerConfig config,
BuiltInMetricsRecorder metricsRecorder,
String resolvedUniverseDomain) {
final AdapterOptions.Builder opBuilder =
new AdapterOptions.Builder()
.spannerEndpoint(config.getSpannerEndpoint())
.universeDomain(resolvedUniverseDomain)
.tcpPort(config.getPort())
.databaseUri(config.getDatabaseUri())
.inetAddress(config.getHostAddress())
Expand All @@ -243,19 +253,6 @@ private AdapterOptions buildAdapterOptions(
return opBuilder.build();
}

private BuiltInMetricsRecorder createMetricsRecorder(
boolean enableBuiltInMetrics, DatabaseName databaseName) {
if (!enableBuiltInMetrics) {
return new BuiltInMetricsRecorder(OpenTelemetry.noop(), Attributes.empty());
}
return builtInMetricsProvider.createMetricsRecorder(
databaseName.getProject(),
databaseName.getInstance(),
databaseName.getDatabase(),
null,
null);
}

private DatabaseName resolveDatabaseName(ListenerConfig config) {
String uriOrId = config.getDatabaseUri();

Expand Down Expand Up @@ -285,10 +282,22 @@ private void startAdapter(ListenerConfig config) throws IOException {
config.isEnableBuiltInMetrics());

final DatabaseName databaseName = resolveDatabaseName(config);
final String resolvedUniverseDomain =
BuiltInMetricsSupport.resolveUniverseDomain(config.getUniverseDomain(), envProvider);
final BuiltInMetricsRecorder metricsRecorder =
createMetricsRecorder(config.isEnableBuiltInMetrics(), databaseName);
BuiltInMetricsSupport.createMetricsRecorder(
builtInMetricsProvider,
config.isEnableBuiltInMetrics(),
databaseName,
null,
config.getSpannerEndpoint(),
resolvedUniverseDomain,
config.usePlainText(),
config.getInstanceType(),
null);
try {
final AdapterOptions options = buildAdapterOptions(config, metricsRecorder);
final AdapterOptions options =
buildAdapterOptions(config, metricsRecorder, resolvedUniverseDomain);

final Adapter adapter = adapterFactory.createAdapter(options);
adapters.add(adapter);
Expand Down
Loading
Loading