fix(ec2): release a capture when a whole batch of instances is terminated (#4127)

* fix(ec2): release a capture when a whole batch of instances is terminated

TerminateInstances excluded only the instance currently being processed when
deciding whether a deregistered AMI's capture still had a live dependant. Every
other instance of the same request still read as running or shutting-down, so
each reclaim attempt in the batch was blocked, and since nothing revisits the
batch once its asynchronous teardown finishes the committed Docker layer stayed
on disk for the lifetime of the emulator.

Thread the ids of the whole request through terminateInstances ->
reclaimCapturesPinnedBy -> reclaimCapturedImage, so none of them counts as a
live dependant. The reclaim is now attempted on the first instance of the batch,
while the other containers may still exist and the daemon may refuse to delete
the layer; the reference is only cleared on success, so the attempt comes round
again on each remaining instance and the last one succeeds. Both behaviours are
covered by new tests that terminate a batch in a single call, with the container
manager stubbed to leave instances shutting-down as production does.

* fix(ec2): retry the capture reclaim once container teardown has finished

Threading the batch through the dependency check was not enough on its own.
terminate() only schedules the container removal, so every attempt made inside
the TerminateInstances loop can run while a container of that same batch still
exists. Docker then refuses to delete the image, and because the loop is the
only thing that retries, a batch whose containers all tear down slowly left the
captured layer on disk for the lifetime of the emulator.

Give terminate() an optional callback that runs on the teardown executor once
the container is really gone, and have terminateInstances pass one that
attempts the reclaim again. The callback is invoked from a finally block so a
failure earlier in teardown does not skip it, and anything it throws is logged
rather than killing the executor task. The synchronous attempt stays: by the
time the loop reaches later instances the earlier containers are often already
gone, and it costs one refused call when they are not.

The existing stubs move to the two-argument form. The default one runs the
callback, modelling teardown that completes immediately;
terminationLeavesInstancesShuttingDown holds it instead, so a test can decide
when teardown finishes. The new test covers the case this commit fixes: every
in-loop attempt refused, then the layer reclaimed once teardown completes.
aRemovalTheDaemonRefusesKeepsTheReferenceForALaterAttempt now expects the extra
post-teardown attempt, with the counts explained in the test.

* fix(ec2): run the teardown hook only once the container is gone

The hook ran from a finally block, so a teardown that threw before the
container was removed still fired it. A capture reclaim would then be
attempted while Docker still referenced the image, be refused, and have no
later retry behind it, which is the state the hook exists to avoid.

Track whether the container is actually gone: removed, already absent, or
never launched. Everything after removal can fail without making the hook
wrong, so it still runs from the finally block, but a failed removal now skips
it and logs why.

Two tests in Ec2ContainerManagerTest: the hook fires on the ordinary path, and
it does not fire when removeContainerCmd throws. The second fails without the
guard.

* style(test): place the AtomicBoolean import with the other java.util.concurrent.atomic entries

* docs(ec2): drop the duplicated teardown-hook rationale, and fix the skip message

The Javadoc's third paragraph and the comment at the top of the teardown
lambda explained the same rule in almost the same words; the Javadoc is the
one callers read, so the inline comment now just names the variable's role
and points there.

The skip message claimed the container "could not be removed", but
unpublishAll runs first inside the same try: if it throws, containerGone is
still false and the same message is logged with no removal ever attempted.
It now says the container is not established to be gone, which is what the
flag actually means on both paths.

* fix(ec2): run the post-teardown reclaim as the account that owns the instances

The hook runs on the teardown executor, which carries no request context, so
every account-aware store it touched resolved under the default account. For a
batch in any other account capturedImageFor looked the AMI up under
000000000000, found nothing, returned null, and the reclaim returned at its
first guard. That is silent: no exception and no log, because having no capture
is the ordinary case this path returns quickly for. The slow-teardown batch is
the whole reason the hook exists, so the leak stayed open exactly there.

The account is captured in terminateInstances, on the request thread where the
context is still active, and the hook runs under RequestScopes.runAs. That is
what the other background workers do, and its Javadoc names this failure.

Scoping the whole hook rather than threading scanForAccount/putForAccount into
reclaimCapturesPinnedBy is deliberate: capturedImageFor runs FIRST and reads
registeredImages.get(), so a fix confined to the scan and the write-back would
still have returned null before reaching either.

The regression test drains the teardown callbacks on a bare thread, because the
existing batch tests run them on the test thread where the request context is
active, which is why none of them could see this. It fails without the change:
the two synchronous in-loop attempts still happen, since those run on the
request thread, and only the third one, the hook's, goes missing.
This commit is contained in:
Allen Sanborn authored and GitHub committed 2026-09-23 11:02:27 -04:00
1 parent 97aa084209
commit aba5f4e919
4 files changed
+303 -43

No files matched your search

@@ -1283,6 +1283,26 @@ public class Ec2ContainerManager {
* Sets terminatedAt for TTL pruning.
*/
public void terminate(Instance instance) {
terminate(instance, null);
}
/**
* Terminates an instance and runs {@code afterTeardown} once the container is actually gone.
*
* <p>The teardown scheduled here is asynchronous, so anything that depends on the container
* no longer holding a Docker resource cannot run at the call site. Reclaiming a deregistered
* AMI's captured layer is the case that needs this: attempted while the container still
* exists, the daemon refuses to delete the image, and with no later attempt the layer stays
* on disk for the lifetime of the emulator.
*
* <p>The callback runs on the teardown executor, and only once the container is established
* to be gone: removed, already absent, or never launched. Everything after removal can fail
* without making the callback wrong, so it runs from a finally block, but running it when
* removal itself failed would attempt work Docker is bound to refuse with no later retry
* behind it. A skip is logged. Anything the callback throws is logged and swallowed rather
* than killing the executor task.
*/
public void terminate(Instance instance, Runnable afterTeardown) {
String containerId;
String containerIp;
String imdsSourceIp;
@@ -1295,39 +1315,62 @@ public class Ec2ContainerManager {
instance.setState(InstanceState.shuttingDown());
}
executor.submit(() -> {
portForwardManager.unpublishAll(instance);
if (containerId != null) {
try {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
} catch (NotFoundException e) {
// already gone
} catch (Exception e) {
LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage());
// The post-teardown hook's only precondition; see the Javadoc above for why.
boolean containerGone = false;
try {
portForwardManager.unpublishAll(instance);
if (containerId == null) {
// Nothing was ever launched, so there is no container to hold the image.
containerGone = true;
}
try {
// iptables/veth teardown lags behind container removal; prevents port-reuse conflicts.
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
if (containerId != null) {
try {
dockerClient.removeContainerCmd(containerId).withForce(true).exec();
containerGone = true;
} catch (NotFoundException e) {
// already gone
containerGone = true;
} catch (Exception e) {
LOG.warnv("Error removing EC2 container {0}: {1}", containerId, e.getMessage());
}
try {
// iptables/veth teardown lags behind container removal; prevents port-reuse conflicts.
Thread.sleep(500);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
}
}
if (firewallManager != null && firewallManager.enabled()
&& instance.getNetworkInterfaces() != null && !instance.getNetworkInterfaces().isEmpty()) {
firewallManager.unregister(instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId());
}
if (sshHostPort > 0) {
portAllocator.release(sshHostPort);
}
metadataServer.unregisterContainer(containerIp, instance);
metadataServer.unregisterContainer(imdsSourceIp, instance);
metadataServer.unregisterInstance(instance);
// Give the address back only now that the container is gone: releasing it while
// Docker still holds the endpoint would hand the same IP to the next launch and
// have Docker refuse it.
vpcNetworkManager.releasePrivateIp(instance.getRegion(), instance.getSubnetId(),
instance.getPrivateIpAddress());
instance.setState(InstanceState.terminated());
instance.setTerminatedAt(System.currentTimeMillis());
} finally {
if (afterTeardown != null && containerGone) {
try {
afterTeardown.run();
} catch (Exception e) {
LOG.warnv("Post-teardown hook failed for instance {0}: {1}",
instance.getInstanceId(), e.getMessage());
}
} else if (afterTeardown != null) {
LOG.warnv("Skipping post-teardown hook for instance {0}: its container is "
+ "not established to be gone, so anything waiting on the container "
+ "being gone would fail", instance.getInstanceId());
}
}
if (firewallManager != null && firewallManager.enabled()
&& instance.getNetworkInterfaces() != null && !instance.getNetworkInterfaces().isEmpty()) {
firewallManager.unregister(instance.getNetworkInterfaces().getFirst().getNetworkInterfaceId());
}
if (sshHostPort > 0) {
portAllocator.release(sshHostPort);
}
metadataServer.unregisterContainer(containerIp, instance);
metadataServer.unregisterContainer(imdsSourceIp, instance);
metadataServer.unregisterInstance(instance);
// Give the address back only now that the container is gone: releasing it while
// Docker still holds the endpoint would hand the same IP to the next launch and
// have Docker refuse it.
vpcNetworkManager.releasePrivateIp(instance.getRegion(), instance.getSubnetId(),
instance.getPrivateIpAddress());
instance.setState(InstanceState.terminated());
instance.setTerminatedAt(System.currentTimeMillis());
});
}
@@ -33,6 +33,7 @@ import org.jboss.logging.Logger;
import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.core.common.RequestContext;
import io.github.hectorvent.floci.core.common.RequestScopes;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsRegions;
@@ -3123,6 +3124,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
public List<Map<String, String>> terminateInstances(String region, List<String> instanceIds) {
ensureDefaultResources(region);
List<Map<String, String>> result = new ArrayList<>();
// Every instance named here is going away, so none of them counts as a live dependant of
// a capture -- not the ones already processed, which linger as shutting-down while their
// containers are torn down asynchronously, and not the ones still waiting their turn.
Set<String> terminating = new LinkedHashSet<>(instanceIds);
// Captured HERE, on the request thread, because the post-teardown hook below runs on the
// teardown executor where no request context is active and every account-aware store
// would silently fall back to the default account.
String owner = callerAccountId();
for (String id : instanceIds) {
Instance inst = getRequiredInstance(region, id);
@@ -3134,7 +3143,12 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
inst.setState(InstanceState.terminated());
inst.setTerminatedAt(System.currentTimeMillis());
} else {
containerManager.terminate(inst);
// Also attempt the reclaim once this container is really gone. The synchronous
// attempt below runs while teardown is still scheduled, so for a batch whose
// containers all tear down slowly every in-loop attempt can be refused by the
// daemon and, without this, nothing would try again.
containerManager.terminate(inst, () ->
RequestScopes.runAs(owner, () -> reclaimCapturesPinnedBy(region, inst, terminating)));
}
// Delete root volume if deleteOnTermination (matches real AWS behavior)
if (inst.getRootVolumeId() != null) {
@@ -3143,7 +3157,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
releaseStandaloneInterfacesOnTermination(region, inst);
instances.put(key(region, id), inst);
// The last instance depending on a deregistered AMI's capture has just gone away.
reclaimCapturesPinnedBy(region, inst);
// Cheap and usually sufficient: by here the container is often already removed.
reclaimCapturesPinnedBy(region, inst, terminating);
Map<String, String> entry = new LinkedHashMap<>();
entry.put("instanceId", id);
entry.put("previousState", prev.getName());
@@ -5510,13 +5525,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
*
* <p>Callers must hold {@link #imageRegistryLock}.
*
* @param excludedInstanceId an instance not to count as a live dependant, used by the
* terminate path where the store still reads the instance as
* running while its container is being torn down; null to count
* every live instance
* @param excludedInstanceIds the instances not to count as live dependants, used by the
* terminate path where the store still reads every instance of the
* request as running or shutting-down while their containers are
* being torn down; null or empty to count every live instance
* @return true when the reference was released, so the caller knows to store the change
*/
private boolean reclaimCapturedImage(Image image, String excludedInstanceId) {
private boolean reclaimCapturedImage(Image image, Set<String> excludedInstanceIds) {
String captured = image.getDockerImage();
if (captured == null || config.services().ec2().mock()) {
return false;
@@ -5530,7 +5545,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return false;
}
boolean stillLaunchable = instances.scan(i -> true).stream()
.filter(i -> i.getRegion() != null && !i.getInstanceId().equals(excludedInstanceId))
.filter(i -> i.getRegion() != null
&& (excludedInstanceIds == null || !excludedInstanceIds.contains(i.getInstanceId())))
.filter(i -> i.getState() != null && !"terminated".equals(i.getState().getName()))
.anyMatch(i -> captured.equals(capturedImageFor(i.getRegion(), i.getImageId())));
if (stillLaunchable) {
@@ -5554,8 +5570,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
*
* <p>Only tombstoned AMIs are considered: while the AMI is still registered its capture is
* needed for the next launch.
*
* <p>{@code terminating} is the whole batch of the current request, not just this instance.
* A reclaim attempted for the first of them can be refused by the daemon while the other
* containers still exist, and {@link #reclaimCapturedImage} only clears the reference on
* success, so the attempt comes round again on each remaining instance of the batch.
*/
private void reclaimCapturesPinnedBy(String region, Instance terminated) {
private void reclaimCapturesPinnedBy(String region, Instance terminated, Set<String> terminating) {
if (config.services().ec2().mock()) {
return;
}
@@ -5569,7 +5590,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
.filter(img -> DEREGISTERED_STATE.equals(img.getState()))
.findFirst()
.orElse(null);
if (holder != null && reclaimCapturedImage(holder, terminated.getInstanceId())) {
if (holder != null && reclaimCapturedImage(holder, terminating)) {
registeredImages.put(key(holder.getRegion(), holder.getImageId()), holder);
}
}