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 @@ -126,6 +126,7 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
}

long totalRemaining = Buffers.totalRemaining(dsts, offset, length);
markMetricsActivity();
try {
// According to the contract of Retrying#run it's possible for sbc to be null even after
// invocation. However, the function we provide is guaranteed to return non-null or throw
Expand All @@ -150,6 +151,7 @@ public long read(ByteBuffer[] dsts, int offset, int length) throws IOException {
}
return totalRead;
} catch (Exception t) {
recordHttpReadStall(t);
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
if (resultRetryAlgorithm.shouldRetry(t, null)) {
// if our retry algorithm COULD allow a retry, continue the loop and allow trying to
// open the stream again.
Expand Down Expand Up @@ -209,6 +211,20 @@ public void close() throws IOException {
}
}

private void markMetricsActivity() {
StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.markActivity();
}
}

private void recordHttpReadStall(Throwable error) {
StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
metricsContext.recordHttpReadStallIfTimeout(error);
}
}

private void recordMidStreamRetry(Throwable error) {
StorageMetricsContext metricsContext = retrier.getMetricsContext();
if (metricsContext != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,23 @@ static String mapThrowable(@Nullable Throwable t) {
return mapThrowable(t, 0);
}

static boolean hasSocketTimeoutCause(@Nullable Throwable t) {
Throwable current = t;
int depth = 0;
while (current != null && depth < MAX_CAUSE_DEPTH) {
if (current instanceof SocketTimeoutException) {
return true;
}
Throwable next = current.getCause();
if (next == current) {
break;
}
current = next;
depth++;
}
return false;
}

static @Nullable String extractRpcStatusCode(@Nullable Throwable t) {
Throwable curr = t;
int depth = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ final class StorageMetricsContext {
private static final ThreadLocal<Runnable> WATCHDOG_TIMEOUT_CALLBACK = new ThreadLocal<>();
private static final long HTTP_STATUS_OK = 200L;
private static final long HTTP_STATUS_UNSET = 0L;
private static final String READ_OBJECT_OPERATION = "ReadObject";
private static final String READ_OBJECT_RPC_METHOD = "google.storage.v2.Storage/ReadObject";

@Nullable private final StorageClientMetrics metrics;
private final String operationName;
Expand All @@ -59,6 +61,7 @@ final class StorageMetricsContext {
private final AtomicInteger attemptCount = new AtomicInteger(0);
private final AtomicLong requestBytes = new AtomicLong(0L);
private final AtomicLong responseBytes = new AtomicLong(0L);
private final AtomicLong lastActivityNanos;
@Nullable private volatile String networkPath;

private StorageMetricsContext(
Expand All @@ -74,6 +77,7 @@ private StorageMetricsContext(
this.baseAttributes = requireNonNull(baseAttributes, "baseAttributes cannot be null");
this.clock = requireNonNull(clock, "clock cannot be null");
this.startTimeNanos = startTimeNanos;
this.lastActivityNanos = new AtomicLong(startTimeNanos);
this.otelContext = requireNonNull(otelContext, "otelContext cannot be null");
this.recordOperationOnRetrierExit = recordOperationOnRetrierExit;
}
Expand Down Expand Up @@ -282,7 +286,7 @@ private void recordResponseBodySize(StorageClientMetrics metrics, Attributes bod
return;
}
long respBytes = responseBytes.get();
if ("ReadObject".equals(operationName) && respBytes >= 0) {
if (READ_OBJECT_OPERATION.equals(operationName) && respBytes >= 0) {
metrics.getResponseBodySize().record(respBytes, bodySizeAttributes, otelContext);
}
}
Expand Down Expand Up @@ -334,6 +338,7 @@ private void recordAttemptFailure(
String networkPath = resolveNetworkPath();
Attributes attemptBase = buildAttemptBaseAttributes(metrics);
recordErrorCounter(metrics, attemptBase, errorType, networkPath);
recordHttpReadStallIfTimeout(metrics, e);

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.

For StorageImpl.downloadTo and readAllBytes, lastActivityNanos isn't updated while bytes stream, so a mid-stream SocketTimeoutException will inflate stall.duration with prior transfer time; can we refresh activity as bytes are read and add a test?

if (metrics.getAttempts() != null) {
AttributesBuilder builder =
attemptBase.toBuilder()
Expand Down Expand Up @@ -371,6 +376,28 @@ void recordRetry(@Nullable StorageClientMetrics metrics, Throwable priorError) {
StorageErrorTypeMapper.mapThrowable(priorError));
}

void recordHttpReadStallIfTimeout(Throwable e) {
recordHttpReadStallIfTimeout(this.metrics, e);
}

private void recordHttpReadStallIfTimeout(
@Nullable StorageClientMetrics metrics, @Nullable Throwable e) {
if (metrics == null
|| metrics.getStallDuration() == null
|| !READ_OBJECT_OPERATION.equals(operationName)
|| !"http".equals(baseAttributes.get(StorageClientMetrics.KEY_RPC_SYSTEM_NAME))
|| !StorageErrorTypeMapper.hasSocketTimeoutCause(e)) {
return;
}
double stallSeconds = (clock.nanoTime() - lastActivityNanos.get()) / 1_000_000_000.0;

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: Read lastActivityNanos.get() before clock.nanoTime() and clamp to >= 0 so concurrent updates or clock skew can't record a negative duration.

metrics.recordStallDuration(
otelContext, stallSeconds, operationName, READ_OBJECT_RPC_METHOD, resolveNetworkPath());
}

void markActivity() {
lastActivityNanos.set(clock.nanoTime());

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 return early in markActivity() when metrics == null || metrics.getStallDuration() == null to skip clock.nanoTime() when debug metrics are off, and reuse it in incrementAttempts()?

}

private void recordErrorCounter(
StorageClientMetrics metrics, Attributes attemptBase, String errorType, String networkPath) {
if (metrics.getErrors() != null) {
Expand Down Expand Up @@ -483,6 +510,7 @@ GrpcCallContext attach(@Nullable GrpcCallContext context) {
}

int incrementAttempts() {
lastActivityNanos.set(clock.nanoTime());
return attemptCount.incrementAndGet();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.testing.http.MockLowLevelHttpRequest;
import com.google.api.client.testing.http.MockLowLevelHttpResponse;
import com.google.api.core.ApiClock;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.retrying.BasicResultRetryAlgorithm;
import com.google.api.gax.retrying.RetrySettings;
import com.google.api.services.storage.Storage;
import com.google.api.services.storage.model.StorageObject;
import com.google.cloud.NoCredentials;
Expand All @@ -40,6 +42,7 @@
import com.google.common.collect.ImmutableMap;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
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.testing.exporter.InMemoryMetricReader;
Expand All @@ -48,16 +51,19 @@
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
Expand Down Expand Up @@ -560,6 +566,164 @@ private static void assertMidStreamRetryRecorded(Collection<MetricData> collecte
assertThat(attemptsTotal).isEqualTo(2L);
}

@Test
public void read_httpSocketTimeout_recordsStallDurationForOpenAndMidStream() throws IOException {
InMemoryMetricReader reader = InMemoryMetricReader.create();
SdkMeterProvider provider = SdkMeterProvider.builder().registerMetricReader(reader).build();
AtomicLong nanos = new AtomicLong(1_000_000_000L);
ApiClock fakeClock =
new ApiClock() {
@Override
public long nanoTime() {
return nanos.get();
}

@Override
public long millisTime() {
return nanos.get() / 1_000_000L;
}
};
HttpStorageOptions options =
StorageOptions.http()
.setProjectId("test-project")
.setCredentials(NoCredentials.getInstance())
.setClock(fakeClock)
.setRetrySettings(
RetrySettings.newBuilder()
.setInitialRetryDelayDuration(Duration.ZERO)
.setMaxRetryDelayDuration(Duration.ZERO)
.setMaxAttempts(3)
.build())
.setEnableOtelMetrics(true)
.setEnableOtelDebugMetrics(true)
.setMeterProvider(provider)
.build();
StorageClientMetrics metrics = options.getStorageClientMetrics();
StorageMetricsContext ctx =
StorageMetricsContext.createForMultiStep(
metrics,
"ReadObject",
metrics.createMultiStepContext("ReadObject").getBaseAttributes(),
fakeClock);

AtomicInteger openCalls = new AtomicInteger(0);
HttpTransport transport =
new HttpTransport() {
@Override
protected LowLevelHttpRequest buildRequest(String method, String url) {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() throws IOException {
int call = openCalls.incrementAndGet();
if (call == 1) {
// Open attempt stalls for 1.2s -> recorded via Retrying.recordAttemptFailure.
nanos.addAndGet(1_200_000_000L);
throw new SocketTimeoutException("open read timed out");
}
if (call == 2) {
// Deliver 5 bytes, then stall 0.8s mid-stream (retryable SocketTimeoutException).
InputStream partialThenTimeout =
new SequenceInputStream(
new ByteArrayInputStream(Arrays.copyOf(CONTENT_BYTES, 5)),
new InputStream() {
@Override
public int read() throws IOException {
nanos.addAndGet(800_000_000L);
throw new SocketTimeoutException("retryable mid-stream timeout");
}
});
return new MockLowLevelHttpResponse()
.setStatusCode(200)
.setContent(partialThenTimeout)
.addHeader("x-goog-generation", "12345");
}
// Call 3: terminal non-retryable mid-stream SocketTimeoutException after 0.5s.
InputStream terminalTimeout =
new InputStream() {
@Override
public int read() throws IOException {
nanos.addAndGet(500_000_000L);
throw new SocketTimeoutException("terminal mid-stream timeout");
}
};
return new MockLowLevelHttpResponse()
.setStatusCode(200)
.setContent(terminalTimeout)
.addHeader("x-goog-generation", "12345");
}
};
}
};
Storage storageClient =
new Storage.Builder(transport, GsonFactory.getDefaultInstance(), null)
.setApplicationName("test")
.build();
ApiaryReadRequest req =
new ApiaryReadRequest(
new StorageObject().setBucket("bucket").setName("blob"),
ImmutableMap.of(),
ByteRangeSpec.nullRange());

try (ApiaryUnbufferedReadableByteChannel channel =
new ApiaryUnbufferedReadableByteChannel(
req,
storageClient,
SettableApiFuture.create(),
options.createRetrier().withMetricsContext(ctx),
new BasicResultRetryAlgorithm<Object>() {

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 reuse the existing retryIf helper below instead of an inline BasicResultRetryAlgorithm?

@Override
public boolean shouldRetry(Throwable previousThrowable, Object previousResponse) {
return previousThrowable != null
&& !String.valueOf(previousThrowable.getMessage()).contains("terminal")
&& (previousThrowable.getCause() == null
|| !String.valueOf(previousThrowable.getCause().getMessage())
.contains("terminal"));
}
},
Hasher.noop())) {
ByteBuffer firstChunk = ByteBuffer.allocate(5);
assertThat(channel.read(new ByteBuffer[] {firstChunk}, 0, 1)).isEqualTo(5L);
// Simulate 10s of application processing between read() calls; must not inflate stall.
nanos.addAndGet(10_000_000_000L);
assertThrows(
SocketTimeoutException.class,
() -> channel.read(new ByteBuffer[] {ByteBuffer.allocate(16)}, 0, 1));
}

MetricData stallMetric =
reader.collectAllMetrics().stream()
.filter(
m ->
m.getName()
.equals(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_STALL_DURATION))
.findFirst()
.orElse(null);
assertThat(stallMetric).isNotNull();
assertThat(stallMetric.getUnit()).isEqualTo("s");
assertThat(stallMetric.getHistogramData().getPoints()).hasSize(1);
HistogramPointData point = stallMetric.getHistogramData().getPoints().iterator().next();
assertThat(point.getCount()).isEqualTo(3L);
assertThat(point.getSum()).isWithin(0.0001).of(2.5);
assertThat(point.getAttributes())
.isEqualTo(
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, "http")
.put(StorageClientMetrics.KEY_SERVER_ADDRESS, "storage.googleapis.com")
.put(StorageClientMetrics.KEY_GCP_STORAGE_OPERATION, "ReadObject")
.put(StorageClientMetrics.KEY_RPC_METHOD, "google.storage.v2.Storage/ReadObject")
.put(
StorageClientMetrics.KEY_NETWORK_PATH,
StorageClientMetrics.NETWORK_PATH_CLOUDPATH)
.build());
}

private static BasicResultRetryAlgorithm<Object> retryIf(Predicate<Throwable> shouldRetry) {
return new BasicResultRetryAlgorithm<Object>() {
@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,30 @@ public void extractHttpStatusCode_extractsAndBoundsDepth() {
assertThat(StorageErrorTypeMapper.extractHttpStatusCode(deep)).isNull();
}

@Test
public void hasSocketTimeoutCause_detectsAndBoundsDepth() {
assertThat(StorageErrorTypeMapper.hasSocketTimeoutCause(null)).isFalse();
assertThat(StorageErrorTypeMapper.hasSocketTimeoutCause(new SocketTimeoutException("read")))
.isTrue();
assertThat(
StorageErrorTypeMapper.hasSocketTimeoutCause(
new StorageException(new IOException(new SocketTimeoutException("nested")))))
.isTrue();
assertThat(StorageErrorTypeMapper.hasSocketTimeoutCause(new ConnectException("refused")))
.isFalse();

Throwable deep = new SocketTimeoutException("too deep");
for (int i = 0; i < 25; i++) {
deep = new RuntimeException("wrap " + i, deep);
}
assertThat(StorageErrorTypeMapper.hasSocketTimeoutCause(deep)).isFalse();

RuntimeException cycleA = new RuntimeException("cycleA");
RuntimeException cycleB = new RuntimeException("cycleB", cycleA);
cycleA.initCause(cycleB);
assertThat(StorageErrorTypeMapper.hasSocketTimeoutCause(cycleA)).isFalse();
}

private static WatchdogTimeoutException createWatchdogTimeoutException() throws Exception {
Constructor<WatchdogTimeoutException> ctor =
WatchdogTimeoutException.class.getDeclaredConstructor(String.class, boolean.class);
Expand Down
Loading
Loading