Repository navigation
feat(spanner): add built-in tracing to Cloud Trace - #15064
uditdasari wants to merge 12 commits into
Conversation
Setting SPANNER_ENABLE_TRACING=true (or SpannerOptions.Builder#setEnableBuiltInTracing(true)) makes the client export its traces to Cloud Trace and turns on end to end tracing, without any OpenTelemetry setup in the application. It is off by default. This adds com.google.cloud.opentelemetry:exporter-trace and io.opentelemetry:opentelemetry-sdk-trace as compile dependencies for all applications, also when built-in tracing is off. They can conflict with other versions of these libraries that an application already uses.
There was a problem hiding this comment.
Code Review
This pull request introduces built-in tracing capabilities to the Google Cloud Spanner Java client using OpenTelemetry. It adds configuration options to SpannerOptions to enable built-in tracing and set a sampling rate, either programmatically or via environment variables. A new BuiltInTracingProvider class is introduced to manage and cache OpenTelemetry instances per project and sampling rate. The Spanner client implementation and RPC layers are updated to use this new tracing mechanism. Feedback on the changes suggests wrapping the Runtime.getRuntime().addShutdownHook call in BuiltInTracingProvider within a try-catch block to handle potential IllegalStateExceptions if the JVM is already shutting down.
| if (shutdownHook == null) { | ||
| shutdownHook = new Thread(this::shutdown); | ||
| Runtime.getRuntime().addShutdownHook(shutdownHook); | ||
| } |
There was a problem hiding this comment.
Registering a shutdown hook via Runtime.getRuntime().addShutdownHook can throw an IllegalStateException if the JVM is already in the process of shutting down. Since this call is outside the try-catch block, it can cause unexpected crashes for callers initializing or using a client during JVM shutdown. Wrapping the registration in a try-catch block for IllegalStateException resolves this safely.
if (shutdownHook == null) {
Thread hook = new Thread(this::shutdown);
try {
Runtime.getRuntime().addShutdownHook(hook);
shutdownHook = hook;
} catch (IllegalStateException e) {
// JVM is shutting down, ignore
}
}There was a problem hiding this comment.
Fixed in 00502ac. The hook is now registered before the instance is cached, inside a try/catch for IllegalStateException. If the JVM is already shutting down, the new instance is closed and built-in tracing is not used. reset() also removes the hook.
Use exporter-trace 0.33.0 so that its dependencies match the versions in the shared dependencies. Do not use built-in tracing when the client uses a universe domain other than googleapis.com. Only log the sampling rate when built-in tracing is enabled, and log which OpenTelemetry instance is used when built-in tracing is not used.
Built-in tracing now exports spans with the OpenTelemetry OTLP gRPC exporter to the Cloud Telemetry (OTLP) API instead of the Cloud Trace exporter, as recommended by Cloud Trace. The OpenTelemetry artifacts are already part of the shared dependencies, so no new third-party dependency is added. Spans carry the gcp.project_id resource attribute and the service name from OTEL_SERVICE_NAME. Built-in tracing is now also used when the configured OpenTelemetry instance has no enabled tracer, for example when an application uses OpenTelemetry only for metrics.
…en built-in tracing steps aside OpenTelemetry 1.66 and earlier report an empty tracer provider as enabled, so a metrics-only instance can make built-in tracing step aside. The log message now says the instance may have tracing, and that OpenTelemetry 1.67 or later is needed to detect a metrics-only instance.
…e current span The OpenTelemetry Java agent replaces the current context of the application, also when the agent itself is disabled. Spans of an OpenTelemetry SDK that is not the agent's own cannot then be set as the current span, which gives flat traces without server spans. Built-in tracing now checks this once and logs a warning instead of being used.
- Remember a failed exporter per project and sampling rate, so it is created and logged only once. - Do not record the metrics of the exporter in the global OpenTelemetry of the application. - Do not fail when the JVM is already shutting down, and remove the shutdown hook in reset(). - Log a warning once when OTEL_TRACES_SAMPLER_ARG is not a number between 0 and 1. - Log why built-in tracing is not used with the emulator, Spanner Omni, no credentials or another universe. - Log a credentials error once until the credentials work again, like the built-in metrics exporter. - Add tests for these cases, the builder settings, and enableOpenCensusTraces(), and use JUnit asserts.
…ILTIN_TRACING SPANNER_ENABLE_TRACING is easy to confuse with the existing SPANNER_ENABLE_END_TO_END_TRACING, SPANNER_ENABLE_API_TRACING and SPANNER_ENABLE_EXTENDED_TRACING switches. The new name matches setEnableBuiltInTracing and the built-in metrics switches.
| if (!isContextUsable()) { | ||
| return null; | ||
| } | ||
| List<Object> key = ImmutableList.of(projectId, samplingRate); |
There was a problem hiding this comment.
Caching these instances based on a key that contains only the projectId and samplingRate means that two different clients using different credentials still get the same OpenTelemetry instance. I don't think that is safe.
There was a problem hiding this comment.
Also, is it 100% guaranteed that projectId will not be null here?
There was a problem hiding this comment.
Fixed in 639020f. The instances are now keyed by project, sampling rate and the credentials object, compared by identity, because equals of some credentials types ignores the identity or depends on the current access token. Clients with different credentials objects get their own instance. To keep the number of instances bounded, at most 10 are created, and clients after that run without built-in tracing and log one warning.
The project id can't be null here. The ServiceOptions constructor throws when no project id is set or can be found, and the emulator gets a default project id.
|
|
||
| private synchronized void shutdown() { | ||
| for (OpenTelemetrySdk openTelemetry : openTelemetries.values()) { | ||
| openTelemetry.close(); |
There was a problem hiding this comment.
I think that this does a flush, which means that it executes a network operation. That is normally not a good idea in a synchronized method. In addition, this method is called from a shutdown hook. Shutdown hooks should preferably also be quick and preferably not execute a network call.
There was a problem hiding this comment.
Note also that the first OpenTelemetry.shutdown that fails will also stop this loop, so maybe put it in a simple try-catch-ignore block
There was a problem hiding this comment.
Fixed in 639020f. shutdown() now only holds the lock to copy the list of instances and mark the provider as shut down. It then shuts down all instances at the same time outside the lock, each in its own try/catch, and waits at most 10 seconds in total. Clients that are created after that do not use built-in tracing.
| return null; | ||
| } | ||
| if (shutdownHook == null) { | ||
| Thread hook = new Thread(this::shutdown); |
There was a problem hiding this comment.
See also my comment further down; I am not sure it is a good idea to call shutdown in a JVM shutdown hook. The shutdown method on this class flushes the currently buffered traces, which means that the JVM shutdown hook will be executing a potentially expensive network call.
There was a problem hiding this comment.
I kept the shutdown hook, because without it the spans of the last few seconds (up to the 5 second export interval) are lost on every normal exit, which can be most of the traces of a short-lived job. The OpenTelemetry autoconfigure module registers the same kind of hook by default (sdk.close(), which waits up to 10 seconds), and the built-in metrics also flush in a shutdown hook. To keep it short, the hook now shuts down all instances in parallel outside the lock, with one 10 second limit in total. In the end to end test, an application that exits right after a query sent its spans 174 ms after it started to exit.
|
|
||
| private static volatile TracingFramework activeTracingFramework; | ||
|
|
||
| static final double DEFAULT_BUILT_IN_TRACING_SAMPLING_RATE = 0.1; |
There was a problem hiding this comment.
This seems too high to me. I would rather say 0.01 or maybe even lower. I know that the feature is disabled by default, but someone who quickly enables it (maybe in a bit of a stressed situation) might easily end up with very many more traces than they expected.
| private static final String SPANNER_ENABLE_END_TO_END_TRACING = | ||
| "SPANNER_ENABLE_END_TO_END_TRACING"; | ||
| private static final String SPANNER_ENABLE_BUILTIN_TRACING = "SPANNER_ENABLE_BUILTIN_TRACING"; | ||
| private static final String OTEL_TRACES_SAMPLER_ARG = "OTEL_TRACES_SAMPLER_ARG"; |
There was a problem hiding this comment.
I think that we should stick to SPANNER_TRACING_SAMPLING_RATE. The meaning of OTEL_TRACES_SAMPLER_ARG is a bit different, depending on the sampler that is chosen (and as it is an env var that is 'owned' by OpenTelemetry, it could be that it allows even more values in the future than it does today).
There was a problem hiding this comment.
Changed in 639020f. The rate is now read from SPANNER_BUILTIN_TRACING_SAMPLING_RATE, and OTEL_TRACES_SAMPLER_ARG is no longer read.
| </dependency> | ||
| <dependency> | ||
| <groupId>io.opentelemetry</groupId> | ||
| <artifactId>opentelemetry-exporter-sender-grpc-managed-channel</artifactId> |
There was a problem hiding this comment.
Adding opentelemetry-exporter-sender-grpc-managed-channel on the runtime classpath registers UpstreamGrpcSenderProvider via META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider. For applications that already depend on opentelemetry-exporter-otlp with opentelemetry-exporter-sender-okhttp, OpenTelemetry's SenderUtil.resolveGrpcSenderProvider will log Multiple GrpcSenderProvider found (even when built-in tracing is off) and select a provider via HashMap iteration order (values().stream().findFirst()).
Relying on HashMap order to keep picking OkHttp is fragile, and if UpstreamGrpcSenderProvider is selected instead for a user's own OTLP gRPC exporter, it silently ignores sslContext/trustManager, retryPolicy, connectTimeout, maxRequestMessageSize, and enabledProtocols when no explicit ManagedChannel is set.
Could we avoid shipping the global GrpcSenderProvider SPI entry—for example, by passing a Spanner-internal ComponentLoader / GrpcSenderProvider backed by io.grpc.ManagedChannel to OtlpGrpcSpanExporterBuilder#setComponentLoader instead of depending on opentelemetry-exporter-sender-grpc-managed-channel, or keeping opentelemetry-exporter-sender-okhttp?
There was a problem hiding this comment.
Fixed in 639020f. The PR no longer depends on opentelemetry-exporter-sender-grpc-managed-channel. The built-in exporter gets a small Spanner GrpcSender on top of grpc-java through setComponentLoader, so no GrpcSenderProvider is registered for the application. A test checks that ServiceLoader finds no GrpcSenderProvider. In the end to end test, an application with its own OTLP exporter and the OkHttp sender kept using OkHttp without the Multiple GrpcSenderProvider found warning, with built-in tracing off and on.
- Use SPANNER_BUILTIN_TRACING_SAMPLING_RATE for the sampling rate and lower the default to 0.01. - Skip built-in tracing when GOOGLE_CLOUD_UNIVERSE_DOMAIN points to another universe. - Create one OpenTelemetry instance per project, sampling rate and credentials object, with at most 10 instances. - Send spans with a gRPC sender that is only given to the built-in exporter, instead of depending on opentelemetry-exporter-sender-grpc-managed-channel, which registers a global GrpcSenderProvider. - Shut down all instances in parallel outside the lock, with one 10 second limit, and stop creating instances after shutdown.
# Conflicts: # java-spanner/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerOptions.java
This adds built-in tracing. Setting
SPANNER_ENABLE_BUILTIN_TRACING=true(orSpannerOptions.Builder#setEnableBuiltInTracing(true)) makes the client export its traces to Cloud Trace and turns on end to end tracing, without any OpenTelemetry setup in the application. It is off by default, because Cloud Trace charges for the spans that are exported.Decisions to review
SPANNER_ENABLE_BUILTIN_TRACING. The design doc calls itSPANNER_ENABLE_TRACING, which is easy to confuse with the existingSPANNER_ENABLE_END_TO_END_TRACING,SPANNER_ENABLE_API_TRACINGandSPANNER_ENABLE_EXTENDED_TRACINGswitches. The new name matchessetEnableBuiltInTracingand the built-in metrics switches.SPANNER_BUILTIN_TRACING_SAMPLING_RATE(the design doc calls itSPANNER_TRACING_SAMPLING_RATE, renamed to match the switch). The default is 0.01 instead of the 0.1 in the design doc, so that turning it on quickly does not create many more traces than expected. A value that is not a number between 0 and 1 is ignored and a warning is logged.Tracer#isEnabled(), which needs OpenTelemetry 1.67 or later to recognize an instance that only has metrics.equalsof some credentials types ignores the identity or changes when the token is refreshed. At most 10 instances are created. Clients after that do not use built-in tracing, and a warning is logged once.setComponentLoader). No gRPC sender is registered for the whole application, so the OTLP exporters of the application keep using their own sender. The OkHttp sender is excluded.GOOGLE_CLOUD_UNIVERSE_DOMAIN), without credentials, with the emulator, with Spanner Omni, and when the OpenTelemetry Java agent is attached with its SDK disabled.enableOpenCensusTraces()after a client with built-in tracing was created now throws.SPANNER_ENABLE_BUILTIN_TRACINGalready works for JDBC and PGAdapter.What it does
telemetry.googleapis.com, which Cloud Trace recommends instead of the Cloud Trace exporter. The exporter uses the credentials of the client, and the spans carry thegcp.project_idresource attribute with the project of the client. The service name is taken fromOTEL_SERVICE_NAMEif that is set.BuiltInTracingGrpcSender, which uses grpc-java (already used by Spanner) and is only given to the built-in exporter.traceparentandx-goog-spanner-end-to-end-tracingare sent and Spanner adds its server side spans to the same trace.SPANNER_BUILTIN_TRACING_SAMPLING_RATEenvironment variable or withsetBuiltInTracingSamplingRate(double). A value inSPANNER_BUILTIN_TRACING_SAMPLING_RATEthat is not a number between 0 and 1 is ignored, and a warning is logged once when built-in tracing is enabled. The startup log of the client shows whether built-in tracing is enabled, and the sampling rate when it is enabled.ConnectionSpannerOptions.Builder#build()does not callSpannerOptions.Builder#build().traceparentheader and API tracing (if enabled separately) use the built-in instance. Metrics are not affected, and the exporter does not record its own metrics in the OpenTelemetry instance of the application.When it is not used
Tracer#isEnabled()), for example anOpenTelemetryset inSpannerOptionswith a tracer provider that exports spans, or a global OpenTelemetry registered by the application or by the OpenTelemetry Java agent. That configuration is used instead, end to end tracing is still turned on, and a log line says which instance is used. An OpenTelemetry instance that is only used for metrics does not disable built-in tracing.OTEL_SDK_DISABLED=true). The agent replaces the context of the application and only keeps its own spans in it, so built-in tracing would give flat traces without server spans. This is checked once per process, and a warning is logged.googleapis.com, set in the options or withGOOGLE_CLOUD_UNIVERSE_DOMAIN. The Telemetry API and Cloud Trace are not available in other universes. A log line says why built-in tracing is not used.Requirements
The project of the client needs the Telemetry API and the Cloud Trace API enabled, and the credentials need the
telemetry.traces.writepermission, which is included inroles/cloudtrace.agent,roles/telemetry.tracesWriterandroles/telemetry.writer. User credentials also need a quota project.Behavior for existing applications
SpannerOptions.enableOpenCensusTraces()after it has created a client or a connection, that call now throws, because the tracing framework is already set to OpenTelemetry. Calling it before creating any client still works, and then built-in tracing is not used.Dependencies
io.opentelemetry:opentelemetry-sdk-trace,io.opentelemetry:opentelemetry-exporter-otlpandio.opentelemetry:opentelemetry-commonare now compile dependencies. Their versions are managed by the OpenTelemetry BOM in the shared dependencies. The OkHttp sender of the OTLP exporter is excluded, and no other sender library is added, because the spans are sent with grpc-java. These dependencies are added for all applications, also when built-in tracing is off, and can conflict with other versions of these libraries that an application already uses. This should be called out in the release notes. The sender needs OpenTelemetry 1.59 or later, and Spanner already needs 1.60 or later for the built-in metrics.Testing
BuiltInTracingTestruns a client against a mock server and checks that the request carries a sampledtraceparentand the end to end tracing header, that the exported spans have the same trace id and thegcp.project_idresource attribute, that clients of the same project and credentials object share one instance and other projects get their own, that an OpenTelemetry instance with tracing is used instead of built-in tracing, that a metrics only OpenTelemetry instance (set in the options or global) does not disable built-in tracing, and that built-in tracing is not used without credentials, in another universe domain, or with OpenCensus. It also checks the request headers and the service name.BuiltInTracingTestalso checks that the builder settings win over the environment, howSPANNER_BUILTIN_TRACING_SAMPLING_RATEis parsed, how the universe domain is taken from the options orGOOGLE_CLOUD_UNIVERSE_DOMAIN, that built-in tracing is not used with the emulator or Spanner Omni, that a failing exporter is only created once, that the exporter does not record metrics in the global OpenTelemetry, that a credentials error is logged once until the credentials work again (the same as the built-in metrics exporter), thatenableOpenCensusTraces()throws after a client with built-in tracing, that the recorded metrics are the same with built-in tracing on and off, and that built-in tracing is not used when its spans cannot be the current span.BuiltInTracingTestchecks that clients with different credentials objects get different instances (also when the credentials are equal), that the instance is kept when the token is refreshed, that no instance is created after the limit of 10, that the built-in exporter sends spans with the credentials header to a gRPC server, that no gRPC sender is registered as a service, and that shutdown exports the spans of all instances without holding the lock.BuiltInTracingConnectionTestchecks that the Connection API spans and the Spanner spans are exported by built-in tracing.SpannerOptionsnow also stubgetTracingOpenTelemetry().GOOGLE_CLOUD_UNIVERSE_DOMAIN=example.combuilt-in tracing is not used. With the OpenTelemetry Java agent 2.33.1, the agent's OpenTelemetry instance is used and built-in tracing is not, and withOTEL_SDK_DISABLED=truebuilt-in tracing is not used and a warning is logged. The new sender and shutdown tests also pass with OpenTelemetry 1.60.End to end test
50 runs on 3 GCE VMs against a real Spanner instance, with the traces read back from Cloud Trace storage and the metrics from Cloud Monitoring. A separate reviewer judged the results from the raw output only. Covered:
TransactionManager, invalid SQL), the Connection API, DirectPath, and grpc-gcp with the dynamic channel pool.telemetry.traces.write(queries work, the exporter logs one warning per minute) and the default access scopes of a GCE VM (export works).A second run of 18 runs after the review changes covered the new sampling variable and default, shutdown, the new sender under load, on Java 8 and with OpenTelemetry 1.62, an application with its own OTLP exporter and the OkHttp sender, credentials objects and the limit of 10, and
GOOGLE_CLOUD_UNIVERSE_DOMAIN. A separate reviewer judged it from the raw output only, and all 18 runs met their criteria. With 50 threads for 2 minutes at 100% sampling, the client ran 479,541 queries (3.5 times more than in the first run). All 1,044 exports succeeded, with the same export time as before (p50 109 ms against 114 ms), and 534,019 spans were stored. The batch span processor dropped 425,066 spans because its queue was full, as the default batch settings send at most about 4,500 spans per second. A separate run with credentials that cannot write traces also passed: all 185 queries worked, all 44 exports were refused with permission denied (the Telemetry API counted the same 44 requests as 403), and after the first minute the exporter logged at most one warning per minute.Known limitations
setChannelProvider) skips the Spanner interceptors, so notraceparentis sent and there are no server spans. This is already the case with an application's own OpenTelemetry.Tracer#isEnabled()returns true for an OpenTelemetry instance that is only used for metrics, so built-in tracing is not used in that case. The log line says so.