Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.SpannerExceptionFactory;
import com.google.common.annotations.VisibleForTesting;
import io.grpc.ChannelCredentials;
import io.grpc.ConnectivityState;
import io.grpc.Grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.alts.AltsChannelCredentials;
import io.grpc.netty.shaded.io.grpc.netty.InternalNettyChannelBuilder;
import io.grpc.netty.shaded.io.grpc.netty.InternalNettyChannelCredentials;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import java.io.IOException;
import java.time.Duration;
import java.util.Map;
Expand All @@ -34,6 +40,7 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
Expand All @@ -42,8 +49,10 @@
* gRPC implementation of {@link ChannelEndpointCache}.
*
* <p>This cache creates and caches gRPC channels per address. It uses {@link
* InstantiatingGrpcChannelProvider#withEndpoint(String)} to create new channels with the same
* configuration but different endpoints, avoiding race conditions.
* InstantiatingGrpcChannelProvider#withEndpoint(String)} to create a provider for each address from
* the settings of the base provider, avoiding race conditions. Routed channels use their own
* keepalive settings and the authority of the default channel. When the base provider can use
* DirectPath, routed channels use ALTS.
*/
@InternalApi
class GrpcChannelEndpointCache implements ChannelEndpointCache {
Expand All @@ -61,6 +70,7 @@ class GrpcChannelEndpointCache implements ChannelEndpointCache {
private final GrpcChannelEndpoint defaultEndpoint;
private final String defaultAuthority;
@Nullable private final GrpcGcpEndpointChannelConfigurator endpointChannelConfigurator;
private final Supplier<ChannelCredentials> directPathCredentials;
private final AtomicBoolean isShutdown = new AtomicBoolean(false);

/**
Expand All @@ -79,8 +89,24 @@ public GrpcChannelEndpointCache(
InstantiatingGrpcChannelProvider channelProvider,
@Nullable GrpcGcpEndpointChannelConfigurator endpointChannelConfigurator)
throws IOException {
this(channelProvider, endpointChannelConfigurator, AltsChannelCredentials::create);
}

/**
* Creates a cache that builds routed DirectPath channels with {@code directPathCredentials}. The
* other constructors pass {@link AltsChannelCredentials#create()}. Tests pass their own
* credentials, so that they can point ALTS at a local handshaker service or connect to a
* plaintext test server.
*/
@VisibleForTesting
GrpcChannelEndpointCache(
InstantiatingGrpcChannelProvider channelProvider,
@Nullable GrpcGcpEndpointChannelConfigurator endpointChannelConfigurator,
Supplier<ChannelCredentials> directPathCredentials)
throws IOException {
this.baseProvider = channelProvider;
this.endpointChannelConfigurator = endpointChannelConfigurator;
this.directPathCredentials = directPathCredentials;
String defaultEndpoint = channelProvider.getEndpoint();
this.defaultEndpoint = new GrpcChannelEndpoint(defaultEndpoint, channelProvider);
this.defaultAuthority = this.defaultEndpoint.getChannel().authority();
Expand All @@ -103,7 +129,7 @@ public ChannelEndpoint get(String address) {
address,
addr -> {
try {
// Create a new provider with the same config but different endpoint.
// Create a new provider for addr from the settings of the base provider.
// This is thread-safe as withEndpoint() returns a new provider instance.
InstantiatingGrpcChannelProvider newProvider =
createProviderWithAuthorityOverride(addr);
Expand All @@ -127,6 +153,10 @@ public ChannelEndpoint getIfPresent(String address) {

@VisibleForTesting
InstantiatingGrpcChannelProvider createProviderWithAuthorityOverride(String address) {
// Read DirectPath eligibility from baseProvider. canUseDirectPath() returns false when the
// endpoint does not contain googleapis.com, so the provider for a server address such as
// 10.0.0.1:443 would return false and its channel would never use ALTS.
final boolean useDirectPath = baseProvider.canUseDirectPath();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we compute and cache this once in the constructor instead of calling canUseDirectPath() on every new routed endpoint? On Linux it reads /sys/class/dmi/id/product_name on every call without caching, so if DirectPath becomes the default in the future, this would add repeated file reads for Omni as well. Computing it once also ensures routed channels stay consistent with what the default channel did.

Also, when the cached flag is true, we should check that the routed endpoint provider cannot already use DirectPath before overriding its credentials (short-circuiting on the cached flag first). Otherwise, if a routed address ever contains googleapis.com, gax will already have created a DirectPath builder with channel credentials, which will hit the IllegalStateException fallback below and drop the google-c2p setup along with all interceptors and headers.

InstantiatingGrpcChannelProvider endpointProvider =
(InstantiatingGrpcChannelProvider) baseProvider.withEndpoint(address);
if (Objects.equals(defaultAuthority, address)) {
Expand All @@ -137,12 +167,27 @@ InstantiatingGrpcChannelProvider createProviderWithAuthorityOverride(String addr
builder.setKeepAliveTimeDuration(ROUTED_KEEPALIVE_TIME);
builder.setKeepAliveTimeoutDuration(ROUTED_KEEPALIVE_TIMEOUT);
builder.setKeepAliveWithoutCalls(Boolean.TRUE);
final Integer maxInboundMessageSize = builder.getMaxInboundMessageSize();
final Integer maxInboundMetadataSize = builder.getMaxInboundMetadataSize();
final com.google.api.core.ApiFunction<ManagedChannelBuilder, ManagedChannelBuilder>
baseConfigurator =
endpointChannelConfigurator == null ? builder.getChannelConfigurator() : null;
builder.setChannelConfigurator(
channelBuilder -> {
ManagedChannelBuilder effectiveBuilder = channelBuilder;
if (useDirectPath) {
// Call useDirectPathCredentials before the configurators below. The grpc-gcp
// configurator wraps channelBuilder in a builder that is not a NettyChannelBuilder.
// useDirectPathCredentials would replace that builder, so the routed channel would
// lose grpc-gcp and the settings that gax set on channelBuilder.
effectiveBuilder =
useDirectPathCredentials(
channelBuilder,
address,
directPathCredentials.get(),
maxInboundMessageSize,
maxInboundMetadataSize);
}
if (endpointChannelConfigurator != null) {
effectiveBuilder = endpointChannelConfigurator.configure(effectiveBuilder);
} else if (baseConfigurator != null) {
Expand All @@ -153,6 +198,60 @@ InstantiatingGrpcChannelProvider createProviderWithAuthorityOverride(String addr
return builder.build();
}

/**
* Returns a builder for channels to {@code address} that connect with {@code credentials}.
*
* <p>gax builds {@code channelBuilder} without DirectPath, because the address of a Spanner
* server does not contain googleapis.com. When {@code channelBuilder} is a {@link
* NettyChannelBuilder} that gax created without {@link ChannelCredentials}, this method sets
* {@code credentials} as the security of {@code channelBuilder} and returns {@code
* channelBuilder}. Its channels then keep the interceptors, header provider headers, user agent,
* executor, keepalive settings and size limits that gax set.
*
* <p>Otherwise this method leaves {@code channelBuilder} unchanged and returns a new builder with
* {@link #ROUTED_KEEPALIVE_TIME}, {@link #ROUTED_KEEPALIVE_TIMEOUT}, {@code
* maxInboundMessageSize} and {@code maxInboundMetadataSize}. The new builder does not get the
* other settings of {@code channelBuilder}, so its channels run without the interceptors and
* headers that gax added.
*/
@VisibleForTesting
static ManagedChannelBuilder<?> useDirectPathCredentials(
ManagedChannelBuilder<?> channelBuilder,
String address,
ChannelCredentials credentials,
@Nullable Integer maxInboundMessageSize,
@Nullable Integer maxInboundMetadataSize) {
if (channelBuilder instanceof NettyChannelBuilder) {
try {
// gRPC has no public API that changes the security of an existing builder.
InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
(NettyChannelBuilder) channelBuilder,
InternalNettyChannelCredentials.toNegotiator(credentials));
return channelBuilder;
Comment on lines +226 to +230

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add a short TODO here noting that using the internal Netty APIs and the fallback builder is a temporary workaround for testing, and that we should move this into gax-grpc before using it in production?

} catch (IllegalStateException e) {
// setProtocolNegotiatorFactory throws IllegalStateException when channelBuilder was
// created with ChannelCredentials. gax creates channelBuilder that way for mTLS and S2A.
}
Comment on lines +225 to +234

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using internal gRPC APIs (InternalNettyChannelBuilder and InternalNettyChannelCredentials) carries a high risk of compatibility issues across different gRPC versions. If a user runs an environment with a mismatched or upgraded gRPC version, these internal classes might be missing or have different method signatures, leading to LinkageError (such as NoSuchMethodError or NoClassDefFoundError).

Currently, only IllegalStateException is caught. To ensure the client does not crash and can safely fall back to the replacement builder, we should catch both Exception and LinkageError.

      try {
        // gRPC has no public API that changes the security of an existing builder.
        InternalNettyChannelBuilder.setProtocolNegotiatorFactory(
            (NettyChannelBuilder) channelBuilder,
            InternalNettyChannelCredentials.toNegotiator(credentials));
        return channelBuilder;
      } catch (Exception | LinkageError e) {
        // Fall back to replacement builder if setProtocolNegotiatorFactory fails.
        // This can happen if channelBuilder was created with ChannelCredentials (throws IllegalStateException),
        // or if internal gRPC APIs are incompatible/absent (throws LinkageError or other exceptions).
        logger.log(
            Level.FINE,
            "Failed to set protocol negotiator factory on NettyChannelBuilder, falling back to replacement builder",
            e);
      }

}
logger.log(
Level.FINE,
"Routed DirectPath channel for {0} does not get the interceptors and headers that gax adds",
address);
Comment on lines +231 to +239

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we log this at WARNING instead of FINE, and include the caught IllegalStateException instead of swallowing it? If a test run hits this fallback path, routed calls will silently lose Spanner's error, request-id, and metrics interceptors as well as headers and the configured executor, so it should be easy to spot in the logs.

ManagedChannelBuilder<?> replacement =
Grpc.newChannelBuilder(address, credentials)
.keepAliveTime(ROUTED_KEEPALIVE_TIME.toMillis(), TimeUnit.MILLISECONDS)
.keepAliveTimeout(ROUTED_KEEPALIVE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)
.keepAliveWithoutCalls(true)
.disableServiceConfigLookUp();
if (maxInboundMessageSize != null) {
replacement.maxInboundMessageSize(maxInboundMessageSize);
}
if (maxInboundMetadataSize != null) {
replacement.maxInboundMetadataSize(maxInboundMetadataSize);
}
return replacement;
}

@Override
public void evict(String address) {
if (defaultEndpoint.getAddress().equals(address)) {
Expand Down
Loading
Loading