diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java index bd20259e8097..c1e4a7946ae6 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java @@ -562,6 +562,29 @@ void recordServerUnreached( serverUnreached.add(1L, attributes, otelContext); } + void recordNetworkIo( + Context otelContext, String networkPath, long transmitBytes, long receiveBytes) { + if (networkIo == null) { + return; + } + if (transmitBytes > 0) { + Attributes transmitAttributes = + baseAttributes.toBuilder() + .put(KEY_NETWORK_PATH, networkPath) + .put(KEY_NETWORK_IO_DIRECTION, NETWORK_IO_DIRECTION_TRANSMIT) + .build(); + networkIo.add(transmitBytes, transmitAttributes, otelContext); + } + if (receiveBytes > 0) { + Attributes receiveAttributes = + baseAttributes.toBuilder() + .put(KEY_NETWORK_PATH, networkPath) + .put(KEY_NETWORK_IO_DIRECTION, NETWORK_IO_DIRECTION_RECEIVE) + .build(); + networkIo.add(receiveBytes, receiveAttributes, otelContext); + } + } + @Nullable static StorageMetricsContext createContext( @Nullable StorageClientMetrics metrics, String operationName) { diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java index 6dbdbd1ecfd5..8e2f80c4f484 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java @@ -26,6 +26,7 @@ import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; +import io.grpc.ClientStreamTracer; import io.grpc.ForwardingClientCall.SimpleForwardingClientCall; import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener; import io.grpc.Grpc; @@ -74,7 +75,14 @@ public ClientCall interceptCall( ? metricsCtx.getOperationName() : defaultOperationName(method.getBareMethodName()); - return new SimpleForwardingClientCall(next.newCall(method, callOptions)) { + NetworkIoTracerFactory networkIoTracerFactory = + metrics.getNetworkIo() != null ? new NetworkIoTracerFactory() : null; + CallOptions effectiveCallOptions = + networkIoTracerFactory != null + ? callOptions.withStreamTracerFactory(networkIoTracerFactory) + : callOptions; + + return new SimpleForwardingClientCall(next.newCall(method, effectiveCallOptions)) { private final AtomicBoolean ttfbRecorded = new AtomicBoolean(false); private final AtomicLong ttfbStartNanos = new AtomicLong(); private final AtomicBoolean activeReleased = new AtomicBoolean(false); @@ -162,6 +170,13 @@ public void onClose(Status status, Metadata trailers) { metrics.recordServerUnreached( otelContext, operationName, networkPath, errorType); } + if (networkIoTracerFactory != null) { + metrics.recordNetworkIo( + otelContext, + networkPath, + networkIoTracerFactory.getOutboundBytes(), + networkIoTracerFactory.getInboundBytes()); + } } finally { releaseActive(); super.onClose(status, trailers); @@ -287,4 +302,37 @@ private static boolean hasNonEmptyMetadata(Metadata metadata, Metadata.Key 0) { + outboundBytes.addAndGet(bytes); + } + } + + @Override + public void inboundWireSize(long bytes) { + if (bytes > 0) { + inboundBytes.addAndGet(bytes); + } + } + }; + } + + long getOutboundBytes() { + return outboundBytes.get(); + } + + long getInboundBytes() { + return inboundBytes.get(); + } + } } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java index 0dfa3db86ac7..8dd1235cc604 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java @@ -18,9 +18,11 @@ import static com.google.common.truth.Truth.assertThat; +import com.google.cloud.NoCredentials; import com.google.common.collect.ImmutableList; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentType; @@ -28,6 +30,7 @@ import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.CollectionRegistration; import io.opentelemetry.sdk.metrics.export.MetricReader; @@ -38,6 +41,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Function; import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -420,6 +424,52 @@ public void createContext_nullMetrics_returnsNull() { assertThat(StorageClientMetrics.createMultiStepContext(null, "WriteObject")).isNull(); } + @Test + public void recordNetworkIo_skipsNonPositiveOrDisabled() { + SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + StorageClientMetrics standardMetrics = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(provider) + .build() + .getStorageClientMetrics(); + standardMetrics.recordNetworkIo( + Context.current(), StorageClientMetrics.NETWORK_PATH_DIRECTPATH, 100L, 200L); + assertThat(findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO)).isNull(); + + StorageClientMetrics debugMetrics = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(true) + .setMeterProvider(provider) + .build() + .getStorageClientMetrics(); + debugMetrics.recordNetworkIo( + Context.current(), StorageClientMetrics.NETWORK_PATH_DIRECTPATH, 0L, -5L); + assertThat(findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO)).isNull(); + + debugMetrics.recordNetworkIo( + Context.current(), StorageClientMetrics.NETWORK_PATH_CLOUDPATH, 128L, 0L); + MetricData metricData = findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO); + assertThat(metricData).isNotNull(); + assertThat(metricData.getLongSumData().getPoints()).hasSize(1); + LongPointData point = metricData.getLongSumData().getPoints().iterator().next(); + assertThat(point.getValue()).isEqualTo(128L); + assertThat(point.getAttributes().get(StorageClientMetrics.KEY_NETWORK_IO_DIRECTION)) + .isEqualTo(StorageClientMetrics.NETWORK_IO_DIRECTION_TRANSMIT); + } + + private @Nullable MetricData findMetric(String name) { + return reader.collectAllMetrics().stream() + .filter(m -> m.getName().equals(name)) + .findFirst() + .orElse(null); + } + static final class TestMetricReader implements MetricReader { private final MetricReader delegate = InMemoryMetricReader.create(); final AtomicBoolean shutdownCalled = new AtomicBoolean(false); diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java index 08a77f968d85..b49e03e0e19e 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java @@ -36,6 +36,7 @@ import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; +import io.grpc.ClientStreamTracer; import io.grpc.Grpc; import io.grpc.Metadata; import io.grpc.MethodDescriptor; @@ -66,10 +67,12 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; import javax.net.ssl.SSLException; import javax.security.sasl.AuthenticationException; import org.jspecify.annotations.Nullable; @@ -669,6 +672,84 @@ public void interceptCall_serverUnreached_directPathAndCloudPathRules() throws E null); } + @Test + public void interceptCall_networkIo_tracksWireBytesWhenDebugEnabled() throws Exception { + // Debug disabled: must not attach a stream tracer or record network.io. + TestClientCall standardCall = new TestClientCall<>(Attributes.EMPTY); + TestChannel standardChannel = new TestChannel(standardCall); + interceptor + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, standardChannel) + .start(new TestListener<>(), new Metadata()); + standardCall.close(Status.OK, new Metadata()); + assertThat(standardChannel.lastCallOptions.getStreamTracerFactories()).isEmpty(); + assertThat(findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO)).isNull(); + + // Debug enabled: accumulates across streams and skips non-positive/zero-byte calls. + StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor(); + Attributes directPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("34.126.1.2"), 443)) + .build(); + TestClientCall testCall = new TestClientCall<>(directPathAttrs); + TestChannel testChannel = new TestChannel(testCall); + + debugInterceptor + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, testChannel) + .start(new TestListener<>(), new Metadata()); + List factories = + testChannel.lastCallOptions.getStreamTracerFactories(); + assertThat(factories).hasSize(1); + ClientStreamTracer.StreamInfo streamInfo = ClientStreamTracer.StreamInfo.newBuilder().build(); + ClientStreamTracer stream1 = factories.get(0).newClientStreamTracer(streamInfo, new Metadata()); + stream1.outboundWireSize(128L); + stream1.outboundWireSize(0L); + stream1.outboundWireSize(-10L); + stream1.inboundWireSize(512L); + ClientStreamTracer stream2 = factories.get(0).newClientStreamTracer(streamInfo, new Metadata()); + stream2.outboundWireSize(256L); + stream2.inboundWireSize(1024L); + testCall.close(Status.OK, new Metadata()); + + MetricData metricData = findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO); + assertThat(metricData).isNotNull(); + assertThat(metricData.getUnit()).isEqualTo("By"); + Map pointsByAttrs = + metricData.getLongSumData().getPoints().stream() + .collect(Collectors.toMap(LongPointData::getAttributes, LongPointData::getValue)); + io.opentelemetry.api.common.Attributes transmitAttrs = + io.opentelemetry.api.common.Attributes.builder() + .put(StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, StorageClientMetrics.SERVICE_STORAGE) + .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version()) + .put( + StorageClientMetrics.KEY_GCP_CLIENT_ARTIFACT, StorageClientMetrics.ARTIFACT_STORAGE) + .put(StorageClientMetrics.KEY_RPC_SYSTEM_NAME, "grpc") + .put(StorageClientMetrics.KEY_SERVER_ADDRESS, "storage.googleapis.com") + .put( + StorageClientMetrics.KEY_NETWORK_PATH, StorageClientMetrics.NETWORK_PATH_DIRECTPATH) + .put( + StorageClientMetrics.KEY_NETWORK_IO_DIRECTION, + StorageClientMetrics.NETWORK_IO_DIRECTION_TRANSMIT) + .build(); + io.opentelemetry.api.common.Attributes receiveAttrs = + transmitAttrs.toBuilder() + .put( + StorageClientMetrics.KEY_NETWORK_IO_DIRECTION, + StorageClientMetrics.NETWORK_IO_DIRECTION_RECEIVE) + .build(); + assertThat(pointsByAttrs).containsExactly(transmitAttrs, 384L, receiveAttrs, 1536L); + + // Zero-byte call should not alter existing counts or create new points. + TestClientCall zeroCall = new TestClientCall<>(Attributes.EMPTY); + debugInterceptor + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(zeroCall)) + .start(new TestListener<>(), new Metadata()); + zeroCall.close(Status.UNAVAILABLE, new Metadata()); + MetricData afterZero = findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO); + assertThat(afterZero.getLongSumData().getPoints()).hasSize(2); + } + @Test public void interceptCall_requestActive_balancesWhenStartThrows() { StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor(); @@ -1132,6 +1213,7 @@ void close(Status status, Metadata trailers) { private static final class TestChannel extends Channel { private final TestClientCall call; + CallOptions lastCallOptions; TestChannel(TestClientCall call) { this.call = call; @@ -1141,6 +1223,7 @@ private static final class TestChannel extends Channel { @Override public ClientCall newCall( MethodDescriptor methodDescriptor, CallOptions callOptions) { + this.lastCallOptions = callOptions; return (ClientCall) call; }