mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(docker): retry transient daemon I/O at the transport seam and split streaming pools (#4614)
Under fan-out load the single Docker socket drops connections mid-call (Broken pipe, Connection reset) and the operation fails. Split out of #2707. - Retry transient I/O at the transport: RetryingDockerHttpClient retries replay-safe control-plane calls with capped backoff (policy in DockerRetry). Interrupted I/O is not retried, except SocketTimeoutException, and the interrupt flag is kept. - Split log-follow streams onto their own @StreamingDocker client and pool (floci.docker.streaming-max-connections, default 512) so they cannot starve create/start/stop calls. Exec and wait streams stay on the main pool for now. - Adopt the container a replayed named create already made (409 matched by a per-attempt label) instead of failing and leaking it. Unnamed container creates, network creates, restart and network connect/disconnect are never replayed. - Retry tar copies at the call site with RetryingTarCopier (Lambda launcher, EC2 authorized_keys, EKS webhook kubeconfig and registries.yaml, MWAA); a local tar-writer failure is reported at once. - Send Connection: close on control-plane requests, since the Apache transport reuses pooled sockets the daemon has already closed (Podman). Hijacked requests and the streaming pool are unchanged.
This commit is contained in:
1 parent
dfe2117fed
commit
1531537559
26 files changed
+2279
-161
No files matched your search
@@ -132,4 +132,24 @@ class ApplicationDefaultsTest {
|
||||
assertEquals(String.valueOf(maxConnections), fallback.value(),
|
||||
"the @WithDefault must match application.yml, which wins over it");
|
||||
}
|
||||
|
||||
// Catches: streaming-max-connections declared and documented but absent from the shipped
|
||||
// application.yml, or a yml value that silently disagrees with the @WithDefault fallback.
|
||||
@Test
|
||||
void productionConfigDeclaresTheStreamingDockerPoolAtItsDefault() throws IOException, NoSuchMethodException {
|
||||
JsonNode streamingMaxConnections = new YAMLMapper()
|
||||
.readTree(Path.of("src/main/resources/application.yml").toFile())
|
||||
.path("floci").path("docker").path("streaming-max-connections");
|
||||
|
||||
assertFalse(streamingMaxConnections.isMissingNode(),
|
||||
"streaming-max-connections should be declared in application.yml");
|
||||
assertEquals(512, streamingMaxConnections.asInt());
|
||||
|
||||
WithDefault fallback = EmulatorConfig.DockerConfig.class
|
||||
.getMethod("streamingMaxConnections")
|
||||
.getAnnotation(WithDefault.class);
|
||||
assertNotNull(fallback, "streamingMaxConnections should declare a fallback default");
|
||||
assertEquals("512", fallback.value(),
|
||||
"the @WithDefault must match application.yml, which wins over it");
|
||||
}
|
||||
}
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateContainerCmd;
|
||||
import com.github.dockerjava.api.command.ListContainersCmd;
|
||||
import com.github.dockerjava.api.exception.ConflictException;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.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.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A create retry can hit the daemon twice for the same logical create: the first attempt's
|
||||
* response is lost to a transient socket error ({@link DockerRetry}), but the daemon already
|
||||
* created the named container, so the retry's {@code createCmd.exec()} fails with a 409 name
|
||||
* conflict instead of a transient I/O error. Without recovery this surfaces as a create
|
||||
* failure while a live, untracked container sits on the daemon.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class ContainerLifecycleManagerCreateConflictRecoveryTest {
|
||||
|
||||
@Mock
|
||||
DockerClient dockerClient;
|
||||
|
||||
@Mock
|
||||
ImageCacheService imageCacheService;
|
||||
|
||||
@Mock
|
||||
ContainerDetector containerDetector;
|
||||
|
||||
@Mock
|
||||
PortAllocator portAllocator;
|
||||
|
||||
@Mock
|
||||
EmulatorConfig config;
|
||||
|
||||
@Mock
|
||||
EmulatorConfig.DockerConfig dockerConfig;
|
||||
|
||||
@Mock
|
||||
EmulatorConfig.TlsConfig tlsConfig;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lenient().when(config.docker()).thenReturn(dockerConfig);
|
||||
lenient().when(config.tls()).thenReturn(tlsConfig);
|
||||
// create() now resolves the image through the cache before building the create command.
|
||||
lenient().when(imageCacheService.ensureImageExists("busybox:stable")).thenReturn("busybox:stable");
|
||||
lenient().when(dockerConfig.resourceNamespace()).thenReturn(Optional.empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void createAdoptsContainerThatWonTheRaceOnRetryConflict() {
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
|
||||
// The container that actually got created on the daemon carries exactly the labels this
|
||||
// create() call applied (including the per-call attempt-id), captured here rather than
|
||||
// hardcoded, since createWithConflictRecovery only adopts a container proven to be THIS
|
||||
// call's own lost-response attempt, not merely one with matching image/spec labels.
|
||||
@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"));
|
||||
|
||||
Container existing = mock(Container.class);
|
||||
when(existing.getId()).thenReturn("winning-container-id");
|
||||
when(existing.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
when(existing.getLabels()).thenAnswer(inv -> labelsCaptor.getValue());
|
||||
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
when(listCmd.exec()).thenReturn(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());
|
||||
|
||||
String containerId = manager().create(spec);
|
||||
|
||||
assertEquals("winning-container-id", containerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
* and spec labels (e.g. a duplicate CreateBroker request retried by an AWS SDK client while
|
||||
* the original is still in flight), both produce a container satisfying {@code matchesSpec}.
|
||||
* Adopting the other call's container means starting, modifying, or removing a container this
|
||||
* invocation doesn't own. Each {@code create()} call tags its own createCmd with a fresh
|
||||
* per-call attempt id; a name-conflicting container missing (or mismatching) this exact id
|
||||
* belongs to a different call and must not be adopted.
|
||||
*/
|
||||
@Test
|
||||
void createRethrowsConflictWhenExistingContainerIsFromADifferentConcurrentCreateCall() {
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
|
||||
when(createCmd.exec()).thenThrow(new ConflictException("named container already exists"));
|
||||
|
||||
Container existing = mock(Container.class);
|
||||
when(existing.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
// Same image and default/spec labels as this call would apply, but a different
|
||||
// create() invocation's attempt id, simulating a genuinely concurrent racing caller,
|
||||
// not this call's own lost-response retry.
|
||||
Map<String, String> foreignLabels = new HashMap<>(
|
||||
Map.of("floci", "true", "floci_emulator", "floci-aws"));
|
||||
foreignLabels.put(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL, "some-other-callers-attempt-id");
|
||||
when(existing.getLabels()).thenReturn(foreignLabels);
|
||||
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
when(listCmd.exec()).thenReturn(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());
|
||||
|
||||
assertThrows(ConflictException.class, () -> manager().create(spec));
|
||||
}
|
||||
|
||||
/**
|
||||
* The list API reports {@code Container.getImage()} as an image ID/digest rather than the tag
|
||||
* whenever the tag has been re-pulled, retagged, or removed since the container was created,
|
||||
* routine on a long-lived host. Comparing it against the spec's tag would then reject the
|
||||
* container THIS call just created, rethrow the conflict, and leak that container untracked:
|
||||
* exactly the failure conflict recovery exists to prevent, and only under the daemon churn that
|
||||
* makes a lost create response likely in the first place. The per-call attempt id is already
|
||||
* proof of ownership no other call can reproduce, so adoption must not hinge on the image
|
||||
* string.
|
||||
*/
|
||||
@Test
|
||||
void createAdoptsOwnContainerWhenListApiReportsImageAsADigest() {
|
||||
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"));
|
||||
|
||||
Container existing = mock(Container.class);
|
||||
when(existing.getId()).thenReturn("winning-container-id");
|
||||
when(existing.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
// lenient: matchesSpec must NOT read the image at all. Stubbing it anyway is the regression
|
||||
// guard, reintroduce a tag comparison and this digest makes the adoption fail.
|
||||
lenient().when(existing.getImage()).thenReturn(
|
||||
"sha256:1f2e3d4c5b6a798877665544332211009988776655443322110099887766554433");
|
||||
when(existing.getLabels()).thenAnswer(inv -> labelsCaptor.getValue());
|
||||
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
when(listCmd.exec()).thenReturn(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());
|
||||
|
||||
assertEquals("winning-container-id", manager().create(spec));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRethrowsConflictWhenExistingContainerLabelsDoNotMatch() {
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
|
||||
when(createCmd.exec()).thenThrow(new ConflictException("named container already exists"));
|
||||
|
||||
Container existing = mock(Container.class);
|
||||
when(existing.getNames()).thenReturn(new String[] {"/emulator-fixed-name"});
|
||||
when(existing.getLabels()).thenReturn(
|
||||
Map.of("floci", "true", "floci_emulator", "floci-lambda"));
|
||||
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
when(listCmd.exec()).thenReturn(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());
|
||||
|
||||
assertThrows(ConflictException.class, () -> manager().create(spec));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRethrowsConflictWhenNoNamedContainerExists() {
|
||||
CreateContainerCmd createCmd = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createContainerCmd("busybox:stable")).thenReturn(createCmd);
|
||||
when(createCmd.exec()).thenThrow(new ConflictException("named container already exists"));
|
||||
|
||||
ListContainersCmd listCmd = mock(ListContainersCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.listContainersCmd()).thenReturn(listCmd);
|
||||
when(listCmd.exec()).thenReturn(List.of());
|
||||
|
||||
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());
|
||||
|
||||
assertThrows(ConflictException.class, () -> manager().create(spec));
|
||||
}
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, portAllocator, config);
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -22,6 +22,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
@@ -314,10 +315,17 @@ class ContainerLifecycleManagerLabelsTest {
|
||||
return createCmd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips the per-call {@code ContainerLifecycleManager.CREATE_ATTEMPT_LABEL}, a random id
|
||||
* generated fresh on every {@code create()} call for conflict-recovery adoption safety,
|
||||
* orthogonal to the default-label behavior this test file covers.
|
||||
*/
|
||||
private Map<String, String> capturedLabels(CreateContainerCmd createCmd) {
|
||||
ArgumentCaptor<Map<String, String>> labels = labelsCaptor();
|
||||
verify(createCmd).withLabels(labels.capture());
|
||||
return labels.getValue();
|
||||
Map<String, String> captured = new HashMap<>(labels.getValue());
|
||||
captured.remove(ContainerLifecycleManager.CREATE_ATTEMPT_LABEL);
|
||||
return captured;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
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.StartContainerCmd;
|
||||
import com.github.dockerjava.api.exception.NotModifiedException;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.lambda.launcher.ImageCacheService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.IntConsumer;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
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.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Start semantics that must hold with retries living at the transport seam
|
||||
* ({@link RetryingDockerHttpClient}), not at this call site.
|
||||
*
|
||||
* <p>The load-bearing piece the transport cannot provide: when the daemon honoured a start whose
|
||||
* response was lost to a broken pipe, the transport's replay meets HTTP 304, a perfectly
|
||||
* successful response at transport level, which docker-java converts to
|
||||
* {@link NotModifiedException} <em>above</em> the transport. The call site must treat it as
|
||||
* success, or a recovered blip becomes a hard launch failure.
|
||||
*
|
||||
* <p>Equally load-bearing in the other direction: this manager sees the docker API through a
|
||||
* client whose transport has already spent the full retry budget, so it must not loop again
|
||||
* itself, an outer loop would compound backoff on an already-exhausted inner one (~90s+ worst
|
||||
* case for a single call) and multiply daemon pressure exactly when the socket is saturated.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class ContainerLifecycleManagerStartTest {
|
||||
|
||||
@Mock
|
||||
private ImageCacheService imageCacheService;
|
||||
|
||||
@Mock
|
||||
private ContainerDetector containerDetector;
|
||||
|
||||
@Mock
|
||||
private PortAllocator portAllocator;
|
||||
|
||||
@Mock
|
||||
private EmulatorConfig config;
|
||||
|
||||
private final ContainerSpec spec = new ContainerSpec("busybox:latest");
|
||||
|
||||
/**
|
||||
* A client whose {@code startContainerCmd(...).exec()} defers to {@code behaviour}, which is
|
||||
* handed the 1-based attempt number and may throw. Attempts are counted in {@code execCalls}.
|
||||
*/
|
||||
private DockerClient dockerWhoseStartExec(AtomicInteger execCalls, IntConsumer behaviour) {
|
||||
StartContainerCmd cmd = mock(StartContainerCmd.class);
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
behaviour.accept(execCalls.incrementAndGet());
|
||||
return null;
|
||||
});
|
||||
DockerClient docker = mock(DockerClient.class, RETURNS_DEEP_STUBS);
|
||||
when(docker.startContainerCmd("container-abc")).thenReturn(cmd);
|
||||
return docker;
|
||||
}
|
||||
|
||||
private ContainerLifecycleManager manager(DockerClient docker) {
|
||||
return new ContainerLifecycleManager(
|
||||
docker, imageCacheService, containerDetector, portAllocator, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCreatedTreatsNotModifiedAsSuccess() {
|
||||
AtomicInteger execCalls = new AtomicInteger();
|
||||
DockerClient docker = dockerWhoseStartExec(execCalls, attempt -> {
|
||||
// The transport's retry replayed a start the daemon had honoured before the socket
|
||||
// died; docker answered the replay with HTTP 304, raised here as NotModifiedException.
|
||||
throw new NotModifiedException("Container already started");
|
||||
});
|
||||
|
||||
ContainerLifecycleManager.ContainerInfo info = assertDoesNotThrow(
|
||||
() -> manager(docker).startCreated("container-abc", spec),
|
||||
"a 304 means the container is running, that is success, not failure");
|
||||
|
||||
assertEquals("container-abc", info.containerId());
|
||||
assertEquals(1, execCalls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCreatedDoesNotRetryOnTopOfTheTransport() {
|
||||
AtomicInteger execCalls = new AtomicInteger();
|
||||
RuntimeException transportGaveUp = new RuntimeException(new IOException("Broken pipe"));
|
||||
DockerClient docker = dockerWhoseStartExec(execCalls, attempt -> {
|
||||
throw transportGaveUp;
|
||||
});
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> manager(docker).startCreated("container-abc", spec));
|
||||
|
||||
assertSame(transportGaveUp, thrown,
|
||||
"a transient error surfacing here means the transport already spent the retry"
|
||||
+ " budget; it must surface unchanged");
|
||||
assertEquals(1, execCalls.get(),
|
||||
"no call-site loop: an outer retry would compound backoff on an exhausted"
|
||||
+ " inner one and multiply pressure on a saturated socket");
|
||||
}
|
||||
|
||||
@Test
|
||||
void startCreatedDoesNotSwallowNonTransientFailure() {
|
||||
AtomicInteger execCalls = new AtomicInteger();
|
||||
RuntimeException portConflict =
|
||||
new RuntimeException("Bind for 0.0.0.0:80 failed: port is already allocated");
|
||||
DockerClient docker = dockerWhoseStartExec(execCalls, attempt -> {
|
||||
throw portConflict;
|
||||
});
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> manager(docker).startCreated("container-abc", spec));
|
||||
|
||||
assertSame(portConflict, thrown, "a genuine daemon rejection must surface unchanged");
|
||||
assertEquals(1, execCalls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void adoptTreatsNotModifiedAsSuccess() {
|
||||
AtomicInteger execCalls = new AtomicInteger();
|
||||
DockerClient docker = dockerWhoseStartExec(execCalls, attempt -> {
|
||||
throw new NotModifiedException("Container already started");
|
||||
});
|
||||
|
||||
// adopt() inspects first, sees a stopped container, and starts it.
|
||||
InspectContainerResponse inspect = mock(InspectContainerResponse.class, RETURNS_DEEP_STUBS);
|
||||
when(inspect.getState().getRunning()).thenReturn(Boolean.FALSE);
|
||||
InspectContainerCmd inspectCmd = mock(InspectContainerCmd.class);
|
||||
when(inspectCmd.exec()).thenReturn(inspect);
|
||||
when(docker.inspectContainerCmd("container-abc")).thenReturn(inspectCmd);
|
||||
|
||||
assertDoesNotThrow(() -> manager(docker).adopt("container-abc", List.of()),
|
||||
"adopting a container that turns out to be running already is success");
|
||||
|
||||
assertEquals(1, execCalls.get());
|
||||
}
|
||||
}
|
||||
+94
@@ -4,6 +4,7 @@ import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CreateContainerCmd;
|
||||
import com.github.dockerjava.api.command.CreateContainerResponse;
|
||||
import com.github.dockerjava.api.command.CreateVolumeCmd;
|
||||
import com.github.dockerjava.api.command.CreateVolumeResponse;
|
||||
import com.github.dockerjava.api.command.InspectVolumeCmd;
|
||||
import com.github.dockerjava.api.command.InspectVolumeResponse;
|
||||
import com.github.dockerjava.api.command.ListVolumesCmd;
|
||||
@@ -24,11 +25,15 @@ import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.IntConsumer;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -431,6 +436,95 @@ class ContainerLifecycleManagerVolumeTest {
|
||||
verify(dockerClient, times(2)).createContainerCmd("busybox:stable");
|
||||
}
|
||||
|
||||
/** Stubs {@code inspectVolumeCmd("vol").exec()} to defer to {@code behaviour}, counting calls. */
|
||||
private AtomicInteger inspectVolumeBehaving(IntFunction<InspectVolumeResponse> behaviour) {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
InspectVolumeCmd cmd = mock(InspectVolumeCmd.class);
|
||||
when(dockerClient.inspectVolumeCmd("vol")).thenReturn(cmd);
|
||||
when(cmd.exec()).thenAnswer(inv -> behaviour.apply(calls.incrementAndGet()));
|
||||
return calls;
|
||||
}
|
||||
|
||||
/** Stubs {@code createVolumeCmd()...exec()} to defer to {@code behaviour}, counting calls. */
|
||||
private AtomicInteger createVolumeBehaving(IntConsumer behaviour) {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
CreateVolumeCmd cmd = mock(CreateVolumeCmd.class, RETURNS_SELF);
|
||||
when(dockerClient.createVolumeCmd()).thenReturn(cmd);
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
behaviour.accept(calls.incrementAndGet());
|
||||
return mock(CreateVolumeResponse.class);
|
||||
});
|
||||
return calls;
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureVolume_createsMissingVolumeExactlyOnce() {
|
||||
AtomicInteger inspects = inspectVolumeBehaving(attempt -> {
|
||||
throw new NotFoundException("No such volume: vol");
|
||||
});
|
||||
AtomicInteger creates = createVolumeBehaving(attempt -> {
|
||||
});
|
||||
|
||||
manager.ensureVolume("vol");
|
||||
|
||||
assertEquals(1, inspects.get());
|
||||
assertEquals(1, creates.get(), "a missing volume must be created");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureVolume_doesNotCreateWhenVolumeAlreadyExists() {
|
||||
// This existence guard is what keeps ensureVolume idempotent now that transient-I/O
|
||||
// retries live at the transport: when the daemon created the volume but the response was
|
||||
// lost to a broken pipe, the transport's replayed create finds the volume already there,
|
||||
// POST /volumes/create with the same name is itself idempotent, and later ensureVolume
|
||||
// calls see it exists and do nothing.
|
||||
AtomicInteger inspects = inspectVolumeBehaving(attempt ->
|
||||
mock(InspectVolumeResponse.class));
|
||||
|
||||
manager.ensureVolume("vol");
|
||||
|
||||
assertEquals(1, inspects.get());
|
||||
verify(dockerClient, never()).createVolumeCmd();
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureVolume_doesNotRetryOnTopOfTheTransport() {
|
||||
inspectVolumeBehaving(attempt -> {
|
||||
throw new NotFoundException("No such volume: vol");
|
||||
});
|
||||
RuntimeException transportGaveUp = new RuntimeException(new IOException("Broken pipe"));
|
||||
AtomicInteger creates = createVolumeBehaving(attempt -> {
|
||||
throw transportGaveUp;
|
||||
});
|
||||
|
||||
RuntimeException thrown =
|
||||
assertThrows(RuntimeException.class, () -> manager.ensureVolume("vol"));
|
||||
|
||||
assertSame(transportGaveUp, thrown,
|
||||
"a transient error surfacing here means the transport already spent the retry"
|
||||
+ " budget; it must surface unchanged");
|
||||
assertEquals(1, creates.get(),
|
||||
"no call-site loop: an outer retry would compound backoff on an exhausted"
|
||||
+ " inner one");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureVolume_doesNotSwallowDaemonRejection() {
|
||||
inspectVolumeBehaving(attempt -> {
|
||||
throw new NotFoundException("No such volume: vol");
|
||||
});
|
||||
DockerException rejected = new DockerException("volume name already in use", 409);
|
||||
AtomicInteger creates = createVolumeBehaving(attempt -> {
|
||||
throw rejected;
|
||||
});
|
||||
|
||||
DockerException thrown =
|
||||
assertThrows(DockerException.class, () -> manager.ensureVolume("vol"));
|
||||
|
||||
assertSame(rejected, thrown, "a genuine daemon rejection must surface unchanged");
|
||||
assertEquals(1, creates.get(), "a name conflict never clears on a retry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void ensureSharedVolume_startsHelperThroughTheTranslatingStartContainer() {
|
||||
// github.com/floci-io/floci/issues/2243 (follow-up, PR #2797 review): the shared-volume
|
||||
|
||||
+28
@@ -255,6 +255,34 @@ class DockerClientProducerTest {
|
||||
"An explicitly-configured docker-host should take priority over the Windows named-pipe fallback");
|
||||
}
|
||||
|
||||
// Control-plane calls (create/start/stop/remove/copyArchive) and long-lived streaming
|
||||
// calls (log-follow, exec output streams) must not share one connection pool: a
|
||||
// container's whole-lifetime streams would otherwise occupy pool slots that
|
||||
// short-lived control-plane calls need, starving them into
|
||||
// ConnectionRequestTimeoutException. The @Default and @StreamingDocker beans must
|
||||
// therefore be genuinely separate DockerClient instances (and thus separate pools),
|
||||
// not the same instance handed out under two qualifiers.
|
||||
@Test
|
||||
void dockerClientAndStreamingDockerClient_areDistinctInstances() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.DockerConfig docker = mock(EmulatorConfig.DockerConfig.class);
|
||||
when(config.docker()).thenReturn(docker);
|
||||
when(docker.dockerHost()).thenReturn("unix:///var/run/docker.sock");
|
||||
when(docker.dockerConfigPath()).thenReturn(Optional.empty());
|
||||
when(docker.maxConnections()).thenReturn(100);
|
||||
when(docker.streamingMaxConnections()).thenReturn(512);
|
||||
|
||||
DockerClientProducer producer = new DockerClientProducer(config);
|
||||
|
||||
DockerClient controlPlaneClient = producer.dockerClient();
|
||||
DockerClient streamingClient = producer.streamingDockerClient();
|
||||
|
||||
assertNotNull(controlPlaneClient);
|
||||
assertNotNull(streamingClient);
|
||||
assertNotSame(controlPlaneClient, streamingClient,
|
||||
"Control-plane and streaming DockerClient beans must use separate connection pools");
|
||||
}
|
||||
|
||||
private static void writeContextFixture(Path dockerConfigDir, String contextName, String host)
|
||||
throws IOException {
|
||||
writeContextFixture(dockerConfigDir, contextName, host, false);
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import org.apache.hc.core5.http.ConnectionRequestTimeoutException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Docker daemon calls made concurrently over the single shared socket intermittently fail with
|
||||
* a transient I/O error ({@code Broken pipe} / {@code Connection reset}) that docker-java wraps
|
||||
* in a {@link RuntimeException}. Such failures clear on a retry; anything else must surface
|
||||
* immediately. {@link DockerRetry} centralises that policy for every docker call site.
|
||||
*/
|
||||
class DockerRetryTest {
|
||||
|
||||
@Test
|
||||
void brokenPipeNestedInRuntimeExceptionIsTransient() {
|
||||
assertTrue(DockerRetry.isTransientIo(new RuntimeException(new IOException("Broken pipe"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void connectionResetIsTransient() {
|
||||
assertTrue(DockerRetry.isTransientIo(new RuntimeException("Connection reset by peer")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void directIoExceptionIsTransient() {
|
||||
assertTrue(DockerRetry.isTransientIo(new IOException("Broken pipe")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void plainRuntimeExceptionIsNotTransient() {
|
||||
assertFalse(DockerRetry.isTransientIo(new RuntimeException("400 Bad Request")));
|
||||
}
|
||||
|
||||
// ConnectionRequestTimeoutException extends InterruptedIOException extends IOException, so the
|
||||
// old "any IOException in the cause chain is transient" rule wrongly retried it. It means the
|
||||
// httpclient5 pool has no free connection/lease after waiting the full request timeout, the
|
||||
// pool is exhausted, not the socket blipping. Retrying just re-enters another full wait and
|
||||
// adds more pressure to an already-starved pool, so this must NOT be classified as transient.
|
||||
@Test
|
||||
void connectionRequestTimeoutIsNotTransient() {
|
||||
assertFalse(DockerRetry.isTransientIo(new ConnectionRequestTimeoutException("Timeout waiting for connection from pool")));
|
||||
}
|
||||
|
||||
// A plain InterruptedIOException (e.g. from Thread.interrupt() during a blocking read) signals
|
||||
// cancellation/shutdown, not a socket blip. Retrying it masks the interrupt and delays
|
||||
// shutdown, so it must not be classified as transient either, same rule as its
|
||||
// ConnectionRequestTimeoutException subtype above, just not pool-exhaustion-specific.
|
||||
@Test
|
||||
void plainInterruptedIoExceptionIsNotTransient() {
|
||||
assertFalse(DockerRetry.isTransientIo(new InterruptedIOException("interrupted")));
|
||||
}
|
||||
|
||||
// A single forward walk returns true as soon as it hits the outer IOException, never
|
||||
// reaching the InterruptedIOException wrapped inside it, the exclusion must be checked
|
||||
// over the whole chain before the general "any IOException is transient" rule applies.
|
||||
@Test
|
||||
void interruptedIoExceptionWrappedInAnotherIOExceptionIsStillNotTransient() {
|
||||
assertFalse(DockerRetry.isTransientIo(
|
||||
new IOException("wrapper", new InterruptedIOException("interrupted"))));
|
||||
}
|
||||
|
||||
// java.net.SocketTimeoutException extends InterruptedIOException, but a slow daemon
|
||||
// response is a socket blip like Broken pipe/Connection reset, not a genuine interrupt or
|
||||
// pool exhaustion -- it must stay retryable.
|
||||
@Test
|
||||
void socketTimeoutExceptionIsStillTransientDespiteExtendingInterruptedIOException() {
|
||||
assertTrue(DockerRetry.isTransientIo(new SocketTimeoutException("Read timed out")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void recoversAfterTransientFailures() {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
DockerRetry.run(4, 0L, () -> {
|
||||
if (calls.incrementAndGet() < 3) {
|
||||
throw new RuntimeException(new IOException("Broken pipe"));
|
||||
}
|
||||
});
|
||||
assertEquals(3, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsValueFromSupplierVariant() {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
String result = DockerRetry.call(3, 0L, () -> {
|
||||
if (calls.incrementAndGet() < 2) {
|
||||
throw new RuntimeException(new IOException("Broken pipe"));
|
||||
}
|
||||
return "ok";
|
||||
});
|
||||
assertEquals("ok", result);
|
||||
assertEquals(2, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void exhaustsThenRethrowsLastTransient() {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
RuntimeException boom = assertThrows(RuntimeException.class,
|
||||
() -> DockerRetry.run(3, 0L, () -> {
|
||||
calls.incrementAndGet();
|
||||
throw new RuntimeException(new IOException("Broken pipe"));
|
||||
}));
|
||||
assertEquals(3, calls.get());
|
||||
assertTrue(DockerRetry.isTransientIo(boom));
|
||||
}
|
||||
|
||||
@Test
|
||||
void backoffIsExponentialAndCapped() {
|
||||
assertEquals(500L, DockerRetry.backoffDelay(1, 500L, 8000L));
|
||||
assertEquals(1000L, DockerRetry.backoffDelay(2, 500L, 8000L));
|
||||
assertEquals(2000L, DockerRetry.backoffDelay(3, 500L, 8000L));
|
||||
assertEquals(4000L, DockerRetry.backoffDelay(4, 500L, 8000L));
|
||||
assertEquals(8000L, DockerRetry.backoffDelay(5, 500L, 8000L)); // 8000 hits cap
|
||||
assertEquals(8000L, DockerRetry.backoffDelay(9, 500L, 8000L)); // capped, no overflow
|
||||
assertEquals(0L, DockerRetry.backoffDelay(3, 0L, 8000L)); // zero base stays zero
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryNonTransient() {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
IllegalStateException expected = new IllegalStateException("nope");
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> DockerRetry.run(5, 0L, () -> {
|
||||
calls.incrementAndGet();
|
||||
throw expected;
|
||||
}));
|
||||
assertEquals(1, calls.get());
|
||||
assertSame(expected, thrown);
|
||||
}
|
||||
|
||||
@Test
|
||||
void interruptedExceptionFromOperationRestoresFlagAndIsNotRetried() {
|
||||
// Catches: wrapping an InterruptedException from the operation without restoring the
|
||||
// thread's interrupt flag, or retrying past a cancellation.
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
try {
|
||||
assertThrows(RuntimeException.class, () -> DockerRetry.call(5, 0L, () -> {
|
||||
calls.incrementAndGet();
|
||||
throw new InterruptedException("stop");
|
||||
}));
|
||||
assertTrue(Thread.currentThread().isInterrupted());
|
||||
assertEquals(1, calls.get());
|
||||
} finally {
|
||||
Thread.interrupted();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMaxAttemptsBelowOne() {
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> DockerRetry.run(0, 0L, calls::incrementAndGet));
|
||||
assertThrows(IllegalArgumentException.class,
|
||||
() -> DockerRetry.run(-1, 0L, calls::incrementAndGet));
|
||||
// The misconfiguration must fail loudly, not silently skip the call entirely.
|
||||
assertEquals(0, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void brokenPipeMatchesRegardlessOfCase() {
|
||||
// The daemon's capitalisation is not a contract, and the default locale must not decide
|
||||
// whether a transient drop is recognised.
|
||||
assertTrue(DockerRetry.isTransientIo(new RuntimeException("broken pipe")));
|
||||
assertTrue(DockerRetry.isTransientIo(new RuntimeException("BROKEN PIPE")));
|
||||
assertTrue(DockerRetry.isTransientIo(new RuntimeException("Broken Pipe")));
|
||||
}
|
||||
}
|
||||
+358
@@ -0,0 +1,358 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import com.github.dockerjava.transport.DockerHttpClient.Request;
|
||||
import com.github.dockerjava.transport.DockerHttpClient.Response;
|
||||
import org.apache.hc.core5.http.ConnectionRequestTimeoutException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.IntFunction;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
/**
|
||||
* The docker daemon drops connections mid-call under fan-out load, and docker-java surfaces the
|
||||
* blip as {@code RuntimeException(IOException("Broken pipe"))} from inside
|
||||
* {@code DockerHttpClient.execute()}. Retrying per call site has now been fixed three separate
|
||||
* times ({@code createContainerCmd}, {@code startContainerCmd}, {@code ensureVolume}) while ~60
|
||||
* other docker call sites stayed bare. {@link RetryingDockerHttpClient} moves the retry to the
|
||||
* transport seam so every call site, present and future, is covered once.
|
||||
*
|
||||
* <p>The retry may only fire when replaying the request cannot change semantics: the request must
|
||||
* be replayable (no one-shot body stream, no hijacked stdin) and must not be an exec-start, which
|
||||
* would re-run a shell command whose first run may have executed.
|
||||
*/
|
||||
class RetryingDockerHttpClientTest {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
|
||||
/** A delegate whose {@code execute} defers to {@code behaviour}, handed the 1-based attempt. */
|
||||
private static final class FakeTransport implements DockerHttpClient {
|
||||
final AtomicInteger calls = new AtomicInteger();
|
||||
final List<Request> seenRequests = new ArrayList<>();
|
||||
final IntFunction<Response> behaviour;
|
||||
|
||||
FakeTransport(IntFunction<Response> behaviour) {
|
||||
this.behaviour = behaviour;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Response execute(Request request) {
|
||||
seenRequests.add(request);
|
||||
return behaviour.apply(calls.incrementAndGet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
}
|
||||
}
|
||||
|
||||
private static RuntimeException brokenPipe() {
|
||||
return new RuntimeException(new IOException("Broken pipe"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesTransientBrokenPipeOnBodylessRequestThenSucceeds() {
|
||||
Response ok = mock(Response.class);
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
if (attempt < 3) {
|
||||
throw brokenPipe();
|
||||
}
|
||||
return ok;
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
|
||||
Request ping = Request.builder().method(Request.Method.GET).path("/_ping").build();
|
||||
|
||||
assertSame(ok, client.execute(ping));
|
||||
assertEquals(3, delegate.calls.get(),
|
||||
"a transient Broken pipe on a bodyless GET must be retried at the transport");
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesByteArrayBodiedRequestReplayingIdenticalBytes() {
|
||||
Response ok = mock(Response.class);
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
if (attempt == 1) {
|
||||
throw brokenPipe();
|
||||
}
|
||||
return ok;
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
|
||||
byte[] body = "{\"Image\":\"busybox\"}".getBytes(StandardCharsets.UTF_8);
|
||||
Request create = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/containers/create?name=x")
|
||||
.bodyBytes(body)
|
||||
.build();
|
||||
|
||||
assertSame(ok, client.execute(create));
|
||||
assertEquals(2, delegate.calls.get(),
|
||||
"a POST whose body is a plain byte[] is replayable and must be retried");
|
||||
// This is the replay-safety proof, not a formality: the transport builds a fresh entity
|
||||
// from bodyBytes() on every execute(), so both attempts must see the very same bytes.
|
||||
assertEquals(2, delegate.seenRequests.size());
|
||||
assertEquals(Arrays.hashCode(delegate.seenRequests.get(0).bodyBytes()),
|
||||
Arrays.hashCode(delegate.seenRequests.get(1).bodyBytes()),
|
||||
"the retried attempt must carry byte-identical body content");
|
||||
assertEquals("/containers/create?name=x", delegate.seenRequests.get(1).path());
|
||||
}
|
||||
|
||||
@Test
|
||||
void injectsCanonicalCloseWhilePreservingRequestDataAndHeaders() {
|
||||
Response ok = mock(Response.class);
|
||||
FakeTransport delegate = new FakeTransport(attempt -> ok);
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
|
||||
byte[] body = "{\"Image\":\"busybox\"}".getBytes(StandardCharsets.UTF_8);
|
||||
Request create = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/containers/create")
|
||||
.bodyBytes(body)
|
||||
.putHeader("Content-Type", "application/json")
|
||||
.putHeader("connection", "keep-alive")
|
||||
.build();
|
||||
|
||||
assertSame(ok, client.execute(create));
|
||||
Request effective = delegate.seenRequests.get(0);
|
||||
assertEquals(create.method(), effective.method());
|
||||
assertEquals(create.path(), effective.path());
|
||||
assertSame(body, effective.bodyBytes());
|
||||
assertEquals("application/json", effective.headers().get("Content-Type"));
|
||||
assertEquals("close", effective.headers().get("Connection"));
|
||||
assertEquals(1, effective.headers().entrySet().stream()
|
||||
.filter(entry -> "Connection".equalsIgnoreCase(entry.getKey()))
|
||||
.count(), "the transport must receive one unambiguous Connection header");
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryOneShotStreamBody() {
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
|
||||
// The tar upload of copyArchiveToContainerCmd: bodyBytes is null, body() is a one-shot
|
||||
// stream that the first (failed) attempt may have partially consumed. Replaying it would
|
||||
// send a truncated archive, so the failure must surface after exactly one attempt.
|
||||
InputStream tar = new ByteArrayInputStream(new byte[]{1, 2, 3});
|
||||
Request putArchive = Request.builder()
|
||||
.method(Request.Method.PUT)
|
||||
.path("/containers/abc/archive")
|
||||
.body(tar)
|
||||
.build();
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () -> client.execute(putArchive));
|
||||
assertEquals("Broken pipe", thrown.getCause().getMessage());
|
||||
assertEquals(1, delegate.calls.get(),
|
||||
"a one-shot stream body cannot be replayed; the transport must not retry it");
|
||||
assertSame(tar, delegate.seenRequests.get(0).body(),
|
||||
"adding Connection: close must preserve the one-shot stream object");
|
||||
assertEquals("close", delegate.seenRequests.get(0).headers().get("Connection"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryHijackedRequest() {
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
|
||||
Request attach = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/containers/abc/attach")
|
||||
.hijackedInput(new ByteArrayInputStream(new byte[0]))
|
||||
.build();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> client.execute(attach));
|
||||
assertEquals(1, delegate.calls.get(),
|
||||
"a hijacked (bidirectional stdin) request must never be replayed");
|
||||
assertSame(attach, delegate.seenRequests.get(0),
|
||||
"hijacked requests must reach docker-java unchanged for Connection: Upgrade");
|
||||
assertEquals(Map.of(), delegate.seenRequests.get(0).headers());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryExecPathsEvenWhenReplayable() {
|
||||
// POST /exec/{id}/start carries a small JSON body, so by the replayable-body rule alone it
|
||||
// would be retried, re-running a shell command whose first run may have executed. Exec
|
||||
// paths are excluded outright.
|
||||
FakeTransport startDelegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient startClient =
|
||||
new RetryingDockerHttpClient(startDelegate, MAX_ATTEMPTS, 0L);
|
||||
Request execStart = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/exec/deadbeef/start")
|
||||
.bodyBytes("{}".getBytes(StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> startClient.execute(execStart));
|
||||
assertEquals(1, startDelegate.calls.get(),
|
||||
"exec-start re-runs the command if replayed; it must surface after one attempt");
|
||||
assertEquals("close", startDelegate.seenRequests.get(0).headers().get("Connection"),
|
||||
"non-replayable exec control calls must still retire their connection");
|
||||
|
||||
// The exclusion is contains("/exec"), not startsWith: exec-create
|
||||
// (POST /containers/{id}/exec) is also excluded, and this pins that breadth so a later
|
||||
// refactor to startsWith cannot pass CI.
|
||||
FakeTransport createDelegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient createClient =
|
||||
new RetryingDockerHttpClient(createDelegate, MAX_ATTEMPTS, 0L);
|
||||
Request execCreate = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/containers/abc/exec")
|
||||
.bodyBytes("{}".getBytes(StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
assertThrows(RuntimeException.class, () -> createClient.execute(execCreate));
|
||||
assertEquals(1, createDelegate.calls.get(),
|
||||
"exec-create must be excluded too, the /exec exclusion covers both spellings");
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryUnnamedContainerCreate() {
|
||||
// Catches: replaying an unnamed containers/create whose first attempt landed, which
|
||||
// creates a second orphaned container nobody can adopt.
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
Request create = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/containers/create")
|
||||
.bodyBytes("{}".getBytes(StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () -> client.execute(create));
|
||||
assertEquals("Broken pipe", thrown.getCause().getMessage());
|
||||
assertEquals(1, delegate.calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryNetworkCreate() {
|
||||
// Catches: replaying networks/create, where the replay gets a 409 that the VPC manager
|
||||
// swallows, so the VPC silently loses its network.
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
Request create = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/networks/create")
|
||||
.bodyBytes("{}".getBytes(StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () -> client.execute(create));
|
||||
assertEquals("Broken pipe", thrown.getCause().getMessage());
|
||||
assertEquals(1, delegate.calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryRestartOrNetworkConnectAndDisconnect() {
|
||||
// Catches: replaying a bodyless restart whose first attempt landed, which restarts the
|
||||
// container a second time, and replaying a network connect/disconnect, which the daemon
|
||||
// answers with a conflict or not-found the caller never expected.
|
||||
for (String path : List.of("/containers/abc/restart?t=10", "/networks/net1/connect",
|
||||
"/networks/net1/disconnect")) {
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
throw brokenPipe();
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
Request request = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path(path)
|
||||
.build();
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class, () -> client.execute(request));
|
||||
assertEquals("Broken pipe", thrown.getCause().getMessage());
|
||||
assertEquals(1, delegate.calls.get(), path);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void retriesNamedContainerCreate() {
|
||||
// Catches: over-broad exclusion that stops replaying named creates, which are safe
|
||||
// because the caller adopts the container on a 409.
|
||||
Response ok = mock(Response.class);
|
||||
FakeTransport delegate = new FakeTransport(attempt -> {
|
||||
if (attempt == 1) {
|
||||
throw brokenPipe();
|
||||
}
|
||||
return ok;
|
||||
});
|
||||
RetryingDockerHttpClient client = new RetryingDockerHttpClient(delegate, MAX_ATTEMPTS, 0L);
|
||||
Request create = Request.builder()
|
||||
.method(Request.Method.POST)
|
||||
.path("/containers/create?platform=linux%2Famd64&name=floci-x")
|
||||
.bodyBytes("{}".getBytes(StandardCharsets.UTF_8))
|
||||
.build();
|
||||
|
||||
assertSame(ok, client.execute(create));
|
||||
assertEquals(2, delegate.calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void doesNotRetryNonTransientFailures() {
|
||||
// Pool exhaustion: retrying re-enters another full connection-request wait and adds
|
||||
// pressure to an already-starved pool. isTransientIo deliberately excludes it.
|
||||
RuntimeException poolExhausted =
|
||||
new RuntimeException(new ConnectionRequestTimeoutException("no free lease"));
|
||||
FakeTransport exhaustedDelegate = new FakeTransport(attempt -> {
|
||||
throw poolExhausted;
|
||||
});
|
||||
RetryingDockerHttpClient exhaustedClient =
|
||||
new RetryingDockerHttpClient(exhaustedDelegate, MAX_ATTEMPTS, 0L);
|
||||
Request ping = Request.builder().method(Request.Method.GET).path("/_ping").build();
|
||||
|
||||
RuntimeException thrown =
|
||||
assertThrows(RuntimeException.class, () -> exhaustedClient.execute(ping));
|
||||
assertSame(poolExhausted, thrown, "pool exhaustion must surface unchanged");
|
||||
assertEquals(1, exhaustedDelegate.calls.get(), "pool exhaustion must not be retried");
|
||||
|
||||
// A genuine daemon rejection (e.g. a 409 name conflict raised above the transport as a
|
||||
// DockerException) never clears on a retry either.
|
||||
IllegalStateException rejection = new IllegalStateException("Conflict: name already in use");
|
||||
FakeTransport rejectedDelegate = new FakeTransport(attempt -> {
|
||||
throw rejection;
|
||||
});
|
||||
RetryingDockerHttpClient rejectedClient =
|
||||
new RetryingDockerHttpClient(rejectedDelegate, MAX_ATTEMPTS, 0L);
|
||||
|
||||
IllegalStateException surfaced =
|
||||
assertThrows(IllegalStateException.class, () -> rejectedClient.execute(ping));
|
||||
assertSame(rejection, surfaced, "a daemon rejection must surface unchanged");
|
||||
assertEquals(1, rejectedDelegate.calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void producerWrapsControlPlaneTransportOnly() {
|
||||
DockerHttpClient raw = new FakeTransport(attempt -> null);
|
||||
|
||||
DockerHttpClient controlPlane = DockerClientProducer.wrapForRole(raw, "control-plane");
|
||||
DockerHttpClient streaming = DockerClientProducer.wrapForRole(raw, "streaming");
|
||||
|
||||
assertSame(RetryingDockerHttpClient.class, controlPlane.getClass(),
|
||||
"the control-plane transport must be wrapped in the retry decorator");
|
||||
assertNotSame(raw, controlPlane);
|
||||
assertSame(raw, streaming,
|
||||
"the streaming transport (log-follow, exec output) must stay unwrapped");
|
||||
}
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
|
||||
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
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.any;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.atLeastOnce;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The transport-level retry ({@code RetryingDockerHttpClient}) must refuse to replay a one-shot
|
||||
* {@code InputStream} body, the streamed tar bytes are gone after the first attempt. Every
|
||||
* tar-copy into a container therefore needs its retry at the call site, rebuilding the whole
|
||||
* operation (tar bytes or pipe, streamer thread, request) per attempt. This module is that call
|
||||
* site, shared by every service that copies content into containers; tar extract over the same
|
||||
* path is idempotent, so replay is safe.
|
||||
*/
|
||||
class RetryingTarCopierTest {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
|
||||
private static RuntimeException brokenPipe() {
|
||||
return new RuntimeException(new IOException("Broken pipe"));
|
||||
}
|
||||
|
||||
private static CopyArchiveToContainerCmd failingOnce(DockerClient docker, AtomicInteger calls) {
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
if (calls.incrementAndGet() == 1) {
|
||||
throw brokenPipe();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
return cmd;
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyBytesRetriesWithAFreshStreamPerAttempt() {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
CopyArchiveToContainerCmd cmd = failingOnce(docker, calls);
|
||||
|
||||
RetryingTarCopier.copyBytes(docker, "c-1", "/etc", "registries.yaml",
|
||||
"mirrors: {}".getBytes(StandardCharsets.UTF_8), 0644, MAX_ATTEMPTS, 0L);
|
||||
|
||||
assertEquals(2, calls.get(), "a broken pipe on a byte copy is a socket blip, not a failure");
|
||||
ArgumentCaptor<InputStream> streams = ArgumentCaptor.forClass(InputStream.class);
|
||||
verify(cmd, atLeastOnce()).withTarInputStream(streams.capture());
|
||||
assertEquals(2, streams.getAllValues().size(), "each attempt must send its own stream");
|
||||
assertNotSame(streams.getAllValues().get(0), streams.getAllValues().get(1),
|
||||
"replaying a consumed stream would upload zero bytes");
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyBytesDoesNotRetryDaemonRejection() {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
RuntimeException noSuchContainer = new RuntimeException("No such container: c-1");
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
calls.incrementAndGet();
|
||||
throw noSuchContainer;
|
||||
});
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> RetryingTarCopier.copyBytes(docker, "c-1", "/etc", "f", new byte[]{1},
|
||||
0644, MAX_ATTEMPTS, 0L));
|
||||
|
||||
assertSame(noSuchContainer, thrown.getCause(),
|
||||
"a genuine daemon rejection must surface after a single attempt");
|
||||
assertEquals(1, calls.get());
|
||||
}
|
||||
|
||||
// copyFile streams tarWriter through a pipe on its own thread; if the writer fails before
|
||||
// producing any bytes (e.g. the source file vanished), closing the pipe with nothing written
|
||||
// looks like a clean, empty tar to a reader that isn't checking for that, the daemon accepts
|
||||
// it and exec() returns normally, so the caller would otherwise see a false success instead
|
||||
// of the real failure.
|
||||
@Test
|
||||
void copyFileFailsTheAttemptWhenTheSourceFileIsMissingInsteadOfReportingSuccess(@TempDir Path tempDir) {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(cmd.exec()).thenAnswer(inv -> null);
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
Path missing = tempDir.resolve("does-not-exist");
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> RetryingTarCopier.copyFile(docker, "c-1", "/etc", "f", missing, 0644, 1, 0L));
|
||||
|
||||
Throwable cause = thrown.getCause();
|
||||
while (cause != null && !(cause instanceof NoSuchFileException)) {
|
||||
cause = cause.getCause();
|
||||
}
|
||||
assertEquals(NoSuchFileException.class, cause == null ? null : cause.getClass(),
|
||||
"the streamer's real failure must surface, not a phantom success");
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyStreamedDoesNotRetryALocalWriterFailure() {
|
||||
// Catches: a local tar-writer IOException (unreadable source file) being retried as a
|
||||
// transient daemon blip, rebuilding the copy several times with backoff.
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
when(cmd.exec()).thenAnswer(inv -> null);
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
AtomicInteger writes = new AtomicInteger();
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> RetryingTarCopier.copyStreamed(docker, "c-1", "/var/task", "fn-code",
|
||||
out -> {
|
||||
writes.incrementAndGet();
|
||||
throw new IOException("Permission denied");
|
||||
},
|
||||
MAX_ATTEMPTS, 0L));
|
||||
|
||||
assertEquals(1, writes.get());
|
||||
assertTrue(thrown.getMessage().contains("Permission denied"), thrown.getMessage());
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFileRebuildsThePipePerAttempt(@TempDir Path dir) throws IOException {
|
||||
Path file = dir.resolve("bootstrap");
|
||||
Files.writeString(file, "#!/bin/sh\n");
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
failingOnce(docker, calls);
|
||||
|
||||
RetryingTarCopier.copyFile(docker, "c-1", "/var/runtime", "bootstrap", file, 0755,
|
||||
MAX_ATTEMPTS, 0L);
|
||||
|
||||
assertEquals(2, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyStreamedInvokesTheWriterFreshlyPerAttempt() {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
failingOnce(docker, calls);
|
||||
AtomicInteger writes = new AtomicInteger();
|
||||
|
||||
RetryingTarCopier.copyStreamed(docker, "c-1", "/var/task", "fn-code",
|
||||
out -> {
|
||||
writes.incrementAndGet();
|
||||
out.write("x".getBytes(StandardCharsets.UTF_8));
|
||||
},
|
||||
MAX_ATTEMPTS, 0L);
|
||||
|
||||
assertEquals(2, calls.get());
|
||||
assertEquals(2, writes.get(), "the tar content must be regenerated for every attempt");
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyHostResourceRetriesTransientBrokenPipe(@TempDir Path dir) throws IOException {
|
||||
Path file = dir.resolve("kubeconfig.yaml");
|
||||
Files.writeString(file, "apiVersion: v1");
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
failingOnce(docker, calls);
|
||||
|
||||
RetryingTarCopier.copyHostResource(docker, "c-1", "/var/lib/rancher", file.toString(),
|
||||
MAX_ATTEMPTS, 0L);
|
||||
|
||||
assertEquals(2, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleFileTarPreservesNameContentAndMode() throws IOException {
|
||||
byte[] content = "ssh-ed25519 AAAA".getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
byte[] tar = RetryingTarCopier.singleFileTar("authorized_keys", content, 0600);
|
||||
|
||||
try (TarArchiveInputStream in = new TarArchiveInputStream(new ByteArrayInputStream(tar))) {
|
||||
TarArchiveEntry entry = in.getNextEntry();
|
||||
assertEquals("authorized_keys", entry.getName());
|
||||
assertEquals(0600, entry.getMode() & 07777, "an ssh key copied world-readable is a defect");
|
||||
assertEquals(new String(content, StandardCharsets.UTF_8),
|
||||
new String(in.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
package io.github.hectorvent.floci.services.lambda.launcher;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.command.CopyArchiveToContainerCmd;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
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.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
|
||||
import static org.mockito.Mockito.RETURNS_SELF;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The transport-level retry ({@code RetryingDockerHttpClient}) must refuse to replay a one-shot
|
||||
* {@code InputStream} body, after the first attempt the streamed tar bytes are gone. That leaves
|
||||
* the Lambda launcher's tar-copies (function code, layers, and the TLS CA cert) exposed to
|
||||
* transient broken pipes: one blip while copying {@code floci-selfsigned.crt} failed an entire
|
||||
* LZA Accounts stage with {@code Lambda.InitError}. The copy is idempotent (tar extract over the
|
||||
* same path), and the whole operation, fresh pipe, fresh streamer thread, fresh request, can be
|
||||
* rebuilt per attempt, so the retry lives at the call site.
|
||||
*/
|
||||
class ContainerLauncherCopyRetryTest {
|
||||
|
||||
private static final int MAX_ATTEMPTS = 3;
|
||||
|
||||
private static RuntimeException brokenPipe() {
|
||||
return new RuntimeException(new IOException("Broken pipe"));
|
||||
}
|
||||
|
||||
private ContainerLauncher launcher() {
|
||||
// The constructor sizes its code-volume populate semaphore off the config, so a bare null
|
||||
// no longer builds; the copy paths under test read nothing else from it.
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
when(config.services().lambda().codeVolumePopulateConcurrency()).thenReturn(Optional.empty());
|
||||
return new ContainerLauncher(null, null, null, null, null, null, config, null, null, null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFileToContainerRetriesTransientBrokenPipe(@TempDir Path dir) throws IOException {
|
||||
Path cert = dir.resolve("floci-selfsigned.crt");
|
||||
Files.writeString(cert, "-----BEGIN CERTIFICATE-----");
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
if (calls.incrementAndGet() == 1) {
|
||||
throw brokenPipe();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
|
||||
launcher().copyFileToContainer(docker, "container-1", cert, "/etc", "floci-ca.crt", "fn",
|
||||
MAX_ATTEMPTS, 0L);
|
||||
|
||||
assertEquals(2, calls.get(),
|
||||
"a broken pipe on the cert copy is a socket blip, not a launch failure");
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyFileToContainerDoesNotRetryDaemonRejection(@TempDir Path dir) throws IOException {
|
||||
Path cert = dir.resolve("floci-selfsigned.crt");
|
||||
Files.writeString(cert, "-----BEGIN CERTIFICATE-----");
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
RuntimeException noSuchContainer = new RuntimeException("No such container: container-1");
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
calls.incrementAndGet();
|
||||
throw noSuchContainer;
|
||||
});
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
|
||||
RuntimeException thrown = assertThrows(RuntimeException.class,
|
||||
() -> launcher().copyFileToContainer(docker, "container-1", cert, "/etc",
|
||||
"floci-ca.crt", "fn", MAX_ATTEMPTS, 0L));
|
||||
|
||||
assertSame(noSuchContainer, thrown.getCause(),
|
||||
"a genuine daemon rejection must surface after a single attempt");
|
||||
assertEquals(1, calls.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void copyDirToContainerRetriesTransientBrokenPipe(@TempDir Path dir) throws IOException {
|
||||
Files.writeString(dir.resolve("index.js"), "exports.handler = () => {};");
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
CopyArchiveToContainerCmd cmd = mock(CopyArchiveToContainerCmd.class, RETURNS_SELF);
|
||||
AtomicInteger calls = new AtomicInteger();
|
||||
when(cmd.exec()).thenAnswer(inv -> {
|
||||
if (calls.incrementAndGet() == 1) {
|
||||
throw brokenPipe();
|
||||
}
|
||||
return null;
|
||||
});
|
||||
when(docker.copyArchiveToContainerCmd(any())).thenReturn(cmd);
|
||||
|
||||
launcher().copyDirToContainer(docker, "container-1", dir, "/var/task", "fn",
|
||||
MAX_ATTEMPTS, 0L);
|
||||
|
||||
assertEquals(2, calls.get(),
|
||||
"each attempt rebuilds the pipe and streamer thread, so the dir copy may retry");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user