Skip to content
Open
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 @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -74,7 +75,14 @@ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
? metricsCtx.getOperationName()
: defaultOperationName(method.getBareMethodName());

return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {
NetworkIoTracerFactory networkIoTracerFactory =
metrics.getNetworkIo() != null ? new NetworkIoTracerFactory() : null;
CallOptions effectiveCallOptions =
networkIoTracerFactory != null
? callOptions.withStreamTracerFactory(networkIoTracerFactory)
: callOptions;

return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, effectiveCallOptions)) {
private final AtomicBoolean ttfbRecorded = new AtomicBoolean(false);
private final AtomicLong ttfbStartNanos = new AtomicLong();
private final AtomicBoolean activeReleased = new AtomicBoolean(false);
Expand Down Expand Up @@ -162,6 +170,13 @@ public void onClose(Status status, Metadata trailers) {
metrics.recordServerUnreached(
otelContext, operationName, networkPath, errorType);
}
if (networkIoTracerFactory != null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we track bytes and network.path per ClientStreamTracer in streamCreated and streamClosed instead of aggregating across streams and flushing in onClose, so retried or hedged streams on different paths aren't misattributed and late callbacks aren't missed?

metrics.recordNetworkIo(
otelContext,
networkPath,
networkIoTracerFactory.getOutboundBytes(),
networkIoTracerFactory.getInboundBytes());
}
} finally {
releaseActive();
super.onClose(status, trailers);
Expand Down Expand Up @@ -287,4 +302,37 @@ private static boolean hasNonEmptyMetadata(Metadata metadata, Metadata.Key<Strin
String value = metadata.get(key);
return value != null && !value.isEmpty();
}

private static final class NetworkIoTracerFactory extends ClientStreamTracer.Factory {
private final AtomicLong outboundBytes = new AtomicLong();
private final AtomicLong inboundBytes = new AtomicLong();

@Override
public ClientStreamTracer newClientStreamTracer(
ClientStreamTracer.StreamInfo info, Metadata headers) {
return new ClientStreamTracer() {
@Override
public void outboundWireSize(long bytes) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ClientStreamTracer only counts framed and deframed message payloads (missing unconsumed HTTP/2 receive-window bytes on cancelled reads and TLS overhead); can we hook into the Netty socket layer for actual TCP bytes or clarify the metric description if this approximation is intentional?

if (bytes > 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();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,19 @@

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;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
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;
Expand All @@ -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;

Expand Down Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<Void, Void> 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<Void, Void> testCall = new TestClientCall<>(directPathAttrs);
TestChannel testChannel = new TestChannel(testCall);

debugInterceptor
.interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, testChannel)
.start(new TestListener<>(), new Metadata());
List<ClientStreamTracer.Factory> 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Can we also call inboundWireSize(0L) and inboundWireSize(-10L) here to cover its non-positive guard alongside outboundWireSize?

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<io.opentelemetry.api.common.Attributes, Long> 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<Void, Void> 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();
Expand Down Expand Up @@ -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;
Expand All @@ -1141,6 +1223,7 @@ private static final class TestChannel extends Channel {
@Override
public <RequestT, ResponseT> ClientCall<RequestT, ResponseT> newCall(
MethodDescriptor<RequestT, ResponseT> methodDescriptor, CallOptions callOptions) {
this.lastCallOptions = callOptions;
return (ClientCall<RequestT, ResponseT>) call;
}

Expand Down
Loading