fix(redshift): reclaim anonymous container volumes (#6382)

Reclaim disposable anonymous volumes while preserving adopted containers during failed recovery. Retain pre-reboot dumps and failed cleanup ownership across partial teardown. Preserve the original database when only proxy shutdown fails. Share startup orchestration while retaining the opt-in cleanup policy.

Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
Andre Kurait authored and GitHub committed 2026-10-23 20:46:24 -04:00
1 parent 5b24703815
commit a96921afad
13 files changed
+500 -87

No files matched your search

@@ -43,9 +43,11 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -226,8 +228,9 @@ class ContainerLifecycleManagerCaBundleTest {
verify(dockerClient, never()).copyArchiveToContainerCmd(anyString());
}
@Test
void aFailedCopyRecreatesTheContainerWithoutTheTrustVariables() throws Exception {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void aFailedCopyRecreatesTheContainerWithoutTheTrustVariables(boolean ephemeral) throws Exception {
// SSL_CERT_FILE and friends replace the image's trust store, so they must never name a
// file that is not there: an image without /etc keeps its own trust instead.
when(tlsConfig.enabled()).thenReturn(true);
@@ -245,7 +248,17 @@ class ContainerLifecycleManagerCaBundleTest {
RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(dockerClient.removeContainerCmd("container-id")).thenReturn(removeCmd);
assertEquals("container-id-2", manager().create(specWithEnv(List.of("FOO=bar"))));
ContainerSpec spec = specWithEnv(List.of("FOO=bar"));
if (ephemeral) {
ContainerLifecycleManager lifecycle = spy(manager());
ContainerLifecycleManager.ContainerInfo info =
new ContainerLifecycleManager.ContainerInfo("container-id-2", Map.of());
doReturn(info).when(lifecycle).startCreated("container-id-2", spec);
assertEquals(info, lifecycle.createAndStartEphemeral(spec));
} else {
assertEquals("container-id-2", manager().create(spec));
}
verify(removeCmd, ephemeral ? times(1) : never()).withRemoveVolumes(true);
verify(removeCmd).withForce(true);
verify(removeCmd).exec();
@@ -0,0 +1,98 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.exception.NotFoundException;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
class ContainerLifecycleManagerEphemeralTest {
private DockerClient docker;
private ContainerLifecycleManager manager;
private RemoveContainerCmd remove;
private CreateContainerCmd create;
private final ContainerSpec spec = new ContainerSpec("postgres:16-alpine");
@BeforeEach
void setUp() {
docker = mock(DockerClient.class);
ImageCacheService images = mock(ImageCacheService.class);
when(images.ensureImageExists(spec.image())).thenReturn("image-id");
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
manager = spy(new ContainerLifecycleManager(docker, images, mock(ContainerDetector.class), config));
create = mock(CreateContainerCmd.class, RETURNS_SELF);
CreateContainerResponse response = new CreateContainerResponse();
response.setId("owned-id");
when(create.exec()).thenReturn(response);
when(docker.createContainerCmd("image-id")).thenReturn(create);
remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
when(docker.removeContainerCmd(anyString())).thenReturn(remove);
}
@Test
void failedEphemeralStartRemovesAnonymousVolumes() {
IllegalStateException failure = new IllegalStateException("start failed");
doThrow(failure).when(manager).startCreated("owned-id", spec);
assertSame(failure, assertThrows(IllegalStateException.class, () -> manager.createAndStartEphemeral(spec)));
verify(remove).withRemoveVolumes(true);
verify(remove).exec();
}
@Test
void failedRemovalPreservesStartFailureAndSuppressedCleanupCause() {
IllegalStateException failure = new IllegalStateException("start failed");
IllegalStateException cleanup = new IllegalStateException("daemon unavailable");
doThrow(failure).when(manager).startCreated("owned-id", spec);
when(remove.exec()).thenThrow(cleanup);
assertSame(failure, assertThrows(IllegalStateException.class, () -> manager.createAndStartEphemeral(spec)));
assertEquals(1, failure.getSuppressed().length);
assertSame(cleanup, failure.getSuppressed()[0].getCause());
}
@Test
void failedCreateDoesNotRemoveUnownedContainer() {
when(create.exec()).thenThrow(new IllegalStateException("create failed"));
assertThrows(IllegalStateException.class, () -> manager.createAndStartEphemeral(spec));
verify(docker, never()).removeContainerCmd(anyString());
}
@Test
void successfulEphemeralStartKeepsItsVolume() {
ContainerLifecycleManager.ContainerInfo info = new ContainerLifecycleManager.ContainerInfo("owned-id", Map.of());
doReturn(info).when(manager).startCreated("owned-id", spec);
assertSame(info, manager.createAndStartEphemeral(spec));
verify(docker, never()).removeContainerCmd(anyString());
}
@Test
void defaultStrictRemovalDoesNotOptIntoVolumeRemoval() {
manager.removeIfExistsStrict("owned-id");
verify(remove, never()).withRemoveVolumes(true);
verify(remove).exec();
}
@Test
void missingEphemeralContainerIsAlreadyClean() {
when(remove.exec()).thenThrow(new NotFoundException("gone"));
assertDoesNotThrow(() -> manager.removeIfExistsStrict("owned-id", true));
verify(remove).withRemoveVolumes(true);
}
@Test
void strictEphemeralRemovalExposesFailure() {
IllegalStateException failure = new IllegalStateException("daemon unavailable");
when(remove.exec()).thenThrow(failure);
assertSame(failure, assertThrows(IllegalStateException.class,
() -> manager.removeIfExistsStrict("owned-id", true)).getCause());
}
}
@@ -118,14 +118,21 @@ class ContainerLifecycleManagerNetworkTest {
verify(connectCmd).exec();
}
@Test
void createRemovesContainerWhenNetworkAttachFails() {
@ParameterizedTest
@ValueSource(booleans = {false, true})
void createRemovesContainerWhenNetworkAttachFails(boolean ephemeral) {
RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class, RETURNS_SELF);
lenient().when(dockerClient.removeContainerCmd("container-id")).thenReturn(removeCmd);
doThrow(new IllegalStateException("network gone")).when(connectCmd).exec();
assertThrows(IllegalStateException.class, () -> manager().create(specWithLinkLocalIp(Map.of())));
assertThrows(IllegalStateException.class, () -> {
if (ephemeral) {
manager().createAndStartEphemeral(specWithLinkLocalIp(Map.of()));
} else {
manager().create(specWithLinkLocalIp(Map.of()));
}
});
verify(removeCmd, ephemeral ? times(1) : never()).withRemoveVolumes(true);
verify(dockerClient).removeContainerCmd("container-id");
}
@@ -1,6 +1,8 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.CreateContainerCmd;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.exception.DockerException;
@@ -17,7 +19,9 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Answers.RETURNS_DEEP_STUBS;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
@@ -44,7 +48,7 @@ class ContainerLifecycleManagerStartFailureTest {
@Mock
private ContainerDetector containerDetector;
@Mock
@Mock(answer = RETURNS_DEEP_STUBS)
private EmulatorConfig config;
private ContainerLifecycleManager manager;
@@ -60,7 +64,7 @@ class ContainerLifecycleManagerStartFailureTest {
void createAndStartRemovesCreatedContainerWhenStartFails() {
RuntimeException startFailure =
new RuntimeException("Bind for 0.0.0.0:80 failed: port is already allocated");
doReturn("container-id").when(manager).create(spec);
stubCreate();
doThrow(startFailure).when(manager).startCreated("container-id", spec);
RemoveContainerCmd removeCmd = mock(RemoveContainerCmd.class);
@@ -78,7 +82,7 @@ class ContainerLifecycleManagerStartFailureTest {
void createAndStartDoesNotRemoveContainerOnSuccess() {
ContainerLifecycleManager.ContainerInfo info =
new ContainerLifecycleManager.ContainerInfo("container-id", Map.of());
doReturn("container-id").when(manager).create(spec);
stubCreate();
doReturn(info).when(manager).startCreated("container-id", spec);
assertSame(info, manager.createAndStart(spec));
@@ -86,6 +90,15 @@ class ContainerLifecycleManagerStartFailureTest {
verify(dockerClient, never()).removeContainerCmd(any(String.class));
}
private void stubCreate() {
when(imageCacheService.ensureImageExists(spec.image())).thenReturn("image-id");
CreateContainerCmd create = mock(CreateContainerCmd.class, RETURNS_SELF);
CreateContainerResponse response = new CreateContainerResponse();
response.setId("container-id");
when(create.exec()).thenReturn(response);
when(dockerClient.createContainerCmd("image-id")).thenReturn(create);
}
@Test
void startCreatedTranslatesKeyringQuotaError() {
// github.com/floci-io/floci/issues/2243: crun/runc report the kernel session-keyring
@@ -67,6 +67,70 @@ import static org.mockito.Mockito.*;
class RedshiftServiceTest {
@Test
void recoveryProxyFailureDoesNotDestructivelyStopAnAdoptedContainer() {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("survivor");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setClusterStatus("available");
cluster.setProxyPort(7107);
when(clusterBackend.scanAllAccountEntries(any())).thenReturn(List.of(
new AccountAwareStorageBackend.AccountEntry<>("111111111111", "survivor", cluster)));
when(cm.adoptOrStart("111111111111", "survivor", "admin", "Secret123"))
.thenReturn(new RedshiftContainerHandle("surviving-container", "survivor", "localhost", 5432));
doThrow(new IllegalStateException("proxy bind failed")).when(proxyManager).startProxy(
anyString(), anyInt(), anyString(), anyInt(), anyString(), anyString(), anyString(), anyString(),
any(), anyList(), isNull());
service.onStart(null);
assertEquals("unavailable", cluster.getClusterStatus());
verify(cm, never()).stop("111111111111", "survivor");
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void rebootTeardownFailureKeepsDumpAndMarksClusterFailed(boolean proxyFailure) throws Exception {
Cluster cluster = new Cluster();
cluster.setClusterIdentifier("partial-stop");
cluster.setMasterUsername("admin");
cluster.setMasterPassword("Secret123");
cluster.setClusterStatus("available");
cluster.setProxyPort(7107);
when(clusterBackend.get("partial-stop")).thenReturn(Optional.of(cluster));
AtomicReference<Path> dump = new AtomicReference<>();
doAnswer(invocation -> {
Path path = invocation.getArgument(3, Path.class);
Files.writeString(path, "preserved database");
dump.set(path);
return null;
}).when(cm).takeSnapshot(eq("111111111111"), eq("partial-stop"), eq("admin"), any(Path.class));
if (proxyFailure) {
doThrow(new IllegalStateException("proxy stop failed"))
.when(proxyManager).stopProxy("111111111111:partial-stop");
} else {
doThrow(new IllegalStateException("log close failed after container removal"))
.when(cm).stop("111111111111", "partial-stop");
}
try {
assertThrows(AwsException.class, () -> service.rebootCluster("partial-stop"));
assertTrue(Files.exists(dump.get()), "The pre-reboot dump must survive partial teardown");
assertEquals("preserved database", Files.readString(dump.get()));
assertEquals("failed", cluster.getClusterStatus());
if (proxyFailure) {
verify(cm, never()).stop(anyString(), anyString());
} else {
verify(cm, atLeastOnce()).stop("111111111111", "partial-stop");
}
} finally {
if (dump.get() != null) {
Files.deleteIfExists(dump.get());
}
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void slowSnapshotDoesNotBlockOtherClusterMutation(boolean finalSnapshot) throws Exception {
@@ -68,7 +68,7 @@ class RedshiftArchiveRetryTest {
when(builder.newContainer(anyString())).thenReturn(mock(ContainerBuilder.Builder.class, RETURNS_SELF));
ContainerLifecycleManager lifecycle = mock(ContainerLifecycleManager.class);
when(lifecycle.getDockerClient()).thenReturn(docker);
when(lifecycle.createAndStart(any())).thenReturn(
when(lifecycle.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo(CONTAINER, Map.of(5432, new EndpointInfo("localhost", 5432))));
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
when(config.services().redshift().imageVersion()).thenReturn("postgres:16-alpine");
@@ -23,11 +23,14 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.InOrder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -46,6 +49,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.RETURNS_SELF;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
@@ -55,6 +59,50 @@ import static org.mockito.Mockito.when;
class RedshiftContainerManagerTest {
@ParameterizedTest
@ValueSource(strings = {"adopt", "readiness", "proxy"})
void startupRollbackPreservesAdoptedDataAndExplicitStopStillRemovesIt(String failureStage) throws IOException {
String name = "floci-aws-redshift-" + ACCOUNT_ID + "-survivor";
Container existing = mock(Container.class);
when(existing.getId()).thenReturn("cont-survivor");
when(lifecycleManager.findByName(name)).thenReturn(Optional.of(existing));
Closeable stream = mock(Closeable.class);
if ("adopt".equals(failureStage)) {
when(lifecycleManager.adopt(eq("cont-survivor"), any(), any()))
.thenThrow(new IllegalStateException("adoption failed"));
assertThrows(IllegalStateException.class,
() -> manager.adoptOrStart(ACCOUNT_ID, "survivor", "admin", "pass"));
} else {
when(lifecycleManager.adopt(eq("cont-survivor"), any(), any())).thenReturn(
new ContainerInfo("cont-survivor", Map.of(5432, new EndpointInfo("localhost", 5432))));
when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
if ("readiness".equals(failureStage)) {
when(dockerClient.execCreateCmd(anyString())).thenThrow(new IllegalStateException("not ready"));
Thread.currentThread().interrupt();
try {
assertThrows(IllegalStateException.class,
() -> manager.adoptOrStart(ACCOUNT_ID, "survivor", "admin", "pass"));
} finally {
Thread.interrupted();
}
} else {
manager.adoptOrStart(ACCOUNT_ID, "survivor", "admin", "pass");
}
}
manager.rollbackStartup(ACCOUNT_ID, "survivor");
manager.rollbackStartup(ACCOUNT_ID, "survivor");
verify(lifecycleManager, never()).removeIfExistsStrict(anyString(), eq(true));
assertTrue(manager.getContainer(ACCOUNT_ID, "survivor").isEmpty());
if (!"adopt".equals(failureStage)) {
verify(stream).close();
}
manager.stop(ACCOUNT_ID, "survivor");
verify(lifecycleManager).removeIfExistsStrict("cont-survivor", true);
}
private ContainerBuilder containerBuilder;
private ContainerLifecycleManager lifecycleManager;
private ContainerLogStreamer logStreamer;
@@ -152,7 +200,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertNotNull(handle);
@@ -211,7 +259,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
@@ -249,7 +297,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
@@ -263,7 +311,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
@@ -308,7 +356,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
@@ -316,7 +364,7 @@ class RedshiftContainerManagerTest {
clearInvocations(lifecycleManager);
manager.stop(ACCOUNT_ID, "test-cluster");
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isEmpty());
verify(lifecycleManager).removeIfExists("floci-aws-redshift-" + ACCOUNT_ID + "-test-cluster");
verify(lifecycleManager).removeIfExistsStrict("cont-123", true);
}
@Test
@@ -324,16 +372,16 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// A container left under the fixed name by an earlier run would make createAndStart fail with a name conflict
InOrder order = inOrder(lifecycleManager);
order.verify(lifecycleManager).removeIfExists("floci-aws-redshift-" + ACCOUNT_ID + "-test-cluster");
order.verify(lifecycleManager).createAndStart(any());
// A legacy-named container may still hold a cluster's data, and no volume backs it
verify(lifecycleManager, never()).removeIfExists("floci-redshift-" + ACCOUNT_ID + "-test-cluster");
order.verify(lifecycleManager).removeIfExistsStrict("floci-aws-redshift-" + ACCOUNT_ID + "-test-cluster", true);
order.verify(lifecycleManager).createAndStartEphemeral(any());
// A legacy-named container may still hold a cluster's data.
verify(lifecycleManager, never()).removeIfExistsStrict("floci-redshift-" + ACCOUNT_ID + "-test-cluster", true);
}
@Test
@@ -342,7 +390,7 @@ class RedshiftContainerManagerTest {
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo infoA = new ContainerInfo("cont-account-a", Map.of(5432, new EndpointInfo("localhost", 5432)));
ContainerInfo infoB = new ContainerInfo("cont-account-b", Map.of(5432, new EndpointInfo("localhost", 5433)));
when(lifecycleManager.createAndStart(any())).thenReturn(infoA, infoB);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(infoA, infoB);
String otherAccountId = "222222222222";
manager.start(ACCOUNT_ID, "shared-id", "admin", "pass");
@@ -370,10 +418,10 @@ class RedshiftContainerManagerTest {
assertEquals("cont-existing", handle.getContainerId());
assertEquals(6000, handle.getPort());
assertTrue(manager.getContainer(ACCOUNT_ID, "test-cluster").isPresent());
// Data lives only in the container's writable layer (no volume): recreating it
// would silently discard it, so a container found by name must never be recreated.
verify(lifecycleManager, never()).createAndStart(any());
verify(lifecycleManager, never()).removeIfExists(anyString());
// The surviving container retains its anonymous PostgreSQL volume. A replacement
// would start with an empty volume, so adoption must preserve the container.
verify(lifecycleManager, never()).createAndStartEphemeral(any());
verify(lifecycleManager, never()).removeIfExistsStrict(anyString(), eq(true));
}
@Test
@@ -383,7 +431,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-fresh", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
RedshiftContainerHandle handle = manager.adoptOrStart(ACCOUNT_ID, "test-cluster", "admin", "pass");
@@ -396,7 +444,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
@@ -438,7 +486,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// Test SQL injection attempt with semicolon
@@ -459,7 +507,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
// Forbidden characters: ', ", \, / and @ (AWS ModifyCluster rejects the same set)
@@ -492,7 +540,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, org.mockito.Mockito.RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-123", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
manager.start(ACCOUNT_ID, "test-cluster", "admin", "pass");
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, org.mockito.Mockito.RETURNS_SELF);
@@ -529,7 +577,7 @@ class RedshiftContainerManagerTest {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
ContainerInfo info = new ContainerInfo("cont-stream", Map.of(5432, new EndpointInfo("localhost", 5432)));
when(lifecycleManager.createAndStart(any())).thenReturn(info);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(info);
Closeable stream = mock(Closeable.class);
when(logStreamer.attach("cont-stream", "/floci/redshift", "test-cluster", "us-east-1", "redshift:test-cluster"))
.thenReturn(stream);
@@ -605,4 +653,79 @@ class RedshiftContainerManagerTest {
org.junit.jupiter.api.Assertions.assertDoesNotThrow(() ->
manager.bootstrapCatalog("cont-bootstrap-fail", "admin", "dev"));
}
@Test
void stopFailureRetainsHandleForRetry() {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-owned", Map.of(5432, new EndpointInfo("localhost", 5432))));
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "owned", "admin", "pass");
doThrow(new IllegalStateException("Docker removal failed"))
.when(lifecycleManager).removeIfExistsStrict("cont-owned", true);
assertThrows(IllegalStateException.class, () -> manager.stop(ACCOUNT_ID, "owned"));
assertEquals(Optional.of(handle), manager.getContainer(ACCOUNT_ID, "owned"));
doNothing().when(lifecycleManager).removeIfExistsStrict("cont-owned", true);
manager.stop(ACCOUNT_ID, "owned");
assertTrue(manager.getContainer(ACCOUNT_ID, "owned").isEmpty());
}
@Test
void successfulStopClosesOwnedLogStream() throws IOException {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-owned", Map.of(5432, new EndpointInfo("localhost", 5432))));
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "owned", "admin", "pass");
Closeable stream = mock(Closeable.class);
handle.setLogStream(stream);
manager.stop(ACCOUNT_ID, "owned");
verify(stream).close();
}
@Test
void staleRemovalFailurePreventsReplacementCreation() {
doThrow(new IllegalStateException("Docker unavailable")).when(lifecycleManager)
.removeIfExistsStrict("floci-aws-redshift-" + ACCOUNT_ID + "-owned", true);
assertThrows(IllegalStateException.class, () -> manager.start(ACCOUNT_ID, "owned", "admin", "pass"));
verify(lifecycleManager, never()).createAndStartEphemeral(any());
}
@Test
void readinessFailureKeepsLogAndContainerOwnershipUntilRollback() throws IOException {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-unready", Map.of(5432, new EndpointInfo("localhost", 5432))));
Closeable stream = mock(Closeable.class);
when(logStreamer.attach(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(stream);
when(dockerClient.execCreateCmd(anyString())).thenThrow(new IllegalStateException("not ready"));
Thread.currentThread().interrupt();
try {
assertThrows(IllegalStateException.class, () -> manager.start(ACCOUNT_ID, "unready", "admin", "pass"));
} finally {
Thread.interrupted();
}
assertTrue(manager.getContainer(ACCOUNT_ID, "unready").isPresent());
verify(stream, never()).close();
manager.rollbackStartup(ACCOUNT_ID, "unready");
verify(lifecycleManager).removeIfExistsStrict("cont-unready", true);
verify(stream).close();
}
@Test
void logCloseFailureRetainsHandleForRetryAfterContainerRemoval() throws IOException {
ContainerBuilder.Builder specBuilder = mock(ContainerBuilder.Builder.class, RETURNS_SELF);
when(containerBuilder.newContainer(anyString())).thenReturn(specBuilder);
when(lifecycleManager.createAndStartEphemeral(any())).thenReturn(
new ContainerInfo("cont-owned", Map.of(5432, new EndpointInfo("localhost", 5432))));
RedshiftContainerHandle handle = manager.start(ACCOUNT_ID, "owned", "admin", "pass");
Closeable stream = mock(Closeable.class);
handle.setLogStream(stream);
doThrow(new IllegalStateException("close failed")).doNothing().when(stream).close();
assertThrows(IllegalStateException.class, () -> manager.stop(ACCOUNT_ID, "owned"));
assertEquals(Optional.of(handle), manager.getContainer(ACCOUNT_ID, "owned"));
manager.stop(ACCOUNT_ID, "owned");
assertTrue(manager.getContainer(ACCOUNT_ID, "owned").isEmpty());
}
}
@@ -108,6 +108,20 @@ class RedshiftServerlessRuntimeTest {
any(Path.class), eq(true));
}
@Test
void failedAdoptedProxyUsesRecoveryRollback() {
when(containers.adoptOrStart(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics")).thenReturn(handle());
doThrow(new RuntimeException("port in use")).when(proxies).startProxy(any(), anyInt(), any(), anyInt(),
any(), any(), any(), any(), any(PasswordValidator.class), any());
assertThrows(RuntimeException.class, () -> runtime.start(ACCOUNT, REGION, "my-wg", "root", "Secret123",
"analytics", ENDPOINT, true, Optional::empty));
verify(proxies).stopProxy(RELAY_KEY);
verify(containers).rollbackStartup(ACCOUNT, BACKEND_ID);
verify(containers, never()).stop(ACCOUNT, BACKEND_ID);
}
@Test
void adoptReattachesToASurvivingContainer() {
when(containers.adoptOrStart(ACCOUNT, BACKEND_ID, "root", "Secret123", "analytics")).thenReturn(handle());
@@ -130,7 +144,7 @@ class RedshiftServerlessRuntimeTest {
"analytics", ENDPOINT, false, Optional::empty));
verify(proxies).stopProxy(RELAY_KEY);
verify(containers).stop(ACCOUNT, BACKEND_ID);
verify(containers).rollbackStartup(ACCOUNT, BACKEND_ID);
assertTrue(broker.resolve(ACCOUNT, BACKEND_ID, "IAM:alice").isEmpty());
}