diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java index 7f1c1aada247..bd20259e8097 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageClientMetrics.java @@ -86,14 +86,14 @@ final class StorageClientMetrics implements AutoCloseable { "gcp.storage.client.request.body.size"; static final String METRIC_GCP_STORAGE_CLIENT_RESPONSE_BODY_SIZE = "gcp.storage.client.response.body.size"; + static final String METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED = + "gcp.storage.client.server.unreached"; // Debug metric names static final String METRIC_GCP_STORAGE_CLIENT_REQUEST_ACTIVE = "gcp.storage.client.request.active"; static final String METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION = "gcp.storage.client.server.duration"; - static final String METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED = - "gcp.storage.client.server.unreached"; static final String METRIC_GCP_STORAGE_CLIENT_STALL_DURATION = "gcp.storage.client.stall.duration"; static final String METRIC_GCP_STORAGE_CLIENT_NETWORK_IO = "gcp.storage.client.network.io"; @@ -191,10 +191,10 @@ static StorageClientMetrics create( @Nullable private final DoubleHistogram ttfb; @Nullable private final LongHistogram requestBodySize; @Nullable private final LongHistogram responseBodySize; + @Nullable private final LongCounter serverUnreached; @Nullable private final LongUpDownCounter requestActive; @Nullable private final DoubleHistogram serverDuration; - @Nullable private final LongCounter serverUnreached; @Nullable private final DoubleHistogram stallDuration; @Nullable private final LongCounter networkIo; @Nullable private final DoubleHistogram credentialRefreshDuration; @@ -297,6 +297,13 @@ private StorageClientMetrics( .setExplicitBucketBoundariesAdvice( OpenTelemetryBootstrappingUtils.sizeHistogramLongBoundaries()) .build(); + this.serverUnreached = + meter + .counterBuilder(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED) + .setDescription( + "Number of GCS client requests that failed before reaching the server") + .setUnit("{request}") + .build(); } else { this.rpcClientCallDuration = null; this.httpClientRequestDuration = null; @@ -308,6 +315,7 @@ private StorageClientMetrics( this.ttfb = null; this.requestBodySize = null; this.responseBodySize = null; + this.serverUnreached = null; } if (enableOtelDebugMetrics) { @@ -327,15 +335,6 @@ private StorageClientMetrics( .setExplicitBucketBoundariesAdvice( OpenTelemetryBootstrappingUtils.latencyHistogramBoundaries()) .build(); - this.serverUnreached = - meter - .counterBuilder(METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED) - .setDescription( - "Number of attempts that received no response from a GCS server (gRPC:" - + " grpc-server-stats-bin trailer absent; HTTP: X-GUploader-UploadID header" - + " absent).") - .setUnit("{attempt}") - .build(); this.stallDuration = meter .histogramBuilder(METRIC_GCP_STORAGE_CLIENT_STALL_DURATION) @@ -367,7 +366,6 @@ private StorageClientMetrics( } else { this.requestActive = null; this.serverDuration = null; - this.serverUnreached = null; this.stallDuration = null; this.networkIo = null; this.credentialRefreshDuration = null; @@ -429,6 +427,10 @@ Attributes attachClientAttributes(@Nullable Attributes other) { return responseBodySize; } + @Nullable LongCounter getServerUnreached() { + return serverUnreached; + } + @Nullable LongUpDownCounter getRequestActive() { return requestActive; } @@ -437,10 +439,6 @@ Attributes attachClientAttributes(@Nullable Attributes other) { return serverDuration; } - @Nullable LongCounter getServerUnreached() { - return serverUnreached; - } - @Nullable DoubleHistogram getStallDuration() { return stallDuration; } @@ -550,6 +548,20 @@ void recordServerDuration( serverDuration.record(durationSeconds, attributes, otelContext); } + void recordServerUnreached( + Context otelContext, String operationName, String networkPath, String errorType) { + if (serverUnreached == null) { + return; + } + Attributes attributes = + baseAttributes.toBuilder() + .put(KEY_GCP_STORAGE_OPERATION, operationName) + .put(KEY_NETWORK_PATH, networkPath) + .put(KEY_ERROR_TYPE, errorType) + .build(); + serverUnreached.add(1L, attributes, otelContext); + } + @Nullable static StorageMetricsContext createContext( @Nullable StorageClientMetrics metrics, String operationName) { diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java index 25d9b5366660..6dbdbd1ecfd5 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageGrpcMetricsInterceptor.java @@ -52,6 +52,8 @@ final class StorageGrpcMetricsInterceptor implements ClientInterceptor { static final Metadata.Key GRPC_SERVER_STATS_BIN_KEY = Metadata.Key.of("grpc-server-stats-bin", Metadata.BINARY_BYTE_MARSHALLER); + static final Metadata.Key UPLOADER_UPLOAD_ID_KEY = + Metadata.Key.of("x-guploader-uploadid", Metadata.ASCII_STRING_MARSHALLER); private final StorageClientMetrics metrics; private final ApiClock clock; @@ -104,8 +106,15 @@ private void startWithMetrics( Listener responseListener, Metadata headers, long startTimeNanos) { super.start( new SimpleForwardingClientCallListener(responseListener) { + private boolean receivedServerHeaders; + private boolean headerHasUploadId; + @Override public void onHeaders(Metadata headers) { + receivedServerHeaders = true; + if (hasNonEmptyMetadata(headers, UPLOADER_UPLOAD_ID_KEY)) { + headerHasUploadId = true; + } if (metricsCtx != null) { metricsCtx.setNetworkPath(detectNetworkPath(getAttributes())); } @@ -137,12 +146,21 @@ public void onClose(Status status, Metadata trailers) { metrics.recordRpcCallDuration( otelContext, durationSeconds, rpcMethod, statusCode, networkPath, errorType); - if (metrics.getServerDuration() != null) { - double serverDurationSeconds = decodeServerDurationSeconds(trailers); - if (serverDurationSeconds >= 0.0) { - metrics.recordServerDuration( - otelContext, serverDurationSeconds, operationName, networkPath); - } + double serverDurationSeconds = decodeServerDurationSeconds(trailers); + if (serverDurationSeconds >= 0.0) { + metrics.recordServerDuration( + otelContext, serverDurationSeconds, operationName, networkPath); + } + if (isServerUnreached( + networkPath, + status, + errorType, + serverDurationSeconds >= 0.0, + receivedServerHeaders, + headerHasUploadId, + trailers)) { + metrics.recordServerUnreached( + otelContext, operationName, networkPath, errorType); } } finally { releaseActive(); @@ -232,4 +250,41 @@ static boolean isDirectPathIp(InetAddress addr) { } return false; } + + private static boolean isServerUnreached( + String networkPath, + Status status, + String errorType, + boolean hasServerDuration, + boolean receivedServerHeaders, + boolean headerHasUploadId, + Metadata trailers) { + if (StorageClientMetrics.NETWORK_PATH_DIRECTPATH.equals(networkPath)) { + boolean reached = + hasServerDuration || receivedServerHeaders || !trailers.keys().isEmpty() || status.isOk(); + return !reached && isPreServerErrorType(errorType); + } + boolean hasUploadId = + headerHasUploadId || hasNonEmptyMetadata(trailers, UPLOADER_UPLOAD_ID_KEY); + boolean reached = hasServerDuration || hasUploadId; + return !reached && !isAmbiguousClientAbort(errorType); + } + + private static boolean isAmbiguousClientAbort(String errorType) { + return StorageErrorTypeMapper.STATUS_CANCELLED.equals(errorType) + || StorageErrorTypeMapper.STATUS_TIMEOUT.equals(errorType) + || StorageErrorTypeMapper.STATUS_DEADLINE_EXCEEDED.equals(errorType); + } + + private static boolean isPreServerErrorType(String errorType) { + return StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR.equals(errorType) + || StorageErrorTypeMapper.STATUS_TLS_FAILURE.equals(errorType) + || StorageErrorTypeMapper.STATUS_DNS_FAILURE.equals(errorType) + || StorageErrorTypeMapper.STATUS_CONNECTION_ERROR.equals(errorType); + } + + private static boolean hasNonEmptyMetadata(Metadata metadata, Metadata.Key key) { + String value = metadata.get(key); + return value != null && !value.isEmpty(); + } } diff --git a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java index 6580e97a7a24..a39ecb2ad455 100644 --- a/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java +++ b/java-storage/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageHttpMetricsInterceptor.java @@ -23,6 +23,7 @@ import com.google.api.client.http.HttpIOExceptionHandler; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; +import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseInterceptor; import com.google.api.client.http.HttpUnsuccessfulResponseHandler; import com.google.api.core.ApiClock; @@ -55,6 +56,9 @@ @NullMarked final class StorageHttpMetricsInterceptor implements HttpRequestInitializer { + static final String HEADER_UPLOADER_UPLOAD_ID = "X-GUploader-UploadID"; + static final String HEADER_GFE_SERVICE_TIME = "X-Goog-Gfe-Service-Time"; + private static final ImmutableSet OBJECT_SUB_RESOURCES = ImmutableSet.of("acl", "compose", "restore"); @@ -180,7 +184,7 @@ public void initialize(HttpRequest request) throws IOException { && recorded.compareAndSet(false, true)) { metrics.recordRequestActive( activeOtelContext.get(), activeOperationName.get(), -1L); - recordResponse(req, startTimeNanos.get(), endNanos, response.getStatusCode()); + recordResponse(req, response, startTimeNanos.get(), endNanos); } } if (handled @@ -203,7 +207,7 @@ public void initialize(HttpRequest request) throws IOException { } finally { if (response.getRequest() == request && recorded.compareAndSet(false, true)) { metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L); - recordResponse(request, startTimeNanos.get(), endNanos, response.getStatusCode()); + recordResponse(request, response, startTimeNanos.get(), endNanos); } } }); @@ -216,11 +220,18 @@ public void initialize(HttpRequest request) throws IOException { if (recorded.compareAndSet(false, true)) { metrics.recordRequestActive(activeOtelContext.get(), activeOperationName.get(), -1L); double durationSeconds = (clock.nanoTime() - startTimeNanos.get()) / 1_000_000_000.0; + String urlTemplate = extractUrlTemplate(req.getUrl()); recordDuration( req, durationSeconds, 0L, - extractUrlTemplate(req.getUrl()), + urlTemplate, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + StorageMetricsContext ctx = StorageMetricsContext.current(); + metrics.recordServerUnreached( + ctx != null ? ctx.getOtelContext() : Context.current(), + resolveOperationName(req, urlTemplate), + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); } boolean handled = @@ -252,7 +263,9 @@ private void recordInternalRetry(HttpRequest request, int priorStatusCode) { errorType); } - private void recordResponse(HttpRequest request, long startNanos, long endNanos, int statusCode) { + private void recordResponse( + HttpRequest request, HttpResponse response, long startNanos, long endNanos) { + int statusCode = response.getStatusCode(); double durationSeconds = (endNanos - startNanos) / 1_000_000_000.0; String urlTemplate = extractUrlTemplate(request.getUrl()); String errorType = @@ -265,11 +278,16 @@ private void recordResponse(HttpRequest request, long startNanos, long endNanos, // may append query parameters (e.g. alt=media, uploadType) after buildRequest(). StorageMetricsContext ctx = StorageMetricsContext.current(); Context otelContext = ctx != null ? ctx.getOtelContext() : Context.current(); + String operationName = resolveOperationName(request, urlTemplate); metrics.recordTtfb( - otelContext, - resolveOperationName(request, urlTemplate), - durationSeconds, - StorageClientMetrics.NETWORK_PATH_CLOUDPATH); + otelContext, operationName, durationSeconds, StorageClientMetrics.NETWORK_PATH_CLOUDPATH); + boolean reached = + hasNonEmptyHeader(response, HEADER_UPLOADER_UPLOAD_ID) + || hasNonEmptyHeader(response, HEADER_GFE_SERVICE_TIME); + if (!reached) { + metrics.recordServerUnreached( + otelContext, operationName, StorageClientMetrics.NETWORK_PATH_CLOUDPATH, errorType); + } } private void recordDuration( @@ -423,4 +441,9 @@ private static String extractObjectUrlTemplate(String[] segments) { } return "/storage/v1/b/{bucket}/o/{object}"; } + + private static boolean hasNonEmptyHeader(HttpResponse response, String headerName) { + String value = response.getHeaders().getFirstHeaderStringValue(headerName); + return value != null && !value.isEmpty(); + } } diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java index a835ad6fbb1a..0dfa3db86ac7 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageClientMetricsTest.java @@ -54,13 +54,13 @@ public final class StorageClientMetricsTest { StorageClientMetrics::getErrors, StorageClientMetrics::getTtfb, StorageClientMetrics::getRequestBodySize, - StorageClientMetrics::getResponseBodySize); + StorageClientMetrics::getResponseBodySize, + StorageClientMetrics::getServerUnreached); private static final List> DEBUG_INSTRUMENTS = ImmutableList.of( StorageClientMetrics::getRequestActive, StorageClientMetrics::getServerDuration, - StorageClientMetrics::getServerUnreached, StorageClientMetrics::getStallDuration, StorageClientMetrics::getNetworkIo, StorageClientMetrics::getCredentialRefreshDuration); @@ -226,7 +226,7 @@ public void inMemoryMetricReader_verifiesViewsAndBoundaries() { String serverUnreachedName = StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED.replace(".", "/"); assertThat(metricsMap).containsKey(serverUnreachedName); - assertThat(metricsMap.get(serverUnreachedName).getUnit()).isEqualTo("{attempt}"); + assertThat(metricsMap.get(serverUnreachedName).getUnit()).isEqualTo("{request}"); assertThat(metricsMap) .containsKey(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_NETWORK_IO.replace(".", "/")); diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java index eeabd9df3a17..08a77f968d85 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageGrpcMetricsInterceptorTest.java @@ -55,10 +55,12 @@ import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; @@ -66,7 +68,10 @@ import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; +import javax.net.ssl.SSLException; +import javax.security.sasl.AuthenticationException; import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -504,6 +509,166 @@ public void interceptCall_serverDuration_recordsWhenDebugEnabledAndValidTrailerP .build()); } + @Test + public void interceptCall_serverUnreached_directPathAndCloudPathRules() throws Exception { + Attributes directPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("34.126.1.2"), 443)) + .build(); + Attributes cloudPathAttrs = + Attributes.newBuilder() + .set( + Grpc.TRANSPORT_ATTR_REMOTE_ADDR, + new InetSocketAddress(InetAddress.getByName("142.250.1.1"), 443)) + .build(); + Metadata headerWithUploadId = new Metadata(); + headerWithUploadId.put(StorageGrpcMetricsInterceptor.UPLOADER_UPLOAD_ID_KEY, "upload-1"); + Metadata headerWithEmptyUploadId = new Metadata(); + headerWithEmptyUploadId.put(StorageGrpcMetricsInterceptor.UPLOADER_UPLOAD_ID_KEY, ""); + Metadata trailerWithStats = new Metadata(); + trailerWithStats.put( + StorageGrpcMetricsInterceptor.GRPC_SERVER_STATS_BIN_KEY, + encodeServerStats(0, 0, 50_000_000L)); + Metadata trailerNonEmpty = new Metadata(); + trailerNonEmpty.put(Metadata.Key.of("x-custom-trailer", Metadata.ASCII_STRING_MARSHALLER), "v"); + + // DirectPath & unknown: only pre-server errors with no headers/trailers/stats/OK are unreached. + assertServerUnreached( + "dp connection error", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new IOException("connect failed")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertServerUnreached( + "dp dns failure", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new UnknownHostException("dns")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_DNS_FAILURE); + assertServerUnreached( + "dp tls failure", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new SSLException("tls")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_TLS_FAILURE); + assertServerUnreached( + "dp authentication error", + directPathAttrs, + null, + new Metadata(), + Status.UNAUTHENTICATED.withCause(new AuthenticationException("token failed")), + StorageClientMetrics.NETWORK_PATH_DIRECTPATH, + StorageErrorTypeMapper.STATUS_AUTHENTICATION_ERROR); + assertServerUnreached( + "unknown path pre-connect error", + Attributes.EMPTY, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new IOException("connection refused")), + StorageClientMetrics.NETWORK_PATH_UNKNOWN, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + assertServerUnreached( + "dp bare UNAVAILABLE not pre-server", + directPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "dp connection error after headers received", + directPathAttrs, + new Metadata(), + new Metadata(), + Status.UNAVAILABLE.withCause(new IOException("reset")), + null, + null); + assertServerUnreached( + "dp connection error with non-empty trailers", + directPathAttrs, + null, + trailerNonEmpty, + Status.UNAVAILABLE.withCause(new IOException("reset")), + null, + null); + assertServerUnreached( + "dp OK without headers", directPathAttrs, null, new Metadata(), Status.OK, null, null); + + // CloudPath: unreached when no stats-bin and no x-guploader-uploadid, excluding client aborts. + assertServerUnreached( + "cp UNAVAILABLE without markers", + cloudPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "cp empty upload id header treated as absent", + cloudPathAttrs, + headerWithEmptyUploadId, + new Metadata(), + Status.UNAVAILABLE, + StorageClientMetrics.NETWORK_PATH_CLOUDPATH, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "cp reached via header upload id", + cloudPathAttrs, + headerWithUploadId, + new Metadata(), + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "cp reached via trailer upload id", + cloudPathAttrs, + null, + headerWithUploadId, + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "cp reached via server stats bin", + cloudPathAttrs, + null, + trailerWithStats, + Status.UNAVAILABLE, + null, + null); + assertServerUnreached( + "cp CANCELLED ambiguous abort", + cloudPathAttrs, + null, + new Metadata(), + Status.CANCELLED, + null, + null); + assertServerUnreached( + "cp DEADLINE_EXCEEDED ambiguous abort", + cloudPathAttrs, + null, + new Metadata(), + Status.DEADLINE_EXCEEDED, + null, + null); + assertServerUnreached( + "cp TIMEOUT ambiguous abort", + cloudPathAttrs, + null, + new Metadata(), + Status.UNAVAILABLE.withCause(new TimeoutException("timed out")), + null, + null); + } + @Test public void interceptCall_requestActive_balancesWhenStartThrows() { StorageGrpcMetricsInterceptor debugInterceptor = createDebugInterceptor(); @@ -806,6 +971,64 @@ public void grpcStorageOptions_interceptorProviderWiring() throws Exception { assertThat(extractInterceptorProvider(disabledDefaultChannelProvider)).isNull(); } + private void assertServerUnreached( + String label, + Attributes attrs, + @Nullable Metadata headers, + Metadata trailers, + Status status, + @Nullable String expectedNetworkPath, + @Nullable String expectedErrorType) { + InMemoryMetricReader caseReader = InMemoryMetricReader.create(); + SdkMeterProvider caseProvider = + SdkMeterProvider.builder().registerMetricReader(caseReader).build(); + StorageClientMetrics caseMetrics = + StorageOptions.grpc() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setEnableOtelMetrics(true) + .setMeterProvider(caseProvider) + .build() + .getStorageClientMetrics(); + TestClientCall testCall = new TestClientCall<>(attrs); + new StorageGrpcMetricsInterceptor(caseMetrics, clock) + .interceptCall(READ_OBJECT_METHOD, CallOptions.DEFAULT, new TestChannel(testCall)) + .start(new TestListener<>(), new Metadata()); + if (headers != null) { + testCall.receiveHeaders(headers); + } + testCall.close(status, trailers); + + MetricData unreached = + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED); + if (expectedErrorType == null) { + assertWithMessage(label).that(unreached).isNull(); + return; + } + assertWithMessage(label).that(unreached).isNotNull(); + assertWithMessage(label).that(unreached.getUnit()).isEqualTo("{request}"); + assertWithMessage(label).that(unreached.getLongSumData().getPoints()).hasSize(1); + LongPointData point = unreached.getLongSumData().getPoints().iterator().next(); + assertWithMessage(label).that(point.getValue()).isEqualTo(1L); + assertWithMessage(label) + .that(point.getAttributes()) + .isEqualTo( + 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_GCP_STORAGE_OPERATION, "ReadObject") + .put(StorageClientMetrics.KEY_NETWORK_PATH, expectedNetworkPath) + .put(StorageClientMetrics.KEY_ERROR_TYPE, expectedErrorType) + .build()); + } + private StorageGrpcMetricsInterceptor createDebugInterceptor() { StorageClientMetrics debugMetrics = StorageOptions.grpc() @@ -836,7 +1059,11 @@ private LongPointData requestActivePoint() { } private @Nullable MetricData findMetric(String name) { - return reader.collectAllMetrics().stream() + return findMetric(reader, name); + } + + private static @Nullable MetricData findMetric(InMemoryMetricReader metricReader, String name) { + return metricReader.collectAllMetrics().stream() .filter(m -> m.getName().equals(name)) .findFirst() .orElse(null); diff --git a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java index 2737bed5de8b..4254c241da42 100644 --- a/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java +++ b/java-storage/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageHttpMetricsInterceptorTest.java @@ -50,6 +50,7 @@ import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; 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; import java.io.IOException; import java.nio.ByteBuffer; @@ -58,6 +59,7 @@ import java.util.Objects; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import org.jspecify.annotations.Nullable; import org.junit.Before; import org.junit.Test; @@ -702,7 +704,8 @@ public LowLevelHttpResponse execute() throws IOException { assertThat(retries.get(0).getValue()).isEqualTo(1L); assertThat(retries.get(0).getAttributes()) .isEqualTo( - expectedRetryAttributes("GetBucket", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); + expectedOperationErrorAttributes( + "GetBucket", StorageErrorTypeMapper.STATUS_CONNECTION_ERROR)); assertInternallyRetriedAttempt(StorageErrorTypeMapper.STATUS_CONNECTION_ERROR, 0L); } @@ -786,7 +789,7 @@ public LowLevelHttpResponse execute() { assertThat(retries).hasSize(1); assertThat(retries.get(0).getValue()).isEqualTo(1L); assertThat(retries.get(0).getAttributes()) - .isEqualTo(expectedRetryAttributes("ReadObject", "UNAUTHENTICATED")); + .isEqualTo(expectedOperationErrorAttributes("ReadObject", "UNAUTHENTICATED")); assertInternallyRetriedAttempt("UNAUTHENTICATED", 401L); } @@ -1031,6 +1034,52 @@ public LowLevelHttpResponse execute() { assertSingleRequestActive(0L, "Batch"); } + @Test + public void initialize_serverUnreached_cases() throws IOException { + assertServerUnreached( + "reached via upload id (debug on, no server.duration)", + true, + 200, + StorageHttpMetricsInterceptor.HEADER_UPLOADER_UPLOAD_ID, + "u-123", + null); + assertServerUnreached( + "reached via gfe service time (debug on, no server.duration)", + true, + 503, + StorageHttpMetricsInterceptor.HEADER_GFE_SERVICE_TIME, + "12.5", + null); + assertServerUnreached( + "502 without markers (standard tier)", + false, + 502, + null, + null, + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "504 proxy timeout without markers", + false, + 504, + null, + null, + StorageErrorTypeMapper.STATUS_DEADLINE_EXCEEDED); + assertServerUnreached( + "502 with empty upload id header", + false, + 502, + StorageHttpMetricsInterceptor.HEADER_UPLOADER_UPLOAD_ID, + "", + StorageErrorTypeMapper.STATUS_UNAVAILABLE); + assertServerUnreached( + "transport IOException", + false, + 0, + null, + null, + StorageErrorTypeMapper.STATUS_CONNECTION_ERROR); + } + @Test public void initialize_batchPart401_doesNotRecordPartDuration() throws IOException { AtomicBoolean refreshHandlerCalled = new AtomicBoolean(false); @@ -1252,6 +1301,87 @@ private List requestActivePoints() { return longSumPoints(StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_REQUEST_ACTIVE); } + private static @Nullable MetricData findMetric(InMemoryMetricReader metricReader, String name) { + return metricReader.collectAllMetrics().stream() + .filter(m -> m.getName().equals(name)) + .findFirst() + .orElse(null); + } + + private void assertServerUnreached( + String label, + boolean debugEnabled, + int statusCode, + @Nullable String headerName, + @Nullable String headerValue, + @Nullable String expectedError) + throws IOException { + InMemoryMetricReader caseReader = InMemoryMetricReader.create(); + SdkMeterProvider caseProvider = + SdkMeterProvider.builder().registerMetricReader(caseReader).build(); + StorageClientMetrics caseMetrics = + StorageOptions.http() + .setProjectId("test-project") + .setCredentials(NoCredentials.getInstance()) + .setClock(clock) + .setEnableOtelMetrics(true) + .setEnableOtelDebugMetrics(debugEnabled) + .setMeterProvider(caseProvider) + .build() + .getStorageClientMetrics(); + StorageHttpMetricsInterceptor interceptor = + new StorageHttpMetricsInterceptor(null, caseMetrics, clock); + HttpTransport transport = + new MockHttpTransport() { + @Override + public LowLevelHttpRequest buildRequest(String method, String url) { + return new MockLowLevelHttpRequest() { + @Override + public LowLevelHttpResponse execute() throws IOException { + if (statusCode == 0) { + throw new IOException("connection refused"); + } + MockLowLevelHttpResponse resp = + new MockLowLevelHttpResponse().setStatusCode(statusCode); + if (headerName != null) { + resp.addHeader(headerName, headerValue); + } + return resp; + } + }; + } + }; + HttpRequest req = + transport + .createRequestFactory(interceptor) + .buildGetRequest(new GenericUrl("https://storage.googleapis.com/storage/v1/b/my-b")); + if (statusCode == 0) { + assertThrows(IOException.class, req::execute); + } else { + req.setThrowExceptionOnExecuteError(false); + req.execute(); + } + + assertWithMessage(label) + .that( + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_DURATION)) + .isNull(); + MetricData unreached = + findMetric(caseReader, StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_SERVER_UNREACHED); + if (expectedError == null) { + assertWithMessage(label).that(unreached).isNull(); + return; + } + assertWithMessage(label).that(unreached).isNotNull(); + assertWithMessage(label).that(unreached.getUnit()).isEqualTo("{request}"); + assertWithMessage(label).that(unreached.getLongSumData().getPoints()).hasSize(1); + LongPointData point = unreached.getLongSumData().getPoints().iterator().next(); + assertWithMessage(label).that(point.getValue()).isEqualTo(1L); + assertWithMessage(label) + .that(point.getAttributes()) + .isEqualTo(expectedOperationErrorAttributes("GetBucket", expectedError)); + } + private List longSumPoints(String metricName) { return reader.collectAllMetrics().stream() .filter(m -> m.getName().equals(metricName)) @@ -1298,7 +1428,8 @@ private void assertInternallyRetriedAttempt(String errorType, long httpStatusCod .isEqualTo(errorType); } - private static Attributes expectedRetryAttributes(String operationName, String errorType) { + private static Attributes expectedOperationErrorAttributes( + String operationName, String errorType) { return Attributes.builder() .put(StorageClientMetrics.KEY_GCP_CLIENT_SERVICE, StorageClientMetrics.SERVICE_STORAGE) .put(StorageClientMetrics.KEY_GCP_CLIENT_VERSION, StorageOptions.version())