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..0b965e6c0062 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 @@ -349,8 +349,10 @@ private StorageClientMetrics( meter .counterBuilder(METRIC_GCP_STORAGE_CLIENT_NETWORK_IO) .setDescription( - "Bytes read from and written to the TCP connections to Cloud Storage, by" - + " network.io.direction (receive, transmit). gRPC only.") + "gRPC framed/deframed message wire bytes exchanged with Cloud Storage via" + + " ClientStreamTracer (excluding unconsumed HTTP/2 flow-control window" + + " bytes and TLS overhead), by network.io.direction (receive, transmit)." + + " gRPC only.") .setUnit("By") .build(); this.credentialRefreshDuration = @@ -562,6 +564,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 74a786a6abe7..ab8300550a04 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,12 @@ public ClientCall interceptCall( ? metricsCtx.getOperationName() : defaultOperationName(method.getBareMethodName()); - return new SimpleForwardingClientCall(next.newCall(method, callOptions)) { + CallOptions effectiveCallOptions = + metrics.getNetworkIo() != null + ? callOptions.withStreamTracerFactory(new NetworkIoTracerFactory(metrics, otelContext)) + : callOptions; + + return new SimpleForwardingClientCall(next.newCall(method, effectiveCallOptions)) { private final AtomicBoolean ttfbRecorded = new AtomicBoolean(false); private final AtomicBoolean ttfbReanchored = new AtomicBoolean(false); private final AtomicLong ttfbStartNanos = new AtomicLong(); @@ -295,4 +301,61 @@ private static boolean hasNonEmptyMetadata(Metadata metadata, Metadata.Key 0) { + outboundBytes.addAndGet(bytes); + } + } + + @Override + public void inboundWireSize(long bytes) { + if (bytes > 0) { + inboundBytes.addAndGet(bytes); + } + } + + @Override + public void streamClosed(Status status) { + if (flushed.compareAndSet(false, true)) { + metrics.recordNetworkIo( + otelContext, streamNetworkPath, outboundBytes.get(), inboundBytes.get()); + } + } + }; + } + } } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java index 4f081073d3a9..74630551115a 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/GrpcStorageImplTest.java @@ -40,7 +40,6 @@ import com.google.api.gax.rpc.NotFoundException; import com.google.api.gax.rpc.ResponseObserver; import com.google.api.gax.rpc.ServerStreamingCallable; -import com.google.api.gax.rpc.StreamController; import com.google.api.gax.rpc.UnaryCallable; import com.google.cloud.NoCredentials; import com.google.cloud.WriteChannel; @@ -789,8 +788,7 @@ public void call( ReadObjectRequest request, ResponseObserver responseObserver, ApiCallContext context) { - StreamController controller = Mockito.mock(StreamController.class); - responseObserver.onStart(controller); + responseObserver.onStart(TestUtils.nullStreamController()); responseObserver.onResponse( ReadObjectResponse.newBuilder() .setChecksummedData( 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 bc106eeac9df..dda9adde06dc 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 @@ -44,6 +44,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; @@ -82,6 +83,7 @@ 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; @@ -753,6 +755,168 @@ 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.streamCreated(directPathAttrs, new Metadata()); + stream1.outboundWireSize(128L); + stream1.outboundWireSize(0L); + stream1.outboundWireSize(-10L); + stream1.inboundWireSize(512L); + stream1.inboundWireSize(0L); + stream1.inboundWireSize(-10L); + stream1.streamClosed(Status.OK); + ClientStreamTracer stream2 = factories.get(0).newClientStreamTracer(streamInfo, new Metadata()); + stream2.streamCreated(directPathAttrs, new Metadata()); + stream2.outboundWireSize(256L); + stream2.inboundWireSize(1024L); + stream2.streamClosed(Status.OK); + 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 = + networkIoAttrs( + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageClientMetrics.NETWORK_IO_DIRECTION_TRANSMIT); + io.opentelemetry.api.common.Attributes receiveAttrs = + networkIoAttrs( + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageClientMetrics.NETWORK_IO_DIRECTION_RECEIVE); + assertThat(pointsByAttrs).containsExactly(transmitAttrs, 384L, receiveAttrs, 1536L); + + // Zero-byte stream should not alter existing counts or create new points. + TestClientCall zeroCall = new TestClientCall<>(Attributes.EMPTY); + TestChannel zeroChannel = new TestChannel(zeroCall); + debugInterceptor + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, zeroChannel) + .start(new TestListener<>(), new Metadata()); + ClientStreamTracer zeroStream = + zeroChannel + .lastCallOptions + .getStreamTracerFactories() + .get(0) + .newClientStreamTracer(streamInfo, new Metadata()); + zeroStream.streamCreated(Attributes.EMPTY, new Metadata()); + zeroStream.streamClosed(Status.UNAVAILABLE); + 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_networkIo_attributesBytesPerStreamAcrossDirectPathAndCloudPath() + throws Exception { + StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor(); + Attributes cloudPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("142.250.1.1"), 443)) + .build(); + Attributes directPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("34.126.1.2"), 443)) + .build(); + // Call attributes differ from stream1's transportAttrs to prove per-stream attribution. + TestClientCall testCall = new TestClientCall<>(directPathAttrs); + TestChannel testChannel = new TestChannel(testCall); + debugInterceptor + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, testChannel) + .start(new TestListener<>(), new Metadata()); + ClientStreamTracer.Factory factory = + testChannel.lastCallOptions.getStreamTracerFactories().get(0); + ClientStreamTracer.StreamInfo streamInfo = ClientStreamTracer.StreamInfo.newBuilder().build(); + + ClientStreamTracer cloudStream = factory.newClientStreamTracer(streamInfo, new Metadata()); + cloudStream.streamCreated(cloudPathAttrs, new Metadata()); + cloudStream.outboundWireSize(100L); + cloudStream.inboundWireSize(200L); + cloudStream.streamClosed(Status.UNAVAILABLE); + // Duplicate streamClosed must be ignored by the once-per-stream flush guard. + cloudStream.streamClosed(Status.UNAVAILABLE); + + ClientStreamTracer directStream = factory.newClientStreamTracer(streamInfo, new Metadata()); + directStream.streamCreated(directPathAttrs, new Metadata()); + directStream.outboundWireSize(300L); + directStream.inboundWireSize(400L); + directStream.streamClosed(Status.OK); + + // Bytes are flushed per stream on streamClosed without waiting for onClose. + testCall.close(Status.OK, new Metadata()); + + MetricData metricData = findMetric(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO); + assertThat(metricData).isNotNull(); + Map pointsByAttrs = + metricData.getLongSumData().getPoints().stream() + .collect(Collectors.toMap(LongPointData::getAttributes, LongPointData::getValue)); + assertThat(pointsByAttrs) + .containsExactly( + networkIoAttrs( + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageClientMetrics.NETWORK_IO_DIRECTION_TRANSMIT), + 100L, + networkIoAttrs( + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageClientMetrics.NETWORK_IO_DIRECTION_RECEIVE), + 200L, + networkIoAttrs( + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageClientMetrics.NETWORK_IO_DIRECTION_TRANSMIT), + 300L, + networkIoAttrs( + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageClientMetrics.NETWORK_IO_DIRECTION_RECEIVE), + 400L); + } + + private static io.opentelemetry.api.common.Attributes networkIoAttrs( + String networkPath, String direction) { + return 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, networkPath) + .put(StorageClientMetrics.KEY_NETWORK_IO_DIRECTION, direction) + .build(); + } + @Test public void interceptCall_requestActive_balancesWhenStartThrows() { StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor(); @@ -1393,6 +1557,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; @@ -1402,6 +1567,7 @@ private static final class TestChannel extends Channel { @Override public ClientCall newCall( MethodDescriptor methodDescriptor, CallOptions callOptions) { + this.lastCallOptions = callOptions; return (ClientCall) call; }