Skip to content
Draft
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 @@ -331,7 +331,27 @@ private Tuple<StorageSettings, Opts<UserProject>> resolveSettingsAndOpts() throw
Collections.singletonList(InstantiatingGrpcChannelProvider.HardBoundTokenTypes.ALTS));
}

if (!NoopGrpcInterceptorProvider.INSTANCE.equals(grpcInterceptorProvider)) {
StorageClientMetrics clientMetrics = getStorageClientMetrics();
if (clientMetrics != null) {
StorageGrpcMetricsInterceptor metricsInterceptor =
new StorageGrpcMetricsInterceptor(clientMetrics, getClock(), endpoint);
GrpcInterceptorProvider combinedProvider =
grpcInterceptorProvider == null
|| NoopGrpcInterceptorProvider.INSTANCE.equals(grpcInterceptorProvider)
? () -> ImmutableList.of(metricsInterceptor)
: () -> {
List<ClientInterceptor> existing = grpcInterceptorProvider.getInterceptors();
if (existing == null || existing.isEmpty()) {
return ImmutableList.of(metricsInterceptor);
}
return ImmutableList.<ClientInterceptor>builder()
.addAll(existing)
.add(metricsInterceptor)
.build();
};
channelProviderBuilder.setInterceptorProvider(combinedProvider);
} else if (grpcInterceptorProvider != null
&& !NoopGrpcInterceptorProvider.INSTANCE.equals(grpcInterceptorProvider)) {
channelProviderBuilder.setInterceptorProvider(grpcInterceptorProvider);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/*
* 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.storage;

import com.google.api.core.ApiClock;
import io.grpc.Attributes;
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.Grpc;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.context.Context;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jspecify.annotations.Nullable;

/** gRPC client interceptor that records call metrics such as rpc.client.call.duration. */
final class StorageGrpcMetricsInterceptor implements ClientInterceptor {

private final StorageClientMetrics metrics;
private final ApiClock clock;
@Nullable private final String defaultServerAddress;
private final boolean isDirectPathEndpoint;

StorageGrpcMetricsInterceptor(
StorageClientMetrics metrics, ApiClock clock, @Nullable String defaultEndpoint) {
this.metrics = metrics;
this.clock = clock;
this.defaultServerAddress =
OpenTelemetryBootstrappingUtils.extractServerAddress(defaultEndpoint);
this.isDirectPathEndpoint =
defaultEndpoint != null && defaultEndpoint.trim().startsWith("google-c2p:///");
}

@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
if (metrics == null || metrics.getRpcClientCallDuration() == null) {
return next.newCall(method, callOptions);
}

String shortMethod = extractShortMethodName(method.getFullMethodName());
String resolvedServerAddress =
defaultServerAddress != null
? defaultServerAddress
: OpenTelemetryBootstrappingUtils.extractServerAddress(next.authority());
final String serverAddress = resolvedServerAddress != null ? resolvedServerAddress : "";

StorageMetricsContext metricsCtx = StorageMetricsContext.from(callOptions);
Context otelContext = metricsCtx != null ? metricsCtx.getOtelContext() : Context.current();

return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
@Override
public void start(Listener<RespT> responseListener, Metadata headers) {
long startTimeNanos = clock.nanoTime();
AtomicBoolean callRecorded = new AtomicBoolean(false);

super.start(
new SimpleForwardingClientCallListener<RespT>(responseListener) {
@Override
public void onClose(Status status, Metadata trailers) {
try {
if (callRecorded.compareAndSet(false, true)
&& metrics.getRpcClientCallDuration() != null) {
double durationSeconds =
Math.max(0.0, (clock.nanoTime() - startTimeNanos) / 1_000_000_000.0);
String networkPath = detectNetworkPath(getAttributes(), isDirectPathEndpoint);
String statusCode =
status != null && status.getCode() != null
? status.getCode().name()
: StorageErrorTypeMapper.STATUS_UNKNOWN;
String errorType =
status != null && !status.isOk() && status.getCause() != null
? StorageErrorTypeMapper.mapThrowable(status.asRuntimeException())
: StorageErrorTypeMapper.mapGrpcStatus(status);

AttributesBuilder attrBuilder =
metrics
.clientAttributesBuilder()
.put(StorageClientMetrics.KEY_RPC_SYSTEM_NAME, "grpc")
.put(StorageClientMetrics.KEY_RPC_METHOD, shortMethod)
.put(StorageClientMetrics.KEY_RPC_RESPONSE_STATUS_CODE, statusCode)
.put(StorageClientMetrics.KEY_NETWORK_PATH, networkPath)
.put(StorageClientMetrics.KEY_SERVER_ADDRESS, serverAddress)
.put(StorageClientMetrics.KEY_ERROR_TYPE, errorType);

metrics
.getRpcClientCallDuration()
.record(durationSeconds, attrBuilder.build(), otelContext);
}
} finally {
super.onClose(status, trailers);
}
}
},
headers);
}
};
}

static String extractShortMethodName(@Nullable String fullMethodName) {
if (fullMethodName == null || fullMethodName.isEmpty()) {
return "UNKNOWN";
}
int idx = fullMethodName.lastIndexOf('/');
if (idx >= 0 && idx < fullMethodName.length() - 1) {
return fullMethodName.substring(idx + 1);
}
return fullMethodName;
}

static String detectNetworkPath(
@Nullable Attributes callAttributes, boolean isDirectPathEndpoint) {
SocketAddress remoteAddr =
callAttributes != null ? callAttributes.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR) : null;
if (remoteAddr instanceof InetSocketAddress) {
InetAddress inetAddr = ((InetSocketAddress) remoteAddr).getAddress();
if (inetAddr != null) {
return isDirectPathIp(inetAddr)
? StorageClientMetrics.NETWORK_PATH_DIRECTPATH
: StorageClientMetrics.NETWORK_PATH_CLOUDPATH;
}
}
if (isDirectPathEndpoint) {
return StorageClientMetrics.NETWORK_PATH_DIRECTPATH;
}
return StorageClientMetrics.NETWORK_PATH_UNKNOWN;
}
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved

static boolean isDirectPathIp(InetAddress addr) {
byte[] b = addr.getAddress();
if (b.length == 4) {
return (b[0] & 0xFF) == 34 && (b[1] & 0xFF) == 126 && ((b[2] & 0xFF) & 0xC0) == 0;
}
if (b.length == 16) {
return (b[0] & 0xFF) == 0x20
&& (b[1] & 0xFF) == 0x01
&& (b[2] & 0xFF) == 0x48
&& (b[3] & 0xFF) == 0x60
&& (b[4] & 0xFF) == 0x80
&& ((b[5] & 0xFF) & 0xC0) == 0x40;
}
return false;
}
}
Loading
Loading