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
Expand Up @@ -25,33 +25,58 @@
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 the built-in metrics eligibility gate shared by {@link
* SpannerCqlSessionBuilder} and {@link Launcher}.
* 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 {

private static final String DEFAULT_SPANNER_ENDPOINT = "spanner.googleapis.com:443";
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 the standard TLS Cloud Spanner endpoint; otherwise returns a no-op recorder (with a
* warning log when metrics were requested).
* 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) {
Expand All @@ -74,22 +99,35 @@ static BuiltInMetricsRecorder createMetricsRecorder(
LOG.warn("Built-in metrics are disabled when a custom TransportChannelProvider is set.");
return createNoopRecorder();
}
if (spannerEndpoint != null && !spannerEndpoint.equalsIgnoreCase(DEFAULT_SPANNER_ENDPOINT)) {
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 '{}').",
"Built-in metrics are disabled for custom Spanner endpoint '{}' (expected default '{}'"
+ " for universe '{}').",
spannerEndpoint,
DEFAULT_SPANNER_ENDPOINT);
expectedEndpoint,
effectiveUniverse);
return createNoopRecorder();
}
return provider.createMetricsRecorder(
databaseName.getProject(),
databaseName.getInstance(),
databaseName.getDatabase(),
credentials,
null);
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 @@ -70,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 @@ -96,6 +99,7 @@
*/
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;
Expand Down Expand Up @@ -228,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 Down Expand Up @@ -275,18 +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 =
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