mirror of
https://github.com/floci-io/floci.git
synced 2026-11-27 07:39:24 -05:00
fix(redshift): reclaim anonymous container volumes (#6382)
Reclaim disposable anonymous volumes while preserving adopted containers during failed recovery. Retain pre-reboot dumps and failed cleanup ownership across partial teardown. Preserve the original database when only proxy shutdown fails. Share startup orchestration while retaining the opt-in cleanup policy. Signed-off-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
5b24703815
commit
a96921afad
13 files changed
+500
-87
No files matched your search
+55
-14
@@ -7,6 +7,7 @@ import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectContainerResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.ListVolumesResponse;
|
||||
import com.github.dockerjava.api.command.RemoveContainerCmd;
|
||||
import com.github.dockerjava.api.exception.ConflictException;
|
||||
import com.github.dockerjava.api.exception.DockerException;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
@@ -127,16 +128,34 @@ public class ContainerLifecycleManager {
|
||||
* @return information about the created container including resolved endpoints and published ports
|
||||
*/
|
||||
public ContainerInfo createAndStart(ContainerSpec spec) {
|
||||
String containerId = create(spec);
|
||||
return createAndStart(spec, false);
|
||||
}
|
||||
|
||||
/** Starts a disposable container, reclaiming its anonymous volumes if startup fails. */
|
||||
public ContainerInfo createAndStartEphemeral(ContainerSpec spec) {
|
||||
return createAndStart(spec, true);
|
||||
}
|
||||
|
||||
private ContainerInfo createAndStart(ContainerSpec spec, boolean removeAnonymousVolumes) {
|
||||
String resolvedImage = imageCacheService.ensureImageExists(spec.image());
|
||||
String containerId = create(spec, resolvedImage, null, removeAnonymousVolumes);
|
||||
try {
|
||||
ContainerInfo info = startCreated(containerId, spec);
|
||||
return withPublishedHostPorts(info, spec);
|
||||
} catch (Exception e) {
|
||||
// A failed start (e.g. host-port conflict) must not leak the created
|
||||
// container: retrying callers would accumulate Created containers and
|
||||
// fixed-name callers would hit name conflicts on the next attempt.
|
||||
removeIfExists(containerId);
|
||||
throw e;
|
||||
return withPublishedHostPorts(startCreated(containerId, spec), spec);
|
||||
} catch (RuntimeException failure) {
|
||||
if (removeAnonymousVolumes) {
|
||||
removeFailedEphemeralContainer(containerId, failure);
|
||||
} else {
|
||||
removeIfExists(containerId);
|
||||
}
|
||||
throw failure;
|
||||
}
|
||||
}
|
||||
|
||||
private void removeFailedEphemeralContainer(String containerId, RuntimeException failure) {
|
||||
try {
|
||||
removeIfExistsStrict(containerId, true);
|
||||
} catch (RuntimeException cleanupFailure) {
|
||||
failure.addSuppressed(cleanupFailure);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,12 +194,20 @@ public class ContainerLifecycleManager {
|
||||
}
|
||||
|
||||
private String create(ContainerSpec spec, String resolvedImage, String platform) {
|
||||
String containerId = createWithCaBundle(spec, resolvedImage, platform);
|
||||
return create(spec, resolvedImage, platform, false);
|
||||
}
|
||||
|
||||
private String create(ContainerSpec spec, String resolvedImage, String platform, boolean removeAnonymousVolumes) {
|
||||
String containerId = createWithCaBundle(spec, resolvedImage, platform, removeAnonymousVolumes);
|
||||
if (spec.hasNetworkConfiguration()) {
|
||||
try {
|
||||
attachNetworkBeforeStart(containerId, spec);
|
||||
} catch (RuntimeException e) {
|
||||
removeIfExists(containerId);
|
||||
if (removeAnonymousVolumes) {
|
||||
removeFailedEphemeralContainer(containerId, e);
|
||||
} else {
|
||||
removeIfExists(containerId);
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"Failed to attach pre-start network configuration for container " + containerId, e);
|
||||
}
|
||||
@@ -188,7 +215,8 @@ public class ContainerLifecycleManager {
|
||||
return containerId;
|
||||
}
|
||||
|
||||
private String createWithCaBundle(ContainerSpec spec, String resolvedImage, String platform) {
|
||||
private String createWithCaBundle(ContainerSpec spec, String resolvedImage, String platform,
|
||||
boolean removeAnonymousVolumes) {
|
||||
LOG.debugv("Creating container from spec: image={0}, name={1}", spec.image(), spec.name());
|
||||
|
||||
// Built once: a dynamic port binding allocates its host port here.
|
||||
@@ -204,7 +232,11 @@ public class ContainerLifecycleManager {
|
||||
}
|
||||
// SSL_CERT_FILE and friends replace the image's trust store, so they must never name a
|
||||
// file that is not there. Start over without them: the container keeps its own trust.
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
if (removeAnonymousVolumes) {
|
||||
removeIfExistsStrict(containerId, true);
|
||||
} else {
|
||||
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
|
||||
}
|
||||
return createContainer(spec, resolvedImage, platform, hostConfig, spec.env());
|
||||
}
|
||||
|
||||
@@ -1046,8 +1078,17 @@ public class ContainerLifecycleManager {
|
||||
* @param name the container name to remove
|
||||
*/
|
||||
public void removeIfExistsStrict(String name) {
|
||||
removeIfExistsStrict(name, false);
|
||||
}
|
||||
|
||||
/** Removes a container, optionally reclaiming anonymous volumes that are no longer in use. */
|
||||
public void removeIfExistsStrict(String name, boolean removeAnonymousVolumes) {
|
||||
try {
|
||||
dockerClient.removeContainerCmd(name).withForce(true).exec();
|
||||
RemoveContainerCmd remove = dockerClient.removeContainerCmd(name).withForce(true);
|
||||
if (removeAnonymousVolumes) {
|
||||
remove.withRemoveVolumes(true);
|
||||
}
|
||||
remove.exec();
|
||||
LOG.infov("Removed stale container {0}", name);
|
||||
} catch (NotFoundException e) {
|
||||
// Not found means the fixed name is available.
|
||||
|
||||
@@ -203,7 +203,7 @@ public class RedshiftService {
|
||||
LOG.warnv(ex, "Failed to stop proxy during recovery rollback for cluster {0}", cluster.getClusterIdentifier());
|
||||
}
|
||||
try {
|
||||
containerManager.stop(entry.accountId(), cluster.getClusterIdentifier());
|
||||
containerManager.rollbackStartup(entry.accountId(), cluster.getClusterIdentifier());
|
||||
} catch (Exception ex) {
|
||||
LOG.warnv(ex, "Failed to stop container during recovery rollback for cluster {0}", cluster.getClusterIdentifier());
|
||||
}
|
||||
@@ -950,8 +950,8 @@ public class RedshiftService {
|
||||
Cluster cluster = clusters.get(clusterIdentifier)
|
||||
.orElseThrow(() -> new AwsException("ClusterNotFound", "Cluster " + clusterIdentifier + " not found", 404));
|
||||
|
||||
// The container backing a cluster has no persistent volume (see RedshiftContainerManager),
|
||||
// so a plain stop+recreate would silently drop the cluster's data. Dump before stopping and
|
||||
// Replacement containers do not reattach the old anonymous volume, so a plain stop+recreate
|
||||
// would silently drop the cluster's data. Dump before stopping and
|
||||
// restore immediately after starting, using a throwaway temp file, so no Snapshot resource is
|
||||
// created or exposed to the caller.
|
||||
Path tempDump;
|
||||
@@ -964,16 +964,18 @@ public class RedshiftService {
|
||||
// Hoisted so a failure after the proxy is (re)started still tears it down and
|
||||
// returns the port, matching createCluster/restoreFromClusterSnapshot rollback.
|
||||
int proxyPort = cluster.getProxyPort() > 0 ? cluster.getProxyPort() : -1;
|
||||
boolean originalTornDown = false; // original proxy + container already stopped
|
||||
boolean teardownStarted = false;
|
||||
boolean containerTeardownStarted = false;
|
||||
boolean rebooted = false;
|
||||
try {
|
||||
String accountId = clusters.accountId();
|
||||
String key = relayKey(accountId, clusterIdentifier);
|
||||
|
||||
containerManager.takeSnapshot(accountId, clusterIdentifier, cluster.getMasterUsername(), tempDump);
|
||||
teardownStarted = true;
|
||||
proxyManager.stopProxy(key);
|
||||
containerTeardownStarted = true;
|
||||
containerManager.stop(accountId, clusterIdentifier);
|
||||
originalTornDown = true;
|
||||
|
||||
String password = cluster.getMasterPassword() != null ? cluster.getMasterPassword() : "admin";
|
||||
RedshiftContainerHandle handle = containerManager.start(
|
||||
@@ -997,15 +999,15 @@ public class RedshiftService {
|
||||
cluster.setClusterStatus("available");
|
||||
rebooted = true;
|
||||
} catch (AwsException e) {
|
||||
rollbackReboot(clusterIdentifier, originalTornDown);
|
||||
if (originalTornDown) {
|
||||
rollbackReboot(clusterIdentifier, containerTeardownStarted);
|
||||
if (teardownStarted) {
|
||||
cluster.setClusterStatus("failed");
|
||||
}
|
||||
clusters.flush();
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
rollbackReboot(clusterIdentifier, originalTornDown);
|
||||
if (originalTornDown) {
|
||||
rollbackReboot(clusterIdentifier, containerTeardownStarted);
|
||||
if (teardownStarted) {
|
||||
cluster.setClusterStatus("failed");
|
||||
}
|
||||
clusters.flush();
|
||||
@@ -1018,9 +1020,9 @@ public class RedshiftService {
|
||||
LOG.warnv(ex, "Failed to clean up temporary dump file {0} after rebooting cluster {1}", tempDump, clusterIdentifier);
|
||||
}
|
||||
} else {
|
||||
if (originalTornDown) {
|
||||
// Once the original container is torn down it holds no volume, so this dump can
|
||||
// be the only surviving copy of the cluster's data, so keep it for manual recovery.
|
||||
if (teardownStarted) {
|
||||
// Teardown may have removed the original container before failing. Keep the
|
||||
// dump for manual recovery even when removal or log closure did not finish.
|
||||
LOG.warnv("Reboot of cluster {0} did not complete; retained pre-reboot data dump at {1}",
|
||||
clusterIdentifier, tempDump);
|
||||
} else {
|
||||
@@ -2115,17 +2117,14 @@ public class RedshiftService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Undo a failed reboot. If {@code originalTornDown} is false the reboot failed before
|
||||
* the original proxy + container were stopped, so the original data-bearing container
|
||||
* is still running and nothing must be touched. Once it is true the original is gone:
|
||||
* tear down the (replacement's) proxy and return its port, and remove any container
|
||||
* running under the cluster's name: {@code containerManager.stop} works by name, so
|
||||
* this also cleans a replacement that {@code containerManager.start} created before
|
||||
* throwing (e.g. its readiness check timed out). The pre-reboot data dump is kept by
|
||||
* the caller.
|
||||
* Undo a failed reboot once container teardown has started. Before that point the
|
||||
* original data-bearing container must be preserved, even if proxy shutdown failed.
|
||||
* Teardown may be partial: stop the proxy and remove the container tracked by the
|
||||
* manager, including a replacement retained after a failed readiness check. The
|
||||
* caller keeps the pre-reboot data dump.
|
||||
*/
|
||||
private void rollbackReboot(String identifier, boolean originalTornDown) {
|
||||
if (!originalTornDown) {
|
||||
private void rollbackReboot(String identifier, boolean containerTeardownStarted) {
|
||||
if (!containerTeardownStarted) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
|
||||
+54
-13
@@ -43,6 +43,7 @@ public class RedshiftContainerManager {
|
||||
private final EmulatorConfig config;
|
||||
private final long retryBackoffMillis;
|
||||
private final Map<String, RedshiftContainerHandle> containers = new ConcurrentHashMap<>();
|
||||
private final Map<String, String> adoptedContainers = new ConcurrentHashMap<>();
|
||||
|
||||
@Inject
|
||||
public RedshiftContainerManager(ContainerBuilder containerBuilder,
|
||||
@@ -76,9 +77,8 @@ public class RedshiftContainerManager {
|
||||
String masterPassword, String databaseName) {
|
||||
String image = config.services().redshift().imageVersion();
|
||||
String containerName = containerName(accountId, clusterIdentifier);
|
||||
// Only the current name: no volume backs this container, so removing a legacy-named survivor
|
||||
// would destroy cluster data that adoptOrStart does not look for.
|
||||
lifecycleManager.removeIfExists(containerName);
|
||||
// Only the current name: adoptOrStart does not look for legacy-named survivors.
|
||||
stop(accountId, clusterIdentifier);
|
||||
|
||||
List<String> envVars = List.of(
|
||||
"POSTGRES_USER=" + masterUsername,
|
||||
@@ -101,7 +101,7 @@ public class RedshiftContainerManager {
|
||||
}
|
||||
|
||||
ContainerSpec spec = specBuilder.build();
|
||||
ContainerInfo info = lifecycleManager.createAndStart(spec);
|
||||
ContainerInfo info = lifecycleManager.createAndStartEphemeral(spec);
|
||||
return initializeAndRegisterHandle(info, accountId, clusterIdentifier, masterUsername, containerName, enginePort,
|
||||
databaseName);
|
||||
}
|
||||
@@ -109,12 +109,12 @@ public class RedshiftContainerManager {
|
||||
/**
|
||||
* Starts a cluster's container the same way {@link #start}, except that a container
|
||||
* already running under this cluster's name (e.g. Floci's own process restarted but
|
||||
* Docker did not) is adopted instead of destroyed and recreated. The container has no
|
||||
* persistent volume, so a blind recreate would silently discard the cluster's data;
|
||||
* Docker did not) is adopted instead of destroyed and recreated. The image's anonymous
|
||||
* volume is not reattached on recreation, so a blind recreate would discard the cluster's data;
|
||||
* adopting preserves it whenever the physical container survived. If no such container
|
||||
* exists (first start, or the container itself was removed), this falls back to
|
||||
* {@link #start}, and in that case the previous data is unrecoverable, matching this
|
||||
* project's decision not to back Redshift containers with a Docker volume.
|
||||
* project's decision not to provision reusable named volumes for Redshift containers.
|
||||
*/
|
||||
public RedshiftContainerHandle adoptOrStart(String accountId, String clusterIdentifier, String masterUsername, String masterPassword) {
|
||||
return adoptOrStart(accountId, clusterIdentifier, masterUsername, masterPassword, DEFAULT_DATABASE);
|
||||
@@ -127,10 +127,11 @@ public class RedshiftContainerManager {
|
||||
Optional<Container> existing = lifecycleManager.findByName(containerName);
|
||||
if (existing.isEmpty()) {
|
||||
LOG.warnv("No surviving container for cluster {0}; starting a fresh empty one: the previous"
|
||||
+ " contents are not recoverable (no Docker volume backs Redshift containers)", clusterIdentifier);
|
||||
+ " contents are not recoverable (no reusable named volume backs Redshift containers)", clusterIdentifier);
|
||||
return start(accountId, clusterIdentifier, masterUsername, masterPassword, databaseName);
|
||||
}
|
||||
|
||||
adoptedContainers.put(containerKey(accountId, clusterIdentifier), existing.get().getId());
|
||||
LOG.infov("Adopting existing container {0} for cluster {1} to avoid discarding its data",
|
||||
containerName, clusterIdentifier);
|
||||
int enginePort = 5432;
|
||||
@@ -164,16 +165,56 @@ public class RedshiftContainerManager {
|
||||
LOG.warnv("Failed to stream logs for {0}", containerName);
|
||||
}
|
||||
|
||||
waitForReady(containerName, info.containerId(), masterUsername, databaseName);
|
||||
bootstrapCatalog(info.containerId(), masterUsername, databaseName);
|
||||
|
||||
try {
|
||||
waitForReady(containerName, info.containerId(), masterUsername, databaseName);
|
||||
bootstrapCatalog(info.containerId(), masterUsername, databaseName);
|
||||
} catch (RuntimeException e) {
|
||||
containers.put(containerKey(accountId, clusterIdentifier), handle);
|
||||
throw e;
|
||||
}
|
||||
containers.put(containerKey(accountId, clusterIdentifier), handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
public void stop(String accountId, String clusterIdentifier) {
|
||||
containers.remove(containerKey(accountId, clusterIdentifier));
|
||||
lifecycleManager.removeIfExists(containerName(accountId, clusterIdentifier));
|
||||
String key = containerKey(accountId, clusterIdentifier);
|
||||
RedshiftContainerHandle handle = containers.get(key);
|
||||
String adoptedId = adoptedContainers.get(key);
|
||||
String containerId = handle == null
|
||||
? adoptedContainers.getOrDefault(key, containerName(accountId, clusterIdentifier)) : handle.getContainerId();
|
||||
lifecycleManager.removeIfExistsStrict(containerId, true);
|
||||
releaseHandle(key, handle);
|
||||
if (containerId.equals(adoptedId)) {
|
||||
adoptedContainers.remove(key, adoptedId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Rolls back startup without destroying a container that survived an earlier process. */
|
||||
public void rollbackStartup(String accountId, String clusterIdentifier) {
|
||||
String key = containerKey(accountId, clusterIdentifier);
|
||||
String adoptedId = adoptedContainers.get(key);
|
||||
if (adoptedId == null) {
|
||||
stop(accountId, clusterIdentifier);
|
||||
return;
|
||||
}
|
||||
RedshiftContainerHandle handle = containers.get(key);
|
||||
if (handle != null && adoptedId.equals(handle.getContainerId())) {
|
||||
releaseHandle(key, handle);
|
||||
}
|
||||
}
|
||||
|
||||
private void releaseHandle(String key, RedshiftContainerHandle handle) {
|
||||
if (handle != null) {
|
||||
Closeable stream = handle.getLogStream();
|
||||
if (stream != null) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Failed to close logs for Redshift container " + handle.getContainerId(), e);
|
||||
}
|
||||
}
|
||||
containers.remove(key, handle);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<RedshiftContainerHandle> getContainer(String accountId, String clusterIdentifier) {
|
||||
|
||||
+3
-3
@@ -63,8 +63,8 @@ public class RedshiftServerlessRuntime {
|
||||
|
||||
/**
|
||||
* Starts (or, when {@code adopt} is set, re-attaches to) the container and fronts it with the
|
||||
* auth proxy on {@code endpoint}. Anything started before a failure is torn down again, so a
|
||||
* failed call leaves neither a container nor a bound port behind.
|
||||
* auth proxy on {@code endpoint}. Failed startup removes newly created containers and closes
|
||||
* the proxy; adopted containers are preserved for another recovery attempt.
|
||||
*/
|
||||
public Backend start(String accountId, String region, String workgroupName, String masterUsername,
|
||||
String masterPassword, String dbName, Endpoint endpoint, boolean adopt,
|
||||
@@ -206,7 +206,7 @@ public class RedshiftServerlessRuntime {
|
||||
LOG.warnv(e, "Could not stop the proxy while rolling back workgroup backend {0}", backendId);
|
||||
}
|
||||
try {
|
||||
containerManager.stop(accountId, backendId);
|
||||
containerManager.rollbackStartup(accountId, backendId);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Could not remove the container while rolling back workgroup backend {0}", backendId);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user