mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(rds): roll back failed standalone instance creation (#7283)
* fix(rds): roll back failed standalone instance creation * fix(rds): serialize failed standalone rollback with deletion * refactor(rds): share rollback suppression and assert monitor wait * test(rds): reuse blocked-thread wait helper
This commit is contained in:
1 parent
918c57a64e
commit
7b07cee8c6
2 files changed
+485
-89
No files matched your search
@@ -790,6 +790,8 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
String instanceVolumeId = null;
|
||||
String instanceDockerVolumeName = null;
|
||||
String instanceStorageResourceId = dbiResourceId;
|
||||
String instanceImage = null;
|
||||
Map<String, String> instanceEngineParameters = null;
|
||||
PlacementResolution placement;
|
||||
DbCluster publicationCluster = null;
|
||||
|
||||
@@ -825,64 +827,91 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
instanceStorageResourceId = resolvedClusterStorageResourceId(cluster);
|
||||
placement = PlacementResolution.fromCluster(cluster);
|
||||
} else {
|
||||
placement = resolvePlacement(dbSubnetGroupName, availabilityZone, multiAz, effectiveRegion);
|
||||
try {
|
||||
placement = resolvePlacement(dbSubnetGroupName, availabilityZone, multiAz, effectiveRegion);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
releaseProxyPort(proxyPort);
|
||||
throw failure;
|
||||
}
|
||||
if (!mock) {
|
||||
// Standalone instance, so it starts its own container. The record itself is metadata:
|
||||
// identifier, ARN, endpoint and tags come from configuration, so the instance is
|
||||
// created and reaches 'available' even when no Docker daemon is reachable.
|
||||
String image = imageForEngine(engine, engineVersion);
|
||||
instanceVolumeId = String.format("%06x", new SecureRandom().nextInt(0xFFFFFF));
|
||||
instanceDockerVolumeName = newVolumeName(
|
||||
instanceVolumeId, instanceStorageResourceId);
|
||||
try {
|
||||
instanceImage = imageForEngine(engine, engineVersion);
|
||||
instanceEngineParameters = instanceEngineParameters(
|
||||
currentAccountId(), effectiveRegion, paramGroupName);
|
||||
instanceVolumeId = String.format("%06x", new SecureRandom().nextInt(0xFFFFFF));
|
||||
instanceDockerVolumeName = newVolumeName(
|
||||
instanceVolumeId, instanceStorageResourceId);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
releaseProxyPort(proxyPort);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DbEndpoint endpoint;
|
||||
DbInstance instance;
|
||||
try {
|
||||
endpoint = mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort);
|
||||
instance = new DbInstance(id, engine, engineVersion, masterUsername, masterPassword,
|
||||
dbName, dbInstanceClass, allocatedStorage, DbInstanceStatus.CREATING,
|
||||
endpoint, iamEnabled, paramGroupName, dbClusterIdentifier, Instant.now(), proxyPort);
|
||||
instance.setOptionGroupName(optionGroupName);
|
||||
instance.setDbSubnetGroupName(dbSubnetGroupName);
|
||||
instance.setContainerId(containerId);
|
||||
instance.setContainerHost(containerHost);
|
||||
instance.setContainerPort(containerPort);
|
||||
instance.setVolumeId(instanceVolumeId);
|
||||
instance.setDockerVolumeName(instanceDockerVolumeName);
|
||||
instance.setContainerStorageResourceId(instanceStorageResourceId);
|
||||
instance.setTags(tags);
|
||||
instance.setVpcSecurityGroupIds(vpcSecurityGroupIds);
|
||||
instance.setDbSubnetGroupName(placement.dbSubnetGroupName());
|
||||
instance.setVpcId(placement.vpcId());
|
||||
instance.setAvailabilityZone(placement.availabilityZone());
|
||||
instance.setMultiAz(placement.multiAz());
|
||||
instance.setSubnetAvailabilityZones(placement.subnetAvailabilityZones());
|
||||
instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade);
|
||||
instance.setEngineIdentifier(engineIdentifier);
|
||||
resolvedSettings.applyTo(instance);
|
||||
instance.setPubliclyAccessible(publiclyAccessible != null
|
||||
? publiclyAccessible
|
||||
: defaultPubliclyAccessible(engineParam, dbSubnetGroupName));
|
||||
instance.setDeletionProtection(Boolean.TRUE.equals(deletionProtection));
|
||||
instance.setDbiResourceId(dbiResourceId);
|
||||
instance.setDbInstanceArn(dbInstanceArn);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
releaseProxyPort(proxyPort);
|
||||
throw failure;
|
||||
}
|
||||
String accountId = accountIdFromArn(instance.getDbInstanceArn());
|
||||
if (isBlank(dbClusterIdentifier) && !mock) {
|
||||
try {
|
||||
RdsContainerHandle handle = containerManager.tryStart(
|
||||
dbInstanceArn, id, instanceStorageResourceId,
|
||||
instanceDockerVolumeName, engine, image,
|
||||
masterUsername, masterPassword, dbName,
|
||||
instanceEngineParameters(currentAccountId(), effectiveRegion, paramGroupName));
|
||||
instanceDockerVolumeName, engine, instanceImage,
|
||||
masterUsername, masterPassword, dbName, instanceEngineParameters);
|
||||
if (handle != null) {
|
||||
backendHost = handle.getHost();
|
||||
backendPort = handle.getPort();
|
||||
containerId = handle.getContainerId();
|
||||
containerHost = handle.getHost();
|
||||
containerPort = handle.getPort();
|
||||
instance.setContainerId(handle.getContainerId());
|
||||
instance.setContainerHost(handle.getHost());
|
||||
instance.setContainerPort(handle.getPort());
|
||||
} else if (!containerManager.refusedParameterGroup(dbInstanceArn)) {
|
||||
LOG.warnv("DB instance {0} created without a backing database container: no "
|
||||
+ "Docker daemon is reachable. Metadata operations work; connections to "
|
||||
+ "the database do not until a daemon appears.", id);
|
||||
}
|
||||
} catch (RuntimeException | Error failure) {
|
||||
synchronized (instance) {
|
||||
rollbackFailedStandaloneInstanceCreate(failure, instance, accountId,
|
||||
effectiveRegion, false, false, mock);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
DbEndpoint endpoint = mock ? new DbEndpoint("localhost", proxyPort) : proxyEndpoint(proxyPort);
|
||||
DbInstance instance = new DbInstance(id, engine, engineVersion, masterUsername, masterPassword,
|
||||
dbName, dbInstanceClass, allocatedStorage, DbInstanceStatus.CREATING,
|
||||
endpoint, iamEnabled, paramGroupName, dbClusterIdentifier, Instant.now(), proxyPort);
|
||||
instance.setOptionGroupName(optionGroupName);
|
||||
instance.setDbSubnetGroupName(dbSubnetGroupName);
|
||||
instance.setContainerId(containerId);
|
||||
instance.setContainerHost(containerHost);
|
||||
instance.setContainerPort(containerPort);
|
||||
instance.setVolumeId(instanceVolumeId);
|
||||
instance.setDockerVolumeName(instanceDockerVolumeName);
|
||||
instance.setContainerStorageResourceId(instanceStorageResourceId);
|
||||
instance.setTags(tags);
|
||||
instance.setVpcSecurityGroupIds(vpcSecurityGroupIds);
|
||||
instance.setDbSubnetGroupName(placement.dbSubnetGroupName());
|
||||
instance.setVpcId(placement.vpcId());
|
||||
instance.setAvailabilityZone(placement.availabilityZone());
|
||||
instance.setMultiAz(placement.multiAz());
|
||||
instance.setSubnetAvailabilityZones(placement.subnetAvailabilityZones());
|
||||
instance.setAutoMinorVersionUpgrade(autoMinorVersionUpgrade);
|
||||
instance.setEngineIdentifier(engineIdentifier);
|
||||
resolvedSettings.applyTo(instance);
|
||||
instance.setPubliclyAccessible(publiclyAccessible != null
|
||||
? publiclyAccessible
|
||||
: defaultPubliclyAccessible(engineParam, dbSubnetGroupName));
|
||||
instance.setDeletionProtection(Boolean.TRUE.equals(deletionProtection));
|
||||
|
||||
instance.setDbiResourceId(dbiResourceId);
|
||||
instance.setDbInstanceArn(dbInstanceArn);
|
||||
String accountId = accountIdFromArn(instance.getDbInstanceArn());
|
||||
// The canonical cluster owns member publication and cluster changes. Standalone
|
||||
// publication and slow relay/storage work do not hold the service-wide monitor.
|
||||
synchronized (publicationCluster != null ? publicationCluster : instance) {
|
||||
@@ -925,51 +954,143 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (manageInstancePassword) {
|
||||
attachManagedMasterUserSecret(instance, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId);
|
||||
}
|
||||
putInstanceForScope(accountId, effectiveRegion, id, instance);
|
||||
boolean proxyStartAttempted = false;
|
||||
try {
|
||||
if (manageInstancePassword) {
|
||||
attachManagedMasterUserSecret(
|
||||
instance, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId);
|
||||
}
|
||||
putInstanceForScope(accountId, effectiveRegion, id, instance);
|
||||
|
||||
if (!mock && hasBackend(backendHost, backendPort)) {
|
||||
final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
|
||||
InstanceBackendIdentity backendIdentity = instanceBackendIdentity(instance);
|
||||
try {
|
||||
proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
|
||||
backendIdentity.runtimeId(),
|
||||
engine, iamEnabled, proxyPort, backendHost, backendPort,
|
||||
instance.getEndpoint().address(),
|
||||
instance.getMasterUsername(), instance.getMasterPassword(), dbName,
|
||||
(user, pw) -> validateDbPasswordForScope(
|
||||
accountId, instanceRegion, id, user, pw),
|
||||
proxyBinding(engine, instance.getEndpoint().address(), instance.getEndpoint().port(),
|
||||
instanceRegion, accountId, backendIdentity.dbUserResourceId()));
|
||||
} catch (RuntimeException | Error e) {
|
||||
if (!mock && hasBackend(backendHost, backendPort)) {
|
||||
final String instanceRegion = regionFromArn(instance.getDbInstanceArn());
|
||||
InstanceBackendIdentity backendIdentity = instanceBackendIdentity(instance);
|
||||
try {
|
||||
deleteInstanceForScope(accountId, effectiveRegion, id);
|
||||
} catch (RuntimeException rollbackFailure) {
|
||||
e.addSuppressed(rollbackFailure);
|
||||
proxyStartAttempted = true;
|
||||
proxyManager.startProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id),
|
||||
backendIdentity.runtimeId(), engine, iamEnabled, proxyPort,
|
||||
backendHost, backendPort, instance.getEndpoint().address(),
|
||||
instance.getMasterUsername(), instance.getMasterPassword(), dbName,
|
||||
(user, pw) -> validateDbPasswordForScope(
|
||||
accountId, instanceRegion, id, user, pw),
|
||||
proxyBinding(engine, instance.getEndpoint().address(), instance.getEndpoint().port(),
|
||||
instanceRegion, accountId, backendIdentity.dbUserResourceId()));
|
||||
} catch (RuntimeException | Error failure) {
|
||||
if (!isBlank(dbClusterIdentifier)) {
|
||||
try {
|
||||
deleteInstanceForScope(accountId, effectiveRegion, id);
|
||||
} catch (RuntimeException | Error rollbackFailure) {
|
||||
addSuppressedUnlessSelf(failure, rollbackFailure);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
if (currentCluster != null) {
|
||||
currentCluster.getDbClusterMembers().add(id);
|
||||
if (currentCluster.resolveWriterIdentifier() == null
|
||||
|| !currentCluster.getDbClusterMembers().contains(currentCluster.getClusterWriterIdentifier())) {
|
||||
currentCluster.setClusterWriterIdentifier(currentCluster.resolveWriterIdentifier());
|
||||
if (currentCluster != null) {
|
||||
currentCluster.getDbClusterMembers().add(id);
|
||||
if (currentCluster.resolveWriterIdentifier() == null
|
||||
|| !currentCluster.getDbClusterMembers().contains(currentCluster.getClusterWriterIdentifier())) {
|
||||
currentCluster.setClusterWriterIdentifier(currentCluster.resolveWriterIdentifier());
|
||||
}
|
||||
putClusterForScope(accountId, effectiveRegion, dbClusterIdentifier, currentCluster);
|
||||
}
|
||||
putClusterForScope(accountId, effectiveRegion, dbClusterIdentifier, currentCluster);
|
||||
}
|
||||
|
||||
instance.setStatus(DbInstanceStatus.AVAILABLE);
|
||||
putInstanceForScope(accountId, effectiveRegion, id, instance);
|
||||
instance.setStatus(DbInstanceStatus.AVAILABLE);
|
||||
putInstanceForScope(accountId, effectiveRegion, id, instance);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
if (isBlank(dbClusterIdentifier)) {
|
||||
rollbackFailedStandaloneInstanceCreate(failure, instance, accountId,
|
||||
effectiveRegion, proxyStartAttempted, manageInstancePassword, mock);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
LOG.infov("DB instance {0} created, engine={1}, endpoint={2}:{3}",
|
||||
id, engine, endpoint.address(), String.valueOf(endpoint.port()));
|
||||
return instance;
|
||||
}
|
||||
|
||||
private void rollbackFailedStandaloneInstanceCreate(
|
||||
Throwable failure, DbInstance instance, String accountId, String region,
|
||||
boolean proxyStartAttempted, boolean managedPassword, boolean mock) {
|
||||
String id = instance.getDbInstanceIdentifier();
|
||||
instance.setStatus(DbInstanceStatus.DELETING);
|
||||
instance.setDeletionProtection(false);
|
||||
instance.setBackendCleanupRequired(!mock && instance.getDockerVolumeName() != null);
|
||||
instance.setManagedSecretCleanupRequired(managedPassword
|
||||
&& (instance.getMasterUserSecretArn() != null
|
||||
|| instance.isManagedSecretCleanupRequired()));
|
||||
try {
|
||||
putInstanceForScope(accountId, region, id, instance);
|
||||
} catch (RuntimeException | Error persistenceFailure) {
|
||||
addSuppressedUnlessSelf(failure, persistenceFailure);
|
||||
return;
|
||||
}
|
||||
|
||||
boolean cleanupComplete = true;
|
||||
boolean proxyStopped = !proxyStartAttempted;
|
||||
if (proxyStartAttempted) {
|
||||
try {
|
||||
proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
|
||||
proxyStopped = true;
|
||||
} catch (RuntimeException | Error cleanupFailure) {
|
||||
cleanupComplete = false;
|
||||
addSuppressedUnlessSelf(failure, cleanupFailure);
|
||||
}
|
||||
}
|
||||
if (!mock && instance.getDockerVolumeName() != null) {
|
||||
try {
|
||||
if (instance.getContainerId() != null) {
|
||||
containerManager.stop(buildHandle(instance));
|
||||
} else {
|
||||
containerManager.stopForDelete(
|
||||
instance.getDbInstanceArn(), instance.getDockerVolumeName());
|
||||
}
|
||||
containerManager.removeVolume(instance.getDbInstanceArn(),
|
||||
resolvedInstanceStorageResourceId(instance),
|
||||
resolvedInstanceDockerVolumeName(instance));
|
||||
instance.setContainerId(null);
|
||||
instance.setBackendCleanupRequired(false);
|
||||
} catch (RuntimeException | Error cleanupFailure) {
|
||||
cleanupComplete = false;
|
||||
addSuppressedUnlessSelf(failure, cleanupFailure);
|
||||
}
|
||||
}
|
||||
if (managedPassword && (instance.getMasterUserSecretArn() != null
|
||||
|| instance.isManagedSecretCleanupRequired())) {
|
||||
try {
|
||||
cleanupFailedCreateManagedSecret(instance, region);
|
||||
} catch (RuntimeException | Error cleanupFailure) {
|
||||
cleanupComplete = false;
|
||||
addSuppressedUnlessSelf(failure, cleanupFailure);
|
||||
}
|
||||
}
|
||||
if (proxyStopped) {
|
||||
releaseProxyPort(instance.getProxyPort());
|
||||
instance.setProxyPort(0);
|
||||
instance.setEndpoint(null);
|
||||
}
|
||||
if (!cleanupComplete) {
|
||||
try {
|
||||
putInstanceForScope(accountId, region, id, instance);
|
||||
} catch (RuntimeException | Error persistenceFailure) {
|
||||
addSuppressedUnlessSelf(failure, persistenceFailure);
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
deleteInstanceForScope(accountId, region, id);
|
||||
} catch (RuntimeException | Error deletionFailure) {
|
||||
addSuppressedUnlessSelf(failure, deletionFailure);
|
||||
try {
|
||||
putInstanceForScope(accountId, region, id, instance);
|
||||
} catch (RuntimeException | Error persistenceFailure) {
|
||||
addSuppressedUnlessSelf(failure, persistenceFailure);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public DbSnapshot createDbSnapshot(String snapshotId, String instanceId) {
|
||||
return createDbSnapshot(snapshotId, instanceId, Map.of(), regionResolver.getDefaultRegion());
|
||||
}
|
||||
@@ -3240,6 +3361,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
List<Secret.Tag> tags = List.of(
|
||||
new Secret.Tag("aws:rds:primaryDBInstanceArn", instance.getDbInstanceArn()),
|
||||
new Secret.Tag("aws:secretsmanager:owningService", MANAGED_SECRET_OWNING_SERVICE));
|
||||
instance.setManagedSecretCleanupRequired(true);
|
||||
Secret secret = secretsManagerService.createSecret(
|
||||
secretName,
|
||||
managedMasterSecretString(instance),
|
||||
@@ -3252,6 +3374,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
instance.setMasterUserSecretArn(secret.getArn());
|
||||
instance.setMasterUserSecretStatus("active");
|
||||
instance.setMasterUserSecretKmsKeyId(effectiveKmsKeyId);
|
||||
instance.setManagedSecretCleanupRequired(false);
|
||||
}
|
||||
|
||||
private static String managedMasterSecretString(DbInstance instance) {
|
||||
@@ -4971,9 +5094,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
try {
|
||||
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
|
||||
} catch (RuntimeException | Error restoreFailure) {
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
addSuppressedUnlessSelf(failure, restoreFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
@@ -5240,9 +5361,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
clusterRemoved = !scopedKeyExists(
|
||||
clusters, clusterAccountId, dbResourceKey(effectiveRegion, id));
|
||||
} catch (RuntimeException verificationFailure) {
|
||||
if (verificationFailure != e) {
|
||||
e.addSuppressed(verificationFailure);
|
||||
}
|
||||
addSuppressedUnlessSelf(e, verificationFailure);
|
||||
}
|
||||
}
|
||||
if (clusterRemoved) {
|
||||
@@ -5252,9 +5371,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
proxyManager.stopProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id));
|
||||
proxyStopped = true;
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
if (cleanupFailure != e) {
|
||||
e.addSuppressed(cleanupFailure);
|
||||
}
|
||||
addSuppressedUnlessSelf(e, cleanupFailure);
|
||||
}
|
||||
if (cluster.getContainerId() != null) {
|
||||
attemptRollback(e, () -> containerManager.stop(buildClusterHandle(cluster)));
|
||||
@@ -5900,9 +6017,7 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
try {
|
||||
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
|
||||
} catch (RuntimeException | Error restoreFailure) {
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
addSuppressedUnlessSelf(failure, restoreFailure);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
@@ -8878,9 +8993,13 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
try {
|
||||
rollback.run();
|
||||
} catch (RuntimeException rollbackFailure) {
|
||||
if (rollbackFailure != failure) {
|
||||
failure.addSuppressed(rollbackFailure);
|
||||
}
|
||||
addSuppressedUnlessSelf(failure, rollbackFailure);
|
||||
}
|
||||
}
|
||||
|
||||
private static void addSuppressedUnlessSelf(Throwable failure, Throwable extra) {
|
||||
if (extra != failure) {
|
||||
failure.addSuppressed(extra);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -97,6 +97,7 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.logging.LogRecord;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.awaitility.Awaitility.await;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -1098,6 +1099,282 @@ class RdsServiceTest {
|
||||
assertThrows(AwsException.class, () -> rdsService.getDbInstance("mypostgres"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceProxyStartCleansBackendAndReusesPort() {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
String instanceArn = "arn:aws:rds:us-east-1:123456789012:db:retry-instance";
|
||||
IllegalStateException startupFailure = new IllegalStateException("proxy start failed");
|
||||
doThrow(startupFailure).doNothing().when(proxyManager).startProxy(
|
||||
any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
|
||||
assertSame(startupFailure, assertThrows(IllegalStateException.class, () ->
|
||||
rdsService.createDbInstance("retry-instance", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false)));
|
||||
assertThrows(AwsException.class, () -> rdsService.getDbInstance("retry-instance"));
|
||||
|
||||
ArgumentCaptor<String> volumeName = ArgumentCaptor.forClass(String.class);
|
||||
verify(containerManager).tryStart(eq(instanceArn), eq("retry-instance"), any(), volumeName.capture(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
verify(proxyManager).stopProxy("rds-resource:" + instanceArn);
|
||||
verify(containerManager).stop(ArgumentMatchers.argThat(
|
||||
handle -> "cont-id".equals(handle.getContainerId())));
|
||||
verify(containerManager).removeVolume(eq(instanceArn), any(), eq(volumeName.getValue()));
|
||||
|
||||
DbInstance retried = rdsService.createDbInstance("retry-instance", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false);
|
||||
assertEquals(7000, retried.getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceProxyCleanupRetainsRecordAndPort() {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
IllegalStateException startupFailure = new IllegalStateException("proxy start failed");
|
||||
IllegalStateException cleanupFailure = new IllegalStateException("proxy stop failed");
|
||||
doThrow(startupFailure).when(proxyManager).startProxy(
|
||||
any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
doThrow(cleanupFailure).when(proxyManager).stopProxy(any());
|
||||
|
||||
assertSame(startupFailure, assertThrows(IllegalStateException.class, () ->
|
||||
rdsService.createDbInstance("failed-instance", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false)));
|
||||
|
||||
DbInstance retained = rdsService.getDbInstance("failed-instance");
|
||||
assertEquals(DbInstanceStatus.DELETING, retained.getStatus());
|
||||
assertEquals(7000, retained.getProxyPort());
|
||||
AwsException noPort = assertThrows(AwsException.class, () ->
|
||||
rdsService.createDbInstance("another-instance", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro",
|
||||
20, false, null, null, null, null, false));
|
||||
assertEquals("InsufficientDBInstanceCapacity", noPort.getErrorCode());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceStartRetainsNamedCleanupAfterRestart(@TempDir Path tempDir) throws Exception {
|
||||
Path file = tempDir.resolve("rds-instance-cleanup.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<>());
|
||||
IllegalStateException startupFailure = new IllegalStateException("Docker create result lost");
|
||||
when(containerManager.tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
.thenThrow(startupFailure);
|
||||
doThrow(new IllegalStateException("cleanup unavailable"))
|
||||
.when(containerManager).stopForDelete(any(), any());
|
||||
|
||||
assertSame(startupFailure, assertThrows(IllegalStateException.class, () ->
|
||||
service.createDbInstance("failed-instance", "postgres", "13", "admin", "secret",
|
||||
"app", "db.t3.micro", 20, false, null, null, null)));
|
||||
PersistentStorage<String, DbInstance> reloaded = new PersistentStorage<>(file, type);
|
||||
reloaded.load();
|
||||
DbInstance retained = reloaded.get("us-east-1::failed-instance").orElseThrow();
|
||||
assertEquals(DbInstanceStatus.DELETING, retained.getStatus());
|
||||
assertTrue(retained.isBackendCleanupRequired());
|
||||
assertNotNull(retained.getDockerVolumeName());
|
||||
|
||||
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("failed-instance");
|
||||
verify(restartedManager).stopForDelete(retained.getDbInstanceArn(), retained.getDockerVolumeName());
|
||||
verify(restartedManager).removeVolume(retained.getDbInstanceArn(),
|
||||
retained.getContainerStorageResourceId(), retained.getDockerVolumeName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceCreatePersistsCleanupBeforeStoppingProxy(@TempDir Path tempDir) throws Exception {
|
||||
Path file = tempDir.resolve("rds-instance-cleanup-order.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<>());
|
||||
IllegalStateException startupFailure = new IllegalStateException("proxy start failed");
|
||||
doThrow(startupFailure).when(proxyManager).startProxy(
|
||||
any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
AtomicReference<DbInstance> persistedAtCleanup = new AtomicReference<>();
|
||||
doAnswer(invocation -> {
|
||||
PersistentStorage<String, DbInstance> reloaded = new PersistentStorage<>(file, type);
|
||||
reloaded.load();
|
||||
persistedAtCleanup.set(reloaded.get("us-east-1::failed-instance").orElse(null));
|
||||
return null;
|
||||
}).when(proxyManager).stopProxy(any());
|
||||
|
||||
assertSame(startupFailure, assertThrows(IllegalStateException.class, () ->
|
||||
service.createDbInstance("failed-instance", "postgres", "13", "admin", "secret",
|
||||
"app", "db.t3.micro", 20, false, null, null, null)));
|
||||
DbInstance retained = persistedAtCleanup.get();
|
||||
assertNotNull(retained);
|
||||
assertEquals(DbInstanceStatus.DELETING, retained.getStatus());
|
||||
assertNotNull(retained.getDockerVolumeName());
|
||||
assertThrows(AwsException.class, () -> service.getDbInstance("failed-instance"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceRollbackKeepsPortOwnedUntilCleanupFinishes() throws Exception {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>());
|
||||
IllegalStateException startupFailure = new IllegalStateException("backend startup failed");
|
||||
when(containerManager.tryStart(any(), any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any())).thenThrow(startupFailure).thenReturn(null);
|
||||
CountDownLatch cleanupEntered = new CountDownLatch(1);
|
||||
CountDownLatch allowCleanup = new CountDownLatch(1);
|
||||
AtomicBoolean firstCleanup = new AtomicBoolean(true);
|
||||
doAnswer(invocation -> {
|
||||
if (firstCleanup.compareAndSet(true, false)) {
|
||||
cleanupEntered.countDown();
|
||||
assertTrue(allowCleanup.await(10, TimeUnit.SECONDS));
|
||||
}
|
||||
return null;
|
||||
}).when(containerManager).stopForDelete(any(), any());
|
||||
|
||||
ExecutorService executor = Executors.newFixedThreadPool(2);
|
||||
Future<?> create = executor.submit(() -> assertSame(startupFailure,
|
||||
assertThrows(IllegalStateException.class, () -> service.createDbInstance(
|
||||
"failed-instance", "postgres", "13", "admin", "secret", "app",
|
||||
"db.t3.micro", 20, false, null, null, null))));
|
||||
try {
|
||||
assertTrue(cleanupEntered.await(10, TimeUnit.SECONDS));
|
||||
AtomicReference<Thread> deleteThread = new AtomicReference<>();
|
||||
Future<?> delete = executor.submit(() -> {
|
||||
deleteThread.set(Thread.currentThread());
|
||||
try {
|
||||
service.deleteDbInstance("failed-instance");
|
||||
} catch (AwsException e) {
|
||||
assertEquals("DBInstanceNotFound", e.getErrorCode());
|
||||
}
|
||||
});
|
||||
awaitBlockedOrDone(deleteThread, delete);
|
||||
assertFalse(delete.isDone(), "delete must wait while failed-create rollback owns the instance");
|
||||
assertEquals(Thread.State.BLOCKED, deleteThread.get().getState());
|
||||
|
||||
allowCleanup.countDown();
|
||||
create.get(10, TimeUnit.SECONDS);
|
||||
delete.get(10, TimeUnit.SECONDS);
|
||||
DbInstance next = service.createDbInstance("next-instance", "postgres", "13",
|
||||
"admin", "secret", "app", "db.t3.micro", 20, false, null, null,
|
||||
null, null, false, false, null, Map.of(), List.of(), null,
|
||||
"us-east-1", true, DbInstanceSettings.defaults(), null, 7000);
|
||||
assertEquals(7000, next.getProxyPort());
|
||||
AwsException conflict = assertThrows(AwsException.class, () ->
|
||||
service.createDbInstance("another-instance", "postgres", "13",
|
||||
"admin", "secret", "app", "db.t3.micro", 20, false,
|
||||
null, null, null, null, false, false, null, Map.of(),
|
||||
List.of(), null, "us-east-1", true,
|
||||
DbInstanceSettings.defaults(), null, 7000));
|
||||
assertEquals("InvalidParameterValue", conflict.getErrorCode());
|
||||
} finally {
|
||||
allowCleanup.countDown();
|
||||
executor.shutdownNow();
|
||||
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidInstancePlacementReleasesRequestedPort() {
|
||||
AwsException invalid = assertThrows(AwsException.class, () -> rdsService.createDbInstance(
|
||||
"invalid-placement", "postgres", "13", "admin", "secret123", null,
|
||||
"db.t3.micro", 20, false, null, null, null, "not-an-az", false,
|
||||
false, null, Map.of(), List.of(), null, "us-east-1", true,
|
||||
DbInstanceSettings.defaults(), null, 7005));
|
||||
assertEquals("InvalidVPCNetworkStateFault", invalid.getErrorCode());
|
||||
|
||||
DbInstance retried = rdsService.createDbInstance("valid-placement", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro", 20, false, null,
|
||||
null, null, null, false, false, null, Map.of(), List.of(), null,
|
||||
"us-east-1", true, DbInstanceSettings.defaults(), null, 7005);
|
||||
assertEquals(7005, retried.getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceEndpointResolutionReleasesPortBeforeBackendStart() {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
IllegalStateException endpointFailure = new IllegalStateException("endpoint unavailable");
|
||||
when(rdsConfig.endpointHost()).thenThrow(endpointFailure).thenReturn(Optional.empty());
|
||||
|
||||
assertSame(endpointFailure, assertThrows(IllegalStateException.class, () ->
|
||||
rdsService.createDbInstance("failed-endpoint", "postgres", "13", "admin",
|
||||
"secret123", null, "db.t3.micro", 20, false, null, null, null,
|
||||
null, false)));
|
||||
assertThrows(AwsException.class, () -> rdsService.getDbInstance("failed-endpoint"));
|
||||
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any());
|
||||
|
||||
DbInstance retried = rdsService.createDbInstance("valid-endpoint", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro", 20, false, null, null,
|
||||
null, null, false);
|
||||
assertEquals(7000, retried.getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceMetadataInitializationReleasesPortBeforeBackendStart() {
|
||||
when(rdsConfig.proxyMaxPort()).thenReturn(7000);
|
||||
DbInstanceSettings settings = new DbInstanceSettings(null, null, null, null, null, null,
|
||||
null, null, null, null, null, Collections.singletonList(null), null, null);
|
||||
|
||||
assertThrows(NullPointerException.class, () -> rdsService.createDbInstance(
|
||||
"failed-metadata", "postgres", "13", "admin", "secret123", null,
|
||||
"db.t3.micro", 20, false, null, null, null, null, false, false,
|
||||
null, Map.of(), List.of(), null, "us-east-1", true, settings, null, 7000));
|
||||
assertThrows(AwsException.class, () -> rdsService.getDbInstance("failed-metadata"));
|
||||
verify(containerManager, never()).tryStart(any(), any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any());
|
||||
|
||||
DbInstance retried = rdsService.createDbInstance("valid-metadata", "postgres", "13",
|
||||
"admin", "secret123", null, "db.t3.micro", 20, false, null, null,
|
||||
null, null, false);
|
||||
assertEquals(7000, retried.getProxyPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedInstanceSecretWriteRetainsOwnedIdentityForStrictRetry() {
|
||||
when(rdsConfig.mock()).thenReturn(true);
|
||||
SecretsManagerService secrets = mock(SecretsManagerService.class);
|
||||
AtomicReference<Secret> written = new AtomicReference<>();
|
||||
IllegalStateException writeFailure = new IllegalStateException("secret response lost");
|
||||
IllegalStateException deleteFailure = new IllegalStateException("secret delete failed");
|
||||
when(secrets.createSecret(any(), any(), isNull(), any(), eq("kms-key-1"),
|
||||
any(), eq("rds"), eq("us-east-1"))).thenAnswer(invocation -> {
|
||||
Secret secret = new Secret();
|
||||
secret.setName(invocation.getArgument(0));
|
||||
secret.setArn("arn:aws:secretsmanager:us-east-1:123456789012:secret:partial-instance");
|
||||
secret.setOwningService("rds");
|
||||
secret.setTags(invocation.getArgument(5));
|
||||
written.set(secret);
|
||||
throw writeFailure;
|
||||
});
|
||||
when(secrets.describeSecret(anyString(), eq("us-east-1"))).thenAnswer(invocation -> written.get());
|
||||
when(secrets.deleteSecret(anyString(), isNull(), eq(true), eq("us-east-1")))
|
||||
.thenThrow(deleteFailure).thenThrow(deleteFailure).thenReturn(new Secret());
|
||||
RdsService service = newService(containerManager, proxyManager,
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
new InMemoryStorage<>(), new InMemoryStorage<>(), secrets);
|
||||
|
||||
assertSame(writeFailure, assertThrows(IllegalStateException.class, () ->
|
||||
service.createDbInstance("failed-instance", "postgres", "13", "admin", null,
|
||||
"app", "db.t3.micro", 20, false, null, null, null, true, "kms-key-1")));
|
||||
DbInstance retained = service.getDbInstance("failed-instance");
|
||||
assertEquals(DbInstanceStatus.DELETING, retained.getStatus());
|
||||
assertEquals(written.get().getArn(), retained.getMasterUserSecretArn());
|
||||
assertTrue(retained.isManagedSecretCleanupRequired());
|
||||
assertSame(deleteFailure, assertThrows(IllegalStateException.class,
|
||||
() -> service.deleteDbInstance("failed-instance")));
|
||||
service.deleteDbInstance("failed-instance");
|
||||
assertThrows(AwsException.class, () -> service.getDbInstance("failed-instance"));
|
||||
verify(secrets, times(3)).deleteSecret(eq(written.get().getArn()),
|
||||
isNull(), eq(true), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidMasterUsernameDoesNotReserveRequestedPort() {
|
||||
assertEquals("InvalidParameterValue", assertThrows(AwsException.class,
|
||||
|
||||
Reference in new issue
Block a user