fix(neptune): roll back proxy port and container on failed provisioning (#1742)

* fix(neptune): roll back proxy port and container on failed provisioning

createDbCluster reserved a proxy port and started the container/proxy with
no rollback: any throw after allocateProxyPort() leaked the port (only freed
on delete) and orphaned the container. Repeated failures could exhaust the
proxy-port range and surface as a spurious InsufficientNeptuneCapacity error.

Wrap startup in try/catch, add rollbackDbCluster() that stops the proxy and
container in isolated try blocks (guarded by handle != null) and always
releases the port in finally, then rethrow. Mirrors the merged ElastiCache
fix (#1618). Adds unit tests for both rollback branches (proxy-start throws
after container is up; container-start throws before any handle).

* fix(neptune): clean up container by id on readiness-timeout rollback

Address Copilot review: NeptuneContainerManager.start() registers the
container in activeContainers before the readiness probe, which throws on
timeout without returning a handle. The previous handle-based rollback saw a
null handle and skipped the container stop, orphaning a running container.

Add an idempotent stopByClusterId() (with a deterministic-name fallback) and
call it from rollbackDbCluster instead of stop(handle); the proxy stop stays
guarded by handle != null. Update the service tests to the by-id cleanup and
add a container-manager test for the name fallback.

* fix(neptune): guarantee proxy-port release against non-RuntimeException

Address greptile review: the finally that runs releaseProxyPort was attached
only to the container-stop try, so an Error (e.g. NoClassDefFoundError) escaping
the proxy-stop step would bypass it and leak the port — the exact failure this
rollback prevents. Wrap both cleanup steps in an outer try whose finally always
releases the port; each step keeps its own RuntimeException handling.

* fix(neptune): roll back on JVM Errors during provisioning, not just RuntimeException

Address greptile P1: the outer catch (RuntimeException) in createDbCluster
would not intercept a JVM Error (OutOfMemoryError, NoClassDefFoundError, etc.)
thrown by a Docker operation, so rollback never ran and the port + container
leaked. (Note: catch (Exception) would not fix this — Error extends Throwable,
not Exception.) Move the rollback into a finally guarded by a success flag so it
fires on any non-success exit, including an Error, while the catch still logs the
common RuntimeException case with detail. Adds a StackOverflowError rollback test.

* fix(neptune): reserve proxy port inside the try to prevent leak on config-read failure

allocateProxyPort() ran before the try opened, so a throw from the
db-type/image config reads between them would leak the reserved port —
the exact failure this rollback path prevents. Move the try to open
immediately after the allocation.
This commit is contained in:
Ahmed khaled authored and GitHub committed 2026-07-10 20:45:47 -05:00
1 parent bf53ff71d8
commit 27f0124e36
4 files changed
+275 -38

No files matched your search

@@ -62,50 +62,93 @@ public class NeptuneService {
"Neptune cluster " + id + " already exists.", 400);
}
// Open the try immediately after reserving the port so config reads below can't leak it.
int proxyPort = allocateProxyPort();
String configuredDbType = config.services().neptune().dbType();
NeptuneDbType dbType = NeptuneDbType.fromConfig(configuredDbType).orElseGet(() -> {
LOG.warnv("Unsupported Neptune db-type ''{0}'', falling back to {1}. Supported: gremlin, neo4j.",
configuredDbType, NeptuneDbType.GREMLIN);
return NeptuneDbType.GREMLIN;
});
String image = switch (dbType) {
case GREMLIN -> config.services().neptune().defaultImage();
case NEO4J -> config.services().neptune().defaultNeo4jImage();
};
NeptuneContainerHandle handle = null;
boolean provisioned = false;
try {
String configuredDbType = config.services().neptune().dbType();
NeptuneDbType dbType = NeptuneDbType.fromConfig(configuredDbType).orElseGet(() -> {
LOG.warnv("Unsupported Neptune db-type ''{0}'', falling back to {1}. Supported: gremlin, neo4j.",
configuredDbType, NeptuneDbType.GREMLIN);
return NeptuneDbType.GREMLIN;
});
String image = switch (dbType) {
case GREMLIN -> config.services().neptune().defaultImage();
case NEO4J -> config.services().neptune().defaultNeo4jImage();
};
LOG.infov("Creating Neptune cluster {0} on proxy port {1}, dbType={2}, image={3}",
id, String.valueOf(proxyPort), dbType, image);
LOG.infov("Creating Neptune cluster {0} on proxy port {1}, dbType={2}, image={3}",
id, String.valueOf(proxyPort), dbType, image);
NeptuneContainerHandle handle = containerManager.start(id, image, dbType);
handle = containerManager.start(id, image, dbType);
String region = regionResolver.getDefaultRegion();
String endpointHost = resolveEndpointHost();
String region = regionResolver.getDefaultRegion();
String endpointHost = resolveEndpointHost();
NeptuneCluster cluster = new NeptuneCluster();
cluster.setDbClusterIdentifier(id);
cluster.setStatus("available");
cluster.setEngineVersion(engineVersion != null ? engineVersion : ENGINE_VERSION_DEFAULT);
cluster.setEndpoint(endpointHost);
cluster.setReaderEndpoint(endpointHost);
cluster.setPort(proxyPort);
cluster.setIamDatabaseAuthenticationEnabled(iamEnabled);
cluster.setDbClusterArn(regionResolver.buildArn("neptune", region, "cluster:" + id));
cluster.setDbClusterResourceId("cluster-" + UUID.randomUUID().toString()
.replace("-", "").substring(0, 24).toUpperCase());
cluster.setCreatedAt(Instant.now());
cluster.setDbClusterMembers(new ArrayList<>());
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setProxyPort(proxyPort);
NeptuneCluster cluster = new NeptuneCluster();
cluster.setDbClusterIdentifier(id);
cluster.setStatus("available");
cluster.setEngineVersion(engineVersion != null ? engineVersion : ENGINE_VERSION_DEFAULT);
cluster.setEndpoint(endpointHost);
cluster.setReaderEndpoint(endpointHost);
cluster.setPort(proxyPort);
cluster.setIamDatabaseAuthenticationEnabled(iamEnabled);
cluster.setDbClusterArn(regionResolver.buildArn("neptune", region, "cluster:" + id));
cluster.setDbClusterResourceId("cluster-" + UUID.randomUUID().toString()
.replace("-", "").substring(0, 24).toUpperCase());
cluster.setCreatedAt(Instant.now());
cluster.setDbClusterMembers(new ArrayList<>());
cluster.setContainerId(handle.getContainerId());
cluster.setContainerHost(handle.getHost());
cluster.setContainerPort(handle.getPort());
cluster.setProxyPort(proxyPort);
proxyManager.startProxy(id, proxyPort, handle.getHost(), handle.getPort());
proxyManager.startProxy(id, proxyPort, handle.getHost(), handle.getPort());
clusters.put(id, cluster);
LOG.infov("Neptune cluster {0} created ({1}), endpoint={2}:{3}",
id, dbType, endpointHost, String.valueOf(proxyPort));
return cluster;
clusters.put(id, cluster);
provisioned = true;
LOG.infov("Neptune cluster {0} created ({1}), endpoint={2}:{3}",
id, dbType, endpointHost, String.valueOf(proxyPort));
return cluster;
} catch (RuntimeException e) {
LOG.warnv("Neptune cluster {0} provisioning failed, rolling back: {1}", id, e.getMessage());
throw e;
} finally {
// Roll back on ANY non-success exit — including a JVM Error, which a
// catch (RuntimeException) would miss — so a failed create never leaks the
// reserved port or leaves a container behind. Idempotent and a no-op on success.
if (!provisioned) {
rollbackDbCluster(id, handle, proxyPort);
}
}
}
private void rollbackDbCluster(String id, NeptuneContainerHandle handle, int proxyPort) {
try {
try {
// The proxy only starts after the container is ready, so a null handle means it
// never started — nothing to stop.
if (handle != null) {
proxyManager.stopProxy(id);
}
} catch (RuntimeException e) {
LOG.warnv("Error stopping proxy for Neptune cluster {0}: {1}", id, e.getMessage());
}
try {
// Stop by id, not handle: a readiness timeout in containerManager.start() throws
// after the container was created and registered but before the handle is returned,
// so cleaning up by handle here would miss (and orphan) it. stopByClusterId is
// idempotent, so it's safe when the container never started.
containerManager.stopByClusterId(id);
} catch (RuntimeException e) {
LOG.warnv("Error stopping container for Neptune cluster {0}: {1}", id, e.getMessage());
}
} finally {
// Always release the port — even if a cleanup step throws a non-RuntimeException
// (e.g. an Error) — since leaking the port is the exact failure this rollback prevents.
releaseProxyPort(proxyPort);
}
}
public NeptuneCluster getDbCluster(String id) {
@@ -66,7 +66,7 @@ public class NeptuneContainerManager {
LOG.infov("Starting Neptune backend container ({0}) for cluster: {1}", dbType, clusterId);
int backendPort = dbType.backendPort();
String containerName = ContainerStorageHelper.resourceName(config, "neptune", null, clusterId);
String containerName = containerName(clusterId);
lifecycleManager.removeIfExists(containerName);
ContainerBuilder.Builder specBuilder = containerBuilder.newContainer(image)
@@ -128,6 +128,28 @@ public class NeptuneContainerManager {
lifecycleManager.stopAndRemove(handle.getContainerId(), handle.getLogStream());
}
/**
* Stops and removes the backend container for a cluster by id, if one exists.
* Used by the service's provisioning rollback: {@link #start} registers the container in
* {@code activeContainers} <em>before</em> {@link #waitForBackendReady}, so a readiness
* timeout throws without ever returning the handle to the caller. In that case rollback
* can't go through {@link #stop} (it has no handle), so it cleans up by id instead. Falls
* back to the deterministic container name to catch a container that failed before it was
* registered. Idempotent — a no-op when nothing is running for the id.
*/
public void stopByClusterId(String clusterId) {
NeptuneContainerHandle handle = activeContainers.get(clusterId);
if (handle != null) {
stop(handle);
return;
}
lifecycleManager.removeIfExists(containerName(clusterId));
}
private String containerName(String clusterId) {
return ContainerStorageHelper.resourceName(config, "neptune", null, clusterId);
}
public void stopAll() {
List<NeptuneContainerHandle> handles = new ArrayList<>(activeContainers.values());
if (!handles.isEmpty()) {