mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -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
@@ -1783,11 +1783,17 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
DbInstanceAutomatedBackup backup = activeInstanceBackupOf(instance, region, now);
|
||||
backup.setStatus(DbInstanceAutomatedBackup.RETAINED);
|
||||
backup.setInstance(instance);
|
||||
String dump = saveBackupData(instance.getEngine(), instance.getContainerId(), instance.getMasterUsername(),
|
||||
"DB instance " + instance.getDbInstanceIdentifier(), "InvalidDBInstanceState");
|
||||
if (dump != null) {
|
||||
snapshotData.put(instanceBackupDataKey(region, instance.getDbiResourceId()), dump);
|
||||
String dataKey = instanceBackupDataKey(region, instance.getDbiResourceId());
|
||||
// A delete retry may no longer have the container that produced the first dump.
|
||||
if (instance.getStatus() == DbInstanceStatus.DELETING && snapshotData.get(dataKey).isPresent()) {
|
||||
backup.setDataSaved(true);
|
||||
} else {
|
||||
String dump = saveBackupData(instance.getEngine(), instance.getContainerId(), instance.getMasterUsername(),
|
||||
"DB instance " + instance.getDbInstanceIdentifier(), "InvalidDBInstanceState");
|
||||
if (dump != null) {
|
||||
snapshotData.put(dataKey, dump);
|
||||
backup.setDataSaved(true);
|
||||
}
|
||||
}
|
||||
return backup;
|
||||
}
|
||||
@@ -1803,11 +1809,16 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
backup.setEarliestTime(cluster.getCreatedAt() != null ? cluster.getCreatedAt() : now);
|
||||
backup.setLatestTime(now);
|
||||
backup.setBackupRetentionPeriod(CLUSTER_BACKUP_RETENTION_DAYS);
|
||||
String dump = saveBackupData(cluster.getEngine(), cluster.getContainerId(), cluster.getMasterUsername(),
|
||||
"DB cluster " + cluster.getDbClusterIdentifier(), "InvalidDBClusterStateFault");
|
||||
if (dump != null) {
|
||||
snapshotData.put(clusterBackupDataKey(region, cluster.getDbClusterResourceId()), dump);
|
||||
String dataKey = clusterBackupDataKey(region, cluster.getDbClusterResourceId());
|
||||
if (cluster.getStatus() == DbInstanceStatus.DELETING && snapshotData.get(dataKey).isPresent()) {
|
||||
backup.setDataSaved(true);
|
||||
} else {
|
||||
String dump = saveBackupData(cluster.getEngine(), cluster.getContainerId(), cluster.getMasterUsername(),
|
||||
"DB cluster " + cluster.getDbClusterIdentifier(), "InvalidDBClusterStateFault");
|
||||
if (dump != null) {
|
||||
snapshotData.put(dataKey, dump);
|
||||
backup.setDataSaved(true);
|
||||
}
|
||||
}
|
||||
return backup;
|
||||
}
|
||||
@@ -3313,6 +3324,69 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
private String matchingManagedSecretArn(String secretName, Secret.Tag ownerTag, String region) {
|
||||
try {
|
||||
Secret secret = secretsManagerService.describeSecret(secretName, region);
|
||||
if (secret != null && secretName.equals(secret.getName())
|
||||
&& MANAGED_SECRET_OWNING_SERVICE.equals(secret.getOwningService())
|
||||
&& secret.getTags() != null && secret.getTags().contains(ownerTag)) {
|
||||
return secret.getArn();
|
||||
}
|
||||
} catch (AwsException failure) {
|
||||
if (!"ResourceNotFoundException".equals(failure.getErrorCode())) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void cleanupFailedCreateManagedSecret(String secretArn, String region) {
|
||||
if (secretArn == null || secretsManagerService == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
secretsManagerService.deleteSecret(secretArn, null, true, region);
|
||||
} catch (AwsException failure) {
|
||||
if (!"ResourceNotFoundException".equals(failure.getErrorCode())) {
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void cleanupFailedCreateManagedSecret(DbInstance instance, String region) {
|
||||
if (secretsManagerService == null) {
|
||||
throw new IllegalStateException("Secrets Manager is required to retry RDS managed secret cleanup");
|
||||
}
|
||||
if (instance.isManagedSecretCleanupRequired() && instance.getMasterUserSecretArn() == null) {
|
||||
instance.setMasterUserSecretArn(matchingManagedSecretArn(
|
||||
"rds!" + instance.getDbiResourceId(),
|
||||
new Secret.Tag("aws:rds:primaryDBInstanceArn", instance.getDbInstanceArn()), region));
|
||||
}
|
||||
if (instance.getMasterUserSecretArn() != null) {
|
||||
instance.setManagedSecretCleanupRequired(true);
|
||||
cleanupFailedCreateManagedSecret(instance.getMasterUserSecretArn(), region);
|
||||
instance.setMasterUserSecretArn(null);
|
||||
}
|
||||
instance.setManagedSecretCleanupRequired(false);
|
||||
}
|
||||
|
||||
private void cleanupFailedCreateManagedSecret(DbCluster cluster, String region) {
|
||||
if (secretsManagerService == null) {
|
||||
throw new IllegalStateException("Secrets Manager is required to retry RDS managed secret cleanup");
|
||||
}
|
||||
if (cluster.isManagedSecretCleanupRequired() && cluster.getMasterUserSecretArn() == null) {
|
||||
cluster.setMasterUserSecretArn(matchingManagedSecretArn(
|
||||
"rds!" + cluster.getDbClusterResourceId(),
|
||||
new Secret.Tag("aws:rds:primaryDBClusterArn", cluster.getDbClusterArn()), region));
|
||||
}
|
||||
if (cluster.getMasterUserSecretArn() != null) {
|
||||
cluster.setManagedSecretCleanupRequired(true);
|
||||
cleanupFailedCreateManagedSecret(cluster.getMasterUserSecretArn(), region);
|
||||
cluster.setMasterUserSecretArn(null);
|
||||
}
|
||||
cluster.setManagedSecretCleanupRequired(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies a new KMS key to a cluster's existing managed master user secret. AWS re-encrypts the
|
||||
* secret in place on {@code ModifyDBCluster}; silently keeping the old key would make the call
|
||||
@@ -4846,17 +4920,20 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
detachReadReplicaLinksBeforeDelete(instance);
|
||||
|
||||
boolean mock = config.services().rds().mock();
|
||||
if (!mock) {
|
||||
if (!mock || instance.isBackendCleanupRequired()) {
|
||||
proxyManager.stopProxy(rdsResourceRelayKey(instance.getDbInstanceArn(), id));
|
||||
}
|
||||
|
||||
if (clusterId == null || clusterId.isBlank()) {
|
||||
// Standalone, so stop its container and clean up its Docker volume. Neither exists in
|
||||
// mock mode, and an instance with no container and no reachable daemon has nothing
|
||||
// Docker could clean up, so its delete stays pure metadata.
|
||||
if (!mock && backendCleanupPossible(
|
||||
instance.getContainerId(), instance.getDbInstanceArn())) {
|
||||
if (instance.getContainerId() != null) {
|
||||
// Standalone, so stop its container and clean up its Docker volume. Current mock mode
|
||||
// skips an ordinary backend, but a persisted cleanup flag still owns a prior backend.
|
||||
// Without either, deletion stays pure metadata.
|
||||
if (instance.isBackendCleanupRequired() || (!mock && backendCleanupPossible(
|
||||
instance.getContainerId(), instance.getDbInstanceArn()))) {
|
||||
if (instance.isBackendCleanupRequired()) {
|
||||
containerManager.stopForDelete(
|
||||
instance.getDbInstanceArn(), resolvedInstanceDockerVolumeName(instance));
|
||||
} else if (instance.getContainerId() != null) {
|
||||
containerManager.stop(buildHandle(instance));
|
||||
} else {
|
||||
containerManager.stopByRuntimeId(instance.getDbInstanceArn());
|
||||
@@ -4865,8 +4942,16 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
instance.getDbInstanceArn(),
|
||||
resolvedInstanceStorageResourceId(instance),
|
||||
resolvedInstanceDockerVolumeName(instance));
|
||||
if (instance.isBackendCleanupRequired()) {
|
||||
instance.setBackendCleanupRequired(false);
|
||||
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
|
||||
}
|
||||
}
|
||||
if (instance.isManagedSecretCleanupRequired()) {
|
||||
cleanupFailedCreateManagedSecret(instance, effectiveRegion);
|
||||
} else {
|
||||
detachManagedMasterUserSecret(instance.getMasterUserSecretArn(), effectiveRegion);
|
||||
}
|
||||
detachManagedMasterUserSecret(instance.getMasterUserSecretArn(), effectiveRegion);
|
||||
} else {
|
||||
// Cluster member — remove from cluster's member list
|
||||
DbCluster cluster = findClusterForScope(
|
||||
@@ -4880,8 +4965,19 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
deleteInstanceForScope(currentAccountId(), effectiveRegion, id);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
try {
|
||||
putInstanceForScope(currentAccountId(), effectiveRegion, id, instance);
|
||||
} catch (RuntimeException | Error restoreFailure) {
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
releaseProxyPort(instance.getProxyPort());
|
||||
deleteInstanceForScope(currentAccountId(), effectiveRegion, id);
|
||||
reportedMemberRelayFailures.remove(instance.getDbInstanceArn());
|
||||
retainReplicatedBackups(instance);
|
||||
if (retained != null) {
|
||||
@@ -5766,15 +5862,23 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
: retainedClusterBackupOf(cluster, effectiveRegion);
|
||||
detachFromGlobalClusterBeforeDelete(cluster);
|
||||
|
||||
detachManagedMasterUserSecret(cluster, effectiveRegion);
|
||||
if (cluster.isManagedSecretCleanupRequired()) {
|
||||
cleanupFailedCreateManagedSecret(cluster, effectiveRegion);
|
||||
} else {
|
||||
detachManagedMasterUserSecret(cluster, effectiveRegion);
|
||||
}
|
||||
|
||||
cluster.setStatus(DbInstanceStatus.DELETING);
|
||||
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
|
||||
|
||||
if (!config.services().rds().mock()) {
|
||||
if (!config.services().rds().mock() || cluster.isBackendCleanupRequired()) {
|
||||
proxyManager.stopProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id));
|
||||
if (backendCleanupPossible(cluster.getContainerId(), cluster.getDbClusterArn())) {
|
||||
if (cluster.getContainerId() != null) {
|
||||
if (cluster.isBackendCleanupRequired()
|
||||
|| backendCleanupPossible(cluster.getContainerId(), cluster.getDbClusterArn())) {
|
||||
if (cluster.isBackendCleanupRequired()) {
|
||||
containerManager.stopForDelete(
|
||||
cluster.getDbClusterArn(), resolvedClusterDockerVolumeName(cluster));
|
||||
} else if (cluster.getContainerId() != null) {
|
||||
containerManager.stop(buildClusterHandle(cluster));
|
||||
} else {
|
||||
containerManager.stopByRuntimeId(cluster.getDbClusterArn());
|
||||
@@ -5783,11 +5887,26 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
cluster.getDbClusterArn(),
|
||||
resolvedClusterStorageResourceId(cluster),
|
||||
resolvedClusterDockerVolumeName(cluster));
|
||||
if (cluster.isBackendCleanupRequired()) {
|
||||
cluster.setBackendCleanupRequired(false);
|
||||
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
deleteClusterForScope(currentAccountId(), effectiveRegion, id);
|
||||
} catch (RuntimeException | Error failure) {
|
||||
try {
|
||||
putClusterForScope(currentAccountId(), effectiveRegion, id, cluster);
|
||||
} catch (RuntimeException | Error restoreFailure) {
|
||||
if (restoreFailure != failure) {
|
||||
failure.addSuppressed(restoreFailure);
|
||||
}
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
releaseProxyPort(cluster.getProxyPort());
|
||||
deleteClusterForScope(currentAccountId(), effectiveRegion, id);
|
||||
// Custom endpoints belong to their cluster and go with it.
|
||||
clusterEndpointsOf(effectiveRegion, id).forEach(endpoint -> clusterEndpoints.delete(
|
||||
clusterEndpointKey(effectiveRegion, endpoint.getDbClusterEndpointIdentifier())));
|
||||
@@ -10444,21 +10563,17 @@ public class RdsService implements Resettable, ResourceProvider {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reserves every persisted endpoint port for its owner before any restore allocates one, so a
|
||||
* resource restored earlier without a port cannot take the port of one restored later. When
|
||||
* two records persisted the same port, the first one seen keeps it.
|
||||
* Reserves every persisted endpoint port, including a deleting resource's retained listener,
|
||||
* before any restore allocates one. When two records persisted the same port, the first one
|
||||
* seen keeps it.
|
||||
*/
|
||||
private Map<Integer, String> reservePersistedProxyPorts() {
|
||||
Map<Integer, String> owners = new HashMap<>();
|
||||
for (DbCluster cluster : allClusters()) {
|
||||
if (cluster.getStatus() != DbInstanceStatus.DELETING) {
|
||||
reservePersistedProxyPort(owners, cluster.getDbClusterArn(), cluster.getProxyPort());
|
||||
}
|
||||
reservePersistedProxyPort(owners, cluster.getDbClusterArn(), cluster.getProxyPort());
|
||||
}
|
||||
for (DbInstance instance : allInstances()) {
|
||||
if (instance.getStatus() != DbInstanceStatus.DELETING) {
|
||||
reservePersistedProxyPort(owners, instance.getDbInstanceArn(), instance.getProxyPort());
|
||||
}
|
||||
reservePersistedProxyPort(owners, instance.getDbInstanceArn(), instance.getProxyPort());
|
||||
}
|
||||
for (DbProxy proxy : allProxies()) {
|
||||
reservePersistedProxyPort(owners, proxy.getDbProxyArn(), proxy.getProxyPort());
|
||||
|
||||
+47
-1
@@ -90,6 +90,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
private final Map<String, String> activeStorageOwners = new ConcurrentHashMap<>();
|
||||
private final Set<String> claimedRuntimes = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> cleanupPending = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> preCreateCleanupPending = ConcurrentHashMap.newKeySet();
|
||||
private final Set<String> parameterGroupRefusals = ConcurrentHashMap.newKeySet();
|
||||
private volatile boolean dockerUnavailableLogged;
|
||||
// Auto-pause state of every running container, by runtime id. The timer thread only keeps
|
||||
@@ -260,7 +261,8 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
|
||||
private void discardNeverCreatedIdentity(String runtimeId, String containerName) {
|
||||
RdsContainerHandle retained = activeContainers.get(runtimeId);
|
||||
if (retained == null || retained.getHost() != null
|
||||
if (retained == null || !preCreateCleanupPending.contains(runtimeId)
|
||||
|| retained.getHost() != null
|
||||
|| !retained.getContainerId().equals(containerName)) {
|
||||
return;
|
||||
}
|
||||
@@ -350,6 +352,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
}
|
||||
|
||||
String cleanupContainerId = containerName;
|
||||
boolean createAttempted = false;
|
||||
RdsContainerHandle handle = null;
|
||||
try {
|
||||
// Remove any stale container with the same name only after storage ownership is
|
||||
@@ -406,6 +409,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
// The fixed name remains a valid cleanup identity if create succeeds but its response
|
||||
// is lost before Docker returns the generated ID.
|
||||
cleanupContainerId = containerName;
|
||||
createAttempted = true;
|
||||
String createdContainerId = lifecycleManager.create(spec);
|
||||
cleanupContainerId = createdContainerId;
|
||||
if (needsMasterGrant(engine, masterUsername)) {
|
||||
@@ -468,6 +472,9 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
null, 0, storageKey, containerKey);
|
||||
activeContainers.put(effectiveRuntimeId, retained);
|
||||
cleanupPending.add(effectiveRuntimeId);
|
||||
if (!createAttempted) {
|
||||
preCreateCleanupPending.add(effectiveRuntimeId);
|
||||
}
|
||||
LOG.errorv(cleanupFailure,
|
||||
"Failed to clean up RDS container {0}; retaining storage ownership for {1}",
|
||||
cleanupContainerId, effectiveRuntimeId);
|
||||
@@ -547,6 +554,44 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes a failed creation's container even after its transient Docker handle is lost. */
|
||||
public void stopForDelete(String runtimeId, String dockerVolumeName) {
|
||||
stopByRuntimeId(runtimeId);
|
||||
String exactVolumeName = requireSafeStorageComponent(dockerVolumeName, "Docker volume name");
|
||||
String currentName = ContainerStorageHelper.dockerName(config, exactVolumeName);
|
||||
String legacyName = ContainerStorageHelper.legacyDockerName(config, exactVolumeName);
|
||||
String currentKey = "container:" + currentName;
|
||||
String legacyKey = legacyName.equals(currentName) ? null : "container:" + legacyName;
|
||||
if (!claimedRuntimes.add(runtimeId)) {
|
||||
throw new IllegalStateException("RDS runtime " + runtimeId + " already has an active container");
|
||||
}
|
||||
boolean cleanupPendingForRetry = false;
|
||||
String cleanupName = currentName;
|
||||
try {
|
||||
claimStorage(currentKey, runtimeId);
|
||||
if (legacyKey != null) {
|
||||
claimStorage(legacyKey, runtimeId);
|
||||
}
|
||||
try {
|
||||
lifecycleManager.removeIfExistsStrict(currentName);
|
||||
if (legacyKey != null) {
|
||||
cleanupName = legacyName;
|
||||
lifecycleManager.removeIfExistsStrict(legacyName);
|
||||
}
|
||||
} catch (RuntimeException | Error e) {
|
||||
activeContainers.put(runtimeId, new RdsContainerHandle(
|
||||
cleanupName, runtimeId, runtimeId, null, 0, currentKey, legacyKey));
|
||||
cleanupPending.add(runtimeId);
|
||||
cleanupPendingForRetry = true;
|
||||
throw e;
|
||||
}
|
||||
} finally {
|
||||
if (!cleanupPendingForRetry) {
|
||||
releaseOwnership(currentKey, legacyKey, runtimeId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Probes a backing RDS container. UNKNOWN means the Docker probe failed and the container's
|
||||
* state is not known, which is not the same as the container being gone.
|
||||
@@ -1341,6 +1386,7 @@ public class RdsContainerManager implements RdsBackendGate, RdsBackendEndpointRe
|
||||
}
|
||||
claimedRuntimes.remove(runtimeId);
|
||||
cleanupPending.remove(runtimeId);
|
||||
preCreateCleanupPending.remove(runtimeId);
|
||||
}
|
||||
|
||||
private static String requireSafeStorageComponent(String value, String label) {
|
||||
|
||||
@@ -51,6 +51,8 @@ public class DbCluster {
|
||||
private String dockerVolumeName;
|
||||
private String volumeId;
|
||||
private String containerStorageResourceId;
|
||||
private boolean backendCleanupRequired;
|
||||
private boolean managedSecretCleanupRequired;
|
||||
|
||||
// Aurora Serverless v2 scaling (ACUs). Null when the cluster is not Serverless v2.
|
||||
private Double serverlessV2MinCapacity;
|
||||
@@ -214,6 +216,16 @@ public class DbCluster {
|
||||
this.containerStorageResourceId = containerStorageResourceId;
|
||||
}
|
||||
|
||||
public boolean isBackendCleanupRequired() { return backendCleanupRequired; }
|
||||
public void setBackendCleanupRequired(boolean backendCleanupRequired) {
|
||||
this.backendCleanupRequired = backendCleanupRequired;
|
||||
}
|
||||
|
||||
public boolean isManagedSecretCleanupRequired() { return managedSecretCleanupRequired; }
|
||||
public void setManagedSecretCleanupRequired(boolean managedSecretCleanupRequired) {
|
||||
this.managedSecretCleanupRequired = managedSecretCleanupRequired;
|
||||
}
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public void setContainerId(String containerId) { this.containerId = containerId; }
|
||||
|
||||
|
||||
@@ -89,6 +89,8 @@ public class DbInstance {
|
||||
private String dockerVolumeName;
|
||||
private String volumeId;
|
||||
private String containerStorageResourceId;
|
||||
private boolean backendCleanupRequired;
|
||||
private boolean managedSecretCleanupRequired;
|
||||
|
||||
private transient String containerId;
|
||||
private transient String containerHost;
|
||||
@@ -295,6 +297,16 @@ public class DbInstance {
|
||||
this.containerStorageResourceId = containerStorageResourceId;
|
||||
}
|
||||
|
||||
public boolean isBackendCleanupRequired() { return backendCleanupRequired; }
|
||||
public void setBackendCleanupRequired(boolean backendCleanupRequired) {
|
||||
this.backendCleanupRequired = backendCleanupRequired;
|
||||
}
|
||||
|
||||
public boolean isManagedSecretCleanupRequired() { return managedSecretCleanupRequired; }
|
||||
public void setManagedSecretCleanupRequired(boolean managedSecretCleanupRequired) {
|
||||
this.managedSecretCleanupRequired = managedSecretCleanupRequired;
|
||||
}
|
||||
|
||||
public String getContainerId() { return containerId; }
|
||||
public void setContainerId(String containerId) { this.containerId = containerId; }
|
||||
|
||||
|
||||
@@ -10,6 +10,8 @@ import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@@ -27,6 +29,7 @@ public class RdsProxyManager {
|
||||
private final RdsBackendGate backendGate;
|
||||
private final RdsContainerManager containerManager;
|
||||
private final ConcurrentHashMap<String, RdsAuthProxy> proxies = new ConcurrentHashMap<>();
|
||||
private final ConcurrentHashMap<String, RdsAuthProxy> pendingFailedStarts = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RdsProxyManager(RdsSigV4Validator sigV4Validator, RdsProxyTlsCertificates tlsCertificates,
|
||||
@@ -89,6 +92,14 @@ public class RdsProxyManager {
|
||||
String masterUsername, String masterPassword, String dbName,
|
||||
RdsAuthProxy.MasterPasswordCheck passwordValidator,
|
||||
RdsProxyBinding binding, RdsAuthProxy.EndpointKind endpointKind) {
|
||||
if (instanceId == null) {
|
||||
throw new IllegalArgumentException("RDS proxy instance ID is required");
|
||||
}
|
||||
RdsAuthProxy pending = pendingFailedStarts.get(instanceId);
|
||||
if (pending != null) {
|
||||
pending.stop();
|
||||
pendingFailedStarts.remove(instanceId, pending);
|
||||
}
|
||||
tlsCertificates.ensureHost(advertisedHost);
|
||||
EmulatorConfig.RdsServiceConfig rdsConfig = config.services().rds();
|
||||
RdsAuthProxy proxy = new RdsAuthProxy(
|
||||
@@ -103,14 +114,17 @@ public class RdsProxyManager {
|
||||
RuntimeException failure = new RuntimeException(
|
||||
"Failed to start RDS proxy for instance " + instanceId
|
||||
+ " on port " + proxyPort, e);
|
||||
cleanupFailedStart(proxy, failure);
|
||||
cleanupFailedStart(instanceId, proxy, failure);
|
||||
throw failure;
|
||||
} catch (RuntimeException e) {
|
||||
RuntimeException failure = new RuntimeException(
|
||||
"Failed to register RDS proxy for instance " + instanceId
|
||||
+ " on port " + proxyPort, e);
|
||||
cleanupFailedStart(proxy, failure);
|
||||
cleanupFailedStart(instanceId, proxy, failure);
|
||||
throw failure;
|
||||
} catch (Error e) {
|
||||
cleanupFailedStart(instanceId, proxy, e);
|
||||
throw e;
|
||||
}
|
||||
RdsAuthProxy previous;
|
||||
try {
|
||||
@@ -119,17 +133,20 @@ public class RdsProxyManager {
|
||||
RuntimeException failure = new RuntimeException(
|
||||
"Failed to register RDS proxy for instance " + instanceId
|
||||
+ " on port " + proxyPort, e);
|
||||
cleanupFailedStart(proxy, failure);
|
||||
cleanupFailedStart(instanceId, proxy, failure);
|
||||
throw failure;
|
||||
} catch (Error e) {
|
||||
cleanupFailedStart(instanceId, proxy, e);
|
||||
throw e;
|
||||
}
|
||||
if (previous != null) {
|
||||
try {
|
||||
previous.stop();
|
||||
} catch (RuntimeException e) {
|
||||
} catch (RuntimeException | Error e) {
|
||||
proxies.put(instanceId, previous);
|
||||
RuntimeException failure = new RuntimeException(
|
||||
"Failed to replace RDS proxy for instance " + instanceId, e);
|
||||
cleanupFailedStart(proxy, failure);
|
||||
cleanupFailedStart(instanceId, proxy, failure);
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
@@ -152,20 +169,45 @@ public class RdsProxyManager {
|
||||
}
|
||||
|
||||
public synchronized void stopProxy(String instanceId) {
|
||||
Throwable failure = null;
|
||||
RdsAuthProxy pending = pendingFailedStarts.get(instanceId);
|
||||
if (pending != null) {
|
||||
try {
|
||||
pending.stop();
|
||||
pendingFailedStarts.remove(instanceId, pending);
|
||||
} catch (RuntimeException | Error e) {
|
||||
failure = e;
|
||||
}
|
||||
}
|
||||
RdsAuthProxy proxy = proxies.get(instanceId);
|
||||
if (proxy != null) {
|
||||
proxy.stop();
|
||||
proxies.remove(instanceId, proxy);
|
||||
LOG.infov("Stopped RDS proxy for instance {0}", instanceId);
|
||||
try {
|
||||
proxy.stop();
|
||||
proxies.remove(instanceId, proxy);
|
||||
LOG.infov("Stopped RDS proxy for instance {0}", instanceId);
|
||||
} catch (RuntimeException | Error e) {
|
||||
if (failure == null) {
|
||||
failure = e;
|
||||
} else if (failure != e) {
|
||||
failure.addSuppressed(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failure instanceof RuntimeException runtimeFailure) {
|
||||
throw runtimeFailure;
|
||||
}
|
||||
if (failure instanceof Error error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void stopAll() {
|
||||
proxies.forEach((instanceId, proxy) -> {
|
||||
Set<String> instanceIds = new HashSet<>(proxies.keySet());
|
||||
instanceIds.addAll(pendingFailedStarts.keySet());
|
||||
instanceIds.forEach(instanceId -> {
|
||||
try {
|
||||
proxy.stop();
|
||||
proxies.remove(instanceId, proxy);
|
||||
} catch (RuntimeException e) {
|
||||
stopProxy(instanceId);
|
||||
} catch (RuntimeException | Error e) {
|
||||
LOG.warnv(e, "Failed to stop RDS proxy for instance {0} during shutdown",
|
||||
instanceId);
|
||||
}
|
||||
@@ -173,11 +215,14 @@ public class RdsProxyManager {
|
||||
LOG.info("Stopped all RDS proxies");
|
||||
}
|
||||
|
||||
private void cleanupFailedStart(RdsAuthProxy proxy, RuntimeException failure) {
|
||||
private void cleanupFailedStart(String instanceId, RdsAuthProxy proxy, Throwable failure) {
|
||||
try {
|
||||
proxy.stop();
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
} catch (RuntimeException | Error cleanupFailure) {
|
||||
if (cleanupFailure != failure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
pendingFailedStarts.put(instanceId, proxy);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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