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 @@ -46,6 +46,7 @@
import io.opentelemetry.api.metrics.MeterProvider;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.time.Clock;
import java.time.Duration;
Expand Down Expand Up @@ -176,6 +177,12 @@ public HttpRequestInitializer decorateWithMetrics(@Nullable HttpRequestInitializ
return new StorageHttpMetricsInterceptor(initializer, metrics, getClock());
}

@InternalApi
public static OutputStream trackCurrentMetricsActivity(OutputStream out) {
StorageMetricsContext ctx = StorageMetricsContext.current();
return ctx != null ? ctx.wrapActivityTracking(out) : out;
}

public static class Builder extends StorageOptions.Builder {

private StorageRetryStrategy storageRetryStrategy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package com.google.cloud.storage;

import com.google.api.core.ApiClock;
import com.google.api.core.NanoClock;
import io.opentelemetry.api.OpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
Expand Down Expand Up @@ -141,11 +143,13 @@ static StorageClientMetrics fromOptions(StorageOptions options) {
if (serverAddress != null && !serverAddress.isEmpty()) {
baseBuilder.put(KEY_SERVER_ADDRESS, serverAddress);
}
ApiClock clock = options.getClock() != null ? options.getClock() : NanoClock.getDefaultClock();
return new StorageClientMetrics(
meter,
clientAttributes,
baseBuilder.build(),
ownedMeterProvider,
clock,
/* enableOtelMetrics= */ true,
options.isEnableOtelDebugMetrics());
}
Expand Down Expand Up @@ -177,6 +181,7 @@ static StorageClientMetrics create(
clientAttributes,
clientAttributes,
ownedMeterProvider,
NanoClock.getDefaultClock(),
enableOtelMetrics,
enableOtelDebugMetrics);
}
Expand All @@ -202,17 +207,20 @@ static StorageClientMetrics create(
private final Attributes clientAttributes;
private final Attributes baseAttributes;
@Nullable private final SdkMeterProvider ownedMeterProvider;
private final ApiClock clock;

private StorageClientMetrics(
Meter meter,
Attributes clientAttributes,
Attributes baseAttributes,
@Nullable SdkMeterProvider ownedMeterProvider,
ApiClock clock,
boolean enableOtelMetrics,
boolean enableOtelDebugMetrics) {
this.clientAttributes = clientAttributes;
this.baseAttributes = baseAttributes;
this.ownedMeterProvider = ownedMeterProvider;
this.clock = clock;

if (enableOtelMetrics) {
this.rpcClientCallDuration =
Expand Down Expand Up @@ -453,11 +461,11 @@ Attributes attachClientAttributes(@Nullable Attributes other) {
}

StorageMetricsContext createContext(String operationName) {
return StorageMetricsContext.create(this, operationName, baseAttributes);
return StorageMetricsContext.create(this, operationName, baseAttributes, clock);
}

StorageMetricsContext createMultiStepContext(String operationName) {
return StorageMetricsContext.createForMultiStep(this, operationName, baseAttributes);
return StorageMetricsContext.createForMultiStep(this, operationName, baseAttributes, clock);
}

void recordRpcCallDuration(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,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 @@ -812,13 +812,16 @@ public void downloadTo(BlobId blob, OutputStream outputStream, BlobSourceOption.
ResultRetryAlgorithm<?> algorithm = retryAlgorithmManager.getForObjectsGet(pb, optionsMap);
StorageMetricsContext metricsContext =
StorageClientMetrics.createContext(getOptions().getStorageClientMetrics(), "ReadObject");
OutputStream streamingOutput =
metricsContext != null
? metricsContext.wrapActivityTracking(countingOutputStream)
: countingOutputStream;
retrier.run(
algorithm,
callable(
() -> {
try {
storageRpc.read(
pb, optionsMap, countingOutputStream.getCount(), countingOutputStream);
storageRpc.read(pb, optionsMap, countingOutputStream.getCount(), streamingOutput);
} finally {
if (metricsContext != null) {
metricsContext.setResponseBytes(countingOutputStream.getCount());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
import io.opentelemetry.api.common.AttributesBuilder;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
Expand All @@ -47,6 +49,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 @@ -60,6 +64,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 @@ -75,6 +80,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 @@ -283,7 +289,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 @@ -335,6 +341,7 @@ private void recordAttemptFailure(
String networkPath = resolveNetworkPath();
Attributes attemptBase = buildAttemptBaseAttributes(metrics);
recordErrorCounter(metrics, attemptBase, errorType, networkPath);
recordHttpReadStallIfTimeout(metrics, e);
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
if (metrics.getAttempts() != null) {
AttributesBuilder builder =
attemptBase.toBuilder()
Expand Down Expand Up @@ -379,6 +386,80 @@ 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;
}
long lastActivity = lastActivityNanos.get();
long elapsedNanos = Math.max(0L, clock.nanoTime() - lastActivity);
double stallSeconds = elapsedNanos / 1_000_000_000.0;
metrics.recordStallDuration(
otelContext, stallSeconds, operationName, READ_OBJECT_RPC_METHOD, resolveNetworkPath());
}

void markActivity() {
if (metrics == null || metrics.getStallDuration() == null) {
return;
}
lastActivityNanos.set(clock.nanoTime());
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
}

OutputStream wrapActivityTracking(OutputStream out) {
if (metrics == null
|| metrics.getStallDuration() == null
|| out instanceof ActivityTrackingOutputStream) {
return out;
}
return new ActivityTrackingOutputStream(out, this);
}

private static final class ActivityTrackingOutputStream extends OutputStream {
private final OutputStream delegate;
private final StorageMetricsContext metricsContext;

ActivityTrackingOutputStream(OutputStream delegate, StorageMetricsContext metricsContext) {
this.delegate = delegate;
this.metricsContext = metricsContext;
}

@Override
public void write(int b) throws IOException {
delegate.write(b);
metricsContext.markActivity();
}

@Override
public void write(byte[] b) throws IOException {
delegate.write(b);
metricsContext.markActivity();
}

@Override
public void write(byte[] b, int off, int len) throws IOException {
delegate.write(b, off, len);
metricsContext.markActivity();
}

@Override
public void flush() throws IOException {
delegate.flush();
}

@Override
public void close() throws IOException {
delegate.close();
}
}

private void recordErrorCounter(
StorageClientMetrics metrics, Attributes attemptBase, String errorType, String networkPath) {
if (metrics.getErrors() != null) {
Expand Down Expand Up @@ -499,6 +580,7 @@ void markHttpResponseReceived() {
}

int incrementAttempts() {
markActivity();
return attemptCount.incrementAndGet();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -902,8 +902,10 @@ public byte[] load(StorageObject from, Map<Option, ?> options) {
}
HttpResponse response = getRequest.executeMedia();
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream trackedOut = HttpStorageOptions.trackCurrentMetricsActivity(out);
boolean shouldValidate = HttpStorageRpcHasherHelper.INSTANCE.shouldValidate(response);
OutputStream activeStream = HttpStorageRpcHasherHelper.INSTANCE.wrap(out, shouldValidate);
OutputStream activeStream =
HttpStorageRpcHasherHelper.INSTANCE.wrap(trackedOut, shouldValidate);
response.download(activeStream);
byte[] content = out.toByteArray();
HttpStorageRpcHasherHelper.INSTANCE.validate(response, activeStream);
Expand Down Expand Up @@ -966,9 +968,10 @@ public long read(
mediaHttpDownloader.setDirectDownloadEnabled(true);

HttpResponse response = req.executeMedia();
OutputStream trackedOut = HttpStorageOptions.trackCurrentMetricsActivity(outputStream);
boolean shouldValidate = HttpStorageRpcHasherHelper.INSTANCE.shouldValidate(response);
OutputStream activeStream =
HttpStorageRpcHasherHelper.INSTANCE.wrap(outputStream, shouldValidate);
HttpStorageRpcHasherHelper.INSTANCE.wrap(trackedOut, shouldValidate);
response.download(activeStream);
// Validate checksum
HttpStorageRpcHasherHelper.INSTANCE.validate(response, activeStream);
Expand Down
Loading
Loading