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:
Sam Fakhreddine authored and GitHub committed 2026-10-03 14:56:35 -05:00
1 parent dfe2117fed
commit 1531537559
26 files changed
+2279 -161

No files matched your search

@@ -3462,10 +3462,10 @@ public interface EmulatorConfig {
/**
* Size of the connection pool behind the shared Docker client. Every Docker call leases a
* connection from it, and some hold one for as long as a container runs: a Lambda
* container holds two (its followed log stream and its exit watcher) plus one per
* extension, and other container-backed services hold one for their log stream. Once
* those fill the pool, create, start, stop and remove wait for a free connection,
* including the calls that would release one, so the emulator stalls.
* container holds one (its exit watcher) plus one per extension. Log-follow streams
* live in the separate streaming pool. Once the long-lived connections fill this pool,
* create, start, stop and remove wait for a free connection, including the calls that
* would release one, so the emulator stalls.
*
* <p>1024 rather than the former hard-coded 100, which capped live Lambda containers at
* about 50: a tenth of the 500 that the runtime API port range
@@ -3475,6 +3475,17 @@ public interface EmulatorConfig {
@WithDefault("1024")
int maxConnections();
/**
* Connection pool size for the {@code @StreamingDocker} DockerClient, sized for the
* long-lived container log-follow streams that occupy a slot for a container's entire
* lifetime. Exec-output and container-wait streams stay on the main pool. Total live
* containers is unbounded across distinct functions (each {@code WarmPool} caps only
* per-function), so this pool is sized generously rather than tied to any single
* function's warm-pool cap.
*/
@WithDefault("512")
int streamingMaxConnections();
/**
* Optional namespace inserted into Floci-managed child container and volume names.
* Useful when multiple Floci processes share one Docker daemon.
@@ -7,8 +7,10 @@ import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.InspectVolumeResponse;
import com.github.dockerjava.api.command.ListVolumesResponse;
import com.github.dockerjava.api.exception.ConflictException;
import com.github.dockerjava.api.exception.DockerException;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.exception.NotModifiedException;
import com.github.dockerjava.api.model.Bind;
import com.github.dockerjava.api.model.Capability;
import com.github.dockerjava.api.model.Container;
@@ -42,6 +44,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -56,6 +59,13 @@ public class ContainerLifecycleManager {
private static final Logger LOG = Logger.getLogger(ContainerLifecycleManager.class);
/**
* Label carrying a fresh id per {@code create()} invocation, used to tell this call's own
* replayed create apart from a genuinely concurrent caller's, see
* {@link #createWithConflictRecovery}.
*/
static final String CREATE_ATTEMPT_LABEL = "floci_create_attempt_id";
// Matches crun/runc's "join keyctl '<id>': Disk quota exceeded" error, which the OCI runtime
// reports for the kernel session-keyring quota (kernel.keys.maxkeys), not actual disk space.
// Under high concurrent container counts (podman machine's Fedora CoreOS default is 200 keys
@@ -217,14 +227,57 @@ public class ContainerLifecycleManager {
.toArray(ExposedPort[]::new);
createCmd.withExposedPorts(exposed);
}
createCmd.withLabels(mergedLabels(spec.labels()));
// A fresh id per create() call, not per spec: two calls can carry identical image, name,
// and labels (a second, genuinely concurrent caller racing on the same fixed name), and
// matchesSpec must be able to tell that apart from a replay of THIS call's own create
// hitting a lost-response conflict, see createWithConflictRecovery.
String createAttemptId = UUID.randomUUID().toString();
Map<String, String> labels = mergedLabels(spec.labels());
labels.put(CREATE_ATTEMPT_LABEL, createAttemptId);
createCmd.withLabels(labels);
CreateContainerResponse response = createCmd.exec();
String containerId = response.getId();
String containerId = createWithConflictRecovery(createCmd, spec, createAttemptId);
LOG.infov("Created container {0} (name={1}, not yet started)", containerId, spec.name());
return containerId;
}
/**
* Executes the create, recovering the container when a replay of it lost the race with its own
* earlier attempt.
*
* <p>{@link RetryingDockerHttpClient} replays {@code POST /containers/create}, it has a
* {@code bodyBytes} body, no hijacked input, and no {@code /exec} in its path, so it is
* replayable by that decorator's rules. That replay is what makes this recovery necessary: a
* create is not idempotent, so if the daemon accepts a named create but the response is lost to
* a transient socket drop, the replay hits a 409 name conflict instead of the transient error
* the retry exists to absorb. {@code DockerRetry} correctly classifies that 409 as
* 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
* 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.
*/
private String createWithConflictRecovery(CreateContainerCmd createCmd, ContainerSpec spec,
String createAttemptId) {
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();
}
}
throw e;
}
}
/**
* Applies endpoint IPAM while the container is still in CREATED state. docker-java does not
* expose Docker's {@code NetworkingConfig} on create, but it does expose the equivalent
@@ -295,6 +348,27 @@ public class ContainerLifecycleManager {
}
}
/**
* Confirms a name-conflicting container is the one THIS create() call produced, not a stale or
* differently-owned container, and not one from a genuinely concurrent create() sharing the same
* fixed name, image, and spec labels. It must carry every label this call would have applied,
* including a {@link #CREATE_ATTEMPT_LABEL} equal to this call's {@code createAttemptId}: the
* one part of the label set a different concurrent call could never coincidentally reproduce,
* and on its own sufficient proof of ownership.
*
* <p>Deliberately does NOT compare the image. The list API reports {@code getImage()} as an
* image ID/digest rather than the tag once that tag has been re-pulled, retagged, or removed, so
* a tag comparison would reject this call's own container and leak it untracked, the failure
* this recovery exists to prevent, arising precisely under the daemon churn that makes a lost
* create response likely. The attempt-id match already excludes every foreign container.
*/
private boolean matchesSpec(Container existing, ContainerSpec spec, String createAttemptId) {
Map<String, String> expectedLabels = mergedLabels(spec.labels());
expectedLabels.put(CREATE_ATTEMPT_LABEL, createAttemptId);
Map<String, String> actualLabels = existing.getLabels();
return actualLabels != null && actualLabels.entrySet().containsAll(expectedLabels.entrySet());
}
/**
* Starts a previously created container and resolves its endpoints.
*
@@ -341,14 +415,29 @@ public class ContainerLifecycleManager {
}
/**
* Starts a container, translating crun/runc's kernel-keyring-quota error into a message that
* names the actual cause and a fix, instead of the misleading "Disk quota exceeded" the OCI
* runtime reports. Package-private so tests can verify a given call site routes through this
* translation rather than a raw {@code dockerClient.startContainerCmd(...)} call.
* Starts {@code containerId}, treating "already running" as success and translating
* crun/runc's kernel-keyring-quota error into a message that names the actual cause and a fix,
* instead of the misleading "Disk quota exceeded" the OCI runtime reports. Transient socket
* blips are retried below this call, at the transport seam
* ({@link RetryingDockerHttpClient}); no retry may live here, where it would compound backoff
* on the transport's already-exhausted budget.
*
* <p>The 304 handling is what makes the transport's replay safe: when the daemon honoured a
* start whose response was lost to a broken pipe, the replayed start meets HTTP 304, a
* successful response at transport level, which docker-java converts to
* {@link NotModifiedException} above it. That reports the outcome we wanted and is swallowed.
* Letting it escape would turn a recovered blip into a hard launch failure, the exact bug
* the retry exists to remove.
*
* <p>Package-private so tests can verify a given call site routes through this translation
* rather than a raw {@code dockerClient.startContainerCmd(...)} call.
*/
void startContainer(String containerId) {
try {
dockerClient.startContainerCmd(containerId).exec();
} catch (NotModifiedException alreadyRunning) {
LOG.debugv("Container {0} was already running (304), treating start as done",
containerId);
} catch (DockerException e) {
String message = e.getMessage();
if (message != null && KEYRING_QUOTA_PATTERN.matcher(message).find()) {
@@ -477,6 +566,13 @@ public class ContainerLifecycleManager {
* {@code floci_emulator=floci-aws} (plus {@code floci_namespace} when configured) so both
* {@code docker volume prune --filter label=floci=true} (all emulators) and
* {@code --filter label=floci_emulator=floci-aws} (this emulator only) work.
*
* <p>Transient socket blips on both daemon calls here, the existence check and the create,
* are retried at the transport seam ({@link RetryingDockerHttpClient}). The existence guard
* is what keeps the transport's replay safe: {@code POST /volumes/create} with the same name
* is itself idempotent, and when the daemon created the volume but the response was lost to
* a broken pipe, the replayed create finds it already there while later calls see it exists
* and do nothing, the volume analogue of start treating an HTTP 304 as success.
*/
public void ensureVolume(String volumeName) {
createVolumeIfAbsent(volumeName);
@@ -47,8 +47,12 @@ public class ContainerLogStreamer {
private final DockerClient dockerClient;
private final CloudWatchLogsService cloudWatchLogsService;
// Log-follow attaches hold their connection open for the whole container lifetime, so
// this class is the primary consumer of the streaming pool: sharing the control-plane
// pool is what starved short create/start/stop calls during an LZA Logging fan-out
// (see DockerClientProducer / StreamingDocker).
@Inject
public ContainerLogStreamer(DockerClient dockerClient, CloudWatchLogsService cloudWatchLogsService) {
public ContainerLogStreamer(@StreamingDocker DockerClient dockerClient, CloudWatchLogsService cloudWatchLogsService) {
this.dockerClient = dockerClient;
this.cloudWatchLogsService = cloudWatchLogsService;
}
@@ -10,6 +10,7 @@ import com.github.dockerjava.core.DockerClientImpl;
import com.github.dockerjava.core.SSLConfig;
import com.github.dockerjava.core.util.CertificateUtils;
import com.github.dockerjava.httpclient5.ApacheDockerHttpClient;
import com.github.dockerjava.transport.DockerHttpClient;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Produces;
import jakarta.inject.Inject;
@@ -33,7 +34,7 @@ import java.util.Optional;
import java.util.function.Function;
/**
* CDI producer for the DockerClient singleton bean.
* CDI producer for the DockerClient beans.
*/
@ApplicationScoped
public class DockerClientProducer {
@@ -408,13 +409,55 @@ public class DockerClientProducer {
return maxConnections;
}
/** Same check as {@link #validateMaxConnections(int)}, for the streaming pool's setting. */
static int validateStreamingMaxConnections(int streamingMaxConnections) {
if (streamingMaxConnections < 1) {
throw new IllegalArgumentException("floci.docker.streaming-max-connections "
+ "(FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS) must be at least 1, got: "
+ streamingMaxConnections);
}
return streamingMaxConnections;
}
/**
* Control-plane DockerClient: create/start/stop/remove/copyArchive and every other
* short-lived call in Floci. Kept on its own connection pool, separate from the
* {@link StreamingDocker} bean, so long-lived log-follow streams can never occupy every
* lease in this pool and starve these short calls until httpclient5's connection-request
* timeout fires. Exec-output and container-wait streams (CodeBuild phases, Lambda
* extensions and exit watchers, EKS audit followers) still use this pool.
*/
@Produces
@ApplicationScoped
public DockerClient dockerClient() {
int maxConnections = validateMaxConnections(config.docker().maxConnections());
return buildDockerClient(buildClientConfig(),
validateMaxConnections(config.docker().maxConnections()), "control-plane");
}
/**
* Streaming DockerClient: container log-follow ({@link ContainerLogStreamer}). Each
* stream occupies a connection pool slot for its entire lifetime, so sharing the
* control-plane pool meant a fan-out of many concurrent streams exhausted it and blocked
* control-plane calls. Sized separately because {@code WarmPool}'s cap is per-function,
* so total live streams across distinct functions is unbounded.
*/
@Produces
@StreamingDocker
@ApplicationScoped
public DockerClient streamingDockerClient() {
return buildDockerClient(buildClientConfig(),
validateStreamingMaxConnections(config.docker().streamingMaxConnections()), "streaming");
}
/**
* Builds the {@link DefaultDockerClientConfig} shared by both DockerClient beans (host and
* Docker-context resolution, optional Docker config path, and any TLS material the active
* context carries). The two beans differ only in connection pool size, never in how they
* reach the daemon.
*/
private DefaultDockerClientConfig buildClientConfig() {
ResolvedDockerConnection connection = resolveDockerConnection(config.docker(), System::getenv);
String dockerHost = connection.host();
LOG.infov("Creating DockerClient for host: {0} (max connections: {1})", dockerHost, maxConnections);
// createDefaultConfigBuilder() reads DOCKER_HOST directly from System.getenv() and passes
// it to withDockerHost(), which calls URI.create() immediately. If DOCKER_HOST is set
@@ -439,7 +482,12 @@ public class DockerClientProducer {
builder.withDockerCertPath(path.toString());
}
});
DefaultDockerClientConfig clientConfig = builder.build();
return builder.build();
}
private DockerClient buildDockerClient(DefaultDockerClientConfig clientConfig, int maxConnections, String role) {
LOG.infov("Creating {0} DockerClient pool (maxConnections={1}) for host: {2}",
role, maxConnections, clientConfig.getDockerHost());
ApacheDockerHttpClient httpClient = new ApacheDockerHttpClient.Builder()
.dockerHost(clientConfig.getDockerHost())
@@ -448,7 +496,22 @@ public class DockerClientProducer {
.responseTimeout(Duration.ofMinutes(5))
.build();
return DockerClientImpl.getInstance(clientConfig, httpClient);
return DockerClientImpl.getInstance(clientConfig, wrapForRole(httpClient, role));
}
/**
* Wraps the control-plane transport in {@link RetryingDockerHttpClient} so every short-lived
* docker call survives a transient socket drop; the streaming transport stays unwrapped,
* its requests (log-follow, exec output) hold hijacked or long-lived streams that must never
* be replayed, and its exec-start calls are the one request retrying could turn into a
* re-run command.
*/
static DockerHttpClient wrapForRole(DockerHttpClient transport, String role) {
if (!"control-plane".equals(role)) {
return transport;
}
LOG.info("Wrapping control-plane docker transport in transient-I/O retry");
return new RetryingDockerHttpClient(transport);
}
/**
@@ -0,0 +1,178 @@
package io.github.hectorvent.floci.core.common.docker;
import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.util.Locale;
/**
* Retry policy for docker daemon calls. Every docker command travels over the single shared
* socket; when many builds drive the daemon at once (e.g. an LZA Bootstrap stage fanning out
* ~15 CodeBuild actions) it intermittently drops a connection mid-call with a transient I/O
* error, {@code Broken pipe} or {@code Connection reset}, that docker-java surfaces wrapped
* in a {@link RuntimeException}. These clear on a retry; a genuine daemon rejection (a 4xx, a
* name conflict) does not and must surface immediately. Callers wrap idempotent docker calls
* (create container, copy archive in) so a transient blip does not fail the whole build.
*/
public final class DockerRetry {
private static final Logger LOG = Logger.getLogger(DockerRetry.class);
/**
* Upper bound on any single backoff sleep. Socket saturation from a fan-out build wave can
* persist for several seconds, so the backoff grows exponentially toward this cap to ride it
* out rather than exhausting a handful of sub-second retries against a still-busy socket.
*/
public static final long BACKOFF_CAP_MS = 8000L;
private DockerRetry() {
}
/**
* Exponential backoff for attempt {@code n} (1-based): {@code base * 2^(n-1)}, clamped to
* {@code cap}. A zero base yields zero (no sleep); the shift is bounded so it cannot overflow.
*/
public static long backoffDelay(int attempt, long baseMillis, long capMillis) {
if (baseMillis <= 0) {
return 0L;
}
int shift = Math.min(attempt - 1, 30);
long delay = baseMillis << shift;
if (delay < 0 || delay > capMillis) {
return capMillis;
}
return delay;
}
/**
* A failure raised on this host while preparing a docker call's payload (for example a tar
* writer that cannot read its source file), as opposed to one raised by the daemon
* transport. It is never retried, even when its cause is an {@link IOException}, because
* rebuilding the payload would fail the same way.
*/
public static final class LocalFailure extends RuntimeException {
public LocalFailure(String message, Throwable cause) {
super(message, cause);
}
}
/** A docker call that returns a value and may throw. */
@FunctionalInterface
public interface DockerCall<T> {
T run() throws Exception;
}
/** A docker call that returns nothing and may throw. */
@FunctionalInterface
public interface DockerOp {
void run() throws Exception;
}
/**
* True when {@code t} (or any cause in its chain) is a transient docker I/O failure worth
* retrying, an {@link IOException} such as {@code Broken pipe} / {@code Connection reset},
* possibly wrapped by docker-java in a {@link RuntimeException}.
*/
public static boolean isTransientIo(Throwable t) {
// InterruptedIOException covers both a genuine thread interruption (masking it would
// delay shutdown) and httpclient5's ConnectionRequestTimeoutException, the pool has no
// free connection lease after waiting the full request timeout, meaning the pool is
// exhausted rather than a socket blip. Retrying either just re-enters another wait and
// adds pressure to an already-starved pool, so both must be excluded from the general
// "any IOException is transient" rule below, checked over the WHOLE chain first, since
// an outer wrapper IOException would otherwise short-circuit the walk before it ever
// reaches an inner InterruptedIOException cause. java.net.SocketTimeoutException is ALSO
// an InterruptedIOException subtype but means something different (the daemon just took
// too long to answer, not that the pool is exhausted or the thread was interrupted) and
// must stay retryable, so it's excluded from this exclusion.
for (Throwable c = t; c != null; c = c.getCause()) {
if (c instanceof InterruptedIOException && !(c instanceof SocketTimeoutException)) {
return false;
}
if (c instanceof LocalFailure) {
return false;
}
if (c.getCause() == c) {
break;
}
}
for (Throwable c = t; c != null; c = c.getCause()) {
if (c instanceof IOException) {
return true;
}
String m = c.getMessage();
if (m != null) {
// Locale.ROOT: the default locale lowercases per the host's language, and a
// Turkish default turns "I" into a dotless i, so "Broken pipe" stops matching on
// exactly the hosts least likely to be tested. Matching both messages
// case-insensitively also covers daemons that vary the capitalisation.
String lower = m.toLowerCase(Locale.ROOT);
if (lower.contains("broken pipe") || lower.contains("connection reset")) {
return true;
}
}
if (c.getCause() == c) {
break;
}
}
return false;
}
/**
* Runs {@code call}, retrying up to {@code maxAttempts} times on a transient docker I/O
* error ({@link #isTransientIo}) with a capped exponential backoff between attempts
* ({@link #backoffDelay}), and returns its value. A non-transient failure is rethrown
* immediately. A {@link RuntimeException} is rethrown as-is; a checked exception is wrapped.
*/
public static <T> T call(int maxAttempts, long backoffMillis, DockerCall<T> call) {
if (maxAttempts < 1) {
// Zero or negative would run the call zero times and fall out of the loop returning
// nothing, turning a misconfiguration into a silent no-op rather than a failure.
throw new IllegalArgumentException("maxAttempts must be >= 1, got " + maxAttempts);
}
int attempt = 0;
while (true) {
attempt++;
try {
return call.run();
} catch (Exception e) {
if (e instanceof InterruptedException) {
Thread.currentThread().interrupt();
throw asUnchecked(e);
}
if (attempt >= maxAttempts || !isTransientIo(e)) {
throw asUnchecked(e);
}
LOG.warnv("Transient docker I/O error on attempt {0}/{1}, retrying: {2}",
attempt, maxAttempts, e.getMessage());
sleep(backoffDelay(attempt, backoffMillis, BACKOFF_CAP_MS));
}
}
}
/** Void variant of {@link #call}. */
public static void run(int maxAttempts, long backoffMillis, DockerOp op) {
call(maxAttempts, backoffMillis, () -> {
op.run();
return null;
});
}
private static RuntimeException asUnchecked(Exception e) {
return e instanceof RuntimeException re ? re : new RuntimeException(e);
}
private static void sleep(long millis) {
if (millis <= 0) {
return;
}
try {
Thread.sleep(millis);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException("Interrupted while backing off before a docker retry", ie);
}
}
}
@@ -0,0 +1,183 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.transport.DockerHttpClient;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Decorates a {@link DockerHttpClient} with the {@link DockerRetry} policy so every docker call
* travelling over the shared daemon socket survives a transient mid-call drop ({@code Broken
* pipe}, {@code Connection reset}) without each call site having to wrap itself.
*
* <p>The daemon drops connections under fan-out load (an LZA Bootstrap stage firing ~15 CodeBuild
* actions, a Prepare stage at six live containers), and docker-java surfaces the blip as
* {@code RuntimeException(IOException)} from inside {@code execute()}, which is exactly where
* this decorator sits. Guarding call sites one at a time was fixed three separate times
* ({@code createContainerCmd}, {@code startContainerCmd}, {@code ensureVolume}) while ~60 other
* docker call sites stayed bare; one guard at the transport boundary covers them all, including
* every call added later.
*
* <p>A request is only retried when replaying it cannot change semantics:
* <ul>
* <li>Its body, if any, must live in {@code bodyBytes()}, a plain {@code byte[]} the transport
* re-reads from scratch on every attempt. A request whose body is only available as a
* one-shot {@code InputStream} (the tar upload of {@code copyArchiveToContainerCmd}) may
* have been partially consumed by the failed attempt and is never replayed.</li>
* <li>It must not carry {@code hijackedInput()} (bidirectional attach streams).</li>
* <li>Its path must not contain {@code /exec}: {@code POST /exec/{id}/start} re-runs a shell
* command whose first run may have executed before the socket died, a worse bug than the
* one retrying fixes. The {@code contains} spelling (not {@code startsWith}) also covers
* exec-create ({@code POST /containers/{id}/exec}), where a replay would merely leak an
* unused exec ID; that conservative breadth costs nothing.</li>
* <li>It must not be an unnamed container create, a network create, a container restart or a
* network connect/disconnect: replaying those after a lost response duplicates a
* container, loses a network to a swallowed 409, restarts twice, or hits a spurious
* conflict.</li>
* </ul>
*
* <p>Idempotency of what a replay <em>means</em> stays the call site's job: docker answers a
* replayed start of an already-running container with HTTP 304 (raised above this transport as
* {@code NotModifiedException} and treated as success by the caller), and {@code ensureVolume}
* re-checks existence so a replayed create finds the volume the lost response landed.
*/
public final class RetryingDockerHttpClient implements DockerHttpClient {
static final String CONNECTION_HEADER = "Connection";
static final String CONNECTION_CLOSE = "close";
/**
* Mirrors the per-call-site policy this decorator replaces: six attempts at 500ms
* exponential backoff (capped by {@link DockerRetry#BACKOFF_CAP_MS}) rides out the
* several-second socket saturation a fan-out build wave causes.
*/
static final int MAX_ATTEMPTS = 6;
static final long BACKOFF_MS = 500L;
private final DockerHttpClient delegate;
private final int maxAttempts;
private final long backoffMillis;
public RetryingDockerHttpClient(DockerHttpClient delegate) {
this(delegate, MAX_ATTEMPTS, BACKOFF_MS);
}
RetryingDockerHttpClient(DockerHttpClient delegate, int maxAttempts, long backoffMillis) {
this.delegate = delegate;
this.maxAttempts = maxAttempts;
this.backoffMillis = backoffMillis;
}
@Override
public Response execute(Request request) {
Request effectiveRequest = withConnectionClose(request);
if (!isReplayable(effectiveRequest)) {
return delegate.execute(effectiveRequest);
}
return DockerRetry.call(maxAttempts, backoffMillis, () -> delegate.execute(effectiveRequest));
}
/**
* Retires every non-hijacked control-plane connection after its response instead of returning
* it to docker-java's pool. The upstream Apache transport disables stale-connection validation,
* so a Podman-closed pooled socket can otherwise be leased again and fail on its next write.
*
* <p>This is independent of retry eligibility: one-shot archive uploads and {@code /exec}
* requests must not be replayed, but their successfully completed connections must not be
* returned to the pool either. Hijacked requests remain unchanged because docker-java upgrades
* those connections and manages their lifetime as streams.
*/
static Request withConnectionClose(Request request) {
if (request.hijackedInput() != null) {
return request;
}
Map<String, String> headers = new LinkedHashMap<>();
request.headers().forEach((name, value) -> {
if (!CONNECTION_HEADER.equalsIgnoreCase(name)) {
headers.put(name, value);
}
});
headers.put(CONNECTION_HEADER, CONNECTION_CLOSE);
Request.Builder builder = Request.builder()
.method(request.method())
.path(request.path())
.headers(headers);
if (request.bodyBytes() != null) {
builder.bodyBytes(request.bodyBytes());
} else if (request.body() != null) {
builder.body(request.body());
}
return builder.build();
}
/**
* Whether re-executing {@code request} after a transient failure is semantically safe.
* {@code bodyBytes()} takes precedence over {@code body()} exactly as it does in the
* transport itself: when both are set the transport sends the bytes and never touches the
* stream, so the request replays cleanly.
*/
static boolean isReplayable(Request request) {
if (request.hijackedInput() != null) {
return false;
}
if (request.path().contains("/exec")) {
return false;
}
if (isNonIdempotentCreate(request) || isNonIdempotentAction(request)) {
return false;
}
return request.bodyBytes() != null || request.body() == null;
}
/**
* Bodyless POST actions whose replay after a lost response changes the outcome. A replayed
* {@code containers/{id}/restart} restarts the container a second time (extra downtime), and
* a replayed {@code networks/{id}/connect} or {@code disconnect} gets a conflict or not-found
* the caller does not expect for an operation that in fact succeeded.
*/
private static boolean isNonIdempotentAction(Request request) {
if (!"POST".equals(request.method())) {
return false;
}
String path = request.path();
int queryStart = path.indexOf('?');
String route = queryStart < 0 ? path : path.substring(0, queryStart);
return route.endsWith("/restart") || route.endsWith("/connect") || route.endsWith("/disconnect");
}
/**
* Creates whose replay after a lost response is harmful. A replayed {@code networks/create}
* gets a 409 that callers swallow, silently losing the network. A replayed unnamed
* {@code containers/create} makes a second, orphaned container; a named one is safe because
* the caller adopts the existing container on a 409.
*/
private static boolean isNonIdempotentCreate(Request request) {
if (!"POST".equals(request.method())) {
return false;
}
String path = request.path();
int queryStart = path.indexOf('?');
String route = queryStart < 0 ? path : path.substring(0, queryStart);
if (route.endsWith("/networks/create")) {
return true;
}
if (route.endsWith("/containers/create")) {
String query = queryStart < 0 ? "" : path.substring(queryStart + 1);
for (String param : query.split("&")) {
if (param.startsWith("name=")) {
return false;
}
}
return true;
}
return false;
}
@Override
public void close() throws IOException {
delegate.close();
}
}
@@ -0,0 +1,203 @@
package io.github.hectorvent.floci.core.common.docker;
import com.github.dockerjava.api.DockerClient;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicReference;
/**
* Retryable tar-copies into containers, shared by every service that pushes content into a
* container over the Docker API.
*
* <p>The transport-level retry ({@link RetryingDockerHttpClient}) must refuse to replay a
* one-shot {@code InputStream} body, the streamed tar bytes are gone after the first attempt,
* so copies retry here instead, where the whole operation (tar bytes or pipe, streamer thread,
* request) is rebuilt per attempt. Tar extract over the same path is idempotent, so a replay is
* safe; non-transient failures (daemon rejections) surface after a single attempt, unwrapped.
*/
public final class RetryingTarCopier {
private static final Logger LOG = Logger.getLogger(RetryingTarCopier.class);
static final int DEFAULT_MAX_ATTEMPTS = 6;
static final long DEFAULT_BACKOFF_MS = 500L;
/**
* Buffer for the tar-streaming pipe. The default {@link PipedInputStream} buffer is only 1KB,
* which forces a writer/reader thread hand-off (wait/notify) every 1KB. Streaming a ~90MB
* node_modules through that ran at ~0.5MB/s (≈3 min per cold start), pure synchronization
* thrash, not I/O. A large buffer lets the tar writer stream ahead so throughput is bound by
* the Docker daemon, not the pipe.
*/
private static final int TAR_PIPE_BUFFER_BYTES = 16 * 1024 * 1024;
private RetryingTarCopier() {
}
/** Writes one attempt's tar content; invoked freshly per attempt. */
@FunctionalInterface
public interface TarWriter {
void write(OutputStream out) throws IOException;
}
/** Copies an in-memory payload as a single-entry tar. */
public static void copyBytes(DockerClient docker, String containerId, String remotePath,
String entryName, byte[] content, int mode) {
copyBytes(docker, containerId, remotePath, entryName, content, mode,
DEFAULT_MAX_ATTEMPTS, DEFAULT_BACKOFF_MS);
}
public static void copyBytes(DockerClient docker, String containerId, String remotePath,
String entryName, byte[] content, int mode,
int maxAttempts, long backoffMillis) {
byte[] tar = singleFileTar(entryName, content, mode);
retry(entryName, containerId, maxAttempts, backoffMillis, () ->
docker.copyArchiveToContainerCmd(containerId)
.withRemotePath(remotePath)
.withTarInputStream(new ByteArrayInputStream(tar))
.exec());
}
/** Streams a file from disk as a single-entry tar, without buffering it in memory. */
public static void copyFile(DockerClient docker, String containerId, String remotePath,
String entryName, Path sourceFile, int mode) {
copyFile(docker, containerId, remotePath, entryName, sourceFile, mode,
DEFAULT_MAX_ATTEMPTS, DEFAULT_BACKOFF_MS);
}
public static void copyFile(DockerClient docker, String containerId, String remotePath,
String entryName, Path sourceFile, int mode,
int maxAttempts, long backoffMillis) {
copyStreamed(docker, containerId, remotePath, sourceFile.toString(), out -> {
try (TarArchiveOutputStream tar = newTarStream(out)) {
TarArchiveEntry entry = new TarArchiveEntry(entryName);
entry.setSize(Files.size(sourceFile));
entry.setMode(mode);
tar.putArchiveEntry(entry);
try (InputStream fis =Files.newInputStream(sourceFile)) {
fis.transferTo(tar);
}
tar.closeArchiveEntry();
}
}, maxAttempts, backoffMillis);
}
/**
* Streams arbitrary tar content produced by {@code tarWriter} through a fresh pipe and
* streamer thread per attempt. {@code label} names the payload in errors and thread names.
*/
public static void copyStreamed(DockerClient docker, String containerId, String remotePath,
String label, TarWriter tarWriter) {
copyStreamed(docker, containerId, remotePath, label, tarWriter,
DEFAULT_MAX_ATTEMPTS, DEFAULT_BACKOFF_MS);
}
public static void copyStreamed(DockerClient docker, String containerId, String remotePath,
String label, TarWriter tarWriter,
int maxAttempts, long backoffMillis) {
retry(label, containerId, maxAttempts, backoffMillis, () -> {
AtomicReference<Throwable> writerFailure = new AtomicReference<>();
try (PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos, TAR_PIPE_BUFFER_BYTES)) {
Thread streamer = new Thread(() -> {
try (pos) {
tarWriter.write(pos);
} catch (Throwable e) {
// Recorded and rechecked below instead of just logged: closing the pipe
// here without producing output looks like a clean, empty tar to the
// reader, the daemon accepts it and exec() below returns normally,
// so a writer failure (e.g. the source file went missing) would otherwise
// report success while nothing (or a truncated file) was actually copied.
writerFailure.set(e);
LOG.debugv("Tar streamer for {0} ended early: {1}", label, e.getMessage());
}
}, "tar-streamer-" + label);
streamer.start();
docker.copyArchiveToContainerCmd(containerId)
.withRemotePath(remotePath)
.withTarInputStream(pis)
.exec();
// Joined before the try-with-resources closes pos/pis on the way out: a real
// exec() only returns after consuming the tar to EOF, which the streamer causes
// by closing pos once it's done, so this never blocks in production, but closing
// pos out from under a still-writing streamer (as a mocked/short-circuited exec()
// would) turns its own write into a spurious "Pipe closed" failure.
streamer.join();
}
Throwable failure = writerFailure.get();
if (failure != null) {
// exec() already returned, so the daemon transport was fine: this is a local
// writer failure that rebuilding the copy would only repeat.
throw new DockerRetry.LocalFailure("Tar streamer for " + label + " failed: "
+ failure.getMessage(), failure);
}
});
}
/** Copies a host path, letting docker-java build the tar; rebuilt per attempt. */
public static void copyHostResource(DockerClient docker, String containerId, String remotePath,
String hostPath) {
copyHostResource(docker, containerId, remotePath, hostPath,
DEFAULT_MAX_ATTEMPTS, DEFAULT_BACKOFF_MS);
}
public static void copyHostResource(DockerClient docker, String containerId, String remotePath,
String hostPath, int maxAttempts, long backoffMillis) {
retry(hostPath, containerId, maxAttempts, backoffMillis, () ->
docker.copyArchiveToContainerCmd(containerId)
.withHostResource(hostPath)
.withRemotePath(remotePath)
.exec());
}
/** Single-entry tar bytes, reusable across attempts and callers. */
public static byte[] singleFileTar(String entryName, byte[] content, int mode) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = newTarStream(out)) {
TarArchiveEntry entry = new TarArchiveEntry(entryName);
entry.setSize(content.length);
entry.setMode(mode);
tar.putArchiveEntry(entry);
tar.write(content);
tar.closeArchiveEntry();
}
return out.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("Could not build in-memory tar for " + entryName, e);
}
}
/** GNU long names + star big numbers so any path length and file size survive the archive. */
public static TarArchiveOutputStream newTarStream(OutputStream out) {
TarArchiveOutputStream tar = new TarArchiveOutputStream(out);
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
return tar;
}
private interface CopyAttempt {
void run() throws Exception;
}
private static void retry(String label, String containerId, int maxAttempts, long backoffMillis,
CopyAttempt attempt) {
try {
DockerRetry.run(maxAttempts, backoffMillis, attempt::run);
} catch (Exception e) {
throw new RuntimeException("Failed to copy " + label + " into container "
+ containerId + ": " + e.getMessage(), e);
}
}
}
@@ -0,0 +1,24 @@
package io.github.hectorvent.floci.core.common.docker;
import jakarta.inject.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* CDI qualifier for the DockerClient dedicated to long-lived streaming operations,
* container log-follow ({@link ContainerLogStreamer}). Exec-output and container-wait
* streams still use the control-plane client. These calls occupy a connection pool
* slot for a container's entire lifetime, so they must not share a pool
* with short-lived control-plane calls (create/start/stop/remove/copyArchive): a fan-out
* of many long-lived streams would otherwise starve the control-plane calls out of a
* lease until httpclient5's connection-request timeout fires. See
* {@link DockerClientProducer} for the two beans this qualifier distinguishes.
*/
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD})
public @interface StreamingDocker {
}
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType;
import io.github.hectorvent.floci.services.ec2.model.Instance;
@@ -32,11 +33,8 @@ import com.github.dockerjava.api.model.MountType;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
@@ -1494,11 +1492,8 @@ public class Ec2ContainerManager {
// Copy authorized_keys via docker cp
String keyContent = publicKey.trim() + "\n";
byte[] tar = buildSingleFileTar("authorized_keys", keyContent.getBytes(StandardCharsets.UTF_8), 0600);
dockerClient.copyArchiveToContainerCmd(containerId)
.withRemotePath("/root/.ssh")
.withTarInputStream(new ByteArrayInputStream(tar))
.exec();
RetryingTarCopier.copyBytes(dockerClient, containerId, "/root/.ssh",
"authorized_keys", keyContent.getBytes(StandardCharsets.UTF_8), 0600);
execInContainer(containerId, new String[]{"chmod", "600", "/root/.ssh/authorized_keys"}, 5);
LOG.infov("Injected SSH public key into container {0}", containerId);
@@ -1764,8 +1759,4 @@ public class Ec2ContainerManager {
static Optional<String> preferredMetadataSourceIp(Map<String, ContainerNetwork> networks) {
return Ec2MetadataProxy.preferredMetadataSourceIp(networks);
}
private byte[] buildSingleFileTar(String filename, byte[] content, int mode) throws IOException {
return UserDataPipeline.buildSingleFileTar(filename, content, mode);
}
}
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.PortAllocator;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.core.common.docker.UserDataPipeline;
import io.github.hectorvent.floci.services.ec2.ClusterNodeInstanceProvider;
import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog;
@@ -1419,11 +1420,8 @@ public class EksClusterManager
*/
private void copyWebhookIntoContainer(String containerId, String localFile, String clusterName) {
try {
lifecycleManager.getDockerClient()
.copyArchiveToContainerCmd(containerId)
.withHostResource(localFile)
.withRemotePath(WEBHOOK_CONFIG_DIR)
.exec();
RetryingTarCopier.copyHostResource(lifecycleManager.getDockerClient(), containerId,
WEBHOOK_CONFIG_DIR, localFile);
} catch (Exception e) {
LOG.warnv("EKS token-webhook may not authenticate for cluster {0}: could not copy kubeconfig "
+ "into the k3s container: {1}", clusterName, e.getMessage());
@@ -1851,11 +1849,8 @@ public class EksClusterManager
writeLocalCopy(Paths.get(config.services().eks().dataPath(), "registries", clusterName,
"registries.yaml"), content, clusterName);
try {
lifecycleManager.getDockerClient()
.copyArchiveToContainerCmd(containerId)
.withTarInputStream(new ByteArrayInputStream(tarSingleFile(REGISTRIES_TAR_ENTRY, content)))
.withRemotePath("/etc")
.exec();
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, "/etc",
REGISTRIES_TAR_ENTRY, content.getBytes(StandardCharsets.UTF_8), 0644);
LOG.infov("Injected ECR registry mirror ({0}) into k3s cluster {1}", endpoint, clusterName);
} catch (Exception e) {
LOG.warnv("EKS cluster {0} gets no ECR registry mirror: could not copy registries.yaml "
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLogStreamer;
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.DockerHostResolver;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.services.ecr.registry.EcrRegistryManager;
import io.github.hectorvent.floci.services.iam.model.SessionCreds;
@@ -1229,20 +1230,19 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
}
/**
* Buffer for the tar-streaming pipe. The default {@link java.io.PipedInputStream} buffer is
* only 1KB, which forces a writer/reader thread hand-off (wait/notify) every 1KB. Streaming a
* ~90MB node_modules through that ran at ~0.5MB/s (≈3 min per cold start) — pure synchronization
* thrash, not I/O. A large buffer lets the tar writer stream ahead so throughput is bound by the
* Docker daemon, not the pipe.
*/
private static final int TAR_PIPE_BUFFER_BYTES = 16 * 1024 * 1024;
@FunctionalInterface
interface DirectoryTarWriter {
void write(Path sourceDir, OutputStream out) throws IOException;
}
/**
* See {@link RetryingTarCopier}: these copies retry at the call site because the transport
* seam cannot replay a one-shot {@code InputStream} body. A failure throws so launch() cleans
* up the half-built container instead of leaking it.
*/
static final int COPY_MAX_ATTEMPTS = 6;
static final long COPY_RETRY_BACKOFF_MS = 500L;
private void copyDirToContainer(DockerClient dockerClient, String containerId,
Path sourceDir, String remotePath, String functionName) {
copyDirToContainer(dockerClient, containerId, sourceDir, remotePath, functionName,
@@ -1253,7 +1253,14 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
Path sourceDir, String remotePath, String functionName,
DirectoryTarWriter tarWriter) {
copyDirToContainer(dockerClient, containerId, sourceDir, remotePath, functionName,
tarWriter, false);
tarWriter, false, COPY_MAX_ATTEMPTS, COPY_RETRY_BACKOFF_MS);
}
void copyDirToContainer(DockerClient dockerClient, String containerId,
Path sourceDir, String remotePath, String functionName,
int maxAttempts, long backoffMillis) {
copyDirToContainer(dockerClient, containerId, sourceDir, remotePath, functionName,
ContainerLauncher::createTarFromDir, false, maxAttempts, backoffMillis);
}
private void copyDirToContainerStrict(DockerClient dockerClient, String containerId,
@@ -1266,93 +1273,79 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
Path sourceDir, String remotePath, String functionName,
DirectoryTarWriter tarWriter) {
copyDirToContainer(dockerClient, containerId, sourceDir, remotePath, functionName,
tarWriter, true);
tarWriter, true, COPY_MAX_ATTEMPTS, COPY_RETRY_BACKOFF_MS);
}
private static void copyDirToContainer(DockerClient dockerClient, String containerId,
Path sourceDir, String remotePath, String functionName,
DirectoryTarWriter tarWriter, boolean failOnTarFailure) {
DirectoryTarWriter tarWriter, boolean failOnTarFailure,
int maxAttempts, long backoffMillis) {
// No per-copy gating here: the heavy /var/task populate for large code already holds a
// populateSemaphore permit; small-code direct copies and layer copies are light enough
// to run unthrottled.
try (java.io.PipedOutputStream pos = new java.io.PipedOutputStream();
java.io.PipedInputStream pis = new java.io.PipedInputStream(pos, TAR_PIPE_BUFFER_BYTES)) {
AtomicReference<IOException> tarFailure = new AtomicReference<>();
Thread tarStreamer = new Thread(() -> {
try (pos) {
tarWriter.write(sourceDir, pos);
} catch (IOException e) {
if (failOnTarFailure) {
tarFailure.set(e);
} else {
LOG.errorv("Failed to stream directory tar for function {0}: {1}",
functionName, e.getMessage());
}
}
}, "tar-streamer-dir-" + functionName);
tarStreamer.start();
dockerClient.copyArchiveToContainerCmd(containerId)
.withRemotePath(remotePath)
.withTarInputStream(pis)
.exec();
if (failOnTarFailure) {
waitForTarStreamer(tarStreamer, tarFailure, functionName, sourceDir);
AtomicReference<IOException> tarFailure = new AtomicReference<>();
try {
RetryingTarCopier.copyStreamed(dockerClient, containerId, remotePath,
"dir-" + functionName, out -> {
tarFailure.set(null);
try {
tarWriter.write(sourceDir, out);
} catch (IOException e) {
tarFailure.set(e);
if (!failOnTarFailure) {
LOG.errorv("Failed to stream directory tar for function {0}: {1}",
functionName, e.getMessage());
}
throw e;
}
},
maxAttempts, backoffMillis);
} catch (RuntimeException e) {
// RetryingTarCopier always surfaces a tar-producer failure it captured (so a writer
// failure the daemon happened to accept doesn't masquerade as success), wrapped in its
// own generic message. A distinct docker-level failure (the daemon itself rejecting the
// stream, not our own writer) isn't ours to reinterpret and must propagate as-is.
IOException producerFailure = tarFailure.get();
if (!isCausedBy(e, producerFailure)) {
throw e;
}
LOG.debugv("Copied directory {0} into container {1} at {2}", sourceDir, containerId, remotePath);
} catch (Exception e) {
// Fail loudly so launch() cleans up the half-built container instead of leaking it.
if (!failOnTarFailure) {
LOG.debugv("Ignoring tolerated tar-producer failure for function {0}", functionName);
return;
}
IOException cause = new IOException("Failed to stream tar for function " + functionName
+ " from " + sourceDir, producerFailure);
throw new RuntimeException("Failed to copy directory " + sourceDir + " into container "
+ containerId + " for function " + functionName + ": " + e.getMessage(), e);
+ containerId + " for function " + functionName + ": " + cause.getMessage(), cause);
}
LOG.debugv("Copied directory {0} into container {1} at {2}", sourceDir, containerId, remotePath);
}
/** True if {@code target} appears by reference in {@code thrown}'s cause chain. */
private static boolean isCausedBy(Throwable thrown, Throwable target) {
if (target == null) {
return false;
}
for (Throwable t = thrown; t != null; t = t.getCause()) {
if (t == target) {
return true;
}
}
return false;
}
private void copyFileToContainer(DockerClient dockerClient, String containerId,
Path sourceFile, String remotePath, String entryName, String functionName) {
try (java.io.PipedOutputStream pos = new java.io.PipedOutputStream();
java.io.PipedInputStream pis = new java.io.PipedInputStream(pos, TAR_PIPE_BUFFER_BYTES)) {
new Thread(() -> {
try (TarArchiveOutputStream tar = newTarStream(pos)) {
TarArchiveEntry entry = new TarArchiveEntry(entryName);
entry.setSize(Files.size(sourceFile));
entry.setMode(0755);
tar.putArchiveEntry(entry);
try (var fis = Files.newInputStream(sourceFile)) {
fis.transferTo(tar);
}
tar.closeArchiveEntry();
} catch (IOException e) {
LOG.errorv("Failed to stream file tar for function {0}: {1}", functionName, e.getMessage());
}
}, "tar-streamer-file-" + functionName).start();
dockerClient.copyArchiveToContainerCmd(containerId)
.withRemotePath(remotePath)
.withTarInputStream(pis)
.exec();
LOG.debugv("Copied file {0} as {1} into container {2} at {3}", sourceFile, entryName, containerId, remotePath);
} catch (Exception e) {
throw new RuntimeException("Failed to copy file " + sourceFile + " into container "
+ containerId + " for function " + functionName + ": " + e.getMessage(), e);
}
copyFileToContainer(dockerClient, containerId, sourceFile, remotePath, entryName, functionName,
COPY_MAX_ATTEMPTS, COPY_RETRY_BACKOFF_MS);
}
private static void waitForTarStreamer(Thread tarStreamer, AtomicReference<IOException> tarFailure,
String functionName, Path sourcePath) throws IOException {
try {
tarStreamer.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Interrupted while streaming tar for function " + functionName
+ " from " + sourcePath, e);
}
IOException failure = tarFailure.get();
if (failure != null) {
throw new IOException("Failed to stream tar for function " + functionName
+ " from " + sourcePath, failure);
}
void copyFileToContainer(DockerClient dockerClient, String containerId,
Path sourceFile, String remotePath, String entryName, String functionName,
int maxAttempts, long backoffMillis) {
RetryingTarCopier.copyFile(dockerClient, containerId, remotePath, entryName, sourceFile,
0755, maxAttempts, backoffMillis);
LOG.debugv("Copied file {0} as {1} into container {2} at {3}", sourceFile, entryName, containerId, remotePath);
}
private static boolean isProvidedRuntime(String runtime) {
@@ -1530,7 +1523,7 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
* are preserved without truncation.
*/
private static void createTarFromDir(Path sourceDir, OutputStream out) throws IOException {
try (TarArchiveOutputStream tar = newTarStream(out);
try (TarArchiveOutputStream tar = RetryingTarCopier.newTarStream(out);
var stream = Files.walk(sourceDir)) {
for (Path path : (Iterable<Path>) stream::iterator) {
if (Files.isDirectory(path)) {
@@ -1548,11 +1541,4 @@ public class ContainerLauncher implements LambdaRuntimeLauncher {
}
}
}
private static TarArchiveOutputStream newTarStream(OutputStream out) {
TarArchiveOutputStream tar = new TarArchiveOutputStream(out);
tar.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
tar.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
return tar;
}
}
@@ -10,17 +10,15 @@ import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager.C
import io.github.hectorvent.floci.core.common.docker.ContainerSpec;
import io.github.hectorvent.floci.core.common.docker.ContainerStorageHelper;
import io.github.hectorvent.floci.core.common.docker.LaunchedContainerAwsEnv;
import io.github.hectorvent.floci.core.common.docker.RetryingTarCopier;
import io.github.hectorvent.floci.services.mwaa.model.Environment;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.exception.NotFoundException;
import com.github.dockerjava.api.model.ContainerNetwork;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.jboss.logging.Logger;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
@@ -693,11 +691,8 @@ public class MwaaEnvironmentManager {
return false;
}
try {
lifecycleManager.getDockerClient()
.copyArchiveToContainerCmd(containerId)
.withTarInputStream(new ByteArrayInputStream(tarSingleFile(relativePath, content)))
.withRemotePath(remoteDir)
.exec();
RetryingTarCopier.copyBytes(lifecycleManager.getDockerClient(), containerId, remoteDir,
relativePath, content, 0644);
return true;
} catch (Exception e) {
LOG.warnv("Could not copy {0} into MWAA container {1}: {2}", relativePath, containerId, e.getMessage());
@@ -705,23 +700,6 @@ public class MwaaEnvironmentManager {
}
}
private static byte[] tarSingleFile(String entryName, byte[] content) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (TarArchiveOutputStream tar = new TarArchiveOutputStream(out)) {
TarArchiveEntry entry = new TarArchiveEntry(entryName);
entry.setSize(content.length);
entry.setMode(0644);
tar.putArchiveEntry(entry);
tar.write(content);
tar.closeArchiveEntry();
}
return out.toByteArray();
} catch (IOException e) {
throw new IllegalStateException("Could not build in-memory tar for " + entryName, e);
}
}
ContainerExec.Result execInContainer(String containerId, String[] cmd) throws Exception {
return ContainerExec.run(lifecycleManager.getDockerClient(), containerId, cmd, 30).throwIfTimedOut(containerId);
}