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 @@ -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 =
Expand Down Expand Up @@ -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) {
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,12 @@ public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(
? metricsCtx.getOperationName()
: defaultOperationName(method.getBareMethodName());

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

return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, effectiveCallOptions)) {
private final AtomicBoolean ttfbRecorded = new AtomicBoolean(false);
private final AtomicBoolean ttfbReanchored = new AtomicBoolean(false);
private final AtomicLong ttfbStartNanos = new AtomicLong();
Expand Down Expand Up @@ -295,4 +301,61 @@ private static boolean hasNonEmptyMetadata(Metadata metadata, Metadata.Key<Strin
String value = metadata.get(key);
return value != null && !value.isEmpty();
}

/**
* {@link ClientStreamTracer.Factory} that tracks gRPC framed/deframed message wire bytes per
* stream via {@link ClientStreamTracer#outboundWireSize} and {@link
* ClientStreamTracer#inboundWireSize} (excluding unconsumed HTTP/2 flow-control window bytes and
* TLS overhead). Uses the public gRPC {@link ClientStreamTracer} API rather than hooking {@code
* grpc-netty-shaded} socket internals, matching {@code grpc-java} OpenTelemetry conventions, and
* attributes bytes to each stream's transport {@code network.path} on {@link
* ClientStreamTracer#streamClosed}.
*/
private static final class NetworkIoTracerFactory extends ClientStreamTracer.Factory {
private final StorageClientMetrics metrics;
private final Context otelContext;

NetworkIoTracerFactory(StorageClientMetrics metrics, Context otelContext) {
this.metrics = metrics;
this.otelContext = otelContext;
}

@Override
public ClientStreamTracer newClientStreamTracer(
ClientStreamTracer.StreamInfo info, Metadata headers) {
return new ClientStreamTracer() {
private final AtomicLong outboundBytes = new AtomicLong();
private final AtomicLong inboundBytes = new AtomicLong();
private final AtomicBoolean flushed = new AtomicBoolean(false);
private volatile String streamNetworkPath = StorageClientMetrics.NETWORK_PATH_UNKNOWN;

@Override
public void streamCreated(Attributes transportAttrs, Metadata headers) {
streamNetworkPath = detectNetworkPath(transportAttrs);
}

@Override
public void outboundWireSize(long bytes) {
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
if (bytes > 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());
}
}
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -789,8 +788,7 @@ public void call(
ReadObjectRequest request,
ResponseObserver<ReadObjectResponse> responseObserver,
ApiCallContext context) {
StreamController controller = Mockito.mock(StreamController.class);
responseObserver.onStart(controller);
responseObserver.onStart(TestUtils.nullStreamController());
responseObserver.onResponse(
ReadObjectResponse.newBuilder()
.setChecksummedData(
Expand Down
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
Loading
Loading