fix(docker): confirm concurrent container removal (#7412)

This commit is contained in:
Andre Kurait authored and GitHub committed 2026-11-03 11:18:49 -04:00
1 parent 6386e8fd07
commit 58cd1ec758
2 files changed
+180 -7

No files matched your search

@@ -23,6 +23,7 @@ import com.github.dockerjava.api.model.Mount;
import com.github.dockerjava.api.model.MountType;
import com.github.dockerjava.api.model.Ports;
import com.github.dockerjava.api.model.Volume;
import com.github.dockerjava.api.model.WaitContainerCondition;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.config.ContainerCaBundle;
import io.github.hectorvent.floci.config.EmulatorConfig;
@@ -653,6 +654,8 @@ public class ContainerLifecycleManager {
* {@link #stopAndRemove(String, Closeable)}. Resource-deletion paths that must retain their
* persisted record for a retry use this stricter variant instead. The log stream is closed
* only once the container is gone; when removal fails it is left open for the retry.
* A concurrent Docker removal is given up to five seconds to finish, followed by an
* independent absence check before cleanup succeeds.
*/
public void stopAndRemoveStrict(String containerId, Closeable logStream) {
stopAndRemoveStrict(containerId, logStream, 5);
@@ -698,20 +701,42 @@ public class ContainerLifecycleManager {
} catch (NotFoundException e) {
// Already gone, so cleanup succeeded.
} catch (Exception e) {
IllegalStateException cleanupFailure = new IllegalStateException(
"Failed to remove container " + containerId, e);
if (stopFailure != null) {
cleanupFailure.addSuppressed(stopFailure);
boolean absent = presenceOf(containerId) == ContainerPresence.ABSENT;
if (!absent && e instanceof ConflictException) {
absent = awaitConcurrentRemoval(containerId);
}
// The container still exists and may still be logging, so the stream stays open for
// the caller's retry.
throw cleanupFailure;
if (!absent) {
IllegalStateException cleanupFailure = new IllegalStateException(
"Failed to remove container " + containerId, e);
if (stopFailure != null) {
cleanupFailure.addSuppressed(stopFailure);
}
// Retain the stream and original failure for the caller's retry.
throw cleanupFailure;
}
LOG.debugv("Container {0} is absent after its removal response failed", containerId);
}
// Closed only once the container is stopped and gone, as in stopAndRemove, so the follower
// can drain the final tail.
closeLogStreamIfPresent(logStream);
}
private boolean awaitConcurrentRemoval(String containerId) {
try (WaitContainerResultCallback callback = new WaitContainerResultCallback()) {
dockerClient.waitContainerCmd(containerId).withCondition(WaitContainerCondition.REMOVED).exec(callback);
callback.awaitCompletion(5, TimeUnit.SECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
LOG.debugv("Interrupted waiting for container {0} removal", containerId);
return false;
} catch (Exception e) {
// Removal can finish before the wait registers, or the wait transport can fail.
// In either case, inspect must confirm absence before cleanup succeeds.
LOG.debugv("Could not await container {0} removal: {1}", containerId, e.getMessage());
}
return presenceOf(containerId) == ContainerPresence.ABSENT;
}
private void withTeardownSlot(Runnable stopAndRemove) {
teardownSlots.acquireUninterruptibly();
try {
@@ -0,0 +1,148 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.InspectContainerCmd;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.RemoveContainerCmd;
import com.github.dockerjava.api.command.StopContainerCmd;
import com.github.dockerjava.api.command.WaitContainerCmd;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.WaitContainerCondition;
import com.github.dockerjava.core.command.WaitContainerResultCallback;
import io.github.hectorvent.floci.config.EmulatorConfig;
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
import io.github.hectorvent.floci.testing.ThreadStates;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.io.Closeable;
import java.time.Duration;
import java.util.EnumSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class ContainerConcurrentRemovalTest {
private final DockerClient docker = mock(DockerClient.class);
private final InspectContainerCmd inspect = mock(InspectContainerCmd.class);
private final WaitContainerCmd wait = mock(WaitContainerCmd.class, RETURNS_SELF);
private final Closeable logs = mock(Closeable.class);
private final Closeable waitStream = mock(Closeable.class);
private final ConflictException conflict = new ConflictException("removal already in progress");
private final ContainerLifecycleManager manager = new ContainerLifecycleManager(
docker, mock(ImageCacheService.class), mock(ContainerDetector.class), mock(EmulatorConfig.class));
private void removalConflict(boolean running) {
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
RemoveContainerCmd remove = mock(RemoveContainerCmd.class, RETURNS_SELF);
InspectContainerResponse response = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
when(docker.stopContainerCmd("runtime")).thenReturn(stop);
when(docker.removeContainerCmd("runtime")).thenReturn(remove);
doThrow(conflict).when(remove).exec();
when(docker.inspectContainerCmd("runtime")).thenReturn(inspect);
when(inspect.exec()).thenReturn(response);
when(response.getState().getRunning()).thenReturn(running);
when(docker.waitContainerCmd("runtime")).thenReturn(wait);
}
@ParameterizedTest
@ValueSource(strings = {"already-absent", "completed", "registration-missed", "transport-failed"})
void confirmedAbsenceClosesLogsAfterConcurrentRemoval(String outcome) throws Exception {
removalConflict(false);
if ("already-absent".equals(outcome)) {
when(inspect.exec()).thenThrow(new NotFoundException("removed"));
} else {
when(wait.exec(any(WaitContainerResultCallback.class))).thenAnswer(call -> {
verify(logs, never()).close();
when(inspect.exec()).thenThrow(new NotFoundException("removed"));
if ("registration-missed".equals(outcome)) {
throw new NotFoundException("removed before wait registered");
}
WaitContainerResultCallback callback = call.getArgument(0);
callback.onStart(waitStream);
if ("transport-failed".equals(outcome)) {
callback.onError(new DockerException("wait response lost", 500));
} else {
callback.onComplete();
}
return callback;
});
}
manager.stopAndRemoveStrict("runtime", logs);
verify(logs).close();
if ("already-absent".equals(outcome)) {
verify(docker, never()).waitContainerCmd(anyString());
} else {
verify(wait).withCondition(WaitContainerCondition.REMOVED);
verify(inspect, times(2)).exec();
if (!"registration-missed".equals(outcome)) {
verify(waitStream, atLeastOnce()).close();
}
}
}
@ParameterizedTest
@ValueSource(strings = {"running", "stopped", "unknown", "timeout", "interrupted"})
void unconfirmedRemovalRetainsLogsAndTheOriginalFailure(String outcome) throws Exception {
removalConflict("running".equals(outcome));
if ("unknown".equals(outcome)) {
when(inspect.exec()).thenThrow(new DockerException("inspection unavailable", 500));
}
AtomicReference<WaitContainerResultCallback> pending = new AtomicReference<>();
CountDownLatch registered = new CountDownLatch(1);
when(wait.exec(any(WaitContainerResultCallback.class))).thenAnswer(call -> {
WaitContainerResultCallback callback = call.getArgument(0);
callback.onStart(waitStream);
pending.set(callback);
registered.countDown();
if ("interrupted".equals(outcome)) {
Thread.currentThread().interrupt();
} else if (!"timeout".equals(outcome)) {
callback.onComplete();
}
return callback;
});
try {
IllegalStateException failure = "timeout".equals(outcome)
? completeTimedWait(pending, registered)
: assertThrows(IllegalStateException.class, () -> manager.stopAndRemoveStrict("runtime", logs));
assertSame(conflict, failure.getCause());
assertEquals("interrupted".equals(outcome), Thread.currentThread().isInterrupted());
verify(logs, never()).close();
verify(waitStream, atLeastOnce()).close();
} finally {
Thread.interrupted();
}
}
private IllegalStateException completeTimedWait(AtomicReference<WaitContainerResultCallback> pending,
CountDownLatch registered) throws Exception {
FutureTask<IllegalStateException> task = new FutureTask<>(() ->
assertThrows(IllegalStateException.class, () -> manager.stopAndRemoveStrict("runtime", logs)));
Thread teardown = Thread.ofPlatform().start(task);
try {
assertTrue(registered.await(5, TimeUnit.SECONDS), "removal callback registered");
ThreadStates.awaitState(teardown, EnumSet.of(Thread.State.TIMED_WAITING),
Duration.ofSeconds(5), "bounded removal wait");
pending.get().onComplete();
return task.get(5, TimeUnit.SECONDS);
} finally {
WaitContainerResultCallback callback = pending.get();
if (callback != null) {
callback.onComplete();
}
teardown.interrupt();
teardown.join(Duration.ofSeconds(5));
assertFalse(teardown.isAlive(), "teardown worker stopped");
}
}
}