Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add opt-in flag and ClientInterceptor to propagate trace context for Spanner end to end tracing #3162

Merged
merged 33 commits into from
Sep 27, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
df54343
feat(spanner): Add x-goog-spanner-end-to-end-tracing header for reque…
nareshz Jun 3, 2024
b4864da
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Jun 13, 2024
290f01e
Add Grpc Telemetry client interceptor for trace context propagation
nareshz Jun 17, 2024
3c92b26
Remove print statement
nareshz Jun 17, 2024
3671173
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Jun 18, 2024
9379106
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Jun 25, 2024
5033b1b
copy grpc telemetry client interceptor code
nareshz Jul 10, 2024
d7c778a
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Jul 10, 2024
4613e29
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Jul 11, 2024
7c39b82
rename spanner option for end to end tracing
nareshz Jul 11, 2024
d2ac8b4
add test for custom client interceptor code
nareshz Jul 15, 2024
3eb5e47
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Jul 15, 2024
233acd2
resolve comments
nareshz Jul 17, 2024
71a8f39
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 7, 2024
1883fed
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 9, 2024
01aa679
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 9, 2024
be7d426
Merge branch 'e2e-tracing-header' into grpc-telemetry-client-interceptor
nareshz Aug 9, 2024
ab71745
Make trace context interceptor conditional based on client opt-in
nareshz Aug 9, 2024
2035d59
resolve comments
nareshz Aug 9, 2024
6af5e04
reformat code
nareshz Aug 13, 2024
0aa51ff
resolve comments
nareshz Aug 14, 2024
39269c0
fix clirr build failure
nareshz Aug 14, 2024
d2fd1c8
fix lint errors
nareshz Aug 14, 2024
2b9409b
combine enable/disable fn into single fn
nareshz Aug 19, 2024
b62b3c0
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 19, 2024
e12cd0f
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 21, 2024
0446fb5
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 21, 2024
aa729a0
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Aug 27, 2024
0febebc
Merge branch 'main' of https://github.com/googleapis/java-spanner int…
nareshz Sep 25, 2024
b3a6d31
Rename server side tracing to spanner tracing
nareshz Sep 25, 2024
117c279
Rename spanner tracing to end to end tracing
nareshz Sep 26, 2024
a982c69
fix comments
nareshz Sep 27, 2024
0a2622d
Fix lint error
nareshz Sep 27, 2024
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 @@ -158,6 +158,7 @@ public class SpannerOptions extends ServiceOptions<Spanner, SpannerOptions> {
private final OpenTelemetry openTelemetry;
private final boolean enableApiTracing;
private final boolean enableExtendedTracing;
private final boolean enableServerSideTracing;

enum TracingFramework {
OPEN_CENSUS,
Expand Down Expand Up @@ -664,6 +665,7 @@ protected SpannerOptions(Builder builder) {
openTelemetry = builder.openTelemetry;
enableApiTracing = builder.enableApiTracing;
enableExtendedTracing = builder.enableExtendedTracing;
enableServerSideTracing = builder.enableServerSideTracing;
}

/**
Expand Down Expand Up @@ -799,6 +801,7 @@ public static class Builder
private OpenTelemetry openTelemetry;
private boolean enableApiTracing = SpannerOptions.environment.isEnableApiTracing();
private boolean enableExtendedTracing = SpannerOptions.environment.isEnableExtendedTracing();
private boolean enableServerSideTracing = false;

private static String createCustomClientLibToken(String token) {
return token + " " + ServiceOptions.getGoogApiClientLibName();
Expand Down Expand Up @@ -864,6 +867,7 @@ protected Builder() {
this.useVirtualThreads = options.useVirtualThreads;
this.enableApiTracing = options.enableApiTracing;
this.enableExtendedTracing = options.enableExtendedTracing;
this.enableServerSideTracing = options.enableServerSideTracing;
}

@Override
Expand Down Expand Up @@ -1391,6 +1395,24 @@ public Builder setEnableExtendedTracing(boolean enableExtendedTracing) {
return this;
}

/**
* Enable spanner server side tracing. Enabling this option will create the trace
* spans at the Spanner layer. By default, server side tracing is disabled.
*/
public Builder enableServerSideTracing() {
nareshz marked this conversation as resolved.
Show resolved Hide resolved
nareshz marked this conversation as resolved.
Show resolved Hide resolved
this.enableServerSideTracing = true;
return this;
}

/**
* Disable spanner server side tracing. If server side is disabled, trace
* spans won't be created at the Spanner layer.
*/
public Builder disableServerSideTracing() {
this.enableServerSideTracing = false;
return this;
}

@SuppressWarnings("rawtypes")
@Override
public SpannerOptions build() {
Expand Down Expand Up @@ -1480,7 +1502,7 @@ public static void enableOpenCensusTraces() {
*/
@ObsoleteApi(
"The OpenCensus project is deprecated. Use enableOpenTelemetryTraces to switch to OpenTelemetry traces")
static void resetActiveTracingFramework() {
public static void resetActiveTracingFramework() {
nareshz marked this conversation as resolved.
Show resolved Hide resolved
activeTracingFramework = null;
}

Expand Down Expand Up @@ -1681,6 +1703,14 @@ public boolean isEnableExtendedTracing() {
return enableExtendedTracing;
}

/**
* Returns whether Spanner server side tracing is enabled. If this option is enabled then trace spans
* will be created at the Spanner layer.
*/
public boolean isServerSideTracingEnabled() {
return enableServerSideTracing;
}

/** Returns the default query options to use for the specific database. */
public QueryOptions getDefaultQueryOptions(DatabaseId databaseId) {
// Use the specific query options for the database if any have been specified. These have
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ public class GapicSpannerRpc implements SpannerRpc {
private static final ConcurrentMap<String, RateLimiter> ADMINISTRATIVE_REQUESTS_RATE_LIMITERS =
new ConcurrentHashMap<>();
private final boolean leaderAwareRoutingEnabled;
private final boolean serverSideTracingEnabled;
private final int numChannels;
private final boolean isGrpcGcpExtensionEnabled;

Expand Down Expand Up @@ -321,6 +322,7 @@ public GapicSpannerRpc(final SpannerOptions options) {
this.callCredentialsProvider = options.getCallCredentialsProvider();
this.compressorName = options.getCompressorName();
this.leaderAwareRoutingEnabled = options.isLeaderAwareRoutingEnabled();
this.serverSideTracingEnabled = options.isServerSideTracingEnabled();
this.numChannels = options.getNumChannels();
this.isGrpcGcpExtensionEnabled = options.isGrpcGcpExtensionEnabled();

Expand All @@ -346,6 +348,8 @@ public GapicSpannerRpc(final SpannerOptions options) {
MoreObjects.firstNonNull(
options.getInterceptorProvider(),
SpannerInterceptorProvider.createDefault(options.getOpenTelemetry())))
// This sets the trace context headers.
.withTraceContext(serverSideTracingEnabled, options.getOpenTelemetry())
// This sets the response compressor (Server -> Client).
.withEncoding(compressorName))
.setHeaderProvider(headerProviderWithUserAgent)
Expand Down Expand Up @@ -1988,6 +1992,9 @@ <ReqT, RespT> GrpcCallContext newCallContext(
if (routeToLeader && leaderAwareRoutingEnabled) {
context = context.withExtraHeaders(metadataProvider.newRouteToLeaderHeader());
}
if (serverSideTracingEnabled) {
context = context.withExtraHeaders(metadataProvider.newServerSideTracingHeader());
}
if (callCredentialsProvider != null) {
CallCredentials callCredentials = callCredentialsProvider.getCallCredentials();
if (callCredentials != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ SpannerInterceptorProvider withEncoding(String encoding) {
return this;
}

SpannerInterceptorProvider withTraceContext(boolean serverSideTracingEnabled, OpenTelemetry openTelemetry) {
if (serverSideTracingEnabled) {
return with(new TraceContextInterceptor(openTelemetry));
}
return this;
}

@Override
public List<ClientInterceptor> getInterceptors() {
return clientInterceptors;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ class SpannerMetadataProvider {
private final Map<Metadata.Key<String>, String> headers;
private final String resourceHeaderKey;
private static final String ROUTE_TO_LEADER_HEADER_KEY = "x-goog-spanner-route-to-leader";
private static final String SERVER_SIDE_TRACING_HEADER_KEY = "x-goog-spanner-end-to-end-tracing";
private static final Pattern[] RESOURCE_TOKEN_PATTERNS = {
Pattern.compile("^(?<headerValue>projects/[^/]*/instances/[^/]*/databases/[^/]*)(.*)?"),
Pattern.compile("^(?<headerValue>projects/[^/]*/instances/[^/]*)(.*)?")
};

private static final Map<String, List<String>> ROUTE_TO_LEADER_HEADER_MAP =
ImmutableMap.of(ROUTE_TO_LEADER_HEADER_KEY, Collections.singletonList("true"));
private static final Map<String, List<String>> SERVER_SIDE_TRACING_HEADER_MAP =
ImmutableMap.of(SERVER_SIDE_TRACING_HEADER_KEY, Collections.singletonList("true"));

private SpannerMetadataProvider(Map<String, String> headers, String resourceHeaderKey) {
this.resourceHeaderKey = resourceHeaderKey;
Expand Down Expand Up @@ -89,6 +92,10 @@ Map<String, List<String>> newRouteToLeaderHeader() {
return ROUTE_TO_LEADER_HEADER_MAP;
}

Map<String, List<String>> newServerSideTracingHeader() {
return SERVER_SIDE_TRACING_HEADER_MAP;
}

private Map<Metadata.Key<String>, String> constructHeadersAsMetadata(
Map<String, String> headers) {
ImmutableMap.Builder<Metadata.Key<String>, String> headersAsMetadataBuilder =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/*
* Copyright 2024 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
*
* https://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.spi.v1;

import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.propagation.TextMapPropagator;
import io.opentelemetry.context.propagation.TextMapSetter;

nareshz marked this conversation as resolved.
Show resolved Hide resolved
/**
* Intercepts all gRPC calls and injects trace context related headers to propagate trace context to
* Spanner. This class takes reference from OpenTelemetry's JAVA instrumentation library for gRPC.
* https://github.com/open-telemetry/opentelemetry-java-instrumentation/blob/9ecf7965aa455d41ea8cc0761b6c6b6eeb106324/instrumentation/grpc-1.6/library/src/main/java/io/opentelemetry/instrumentation/grpc/v1_6/TracingClientInterceptor.java#L27
*/
class TraceContextInterceptor implements ClientInterceptor {

private final TextMapPropagator textMapPropagator;

TraceContextInterceptor(OpenTelemetry openTelemetry) {
this.textMapPropagator = openTelemetry.getPropagators().getTextMapPropagator();
}

enum MetadataSetter implements TextMapSetter<Metadata> {
INSTANCE;

@SuppressWarnings("null")
@Override
public void set(Metadata carrier, String key, String value) {
carrier.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value);
}
}

private static final class NoopSimpleForwardingClientCallListener<RespT>
extends SimpleForwardingClientCallListener<RespT> {
public NoopSimpleForwardingClientCallListener(ClientCall.Listener<RespT> responseListener) {
super(responseListener);
}
}

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
Context parentContext = Context.current();
textMapPropagator.inject(parentContext, headers, MetadataSetter.INSTANCE);
super.start(new NoopSimpleForwardingClientCallListener<RespT>(responseListener), headers);
}
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,24 @@ public void testLeaderAwareRoutingEnablement() {
.isLeaderAwareRoutingEnabled());
}

@Test
public void testServerSideTracingEnablement() {
// Test that end to end tracing is disabled by default.
assertFalse(SpannerOptions.newBuilder().setProjectId("p").build().isServerSideTracingEnabled());
assertTrue(
SpannerOptions.newBuilder()
.setProjectId("p")
.enableServerSideTracing()
.build()
.isServerSideTracingEnabled());
assertFalse(
SpannerOptions.newBuilder()
.setProjectId("p")
.disableServerSideTracing()
.build()
.isServerSideTracingEnabled());
}

@Test
public void testSetDirectedReadOptions() {
final DirectedReadOptions directedReadOptions =
Expand Down
Loading
Loading