From 0d6bbe9662769de95cd5e772be56f9ee919a5f26 Mon Sep 17 00:00:00 2001 From: Jimmy Liu Jia <91264074+JimmyLiuJia@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:00:12 +0800 Subject: [PATCH] fix(rds): clean up late cluster creation failures (#7210) --- .../floci/services/rds/RdsService.java | 69 +++++++-- .../floci/services/rds/RdsServiceTest.java | 135 ++++++++++++++++++ 2 files changed, 189 insertions(+), 15 deletions(-) diff --git a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java index 7a6b96cf5a..19415a683a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java +++ b/src/main/java/io/github/hectorvent/floci/services/rds/RdsService.java @@ -5105,32 +5105,71 @@ public class RdsService implements Resettable, ResourceProvider { attachManagedMasterUserSecret(cluster, effectiveRegion, masterUserSecretKmsKeyId, effectiveSecretKmsKeyId); } + String clusterAccountId = currentAccountId(); + boolean clusterWriteStarted = false; + boolean proxyStartupCleanupFailed = false; try { if (!mock && hasBackend(cluster.getContainerHost(), cluster.getContainerPort())) { String effectiveMasterUser = masterUsername != null ? masterUsername : "root"; final String accountId = accountIdFromArn(cluster.getDbClusterArn()); final String clusterRegion = regionFromArn(cluster.getDbClusterArn()); - proxyManager.startProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id), - cluster.getDbClusterArn(), - engine, iamEnabled, proxyPort, - cluster.getContainerHost(), cluster.getContainerPort(), - cluster.getEndpoint().address(), - effectiveMasterUser, masterPassword, databaseName, - (user, pw) -> validateDbClusterPasswordForScope( - accountId, clusterRegion, id, user, pw), - proxyBinding(engine, cluster.getEndpoint().address(), cluster.getEndpoint().port(), - clusterRegion, accountId, cluster.getDbClusterResourceId())); + try { + proxyManager.startProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id), + cluster.getDbClusterArn(), + engine, iamEnabled, proxyPort, + cluster.getContainerHost(), cluster.getContainerPort(), + cluster.getEndpoint().address(), + effectiveMasterUser, masterPassword, databaseName, + (user, pw) -> validateDbClusterPasswordForScope( + accountId, clusterRegion, id, user, pw), + proxyBinding(engine, cluster.getEndpoint().address(), cluster.getEndpoint().port(), + clusterRegion, accountId, cluster.getDbClusterResourceId())); + } catch (RuntimeException startupFailure) { + // A failed stop before proxy registration leaves no listener for stopProxy to find. + proxyStartupCleanupFailed = startupFailure.getSuppressed().length > 0; + throw startupFailure; + } } cluster.setServerlessV2MinCapacity(serverlessV2MinCapacity); cluster.setServerlessV2MaxCapacity(serverlessV2MaxCapacity); cluster.setServerlessV2SecondsUntilAutoPause(effectiveAutoPauseSeconds); - putClusterForScope(currentAccountId(), effectiveRegion, id, cluster); + clusterWriteStarted = true; + putClusterForScope(clusterAccountId, effectiveRegion, id, cluster); } catch (RuntimeException e) { - // The cluster is not persisted, so DeleteDBCluster cannot reach the secret we just - // created: roll it back here rather than leave an orphaned RDS-owned secret. - if (manageMasterUserPassword) { - detachManagedMasterUserSecret(cluster, effectiveRegion); + boolean clusterRemoved = !clusterWriteStarted; + if (clusterWriteStarted) { + attemptRollback(e, () -> deleteClusterForScope(clusterAccountId, effectiveRegion, id)); + try { + clusterRemoved = !scopedKeyExists( + clusters, clusterAccountId, dbResourceKey(effectiveRegion, id)); + } catch (RuntimeException verificationFailure) { + if (verificationFailure != e) { + e.addSuppressed(verificationFailure); + } + } + } + if (clusterRemoved) { + boolean proxyStopped = mock; + if (!mock) { + try { + proxyManager.stopProxy(rdsResourceRelayKey(cluster.getDbClusterArn(), id)); + proxyStopped = true; + } catch (RuntimeException cleanupFailure) { + if (cleanupFailure != e) { + e.addSuppressed(cleanupFailure); + } + } + if (cluster.getContainerId() != null) { + attemptRollback(e, () -> containerManager.stop(buildClusterHandle(cluster))); + } + } + if (manageMasterUserPassword) { + attemptRollback(e, () -> detachManagedMasterUserSecret(cluster, effectiveRegion)); + } + if (proxyStopped && !proxyStartupCleanupFailed) { + releaseProxyPort(proxyPort); + } } throw e; } diff --git a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java index 0ae1013ab4..52ce1a6e19 100644 --- a/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/rds/RdsServiceTest.java @@ -1649,6 +1649,141 @@ class RdsServiceTest { verify(containerManager, times(2)).tryStart(any(), any(), any(), any(), any(), any(), any(), any(), any(), any()); } + @Test + void createDbClusterProxyFailureStopsContainerAndReusesPort() { + when(rdsConfig.proxyMaxPort()).thenReturn(7000); + String clusterArn = "arn:aws:rds:us-east-1:123456789012:cluster:retry-cluster"; + IllegalStateException startupFailure = new IllegalStateException("proxy start failed after binding"); + AtomicBoolean proxyRunning = new AtomicBoolean(); + doAnswer(invocation -> { + proxyRunning.set(true); + throw startupFailure; + }).doAnswer(invocation -> { + proxyRunning.set(true); + return null; + }).when(proxyManager).startProxy(any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), + any(), any(), any(), any(), any(), any()); + doAnswer(invocation -> { + proxyRunning.set(false); + return null; + }).when(proxyManager).stopProxy("rds-resource:" + clusterArn); + + IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> + rdsService.createDbCluster("retry-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false)); + + assertSame(startupFailure, thrown); + assertFalse(proxyRunning.get()); + verify(containerManager).stop(ArgumentMatchers.argThat( + handle -> "cont-id".equals(handle.getContainerId()))); + assertThrows(AwsException.class, () -> rdsService.getDbCluster("retry-cluster")); + DbCluster retried = rdsService.createDbCluster("retry-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false); + assertEquals(7000, retried.getProxyPort()); + } + + @Test + void createDbClusterPersistenceFailureRollsBackRuntimeAndRecord() { + when(rdsConfig.proxyMaxPort()).thenReturn(7000); + InMemoryStorage clusters = spy(new InMemoryStorage<>()); + String clusterKey = "us-east-1::retry-cluster"; + IllegalStateException persistenceFailure = new IllegalStateException("store wrote then failed"); + doAnswer(invocation -> { + invocation.callRealMethod(); + throw persistenceFailure; + }).doCallRealMethod().when(clusters).put(eq(clusterKey), any()); + RdsService service = newService(containerManager, proxyManager, + new InMemoryStorage<>(), clusters, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + + IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> + service.createDbCluster("retry-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false)); + + assertSame(persistenceFailure, thrown); + assertTrue(clusters.get(clusterKey).isEmpty()); + verify(proxyManager).stopProxy( + "rds-resource:arn:aws:rds:us-east-1:123456789012:cluster:retry-cluster"); + verify(containerManager).stop(ArgumentMatchers.argThat( + handle -> "cont-id".equals(handle.getContainerId()))); + DbCluster retried = service.createDbCluster("retry-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false); + assertEquals(7000, retried.getProxyPort()); + } + + @Test + void createDbClusterRetainsPortIfProxyCleanupFails() { + 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()); + + IllegalStateException thrown = assertThrows(IllegalStateException.class, () -> + rdsService.createDbCluster("failed-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false)); + + assertSame(startupFailure, thrown); + assertTrue(List.of(thrown.getSuppressed()).contains(cleanupFailure)); + verify(containerManager).stop(ArgumentMatchers.argThat( + handle -> "cont-id".equals(handle.getContainerId()))); + AwsException noPort = assertThrows(AwsException.class, () -> + rdsService.createDbCluster("another-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false)); + assertEquals("InsufficientDBInstanceCapacity", noPort.getErrorCode()); + } + + @Test + void createDbClusterRetainsPortIfUnregisteredProxyCleanupFails() { + when(rdsConfig.proxyMaxPort()).thenReturn(7000); + IllegalStateException startupFailure = new IllegalStateException("proxy start failed after binding"); + startupFailure.addSuppressed(new IllegalStateException("unregistered proxy could not stop")); + doThrow(startupFailure).when(proxyManager).startProxy( + any(), any(), any(), anyBoolean(), anyInt(), any(), anyInt(), + any(), any(), any(), any(), any(), any()); + + assertSame(startupFailure, assertThrows(IllegalStateException.class, () -> + rdsService.createDbCluster("failed-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false))); + + verify(proxyManager).stopProxy(any()); + verify(containerManager).stop(ArgumentMatchers.argThat( + handle -> "cont-id".equals(handle.getContainerId()))); + AwsException noPort = assertThrows(AwsException.class, () -> + rdsService.createDbCluster("another-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false)); + assertEquals("InsufficientDBInstanceCapacity", noPort.getErrorCode()); + } + + @Test + void createDbClusterPreservesOriginalFailureWhenStorageVerificationRethrowsIt() { + InMemoryStorage clusters = spy(new InMemoryStorage<>()); + String clusterKey = "us-east-1::failed-cluster"; + IllegalStateException persistenceFailure = new IllegalStateException("store failed"); + AtomicBoolean writeStarted = new AtomicBoolean(); + doAnswer(invocation -> { + invocation.callRealMethod(); + writeStarted.set(true); + throw persistenceFailure; + }).when(clusters).put(eq(clusterKey), any()); + doAnswer(invocation -> { + if (writeStarted.get()) { + throw persistenceFailure; + } + return invocation.callRealMethod(); + }).when(clusters).get(clusterKey); + RdsService service = newService(containerManager, proxyManager, + new InMemoryStorage<>(), clusters, + new InMemoryStorage<>(), new InMemoryStorage<>(), new InMemoryStorage<>()); + + assertSame(persistenceFailure, assertThrows(IllegalStateException.class, () -> + service.createDbCluster("failed-cluster", "postgres", "17.5", + "admin", "password", "dbname", false, null, null, null, false))); + assertTrue(clusters.keys().isEmpty()); + } + @Test void createDbInstanceStartsContainerWithRequestedEngineVersionImage() { rdsService.createDbInstance("mydb", "postgres", "18.1",