From 7d30b4fac510c905b68407c6ea15214f0497cc19 Mon Sep 17 00:00:00 2001 From: Jithesh Thekkarikottil Rajan Date: Wed, 2 Dec 2026 17:33:14 -0800 Subject: [PATCH] Drain named DELETE retirement before a planned frontend stop Include the writer, named DELETE wiring, and startup pause. Close admission before waiting for the retirement worker and terminal HTTP write. Bound preparation without interrupting publication or receipt recovery. Expose a pre-stop drain for deployment integration. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../github/ambry/config/FrontendConfig.java | 20 + .../com/github/ambry/named/NamedBlobDb.java | 26 + .../github/ambry/rest/RestRequestService.java | 14 + .../ambry/rest/RestResponseChannel.java | 11 + .../java/com/github/ambry/rest/RestUtils.java | 1 + .../github/ambry/router/GetBlobOptions.java | 50 +- .../ambry/router/GetBlobOptionsBuilder.java | 28 +- .../ambry/config/FrontendConfigTest.java | 12 + .../ambry/router/GetBlobOptionsTest.java | 24 + .../S3NamedBlobRetirementIntegrationTest.java | 361 +++++++++++ .../ambry/frontend/DeleteBlobHandler.java | 29 +- .../ambry/frontend/DeleteDatasetHandler.java | 1 + .../frontend/FrontendRestRequestService.java | 20 +- .../frontend/NamedBlobRetirementHandler.java | 237 +++++++ .../frontend/s3/S3BatchDeleteHandler.java | 3 +- .../frontend/NamedBlobDeleteHandlerTest.java | 212 +++++++ .../frontend/S3BatchDeleteHandlerTest.java | 37 ++ .../messageformat/MessageFormatRecord.java | 26 +- .../messageformat/MetadataContentSerDe.java | 41 +- .../MessageFormatRecordTest.java | 17 + ambry-named-mysql/README.md | 84 ++- ...NamedBlobManifestStoreIntegrationTest.java | 580 ++++++++++++++++-- .../github/ambry/named/MySqlNamedBlobDb.java | 314 ++++++++-- .../ambry/named/NamedBlobManifestStore.java | 276 +++++---- .../named/NamedBlobManifestStoreTest.java | 34 +- .../ambry/rest/NettyResponseChannel.java | 39 ++ .../com/github/ambry/rest/RestServer.java | 11 + .../ambry/rest/NettyResponseChannelTest.java | 29 + .../github/ambry/router/GetBlobOperation.java | 64 +- .../ambry/router/NonBlockingRouter.java | 2 +- .../ambry/router/S3NonBlockingRouterTest.java | 24 + 31 files changed, 2330 insertions(+), 297 deletions(-) create mode 100644 ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java create mode 100644 ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java diff --git a/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java b/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java index cca2adb943..7ba0080ea1 100644 --- a/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java +++ b/ambry-api/src/main/java/com/github/ambry/config/FrontendConfig.java @@ -42,6 +42,8 @@ public class FrontendConfig { public static final String MAX_JSON_REQUEST_SIZE_BYTES_KEY = PREFIX + "max.json.request.size.bytes"; public static final String ENABLE_UNDELETE = PREFIX + "enable.undelete"; public static final String NAMED_BLOB_DB_FACTORY = PREFIX + "named.blob.db.factory"; + public static final String NAMED_BLOB_RETIREMENT_NAMESPACE = PREFIX + "named.blob.retirement.namespace"; + public static final String NAMED_BLOB_RETIREMENT_PAUSED = PREFIX + "named.blob.retirement.paused"; public static final String CONTAINER_METRICS_EXCLUDED_ACCOUNTS = PREFIX + "container.metrics.excluded.accounts"; public static final String CONTAINER_METRICS_AGGREGATED_ACCOUNTS = PREFIX + "container.metrics.aggregated.accounts"; public static final String INVALID_ASCII_BLOB_NAME_CHARS = PREFIX + "invalid.ascii.blob.name.chars"; @@ -335,6 +337,16 @@ public class FrontendConfig { @Default("null") public final String namedBlobDbFactory; + /** One account/container for single-object named DELETE retirement. Empty disables it. */ + @Config(NAMED_BLOB_RETIREMENT_NAMESPACE) + @Default("") + public final String namedBlobRetirementNamespace; + + /** Reject named DELETE in the configured retirement namespace without restoring legacy DELETE. */ + @Config(NAMED_BLOB_RETIREMENT_PAUSED) + @Default("false") + public final boolean namedBlobRetirementPaused; + /** * The comma separated list of account names for which container metrics should not be generated. */ @@ -451,6 +463,14 @@ public FrontendConfig(VerifiableProperties verifiableProperties) { accountStatsStoreFactory = verifiableProperties.getString(ACCOUNT_STATS_STORE_FACTORY, DEFAULT_ACCOUNT_STATS_STORE_FACTORY); namedBlobDbFactory = verifiableProperties.getString(NAMED_BLOB_DB_FACTORY, null); + namedBlobRetirementNamespace = verifiableProperties.getString(NAMED_BLOB_RETIREMENT_NAMESPACE, ""); + if (!namedBlobRetirementNamespace.isEmpty() && !namedBlobRetirementNamespace.matches("[^/]+/[^/]+")) { + throw new IllegalArgumentException(NAMED_BLOB_RETIREMENT_NAMESPACE + " must be empty or account/container"); + } + namedBlobRetirementPaused = verifiableProperties.getBoolean(NAMED_BLOB_RETIREMENT_PAUSED, false); + if (namedBlobRetirementPaused && namedBlobRetirementNamespace.isEmpty()) { + throw new IllegalArgumentException(NAMED_BLOB_RETIREMENT_PAUSED + " requires " + NAMED_BLOB_RETIREMENT_NAMESPACE); + } containerMetricsExcludedAccounts = Utils.splitString(verifiableProperties.getString(CONTAINER_METRICS_EXCLUDED_ACCOUNTS, ""), ","); containerMetricsAggregatedAccounts = diff --git a/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java b/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java index a26ab5ecb3..f74c8b8904 100644 --- a/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java +++ b/ambry-api/src/main/java/com/github/ambry/named/NamedBlobDb.java @@ -18,6 +18,10 @@ import com.github.ambry.frontend.Page; import com.github.ambry.protocol.GetOption; import com.github.ambry.protocol.NamedBlobState; +import com.github.ambry.rest.RestServiceErrorCode; +import com.github.ambry.rest.RestServiceException; +import com.github.ambry.store.StoreKey; +import com.github.ambry.store.StoreKeyFactory; import java.io.Closeable; import java.util.List; import java.util.concurrent.CompletableFuture; @@ -108,6 +112,28 @@ default CompletableFuture put(NamedBlobRecord record) { */ CompletableFuture delete(String accountName, String containerName, String blobName); + /** + * Retire the unfenced versions of the authorized name without deleting data. Blocks on the caller's worker. + * The loader must return the full ordered child list of the exact root, decoding at most the supplied limit. + * A publication is successful only after commit or positive confirmation of the original intent. + */ + default void retire(Container container, String blobName, StoreKeyFactory keyFactory, RetirementLoader loader) + throws Exception { + throw new RestServiceException("Named retirement is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + + @FunctionalInterface + interface RetirementLoader { + List load(StoreKey root, int maxChildren) throws Exception; + + /** + * Check the caller's preparation deadline before writer checkout and again before entering publication. + * Do not consult this deadline once publication starts; receipt recovery must still run. + */ + default void checkPreparationDeadline() throws RestServiceException { + } + } + /** * Pull the stale blobs that need to be cleaned up */ diff --git a/ambry-api/src/main/java/com/github/ambry/rest/RestRequestService.java b/ambry-api/src/main/java/com/github/ambry/rest/RestRequestService.java index 355c46fda1..9e26a62e53 100644 --- a/ambry-api/src/main/java/com/github/ambry/rest/RestRequestService.java +++ b/ambry-api/src/main/java/com/github/ambry/rest/RestRequestService.java @@ -13,6 +13,8 @@ */ package com.github.ambry.rest; +import java.util.concurrent.TimeUnit; + /** * RestRequestService defines a service that handles {@link RestRequest}. * Typically, a RestRequestService is expected to receive requests and handle them as required and either send a @@ -42,6 +44,18 @@ public interface RestRequestService { */ void shutdown(); + /** + * Close named retirement admission and wait up to the supplied timeout for admitted requests to finish work that + * can still publish a retirement or recover its receipt, and to reach a terminal response write. A read-only + * descriptor operation can outlive its preparation deadline; its result can no longer lead to publication, + * so the drain does not wait for it. A drain timeout does not reopen admission or cancel work. + * @return whether the process drained; a successful drain does not confirm delivery to clients. + * @throws UnsupportedOperationException if the service does not implement retirement drain. + */ + default boolean drainNamedBlobRetirement(long timeout, TimeUnit unit) throws InterruptedException { + throw new UnsupportedOperationException("Named retirement drain is unsupported"); + } + /** * Handles a GET operation. *

diff --git a/ambry-api/src/main/java/com/github/ambry/rest/RestResponseChannel.java b/ambry-api/src/main/java/com/github/ambry/rest/RestResponseChannel.java index c1c92d0c00..86c66f00aa 100644 --- a/ambry-api/src/main/java/com/github/ambry/rest/RestResponseChannel.java +++ b/ambry-api/src/main/java/com/github/ambry/rest/RestResponseChannel.java @@ -18,6 +18,7 @@ import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; +import java.util.concurrent.CompletionStage; import java.util.concurrent.Future; @@ -88,6 +89,16 @@ public interface RestResponseChannel extends AsyncWritableChannel { */ public void onResponseComplete(Exception exception); + /** + * Opt in to tracking the terminal transport write before starting work that can produce a response. An error + * response completes successfully if written; an aborted or failed write completes exceptionally. Success means + * the transport accepted the final write, not that the client received it. + * @return the completion stage, or {@code null} if this channel does not support tracking for this request. + */ + default CompletionStage trackResponseWriteCompletion() { + return null; + } + /** * Sets the response status. * @param status the response status. diff --git a/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java b/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java index 8627092767..5ceec8ffad 100644 --- a/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java +++ b/ambry-api/src/main/java/com/github/ambry/rest/RestUtils.java @@ -523,6 +523,7 @@ public static final class InternalKeys { * The internal header to determine if the delete request is coming from a dataset deletion. */ public static final String DATASET_DELETE_ENABLED = KEY_PREFIX + "dataset-delete-enabled"; + public static final String S3_BATCH_DELETE_SUBREQUEST = KEY_PREFIX + "s3-batch-delete-subrequest"; /** diff --git a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java index e78459200c..02ab585667 100644 --- a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java +++ b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptions.java @@ -34,6 +34,9 @@ public class GetBlobOptions { private final boolean rawMode; private final int blobSegmentIdx; private final RestRequest restRequest; + private final int maxChunkIds; + private final boolean bypassNotFoundCache; + static final int NO_CHUNK_ID_LIMIT = -1; public static final int NO_BLOB_SEGMENT_IDX_SPECIFIED = -1; /** @@ -51,6 +54,13 @@ public class GetBlobOptions { */ public GetBlobOptions(OperationType operationType, GetOption getOption, ByteRange range, boolean resolveRangeOnEmptyBlob, boolean rawMode, int blobSegmentIdx, RestRequest restRequest) { + this(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, restRequest, + NO_CHUNK_ID_LIMIT, false); + } + + GetBlobOptions(OperationType operationType, GetOption getOption, ByteRange range, + boolean resolveRangeOnEmptyBlob, boolean rawMode, int blobSegmentIdx, RestRequest restRequest, int maxChunkIds, + boolean bypassNotFoundCache) { if (operationType == null || getOption == null) { throw new IllegalArgumentException("operationType and getOption must be defined"); } @@ -60,6 +70,12 @@ public GetBlobOptions(OperationType operationType, GetOption getOption, ByteRang if (rawMode && operationType != OperationType.All) { throw new IllegalArgumentException("Raw mode can be used only with OperationType.ALL"); } + if (maxChunkIds != NO_CHUNK_ID_LIMIT && (operationType != OperationType.BlobChunkIds || range != null + || blobSegmentIdx != NO_BLOB_SEGMENT_IDX_SPECIFIED)) { + throw new IllegalArgumentException("maxChunkIds requires BlobChunkIds without a range or segment"); + } + this.maxChunkIds = maxChunkIds; + this.bypassNotFoundCache = bypassNotFoundCache; this.operationType = operationType; this.getOption = getOption; this.range = range; @@ -126,10 +142,33 @@ public RestRequest getRestRequest() { return restRequest; } + /** + * @return whether the caller supplied a chunk ID limit. + */ + public boolean hasMaxChunkIds() { + return maxChunkIds != NO_CHUNK_ID_LIMIT; + } + + /** + * @return the maximum number of child IDs to decode, or {@code -1} if no limit was supplied. + */ + public int getMaxChunkIds() { + return maxChunkIds; + } + + /** + * @return whether the router should query storage despite a cached not-found result. + */ + public boolean shouldBypassNotFoundCache() { + return bypassNotFoundCache; + } + @Override public String toString() { return "GetBlobOptions{operationType=" + operationType + ", getOption=" + getOption + ", range=" + range - + ", rawMode=" + rawMode + ", blobSegmentIdx=" + blobSegmentIdx + ", restRequest=" + restRequest + '}'; + + ", rawMode=" + rawMode + ", blobSegmentIdx=" + blobSegmentIdx + ", restRequest=" + restRequest + + (hasMaxChunkIds() ? ", maxChunkIds=" + maxChunkIds : "") + + (bypassNotFoundCache ? ", bypassNotFoundCache=true" : "") + '}'; } @Override @@ -141,14 +180,17 @@ public boolean equals(Object o) { return false; } GetBlobOptions that = (GetBlobOptions) o; - return resolveRangeOnEmptyBlob == that.resolveRangeOnEmptyBlob && rawMode == that.rawMode - && blobSegmentIdx == that.blobSegmentIdx && operationType == that.operationType && getOption == that.getOption + return maxChunkIds == that.maxChunkIds && bypassNotFoundCache == that.bypassNotFoundCache + && resolveRangeOnEmptyBlob == that.resolveRangeOnEmptyBlob + && rawMode == that.rawMode && blobSegmentIdx == that.blobSegmentIdx && operationType == that.operationType + && getOption == that.getOption && Objects.equals(range, that.range) && Objects.equals(restRequest, that.restRequest); } @Override public int hashCode() { - return Objects.hash(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, restRequest); + return Objects.hash(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, restRequest, + maxChunkIds, bypassNotFoundCache); } /** diff --git a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java index e2f5d8a7e6..7cef3954d8 100644 --- a/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java +++ b/ambry-api/src/main/java/com/github/ambry/router/GetBlobOptionsBuilder.java @@ -32,6 +32,8 @@ public class GetBlobOptionsBuilder { private boolean rawMode = false; private RestRequest restRequest = null; private int blobSegmentIdx = NO_BLOB_SEGMENT_IDX_SPECIFIED; + private int maxChunkIds = NO_CHUNK_ID_LIMIT; + private boolean bypassNotFoundCache; /** * @param operationType the {@link GetBlobOptions.OperationType} for this request. @@ -100,11 +102,35 @@ public GetBlobOptionsBuilder blobSegment(int blobSegmentIdx) { return this; } + /** + * Limit an exact, whole-blob {@link GetBlobOptions.OperationType#BlobChunkIds} request. + * The request returns no data channel and fails with {@link RouterErrorCode#BlobTooLarge} if the metadata + * declares more child IDs than the limit. A limit of zero permits blobs with no child IDs. + * @param maxChunkIds the nonnegative remaining child ID budget. + * @return this builder + */ + public GetBlobOptionsBuilder maxChunkIds(int maxChunkIds) { + if (maxChunkIds < 0) { + throw new IllegalArgumentException("maxChunkIds must be nonnegative"); + } + this.maxChunkIds = maxChunkIds; + return this; + } + + /** + * @param bypassNotFoundCache whether to ignore cached not-found results when starting the GET. + * @return this builder + */ + public GetBlobOptionsBuilder bypassNotFoundCache(boolean bypassNotFoundCache) { + this.bypassNotFoundCache = bypassNotFoundCache; + return this; + } + /** * @return the {@link GetBlobOptions} built. */ public GetBlobOptions build() { return new GetBlobOptions(operationType, getOption, range, resolveRangeOnEmptyBlob, rawMode, blobSegmentIdx, - restRequest); + restRequest, maxChunkIds, bypassNotFoundCache); } } diff --git a/ambry-api/src/test/java/com/github/ambry/config/FrontendConfigTest.java b/ambry-api/src/test/java/com/github/ambry/config/FrontendConfigTest.java index 270dae8bc5..a3c8a22a91 100644 --- a/ambry-api/src/test/java/com/github/ambry/config/FrontendConfigTest.java +++ b/ambry-api/src/test/java/com/github/ambry/config/FrontendConfigTest.java @@ -26,6 +26,18 @@ */ public class FrontendConfigTest { + @Test + public void testRetirementPauseRejectsMissingNamespace() { + Properties properties = new Properties(); + properties.setProperty(FrontendConfig.NAMED_BLOB_RETIREMENT_PAUSED, "true"); + try { + new FrontendConfig(new VerifiableProperties(properties)); + Assert.fail("A pause without a configured namespace would permit legacy DELETE"); + } catch (IllegalArgumentException expected) { + Assert.assertTrue(expected.getMessage().contains(FrontendConfig.NAMED_BLOB_RETIREMENT_NAMESPACE)); + } + } + @Test public void testNamedBlobCleanupContainerDelaySeconds() { Properties properties = new Properties(); diff --git a/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java b/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java index a3fc03d2e4..901be0ac04 100644 --- a/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java +++ b/ambry-api/src/test/java/com/github/ambry/router/GetBlobOptionsTest.java @@ -99,6 +99,30 @@ public void testRawModeWithInvalidCombinations() throws Exception { TestUtils.assertException(IllegalArgumentException.class, () -> options.build(), null); } + @Test + public void testMaxChunkIdsOption() throws Exception { + assertFalse(new GetBlobOptionsBuilder().build().hasMaxChunkIds()); + GetBlobOptionsBuilder options = new GetBlobOptionsBuilder(); + TestUtils.assertException(IllegalArgumentException.class, () -> options.maxChunkIds(-1), null); + for (GetBlobOptions.OperationType type : GetBlobOptions.OperationType.values()) { + if (type != GetBlobOptions.OperationType.BlobChunkIds) { + TestUtils.assertException(IllegalArgumentException.class, + () -> options.operationType(type).maxChunkIds(0).build(), null); + } + } + options.operationType(GetBlobOptions.OperationType.BlobChunkIds); + GetBlobOptions unbounded = + new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobChunkIds).build(); + GetBlobOptions bounded = options.maxChunkIds(0).build(); + assertTrue(bounded.hasMaxChunkIds()); + assertEquals(0, bounded.getMaxChunkIds()); + assertOptionsAreDistinct(unbounded, bounded); + assertOptionsAreDistinct(bounded, options.maxChunkIds(1).build()); + TestUtils.assertException(IllegalArgumentException.class, + () -> options.range(ByteRanges.fromLastNBytes(1)).build(), null); + TestUtils.assertException(IllegalArgumentException.class, () -> options.range(null).blobSegment(0).build(), null); + } + /** * Test toString, equals, and hashCode methods. */ diff --git a/ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java b/ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java new file mode 100644 index 0000000000..aef3c5e3da --- /dev/null +++ b/ambry-frontend/src/integration-test/java/com/github/ambry/frontend/S3NamedBlobRetirementIntegrationTest.java @@ -0,0 +1,361 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + */ +package com.github.ambry.frontend; + +import com.codahale.metrics.MetricRegistry; +import com.github.ambry.account.Account; +import com.github.ambry.account.AccountService; +import com.github.ambry.account.AccountServiceFactory; +import com.github.ambry.account.Container; +import com.github.ambry.account.InMemAccountService; +import com.github.ambry.clustermap.MockClusterMap; +import com.github.ambry.commons.BlobId; +import com.github.ambry.commons.LoggingNotificationSystem; +import com.github.ambry.config.FrontendConfig; +import com.github.ambry.config.RestServerConfig; +import com.github.ambry.config.VerifiableProperties; +import com.github.ambry.named.NamedBlobDb; +import com.github.ambry.named.NamedBlobDbFactory; +import com.github.ambry.quota.QuotaResourceType; +import com.github.ambry.rest.NettyClient; +import com.github.ambry.rest.RestServer; +import com.github.ambry.rest.RestServiceErrorCode; +import com.github.ambry.rest.RestServiceException; +import com.github.ambry.utils.TestUtils; +import io.netty.channel.ChannelHandler; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelOutboundHandlerAdapter; +import io.netty.channel.ChannelPromise; +import io.netty.handler.codec.http.DefaultFullHttpRequest; +import io.netty.handler.codec.http.HttpMethod; +import io.netty.handler.codec.http.HttpResponse; +import io.netty.handler.codec.http.HttpResponseStatus; +import io.netty.handler.codec.http.HttpVersion; +import io.netty.util.ReferenceCountUtil; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.*; +import static org.mockito.Mockito.*; + + +/** Exercises named DELETE over HTTP with a real frontend, in-memory router, and injected named DB outcomes. */ +public class S3NamedBlobRetirementIntegrationTest { + private static final String KEY = "object"; + private static final int SERVER_PORT = FrontendIntegrationTestBase.PLAINTEXT_SERVER_PORT; + private static final int SECOND_SERVER_PORT = SERVER_PORT + 100; + private static final InMemAccountService ACCOUNTS = new InMemAccountService(false, false); + private static final NamedBlobDb DB = mock(NamedBlobDb.class); + private static MockClusterMap clusterMap; + private static RestServer server; + private static Container container; + private static String namespace; + private static String objectPath; + private static BlobId missingRoot; + + @ClassRule + public static final TemporaryFolder TEMP = new TemporaryFolder(); + + @BeforeClass + public static void startServer() throws Exception { + Account account = ACCOUNTS.createAndAddRandomAccount(QuotaResourceType.ACCOUNT); + container = account.getAllContainers().iterator().next(); + namespace = account.getName() + "/" + container.getName(); + objectPath = "/s3/" + namespace + "/" + KEY; + clusterMap = new MockClusterMap(); + missingRoot = new BlobId(BlobId.BLOB_ID_V6, BlobId.BlobIdType.NATIVE, clusterMap.getLocalDatacenterId(), + account.getId(), container.getId(), clusterMap.getWritablePartitionIds(null).get(0), false, + BlobId.BlobDataType.METADATA); + server = createServer(clusterMap, SERVER_PORT, false, null); + server.start(); + } + + private static RestServer createServer(MockClusterMap map, int port, boolean paused, ChannelHandler handler) + throws Exception { + Properties extraProps = new Properties(); + extraProps.setProperty(FrontendConfig.NAMED_BLOB_RETIREMENT_NAMESPACE, namespace); + if (paused) { + extraProps.setProperty(FrontendConfig.NAMED_BLOB_RETIREMENT_PAUSED, "true"); + } + extraProps.setProperty("rest.server.account.service.factory", TestAccountServiceFactory.class.getName()); + extraProps.setProperty("netty.server.port", Integer.toString(port)); + extraProps.setProperty("netty.server.enable.ssl", "false"); + extraProps.setProperty(RestServerConfig.ENABLE_ADDED_CHANNEL_HANDLERS, Boolean.toString(handler != null)); + Properties props = S3IntegrationTest.buildFrontendVProps(TEMP.newFile(), + TestNamedBlobDbFactory.class.getName(), extraProps); + return new RestServer(new VerifiableProperties(props), map, new LoggingNotificationSystem(), null, + handler == null ? null : Collections.singletonList(handler), null); + } + + @AfterClass + public static void stopServer() { + try { + if (server != null) { + server.shutdown(); + } + } finally { + if (clusterMap != null) { + clusterMap.close(); + } + } + } + + @Before + public void resetDb() { + reset(DB); + } + + @Test + public void testSuccessfulRetirementReturnsNoContent() throws Exception { + doNothing().when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.NO_CONTENT, true); + } + + @Test + public void testAbsentNameReturnsNoContent() throws Exception { + doThrow(new RestServiceException("Name is absent", RestServiceErrorCode.NotFound)).when(DB) + .retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.NO_CONTENT, true); + } + + @Test + public void testMissingStorageRootReturnsServiceUnavailable() throws Exception { + doAnswer(call -> { + NamedBlobDb.RetirementLoader loader = call.getArgument(3); + loader.load(missingRoot, 1); + return null; + }).when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.SERVICE_UNAVAILABLE, true); + } + + @Test + public void testUnconfirmedPublicationReturnsServiceUnavailable() throws Exception { + doThrow(new RestServiceException("Retirement was not confirmed", RestServiceErrorCode.ServiceUnavailable)) + .when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDelete(objectPath, HttpResponseStatus.SERVICE_UNAVAILABLE, true); + } + + @Test + public void testVersionIdDoesNotEnterEitherDeletePath() throws Exception { + assertDelete(objectPath + "?versionId=1", HttpResponseStatus.METHOD_NOT_ALLOWED, false); + } + + @Test + public void testPausePropertyRejectsNativeAndS3NamedDelete() throws Exception { + try (MockClusterMap pausedMap = new MockClusterMap()) { + RestServer pausedServer = createServer(pausedMap, SECOND_SERVER_PORT, true, null); + try { + pausedServer.start(); + assertDeleteStatus(SECOND_SERVER_PORT, "/named/" + namespace + "/" + KEY, HttpResponseStatus.METHOD_NOT_ALLOWED); + assertDeleteStatus(SECOND_SERVER_PORT, objectPath, HttpResponseStatus.METHOD_NOT_ALLOWED); + verifyNoInteractions(DB); + } finally { + pausedServer.shutdown(); + } + } + } + + @Test + public void testDeploymentDrainWaitsForFinalWriteAfterRetirement() throws Exception { + assertDeploymentDrainWaitsForFinalWrite(HttpResponseStatus.NO_CONTENT); + } + + @Test + public void testDeploymentDrainWaitsForFinalErrorWrite() throws Exception { + doThrow(new RestServiceException("Retirement was not confirmed", RestServiceErrorCode.ServiceUnavailable)) + .when(DB).retire(eq(container), eq(KEY), any(), any()); + assertDeploymentDrainWaitsForFinalWrite(HttpResponseStatus.SERVICE_UNAVAILABLE); + } + + private void assertDeploymentDrainWaitsForFinalWrite(HttpResponseStatus status) throws Exception { + CompletableFuture releaseWrite = new CompletableFuture<>(); + try (MockClusterMap map = new MockClusterMap()) { + RestServer drainingServer = + createServer(map, SECOND_SERVER_PORT, false, new HoldDeleteResponse(status, releaseWrite)); + try { + drainingServer.start(); + try (NettyClient client = new NettyClient("::1", SECOND_SERVER_PORT, null)) { + DefaultFullHttpRequest request = + new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, objectPath); + Future response = client.sendRequest(request, null, null); + Runnable release = releaseWrite.get(10, TimeUnit.SECONDS); + try { + awaitRetirementWorkerCompletion(drainingServer); + verify(DB).retire(eq(container), eq(KEY), any(), any()); + assertFalse("The held response alone must keep the drain pending", + drainingServer.drainNamedBlobRetirement(0, TimeUnit.SECONDS)); + assertDeleteStatus(SECOND_SERVER_PORT, objectPath, HttpResponseStatus.METHOD_NOT_ALLOWED); + assertFalse(response.isDone()); + } finally { + release.run(); + } + NettyClient.ResponseParts parts = response.get(10, TimeUnit.SECONDS); + try { + assertEquals(status, ((HttpResponse) parts.queue.element()).status()); + } finally { + parts.queue.forEach(ReferenceCountUtil::release); + } + assertTrue(drainingServer.drainNamedBlobRetirement(10, TimeUnit.SECONDS)); + verifyNoMoreInteractions(DB); + } + } finally { + drainingServer.shutdown(); + } + } + } + + private static void awaitRetirementWorkerCompletion(RestServer server) throws ReflectiveOperationException { + // The injected DB returns before the worker calls back and marks its work finished. + Object service = readField(RestServer.class, server, "restRequestService"); + Object handler = readField(FrontendRestRequestService.class, service, "retirementHandler"); + ThreadPoolExecutor worker = (ThreadPoolExecutor) readField(NamedBlobRetirementHandler.class, handler, "worker"); + assertTrue("The retirement worker must finish before the drain is checked", + TestUtils.checkAndSleep(1L, worker::getCompletedTaskCount, (int) TimeUnit.SECONDS.toMillis(10))); + } + + private static Object readField(Class owner, Object instance, String name) throws ReflectiveOperationException { + Field field = owner.getDeclaredField(name); + field.setAccessible(true); + return field.get(instance); + } + + @Test + public void testDeploymentDrainWaitsForWorkerAfterClientDisconnect() throws Exception { + CountDownLatch inWriter = new CountDownLatch(1); + CountDownLatch releaseWriter = new CountDownLatch(1); + doAnswer(call -> { + inWriter.countDown(); + if (!releaseWriter.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Test did not release the retirement worker"); + } + return null; + }).when(DB).retire(eq(container), eq(KEY), any(), any()); + + try (MockClusterMap map = new MockClusterMap()) { + ObserveDisconnect disconnect = new ObserveDisconnect(); + RestServer drainingServer = createServer(map, SECOND_SERVER_PORT, false, disconnect); + try { + drainingServer.start(); + try { + try (Socket client = new Socket()) { + client.connect(new InetSocketAddress("::1", SECOND_SERVER_PORT), 10_000); + client.getOutputStream().write(("DELETE " + objectPath + " HTTP/1.1\r\nHost: [::1]\r\n\r\n") + .getBytes(StandardCharsets.US_ASCII)); + assertTrue("Retirement should reach the worker", inWriter.await(10, TimeUnit.SECONDS)); + } + assertTrue("The server must observe the socket close", disconnect.closed.await(10, TimeUnit.SECONDS)); + assertFalse("A disconnect must not mark the worker drained", + drainingServer.drainNamedBlobRetirement(0, TimeUnit.SECONDS)); + } finally { + releaseWriter.countDown(); + } + assertTrue(drainingServer.drainNamedBlobRetirement(10, TimeUnit.SECONDS)); + verify(DB).retire(eq(container), eq(KEY), any(), any()); + verifyNoMoreInteractions(DB); + } finally { + drainingServer.shutdown(); + } + } + } + + @ChannelHandler.Sharable + private static final class ObserveDisconnect extends ChannelInboundHandlerAdapter { + private final CountDownLatch closed = new CountDownLatch(1); + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + ctx.fireChannelInactive(); + closed.countDown(); + } + } + + @ChannelHandler.Sharable + private static final class HoldDeleteResponse extends ChannelOutboundHandlerAdapter { + private final HttpResponseStatus status; + private final CompletableFuture releaseWrite; + + HoldDeleteResponse(HttpResponseStatus status, CompletableFuture releaseWrite) { + this.status = status; + this.releaseWrite = releaseWrite; + } + + @Override + public void write(ChannelHandlerContext ctx, Object message, ChannelPromise promise) { + if (message instanceof HttpResponse && ((HttpResponse) message).status().equals(status) + && releaseWrite.complete(() -> ctx.writeAndFlush(message, promise))) { + return; + } + ctx.write(message, promise); + } + } + + private void assertDelete(String path, HttpResponseStatus expected, boolean expectRetirement) throws Exception { + assertDeleteStatus(SERVER_PORT, path, expected); + if (expectRetirement) { + verify(DB).retire(eq(container), eq(KEY), any(), any()); + } + verifyNoMoreInteractions(DB); + } + + private void assertDeleteStatus(int port, String path, HttpResponseStatus expected) throws Exception { + try (NettyClient client = new NettyClient("::1", port, null)) { + DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.DELETE, path); + NettyClient.ResponseParts parts = client.sendRequest(request, null, null).get(10, TimeUnit.SECONDS); + try { + assertEquals(expected, ((HttpResponse) parts.queue.element()).status()); + } finally { + parts.queue.forEach(ReferenceCountUtil::release); + } + } + } + + public static class TestAccountServiceFactory implements AccountServiceFactory { + public TestAccountServiceFactory(VerifiableProperties properties, MetricRegistry metrics) { + } + + @Override + public AccountService getAccountService() { + return ACCOUNTS; + } + } + + public static class TestNamedBlobDbFactory implements NamedBlobDbFactory { + public TestNamedBlobDbFactory(VerifiableProperties properties, MetricRegistry metrics, AccountService accounts) { + } + + @Override + public NamedBlobDb getNamedBlobDb() { + return DB; + } + } +} diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java index ba0b0556b6..7bd9a2e7fa 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteBlobHandler.java @@ -36,6 +36,7 @@ import com.github.ambry.router.Router; import com.github.ambry.utils.Pair; import java.io.IOException; +import java.util.Collections; import java.util.GregorianCalendar; import java.util.Map; import org.slf4j.Logger; @@ -63,10 +64,19 @@ public class DeleteBlobHandler { private final QuotaManager quotaManager; private final AccountService accountService; private final IdSigningService idSigningService; + private final NamedBlobRetirementHandler retirementHandler; DeleteBlobHandler(Router router, SecurityService securityService, IdConverter idConverter, AccountAndContainerInjector accountAndContainerInjector, FrontendMetrics metrics, ClusterMap clusterMap, QuotaManager quotaManager, AccountService accountService, IdSigningService idSigningService) { + this(router, securityService, idConverter, accountAndContainerInjector, metrics, clusterMap, quotaManager, + accountService, idSigningService, null); + } + + DeleteBlobHandler(Router router, SecurityService securityService, IdConverter idConverter, + AccountAndContainerInjector accountAndContainerInjector, FrontendMetrics metrics, ClusterMap clusterMap, + QuotaManager quotaManager, AccountService accountService, IdSigningService idSigningService, + NamedBlobRetirementHandler retirementHandler) { this.router = router; this.securityService = securityService; this.idConverter = idConverter; @@ -76,6 +86,14 @@ public class DeleteBlobHandler { this.quotaManager = quotaManager; this.accountService = accountService; this.idSigningService = idSigningService; + this.retirementHandler = retirementHandler; + } + + void rejectDatasetRetirement(RestRequest request) throws RestServiceException { + if (retirementHandler != null && retirementHandler.matchesAuthorizedNamespace(request)) { + throw new RestServiceException("Dataset DELETE is unsupported in the retirement namespace", + RestServiceErrorCode.NotAllowed); + } } public void handle(RestRequest restRequest, RestResponseChannel restResponseChannel, Callback callback) @@ -145,13 +163,22 @@ private Callback securityProcessRequestCallback() { private Callback securityPostProcessRequestCallback() { return buildCallback(metrics.deleteBlobSecurityPostProcessRequestMetrics, result -> { String serviceId = RestUtils.getHeader(restRequest.getArgs(), RestUtils.Headers.SERVICE_ID, false); + RequestPath requestPath = getRequestPath(restRequest); + if (retirementHandler != null && requestPath.matchesOperation(NAMED_BLOB)) { + // Resolve the target from the same path the legacy DELETE converter would use, not from a header. + NamedBlobPath path = NamedBlobPath.parse(requestPath, Collections.emptyMap()); + if (retirementHandler.matches(path.getAccountName(), path.getContainerName()) + || retirementHandler.matchesAuthorizedNamespace(restRequest)) { + retirementHandler.handle(restRequest, path, restResponseChannel, routerCallback()); + return; + } + } if (RestUtils.isDatasetVersionQueryEnabled(restRequest.getArgs())) { accountAndContainerInjector.injectDatasetForNamedBlob(restRequest); String datasetVersionPathString = getRequestPath(restRequest).getOperationOrBlobId(false); DatasetVersionRecord datasetVersionRecord = getDatasetVersionHelper(restRequest, datasetVersionPathString, accountService, metrics); if (datasetVersionRecord.getRenameFrom() != null) { - RequestPath requestPath = getRequestPath(restRequest); RequestPath newRequestPath = reconstructRequestPath(datasetVersionRecord, requestPath, ((Account) restRequest.getArgs().get(InternalKeys.TARGET_ACCOUNT_KEY)).getName(), ((Container) restRequest.getArgs().get(InternalKeys.TARGET_CONTAINER_KEY)).getName()); diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java index 7a74888f1f..1c870d4d02 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/DeleteDatasetHandler.java @@ -126,6 +126,7 @@ private Callback securityProcessRequestCallback() { */ private Callback securityPostProcessRequestCallback() { return buildCallback(frontendMetrics.deleteDatasetsSecurityPostProcessRequestMetrics, securityCheckResult -> { + deleteBlobHandler.rejectDatasetRetirement(restRequest); deleteDataset(); }, uri, LOGGER, finalCallback); } diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java index b05ea3240c..9dbf0529e9 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/FrontendRestRequestService.java @@ -106,6 +106,7 @@ class FrontendRestRequestService implements RestRequestService, RestRequestMetri private TtlUpdateHandler ttlUpdateHandler; private CopyDatasetVersionHandler copyDatasetVersionHandler; private DeleteBlobHandler deleteBlobHandler; + private NamedBlobRetirementHandler retirementHandler; private DeleteDatasetHandler deleteDatasetHandler; private HeadBlobHandler headBlobHandler; private UndeleteHandler undeleteHandler; @@ -128,7 +129,7 @@ class FrontendRestRequestService implements RestRequestService, RestRequestMetri private S3MultipartAbortUploadHandler s3MultipartAbortHandler; private S3GetHandler s3GetHandler; private QuotaManager quotaManager; - private boolean isUp = false; + private volatile boolean isUp = false; private final Random random = new Random(); /** @@ -212,9 +213,13 @@ public void start() throws InstantiationException { clusterMap, quotaManager, namedBlobDb, accountService); copyDatasetVersionHandler = new CopyDatasetVersionHandler(securityService, accountService, frontendMetrics, accountAndContainerInjector); + if (!frontendConfig.namedBlobRetirementNamespace.isEmpty()) { + retirementHandler = new NamedBlobRetirementHandler(frontendConfig.namedBlobRetirementNamespace, + frontendConfig.namedBlobRetirementPaused, namedBlobDb, router, clusterMap, quotaManager); + } deleteBlobHandler = new DeleteBlobHandler(router, securityService, idConverter, accountAndContainerInjector, frontendMetrics, - clusterMap, quotaManager, accountService, idSigningService); + clusterMap, quotaManager, accountService, idSigningService, retirementHandler); deleteDatasetHandler = new DeleteDatasetHandler(securityService, accountService, frontendMetrics, accountAndContainerInjector, deleteBlobHandler); @@ -293,10 +298,21 @@ public void start() throws InstantiationException { frontendMetrics.restRequestServiceStartupTimeInMs.update(System.currentTimeMillis() - startupBeginTime); } + @Override + public boolean drainNamedBlobRetirement(long timeout, TimeUnit unit) throws InterruptedException { + if (!isUp) { + throw new IllegalStateException("Drain requires a running frontend"); + } + return retirementHandler == null || retirementHandler.drain(timeout, unit); + } + @Override public void shutdown() { long shutdownBeginTime = System.currentTimeMillis(); isUp = false; + if (retirementHandler != null) { + retirementHandler.close(); + } try { if (quotaManager != null) { quotaManager.shutdown(); diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java new file mode 100644 index 0000000000..4ed38f5cd1 --- /dev/null +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/NamedBlobRetirementHandler.java @@ -0,0 +1,237 @@ +/* + * Copyright 2026 LinkedIn Corp. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + */ +package com.github.ambry.frontend; + +import com.github.ambry.account.Account; +import com.github.ambry.account.Container; +import com.github.ambry.clustermap.ClusterMap; +import com.github.ambry.commons.BlobIdFactory; +import com.github.ambry.commons.Callback; +import com.github.ambry.named.NamedBlobDb; +import com.github.ambry.protocol.GetOption; +import com.github.ambry.quota.QuotaChargeCallback; +import com.github.ambry.quota.QuotaManager; +import com.github.ambry.quota.QuotaUtils; +import com.github.ambry.rest.RestMethod; +import com.github.ambry.rest.RestRequest; +import com.github.ambry.rest.RestResponseChannel; +import com.github.ambry.rest.RestServiceErrorCode; +import com.github.ambry.rest.RestServiceException; +import com.github.ambry.rest.RestUtils; +import com.github.ambry.router.GetBlobOptions; +import com.github.ambry.router.GetBlobOptionsBuilder; +import com.github.ambry.router.GetBlobResult; +import com.github.ambry.router.Router; +import com.github.ambry.router.RouterErrorCode; +import com.github.ambry.router.RouterException; +import com.github.ambry.store.StoreKey; +import com.github.ambry.utils.Utils; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static com.github.ambry.rest.RestUtils.InternalKeys.*; + +/** Performs metadata-only DELETE retirement after request authorization. */ +final class NamedBlobRetirementHandler implements AutoCloseable { + private static final Logger LOGGER = LoggerFactory.getLogger(NamedBlobRetirementHandler.class); + private static final long PREPARATION_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(30); + private final String namespace; + private final long preparationTimeoutNanos; + private final NamedBlobDb namedBlobDb; + private final Router router; + private final BlobIdFactory keyFactory; + private final QuotaManager quotaManager; + private final ThreadPoolExecutor worker = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, + new SynchronousQueue<>(), new Utils.SchedulerThreadFactory("NamedBlobRetirement", true)); + private final CountDownLatch drained = new CountDownLatch(1); + private boolean paused; + private int inFlight; + + NamedBlobRetirementHandler(String namespace, boolean paused, NamedBlobDb namedBlobDb, Router router, + ClusterMap clusterMap, QuotaManager quotaManager) { + this(namespace, paused, namedBlobDb, router, clusterMap, quotaManager, PREPARATION_TIMEOUT_NANOS); + } + + NamedBlobRetirementHandler(String namespace, boolean paused, NamedBlobDb namedBlobDb, Router router, + ClusterMap clusterMap, QuotaManager quotaManager, long preparationTimeoutNanos) { + this.namespace = namespace; + this.paused = paused; + this.preparationTimeoutNanos = preparationTimeoutNanos; + this.namedBlobDb = namedBlobDb; + this.router = router; + this.keyFactory = new BlobIdFactory(clusterMap); + this.quotaManager = quotaManager; + } + + boolean matches(String account, String container) { + return namespace.equals(account + "/" + container); + } + + boolean matchesAuthorizedNamespace(RestRequest request) { + Account account = (Account) request.getArgs().get(TARGET_ACCOUNT_KEY); + Container container = (Container) request.getArgs().get(TARGET_CONTAINER_KEY); + return account != null && container != null && matches(account.getName(), container.getName()); + } + + synchronized void handle(RestRequest request, NamedBlobPath path, RestResponseChannel response, + Callback callback) throws RestServiceException { + if (!matches(path.getAccountName(), path.getContainerName()) || !matchesAuthorizedNamespace(request) + || request.getArgs().containsKey(RestUtils.Headers.BLOB_ID)) { + throw new RestServiceException("Named DELETE path does not match the authorized retirement target", + RestServiceErrorCode.BadRequest); + } + if (request.getRestMethod() != RestMethod.DELETE || request.getArgs().containsKey(S3_BATCH_DELETE_SUBREQUEST) + || request.getArgs().containsKey(DATASET_DELETE_ENABLED) || RestUtils.isDatasetVersionQueryEnabled(request.getArgs()) + || (RestUtils.isS3Request(request) && request.getArgs().containsKey("versionId"))) { + throw new RestServiceException("Only single-object named DELETE is supported in the retirement namespace", + RestServiceErrorCode.NotAllowed); + } + if (paused) { + throw new RestServiceException("Named DELETE is paused for this namespace", RestServiceErrorCode.NotAllowed); + } + if (namedBlobDb == null) { + throw new RestServiceException("Named retirement is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + CompletionStage responseWrite = response.trackResponseWriteCompletion(); + if (responseWrite == null) { + throw new RestServiceException("Named retirement requires response write tracking", + RestServiceErrorCode.ServiceUnavailable); + } + CompletableFuture writeFinished = responseWrite.toCompletableFuture(); + Container container = (Container) request.getArgs().get(TARGET_CONTAINER_KEY); + long deadline = System.nanoTime() + preparationTimeoutNanos; + CompletableFuture workFinished = new CompletableFuture<>(); + try { + worker.execute(() -> { + try { + Exception failure = null; + try { + retire(request, container, path.getBlobName(), deadline); + } catch (Exception e) { + failure = e; + } + callback.onCompletion(null, failure); + } finally { + workFinished.complete(null); + } + }); + } catch (RejectedExecutionException e) { + throw new RestServiceException("Named retirement worker is busy or stopped", e, + RestServiceErrorCode.ServiceUnavailable); + } + inFlight++; + // A disconnected client may finish the transport before the worker finishes receipt recovery. + CompletableFuture.allOf(workFinished, writeFinished).whenComplete((ignored, failure) -> finish(failure)); + } + + private void retire(RestRequest request, Container container, String blobName, long deadline) throws Exception { + QuotaChargeCallback charge = QuotaUtils.buildQuotaChargeCallback(request, quotaManager, false); + namedBlobDb.retire(container, blobName, keyFactory, new NamedBlobDb.RetirementLoader() { + @Override + public List load(StoreKey root, int limit) throws Exception { + return loadChildren(root, limit, request, charge, deadline); + } + + @Override + public void checkPreparationDeadline() throws RestServiceException { + remainingPreparationNanos(deadline); + } + }); + } + + private void finish(Throwable failure) { + if (failure != null) { + LOGGER.warn("Named retirement response write failed", failure); + } + synchronized (this) { + if (--inFlight == 0 && paused) { + drained.countDown(); + } + } + } + + boolean drain(long timeout, TimeUnit unit) throws InterruptedException { + synchronized (this) { + paused = true; + if (inFlight == 0) { + drained.countDown(); + } + } + return drained.await(timeout, unit); + } + + private static long remainingPreparationNanos(long deadline) throws RestServiceException { + long remaining = deadline - System.nanoTime(); + if (remaining <= 0) { + throw new RestServiceException("Named retirement preparation timed out", RestServiceErrorCode.ServiceUnavailable); + } + return remaining; + } + + private List loadChildren(StoreKey root, int limit, RestRequest request, QuotaChargeCallback charge, + long deadline) throws Exception { + remainingPreparationNanos(deadline); + GetBlobOptions options = new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobChunkIds) + .maxChunkIds(limit).bypassNotFoundCache(true).getOption(GetOption.Include_Expired_Blobs).restRequest(request) + .build(); + // The raw-ID overload cannot resolve the name again or invoke named DELETE conversion. + Future read = router.getBlob(root.getID(), options, null, charge); + try { + GetBlobResult result = read.get(remainingPreparationNanos(deadline), TimeUnit.NANOSECONDS); + if (result != null && result.getBlobDataChannel() != null) { + result.getBlobDataChannel().close(); + throw new RestServiceException("Named retirement requires metadata only", RestServiceErrorCode.Conflict); + } + return result == null ? null : result.getBlobChunkIds(); + } catch (TimeoutException e) { + throw new RestServiceException("Named retirement preparation timed out", e, + RestServiceErrorCode.ServiceUnavailable); + } catch (ExecutionException e) { + Throwable failure = e.getCause(); + if (failure instanceof RouterException) { + RouterErrorCode code = ((RouterException) failure).getErrorCode(); + if (code == RouterErrorCode.BlobTooLarge) { + throw new RestServiceException("Named retirement exceeds its child limit", failure, + RestServiceErrorCode.Conflict); + } + if (code == RouterErrorCode.TooManyRequests) { + throw new RestServiceException("Named retirement metadata read exceeded quota", failure, + RestServiceErrorCode.TooManyRequests); + } + } + // Storage absence does not prove that the name is absent (S3 maps NotFound to success). + throw new RestServiceException("Cannot read named retirement root", failure, + RestServiceErrorCode.ServiceUnavailable); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw e; + } + } + + @Override + public void close() { + worker.shutdown(); + } +} diff --git a/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java b/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java index 7e2488fb85..bab40ce558 100644 --- a/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java +++ b/ambry-frontend/src/main/java/com/github/ambry/frontend/s3/S3BatchDeleteHandler.java @@ -47,7 +47,7 @@ import static com.github.ambry.rest.RestUtils.*; public class S3BatchDeleteHandler extends S3BaseHandler { - private static DeleteBlobHandler deleteBlobHandler; + private final DeleteBlobHandler deleteBlobHandler; private final XmlMapper xmlMapper; private FrontendMetrics metrics; private static final Logger logger = LoggerFactory.getLogger(S3BatchDeleteHandler.class); @@ -145,6 +145,7 @@ private Callback parseRequestBodyAndDeleteCallback(RetainingAsyncWritableC WrappedRestRequest singleDeleteRequest = new WrappedRestRequest(restRequest); singleDeleteRequest.setArg(InternalKeys.REQUEST_PATH, newRequestPath); singleDeleteRequest.removeArg(BATCH_DELETE_QUERY_PARAM); + singleDeleteRequest.setArg(InternalKeys.S3_BATCH_DELETE_SUBREQUEST, true); NoOpResponseChannel noOpResponseChannel = new NoOpResponseChannel(); CompletableFuture future = new CompletableFuture<>(); diff --git a/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java b/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java index acb754759c..ba24517d4d 100644 --- a/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java +++ b/ambry-frontend/src/test/java/com/github/ambry/frontend/NamedBlobDeleteHandlerTest.java @@ -29,32 +29,49 @@ import com.github.ambry.config.VerifiableProperties; import com.github.ambry.named.NamedBlobDb; import com.github.ambry.named.NamedBlobDbFactory; +import com.github.ambry.protocol.GetOption; +import com.github.ambry.quota.QuotaChargeCallback; +import com.github.ambry.quota.QuotaManager; import com.github.ambry.quota.QuotaTestUtils; import com.github.ambry.rest.MockRestResponseChannel; import com.github.ambry.rest.RequestPath; import com.github.ambry.rest.RestMethod; +import com.github.ambry.rest.ResponseStatus; import com.github.ambry.rest.RestRequest; import com.github.ambry.rest.RestResponseChannel; +import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; import com.github.ambry.rest.RestUtils; import com.github.ambry.router.FutureResult; +import com.github.ambry.router.GetBlobOptions; +import com.github.ambry.router.GetBlobResult; import com.github.ambry.router.InMemoryRouter; +import com.github.ambry.router.Router; +import com.github.ambry.router.RouterErrorCode; +import com.github.ambry.router.RouterException; +import com.github.ambry.store.StoreKey; import com.github.ambry.utils.MockTime; import com.github.ambry.utils.TestUtils; import java.io.UnsupportedEncodingException; import java.net.URISyntaxException; import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import org.json.JSONObject; import org.junit.Test; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; /** @@ -165,6 +182,201 @@ public void deleteMultipleVersionsTest() throws Exception { } } + @Test + public void testRetirementReadsExactRootAndWaitsForPublication() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router exactRouter = mock(Router.class); + StoreKey root = mock(StoreKey.class); + StoreKey child = mock(StoreKey.class); + when(root.getID()).thenReturn("exact-root"); + when(exactRouter.getBlob(eq("exact-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class))) + .thenAnswer(call -> { + GetBlobOptions options = call.getArgument(1); + assertEquals(GetBlobOptions.OperationType.BlobChunkIds, options.getOperationType()); + assertEquals(GetOption.Include_Expired_Blobs, options.getGetOption()); + assertEquals(17, options.getMaxChunkIds()); + assertTrue(options.shouldBypassNotFoundCache()); + return CompletableFuture.completedFuture(new GetBlobResult(null, null, Collections.singletonList(child))); + }); + CountDownLatch loaded = new CountDownLatch(1); + CountDownLatch publish = new CountDownLatch(1); + Thread caller = Thread.currentThread(); + doAnswer(call -> { + assertNotSame(caller, Thread.currentThread()); + NamedBlobDb.RetirementLoader loader = call.getArgument(3); + assertEquals(Collections.singletonList(child), loader.load(root, 17)); + loaded.countDown(); + assertTrue(publish.await(TIMEOUT_SECS, TimeUnit.SECONDS)); + return null; + }).when(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + try (NamedBlobRetirementHandler retirement = retirement(db, exactRouter)) { + DeleteBlobHandler handler = withRetirement(retirement, exactRouter); + RetirementResponse response = new RetirementResponse(); + CompletableFuture first = delete(handler, getDeleteRestRequest(new JSONObject(), request_path), response); + try { + assertTrue(loaded.await(TIMEOUT_SECS, TimeUnit.SECONDS)); + assertFalse(first.isDone()); + assertDeleteError(RestServiceErrorCode.ServiceUnavailable, + delete(handler, getDeleteRestRequest(new JSONObject(), request_path), new RetirementResponse())); + response.write.completeExceptionally(new ClosedChannelException()); + assertFalse("A disconnect must not mark the worker drained", retirement.drain(0, TimeUnit.SECONDS)); + } finally { + publish.countDown(); + } + first.get(TIMEOUT_SECS, TimeUnit.SECONDS); + assertTrue(retirement.drain(TIMEOUT_SECS, TimeUnit.SECONDS)); + assertEquals(ResponseStatus.Accepted, response.getStatus()); + verify(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + verify(exactRouter).getBlob(eq("exact-root"), any(GetBlobOptions.class), isNull(), + any(QuotaChargeCallback.class)); + verifyNoMoreInteractions(db, exactRouter); + } + } + + @Test + public void testPausedRetirementRejectsSelectedNamespaceWithoutCallingEitherDeletePath() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router unusedRouter = mock(Router.class); + IdConverter unusedConverter = mock(IdConverter.class); + QuotaManager quota = QuotaTestUtils.createDummyQuotaManager(); + try (NamedBlobRetirementHandler retirement = new NamedBlobRetirementHandler( + REF_ACCOUNT.getName() + "/" + REF_CONTAINER.getName(), true, db, unusedRouter, CLUSTER_MAP, quota)) { + DeleteBlobHandler handler = new DeleteBlobHandler(unusedRouter, securityServiceFactory.getSecurityService(), + unusedConverter, injector, metrics, CLUSTER_MAP, quota, ACCOUNT_SERVICE, idSigningService, retirement); + RestRequest nativeRequest = getDeleteRestRequest(new JSONObject(), request_path); + assertDeleteError(RestServiceErrorCode.NotAllowed, delete(handler, nativeRequest, new MockRestResponseChannel())); + verifyNoInteractions(db, unusedRouter, unusedConverter); + } + } + + @Test + public void testPausedRetirementLeavesOtherNamespacesOnLegacyDelete() throws Exception { + String blobId = uploadOneVersion(); + NamedBlobDb db = mock(NamedBlobDb.class); + try (NamedBlobRetirementHandler retirement = new NamedBlobRetirementHandler( + REF_ACCOUNT.getName() + "/" + REF_CONTAINER_WITH_TTL_REQUIRED.getName(), true, db, router, CLUSTER_MAP, + QuotaTestUtils.createDummyQuotaManager())) { + RestRequest request = getDeleteRestRequest(new JSONObject(), request_path); + delete(withRetirement(retirement, router), request, new MockRestResponseChannel()).get(TIMEOUT_SECS, + TimeUnit.SECONDS); + assertTrue(router.getDeletedBlobs().contains(blobId)); + verifyNoInteractions(db); + } + } + + @Test + public void testRetirementRejectsUnsupportedDeleteShapesWithoutLegacyDelete() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router unusedRouter = mock(Router.class); + try (NamedBlobRetirementHandler retirement = retirement(db, unusedRouter)) { + DeleteBlobHandler handler = withRetirement(retirement, unusedRouter); + for (String marker : Arrays.asList(RestUtils.InternalKeys.S3_BATCH_DELETE_SUBREQUEST, + RestUtils.InternalKeys.DATASET_DELETE_ENABLED)) { + RestRequest request = getDeleteRestRequest(new JSONObject(), request_path); + request.setArg(marker, true); + assertDeleteError(RestServiceErrorCode.NotAllowed, delete(handler, request, new MockRestResponseChannel())); + } + verifyNoInteractions(db, unusedRouter); + } + } + + @Test + public void testRetirementDoesNotTreatMissingStorageAsMissingName() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router exactRouter = mock(Router.class); + StoreKey root = mock(StoreKey.class); + when(root.getID()).thenReturn("missing-root"); + CompletableFuture missing = new CompletableFuture<>(); + missing.completeExceptionally(new RouterException("Missing root", RouterErrorCode.BlobDoesNotExist)); + when(exactRouter.getBlob(eq("missing-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class))) + .thenReturn(missing); + doAnswer(call -> { + ((NamedBlobDb.RetirementLoader) call.getArgument(3)).load(root, 1); + return null; + }).when(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + try (NamedBlobRetirementHandler retirement = retirement(db, exactRouter)) { + assertDeleteError(RestServiceErrorCode.ServiceUnavailable, delete(withRetirement(retirement, exactRouter), + getDeleteRestRequest(new JSONObject(), request_path), new RetirementResponse())); + verify(exactRouter).getBlob(eq("missing-root"), any(GetBlobOptions.class), isNull(), + any(QuotaChargeCallback.class)); + verifyNoMoreInteractions(exactRouter); + } + } + + @Test + public void testStalledDescriptorTimesOutWithoutPublicationAndDrainWaitsForWrite() throws Exception { + NamedBlobDb db = mock(NamedBlobDb.class); + Router exactRouter = mock(Router.class); + StoreKey root = mock(StoreKey.class); + when(root.getID()).thenReturn("stalled-root"); + when(exactRouter.getBlob(eq("stalled-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class))) + .thenReturn(new CompletableFuture<>()); + doAnswer(call -> { + NamedBlobDb.RetirementLoader loader = call.getArgument(3); + loader.load(root, 1); + throw new AssertionError("A stalled descriptor must not advance to publication"); + }).when(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + RetirementResponse response = new RetirementResponse(); + try (NamedBlobRetirementHandler retirement = new NamedBlobRetirementHandler( + REF_ACCOUNT.getName() + "/" + REF_CONTAINER.getName(), false, db, exactRouter, CLUSTER_MAP, + QuotaTestUtils.createDummyQuotaManager(), TimeUnit.SECONDS.toNanos(1))) { + DeleteBlobHandler handler = withRetirement(retirement, exactRouter); + assertDeleteError(RestServiceErrorCode.ServiceUnavailable, + delete(handler, getDeleteRestRequest(new JSONObject(), request_path), response)); + verify(exactRouter).getBlob(eq("stalled-root"), any(GetBlobOptions.class), isNull(), any(QuotaChargeCallback.class)); + assertFalse(retirement.drain(0, TimeUnit.SECONDS)); + assertDeleteError(RestServiceErrorCode.NotAllowed, + delete(handler, getDeleteRestRequest(new JSONObject(), request_path), new RetirementResponse())); + response.write.completeExceptionally(new ClosedChannelException()); + assertTrue(retirement.drain(TIMEOUT_SECS, TimeUnit.SECONDS)); + verify(db).retire(eq(REF_CONTAINER), eq(BLOBNAME), any(), any()); + verifyNoMoreInteractions(db, exactRouter); + } + } + + private static class RetirementResponse extends MockRestResponseChannel { + private final CompletableFuture write = new CompletableFuture<>(); + + @Override + public CompletionStage trackResponseWriteCompletion() { + return write; + } + } + + private NamedBlobRetirementHandler retirement(NamedBlobDb db, Router retirementRouter) { + return new NamedBlobRetirementHandler(REF_ACCOUNT.getName() + "/" + REF_CONTAINER.getName(), false, db, + retirementRouter, CLUSTER_MAP, QuotaTestUtils.createDummyQuotaManager()); + } + + private DeleteBlobHandler withRetirement(NamedBlobRetirementHandler retirement, Router retirementRouter) { + QuotaManager quota = QuotaTestUtils.createDummyQuotaManager(); + return new DeleteBlobHandler(retirementRouter, securityServiceFactory.getSecurityService(), + idConverterFactory.getIdConverter(), injector, metrics, CLUSTER_MAP, quota, ACCOUNT_SERVICE, idSigningService, + retirement); + } + + private static CompletableFuture delete(DeleteBlobHandler handler, RestRequest request, + RestResponseChannel response) throws RestServiceException { + CompletableFuture future = new CompletableFuture<>(); + handler.handle(request, response, (result, failure) -> { + if (failure == null) { + future.complete(result); + } else { + future.completeExceptionally(failure); + } + }); + return future; + } + + private static void assertDeleteError(RestServiceErrorCode code, CompletableFuture future) throws Exception { + try { + future.get(TIMEOUT_SECS, TimeUnit.SECONDS); + fail("Expected " + code); + } catch (ExecutionException failure) { + assertEquals(code, ((RestServiceException) failure.getCause()).getErrorCode()); + } + } + /** * Upload a new version for this named blob and return the blob id. * @return The blob id for the new version diff --git a/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java b/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java index 751c3410a9..95960489ec 100644 --- a/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java +++ b/ambry-frontend/src/test/java/com/github/ambry/frontend/S3BatchDeleteHandlerTest.java @@ -41,6 +41,7 @@ import com.github.ambry.rest.RestMethod; import com.github.ambry.rest.RestRequest; import com.github.ambry.rest.RestResponseChannel; +import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestUtils; import com.github.ambry.router.FutureResult; import com.github.ambry.router.InMemoryRouter; @@ -52,6 +53,7 @@ import java.util.Collections; import java.util.LinkedList; import java.util.Properties; +import java.util.concurrent.TimeUnit; import org.json.JSONObject; import org.junit.After; import org.junit.Before; @@ -59,6 +61,7 @@ import static com.github.ambry.frontend.s3.S3Constants.*; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; public class S3BatchDeleteHandlerTest { @@ -142,6 +145,40 @@ public void deleteObjectTest() throws Exception { assertEquals("Mismatch on status", ResponseStatus.Ok, restResponseChannel.getStatus()); } + @Test + public void testBatchDeleteDoesNotRetireOrDeleteSelectedNamespace() throws Exception { + MockClusterMap clusterMap = new MockClusterMap(); + NamedBlobDb db = mock(NamedBlobDb.class); + InMemoryRouter router = mock(InMemoryRouter.class); + AccountAndContainerInjector injector = new AccountAndContainerInjector(ACCOUNT_SERVICE, metrics, frontendConfig); + SecurityService security = new FrontendTestSecurityServiceFactory().getSecurityService(); + try (NamedBlobRetirementHandler retirement = new NamedBlobRetirementHandler( + account.getName() + "/" + container.getName(), false, db, router, clusterMap, + QuotaTestUtils.createDummyQuotaManager())) { + DeleteBlobHandler delete = new DeleteBlobHandler(router, security, null, injector, metrics, clusterMap, + QuotaTestUtils.createDummyQuotaManager(), ACCOUNT_SERVICE, null, retirement); + S3BatchDeleteHandler batch = new S3BatchDeleteHandler(delete, metrics); + String uri = String.format("/s3/%s/%s", account.getName(), container.getName()); + byte[] body = ("" + KEY_NAME + "") + .getBytes(StandardCharsets.UTF_8); + RestRequest request = FrontendRestRequestServiceTest.createRestRequest(RestMethod.POST, uri, new JSONObject(), + new LinkedList<>(Arrays.asList(ByteBuffer.wrap(body), null))); + request.setArg(RestUtils.InternalKeys.REQUEST_PATH, + RequestPath.parse(request, frontendConfig.pathPrefixesToRemove, CLUSTER_NAME)); + FutureResult future = new FutureResult<>(); + batch.handle(request, new MockRestResponseChannel(), future::done); + try (ReadableStreamChannel response = future.get(5, TimeUnit.SECONDS)) { + ByteBuffer xml = ((ByteBufferReadableStreamChannel) response).getContent(); + S3MessagePayload.DeleteResult result = new XmlMapper().readValue(xml.array(), S3MessagePayload.DeleteResult.class); + assertTrue(result.getDeleted() == null || result.getDeleted().isEmpty()); + assertEquals(1, result.getErrors().size()); + assertEquals(new S3MessagePayload.S3ErrorObject(KEY_NAME, RestServiceErrorCode.NotAllowed.toString()).toString(), + result.getErrors().get(0).toString()); + } + verifyNoInteractions(db, router); + } + } + @Test public void testConsumeContentAsBytesReleasesBuffer() { // Arrange: Create a ByteBuf with some data diff --git a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java index d2a6a59914..1e55460bcb 100644 --- a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java +++ b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MessageFormatRecord.java @@ -1912,10 +1912,24 @@ public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, int c */ public static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory) throws IOException { - List keys = new ArrayList(); + return deserializeMetadataContentRecord(stream, storeKeyFactory, MetadataContentSerDe.NO_CHUNK_ID_LIMIT); + } + + static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory, + int maxChunkIds) throws IOException { int chunkSize = stream.readInt(); long totalSize = stream.readLong(); - long numberOfKeys = (totalSize + chunkSize - 1) / chunkSize; + long numberOfKeys; + if (maxChunkIds == MetadataContentSerDe.NO_CHUNK_ID_LIMIT) { + numberOfKeys = (totalSize + chunkSize - 1) / chunkSize; + } else { + if (chunkSize <= 0 || totalSize <= 0) { + throw new IOException("Invalid V2 metadata chunk or total size"); + } + numberOfKeys = 1 + (totalSize - 1) / chunkSize; + MetadataContentSerDe.checkChunkCount(numberOfKeys, maxChunkIds); + } + List keys = new ArrayList<>(); for (int i = 0; i < numberOfKeys; i++) { StoreKey storeKey = storeKeyFactory.getStoreKey(stream); keys.add(storeKey); @@ -1998,10 +2012,16 @@ public static void serializeMetadataContentRecord(ByteBuffer outputBuffer, long */ public static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory) throws IOException { - List> keysAndContentSizes = new ArrayList<>(); + return deserializeMetadataContentRecord(stream, storeKeyFactory, MetadataContentSerDe.NO_CHUNK_ID_LIMIT); + } + + static CompositeBlobInfo deserializeMetadataContentRecord(DataInputStream stream, StoreKeyFactory storeKeyFactory, + int maxChunkIds) throws IOException { long totalSize = stream.readLong(); long sum = 0; int numberOfKeys = stream.readInt(); + MetadataContentSerDe.checkChunkCount(numberOfKeys, maxChunkIds); + List> keysAndContentSizes = new ArrayList<>(); for (int i = 0; i < numberOfKeys; i++) { long contentSize = stream.readLong(); StoreKey storeKey = storeKeyFactory.getStoreKey(stream); diff --git a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java index 22495f03a7..94b19fe995 100644 --- a/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java +++ b/ambry-messageformat/src/main/java/com/github/ambry/messageformat/MetadataContentSerDe.java @@ -27,6 +27,7 @@ * A class to serialize and deserialize MetadataContent which forms the content of a Metadata Blob. */ public class MetadataContentSerDe { + static final int NO_CHUNK_ID_LIMIT = -1; /** * Serialize the input list of keys that form the metadata content. @@ -70,17 +71,53 @@ public static ByteBuffer serializeMetadataContentV3(long totalSize, List maxChunkIds) { + throw new ChunkCountLimitExceededException(chunkCount, maxChunkIds); + } + } + } + + /** Indicates that a metadata record declares more child IDs than the request permits. */ + public static final class ChunkCountLimitExceededException extends IOException { + private ChunkCountLimitExceededException(long chunkCount, int maxChunkIds) { + super("Metadata declares " + chunkCount + " chunk IDs; limit is " + maxChunkIds); + } + } } diff --git a/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java b/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java index 21eae28896..14e8792b01 100644 --- a/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java +++ b/ambry-messageformat/src/test/java/com/github/ambry/messageformat/MessageFormatRecordTest.java @@ -564,6 +564,8 @@ public void testMetadataContentRecordV2() throws IOException, MessageFormatExcep long[] totalSizes = {(long) keys.size() * chunkSizes[0], ((long) keys.size() * chunkSizes[1]) - 11}; for (int i = 0; i < chunkSizes.length; i++) { ByteBuffer metadataContent = getSerializedMetadataContentV2(chunkSizes[i], totalSizes[i], keys); + assertEquals(keys, MetadataContentSerDe.deserializeMetadataContentRecord(metadataContent.duplicate(), + new MockIdFactory(), keys.size()).getKeys()); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV2(metadataContent, new MockIdFactory()); Assert.assertEquals("Chunk size doesn't match", chunkSizes[i], compositeBlobInfo.getChunkSize()); Assert.assertEquals("Total size doesn't match", totalSizes[i], compositeBlobInfo.getTotalSize()); @@ -586,6 +588,8 @@ public void testMetadataContentRecordV3() throws IOException, MessageFormatExcep } ByteBuffer metadataContent = getSerializedMetadataContentV3(total, keysAndContentSizes); + assertEquals(keys, MetadataContentSerDe.deserializeMetadataContentRecord(metadataContent.duplicate(), + new MockIdFactory(), keys.size()).getKeys()); CompositeBlobInfo compositeBlobInfo = deserializeMetadataContentV3(metadataContent, new MockIdFactory()); Assert.assertEquals("Total size doesn't match", total, compositeBlobInfo.getTotalSize()); Assert.assertEquals("List of keys dont match", keys, compositeBlobInfo.getKeys()); @@ -600,6 +604,19 @@ public void testMetadataContentRecordV3() throws IOException, MessageFormatExcep } } + @Test + public void testRejectsOversizedMetadataBeforeReadingChildRecords() throws Exception { + ByteBuffer v2 = ByteBuffer.allocate(Short.BYTES + Integer.BYTES + Long.BYTES); + v2.putShort(Metadata_Content_Version_V2).putInt(2).putLong(Long.MAX_VALUE); + ByteBuffer v3 = ByteBuffer.allocate(Short.BYTES + Long.BYTES + Integer.BYTES); + v3.putShort(Metadata_Content_Version_V3).putLong(1).putInt(Integer.MAX_VALUE); + for (ByteBuffer header : new ByteBuffer[]{v2, v3}) { + header.flip(); + TestUtils.assertException(MetadataContentSerDe.ChunkCountLimitExceededException.class, + () -> MetadataContentSerDe.deserializeMetadataContentRecord(header, new MockIdFactory(), 1), null); + } + } + @Test public void testInvalidMetadataContentV2Fields() { List keys = getKeys(60, 5); diff --git a/ambry-named-mysql/README.md b/ambry-named-mysql/README.md index 919c88c07c..9aa8270427 100644 --- a/ambry-named-mysql/README.md +++ b/ambry-named-mysql/README.md @@ -6,10 +6,25 @@ the source of the list; repeated child IDs retain their positions. Prepare the l manifest and retire the named versions in one transaction. A crash before commit leaves neither a manifest nor a retirement. -Before dispatch, retain the original named-version keys, each root ID, and its ordered child IDs. If the commit reply is -lost, check that exact request on the authoritative writer. A match confirms the commit; it does not authorize cleanup. -No match means the commit was not observed, not that it rolled back. Retry only the original request. If the inputs are -unavailable, stop. Never resolve the current name to reconstruct the request or fall back to the router's ordinary delete. +`prepareRetirement` resolves the account and container once and reserves one request per named DB instance before +invoking the descriptor supplier. Supply the exact named versions and roots, and defer descriptor work to the supplier. +Preparation, publication, and receipt checks block; run them off the event loop. There is no payload queue. Close the +handle on all paths: while it is open, a second request is rejected as unavailable. The 32 MiB limit is on encoded child +bytes, not peak heap: allow for encoding buffers, supplier memory, and JDBC packet buffers. Publication or confirmation +can also occupy one connection from the same pool as ordinary requests, outside the transaction executor. + +Use the same handle to publish, to check its receipt after an uncertain result, and to retry. Each call checks out an +idle, autocommit `REPEATABLE READ` session from the configured local writer pool and starts a fresh transaction. +Publication and confirmation require a fixed Connector/J connection with reconnect disabled. The retirement checkout +caps socket reads at five seconds and restores the previous timeout before returning a healthy connection. Do not set a +pool-wide `socketTimeout` for retirement. Socket or communications failures discard the checkout without a rollback +attempt; an interrupted commit is still an unknown outcome. Configure bounded pool checkout and descriptor fetches. +The read timeout is not an end-to-end deadline, and closing the handle does not interrupt an active call. + +A matching receipt confirms the commit; it does not authorize cleanup. No match means the commit was not observed, not +that it rolled back. A replay whose read snapshot predates a concurrent commit can still reject if replacements now +exceed the range cap; confirm again in a fresh transaction. If the original inputs are unavailable, stop. Never resolve +the current name to reconstruct the request or use the router's ordinary delete. A reader with a saved tuple can recover the published list after a restart without fetching the original root. Configure the reader data source for `READ COMMITTED` or stronger on every checkout. @@ -18,8 +33,8 @@ reference the same child; finding its ID does not authorize deletion. ## Compatibility and limits -These package-private methods have no frontend caller. They require one authoritative InnoDB writer for the name range, -soft deletes, and `REPEATABLE READ` during publication. They do not coordinate independent active-active writers. +Retirement requires one authoritative InnoDB writer for the name range, soft deletes, and `REPEATABLE READ` during +publication. It does not coordinate independent active-active writers. Publication locks the indexed range of unfenced versions, including the gap for new inserts. Every live version needs a matching manifest and must be READY. An elapsed legacy tombstone or expiry needs no manifest: the same transaction preserves its timestamp and fences it against TTL finalization, without publishing cleanup work for it. Fenced rows no @@ -114,10 +129,54 @@ before retrying `ALTER TABLE ... ADD INDEX`; each retry rebuilds the index. Afte version, finalize its TTL by exact primary key, verify one row changed to READY with `deleted_ts IS NULL`, and roll back. Verify the fixture row is absent afterward. Never use a customer row; stop on any error. -## Before enabling a caller +## Single-object named DELETE + +`frontend.named.blob.retirement.namespace` defaults to empty. If set to one `account/container`, authorized native and +S3 single-object named DELETEs for that namespace use retirement instead of the legacy named and router DELETEs. The +writer refuses publication unless `mysql.named.blob.honor.retirement.fence` is enabled. Batch, dataset, and S3 +`versionId` DELETEs are rejected for the selected namespace; multipart aborts and raw-ID DELETEs do not use this path. + +The frontend uses one worker with no queue. Under the DB's admission permit, it selects exact live versions from the +local writer, closes the selection transaction, and fetches only their root metadata by ID. The router bypasses its +negative cache and checks the remaining child budget before allocating the decoded list. Publication rechecks the full +name range under lock. If the commit reply is lost, the same request checks only its exact receipt. A missing or +unreadable receipt returns an error, not success. + +### Pausing named DELETE + +Keep `frontend.named.blob.retirement.namespace` set and set `frontend.named.blob.retirement.paused=true` on each serving +frontend. The pause defaults to `false` and is read at startup. A frontend configured to pause without a namespace fails +to start. A paused frontend rejects authorized single-object named DELETEs in that namespace with HTTP 405 before +selecting roots, publishing a manifest, or invoking legacy DELETE. Nonmatching namespaces are unchanged. Clearing the +namespace restores legacy physical DELETE; it is not a pause mechanism. The pause does not change fence-aware serving or +cleaner exclusions. + +The startup pause does not drain an existing process. A deployment gate must call +`RestServer.drainNamedBlobRetirement(timeout, unit)` on a deployment control thread while the old frontend, writer, and +Netty are still running. Do not call it on a Netty event loop or a worker needed to finish admitted requests. The drain +closes retirement admission and waits for work that can still publish a retirement or recover its receipt, and for the +terminal HTTP write. A completed write does not prove the client received the response; a failed write is terminal and +logged, not grounds for replay. A drain timeout or interruption leaves admission closed and does not cancel work. Keep +ingress blocked and veto shutdown unless the drain succeeds. No deployment system invokes this operation automatically. + +The worker shares a 30-second preparation budget across descriptor waits. It checks the deadline before writer checkout +and again after session setup, before the manifest transaction body. A read-only router operation may still be pending +after a descriptor wait expires. Its result cannot lead to publication, so the drain neither cancels nor waits for it. +The deadline does not interrupt JDBC calls or bound publication or receipt recovery. Rehearse a stalled descriptor read, +a completed publication with a pending response write, and a failed write before activation. A 405 from the replacement +verifies only its own admission gate. + +Before lifting the block, confirm every serving frontend returns 405 for native and S3 DELETE of a disposable live name +without changing the name or its manifest rows. Verify fence-aware reads and cleaner exclusion remain in effect. Resume +by setting `frontend.named.blob.retirement.paused=false` with the same namespace only after the remaining activation +gates are met. Direct DELETE callers still need the separate gate below. + +## Before enabling publication The database operations alone are not safe to activate. In addition to the DELETE and cleaner gates below: +- Rehearse the pause above. Verify that clients and intermediaries will not automatically replay ambiguous DELETEs: + a new HTTP request may target a replacement. - After verifying the migration on every read endpoint, enable `mysql.named.blob.honor.retirement.fence` on every frontend before publishing any retirements. It defaults to `false`, so readers can run against the original schema. When enabled, ordinary and include-expired GET return `Deleted` for a fenced version even if the frontend clock is @@ -162,8 +221,9 @@ The database operations alone are not safe to activate. In addition to the DELET - Admit only namespaces that will stay within the version limit **with cleanup excluded**. PUT keeps older versions: an initial permanent PUT and 32 overwrites can leave 33 unfenced rows. Even below the limit, a live non-composite version cannot supply a composite manifest. Restrict writes accordingly or reconcile history safely first. -- Give the worker indexed discovery of committed publications or durably record the exact tuples before retirement. - A process-local list is lost on restart; a saved tuple is actionable only after publication. +- Before enabling reclamation, give the worker indexed discovery of committed publications or durably record the + exact tuples before retirement. A process-local list is lost on restart; a saved tuple is actionable only after + publication. Before publishing the first manifest, route all frontend and direct named DELETE callers away from legacy DELETE for the enabled namespace, or reject those requests. Also exclude its account or container from `NamedBlobsCleanupRunner` on @@ -171,9 +231,9 @@ every runner, for both stale cleanup and purge. Drain in-flight requests, cleane router deletes. Either path can send a root to the router, which can eagerly delete shared children. If the exclusion cannot be guaranteed (for example, the runner cannot resolve the account), keep the cleaner stopped. -On rollback, disable publication but retain fence-aware reads, the DELETE gate, cleaner exclusion, database fence, +On rollback, pause publication but retain fence-aware reads, the DELETE gate, cleaner exclusion, database fence, index, and published evidence. Do not send affected traffic or cleaner work to an old binary that cannot honor those gates. -This store does not retire raw parent IDs, establish exclusive ownership of chunks, schedule cleanup, or reclaim space. -Those steps and an ownership policy are required before wiring the public DELETE path. +This path does not retire raw parent IDs, establish exclusive ownership of chunks, schedule cleanup, or reclaim space. +Those are separate prerequisites for reclamation. diff --git a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java index 69c053e6c1..7b7cad46e7 100644 --- a/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java +++ b/ambry-named-mysql/src/integration-test/java/com/github/ambry/named/NamedBlobManifestStoreIntegrationTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.*; import java.io.InputStream; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -26,11 +27,13 @@ import java.util.Scanner; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import javax.sql.DataSource; @@ -53,10 +56,12 @@ import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; +import com.github.ambry.store.StoreKeyFactory; import com.github.ambry.utils.MockTime; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.mysql.cj.jdbc.MysqlDataSource; +import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class NamedBlobManifestStoreIntegrationTest { @@ -118,6 +123,12 @@ private static MySqlNamedBlobDb namedDb(DataSource db) throws Exception { return namedDb(db, new Properties(), SystemTime.getInstance()); } + private static MySqlNamedBlobDb namedDb(DataSource db, boolean hardDelete) throws Exception { + Properties properties = new Properties(); + properties.setProperty(MySqlNamedBlobDbConfig.ENABLE_HARD_DELETE, Boolean.toString(hardDelete)); + return namedDb(db, properties, SystemTime.getInstance()); + } + private static MySqlNamedBlobDb namedDb(DataSource db, Properties properties, Time time) throws Exception { properties.setProperty(MySqlNamedBlobDbConfig.DB_INFO, "[{\"url\":\"jdbc:mysql://[::1]\",\"datacenter\":\"local\",\"isWriteable\":true," @@ -134,6 +145,146 @@ private static InMemAccountService fixtureAccounts() throws Exception { return accounts; } + @Test + public void testWiredRetirementConfirmsLostReplyWithoutLoadingReplacement() throws Exception { + withDatabase((db, disabled) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId replacement = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + NamedBlobDb.RetirementLoader loader = mock(NamedBlobDb.RetirementLoader.class); + doReturn(Collections.singletonList(child)).when(loader).load(root, MAX_CHILDREN); + AtomicBoolean committed = new AtomicBoolean(); + doAnswer(call -> { + assertFalse("Receipt recovery must not check the preparation deadline", committed.get()); + return null; + }).when(loader).checkPreparationDeadline(); + try { + disabled.retire(container, NAME, keyFactory, loader); + fail("Fence-aware reads are disabled"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + } + verifyNoInteractions(loader); + try (Connection physical = db.getConnection()) { + Connection lostReply = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + committed.set(true); + insertNamed(db, 2, replacement, NamedBlobState.READY); + throw new SQLException("Simulated lost commit reply", "S1000", new SocketTimeoutException()); + }).when(lostReply).commit(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenAnswer(call -> db.getConnection()).thenReturn(lostReply) + .thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb named = fenceAwareWriter(writer)) { + named.retire(container, NAME, keyFactory, loader); + } + } + verify(loader).load(root, MAX_CHILDREN); + verify(loader, times(2)).checkPreparationDeadline(); + verifyNoMoreInteractions(loader); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE version=1")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE version=2 AND retirement_fenced=FALSE")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1 WHERE version=2")); + }); + } + + @Test + public void testWiredRetirementDoesNotPublishAfterPreparationDeadline() throws Exception { + assertWiredRetirementDoesNotPublishAfterPreparationDeadline(false); + } + + @Test + public void testWiredRetirementDoesNotPublishWhenDeadlineExpiresDuringWriterCheckout() throws Exception { + assertWiredRetirementDoesNotPublishAfterPreparationDeadline(true); + } + + private void assertWiredRetirementDoesNotPublishAfterPreparationDeadline(boolean expiresDuringCheckout) + throws Exception { + withDatabase((db, unused) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + NamedBlobDb.RetirementLoader loader = mock(NamedBlobDb.RetirementLoader.class); + doReturn(Collections.singletonList(child)).when(loader).load(root, MAX_CHILDREN); + AtomicBoolean expired = new AtomicBoolean(!expiresDuringCheckout); + String timeoutMessage = "Preparation timed out"; + doAnswer(call -> { + if (expired.get()) { + throw new RestServiceException(timeoutMessage, RestServiceErrorCode.ServiceUnavailable); + } + return null; + }).when(loader).checkPreparationDeadline(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenAnswer(call -> db.getConnection()).thenAnswer(call -> { + expired.set(true); + return db.getConnection(); + }); + try (MySqlNamedBlobDb named = fenceAwareWriter(writer)) { + try { + named.retire(container, NAME, keyFactory, loader); + fail("Preparation deadline must stop publication"); + } catch (RestServiceException expected) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, expected.getErrorCode()); + assertEquals(timeoutMessage, expected.getMessage()); + } + } + verify(writer, times(expiresDuringCheckout ? 2 : 1)).getConnection(); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=FALSE")); + }); + } + + @Test + public void testWiredRetirementRejectsReplacementAndUnsupportedRootsWithoutMutation() throws Exception { + withDatabase((db, unused) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId replacement = blob(BlobId.BlobDataType.SIMPLE); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + StoreKeyFactory keyFactory = mock(StoreKeyFactory.class); + when(keyFactory.getStoreKey(root.getID())).thenReturn(root); + when(keyFactory.getStoreKey(replacement.getID())).thenReturn(replacement); + Container container = fixtureAccounts().getAccountById(ACCOUNT).getContainerById(CONTAINER); + try (MySqlNamedBlobDb named = fenceAwareWriter(db)) { + try { + named.retire(container, NAME, keyFactory, (selected, limit) -> { + assertEquals(root, selected); + insertNamed(db, 2, replacement, NamedBlobState.READY); + return Collections.singletonList(child); + }); + fail("The original intent did not represent the replacement"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, failure.getErrorCode()); + } + try { + named.retire(container, NAME, keyFactory, (selected, limit) -> { + fail("All roots must be supported before reading any children"); + return Collections.emptyList(); + }); + fail("A simple root is not supported"); + } catch (RestServiceException failure) { + assertEquals(RestServiceErrorCode.Conflict, failure.getErrorCode()); + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(2, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=FALSE")); + }); + } + + private static MySqlNamedBlobDb fenceAwareWriter(DataSource writer) throws Exception { + Properties properties = new Properties(); + properties.setProperty(MySqlNamedBlobDbConfig.HONOR_RETIREMENT_FENCE, "true"); + return namedDb(writer, properties, SystemTime.getInstance()); + } + @Test public void testFenceAwareGetWithSlowFrontend() throws Exception { withDatabase((db, writer) -> { @@ -266,8 +417,7 @@ private static void assertPage(MySqlNamedBlobDb reader, String prefix, String to } /** - * Validate, publish and fence one named version in one call; there is no separate staging step, so the - * descriptors are supplied and consumed in the same transaction that retires the version. + * Capture descriptors in memory, then publish the manifest and fence the named version in one transaction. */ private static void retireOne(MySqlNamedBlobDb db, long version, BlobId root, int count, Iterator children) throws Exception { @@ -287,16 +437,23 @@ private static void retireMany(MySqlNamedBlobDb db, Map pending) throws Exception { - try { - db.retireWithManifests("account", "container", name, pending).get(10, TimeUnit.SECONDS); - } catch (ExecutionException e) { - if (e.getCause() instanceof SQLException) { - throw (SQLException) e.getCause(); - } - throw e; + try (MySqlNamedBlobDb.Retirement retirement = db.prepareRetirement("account", "container", name, () -> pending)) { + retirement.publish(); + } + } + + private static boolean isPublished(MySqlNamedBlobDb db, Map pending) + throws Exception { + try (MySqlNamedBlobDb.Retirement retirement = db.prepareRetirement("account", "container", NAME, () -> pending)) { + return retirement.isPublished(); } } + private static void retireInTransaction(Connection c, String name, + Map pending) throws SQLException { + NamedBlobManifestStore.retire(c, NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, name, pending)); + } + private static Map pendingFor(List versions, Map roots, Map> childrenByVersion) { Map pending = new LinkedHashMap<>(); @@ -333,10 +490,8 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep List ids = children.stream().map(BlobId::getID).collect(Collectors.toList()); insertNamed(db, 7, old, NamedBlobState.READY); insertNamed(db, 8, replacement, NamedBlobState.IN_PROGRESS); - NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - // Retirement only ever covers a contiguous prefix of the unfenced range: an unrequested, still-live version - // blocks retiring an older one, exactly as it did before capture and retire were merged. + // An unrequested, still-live version blocks retiring an older version of the same name. expectDataError("Unrepresented or ineligible", () -> retireOne(named, 7, old, children.size(), children.iterator())); assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); @@ -371,14 +526,13 @@ private static void exercise(DataSource db, MySqlNamedBlobDb named) throws Excep insertNamed(db, 8, replacement, NamedBlobState.READY); retireOne(named, 7, old, children.size(), children.iterator()); // isPublished resolves a lost commit reply from the exact content-bound intent, not merely the version set. - assertTrue(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, - Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), - children.iterator()))))); + assertTrue(isPublished(named, Collections.singletonMap(7L, + new NamedBlobManifestStore.PendingVersion(old, children.size(), children.iterator())))); Map unpublishedPair = new LinkedHashMap<>(); unpublishedPair.put(7L, new NamedBlobManifestStore.PendingVersion(old, children.size(), children.iterator())); unpublishedPair.put(8L, new NamedBlobManifestStore.PendingVersion(replacement, 1, Collections.singletonList(children.get(0)).iterator())); - assertFalse(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, unpublishedPair))); + assertFalse(isPublished(named, unpublishedPair)); assertEquals(replacement.getID(), named.get("account", "container", NAME).get(10, TimeUnit.SECONDS).getBlobId()); // Remove the retired fixture row entirely: a worker that resolves the source name cannot pass. try (Connection c = db.getConnection(); PreparedStatement remove = c.prepareStatement( @@ -458,10 +612,10 @@ public void testStaleSnapshotRetireReplayObservesCommittedPublication() throws E retireOne(named, 1, root, 1, children.iterator()); // A racer whose snapshot predates the winner's commit must still observe the published row when its own // locking read runs: that read is not snapshot-isolated, so the replay is idempotent rather than blind. - NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + retireInTransaction(loser, NAME, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); expectDataError("Conflicting manifest for named version", - () -> NamedBlobManifestStore.retire(loser, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(1L, + () -> retireInTransaction(loser, NAME, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); loser.rollback(); @@ -560,7 +714,7 @@ public void testFenceAwarePutDuringPublication() throws Exception { rc.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); when(checkouts.getConnection()).thenReturn(rr, rc); publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, pending); + retireInTransaction(publisher, NAME, pending); CompletableFuture waiting = writer.put(lower, NamedBlobState.READY, true); awaitCount(publisher, "SELECT COUNT(*) FROM performance_schema.data_lock_waits" + " WHERE BLOCKING_THREAD_ID=PS_CURRENT_THREAD_ID()", 1); @@ -866,7 +1020,7 @@ public void testRetirementLocksGapForReplacement() throws Exception { try (Connection publisher = db.getConnection(); Connection replacement = db.getConnection(); Statement insert = replacement.createStatement()) { publisher.setAutoCommit(false); - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(publisher, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); insert.execute("SET SESSION innodb_lock_wait_timeout=1"); String put = "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" @@ -923,10 +1077,9 @@ public void testPublicationRollsBackWhenNameMutationFails() throws Exception { reversed.sort(Collections.reverseOrder()); try (Connection replay = db.getConnection()) { replay.setAutoCommit(false); - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, - pendingFor(reversed, roots, childrenByVersion)); + retireInTransaction(replay, NAME, pendingFor(reversed, roots, childrenByVersion)); try { - NamedBlobManifestStore.retire(replay, ACCOUNT, CONTAINER, NAME, Collections.emptyMap()); + retireInTransaction(replay, NAME, Collections.emptyMap()); fail("An empty set is not a publication receipt"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); @@ -972,7 +1125,7 @@ public void testWaitingTtlCannotReviveRetiredVersion() throws Exception { + " AND info LIKE 'UPDATE named_blobs_v2 SET blob_state=%'") == 0) { assertTrue("TTL statement never began", System.nanoTime() < deadline && !blocked.isDone()); } - NamedBlobManifestStore.retire(publisher, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(publisher, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); publisher.commit(); assertEquals("45000", blocked.get(10, TimeUnit.SECONDS)); @@ -1152,9 +1305,9 @@ public void testTwoUnrelatedFreshPublicationsDoNotContendOnTheManifestTable() th } // Both are genuinely fresh inserts into the same, otherwise empty manifest table; a preceding locking // read on either absent key would gap-lock the other, and the two inserts would then deadlock (1213). - NamedBlobManifestStore.retire(first, ACCOUNT, CONTAINER, nameA, Collections.singletonMap(1L, + retireInTransaction(first, nameA, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(rootA, 1, childrenA.iterator()))); - NamedBlobManifestStore.retire(second, ACCOUNT, CONTAINER, nameB, Collections.singletonMap(1L, + retireInTransaction(second, nameB, Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(rootB, 1, childrenB.iterator()))); first.commit(); second.commit(); @@ -1199,23 +1352,16 @@ public void testDifferentRootForTheSameVersionCannotImpersonateAPublishedIntent( insertNamed(db, 1, publishedRoot, NamedBlobState.READY); List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); retireOne(named, 1, publishedRoot, 1, children.iterator()); - NamedBlobManifestStore writer = new NamedBlobManifestStore(db); - assertFalse(writer.isPublished(NamedBlobManifestStore.prepare(ACCOUNT, CONTAINER, NAME, - Collections.singletonMap(1L, new NamedBlobManifestStore.PendingVersion(impostorRoot, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator()))))); + assertFalse(isPublished(named, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(impostorRoot, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())))); expectDataError("Conflicting manifest for named version", () -> retireOne(named, 1, impostorRoot, 1, Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); }); } - /** - * The concretely reported gap: retireWithManifests used to capture the caller's own mutable map by reference - * into a lambda queued for a background thread. Everything is now validated and every iterator fully consumed - * into an immutable, caller-retainable description before that dispatch, so mutating or clearing the caller's - * map immediately after the call returns must not change what gets published. - */ @Test - public void testMutatingCallerMapAfterDispatchDoesNotAffectThePublishedContent() throws Exception { + public void testMutatingCallerMapAfterPreparationDoesNotAffectThePublishedContent() throws Exception { withDatabase((db, named) -> { BlobId root = blob(BlobId.BlobDataType.METADATA); BlobId decoy = blob(BlobId.BlobDataType.METADATA); @@ -1223,19 +1369,353 @@ public void testMutatingCallerMapAfterDispatchDoesNotAffectThePublishedContent() List children = Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)); Map pending = new LinkedHashMap<>(); pending.put(1L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator())); - Future future = named.retireWithManifests("account", "container", NAME, pending); - // Mutate the caller's own map immediately after dispatch: a captured reference to this map would let this - // mutation race the background transaction and silently change what it publishes. - pending.clear(); - pending.put(1L, new NamedBlobManifestStore.PendingVersion(decoy, 1, - Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); - future.get(10, TimeUnit.SECONDS); + try (MySqlNamedBlobDb.Retirement retirement = + named.prepareRetirement("account", "container", NAME, () -> pending)) { + pending.clear(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(decoy, 1, + Collections.singletonList(blob(BlobId.BlobDataType.DATACHUNK)).iterator())); + retirement.publish(); + } NamedBlobManifestStore worker = new NamedBlobManifestStore(db); NamedBlobManifestStore.Manifest manifest = worker.getPublished(ACCOUNT, CONTAINER, NAME, 1); assertEquals(root.getID(), manifest.root); }); } + @Test + public void testReplacementDuringEncodingCannotChangeValidatedVersion() throws Exception { + withDatabase((db, named) -> { + BlobId first = blob(BlobId.BlobDataType.METADATA); + BlobId second = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, first, NamedBlobState.READY); + insertNamed(db, 2, second, NamedBlobState.READY); + Map pending = new LinkedHashMap<>(); + pending.put(1L, new NamedBlobManifestStore.PendingVersion(first, 1, new Iterator() { + private boolean consumed; + + @Override + public boolean hasNext() { + return !consumed; + } + + @Override + public BlobId next() { + consumed = true; + pending.put(2L, new NamedBlobManifestStore.PendingVersion(first, MAX_CHILDREN, poisonIterator())); + return child; + } + })); + pending.put(2L, new NamedBlobManifestStore.PendingVersion(second, 1, Collections.singleton(child).iterator())); + retireMany(named, pending); + NamedBlobManifestStore store = new NamedBlobManifestStore(db); + NamedBlobManifestStore.Manifest manifest = store.getPublished(ACCOUNT, CONTAINER, NAME, 2); + assertEquals(second.getID(), manifest.root); + assertEquals(Collections.singletonList(child.getID()), store.read(manifest)); + }); + } + + @Test + public void testAdmissionCoversPreparationAndRecoveryAndReleasesOnFailure() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + ExecutorService preparer = Executors.newSingleThreadExecutor(); + CountDownLatch preparing = new CountDownLatch(1); + CountDownLatch resume = new CountDownLatch(1); + Future preparingFuture = preparer.submit( + () -> named.prepareRetirement("account", "container", NAME, () -> { + preparing.countDown(); + try { + assertTrue(resume.await(10, TimeUnit.SECONDS)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new AssertionError(e); + } + return Collections.emptyMap(); + })); + try { + assertTrue(preparing.await(10, TimeUnit.SECONDS)); + assertRetirementBusy(named); + } finally { + resume.countDown(); + preparer.shutdown(); + } + try { + preparingFuture.get(10, TimeUnit.SECONDS); + fail("No versions were supplied"); + } catch (ExecutionException e) { + assertTrue(e.getCause().toString(), e.getCause() instanceof IllegalArgumentException); + } + insertNamed(db, 1, root, NamedBlobState.READY); + try (MySqlNamedBlobDb.Retirement retirement = named.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + assertFalse(retirement.isPublished()); + retirement.publish(); + assertRetirementBusy(named); + } + retireOne(named, 1, root, 1, Collections.singleton(child).iterator()); + }); + } + + private static void assertRetirementBusy(MySqlNamedBlobDb named) throws Exception { + try { + named.prepareRetirement("account", "container", NAME, () -> { + throw new AssertionError("Rejected request must not fetch descriptors"); + }); + fail("Concurrent preparation was admitted"); + } catch (RestServiceException e) { + assertEquals(RestServiceErrorCode.ServiceUnavailable, e.getErrorCode()); + } + } + + @Test + public void testExactHandleConfirmsLostReplyAfterOverCapReplacement() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection physical = db.getConnection()) { + Connection lostReply = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + throw new SQLException("Simulated lost commit reply", "S1000", new SocketTimeoutException()); + }).when(lostReply).commit(); + DataSource writer = mock(DataSource.class); + when(writer.getConnection()).thenReturn(lostReply).thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb withLostReply = namedDb(writer); + MySqlNamedBlobDb.Retirement retirement = withLostReply.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + assertLostReplyAndRecover(db, retirement, root, child); + } + verify(lostReply, never()).rollback(); + } + }); + } + + private static void assertLostReplyAndRecover(DataSource db, MySqlNamedBlobDb.Retirement retirement, BlobId root, + BlobId child) throws Exception { + try (Connection stale = db.getConnection(); Statement snapshot = stale.createStatement()) { + stale.setAutoCommit(false); + try (ResultSet rs = snapshot.executeQuery("SELECT COUNT(*) FROM named_blob_manifests_v1")) { + assertTrue(rs.next()); + assertEquals(0, rs.getInt(1)); + } + try { + retirement.publish(); + fail("Expected the commit reply to be lost"); + } catch (SQLException e) { + assertEquals("Simulated lost commit reply", e.getMessage()); + } + for (int version = 2; version <= 34; version++) { + insertNamed(db, version, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + } + expectDataError("Unsupported named version range", + () -> retireInTransaction(stale, NAME, Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))); + stale.rollback(); + } + assertTrue(retirement.isPublished()); + retirement.publish(); + assertEquals(33, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE retirement_fenced=FALSE")); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + + @Test + public void testRetirementRejectsActiveWriterTransactionWithoutCommittingIt() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection writer = db.getConnection(); Statement sql = writer.createStatement()) { + sql.execute("START TRANSACTION"); + assertEquals(1, sql.executeUpdate("UPDATE named_blobs_v2 SET blob_size=123")); + assertTrue(writer.getAutoCommit()); + DataSource source = mock(DataSource.class); + when(source.getConnection()).thenReturn(writer); + try (MySqlNamedBlobDb unsafe = namedDb(source); + MySqlNamedBlobDb.Retirement retirement = unsafe.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + try { + retirement.publish(); + fail("Borrowed an active writer transaction"); + } catch (SQLException e) { + assertTrue(e.getMessage(), e.getMessage().contains("idle autocommit")); + } + } + } + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blobs_v2 WHERE blob_size=123 OR retirement_fenced")); + }); + } + + @Test + public void testPublishOverridesPendingReadCommittedAndLocksNamingGap() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + try (Connection physical = db.getConnection(); Statement setting = physical.createStatement(); + Connection competing = db.getConnection(); Statement limit = competing.createStatement()) { + setting.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + limit.execute("SET SESSION innodb_lock_wait_timeout=1"); + Connection writer = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + // Probe after the range was read but before any manifest or named-row write. + try { + insertNamed(competing, NAME, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + fail("A replacement entered the name range before publication"); + } catch (SQLException expected) { + assertEquals(expected.getMessage(), 1205, expected.getErrorCode()); + } + return physical.prepareStatement(call.getArgument(0)); + }).when(writer).prepareStatement(startsWith("INSERT INTO named_blob_manifests_v1")); + DataSource checkout = mock(DataSource.class); + when(checkout.getConnection()).thenReturn(writer).thenAnswer(call -> db.getConnection()); + try (MySqlNamedBlobDb isolated = namedDb(checkout); + MySqlNamedBlobDb.Retirement retirement = isolated.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + retirement.publish(); + assertTrue(retirement.isPublished()); + } + verify(writer).prepareStatement(startsWith("INSERT INTO named_blob_manifests_v1")); + insertNamed(competing, NAME, 2, blob(BlobId.BlobDataType.METADATA), NamedBlobState.READY); + } + }); + } + + @Test + public void testRetirementRestoresPooledTimeoutAndEvictsAfterReadStall() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + insertNamed(db, 1, root, NamedBlobState.READY); + MysqlDataSource source; + try (Connection connection = db.getConnection()) { + source = source(connection.getCatalog()); + } + source.setSocketTimeout(0); + HikariConfig config = new HikariConfig(); + config.setDataSource(source); + config.setMaximumPoolSize(1); + config.setConnectionInitSql("SET SESSION innodb_lock_wait_timeout=15"); + try (HikariDataSource pool = new HikariDataSource(config); + MySqlNamedBlobDb pooled = namedDb(pool); + MySqlNamedBlobDb.Retirement retirement = pooled.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(1L, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + int originalId = ordinaryCheckout(pool, 0); + assertFalse(retirement.isPublished()); + assertEquals(originalId, ordinaryCheckout(pool, 0)); + + try (Connection blocker = db.getConnection(); Statement lock = blocker.createStatement()) { + blocker.setAutoCommit(false); + try (ResultSet locked = lock.executeQuery("SELECT version FROM named_blobs_v2 FOR UPDATE")) { + assertTrue(locked.next()); + } + try { + retirement.publish(); + fail("Published while another transaction held the row lock"); + } catch (SQLException expected) { + Throwable cause = expected; + while (cause != null && !(cause instanceof SocketTimeoutException)) { + cause = cause.getCause(); + } + assertNotNull(expected.toString(), cause); + } finally { + blocker.rollback(); + } + } + int replacementId = ordinaryCheckout(pool, 0); + assertNotEquals(originalId, replacementId); + assertFalse(retirement.isPublished()); + retirement.publish(); + assertTrue(retirement.isPublished()); + assertEquals(replacementId, ordinaryCheckout(pool, 0)); + assertEquals(1, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + }); + } + + @Test + public void testRetirementPreservesCommitAndEvictsWhenTimeoutRestoreFails() throws Exception { + withDatabase((db, named) -> { + BlobId root = blob(BlobId.BlobDataType.METADATA); + BlobId child = blob(BlobId.BlobDataType.DATACHUNK); + long version = 1; + insertNamed(db, version, root, NamedBlobState.READY); + try (Connection physical = db.getConnection()) { + int originalTimeout = physical.getNetworkTimeout(); + AtomicBoolean committed = new AtomicBoolean(); + AtomicBoolean restoreFailed = new AtomicBoolean(); + Connection failingRestore = mock(Connection.class, delegatesTo(physical)); + doAnswer(call -> { + physical.commit(); + committed.set(true); + return null; + }).when(failingRestore).commit(); + doAnswer(call -> { + // Fail only the first restore so a later Hikari health check cannot mask a missing eviction. + if (committed.get() && restoreFailed.compareAndSet(false, true)) { + throw new SQLException("Socket timeout restore failed", "HY000"); + } + physical.setNetworkTimeout(call.getArgument(0), originalTimeout); + return null; + }).when(failingRestore).setNetworkTimeout(any(), eq(originalTimeout)); + DataSource checkout = mock(DataSource.class); + when(checkout.getConnection()).thenReturn(failingRestore).thenAnswer(call -> db.getConnection()); + HikariConfig config = new HikariConfig(); + config.setDataSource(checkout); + // Keep the injected checkout but select Hikari's synchronous MySQL timeout executor. + config.setJdbcUrl(physical.getMetaData().getURL()); + config.setMaximumPoolSize(1); + config.setConnectionTimeout(3000); + try (HikariDataSource pool = new HikariDataSource(config); + MySqlNamedBlobDb pooled = namedDb(pool); + MySqlNamedBlobDb.Retirement retirement = pooled.prepareRetirement("account", "container", NAME, + () -> Collections.singletonMap(version, + new NamedBlobManifestStore.PendingVersion(root, 1, Collections.singleton(child).iterator())))) { + int originalId = ordinaryCheckout(pool, originalTimeout); + retirement.publish(); + assertTrue("Timeout restoration must fail after the real commit", restoreFailed.get()); + assertNotEquals("The next borrower must get a different physical connection", originalId, + ordinaryCheckout(pool, originalTimeout)); + assertTrue("The exact receipt must survive the cleanup failure", retirement.isPublished()); + } + } + }); + } + + private static int ordinaryCheckout(DataSource pool, int expectedTimeout) throws SQLException { + try (Connection c = pool.getConnection(); Statement s = c.createStatement(); + ResultSet rows = s.executeQuery("SELECT CONNECTION_ID()")) { + assertEquals(expectedTimeout, c.getNetworkTimeout()); + assertTrue(c.getAutoCommit()); + assertTrue(rows.next()); + return rows.getInt(1); + } + } + + @Test + public void testHardDeleteRejectsBeforeLoadingDescriptors() throws Exception { + withDatabase((db, named) -> { + try (MySqlNamedBlobDb hardDelete = namedDb(db, true)) { + try { + hardDelete.prepareRetirement("account", "container", NAME, () -> { + throw new AssertionError("Hard-delete mode must not fetch descriptors"); + }); + fail("Accepted manifest retirement in hard-delete mode"); + } catch (UnsupportedOperationException expected) { + assertEquals(0, scalar(db, "SELECT COUNT(*) FROM named_blob_manifests_v1")); + } + } + }); + } + /** * The actual race the guard and the lock order exist for: a retire that has locked the named range (but not yet * committed its manifest insert) must block a concurrent direct replace for the same tuple. Once it commits, @@ -1251,7 +1731,7 @@ public void testConcurrentRetireBlocksRacingDirectReplaceThenRejectsReuse() thro try (Connection retiring = db.getConnection(); Connection replacing = db.getConnection(); Statement replace = replacing.createStatement()) { retiring.setAutoCommit(false); - NamedBlobManifestStore.retire(retiring, ACCOUNT, CONTAINER, NAME, Collections.singletonMap(7L, + retireInTransaction(retiring, NAME, Collections.singletonMap(7L, new NamedBlobManifestStore.PendingVersion(root, 1, children.iterator()))); replace.execute("SET SESSION innodb_lock_wait_timeout=1"); try { @@ -1399,6 +1879,7 @@ private static MysqlDataSource source(String schema) throws SQLException { } db.setDatabaseName(schema); db.setServerTimezone("UTC"); + db.setSocketTimeout(15_000); // Mirror production's Hikari useServerPrepStmts=true so large-payload tests exercise the same statement mode. db.setUseServerPrepStmts(true); return db; @@ -1438,7 +1919,14 @@ private static void insertNamed(DataSource db, long version, BlobId root, NamedB private static void insertNamed(DataSource db, String name, long version, BlobId root, NamedBlobState state) throws SQLException { - try (Connection c = db.getConnection(); PreparedStatement s = c.prepareStatement( + try (Connection c = db.getConnection()) { + insertNamed(c, name, version, root, state); + } + } + + private static void insertNamed(Connection c, String name, long version, BlobId root, NamedBlobState state) + throws SQLException { + try (PreparedStatement s = c.prepareStatement( "INSERT INTO named_blobs_v2 (account_id,container_id,blob_name,version,blob_id,blob_state)" + " VALUES (?,?,?,?,?,?)")) { s.setShort(1, ACCOUNT); diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java index 463d0c5a21..770fa8d489 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/MySqlNamedBlobDb.java @@ -22,6 +22,7 @@ import com.github.ambry.account.Account; import com.github.ambry.account.AccountService; import com.github.ambry.account.Container; +import com.github.ambry.commons.BlobId; import com.github.ambry.commons.Callback; import com.github.ambry.commons.RetryExecutor; import com.github.ambry.commons.RetryPolicies; @@ -33,6 +34,8 @@ import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.rest.RestServiceErrorCode; import com.github.ambry.rest.RestServiceException; +import com.github.ambry.store.StoreKey; +import com.github.ambry.store.StoreKeyFactory; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import com.github.ambry.utils.Utils; @@ -41,10 +44,14 @@ import com.mysql.cj.jdbc.JdbcConnection; import com.zaxxer.hikari.HikariDataSource; import java.io.Closeable; +import java.io.EOFException; import java.io.IOException; +import java.net.SocketException; +import java.net.SocketTimeoutException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.SQLDataException; import java.sql.SQLException; import java.sql.SQLNonTransientConnectionException; import java.sql.SQLTransientConnectionException; @@ -57,6 +64,7 @@ import java.util.Deque; import java.util.HashSet; import java.util.IdentityHashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -64,8 +72,10 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.sql.DataSource; @@ -84,6 +94,7 @@ public class MySqlNamedBlobDb implements NamedBlobDb { private static final Logger logger = LoggerFactory.getLogger(MySqlNamedBlobDb.class); private static final int MAX_NUMBER_OF_VERSIONS_IN_DELETE = 1000; private static final int VERSION_BASE = 100000; + private static final int RETIREMENT_READ_TIMEOUT_MS = 5_000; private final Time time; private static final String MULTI_VERSION_PLACE_HOLDER = "MULTI_VERSION_PLACE_HOLDER"; @@ -189,6 +200,8 @@ public class MySqlNamedBlobDb implements NamedBlobDb { private final Map transactionExecutors; private final MySqlNamedBlobDbConfig config; private final Metrics metricsRecoder; + // Reserve one worst-case encoded request (32 MiB), including while its caller decides whether to retry. + private final Semaphore retirementSlot = new Semaphore(1); MySqlNamedBlobDb(AccountService accountService, MySqlNamedBlobDbConfig config, DataSourceFactory dataSourceFactory, String localDatacenter, Metrics metricRecorder, Time time) { @@ -467,45 +480,177 @@ public CompletableFuture updateBlobTtlAndStateToReady(NamedBlobRecord } /** - * Validate, publish and fence this exact set of named versions in one transaction. Never returns IDs for a - * router cascade. There is no separate staging step: a version's descriptors are supplied and consumed in the - * same call that retires it. Everything is validated and every iterator is fully consumed into an immutable - * {@link NamedBlobManifestStore.PreparedRetirement} synchronously, before this is handed to the background - * transaction thread: the thread never sees {@code pendingVersions} itself, so the caller mutating or clearing - * that map after this call returns cannot change what gets published. + * Admit and prepare one exact intent. The supplier must defer fetching descriptors until invoked. This blocks, + * as do the returned handle's methods; callers must run it off the event loop and close the handle on all paths. */ - CompletableFuture retireWithManifests(String accountName, String containerName, String blobName, - Map pendingVersions) { + Retirement prepareRetirement(String accountName, String containerName, String blobName, + Supplier> pendingVersions) throws RestServiceException, + SQLException { + if (config.enableHardDelete) { + throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + } Account account = accountService.getAccountByName(accountName); if (account == null) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally( - new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound)); - return failed; + throw new RestServiceException("Account not found: " + accountName, RestServiceErrorCode.NotFound); } Container container = account.getContainerByName(containerName); if (container == null) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally( - new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound)); - return failed; + throw new RestServiceException("Container not found: " + containerName, RestServiceErrorCode.NotFound); + } + return prepareRetirement(container, blobName, writer -> pendingVersions.get()); + } + + @FunctionalInterface + private interface RetirementInput { + Map load(TransactionExecutor writer) throws E; + } + + private Retirement prepareRetirement(Container container, String blobName, + RetirementInput input) throws RestServiceException, SQLException, E { + TransactionExecutor writer = transactionExecutors.get(localDatacenter); + if (writer == null || writer.executor.isShutdown()) { + throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + if (!retirementSlot.tryAcquire()) { + throw new RestServiceException("Named retirement already in progress", RestServiceErrorCode.ServiceUnavailable); } - NamedBlobManifestStore.PreparedRetirement prepared; + boolean prepared = false; try { - prepared = NamedBlobManifestStore.prepare((short) account.getId(), (short) container.getId(), blobName, - pendingVersions); - } catch (SQLException e) { - CompletableFuture failed = new CompletableFuture<>(); - failed.completeExceptionally(e); - return failed; + Retirement retirement = new Retirement(writer, + NamedBlobManifestStore.prepare(container.getParentAccountId(), container.getId(), blobName, + input.load(writer))); + prepared = true; + return retirement; + } finally { + if (!prepared) { + retirementSlot.release(); + } + } + } + + @Override + public void retire(Container container, String blobName, StoreKeyFactory keyFactory, RetirementLoader loader) + throws Exception { + if (!config.honorRetirementFence || config.enableHardDelete) { + throw new RestServiceException("Named retirement requires fence-aware soft delete", + RestServiceErrorCode.ServiceUnavailable); } - return executeTransactionAsync(accountName, containerName, false, (ignoredAccount, ignoredContainer, connection) -> { - if (config.enableHardDelete) { - throw new UnsupportedOperationException("Manifest retirement requires named soft delete"); + short accountId = container.getParentAccountId(); + short containerId = container.getId(); + try (Retirement retirement = prepareRetirement(container, blobName, writer -> { + Map roots = writer.runRetirementTransaction( + connection -> NamedBlobManifestStore.selectRoots(connection, accountId, containerId, blobName, keyFactory)); + if (roots.isEmpty()) { + throw new RestServiceException("Named blob does not have a live version", RestServiceErrorCode.NotFound); + } + Map pending = new LinkedHashMap<>(); + int remaining = NamedBlobManifestStore.MAX_CHILDREN; + for (Map.Entry entry : roots.entrySet()) { + if (remaining == 0) { + throw new SQLDataException("Too many children for named retirement"); + } + List children = loader.load(entry.getValue(), remaining); + if (children == null || children.isEmpty() || children.size() > remaining) { + throw new SQLDataException("Invalid child list for named retirement"); + } + remaining -= children.size(); + pending.put(entry.getKey(), + new NamedBlobManifestStore.PendingVersion(entry.getValue(), children.size(), children.iterator())); } - NamedBlobManifestStore.retire(connection, prepared); - return null; - }, null, metricsRecoder.namedBlobDBDeleteErrorCount); + return pending; + })) { + loader.checkPreparationDeadline(); + try { + retirement.publish(loader::checkPreparationDeadline); + } catch (RetirementPreparationExpired expired) { + // The manifest transaction body was never entered, so there is no receipt to recover. + throw expired; + } catch (Exception publishFailure) { + // Never rediscover the name after a failed publish: it could already point to a replacement. + try { + if (retirement.isPublished()) { + return; + } + } catch (Exception confirmationFailure) { + if (publishFailure != confirmationFailure) { + publishFailure.addSuppressed(confirmationFailure); + } + } + throw new RestServiceException("Named retirement was not confirmed", publishFailure, + RestServiceErrorCode.ServiceUnavailable); + } + } catch (SQLDataException unsupported) { + throw new RestServiceException("Named blob history cannot be retired", unsupported, RestServiceErrorCode.Conflict); + } + } + + @FunctionalInterface + private interface PreparationDeadline { + void check() throws RestServiceException; + } + + private static final class RetirementPreparationExpired extends RestServiceException { + RetirementPreparationExpired(RestServiceException cause) { + super(cause.getMessage(), cause, cause.getErrorCode()); + } + } + + /** Owns the admission slot and the encoded bytes until close. Never queues a payload. */ + final class Retirement implements AutoCloseable { + private final TransactionExecutor writer; + private NamedBlobManifestStore.PreparedRetirement prepared; + + private Retirement(TransactionExecutor writer, NamedBlobManifestStore.PreparedRetirement prepared) { + this.writer = writer; + this.prepared = prepared; + } + + void publish() throws Exception { + publish(() -> { }); + } + + private synchronized void publish(PreparationDeadline deadline) throws Exception { + run(connection -> { + try { + deadline.check(); + } catch (RestServiceException expired) { + throw new RetirementPreparationExpired(expired); + } + NamedBlobManifestStore.retire(connection, prepared); + return null; + }); + } + + /** A negative result means "not observed"; only a positive exact receipt confirms publication. */ + synchronized boolean isPublished() throws Exception { + return run(connection -> NamedBlobManifestStore.matchesReceipt(connection, prepared)); + } + + private T run(TransactionGeneric transaction) throws Exception { + if (prepared == null) { + throw new IllegalStateException("Named retirement is closed"); + } + if (writer.executor.isShutdown()) { + throw new RestServiceException("Named retirement writer is unavailable", RestServiceErrorCode.ServiceUnavailable); + } + try { + return writer.runRetirementTransaction(transaction); + } catch (Exception | Error e) { + writer.recordConnectionFailure(e); + if (e instanceof SQLException) { + metricsRecoder.namedBlobDBDeleteErrorCount.inc(); + } + throw e; + } + } + + @Override + public synchronized void close() { + if (prepared != null) { + prepared = null; + retirementSlot.release(); + } + } } @Override @@ -735,7 +880,7 @@ private static class TransactionExecutor implements Closeable { /** * Whether the given throwable represents a JDBC connection failure (vs. any other SQL error). * - *

Three independent positive signals, all spec-defined as connection-class: + *

Positive signals include: *

    *
  1. {@link SQLNonTransientConnectionException} — JDBC's non-transient connection-failure * subclass; MySQL {@code CommunicationsException} extends this.
  2. @@ -746,6 +891,7 @@ private static class TransactionExecutor implements Closeable { *
* *

The walk includes causes, chained SQL exceptions and suppressed cleanup failures. + * Connector/J can wrap a socket failure in a generic SQLException. * SQLSTATE "40*" (transaction rollback), "57*" (operator intervention), and other * adjacent classes are intentionally NOT counted — those are not connection failures. */ @@ -761,7 +907,8 @@ private static boolean isConnectionFailure(Throwable t) { if (!seen.add(cur)) { continue; } - if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException) { + if (cur instanceof SQLNonTransientConnectionException || cur instanceof SQLTransientConnectionException + || cur instanceof SocketTimeoutException || cur instanceof SocketException || cur instanceof EOFException) { return true; } if (cur instanceof SQLException) { @@ -789,6 +936,12 @@ void executeTransaction(Container container, boolean autoCommit, Transaction connection -> transaction.run(container.getParentAccountId(), container.getId(), connection), callback); } + private void recordConnectionFailure(Throwable failure) { + if (isConnectionFailure(failure)) { + connectionFailureCount.inc(); + } + } + void executeTransactionGeneric(boolean autoCommit, TransactionGeneric transaction, Callback callback) { final long enqueueTimeMs = System.currentTimeMillis(); try { @@ -796,11 +949,9 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra enqueueWaitTimeInMs.update(System.currentTimeMillis() - enqueueTimeMs); T result; try { - result = runTransaction(autoCommit, transaction); + result = runTransaction(autoCommit ? TransactionMode.AUTOCOMMIT : TransactionMode.EXPLICIT, transaction); } catch (Exception | Error e) { - if (isConnectionFailure(e)) { - connectionFailureCount.inc(); - } + recordConnectionFailure(e); callback.onCompletion(null, e instanceof Exception ? (Exception) e : new IllegalStateException(e)); return; } @@ -811,13 +962,51 @@ void executeTransactionGeneric(boolean autoCommit, TransactionGeneric tra } } - private T runTransaction(boolean autoCommit, TransactionGeneric transaction) throws Exception { + private enum TransactionMode { + AUTOCOMMIT, EXPLICIT, RETIREMENT + } + + private T runRetirementTransaction(TransactionGeneric transaction) throws Exception { + return runTransaction(TransactionMode.RETIREMENT, transaction); + } + + private T runTransaction(TransactionMode mode, TransactionGeneric transaction) throws Exception { + boolean autoCommit = mode == TransactionMode.AUTOCOMMIT; + boolean retirement = mode == TransactionMode.RETIREMENT; Connection connection = dataSource.getConnection(); + int timeoutToRestore = -1; + if (retirement) { + try { + JdbcConnection driver = requireFixedRetirementSession(connection); + int originalTimeout = connection.getNetworkTimeout(); + if (originalTimeout == 0 || originalTimeout > RETIREMENT_READ_TIMEOUT_MS) { + connection.setNetworkTimeout(Runnable::run, RETIREMENT_READ_TIMEOUT_MS); + timeoutToRestore = originalTimeout; + } + requireIdleRetirementSession(connection, driver); + } catch (Exception | Error failure) { + // This connection may contain someone else's transaction. Do not reset autocommit. + discardConnection(connection, failure); + throw failure; + } + } final T result; try { if (!autoCommit) { connection.setAutoCommit(false); } + if (retirement) { + try (Statement check = connection.createStatement(); + ResultSet settings = check.executeQuery("SELECT @@session.autocommit")) { + if (!settings.next() || settings.getBoolean(1)) { + throw new SQLException("Named retirement could not disable autocommit"); + } + } + // A per-transaction override is not visible in @@session.transaction_isolation. + try (Statement statement = connection.createStatement()) { + statement.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + } + } result = transaction.run(connection); if (!autoCommit) { connection.commit(); @@ -827,6 +1016,10 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti discardConnection(connection, failure); throw failure; } catch (Exception | Error failure) { + if (retirement && isConnectionFailure(failure)) { + discardConnection(connection, failure); + throw failure; + } if (!autoCommit) { try { connection.rollback(); @@ -839,31 +1032,56 @@ private T runTransaction(boolean autoCommit, TransactionGeneric transacti throw failure; } } - returnConnection(connection, autoCommit, failure); + returnConnection(connection, autoCommit, timeoutToRestore, failure); throw failure; } - returnConnection(connection, autoCommit, null); + returnConnection(connection, autoCommit, timeoutToRestore, null); return result; } - private void returnConnection(Connection connection, boolean autoCommit, Throwable operationFailure) { + private static JdbcConnection requireFixedRetirementSession(Connection connection) throws SQLException { + JdbcConnection driver = connection.unwrap(JdbcConnection.class); + if (!(driver instanceof ConnectionImpl) || driver.isProxySet() + || driver.getPropertySet().getBooleanProperty(PropertyKey.autoReconnect).getValue() + || driver.getPropertySet().getBooleanProperty(PropertyKey.autoReconnectForPools).getValue() + || driver.getPropertySet().getBooleanProperty(PropertyKey.reconnectAtTxEnd).getValue()) { + throw new SQLException("Named retirement requires a fixed physical MySQL session"); + } + return driver; + } + + private static void requireIdleRetirementSession(Connection connection, JdbcConnection driver) throws SQLException { + try (Statement check = connection.createStatement()) { + check.setFetchSize(0); + try (ResultSet settings = check.executeQuery("SELECT @@session.autocommit, @@session.transaction_isolation")) { + if (!settings.next() || !settings.getBoolean(1) || !"REPEATABLE-READ".equals(settings.getString(2)) + || driver.getSession().getServerSession().inTransactionOnServer()) { + throw new SQLException("Named retirement requires an idle autocommit REPEATABLE READ session"); + } + } + } + } + + private void returnConnection(Connection connection, boolean autoCommit, int timeoutToRestore, + Throwable operationFailure) { try { - if (!autoCommit) { - try { + try { + if (!autoCommit) { connection.setAutoCommit(true); - } catch (Exception | Error resetFailure) { - // Hikari can recycle a connection even when a reset inside close() fails. - discardConnection(connection, resetFailure); - throw resetFailure; } + if (timeoutToRestore >= 0) { + connection.setNetworkTimeout(Runnable::run, timeoutToRestore); + } + } catch (Exception | Error resetFailure) { + // Hikari can recycle a connection even when a reset inside close() fails. + discardConnection(connection, resetFailure); + throw resetFailure; } connection.close(); } catch (Exception | Error cleanupFailure) { metrics.connectionCloseErrorCount.inc(); if (operationFailure == null) { - if (isConnectionFailure(cleanupFailure)) { - connectionFailureCount.inc(); - } + recordConnectionFailure(cleanupFailure); } else if (operationFailure != cleanupFailure) { operationFailure.addSuppressed(cleanupFailure); } diff --git a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java index 9ebab8f921..e61788af75 100644 --- a/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java +++ b/ambry-named-mysql/src/main/java/com/github/ambry/named/NamedBlobManifestStore.java @@ -4,6 +4,7 @@ */ package com.github.ambry.named; +import java.io.IOException; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; @@ -24,11 +25,12 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import java.util.TreeSet; +import java.util.TreeMap; import javax.sql.DataSource; import com.github.ambry.commons.BlobId; import com.github.ambry.protocol.NamedBlobState; import com.github.ambry.store.StoreKey; +import com.github.ambry.store.StoreKeyFactory; /** * Detached evidence for one immutable root at one named version. A row in {@code named_blob_manifests_v1} exists @@ -48,12 +50,16 @@ final class NamedBlobManifestStore { // Length-prefixed child descriptors: an unsigned length byte followed by 1..127 blob ID bytes, repeated for every // declared child. The maximum encoded body is 32 MiB before driver and protocol overhead. private static final int MAX_ID_BYTES = 127; - private static final int MAX_CHILDREN = 262144; + static final int MAX_CHILDREN = 262144; private static final int MAX_VERSIONS = 32; private static final String TABLE = "named_blob_manifests_v1"; private static final String HEADER_COLUMNS = "account_id,container_id,blob_name,version,root_id,child_count,publication_key"; private static final String KEY = "account_id=? AND container_id=? AND blob_name=? AND version=?"; + private static final String SELECT_UNFENCED = "SELECT blob_name,version,blob_id,blob_state," + + "(deleted_ts IS NOT NULL AND deleted_ts<=UTC_TIMESTAMP(6)) FROM named_blobs_v2" + + " FORCE INDEX (named_blob_unfenced_versions) WHERE account_id=? AND container_id=? AND blob_name=?" + + " AND retirement_fenced=FALSE ORDER BY version LIMIT ?"; private final DataSource db; @@ -61,6 +67,50 @@ final class NamedBlobManifestStore { this.db = Objects.requireNonNull(db, "db"); } + /** Read the same bounded range publication will validate under lock, without holding locks during router IO. */ + static Map selectRoots(Connection c, short account, short container, String name, + StoreKeyFactory keyFactory) throws SQLException, IOException { + Map roots = new LinkedHashMap<>(); + try (PreparedStatement s = c.prepareStatement(SELECT_UNFENCED)) { + bindUnfenced(s, account, container, name); + try (ResultSet r = s.executeQuery()) { + int rows = 0; + while (r.next()) { + if (++rows > MAX_VERSIONS || !name.equals(r.getString(1))) { + throw new SQLDataException("Unsupported named version range"); + } + if (r.getBoolean(5)) { + continue; + } + byte[] bytes = r.getBytes(3); + if (r.getInt(4) != NamedBlobState.READY.ordinal() || bytes == null || bytes.length == 0) { + throw new SQLDataException("Ineligible named version"); + } + StoreKey key = keyFactory.getStoreKey(Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)); + if (!(key instanceof BlobId) || !Arrays.equals(bytes, key.toBytes()) + || !isCompositeRoot((BlobId) key, account, container)) { + throw new SQLDataException("Unsupported named composite capture"); + } + roots.put(r.getLong(2), (BlobId) key); + } + } + } + return roots; + } + + private static void bindUnfenced(PreparedStatement s, short account, short container, String name) + throws SQLException { + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setInt(4, MAX_VERSIONS + 1); + } + + private static boolean isCompositeRoot(BlobId root, short account, short container) { + return root.sizeInBytes() >= 1 && root.sizeInBytes() <= 50 && root.getAccountId() == account + && root.getContainerId() == container && root.getBlobDataType() == BlobId.BlobDataType.METADATA; + } + private static void requireCommittedReads(Connection c) throws SQLException { int isolation = c.getTransactionIsolation(); if (isolation != Connection.TRANSACTION_READ_COMMITTED && isolation != Connection.TRANSACTION_REPEATABLE_READ @@ -83,36 +133,37 @@ static final class PendingVersion { } /** - * An entire publication request, fully validated and fully encoded: every iterator has already been consumed - * into an immutable {@code byte[]} body, and every bound (per-version and aggregate child count, root shape) has - * already been checked. It owns its own bytes rather than the caller's map or iterators, so it is safe to retain - * across an asynchronous dispatch boundary and hand to a background thread. + * An immutable publication request that owns its encoded bytes for publication, confirmation, and replay. */ static final class PreparedRetirement { final short account; final short container; final String name; - final List requested; - private final Map rootBytes; - private final Map rootIds; - private final Map counts; - private final Map bodies; - private final Map rowHashes; + private final Map versions; private final byte[] intentToken; - private PreparedRetirement(short account, short container, String name, List requested, - Map rootBytes, Map rootIds, Map counts, Map bodies, - Map rowHashes, byte[] intentToken) { + private PreparedRetirement(short account, short container, String name, Map versions) { this.account = account; this.container = container; this.name = name; - this.requested = Collections.unmodifiableList(requested); - this.rootBytes = Collections.unmodifiableMap(rootBytes); - this.rootIds = Collections.unmodifiableMap(rootIds); - this.counts = Collections.unmodifiableMap(counts); - this.bodies = Collections.unmodifiableMap(bodies); - this.rowHashes = Collections.unmodifiableMap(rowHashes); - this.intentToken = intentToken; + this.versions = Collections.unmodifiableMap(versions); + this.intentToken = intentToken(name, versions); + } + } + + private static final class PreparedVersion { + private final byte[] root; + private final int count; + private final byte[] body; + private final byte[] hash; + + private PreparedVersion(short account, short container, String name, long version, PendingVersion pending) + throws SQLException { + root = pending.root.toBytes(); + count = pending.expected; + body = encode(pending.descriptors, count, root); + hash = hash(account, container, name, version, count, + Base64.getUrlEncoder().withoutPadding().encodeToString(root), body); } } @@ -139,32 +190,10 @@ private static byte[] encode(Iterator descriptors, int expec private static void bindKey(PreparedStatement s, short account, short container, String name, long version) throws SQLException { - bindKey(s, account, container, name, version, 1); - } - - private static void bindKey(PreparedStatement s, short account, short container, String name, long version, int at) - throws SQLException { - s.setInt(at, account); - s.setInt(at + 1, container); - s.setString(at + 2, name); - s.setLong(at + 3, version); - } - - static void checkManifestCount(List versions) { - if (versions == null || versions.isEmpty() || versions.size() > MAX_VERSIONS) { - throw new IllegalArgumentException("Invalid number of manifests"); - } - } - - static List canonicalVersions(List versions) { - checkManifestCount(versions); - TreeSet sorted = new TreeSet<>(); - for (Long version : versions) { - if (version == null || !sorted.add(version)) { - throw new IllegalArgumentException("Expected distinct canonical manifest versions"); - } - } - return new ArrayList<>(sorted); + s.setInt(1, account); + s.setInt(2, container); + s.setString(3, name); + s.setLong(4, version); } /** @@ -172,8 +201,7 @@ static List canonicalVersions(List versions) { * exactly what will be published. Every declared bound -- per-version child count, aggregate child count across * the whole request, root shape -- is checked purely against caller-supplied values before a single iterator is * touched, a payload is encoded, or a connection is opened: a doomed oversized request never reads or hashes a - * byte. The result owns its own encoded bytes and holds no reference to {@code pending}, so it is safe to retain - * and hand to another thread for asynchronous publication. + * byte. The result holds no reference to {@code pending} or its iterators. */ static PreparedRetirement prepare(short account, short container, String name, Map pending) throws SQLException { @@ -181,22 +209,27 @@ static PreparedRetirement prepare(short account, short container, String name, M throw new SQLDataException("Unsupported named composite capture"); } Objects.requireNonNull(pending, "pending"); - List requested = canonicalVersions(new ArrayList<>(pending.keySet())); - - long totalDeclared = 0; - Map counts = new LinkedHashMap<>(); - for (long version : requested) { - PendingVersion p = pending.get(version); - if (p == null) { - throw new IllegalArgumentException("Missing pending descriptors for version " + version); + // Copy both key and value, not Map.Entry references that may continue to reflect changes to the caller's map. + Map captured = new TreeMap<>(); + for (Map.Entry entry : pending.entrySet()) { + Long version = entry.getKey(); + PendingVersion input = entry.getValue(); + if (captured.size() >= MAX_VERSIONS) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + if (version == null || input == null || captured.putIfAbsent(version, input) != null) { + throw new IllegalArgumentException("Invalid pending manifest versions"); } + } + if (captured.isEmpty()) { + throw new IllegalArgumentException("Invalid number of manifests"); + } + long totalDeclared = 0; + for (PendingVersion p : captured.values()) { BlobId root = p.root; - if (p.expected < 1 || p.expected > MAX_CHILDREN || root.sizeInBytes() < 1 || root.sizeInBytes() > 50 - || root.getAccountId() != account || root.getContainerId() != container - || root.getBlobDataType() != BlobId.BlobDataType.METADATA) { + if (p.expected < 1 || p.expected > MAX_CHILDREN || !isCompositeRoot(root, account, container)) { throw new SQLDataException("Unsupported named composite capture"); } - counts.put(version, p.expected); totalDeclared += p.expected; } if (totalDeclared > MAX_CHILDREN) { @@ -204,51 +237,27 @@ static PreparedRetirement prepare(short account, short container, String name, M } // Only now, with the whole request's declared size already bounded, consume each iterator and encode its body. - Map rootBytes = new LinkedHashMap<>(); - Map rootIds = new LinkedHashMap<>(); - Map bodies = new LinkedHashMap<>(); - Map rowHashes = new LinkedHashMap<>(); - for (long version : requested) { - PendingVersion p = pending.get(version); - byte[] rb = p.root.toBytes(); - rootBytes.put(version, rb); - String rootId = Base64.getUrlEncoder().withoutPadding().encodeToString(rb); - rootIds.put(version, rootId); - byte[] body = encode(p.descriptors, p.expected, rb); - bodies.put(version, body); - rowHashes.put(version, hash(account, container, name, version, p.expected, rootId, body)); + Map versions = new LinkedHashMap<>(); + for (Map.Entry entry : captured.entrySet()) { + long version = entry.getKey(); + versions.put(version, new PreparedVersion(account, container, name, version, entry.getValue())); } - - return new PreparedRetirement(account, container, name, requested, rootBytes, rootIds, counts, bodies, rowHashes, - intentToken(name, requested, rowHashes)); - } - - /** - * Validate, publish and fence this exact set of named versions in one transaction. A replay that already carries - * this exact content for every requested version returns successfully without resolving the name or locking the - * named range; anything less than all of them matching is rejected rather than partially honored. - */ - static void retire(Connection c, short account, short container, String name, Map pending) - throws SQLException { - retire(c, prepare(account, container, name, pending)); + return new PreparedRetirement(account, container, name, versions); } /** * Publish and fence the given prepared request in one transaction. A pure, non-locking check for an already- - * complete publication runs first and never touches {@code named_blobs_v2} at all, so a legitimate replay is - * never blocked by the named range's own size cap, however many unrelated versions have since replaced it. Only - * when that check is incomplete does this lock the named range -- the same order (named_blobs_v2, then - * named_blob_manifests_v1) an ordinary named PUT's own AFTER INSERT/UPDATE guard uses, so neither ever waits on - * the other in the opposite order. Every requested version is then published by a plain {@code INSERT}, never by - * a locking read against a key that might not exist: only once a duplicate-key signal proves a row already - * exists is a locking read issued against that now-known-existing key. This keeps two unrelated publishers' - * concurrent inserts into the same manifest-table gap from contending on a shared gap lock at all. + * complete publication runs first and never touches {@code named_blobs_v2}, so a replay that sees its existing + * receipt is not blocked by the named range's size cap. If the receipt does not match, lock the named range before + * inserting manifests, in the same order as the named PUT's AFTER INSERT/UPDATE guard. Use a plain {@code INSERT} + * for each manifest and issue a locking read only on a duplicate key. This avoids gap locks from checking for a + * missing manifest and lets unrelated publishers insert into the same manifest-table gap. */ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (c.getAutoCommit() || c.getTransactionIsolation() != Connection.TRANSACTION_REPEATABLE_READ) { throw new IllegalStateException("Publication requires an InnoDB REPEATABLE READ transaction"); } - if (fullyMatches(c, p)) { + if (matchesReceipt(c, p)) { return; } @@ -261,14 +270,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { // the unfenced range -- but never blocks a version that is already published, since that is already-settled // history regardless of what else now sits above it. boolean unrequestedLiveVersion = false; - try (PreparedStatement s = c.prepareStatement("SELECT blob_name,version,blob_id,blob_state," - + "(deleted_ts IS NOT NULL AND deleted_ts<=UTC_TIMESTAMP(6)) FROM named_blobs_v2" - + " FORCE INDEX (named_blob_unfenced_versions) WHERE account_id=? AND container_id=? AND blob_name=?" - + " AND retirement_fenced=FALSE ORDER BY version LIMIT ? FOR UPDATE")) { - s.setInt(1, p.account); - s.setInt(2, p.container); - s.setString(3, p.name); - s.setInt(4, MAX_VERSIONS + 1); + try (PreparedStatement s = c.prepareStatement(SELECT_UNFENCED + " FOR UPDATE")) { + bindUnfenced(s, p.account, p.container, p.name); try (ResultSet r = s.executeQuery()) { int rows = 0; while (r.next()) { @@ -276,7 +279,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { throw new SQLDataException("Unsupported named version range"); } long version = r.getLong(2); - if (!p.counts.containsKey(version)) { + PreparedVersion expected = p.versions.get(version); + if (expected == null) { if (r.getBoolean(5)) { history.add(version); } else { @@ -285,7 +289,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { continue; } boolean eligible = r.getInt(4) == NamedBlobState.READY.ordinal() && !r.getBoolean(5) - && Arrays.equals(r.getBytes(3), p.rootBytes.get(version)); + && Arrays.equals(r.getBytes(3), expected.root); liveMatch.put(version, eligible); } } @@ -297,16 +301,18 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { List freshlyPublished = new ArrayList<>(); try (PreparedStatement insert = c.prepareStatement( "INSERT INTO " + TABLE + " (" + HEADER_COLUMNS + ",payload,payload_hash) VALUES (?,?,?,?,?,?,?,?,?)")) { - for (long version : p.requested) { + for (Map.Entry entry : p.versions.entrySet()) { + long version = entry.getKey(); + PreparedVersion requested = entry.getValue(); insert.setInt(1, p.account); insert.setInt(2, p.container); insert.setString(3, p.name); insert.setLong(4, version); - insert.setBytes(5, p.rootBytes.get(version)); - insert.setInt(6, p.counts.get(version)); + insert.setBytes(5, requested.root); + insert.setInt(6, requested.count); insert.setBytes(7, p.intentToken); - insert.setBytes(8, p.bodies.get(version)); - insert.setBytes(9, p.rowHashes.get(version)); + insert.setBytes(8, requested.body); + insert.setBytes(9, requested.hash); try { if (insert.executeUpdate() != 1) { throw new SQLDataException("Cannot publish sealed manifest"); @@ -321,7 +327,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (duplicate.getErrorCode() != 1062) { throw duplicate; } - confirmExistingMatches(c, p, version); + confirmExistingMatches(c, p, version, requested); } } } @@ -329,7 +335,7 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { if (freshlyPublished.isEmpty()) { return; } - if (freshlyPublished.size() != p.requested.size()) { + if (freshlyPublished.size() != p.versions.size()) { throw new SQLDataException("Partial manifest set"); } try (PreparedStatement retireRow = c.prepareStatement( @@ -360,7 +366,8 @@ static void retire(Connection c, PreparedRetirement p) throws SQLException { * A row proven to already exist by a duplicate-key signal must carry exactly this request's content and this * request's intent, or the request is rejected rather than silently accepted or silently dropped. */ - private static void confirmExistingMatches(Connection c, PreparedRetirement p, long version) throws SQLException { + private static void confirmExistingMatches(Connection c, PreparedRetirement p, long version, + PreparedVersion requested) throws SQLException { try (PreparedStatement s = c.prepareStatement( "SELECT payload_hash,publication_key FROM " + TABLE + " WHERE " + KEY + " FOR UPDATE")) { bindKey(s, p.account, p.container, p.name, version); @@ -368,7 +375,7 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l if (!r.next()) { throw new SQLDataException("Manifest belongs to a different publication"); } - if (!MessageDigest.isEqual(r.getBytes(1), p.rowHashes.get(version))) { + if (!MessageDigest.isEqual(r.getBytes(1), requested.hash)) { throw new SQLDataException("Conflicting manifest for named version"); } if (!MessageDigest.isEqual(r.getBytes(2), p.intentToken)) { @@ -379,22 +386,21 @@ private static void confirmExistingMatches(Connection c, PreparedRetirement p, l } /** - * A pure, non-locking check for an already-complete publication: never touches {@code named_blobs_v2}, so it is - * never blocked by the named range's own size cap. This can under-report on a connection whose REPEATABLE READ - * snapshot predates a just-committed publication, but it can never over-report -- a plain read only ever shows - * what was truly committed -- so a false negative here only costs falling through to the slower, authoritative - * path below, never a wrongful success. + * Match the exact receipt visible to the supplied transaction without locking or reading {@code named_blobs_v2}. + * A transaction can see its own uncommitted writes, and an older snapshot can miss a committed receipt. + * To confirm publication, check in a fresh writer transaction before making any writes. */ - private static boolean fullyMatches(Connection c, PreparedRetirement p) throws SQLException { - String placeholders = String.join(",", Collections.nCopies(p.requested.size(), "?")); + static boolean matchesReceipt(Connection c, PreparedRetirement p) throws SQLException { + String placeholders = String.join(",", Collections.nCopies(p.versions.size(), "?")); String sql = "SELECT blob_name,version,payload_hash,publication_key FROM " + TABLE + " WHERE account_id=? AND container_id=? AND blob_name=? AND version IN (" + placeholders + ")"; try (PreparedStatement s = c.prepareStatement(sql)) { s.setInt(1, p.account); s.setInt(2, p.container); s.setString(3, p.name); - for (int i = 0; i < p.requested.size(); i++) { - s.setLong(i + 4, p.requested.get(i)); + int parameter = 4; + for (long version : p.versions.keySet()) { + s.setLong(parameter++, version); } try (ResultSet r = s.executeQuery()) { int matched = 0; @@ -403,13 +409,13 @@ private static boolean fullyMatches(Connection c, PreparedRetirement p) throws S return false; } long version = r.getLong(2); - if (!MessageDigest.isEqual(r.getBytes(3), p.rowHashes.get(version)) || !MessageDigest.isEqual( + if (!MessageDigest.isEqual(r.getBytes(3), p.versions.get(version).hash) || !MessageDigest.isEqual( r.getBytes(4), p.intentToken)) { return false; } matched++; } - return matched == p.requested.size(); + return matched == p.versions.size(); } } } @@ -444,26 +450,18 @@ private Manifest(ResultSet r) throws SQLException { * grouped into this request, changes the token: two intents cannot impersonate each other merely by sharing a * version set or merely by sharing content. */ - private static byte[] intentToken(String name, List orderedVersions, Map rowHashes) { + private static byte[] intentToken(String name, Map versions) { MessageDigest d = sha256(); byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8); d.update(ByteBuffer.allocate(Integer.BYTES).putInt(nameBytes.length).array()); d.update(nameBytes); - for (long version : orderedVersions) { - d.update(ByteBuffer.allocate(Long.BYTES).putLong(version).array()); - d.update(rowHashes.get(version)); + for (Map.Entry entry : versions.entrySet()) { + d.update(ByteBuffer.allocate(Long.BYTES).putLong(entry.getKey()).array()); + d.update(entry.getValue().hash); } return d.digest(); } - /** Resolve a lost commit reply from an exact, content-bound intent, without reading the name. */ - boolean isPublished(PreparedRetirement p) throws SQLException { - try (Connection c = db.getConnection()) { - requireCommittedReads(c); - return fullyMatches(c, p); - } - } - /** * Recover a known publication by its exact tuple, without resolving the name or reading the original root. Every * row in this table is published by construction, so existence alone is sufficient. diff --git a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java index debd4ee353..97c40ff30a 100644 --- a/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java +++ b/ambry-named-mysql/src/test/java/com/github/ambry/named/NamedBlobManifestStoreTest.java @@ -6,12 +6,12 @@ import java.sql.Connection; import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Arrays; import java.util.Collections; -import java.util.List; +import java.util.LinkedHashMap; +import java.util.Map; import javax.sql.DataSource; import org.junit.Test; +import com.github.ambry.commons.BlobId; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -38,30 +38,30 @@ public void testReaderRejectsDirtyReadsWithoutChangingPoolIsolation() throws SQL } @Test - public void testPublicationUsesADistinctOrderIndependentSet() { - assertEquals(Arrays.asList(1L, 2L), NamedBlobManifestStore.canonicalVersions(Arrays.asList(2L, 1L))); - for (List invalid : Arrays.asList(Arrays.asList(1L, 1L), Collections.singletonList(null), - Collections.emptyList())) { - try { - NamedBlobManifestStore.canonicalVersions(invalid); - fail("Invalid publication set accepted: " + invalid); - } catch (IllegalArgumentException expected) { - // Reject before acquiring database locks. - } + public void testPublicationRejectsNullVersion() throws SQLException { + try { + NamedBlobManifestStore.prepare((short) 17, (short) 4, "name", + Collections.singletonMap(null, new NamedBlobManifestStore.PendingVersion(mock(BlobId.class), 1, + Collections.emptyList().iterator()))); + fail("Accepted a null version"); + } catch (IllegalArgumentException expected) { + assertEquals("Invalid pending manifest versions", expected.getMessage()); } } @Test - public void testPublicationRejectsMoreThanTheDeclaredVersionCap() { - List tooMany = new ArrayList<>(); + public void testPublicationRejectsMoreThanTheDeclaredVersionCap() throws SQLException { + Map tooMany = new LinkedHashMap<>(); + BlobId root = mock(BlobId.class); for (long version = 1; version <= 33; version++) { - tooMany.add(version); + tooMany.put(version, new NamedBlobManifestStore.PendingVersion(root, 1, Collections.emptyList().iterator())); } try { - NamedBlobManifestStore.checkManifestCount(tooMany); + NamedBlobManifestStore.prepare((short) 17, (short) 4, "name", tooMany); fail("More than the declared cap of distinct named versions was accepted in one publication"); } catch (IllegalArgumentException expected) { assertEquals("Invalid number of manifests", expected.getMessage()); } + verifyNoInteractions(root); } } diff --git a/ambry-rest/src/main/java/com/github/ambry/rest/NettyResponseChannel.java b/ambry-rest/src/main/java/com/github/ambry/rest/NettyResponseChannel.java index f2f375def2..0d68049099 100644 --- a/ambry-rest/src/main/java/com/github/ambry/rest/NettyResponseChannel.java +++ b/ambry-rest/src/main/java/com/github/ambry/rest/NettyResponseChannel.java @@ -59,6 +59,8 @@ import java.util.List; import java.util.Map; import java.util.Queue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -107,6 +109,7 @@ class NettyResponseChannel implements RestResponseChannel { private final AtomicLong chunksToWriteCount = new AtomicLong(0); private NettyRequest request = null; + private volatile CompletableFuture deleteWriteCompletion; private ChunkDispenser chunkDispenser; // marked as true if force close is required because close() was called. private volatile boolean forceClose = false; @@ -349,6 +352,38 @@ public void onResponseComplete(Exception exception) { } } + @Override + public synchronized CompletionStage trackResponseWriteCompletion() { + if (request == null || request.getRestMethod() != RestMethod.DELETE) { + return null; + } + if (deleteWriteCompletion != null) { + return deleteWriteCompletion; + } + CompletableFuture completion = new CompletableFuture<>(); + deleteWriteCompletion = completion; + ChannelFuture closeFuture = ctx.channel().closeFuture(); + ChannelFutureListener onClose = ignored -> completion.completeExceptionally(new ClosedChannelException()); + if (closeFuture.isDone()) { + completion.completeExceptionally(new ClosedChannelException()); + } else { + closeFuture.addListener(onClose); + completion.whenComplete((ignored, failure) -> closeFuture.removeListener(onClose)); + } + return completion; + } + + private void completeDeleteWrite(Throwable failure) { + CompletableFuture completion = deleteWriteCompletion; + if (completion != null) { + if (failure == null) { + completion.complete(null); + } else { + completion.completeExceptionally(failure); + } + } + } + @Override public void setStatus(ResponseStatus status) throws RestServiceException { responseMetadata.setStatus(getHttpResponseStatus(status)); @@ -928,6 +963,7 @@ private void handleChannelWriteFailure(Throwable cause, boolean propagateErrorIf try { nettyMetrics.channelWriteError.inc(); if (networkWriteFailed) { + completeDeleteWrite(cause); recordClientTerminationOnWriteFailure(cause, false); } Exception exception; @@ -1258,6 +1294,7 @@ public void operationProgressed(ChannelProgressiveFuture future, long progress, public void operationComplete(ChannelProgressiveFuture future) { if (future.isSuccess()) { logger.trace("Response sending complete on channel {}", ctx.channel()); + completeDeleteWrite(null); completeRequest(request == null || !request.isKeepAlive(), false, true); } else { handleChannelWriteFailure(future.cause(), true, true); @@ -1289,6 +1326,7 @@ public void operationComplete(ChannelFuture future) { if (finalResponseMetadata instanceof LastHttpContent) { // this is the case if finalResponseMetadata is a FullHttpResponse. // in this case there is nothing more to write. + completeDeleteWrite(null); if (!writeFuture.isDone()) { writeFuture.setSuccess(); //Don't close the request when we see 100-continue in EXPECT header. @@ -1326,6 +1364,7 @@ public void operationComplete(ChannelFuture future) throws Exception { long writeFinishTime = System.currentTimeMillis(); long channelWriteTime = writeFinishTime - responseWriteStartTime; if (future.isSuccess()) { + completeDeleteWrite(null); completeRequest(!HttpUtil.isKeepAlive(finalResponseMetadata), true, true); } else { handleChannelWriteFailure(future.cause(), true, true); diff --git a/ambry-rest/src/main/java/com/github/ambry/rest/RestServer.java b/ambry-rest/src/main/java/com/github/ambry/rest/RestServer.java index 00b4b74368..63795a1297 100644 --- a/ambry-rest/src/main/java/com/github/ambry/rest/RestServer.java +++ b/ambry-rest/src/main/java/com/github/ambry/rest/RestServer.java @@ -38,6 +38,7 @@ import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -293,6 +294,16 @@ public void start() throws InstantiationException { } } + /** + * Gate a planned stop while the server is still running. Call from a deployment control thread, not a Netty event + * loop or a worker needed to complete admitted requests. Wait for success before starting {@link #shutdown()}; + * do not stop on timeout or interruption. + * @see RestRequestService#drainNamedBlobRetirement(long, TimeUnit) + */ + public boolean drainNamedBlobRetirement(long timeout, TimeUnit unit) throws InterruptedException { + return restRequestService.drainNamedBlobRetirement(timeout, unit); + } + /** * Shuts down all the components. Returns when shutdown is FULLY complete. * This method is expected to be called in the exit path as long as the RestServer instance construction was diff --git a/ambry-rest/src/test/java/com/github/ambry/rest/NettyResponseChannelTest.java b/ambry-rest/src/test/java/com/github/ambry/rest/NettyResponseChannelTest.java index 1a449d6d3d..84c5d37286 100644 --- a/ambry-rest/src/test/java/com/github/ambry/rest/NettyResponseChannelTest.java +++ b/ambry-rest/src/test/java/com/github/ambry/rest/NettyResponseChannelTest.java @@ -1916,6 +1916,35 @@ public void channelInactiveTest() { } } + /** + * A retirement that registers on an already closed channel must not wait for a response write. + */ + @Test + public void testTrackDeleteResponseWriteOnClosedChannel() throws Exception { + EmbeddedChannel channel = new EmbeddedChannel(new ChunkedWriteHandler()); + VerifiableProperties properties = new VerifiableProperties(new Properties()); + NettyMetrics metrics = new NettyMetrics(new MetricRegistry()); + NettyResponseChannel response = + new NettyResponseChannel(new MockChannelHandlerContext(channel), metrics, new PerformanceConfig(properties), + new NettyConfig(properties)); + try { + HttpRequest request = createRequestWithHeaders(HttpMethod.DELETE, TestingUri.Close.toString()); + response.setRequest(new NettyRequest(request, channel, metrics, Collections.emptySet())); + channel.close().sync(); + Future completion = response.trackResponseWriteCompletion().toCompletableFuture(); + assertTrue("Tracking must observe a completed close immediately", completion.isDone()); + assertSame(completion, response.trackResponseWriteCompletion().toCompletableFuture()); + try { + completion.get(5, TimeUnit.SECONDS); + fail("A closed transport must complete exceptionally"); + } catch (ExecutionException e) { + assertTrue(e.getCause() instanceof ClosedChannelException); + } + } finally { + channel.finishAndReleaseAll(); + } + } + /** * Tests that writing to an inactive channel for a GET request tags the exception as a client termination, * while writing for a POST request keeps a bare {@link ClosedChannelException}. diff --git a/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java b/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java index 685428634f..a1d845d9fb 100644 --- a/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java +++ b/ambry-router/src/main/java/com/github/ambry/router/GetBlobOperation.java @@ -32,6 +32,7 @@ import com.github.ambry.messageformat.MessageFormatRecord; import com.github.ambry.messageformat.MessageMetadata; import com.github.ambry.messageformat.MetadataContentSerDe; +import com.github.ambry.messageformat.MetadataContentSerDe.ChunkCountLimitExceededException; import com.github.ambry.network.Port; import com.github.ambry.network.RequestInfo; import com.github.ambry.network.ResponseInfo; @@ -47,6 +48,7 @@ import com.github.ambry.server.ServerErrorCode; import com.github.ambry.store.MessageInfo; import com.github.ambry.store.StoreKey; +import com.github.ambry.utils.NettyByteBufDataInputStream; import com.github.ambry.utils.SystemTime; import com.github.ambry.utils.Time; import io.netty.buffer.ByteBuf; @@ -62,7 +64,6 @@ import java.util.List; import java.util.ListIterator; import java.util.Map; -import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; @@ -321,7 +322,12 @@ private void onChunkOperationComplete(GetChunk chunk) { // GetManager remove this operation. setOperationCompleted(); List chunkIds = e == null && compositeBlobInfo != null ? compositeBlobInfo.getKeys() : null; - operationResult = new GetBlobResult(blobInfo, null, chunkIds); + if (e != null && options.getBlobOptions.hasMaxChunkIds()) { + operationResult = null; + routerMetrics.onGetBlobError(e, options, isEncrypted); + } else { + operationResult = new GetBlobResult(blobInfo, null, chunkIds); + } } else { // Complete the operation from the caller's perspective, so that the caller can start reading from the // channel if there is no exception. The operation will not be marked as complete internally as subsequent @@ -1200,6 +1206,11 @@ void handleResponse(ResponseInfo responseInfo, GetResponse getResponse) { } else { try { processGetBlobResponse(getRequestInfo, getResponse); + } catch (ChunkCountLimitExceededException e) { + // This is a request limit, not a bad replica response. Do not retry. + chunkException = buildChunkException("Metadata exceeds the requested chunk ID limit", e, + RouterErrorCode.BlobTooLarge); + chunkCompleted = true; } catch (IOException | MessageFormatException e) { // This should really not happen. Again, we do not notify the ResponseHandler responsible for failure // detection. @@ -1637,26 +1648,39 @@ void handleBody(InputStream payload, MessageMetadata messageMetadata, MessageInf encryptionKey = messageMetadata == null ? null : messageMetadata.getEncryptionKey(); } else { BlobAll blobAll = MessageFormatRecord.deserializeBlobAll(payload, blobIdFactory); - BlobInfo serverBlobInfo = blobAll.getBlobInfo(); - updateTtlIfRequired(serverBlobInfo.getBlobProperties(), messageInfo); - getOptions().ageAtAccessTracker.trackAgeAtAccess(serverBlobInfo.getBlobProperties().getCreationTimeInMs()); blobData = blobAll.getBlobData(); encryptionKey = blobAll.getBlobEncryptionKey(); - if (Objects.isNull(encryptionKey) || options.getChunkIdsOnly) { - // set blobInfo iff: - // 1. blob is not encrypted OR, - // 2. getChunkIdsOnly is set. - // If the blob is encrypted, then the user metadata is encrypted too. So in that case, - // maybeProcessCallbackAndComplete() will set the appropriate value for blobInfo after decryption. - // In the case of getChunkIdsOnly call, we don't need the user metadata but still need blob - // properties to evaluate if the metadata chunk is already updated for update requests. So we allow blobInfo - // to be set here. - blobInfo = serverBlobInfo; - blobInfo.setLifeVersion(messageInfo.getLifeVersion()); - } else { - serverBlobProperties = serverBlobInfo.getBlobProperties(); - lifeVersion = messageInfo.getLifeVersion(); - userMetadata = serverBlobInfo.getUserMetadata(); + boolean bounded = options.getBlobOptions.hasMaxChunkIds(); + try { + BlobInfo serverBlobInfo = blobAll.getBlobInfo(); + BlobProperties properties = serverBlobInfo.getBlobProperties(); + updateTtlIfRequired(properties, messageInfo); + getOptions().ageAtAccessTracker.trackAgeAtAccess(properties.getCreationTimeInMs()); + if (encryptionKey == null || options.getChunkIdsOnly) { + // Chunk-ID callers need properties, not decrypted user metadata. + blobInfo = serverBlobInfo; + blobInfo.setLifeVersion(messageInfo.getLifeVersion()); + } else { + serverBlobProperties = properties; + lifeVersion = messageInfo.getLifeVersion(); + userMetadata = serverBlobInfo.getUserMetadata(); + } + if (bounded) { + blobType = blobData.getBlobType(); + if (blobType == BlobType.MetadataBlob) { + compositeBlobInfo = MetadataContentSerDe.deserializeMetadataContentRecord(blobData.content().nioBuffer(), + blobIdFactory, options.getBlobOptions.getMaxChunkIds()); + } else { + totalSize = blobData.getSize(); + } + successfullyDeserialized = true; + return; + } + } finally { + // The metadata-only path keeps no response data. Release only copies, not borrowed Netty slices. + if (bounded && !(payload instanceof NettyByteBufDataInputStream)) { + blobData.release(); + } } } blobType = blobData.getBlobType(); diff --git a/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java b/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java index b3ae7ac395..1b2f91cc78 100644 --- a/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java +++ b/ambry-router/src/main/java/com/github/ambry/router/NonBlockingRouter.java @@ -376,7 +376,7 @@ private void getBlobHelper(String blobIdStr, GetBlobOptions options, Callback chunkIds = getChunkResult.getBlobChunkIds(); + router.getNotFoundCache().put(blobID, Boolean.TRUE); + GetBlobOptionsBuilder bounded = + new GetBlobOptionsBuilder().operationType(GetBlobOptions.OperationType.BlobChunkIds); + assertException(ExecutionException.class, + () -> router.getBlob(blobID, bounded.maxChunkIds(chunkIds.size()).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS), + e -> Assert.assertEquals(RouterErrorCode.BlobDoesNotExist, ((RouterException) e.getCause()).getErrorCode())); + GetBlobResult fresh = router.getBlob(blobID, new GetBlobOptionsBuilder() + .operationType(GetBlobOptions.OperationType.BlobChunkIds).bypassNotFoundCache(true).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS); + Assert.assertEquals(chunkIds, fresh.getBlobChunkIds()); + bounded.bypassNotFoundCache(true); + assertException(ExecutionException.class, + () -> router.getBlob(blobID, bounded.maxChunkIds(chunkIds.size() - 1).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS), + e -> Assert.assertEquals(RouterErrorCode.BlobTooLarge, ((RouterException) e.getCause()).getErrorCode())); + GetBlobResult exact = router.getBlob(blobID, bounded.maxChunkIds(chunkIds.size()).build()) + .get(AWAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS); + Assert.assertEquals(chunkIds, exact.getBlobChunkIds()); + Assert.assertNull(exact.getBlobDataChannel()); + router.getNotFoundCache().invalidate(blobID); + // verify the content, one data chunk after another int chunkSize = maxPutChunkSize; for (int i = 0; i < chunkIds.size(); i++) {