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 @@ -455,6 +455,9 @@ protected void onResponseImpl(ReadObjectResponse response) {

@Override
protected void onErrorImpl(Throwable t) {
if (t instanceof WatchdogTimeoutException) {
StorageMetricsContext.notifyWatchdogTimeout();
}
if (t instanceof CancellationException) {
cancellation.set(t);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,8 +339,7 @@ private StorageClientMetrics(
meter
.histogramBuilder(METRIC_GCP_STORAGE_CLIENT_STALL_DURATION)
.setDescription(
"Stall timeout after which a read attempt was aborted while waiting for the"
+ " initial response.")
"Duration of stalled streaming read or write attempts before watchdog timeout.")
.setUnit("s")
.setExplicitBucketBoundariesAdvice(
OpenTelemetryBootstrappingUtils.latencyHistogramBoundaries())
Expand Down Expand Up @@ -585,6 +584,24 @@ void recordNetworkIo(
}
}

void recordStallDuration(
Context otelContext,
double durationSeconds,
String operationName,
String rpcMethod,
String networkPath) {
if (stallDuration == null) {
return;
}
Attributes attributes =
baseAttributes.toBuilder()
.put(KEY_GCP_STORAGE_OPERATION, operationName)
.put(KEY_RPC_METHOD, rpcMethod)
.put(KEY_NETWORK_PATH, networkPath)
.build();
stallDuration.record(durationSeconds, attributes, otelContext);
}

@Nullable
static StorageMetricsContext createContext(
@Nullable StorageClientMetrics metrics, String operationName) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import io.grpc.MethodDescriptor;
import io.grpc.Status;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
Expand Down Expand Up @@ -116,6 +117,7 @@ private void startWithMetrics(
new SimpleForwardingClientCallListener<RespT>(responseListener) {
private boolean receivedServerHeaders;
private boolean headerHasUploadId;
private long lastActivityNanos = startTimeNanos;
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved

@Override
public void onHeaders(Metadata headers) {
Expand All @@ -131,10 +133,12 @@ public void onHeaders(Metadata headers) {

@Override
public void onMessage(@Nullable RespT message) {
long now = clock.nanoTime();
lastActivityNanos = now;

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 update lastActivityNanos after super.onMessage(message) returns so time spent blocked in ReadObjectObserver's queue isn't counted as server stall duration?

// The first response message from the server (including metadata-only
// responses for 0-byte objects) marks Time To First Byte (TTFB).
if (ttfbRecorded.compareAndSet(false, true)) {
double ttfbSeconds = (clock.nanoTime() - ttfbStartNanos.get()) / 1_000_000_000.0;
double ttfbSeconds = (now - ttfbStartNanos.get()) / 1_000_000_000.0;
String networkPath = detectNetworkPath(getAttributes());
metrics.recordTtfb(otelContext, operationName, ttfbSeconds, networkPath);
}
Expand All @@ -143,14 +147,56 @@ public void onMessage(@Nullable RespT message) {

@Override
public void onClose(Status status, Metadata trailers) {
try {
double durationSeconds = (clock.nanoTime() - startTimeNanos) / 1_000_000_000.0;
String networkPath = detectNetworkPath(getAttributes());
if (metricsCtx != null) {
metricsCtx.setNetworkPath(networkPath);
long endTimeNanos = clock.nanoTime();
String networkPath = detectNetworkPath(getAttributes());
if (metricsCtx != null) {
metricsCtx.setNetworkPath(networkPath);
}
if (status.getCode() != Status.Code.CANCELLED) {
try {
recordOnCloseMetrics(
/* watchdogTimedOut= */ false, endTimeNanos, networkPath, status, trailers);
} finally {
super.onClose(status, trailers);
}
return;
}
boolean[] recordedOnClose = {false};
Runnable onWatchdogTimeout =
() -> {
if (!recordedOnClose[0]) {
recordedOnClose[0] = true;
recordOnCloseMetrics(
/* watchdogTimedOut= */ true,
endTimeNanos,
networkPath,
status,
trailers);
}
};
try (Scope ignore = StorageMetricsContext.enterWatchdogScope(onWatchdogTimeout)) {
super.onClose(status, trailers);
} finally {
if (!recordedOnClose[0]) {
recordOnCloseMetrics(
/* watchdogTimedOut= */ false, endTimeNanos, networkPath, status, trailers);
}
}
Comment thread
nidhiii-27 marked this conversation as resolved.
Resolved
}

private void recordOnCloseMetrics(
boolean watchdogTimedOut,
long endTimeNanos,
String networkPath,
Status status,
Metadata trailers) {
try {
double durationSeconds = (endTimeNanos - startTimeNanos) / 1_000_000_000.0;
String statusCode = status.getCode().name();
String errorType = StorageErrorTypeMapper.mapGrpcStatus(status);
String errorType =
watchdogTimedOut
? StorageErrorTypeMapper.STATUS_TIMEOUT
: StorageErrorTypeMapper.mapGrpcStatus(status);

metrics.recordRpcCallDuration(
otelContext, durationSeconds, rpcMethod, statusCode, networkPath, errorType);
Expand All @@ -177,9 +223,13 @@ public void onClose(Status status, Metadata trailers) {
networkIoTracerFactory.getOutboundBytes(),
networkIoTracerFactory.getInboundBytes());
}
if (watchdogTimedOut) {
double stallSeconds = (endTimeNanos - lastActivityNanos) / 1_000_000_000.0;
metrics.recordStallDuration(
otelContext, stallSeconds, operationName, rpcMethod, networkPath);
}
} finally {
releaseActive();
super.onClose(status, trailers);
}
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ final class StorageMetricsContext {
CallOptions.Key.create("storage-metrics-context");

private static final ThreadLocal<StorageMetricsContext> CURRENT = new ThreadLocal<>();
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;

Expand Down Expand Up @@ -180,6 +181,25 @@ static StorageMetricsContext createForMultiStep(
return CURRENT.get();
}

static Scope enterWatchdogScope(Runnable onWatchdogTimeout) {
Runnable prev = WATCHDOG_TIMEOUT_CALLBACK.get();
WATCHDOG_TIMEOUT_CALLBACK.set(onWatchdogTimeout);
return () -> {
if (prev == null) {
WATCHDOG_TIMEOUT_CALLBACK.remove();
} else {
WATCHDOG_TIMEOUT_CALLBACK.set(prev);
}
};
}

static void notifyWatchdogTimeout() {
Runnable callback = WATCHDOG_TIMEOUT_CALLBACK.get();
if (callback != null) {
callback.run();
}
}

Scope makeCurrent() {
Scope otelScope = otelContext.makeCurrent();
StorageMetricsContext prev = CURRENT.get();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,15 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import com.google.api.core.ApiClock;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.retrying.ResultRetryAlgorithm;
import com.google.api.gax.rpc.ApiCallContext;
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.Watchdog;
import com.google.api.gax.rpc.WatchdogTimeoutException;
import com.google.cloud.NoCredentials;
import com.google.cloud.storage.GrpcUtils.ZeroCopyServerStreamingCallable;
import com.google.cloud.storage.Retrying.Retrier;
Expand All @@ -35,15 +39,21 @@
import com.google.storage.v2.ReadObjectResponse;
import io.grpc.Status;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.data.LongPointData;
import io.opentelemetry.sdk.metrics.data.MetricData;
import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.Collection;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Test;

public final class GapicUnbufferedReadableByteChannelTest {
Expand Down Expand Up @@ -683,6 +693,73 @@ private static void assertMidStreamRetryRecorded(
assertThat(attemptsTotal).isEqualTo(2L);
}

@Test
public void read_watchdogTimeout_notifiesWatchdogScopeSynchronously() throws IOException {

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: Could we also test a non-watchdog CancellationException inside enterWatchdogScope to verify the callback isn't triggered for normal cancellations?

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;
}
};
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
AtomicBoolean watchdogNotified = new AtomicBoolean(false);
try (Watchdog watchdog = Watchdog.createDuration(fakeClock, Duration.ofHours(1), scheduler);
GapicUnbufferedReadableByteChannel c =
new GapicUnbufferedReadableByteChannel(
SettableApiFuture.create(),
new ZeroCopyServerStreamingCallable<>(
new ServerStreamingCallable<ReadObjectRequest, ReadObjectResponse>() {
@Override
public void call(
ReadObjectRequest request,
ResponseObserver<ReadObjectResponse> respond,
ApiCallContext context) {
ResponseObserver<ReadObjectResponse> watched =
watchdog.watchDuration(
respond, Duration.ofSeconds(1), Duration.ofSeconds(2));
watched.onStart(
new StreamController() {
@Override
public void cancel() {
try (Scope ignore =
StorageMetricsContext.enterWatchdogScope(
() -> watchdogNotified.set(true))) {
watched.onError(
new CancellationException("cancelled by watchdog"));
}
}

@Override
public void disableAutoInboundFlowControl() {}

@Override
public void request(int count) {}
});
nanos.addAndGet(1_500_000_000L);
watchdog.run();
}
},
ResponseContentLifecycleManager.noop()),
ReadObjectRequest.getDefaultInstance(),
Hasher.noop(),
Retrier.attemptOnce(),
Retrying.neverRetry())) {
StorageException se =
assertThrows(StorageException.class, () -> c.read(ByteBuffer.allocate(16)));
assertThat(se.getCause()).isInstanceOf(WatchdogTimeoutException.class);
assertThat(watchdogNotified.get()).isTrue();
} finally {
scheduler.shutdownNow();
}
}

private static LongPointData findSinglePoint(Collection<MetricData> collected, String name) {
MetricData metric =
collected.stream()
Expand Down
Loading
Loading