Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
14 commits
Select commit Hold shift + click to select a range
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 @@ -140,6 +140,9 @@ public final int write(ByteBuffer src) throws IOException {
return 0;
}
int write = tmp.write(src);
if (write > 0 && metricsContext != null) {
metricsContext.addRequestBytes(write);
}
return write;
} catch (StorageException e) {
lastOperationError = e;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Streams;
import com.google.common.io.ByteStreams;
import com.google.common.io.CountingInputStream;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.SetIamPolicyRequest;
Expand Down Expand Up @@ -293,8 +294,15 @@ public Blob create(BlobInfo blobInfo, InputStream content, BlobWriteOption... op
.setRequest(req)
.build();

CountingInputStream countingStream =
metricsContext != null ? new CountingInputStream(inputStreamParam) : null;
try (UnbufferedWritableByteChannel c = session.open()) {
ByteStreams.copy(Channels.newChannel(inputStreamParam), c);
ByteStreams.copy(
Channels.newChannel(countingStream != null ? countingStream : inputStreamParam), c);
} finally {
if (metricsContext != null && countingStream != null) {
metricsContext.setRequestBytes(countingStream.getCount());
}
}
ApiFuture<WriteObjectResponse> responseApiFuture = session.getResult();
return this.getBlob(responseApiFuture);
Expand Down Expand Up @@ -323,12 +331,16 @@ public Blob internalCreateFrom(Path path, BlobInfo info, Opts<ObjectTargetOpt> o
if (Files.isDirectory(path)) {
throw new StorageException(0, path + " is a directory");
}
long size = Files.size(path);

StorageMetricsContext multiContext =
StorageClientMetrics.createMultiStepContext(
getOptions().getStorageClientMetrics(), "WriteObject");
Throwable error = null;
try {
if (multiContext != null) {
multiContext.setRequestBytes(size);
}
GrpcCallContext grpcCallContext =
opts.grpcMetadataMapper().apply(GrpcCallContext.createDefault());
GrpcCallContext callContextWithMetrics =
Expand Down Expand Up @@ -414,12 +426,19 @@ public Blob createFrom(
.build();

// Specifically not in the try-with, so we don't close the provided stream
InputStream inputStreamParam = firstNonNull(in, new ByteArrayInputStream(ZERO_BYTES));
CountingInputStream countingStream =
multiContext != null ? new CountingInputStream(inputStreamParam) : null;
ReadableByteChannel src =
Channels.newChannel(firstNonNull(in, new ByteArrayInputStream(ZERO_BYTES)));
Channels.newChannel(countingStream != null ? countingStream : inputStreamParam);
try (BufferedWritableByteChannel dst = session.open()) {
ByteStreams.copy(src, dst);
} catch (Exception e) {
throw StorageException.coalesce(e);
} finally {
if (multiContext != null && countingStream != null) {
multiContext.setRequestBytes(countingStream.getCount());
}
}
return getBlob(session.getResult());
} catch (Throwable t) {
Expand Down Expand Up @@ -974,6 +993,10 @@ private BlobInfo internalDirectUpload(
optsWithDefaults.grpcMetadataMapper().apply(GrpcCallContext.createDefault());
WriteObjectRequest req = getWriteObjectRequest(blobInfo, optsWithDefaults);
Hasher hasher = opts.getHasher();
int totalBytes = buf.remaining();
if (metricsContext != null) {
metricsContext.setRequestBytes(totalBytes);
}
GrpcCallContext merge = Utils.merge(grpcCallContext, Retrying.newCallContext(metricsContext));
RewindableContent content = RewindableContent.of(buf);
return retrier.run(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ final class StorageClientMetrics implements AutoCloseable {
AttributeKey.longKey("http.response.status_code");
static final AttributeKey<String> KEY_URL_TEMPLATE = AttributeKey.stringKey("url.template");
static final AttributeKey<String> KEY_SERVER_ADDRESS = AttributeKey.stringKey("server.address");
static final AttributeKey<Long> KEY_SERVER_PORT = AttributeKey.longKey("server.port");
static final AttributeKey<String> KEY_ERROR_TYPE = AttributeKey.stringKey("error.type");
static final AttributeKey<String> KEY_NETWORK_PATH = AttributeKey.stringKey("network.path");
static final AttributeKey<String> KEY_NETWORK_IO_DIRECTION =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CountingInputStream;
import com.google.common.io.CountingOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
Expand Down Expand Up @@ -204,12 +205,24 @@ public Blob create(BlobInfo blobInfo, InputStream content, BlobWriteOption... op
StorageObject blobPb = codecs.blobInfo().encode(updated);
InputStream inputStreamParam =
firstNonNull(content, new ByteArrayInputStream(EMPTY_BYTE_ARRAY));
StorageMetricsContext metricsContext =
StorageClientMetrics.createContext(getOptions().getStorageClientMetrics(), "WriteObject");
// retries are not safe when the input is an InputStream, so we can't retry.
return run(
"WriteObject",
return retrier.run(
Retrying.neverRetry(),
() -> storageRpc.create(blobPb, inputStreamParam, optionsMap),
(x) -> Conversions.json().blobInfo().decode(x).asBlob(this));
() -> {
if (metricsContext == null) {
return storageRpc.create(blobPb, inputStreamParam, optionsMap);
}
CountingInputStream countingStream = new CountingInputStream(inputStreamParam);
try {
return storageRpc.create(blobPb, countingStream, optionsMap);
} finally {
metricsContext.setRequestBytes(countingStream.getCount());
}
},
(x) -> Conversions.json().blobInfo().decode(x).asBlob(this),
metricsContext);
}

@Override
Expand Down Expand Up @@ -1944,6 +1957,9 @@ public BlobInfo internalCreateFrom(Path path, BlobInfo info, Opts<ObjectTargetOp
getOptions().getStorageClientMetrics(), "WriteObject");
Throwable error = null;
try {
if (multiContext != null) {
multiContext.setRequestBytes(size);
}
final Map<StorageRpc.Option, ?> optionsMap = opts.getRpcOptions();
BlobInfo.Builder builder = info.toBuilder().setMd5(null).setCrc32c(null);
BlobInfo updated = opts.blobInfoMapper().apply(builder).build();
Expand Down Expand Up @@ -2002,6 +2018,10 @@ private BlobInfo internalDirectUpload(
Opts<ObjectTargetOpt> opts,
ByteBuffer buf,
@Nullable StorageMetricsContext metricsContext) {
int totalBytes = buf.remaining();
if (metricsContext != null) {
metricsContext.setRequestBytes(totalBytes);
}
BlobInfo.Builder builder =
opts.blobInfoMapper().apply(info.toBuilder().clearMd5().clearCrc32c());
@Nullable Crc32cLengthKnown hash = opts.getHasher().hash(buf.duplicate());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,9 +195,12 @@ void recordOperation(
clientMethod = operationName;
}

Attributes operationAttributes =
Attributes bodySizeAttributes =
buildAttemptBaseAttributes(metrics).toBuilder()
.put(StorageClientMetrics.KEY_GCP_CLIENT_METHOD, clientMethod)
.build();
Attributes operationAttributes =
bodySizeAttributes.toBuilder()
.put(StorageClientMetrics.KEY_ERROR_TYPE, terminalErrorType)
.build();

Expand All @@ -216,6 +219,18 @@ void recordOperation(
.build();
metrics.getGcpClientRequestDuration().record(getElapsedSeconds(), durationAttributes);
}

recordRequestBodySize(metrics, bodySizeAttributes);
}
}

private void recordRequestBodySize(StorageClientMetrics metrics, Attributes bodySizeAttributes) {
if (metrics.getRequestBodySize() == null) {
return;
}
long reqBytes = requestBytes.get();
if ("WriteObject".equals(operationName) && reqBytes >= 0) {
metrics.getRequestBodySize().record(reqBytes, bodySizeAttributes, otelContext);
}
}

Expand Down Expand Up @@ -380,6 +395,10 @@ long addRequestBytes(long bytes) {
return requestBytes.addAndGet(bytes);
}

void setRequestBytes(long bytes) {
requestBytes.set(bytes);
}

long getRequestBytes() {
return requestBytes.get();
}
Expand Down
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 @@ -92,6 +91,7 @@
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicReference;
Expand Down Expand Up @@ -762,6 +762,24 @@ public void createFromInputStream_resumable_preservesMetricsContextAcrossCallCon
assertOperationCount("WriteObject", STATUS_OK, 1L);
}

@Test
public void createFromPath_nonExistentFile_throwsWithoutRecordingZeroRequestBodySize() {
Path missing = tmpDir.getRoot().toPath().resolve("missing.bin");
assertThrows(
NoSuchFileException.class,
() -> grpcStorage.createFrom(BlobInfo.newBuilder(BUCKET_NAME, BLOB_NAME).build(), missing));

Collection<MetricData> collected = reader.collectAllMetrics();
assertThat(
collected.stream()
.anyMatch(
md ->
md.getName()
.equals(
StorageClientMetrics.METRIC_GCP_STORAGE_CLIENT_REQUEST_BODY_SIZE)))
.isFalse();
}

private void stubMidStreamReadFailure(Throwable streamError) {
storageStub.readObjectCallable =
new ServerStreamingCallable<ReadObjectRequest, ReadObjectResponse>() {
Expand All @@ -770,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
Loading
Loading