mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(rds): retain incomplete cleanup for retry (#7339)
* fix(rds): retain incomplete cleanup for retry * fix(rds): reuse retained backup dump on delete retry * refactor(rds): simplify retry ownership and test isolation
This commit is contained in:
1 parent
cffad85ac1
commit
1b4f99cb8a
8 files changed
+732
-56
No files matched your search
@@ -1,5 +1,6 @@
|
||||
package io.github.hectorvent.floci.services.rds;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
@@ -9,6 +10,7 @@ import io.github.hectorvent.floci.core.common.docker.CurrentContainerNetworkReso
|
||||
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
|
||||
import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.core.storage.PersistentStorage;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
@@ -59,6 +61,7 @@ import io.github.hectorvent.floci.testutil.LogCapture;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.function.Executable;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
@@ -68,6 +71,8 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.net.ServerSocket;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
@@ -1218,6 +1223,283 @@ class RdsServiceTest {
|
||||
assertThrows(AwsException.class, () -> rdsService.getDbInstance("protected-db"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceStorageDeleteRetainsRecordAndPortForRetry() {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
InMemoryStorage<String, DbInstance> instances = spy(new InMemoryStorage<>());
|
||||
RdsService service = newService(containerManager, proxyManager, instances,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
service.createDbInstance("old-instance", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false);
|
||||
IllegalStateException failure = new IllegalStateException("delete wrote then failed");
|
||||
doAnswer(invocation -> {
|
||||
invocation.callRealMethod();
|
||||
throw failure;
|
||||
}).doCallRealMethod().when(instances).delete("us-east-1::old-instance");
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbInstance("old-instance")));
|
||||
assertEquals(DbInstanceStatus.DELETING, service.getDbInstance("old-instance").getStatus());
|
||||
assertEquals("InsufficientDBInstanceCapacity", assertThrows(AwsException.class,
|
||||
() -> service.createDbInstance("new-instance", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false)).getErrorCode());
|
||||
|
||||
RdsService restarted = newService(containerManager, proxyManager, instances,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
restarted.restorePersistedRuntime();
|
||||
assertEquals("InsufficientDBInstanceCapacity", assertThrows(AwsException.class,
|
||||
() -> restarted.createDbInstance("new-instance", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false)).getErrorCode());
|
||||
|
||||
restarted.deleteDbInstance("old-instance");
|
||||
assertEquals(7000, restarted.createDbInstance("new-instance", "postgres", "13", "admin",
|
||||
"password", "dbname", "db.t3.micro", 20, false, null, null, null, null, false)
|
||||
.getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainedInstanceBackupDeleteRetryReusesSavedDump() {
|
||||
InMemoryStorage<String, DbInstance> instances = spy(new InMemoryStorage<>());
|
||||
RdsService service = newService(containerManager, proxyManager, instances,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
service.createDbInstance("retry-backup", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false);
|
||||
when(containerManager.createPostgresSnapshot("cont-id", "admin"))
|
||||
.thenReturn("saved-dump").thenThrow(new IllegalStateException("container is gone"));
|
||||
IllegalStateException failure = new IllegalStateException("delete wrote then failed");
|
||||
doAnswer(invocation -> {
|
||||
invocation.callRealMethod();
|
||||
throw failure;
|
||||
}).doCallRealMethod().when(instances).delete("us-east-1::retry-backup");
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbInstance("retry-backup", "us-east-1", false)));
|
||||
assertEquals(DbInstanceStatus.DELETING, service.getDbInstance("retry-backup").getStatus());
|
||||
assertDoesNotThrow(() -> service.deleteDbInstance("retry-backup", "us-east-1", false));
|
||||
verify(containerManager).createPostgresSnapshot("cont-id", "admin");
|
||||
assertTrue(service.describeDbInstanceAutomatedBackups("us-east-1", null, "retry-backup", null,
|
||||
List.of(), List.of(), List.of(), null, null).backups().getFirst().isDataSaved());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedClusterStorageDeleteRetainsRecordAndPortForRetry() {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
InMemoryStorage<String, DbCluster> clusters = spy(new InMemoryStorage<>());
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), clusters, new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
service.createDbCluster("old-cluster", "postgres", "17.5", "admin", "password",
|
||||
"dbname", false, null, null, null, false);
|
||||
IllegalStateException failure = new IllegalStateException("delete wrote then failed");
|
||||
doAnswer(invocation -> {
|
||||
invocation.callRealMethod();
|
||||
throw failure;
|
||||
}).doCallRealMethod().when(clusters).delete("us-east-1::old-cluster");
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbCluster("old-cluster")));
|
||||
assertEquals(DbInstanceStatus.DELETING, service.getDbCluster("old-cluster").getStatus());
|
||||
assertEquals("InsufficientDBInstanceCapacity", assertThrows(AwsException.class,
|
||||
() -> service.createDbCluster("new-cluster", "postgres", "17.5", "admin", "password",
|
||||
"dbname", false, null, null, null, false)).getErrorCode());
|
||||
|
||||
RdsService restarted = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), clusters, new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
restarted.restorePersistedRuntime();
|
||||
assertEquals("InsufficientDBInstanceCapacity", assertThrows(AwsException.class,
|
||||
() -> restarted.createDbCluster("new-cluster", "postgres", "17.5", "admin", "password",
|
||||
"dbname", false, null, null, null, false)).getErrorCode());
|
||||
|
||||
restarted.deleteDbCluster("old-cluster");
|
||||
assertEquals(7000, restarted.createDbCluster("new-cluster", "postgres", "17.5", "admin",
|
||||
"password", "dbname", false, null, null, null, false).getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void retainedClusterBackupDeleteRetryReusesSavedDump() {
|
||||
InMemoryStorage<String, DbCluster> clusters = spy(new InMemoryStorage<>());
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), clusters, new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
service.createDbCluster("retry-backup", "postgres", "17.5", "admin", "password",
|
||||
"dbname", false, null, null, null, false);
|
||||
when(containerManager.createPostgresSnapshot("cont-id", "admin"))
|
||||
.thenReturn("saved-dump").thenThrow(new IllegalStateException("container is gone"));
|
||||
IllegalStateException failure = new IllegalStateException("delete wrote then failed");
|
||||
doAnswer(invocation -> {
|
||||
invocation.callRealMethod();
|
||||
throw failure;
|
||||
}).doCallRealMethod().when(clusters).delete("us-east-1::retry-backup");
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbCluster("retry-backup", "us-east-1", false)));
|
||||
assertEquals(DbInstanceStatus.DELETING, service.getDbCluster("retry-backup").getStatus());
|
||||
assertDoesNotThrow(() -> service.deleteDbCluster("retry-backup", "us-east-1", false));
|
||||
verify(containerManager).createPostgresSnapshot("cont-id", "admin");
|
||||
assertTrue(service.describeDbClusterAutomatedBackups("us-east-1", null, "retry-backup",
|
||||
List.of(), List.of(), List.of(), null, null).backups().getFirst().isDataSaved());
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void persistedInstanceTombstoneRetriesNamedBackendCleanup(boolean mockOnRestart, @TempDir Path tempDir)
|
||||
throws Exception {
|
||||
Path file = tempDir.resolve("rds-instance-retry.json");
|
||||
TypeReference<Map<String, DbInstance>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, DbInstance> storage = new PersistentStorage<>(file, type);
|
||||
RdsService service = newService(containerManager, proxyManager, storage,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
DbInstance instance = service.createDbInstance("retry-instance", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false);
|
||||
instance.setStatus(DbInstanceStatus.DELETING);
|
||||
instance.setBackendCleanupRequired(true);
|
||||
storage.put("us-east-1::retry-instance", instance);
|
||||
|
||||
PersistentStorage<String, DbInstance> reloaded = new PersistentStorage<>(file, type);
|
||||
reloaded.load();
|
||||
DbInstance retained = reloaded.get("us-east-1::retry-instance").orElseThrow();
|
||||
assertTrue(retained.isBackendCleanupRequired());
|
||||
assertNotNull(retained.getDockerVolumeName());
|
||||
when(rdsConfig.mock()).thenReturn(mockOnRestart);
|
||||
RdsContainerManager restartedManager = mock(RdsContainerManager.class);
|
||||
RdsService restarted = newService(restartedManager, mock(RdsProxyManager.class), reloaded,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
restarted.restorePersistedRuntime();
|
||||
restarted.deleteDbInstance("retry-instance");
|
||||
verify(restartedManager).stopForDelete(retained.getDbInstanceArn(), retained.getDockerVolumeName());
|
||||
verify(restartedManager).removeVolume(retained.getDbInstanceArn(),
|
||||
retained.getContainerStorageResourceId(), retained.getDockerVolumeName());
|
||||
assertThrows(AwsException.class, () -> restarted.getDbInstance("retry-instance"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void persistedClusterTombstoneRetriesNamedBackendCleanup(boolean mockOnRestart, @TempDir Path tempDir)
|
||||
throws Exception {
|
||||
Path file = tempDir.resolve("rds-cluster-retry.json");
|
||||
TypeReference<Map<String, DbCluster>> type = new TypeReference<>() {};
|
||||
PersistentStorage<String, DbCluster> storage = new PersistentStorage<>(file, type);
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), storage, new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
DbCluster cluster = service.createDbCluster("retry-cluster", "postgres", "17.5", "admin", "password",
|
||||
"dbname", false, null, null, null, false);
|
||||
cluster.setStatus(DbInstanceStatus.DELETING);
|
||||
cluster.setBackendCleanupRequired(true);
|
||||
storage.put("us-east-1::retry-cluster", cluster);
|
||||
|
||||
PersistentStorage<String, DbCluster> reloaded = new PersistentStorage<>(file, type);
|
||||
reloaded.load();
|
||||
DbCluster retained = reloaded.get("us-east-1::retry-cluster").orElseThrow();
|
||||
assertTrue(retained.isBackendCleanupRequired());
|
||||
assertNotNull(retained.getDockerVolumeName());
|
||||
when(rdsConfig.mock()).thenReturn(mockOnRestart);
|
||||
RdsContainerManager restartedManager = mock(RdsContainerManager.class);
|
||||
RdsService restarted = newService(restartedManager, mock(RdsProxyManager.class),
|
||||
new InMemoryStorage<>(), reloaded, new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
restarted.restorePersistedRuntime();
|
||||
restarted.deleteDbCluster("retry-cluster");
|
||||
verify(restartedManager).stopForDelete(retained.getDbClusterArn(), retained.getDockerVolumeName());
|
||||
verify(restartedManager).removeVolume(retained.getDbClusterArn(),
|
||||
retained.getContainerStorageResourceId(), retained.getDockerVolumeName());
|
||||
assertThrows(AwsException.class, () -> restarted.getDbCluster("retry-cluster"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceTombstoneKeepsManagedSecretForStrictDeleteRetry() {
|
||||
when(rdsConfig.mock()).thenReturn(true);
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), secrets);
|
||||
DbInstance instance = service.createDbInstance("retry-secret", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false);
|
||||
String secretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:owned-instance";
|
||||
instance.setStatus(DbInstanceStatus.DELETING);
|
||||
instance.setMasterUserSecretArn(secretArn);
|
||||
instance.setManagedSecretCleanupRequired(true);
|
||||
IllegalStateException failure = new IllegalStateException("Secrets Manager unavailable");
|
||||
when(secrets.deleteSecret(eq(secretArn), isNull(), eq(true), eq("us-east-1")))
|
||||
.thenThrow(failure).thenReturn(new Secret());
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbInstance("retry-secret")));
|
||||
assertTrue(service.getDbInstance("retry-secret").isManagedSecretCleanupRequired());
|
||||
service.deleteDbInstance("retry-secret");
|
||||
assertThrows(AwsException.class, () -> service.getDbInstance("retry-secret"));
|
||||
verify(secrets, times(2)).deleteSecret(eq(secretArn), isNull(), eq(true), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void clusterTombstoneKeepsManagedSecretForStrictDeleteRetry() {
|
||||
when(rdsConfig.mock()).thenReturn(true);
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), secrets);
|
||||
DbCluster cluster = service.createDbCluster("retry-secret", "postgres", "17.5", "admin", "password",
|
||||
"dbname", false, null, null, null, false);
|
||||
String secretArn = "arn:aws:secretsmanager:us-east-1:123456789012:secret:owned-cluster";
|
||||
cluster.setStatus(DbInstanceStatus.DELETING);
|
||||
cluster.setMasterUserSecretArn(secretArn);
|
||||
cluster.setManagedSecretCleanupRequired(true);
|
||||
IllegalStateException failure = new IllegalStateException("Secrets Manager unavailable");
|
||||
when(secrets.deleteSecret(eq(secretArn), isNull(), eq(true), eq("us-east-1")))
|
||||
.thenThrow(failure).thenReturn(new Secret());
|
||||
|
||||
assertSame(failure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbCluster("retry-secret")));
|
||||
assertTrue(service.getDbCluster("retry-secret").isManagedSecretCleanupRequired());
|
||||
service.deleteDbCluster("retry-secret");
|
||||
assertThrows(AwsException.class, () -> service.getDbCluster("retry-secret"));
|
||||
verify(secrets, times(2)).deleteSecret(eq(secretArn), isNull(), eq(true), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceTombstoneDoesNotDeleteUnownedManagedSecretName() {
|
||||
when(rdsConfig.mock()).thenReturn(true);
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), secrets);
|
||||
DbInstance instance = service.createDbInstance("retry-secret", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false);
|
||||
instance.setStatus(DbInstanceStatus.DELETING);
|
||||
instance.setManagedSecretCleanupRequired(true);
|
||||
Secret unowned = new Secret();
|
||||
unowned.setName("rds!" + instance.getDbiResourceId());
|
||||
unowned.setArn("arn:aws:secretsmanager:us-east-1:123456789012:secret:unowned");
|
||||
unowned.setOwningService("rds");
|
||||
when(secrets.describeSecret(eq(unowned.getName()), eq("us-east-1"))).thenReturn(unowned);
|
||||
|
||||
service.deleteDbInstance("retry-secret");
|
||||
verify(secrets, never()).deleteSecret(any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void instanceTombstoneRetainsManagedSecretWhenServiceIsUnavailable() {
|
||||
when(rdsConfig.mock()).thenReturn(true);
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), (SecretsManagerService) null);
|
||||
DbInstance instance = service.createDbInstance("retry-secret", "postgres", "13", "admin", "password",
|
||||
"dbname", "db.t3.micro", 20, false, null, null, null, null, false);
|
||||
instance.setStatus(DbInstanceStatus.DELETING);
|
||||
instance.setMasterUserSecretArn("arn:aws:secretsmanager:us-east-1:123456789012:secret:owned-instance");
|
||||
instance.setManagedSecretCleanupRequired(true);
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> service.deleteDbInstance("retry-secret"));
|
||||
assertTrue(service.getDbInstance("retry-secret").isManagedSecretCleanupRequired());
|
||||
assertNotNull(service.getDbInstance("retry-secret").getMasterUserSecretArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifyDbInstanceAppliesInstanceClassStorageAndEngineVersion() {
|
||||
createScalingInstance("scaled", "postgres", "13", 20);
|
||||
|
||||
+86
@@ -898,6 +898,39 @@ class RdsContainerManagerTest {
|
||||
ArgumentMatchers.eq("created-container"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryStartKeepsFixedNameWhenCreateResponseAndCleanupAreLost() {
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.create(any()))
|
||||
.thenThrow(new IllegalStateException("connection reset after Docker create"));
|
||||
doThrow(new IllegalStateException("fixed-name cleanup unavailable"))
|
||||
.when(lifecycleManager).stopAndRemoveStrict(any(), any());
|
||||
when(lifecycleManager.getDockerClient()).thenThrow(
|
||||
new RuntimeException("java.net.SocketException: No such file or directory"));
|
||||
RdsContainerManager manager = daemonlessCapableManager(lifecycleManager);
|
||||
String runtimeId = "arn:aws:rds:us-east-1:000000000000:db:db1";
|
||||
|
||||
assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of()));
|
||||
assertEquals("floci-aws-rds-db1", manager.getActiveHandle(runtimeId).getContainerId());
|
||||
|
||||
assertNull(manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of()));
|
||||
assertEquals("floci-aws-rds-db1", manager.getActiveHandle(runtimeId).getContainerId());
|
||||
|
||||
Mockito.reset(lifecycleManager);
|
||||
stubStarts(lifecycleManager, new ContainerLifecycleManager.ContainerInfo(
|
||||
"late-container", Map.of(3306, new ContainerLifecycleManager.EndpointInfo("db1", 3306))));
|
||||
DockerClient dockerClient = mock(DockerClient.class, Mockito.RETURNS_DEEP_STUBS);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(dockerClient);
|
||||
|
||||
RdsContainerHandle handle = manager.tryStart(runtimeId, "db1", "db1", "floci-rds-db1",
|
||||
DatabaseEngine.MYSQL, "mysql:8.0", "root", "password", "db", Map.of());
|
||||
|
||||
assertEquals("late-container", handle.getContainerId());
|
||||
verify(lifecycleManager).stopAndRemoveStrict(eq("floci-aws-rds-db1"), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tryStartRetriesACleanupThatFailedAfterAStop() {
|
||||
// The service stops a container whose auth proxy did not start. When that stop fails
|
||||
@@ -1183,6 +1216,59 @@ class RdsContainerManagerTest {
|
||||
assertNull(manager.getActiveHandle(runtimeId));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopForDeleteRemovesPersistedCurrentAndLegacyContainerNames() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
|
||||
manager.stopForDelete("arn:aws:rds:us-east-1:111111111111:db:legacy",
|
||||
"floci-rds-legacy-volume");
|
||||
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-aws-rds-legacy-volume");
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-rds-legacy-volume");
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedFixedNameDeleteRetainsOwnershipForRetry() {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
doThrow(new IllegalStateException("fixed-name removal failed"))
|
||||
.doNothing()
|
||||
.when(lifecycleManager).removeIfExistsStrict("floci-aws-rds-legacy-volume");
|
||||
RdsContainerManager manager = new RdsContainerManager(
|
||||
new ContainerBuilder(config, mock(DockerHostResolver.class),
|
||||
mock(EmbeddedDnsServer.class)),
|
||||
lifecycleManager, mock(ContainerLogStreamer.class),
|
||||
mock(ContainerDetector.class), config,
|
||||
new RegionResolver("us-east-1", "000000000000"),
|
||||
mock(ServiceConfigAccess.class));
|
||||
String runtimeId = "arn:aws:rds:us-east-1:111111111111:db:legacy";
|
||||
|
||||
assertThrows(IllegalStateException.class, () ->
|
||||
manager.stopForDelete(runtimeId, "floci-rds-legacy-volume"));
|
||||
assertEquals("floci-aws-rds-legacy-volume",
|
||||
manager.getActiveHandle(runtimeId).getContainerId());
|
||||
assertThrows(IllegalStateException.class, () -> manager.start(
|
||||
"arn:aws:rds:us-east-1:222222222222:db:legacy", "legacy", "legacy",
|
||||
"floci-rds-legacy-volume", DatabaseEngine.MYSQL, "mysql:8.0",
|
||||
"root", "password", "db"));
|
||||
verify(lifecycleManager, never()).create(any());
|
||||
|
||||
manager.stopForDelete(runtimeId, "floci-rds-legacy-volume");
|
||||
assertNull(manager.getActiveHandle(runtimeId));
|
||||
verify(lifecycleManager).stopAndRemoveStrict(eq("floci-aws-rds-legacy-volume"),
|
||||
ArgumentMatchers.isNull());
|
||||
verify(lifecycleManager, times(2)).removeIfExistsStrict("floci-aws-rds-legacy-volume");
|
||||
verify(lifecycleManager).removeIfExistsStrict("floci-rds-legacy-volume");
|
||||
}
|
||||
|
||||
@Test
|
||||
void inProgressRuntimeClaimRejectsConcurrentDuplicateStart() throws Exception {
|
||||
EmulatorConfig config = config(tempDir.resolve("host-root"));
|
||||
|
||||
+87
-9
@@ -14,6 +14,7 @@ import java.io.DataInputStream;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.Socket;
|
||||
@@ -36,6 +37,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doNothing;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -52,7 +54,7 @@ class RdsProxyManagerTest {
|
||||
Thread accepting = blockedRetirement(release);
|
||||
AtomicReference<RuntimeException> failure = new AtomicReference<>();
|
||||
AtomicBoolean interrupted = new AtomicBoolean();
|
||||
ConcurrentHashMap<String, RdsAuthProxy> owned = registry(manager);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> owned = registry(manager, "proxies");
|
||||
try (ServerSocket listener = reusableSocket(0)) {
|
||||
int port = listener.getLocalPort();
|
||||
setServerSocket(proxy, listener);
|
||||
@@ -92,7 +94,7 @@ class RdsProxyManagerTest {
|
||||
proxy.acceptRetirementTimeout = Duration.ofMillis(10);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
Thread accepting = blockedRetirement(release);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> owned = registry(manager);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> owned = registry(manager, "proxies");
|
||||
try (ServerSocket listener = reusableSocket(0)) {
|
||||
int port = listener.getLocalPort();
|
||||
setServerSocket(proxy, listener);
|
||||
@@ -214,7 +216,7 @@ class RdsProxyManagerTest {
|
||||
|
||||
manager.updateMasterPassword("proxy", "rotated");
|
||||
|
||||
assertEquals("rotated", masterPassword(registry(manager).get("proxy")));
|
||||
assertEquals("rotated", masterPassword(registry(manager, "proxies").get("proxy")));
|
||||
assertPortUnavailable(proxyPort);
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
@@ -251,7 +253,7 @@ class RdsProxyManagerTest {
|
||||
IOException closeFailure = new IOException("simulated close failure");
|
||||
doThrow(closeFailure).when(serverSocket).close();
|
||||
setServerSocket(proxy, serverSocket);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager, "proxies");
|
||||
registry.put("proxy", proxy);
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () ->
|
||||
@@ -268,7 +270,7 @@ class RdsProxyManagerTest {
|
||||
RdsAuthProxy previous = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("simulated previous stop failure"))
|
||||
.when(previous).stop();
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager, "proxies");
|
||||
registry.put("proxy", previous);
|
||||
int candidatePort = FreePorts.anyInterfacePort();
|
||||
|
||||
@@ -279,6 +281,74 @@ class RdsProxyManagerTest {
|
||||
registry.clear();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedStartCleanupDoesNotReplaceExistingListenerAndStartRetriesIt() throws Exception {
|
||||
RdsProxyManager manager = manager();
|
||||
int originalPort = FreePorts.anyInterfacePort();
|
||||
try {
|
||||
start(manager, "proxy", originalPort);
|
||||
RdsAuthProxy original = registry(manager, "proxies").get("proxy");
|
||||
RdsAuthProxy failedCandidate = mock(RdsAuthProxy.class);
|
||||
IllegalStateException stopFailure = new IllegalStateException("candidate stop failed");
|
||||
doThrow(stopFailure).doNothing().when(failedCandidate).stop();
|
||||
RuntimeException startupFailure = new RuntimeException("candidate start failed");
|
||||
recordFailedStart(manager, "proxy", failedCandidate, startupFailure);
|
||||
|
||||
assertSame(stopFailure, startupFailure.getSuppressed()[0]);
|
||||
assertSame(original, registry(manager, "proxies").get("proxy"));
|
||||
int replacementPort = FreePorts.anyInterfacePort();
|
||||
start(manager, "proxy", replacementPort);
|
||||
verify(failedCandidate, times(2)).stop();
|
||||
assertFalse(registry(manager, "pendingFailedStarts").containsKey("proxy"));
|
||||
assertPortAvailable(originalPort);
|
||||
assertPortUnavailable(replacementPort);
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopProxyRetainsOnlyFailedPendingCandidateForRetry() throws Exception {
|
||||
RdsProxyManager manager = manager();
|
||||
int originalPort = FreePorts.anyInterfacePort();
|
||||
try {
|
||||
start(manager, "proxy", originalPort);
|
||||
RdsAuthProxy failedCandidate = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("candidate stop failed"))
|
||||
.doThrow(new IllegalStateException("candidate retry failed"))
|
||||
.doNothing().when(failedCandidate).stop();
|
||||
recordFailedStart(manager, "proxy", failedCandidate, new RuntimeException("start failed"));
|
||||
|
||||
assertThrows(IllegalStateException.class, () -> manager.stopProxy("proxy"));
|
||||
assertFalse(registry(manager, "proxies").containsKey("proxy"));
|
||||
assertSame(failedCandidate, registry(manager, "pendingFailedStarts").get("proxy"));
|
||||
assertPortAvailable(originalPort);
|
||||
manager.stopProxy("proxy");
|
||||
assertFalse(registry(manager, "pendingFailedStarts").containsKey("proxy"));
|
||||
} finally {
|
||||
manager.stopAll();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopAllRetainsFailedStartCandidateUntilNextAttempt() throws Exception {
|
||||
RdsProxyManager manager = manager();
|
||||
int originalPort = FreePorts.anyInterfacePort();
|
||||
start(manager, "proxy", originalPort);
|
||||
RdsAuthProxy failedCandidate = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("candidate stop failed"))
|
||||
.doThrow(new IllegalStateException("candidate shutdown failed"))
|
||||
.doNothing().when(failedCandidate).stop();
|
||||
recordFailedStart(manager, "proxy", failedCandidate, new RuntimeException("start failed"));
|
||||
|
||||
manager.stopAll();
|
||||
assertFalse(registry(manager, "proxies").containsKey("proxy"));
|
||||
assertSame(failedCandidate, registry(manager, "pendingFailedStarts").get("proxy"));
|
||||
assertPortAvailable(originalPort);
|
||||
manager.stopAll();
|
||||
assertFalse(registry(manager, "pendingFailedStarts").containsKey("proxy"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stopAllContinuesAndRetainsOnlyFailedListenerOwnership() throws Exception {
|
||||
RdsProxyManager manager = manager();
|
||||
@@ -287,7 +357,7 @@ class RdsProxyManagerTest {
|
||||
RdsAuthProxy failed = mock(RdsAuthProxy.class);
|
||||
doThrow(new IllegalStateException("simulated shutdown stop failure"))
|
||||
.when(failed).stop();
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager);
|
||||
ConcurrentHashMap<String, RdsAuthProxy> registry = registry(manager, "proxies");
|
||||
registry.put("failed", failed);
|
||||
|
||||
assertDoesNotThrow(manager::stopAll);
|
||||
@@ -316,7 +386,7 @@ class RdsProxyManagerTest {
|
||||
FreePorts.anyInterfacePort(), "stale-address", 1, "localhost",
|
||||
"sa", "secret", null, (user, password) -> true, null);
|
||||
RdsAuthProxy.BackendEndpointResolver resolver = endpointResolver(
|
||||
registry(manager).get("proxy"));
|
||||
registry(manager, "proxies").get("proxy"));
|
||||
|
||||
List<LogRecord> records = LogCapture.capture(RdsProxyManager.class, () -> {
|
||||
assertThrows(IOException.class, resolver::resolve);
|
||||
@@ -459,12 +529,20 @@ class RdsProxyManagerTest {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static ConcurrentHashMap<String, RdsAuthProxy> registry(
|
||||
RdsProxyManager manager) throws Exception {
|
||||
Field field = RdsProxyManager.class.getDeclaredField("proxies");
|
||||
RdsProxyManager manager, String name) throws Exception {
|
||||
Field field = RdsProxyManager.class.getDeclaredField(name);
|
||||
field.setAccessible(true);
|
||||
return (ConcurrentHashMap<String, RdsAuthProxy>) field.get(manager);
|
||||
}
|
||||
|
||||
private static void recordFailedStart(
|
||||
RdsProxyManager manager, String key, RdsAuthProxy candidate, Throwable failure) throws Exception {
|
||||
Method method = RdsProxyManager.class.getDeclaredMethod(
|
||||
"cleanupFailedStart", String.class, RdsAuthProxy.class, Throwable.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(manager, key, candidate, failure);
|
||||
}
|
||||
|
||||
private static void assertPortAvailable(int port) {
|
||||
IOException lastFailure = null;
|
||||
for (int attempt = 0; attempt < 50; attempt++) {
|
||||
|
||||
Reference in new issue
Block a user