mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(docker): recover delayed named container creation (#8862)
When a replayed create gets a 409 because Docker reserved the name before the original container shows up in its inventory, poll the inventory with backoff for up to the configured Docker API timeout and adopt the container only when it carries this call's create-attempt and ownership labels. A foreign container, a failed inventory read, an interruption or an expired budget rethrows the original conflict. Co-authored-by: Andre Kurait <AndreKurait@gmail.com>
This commit is contained in:
1 parent
c83940bf78
commit
88a545a36f
2 files changed
+345
-25
No files matched your search
@@ -58,6 +58,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
@@ -97,6 +98,8 @@ public class ContainerLifecycleManager {
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
private final long archiveRetryBackoffMillis;
|
||||
private final LongSupplier nanoTime;
|
||||
private final CreateWait createWait;
|
||||
|
||||
/** Volumes whose shared-ownership root has already been initialised this process (run-once guard). */
|
||||
private final ConcurrentHashMap<String, Boolean> initializedSharedVolumes = new ConcurrentHashMap<>();
|
||||
@@ -121,11 +124,30 @@ public class ContainerLifecycleManager {
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
long archiveRetryBackoffMillis) {
|
||||
this(dockerClient, imageCacheService, containerDetector, config, archiveRetryBackoffMillis,
|
||||
System::nanoTime, TimeUnit.NANOSECONDS::sleep);
|
||||
}
|
||||
|
||||
ContainerLifecycleManager(DockerClient dockerClient,
|
||||
ImageCacheService imageCacheService,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
long archiveRetryBackoffMillis,
|
||||
LongSupplier nanoTime,
|
||||
CreateWait createWait) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.imageCacheService = imageCacheService;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
this.archiveRetryBackoffMillis = archiveRetryBackoffMillis;
|
||||
this.nanoTime = nanoTime;
|
||||
this.createWait = createWait;
|
||||
}
|
||||
|
||||
/** Pause between creation checks; tests advance the monotonic clock instead of sleeping. */
|
||||
@FunctionalInterface
|
||||
interface CreateWait {
|
||||
void sleep(long nanos) throws InterruptedException;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -380,8 +402,13 @@ public class ContainerLifecycleManager {
|
||||
* non-transient and rethrows it immediately, so without this it surfaces as a spurious build
|
||||
* failure, and leaks the container the first attempt actually created, untracked.
|
||||
*
|
||||
* <p>Recovery only fires for a named spec, and only adopts a candidate whose image, labels, and
|
||||
* this exact call's {@link #CREATE_ATTEMPT_LABEL} all match. Image and labels alone cannot tell
|
||||
* <p>Docker can reserve the name before the original create becomes visible to list or inspect.
|
||||
* Successful empty lookups may be retried for one additional configured Docker API timeout,
|
||||
* using monotonic elapsed time. Each lookup retains the transport's own timeout and retries;
|
||||
* this budget bounds polling, not an already running lookup.
|
||||
*
|
||||
* <p>Recovery only fires for a named spec, and only adopts a candidate whose labels and
|
||||
* this exact call's {@link #CREATE_ATTEMPT_LABEL} all match. Image and spec labels alone cannot tell
|
||||
* this call's own lost-response replay apart from a second, genuinely concurrent
|
||||
* {@code create()} racing on the same fixed name/image/labels, which would otherwise be adopted
|
||||
* as if it were this invocation's container.
|
||||
@@ -391,13 +418,52 @@ public class ContainerLifecycleManager {
|
||||
try {
|
||||
return createCmd.exec().getId();
|
||||
} catch (ConflictException e) {
|
||||
if (spec.name() != null) {
|
||||
Optional<Container> existing = findByName(spec.name());
|
||||
if (existing.isPresent() && matchesSpec(existing.get(), spec, createAttemptId)) {
|
||||
LOG.infov("Create for {0} hit a name conflict; an earlier attempt''s response "
|
||||
+ "was lost but the container exists, adopting {1}",
|
||||
spec.name(), existing.get().getId());
|
||||
return existing.get().getId();
|
||||
if (spec.name() == null) {
|
||||
throw e;
|
||||
}
|
||||
long started = nanoTime.getAsLong();
|
||||
long budget = TimeUnit.SECONDS.toNanos(config.docker().apiTimeoutSeconds());
|
||||
int attempt = 0;
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
if (attempt > 0 && nanoTime.getAsLong() - started >= budget) {
|
||||
break;
|
||||
}
|
||||
Optional<Container> existing;
|
||||
try {
|
||||
existing = findByNameStrict(spec.name());
|
||||
} catch (RuntimeException lookupFailure) {
|
||||
// An unreadable inventory is not evidence that creation is still pending.
|
||||
e.addSuppressed(lookupFailure);
|
||||
throw e;
|
||||
}
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
break;
|
||||
}
|
||||
if (existing.isPresent()) {
|
||||
if (matchesSpec(existing.get(), spec, createAttemptId)) {
|
||||
LOG.infov("Create for {0} hit a name conflict; an earlier attempt''s response "
|
||||
+ "was lost but the container exists, adopting {1}",
|
||||
spec.name(), existing.get().getId());
|
||||
return existing.get().getId();
|
||||
}
|
||||
break;
|
||||
}
|
||||
long remaining = budget - (nanoTime.getAsLong() - started);
|
||||
if (remaining <= 0) {
|
||||
break;
|
||||
}
|
||||
if (attempt == 0) {
|
||||
LOG.infov("Reconciling reserved name {0} while its container creation finishes", spec.name());
|
||||
}
|
||||
attempt++;
|
||||
long delay = TimeUnit.MILLISECONDS.toNanos(DockerRetry.backoffDelay(
|
||||
attempt, RetryingDockerHttpClient.BACKOFF_MS, DockerRetry.BACKOFF_CAP_MS));
|
||||
try {
|
||||
createWait.sleep(Math.min(remaining, delay));
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
e.addSuppressed(interrupted);
|
||||
break;
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
@@ -1170,28 +1236,32 @@ public class ContainerLifecycleManager {
|
||||
*/
|
||||
public Optional<Container> findByName(String name) {
|
||||
try {
|
||||
List<Container> containers = dockerClient.listContainersCmd()
|
||||
.withShowAll(true)
|
||||
.exec();
|
||||
|
||||
for (Container c : containers) {
|
||||
String[] names = c.getNames();
|
||||
if (names == null) {
|
||||
continue;
|
||||
}
|
||||
for (String n : names) {
|
||||
// Docker prefixes names with /
|
||||
if (n.equals("/" + name) || n.equals(name)) {
|
||||
return Optional.of(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return findByNameStrict(name);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Error searching for container {0}: {1}", name, e.getMessage());
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<Container> findByNameStrict(String name) {
|
||||
List<Container> containers = dockerClient.listContainersCmd()
|
||||
.withShowAll(true)
|
||||
.exec();
|
||||
for (Container c : containers) {
|
||||
String[] names = c.getNames();
|
||||
if (names == null) {
|
||||
continue;
|
||||
}
|
||||
for (String n : names) {
|
||||
// Docker prefixes names with /
|
||||
if (n.equals("/" + name) || n.equals(name)) {
|
||||
return Optional.of(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the environment a container was created with. The {@link Container} summaries
|
||||
* returned by {@link #findByName} carry no environment, so callers that must compare an
|
||||
|
||||
+250
@@ -10,6 +10,8 @@ import io.floci.aws.services.lambda.launcher.ImageCacheService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
@@ -18,12 +20,21 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.atLeast;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
@@ -96,6 +107,36 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
|
||||
assertEquals("winning-container-id", containerId);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAdoptsOwnContainerWhenReservedNameBecomesVisibleAfterConflict() {
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> labelsCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
when(createCmd.withLabels(labelsCaptor.capture())).thenReturn(createCmd);
|
||||
when(createCmd.exec()).thenThrow(new ConflictException("named container already exists"));
|
||||
lenient().when(dockerConfig.apiTimeoutSeconds()).thenReturn(300);
|
||||
|
||||
Container existing = mock(Container.class);
|
||||
lenient().when(existing.getId()).thenReturn("slowly-created-container");
|
||||
lenient().when(existing.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
lenient().when(existing.getLabels()).thenAnswer(inv -> labelsCaptor.getValue());
|
||||
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
// Docker reserves the name before publishing the container to list/inspect. The
|
||||
// replay can conflict while the original create is still finishing its filesystem.
|
||||
when(listCmd.exec()).thenReturn(List.of(), List.of(existing));
|
||||
|
||||
ContainerSpec spec = new ContainerSpec(
|
||||
"busybox:stable", "emulator-fixed-name", List.of(), null, null, null, Map.of(),
|
||||
List.of(), null, List.of(), List.of(), List.of(), Map.of(), null, false, null,
|
||||
List.of(), null, null, List.of());
|
||||
|
||||
AtomicLong now = new AtomicLong();
|
||||
assertEquals("slowly-created-container", manager(now, now::addAndGet).create(spec));
|
||||
}
|
||||
|
||||
/**
|
||||
* Image and label matching alone cannot tell "my own create's lost response" apart from a
|
||||
* second, genuinely concurrent {@code create()} call racing on the same fixed name, image,
|
||||
@@ -216,6 +257,215 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
|
||||
assertThrows(ConflictException.class, () -> manager().create(spec));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAdoptsOriginalAttemptAfterMinutesOfDelayedVisibility() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong(TimeUnit.HOURS.toNanos(2));
|
||||
long started = now.get();
|
||||
when(scenario.listCmd().exec()).thenAnswer(inv ->
|
||||
now.get() - started < TimeUnit.SECONDS.toNanos(140) ? List.of() : List.of(scenario.owned()));
|
||||
|
||||
String id = manager(now, now::addAndGet).create(scenario.spec());
|
||||
|
||||
assertEquals("original-container-id", id);
|
||||
assertTrue(now.get() - started >= TimeUnit.SECONDS.toNanos(140));
|
||||
assertTrue(now.get() - started < TimeUnit.SECONDS.toNanos(300));
|
||||
verify(scenario.listCmd(), atLeast(2)).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPreservesOriginalConflictWhenVisibilityBudgetExpires() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
when(scenario.listCmd().exec()).thenReturn(List.of());
|
||||
|
||||
ConflictException failure = assertThrows(ConflictException.class,
|
||||
() -> manager(now, now::addAndGet).create(scenario.spec()));
|
||||
|
||||
assertSame(scenario.conflict(), failure);
|
||||
assertEquals(TimeUnit.SECONDS.toNanos(300), now.get());
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(longs = {300, 301})
|
||||
void createDoesNotPollAgainWhenWaitReachesOrExceedsDeadline(long elapsedSeconds) {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
when(scenario.listCmd().exec()).thenReturn(List.of(), List.of(scenario.owned()));
|
||||
|
||||
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
|
||||
() -> manager(now, nanos -> now.set(TimeUnit.SECONDS.toNanos(elapsedSeconds)))
|
||||
.create(scenario.spec())));
|
||||
|
||||
verify(scenario.listCmd()).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createChargesLookupTimeToVisibilityBudget() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
when(scenario.listCmd().exec()).thenAnswer(inv -> {
|
||||
now.addAndGet(TimeUnit.SECONDS.toNanos(301));
|
||||
return List.of();
|
||||
});
|
||||
AtomicLong sleeps = new AtomicLong();
|
||||
|
||||
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
|
||||
() -> manager(now, nanos -> sleeps.incrementAndGet()).create(scenario.spec())));
|
||||
|
||||
assertEquals(0, sleeps.get());
|
||||
verify(scenario.listCmd()).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(booleans = {false, true})
|
||||
void createRejectsForeignContainerThatAppearsWhileWaiting(boolean missingAttemptLabel) {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
Container foreign = mock(Container.class);
|
||||
when(foreign.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
when(foreign.getLabels()).thenAnswer(inv -> {
|
||||
Map<String, String> labels = new HashMap<>(scenario.owned().getLabels());
|
||||
if (missingAttemptLabel) {
|
||||
labels.remove(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL);
|
||||
} else {
|
||||
labels.put(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL, "different-create-attempt");
|
||||
}
|
||||
return labels;
|
||||
});
|
||||
when(scenario.listCmd().exec()).thenReturn(List.of(), List.of(foreign), List.of(scenario.owned()));
|
||||
|
||||
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
|
||||
() -> manager(now, now::addAndGet).create(scenario.spec())));
|
||||
|
||||
verify(scenario.listCmd(), times(2)).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPreservesLookupFailureInsteadOfTreatingItAsPendingCreation() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
IllegalStateException lookupFailure = new IllegalStateException("Docker inventory unavailable");
|
||||
when(scenario.listCmd().exec()).thenThrow(lookupFailure);
|
||||
|
||||
ConflictException failure = assertThrows(ConflictException.class,
|
||||
() -> manager(now, now::addAndGet).create(scenario.spec()));
|
||||
|
||||
assertSame(scenario.conflict(), failure);
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
assertSame(lookupFailure, failure.getSuppressed()[0]);
|
||||
assertEquals(0, now.get());
|
||||
verify(scenario.listCmd()).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPreservesInterruptedSleepAndOriginalConflict() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
InterruptedException interruption = new InterruptedException("caller cancelled");
|
||||
when(scenario.listCmd().exec()).thenReturn(List.of());
|
||||
|
||||
try {
|
||||
ConflictException failure = assertThrows(ConflictException.class,
|
||||
() -> manager(now, nanos -> {
|
||||
throw interruption;
|
||||
}).create(scenario.spec()));
|
||||
|
||||
assertSame(scenario.conflict(), failure);
|
||||
assertTrue(Thread.currentThread().isInterrupted());
|
||||
assertEquals(1, failure.getSuppressed().length);
|
||||
assertSame(interruption, failure.getSuppressed()[0]);
|
||||
verify(scenario.listCmd()).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
} finally {
|
||||
Thread.interrupted();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDoesNotPollWhenConflictRecoveryIsAlreadyInterrupted() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
|
||||
try {
|
||||
Thread.currentThread().interrupt();
|
||||
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
|
||||
() -> manager(now, now::addAndGet).create(scenario.spec())));
|
||||
|
||||
assertTrue(Thread.currentThread().isInterrupted());
|
||||
verify(scenario.listCmd(), never()).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
} finally {
|
||||
Thread.interrupted();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createDoesNotAdoptWhenInterruptedDuringLookup() {
|
||||
ConflictScenario scenario = conflictScenario();
|
||||
AtomicLong now = new AtomicLong();
|
||||
when(scenario.listCmd().exec()).thenAnswer(inv -> {
|
||||
Thread.currentThread().interrupt();
|
||||
return List.of(scenario.owned());
|
||||
});
|
||||
|
||||
try {
|
||||
assertSame(scenario.conflict(), assertThrows(ConflictException.class,
|
||||
() -> manager(now, now::addAndGet).create(scenario.spec())));
|
||||
|
||||
assertTrue(Thread.currentThread().isInterrupted());
|
||||
verify(scenario.listCmd()).exec();
|
||||
verifyOnlyOriginalCreate(scenario);
|
||||
} finally {
|
||||
Thread.interrupted();
|
||||
}
|
||||
}
|
||||
|
||||
private ConflictScenario conflictScenario() {
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
|
||||
@SuppressWarnings("unchecked")
|
||||
ArgumentCaptor<Map<String, String>> labelsCaptor = ArgumentCaptor.forClass(Map.class);
|
||||
when(createCmd.withLabels(labelsCaptor.capture())).thenReturn(createCmd);
|
||||
ConflictException conflict = new ConflictException("named container already exists");
|
||||
when(createCmd.exec()).thenThrow(conflict);
|
||||
when(dockerConfig.apiTimeoutSeconds()).thenReturn(300);
|
||||
|
||||
Container owned = mock(Container.class);
|
||||
lenient().when(owned.getId()).thenReturn("original-container-id");
|
||||
lenient().when(owned.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
lenient().when(owned.getLabels()).thenAnswer(inv -> labelsCaptor.getValue());
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
lenient().when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
ContainerSpec spec = new ContainerSpec(
|
||||
"busybox:stable", "emulator-fixed-name", List.of(), null, null, null, Map.of(),
|
||||
List.of(), null, List.of(), List.of(), List.of(), Map.of("resource_owner", "caller-a"),
|
||||
null, false, null, List.of(), null, null, List.of());
|
||||
return new ConflictScenario(createCmd, listCmd, owned, spec, conflict);
|
||||
}
|
||||
|
||||
private void verifyOnlyOriginalCreate(ConflictScenario scenario) {
|
||||
verify(dockerClient).createContainerCmd("busybox:stable");
|
||||
verify(scenario.createCmd()).exec();
|
||||
verify(dockerClient, never()).startContainerCmd(anyString());
|
||||
verify(dockerClient, never()).removeContainerCmd(anyString());
|
||||
}
|
||||
|
||||
private ContainerLifecycleManager manager(AtomicLong now, ContainerLifecycleManager.CreateWait wait) {
|
||||
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config,
|
||||
0, now::get, wait);
|
||||
}
|
||||
|
||||
private record ConflictScenario(CreateContainerCmd createCmd, ListContainersCmd listCmd, Container owned,
|
||||
ContainerSpec spec, ConflictException conflict) {
|
||||
}
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
|
||||
Reference in new issue
Block a user