mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(docker): open long-lived exec streams on the streaming Docker pool (#8950)
* fix(docker): open long-lived exec streams on the streaming Docker pool CodeBuild build phases, SSM run commands, ECS Exec sessions, the EKS audit log follower, ECR garbage collection, EC2 and EKS user data scripts and EMR bootstrap actions held a control-plane connection for as long as their exec ran, so enough of them could leave the short Docker calls waiting for a lease. Their exec starts now use the @StreamingDocker client: ContainerLifecycleManager exposes getStreamingDockerClient(), CodeBuildRunner and SsmDirectCommandExecutor inject it, and UserDataPipeline and ContainerExec take it beside the control-plane client. Neither transport replays an exec start and both exempt it from the response timeout, so only the pool changes; creating, inspecting and resizing an exec stay on the control plane. The connection pool docs, the environment variable tables, the application.yml comment and the javadocs now name these streams. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * fix(codebuild): close a timed-out phase's output stream, and drop the test-only constructor runPhase discarded the callback of its exec start, so a phase that timed out or was interrupted left its output stream open, now holding a streaming connection for as long as the command ran on; it is now closed. ContainerLifecycleManager's public four-argument constructor existed only so tests could pass one client for both pools; it goes, and those tests name both clients through the injected constructor. Signed-off-by: Hector Ventura <hectorvent@gmail.com> * test(docker): give the reachability test the streaming client the constructor now takes Signed-off-by: Hector Ventura <hectorvent@gmail.com> #8951 added ContainerLifecycleManagerReachabilityTest with the four-argument constructor this branch removes, so the two no longer compiled together on main. --------- Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
1 parent
aabe2247c5
commit
ad0e47910f
54 files changed
+322
-113
No files matched your search
@@ -52,9 +52,9 @@ The entrypoint needs to start as root to read the socket's group and to honour t
|
||||
|
||||
## Connection Pool
|
||||
|
||||
Floci's short Docker calls (create, start, stop, remove and the like) go through one client with a bounded connection pool. A few streams also hold a connection from it for as long as they run: CodeBuild phase commands, EKS audit log followers and ECS Exec sessions. When long-lived connections fill the pool, every other Docker call waits for one to free up, and Floci stops making progress.
|
||||
Floci's short Docker calls (create, start, stop, remove and the like) go through one client with a bounded connection pool. When it is full, every other Docker call waits for a connection to free up, and Floci stops making progress. Streams that stay open while they run use the separate streaming pool below, so this pool only fills under a burst of short calls.
|
||||
|
||||
The default is 1024 connections. Raise it if you run many CodeBuild builds or ECS Exec sessions at the same time:
|
||||
The default is 1024 connections:
|
||||
|
||||
```yaml
|
||||
floci:
|
||||
@@ -64,7 +64,7 @@ floci:
|
||||
|
||||
Environment variable: `FLOCI_DOCKER_MAX_CONNECTIONS`
|
||||
|
||||
Streams that stay open for as long as a container runs use a second, separate pool, so they can never starve create, start, stop and remove calls. Each Lambda container holds two of these (its log stream and the watcher that notices its runtime exiting) plus one per Lambda extension, and other containers' log streams use it too. The default of 2048 covers the 500 concurrent Lambda containers the default [Runtime API port range](../services/lambda.md#configuration) allows, with two extensions each. Raise it if you widen that range or run many other containers at the same time. It follows the same rule (at least 1):
|
||||
Streams that stay open for as long as a container or a command runs use a second, separate pool, so they can never starve create, start, stop and remove calls. Each Lambda container holds two of these (its log stream and the watcher that notices its runtime exiting) plus one per Lambda extension; other containers' log streams use it too, and so does the output of each long-running command: CodeBuild build phases, SSM run commands, ECS Exec sessions, EKS audit log followers, ECR garbage collection, EC2 and EKS user data and EMR bootstrap actions. The default of 2048 covers the 500 concurrent Lambda containers the default [Runtime API port range](../services/lambda.md#configuration) allows, with two extensions each. Raise it if you widen that range, or run many builds, sessions or other containers at the same time. It follows the same rule (at least 1):
|
||||
|
||||
```yaml
|
||||
floci:
|
||||
@@ -365,8 +365,8 @@ caller keeps its existing failure handling after retries are exhausted.
|
||||
|---|---|---|
|
||||
| `FLOCI_DOCKER_DOCKER_HOST` | `unix:///var/run/docker.sock` | Docker daemon socket |
|
||||
| `FLOCI_DOCKER_DOCKER_CONFIG_PATH` | _(unset)_ | Path to directory containing Docker's `config.json` |
|
||||
| `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls, plus CodeBuild phase commands, EKS audit log followers and ECS Exec sessions |
|
||||
| `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `2048` | Connection pool size for streams that last a container's lifetime. Each live Lambda container holds two (log stream and exit watcher) plus one per extension |
|
||||
| `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls |
|
||||
| `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `2048` | Connection pool size for streams that last a container's lifetime or a long command's run. Each live Lambda container holds two (log stream and exit watcher) plus one per extension, and each CodeBuild phase, SSM command, ECS Exec session, EKS audit follower, user data script and EMR bootstrap action one |
|
||||
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__SERVER` | _(unset)_ | Registry hostname for credential entry 0 |
|
||||
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__USERNAME` | _(unset)_ | Username for credential entry 0 |
|
||||
| `FLOCI_DOCKER_REGISTRY_CREDENTIALS_0__PASSWORD` | _(unset)_ | Password for credential entry 0 |
|
||||
|
||||
@@ -146,8 +146,8 @@ This foundation release provides opt-in security-group filtering for EC2 Docker
|
||||
| `FLOCI_NETWORK_SECURITY_GROUP_ENFORCEMENT_HELPER_IMAGE` | `floci/network-helper:local` | Linux helper image containing nftables; Floci builds the default image locally when missing |
|
||||
| `FLOCI_DOCKER_DOCKER_HOST` | `unix:///var/run/docker.sock` | Docker daemon socket path or TCP address |
|
||||
| `FLOCI_DOCKER_DOCKER_CONFIG_PATH` | _(none)_ | Path to a directory containing Docker's `config.json` for registry auth |
|
||||
| `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls, plus CodeBuild phase commands, EKS audit log followers and ECS Exec sessions. See [Docker Configuration](docker.md#connection-pool) |
|
||||
| `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `2048` | Connection pool size for streams that last a container's lifetime, kept apart from the main pool so they never starve create, start, stop and remove. Each live Lambda container holds two (log stream and exit watcher) plus one per extension. See [Docker Configuration](docker.md#connection-pool) |
|
||||
| `FLOCI_DOCKER_MAX_CONNECTIONS` | `1024` | Connection pool size for Floci's short Docker calls. See [Docker Configuration](docker.md#connection-pool) |
|
||||
| `FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS` | `2048` | Connection pool size for streams that last a container's lifetime or a long command's run, kept apart from the main pool so they never starve create, start, stop and remove. Each live Lambda container holds two (log stream and exit watcher) plus one per extension, and each CodeBuild phase, SSM command, ECS Exec session, EKS audit follower, user data script and EMR bootstrap action one. See [Docker Configuration](docker.md#connection-pool) |
|
||||
| `FLOCI_DOCKER_POOL_GAUGE_INTERVAL_SECONDS` | `60` | Seconds between the log lines that report each Docker pool's leased, available and pending connections and its open streams, written only while a pool is in use; `0` turns them off. See [Docker Configuration](docker.md#connection-pool) |
|
||||
| `FLOCI_DOCKER_IMAGE_REGISTRY_BASE` | _(none)_ | Optional registry/repository base for every Docker image Floci launches. When set, `postgres:16-alpine` resolves as `<base>/postgres:16-alpine` and `public.ecr.aws/docker/library/ubuntu:24.04` resolves as `<base>/public.ecr.aws/docker/library/ubuntu:24.04`. An image in a registry on `localhost` or a loopback address, Floci's own ECR among them, is launched as it is |
|
||||
| `FLOCI_DOCKER_LOG_MAX_SIZE` | `10m` | Log rotation max size for spawned containers (e.g. `10m`, `1g`) |
|
||||
|
||||
@@ -4392,11 +4392,10 @@ public interface EmulatorConfig {
|
||||
|
||||
/**
|
||||
* Size of the connection pool behind the shared Docker client. Every short Docker call
|
||||
* leases a connection from it, and a few streams hold one for as long as they run:
|
||||
* CodeBuild phase execs, EKS audit followers and ECS Exec sessions. The streams a Lambda
|
||||
* container holds for its whole lifetime live in the separate streaming pool. Once
|
||||
* 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.
|
||||
* leases a connection from it; streams that stay open while a container or a command runs
|
||||
* live in the separate streaming pool. Once this pool is full, 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. Connections are opened on demand, so a
|
||||
* small stack never approaches the limit.
|
||||
@@ -4406,8 +4405,11 @@ public interface EmulatorConfig {
|
||||
|
||||
/**
|
||||
* Connection pool size for the {@code @StreamingDocker} DockerClient, sized for the
|
||||
* long-lived streams that occupy a slot for a container's entire lifetime: container log
|
||||
* follow, and for each Lambda container its exit watcher and one exec per extension.
|
||||
* long-lived streams that occupy a slot for a container's entire lifetime or a long
|
||||
* command's run: container log follow, for each Lambda container its exit watcher and one
|
||||
* exec per extension, and the output of each CodeBuild phase, SSM command, ECS Exec
|
||||
* session, EKS audit follower, ECR garbage collection, user data script and EMR bootstrap
|
||||
* action.
|
||||
* 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.
|
||||
|
||||
@@ -91,6 +91,18 @@ public final class ContainerExec {
|
||||
*/
|
||||
public static Result run(DockerClient dockerClient, String containerId, String[] cmd, List<String> env,
|
||||
int timeoutSeconds, OutputStream stdout, OutputStream stderr) {
|
||||
return run(dockerClient, dockerClient, containerId, cmd, env, timeoutSeconds, stdout, stderr);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #run(DockerClient, String, String[], List, int, OutputStream, OutputStream)}, the command's
|
||||
* output read over {@code streamingDockerClient}: for a command that may run for a long time, such as a
|
||||
* user's script, so its output stream holds a streaming lease rather than a control-plane one. The exec
|
||||
* is still created and inspected on {@code dockerClient}.
|
||||
*/
|
||||
public static Result run(DockerClient dockerClient, DockerClient streamingDockerClient, String containerId,
|
||||
String[] cmd, List<String> env, int timeoutSeconds, OutputStream stdout,
|
||||
OutputStream stderr) {
|
||||
ExecCreateCmd create = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
.withAttachStdout(true)
|
||||
@@ -118,7 +130,7 @@ public final class ContainerExec {
|
||||
}
|
||||
}
|
||||
};
|
||||
dockerClient.execStartCmd(execId).exec(callback);
|
||||
streamingDockerClient.execStartCmd(execId).exec(callback);
|
||||
|
||||
try {
|
||||
// docker-java closes the attach stream on completion, timeout, or interruption.
|
||||
|
||||
@@ -94,6 +94,7 @@ public class ContainerLifecycleManager {
|
||||
private static final String LOOPBACK_HOST_IP = "127.0.0.1";
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
private final DockerClient streamingDockerClient;
|
||||
private final ImageCacheService imageCacheService;
|
||||
private final ContainerDetector containerDetector;
|
||||
private final EmulatorConfig config;
|
||||
@@ -112,11 +113,12 @@ public class ContainerLifecycleManager {
|
||||
|
||||
@Inject
|
||||
public ContainerLifecycleManager(DockerClient dockerClient,
|
||||
@StreamingDocker DockerClient streamingDockerClient,
|
||||
ImageCacheService imageCacheService,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config) {
|
||||
this(dockerClient, imageCacheService, containerDetector, config,
|
||||
RetryingTarCopier.DEFAULT_BACKOFF_MS);
|
||||
this(dockerClient, streamingDockerClient, imageCacheService, containerDetector, config,
|
||||
RetryingTarCopier.DEFAULT_BACKOFF_MS, System::nanoTime, TimeUnit.NANOSECONDS::sleep);
|
||||
}
|
||||
|
||||
ContainerLifecycleManager(DockerClient dockerClient,
|
||||
@@ -135,7 +137,20 @@ public class ContainerLifecycleManager {
|
||||
long archiveRetryBackoffMillis,
|
||||
LongSupplier nanoTime,
|
||||
CreateWait createWait) {
|
||||
this(dockerClient, dockerClient, imageCacheService, containerDetector, config, archiveRetryBackoffMillis,
|
||||
nanoTime, createWait);
|
||||
}
|
||||
|
||||
private ContainerLifecycleManager(DockerClient dockerClient,
|
||||
DockerClient streamingDockerClient,
|
||||
ImageCacheService imageCacheService,
|
||||
ContainerDetector containerDetector,
|
||||
EmulatorConfig config,
|
||||
long archiveRetryBackoffMillis,
|
||||
LongSupplier nanoTime,
|
||||
CreateWait createWait) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.streamingDockerClient = streamingDockerClient;
|
||||
this.imageCacheService = imageCacheService;
|
||||
this.containerDetector = containerDetector;
|
||||
this.config = config;
|
||||
@@ -1606,6 +1621,17 @@ public class ContainerLifecycleManager {
|
||||
return dockerClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the {@link StreamingDocker} client, for a request that holds its connection for as long
|
||||
* as what it follows, so it never takes a control-plane lease: an exec start whose output may run
|
||||
* long, a container wait, or a followed log. Only those belong here: the streaming transport
|
||||
* replays nothing but a container wait after a dropped connection, while the control-plane one
|
||||
* also replays reads.
|
||||
*/
|
||||
public DockerClient getStreamingDockerClient() {
|
||||
return streamingDockerClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns {@code true} if the container runtime (Docker, Moby, or Podman) has a volume
|
||||
* with the given name. The volume does not need to be attached to the current container.
|
||||
|
||||
@@ -438,7 +438,6 @@ public class DockerClientProducer {
|
||||
* short-lived call in Floci. Kept on its own connection pool, separate from the
|
||||
* {@link StreamingDocker} bean, so long-lived streams can never occupy every lease in this
|
||||
* pool and starve these short calls until httpclient5's connection-request timeout fires.
|
||||
* CodeBuild phase execs, EKS audit followers and ECS Exec sessions still use this pool.
|
||||
*/
|
||||
@Produces
|
||||
@ApplicationScoped
|
||||
@@ -449,7 +448,8 @@ public class DockerClientProducer {
|
||||
|
||||
/**
|
||||
* Streaming DockerClient: container log-follow ({@link ContainerLogStreamer}), Lambda
|
||||
* extension execs and Lambda exit watchers, and Lambda Web attach streams. Each
|
||||
* extension execs and Lambda exit watchers, Lambda Web attach streams, and the output of
|
||||
* long-running execs (CodeBuild phases, SSM run commands, ECS Exec sessions, EKS audit log followers, ECR garbage collection, EC2 and EKS user data and EMR bootstrap actions). 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,
|
||||
|
||||
@@ -10,7 +10,9 @@ import java.lang.annotation.Target;
|
||||
/**
|
||||
* CDI qualifier for the DockerClient dedicated to long-lived streaming operations:
|
||||
* container log-follow ({@link ContainerLogStreamer}), Lambda extension execs and exit
|
||||
* watchers, and Lambda Web attach streams. These calls occupy a connection pool
|
||||
* watchers, Lambda Web attach streams, and the output of long-running execs (CodeBuild phases,
|
||||
* SSM run commands, ECS Exec sessions, EKS audit log followers, ECR garbage collection, EC2 and EKS
|
||||
* user data, EMR bootstrap actions). 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
|
||||
|
||||
@@ -215,8 +215,14 @@ public final class UserDataPipeline {
|
||||
return text;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param dockerClient copies the scripts in, creates and inspects their execs
|
||||
* @param streamingDockerClient carries each script's output, a stream that stays open for as long as the
|
||||
* script runs, so it holds a streaming lease rather than a control-plane one
|
||||
*/
|
||||
public static ExecutionResult executeUserData(
|
||||
DockerClient dockerClient,
|
||||
DockerClient streamingDockerClient,
|
||||
String containerId,
|
||||
String contextDescription,
|
||||
String userData,
|
||||
@@ -224,12 +230,13 @@ public final class UserDataPipeline {
|
||||
Consumer<String> outputLineConsumer,
|
||||
Set<ResultCallback<Frame>> activeCallbacks
|
||||
) {
|
||||
return executeUserData(dockerClient, containerId, contextDescription, userData, timeout,
|
||||
return executeUserData(dockerClient, streamingDockerClient, containerId, contextDescription, userData, timeout,
|
||||
outputLineConsumer, activeCallbacks, RetryingTarCopier.DEFAULT_BACKOFF_MS);
|
||||
}
|
||||
|
||||
static ExecutionResult executeUserData(
|
||||
DockerClient dockerClient,
|
||||
DockerClient streamingDockerClient,
|
||||
String containerId,
|
||||
String contextDescription,
|
||||
String userData,
|
||||
@@ -238,7 +245,7 @@ public final class UserDataPipeline {
|
||||
Set<ResultCallback<Frame>> activeCallbacks,
|
||||
long archiveRetryBackoffMillis
|
||||
) {
|
||||
if (dockerClient == null || containerId == null || containerId.isBlank()) {
|
||||
if (dockerClient == null || streamingDockerClient == null || containerId == null || containerId.isBlank()) {
|
||||
return ExecutionResult.skipped("No container available");
|
||||
}
|
||||
List<String> shellScripts = extractShellScripts(userData);
|
||||
@@ -252,7 +259,8 @@ public final class UserDataPipeline {
|
||||
int partCount = shellScripts.size();
|
||||
String scriptContent = shellScripts.get(i);
|
||||
ExecutionResult partResult = executeSingleScript(
|
||||
dockerClient, containerId, contextDescription, scriptContent, partNumber, partCount,
|
||||
dockerClient, streamingDockerClient, containerId, contextDescription, scriptContent, partNumber,
|
||||
partCount,
|
||||
effectiveTimeout, outputLineConsumer, activeCallbacks, archiveRetryBackoffMillis);
|
||||
if (!partResult.isSuccess()) {
|
||||
return partResult;
|
||||
@@ -263,6 +271,7 @@ public final class UserDataPipeline {
|
||||
|
||||
private static ExecutionResult executeSingleScript(
|
||||
DockerClient dockerClient,
|
||||
DockerClient streamingDockerClient,
|
||||
String containerId,
|
||||
String contextDescription,
|
||||
String scriptContent,
|
||||
@@ -345,7 +354,7 @@ public final class UserDataPipeline {
|
||||
}
|
||||
|
||||
try {
|
||||
dockerClient.execStartCmd(execId).exec(callback);
|
||||
streamingDockerClient.execStartCmd(execId).exec(callback);
|
||||
|
||||
boolean completed = latch.await(timeout.toMillis(), TimeUnit.MILLISECONDS);
|
||||
if (!completed) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import io.floci.aws.core.common.docker.ContainerSpec;
|
||||
import io.floci.aws.core.common.docker.ContainerStorageHelper;
|
||||
import io.floci.aws.core.common.docker.RetryingTarCopier;
|
||||
import io.floci.aws.core.common.docker.RunLabelledContainers;
|
||||
import io.floci.aws.core.common.docker.StreamingDocker;
|
||||
import io.floci.aws.services.codebuild.BuildspecParser.ParsedArtifacts;
|
||||
import io.floci.aws.services.codebuild.BuildspecParser.ParsedBuildspec;
|
||||
import io.floci.aws.services.codebuild.model.Build;
|
||||
@@ -76,6 +77,8 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
private static final int FAILURE_OUTPUT_CHARS = 512;
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
/** Carries a phase's output, a stream that stays open for as long as the phase runs. */
|
||||
private final DockerClient streamingDockerClient;
|
||||
private final ContainerBuilder containerBuilder;
|
||||
private final ContainerLifecycleManager lifecycleManager;
|
||||
private final ContainerLogStreamer logStreamer;
|
||||
@@ -97,6 +100,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
|
||||
@Inject
|
||||
public CodeBuildRunner(DockerClient dockerClient,
|
||||
@StreamingDocker DockerClient streamingDockerClient,
|
||||
ContainerBuilder containerBuilder,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
ContainerLogStreamer logStreamer,
|
||||
@@ -110,6 +114,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
Ec2Service ec2Service,
|
||||
CodeBuildRoleCredentials roleCredentials) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.streamingDockerClient = streamingDockerClient;
|
||||
this.containerBuilder = containerBuilder;
|
||||
this.lifecycleManager = lifecycleManager;
|
||||
this.logStreamer = logStreamer;
|
||||
@@ -722,6 +727,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
String script = String.join("\n", commands);
|
||||
String[] cmd = {"sh", "-e", "-c", script};
|
||||
|
||||
Closeable phaseOutput = null;
|
||||
try {
|
||||
String execId = dockerClient.execCreateCmd(containerId)
|
||||
.withCmd(cmd)
|
||||
@@ -735,7 +741,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
CountDownLatch latch = new CountDownLatch(1);
|
||||
OutputTail outputCapture = new OutputTail();
|
||||
|
||||
dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
|
||||
phaseOutput = streamingDockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
if (frame.getPayload() != null) {
|
||||
@@ -750,6 +756,8 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
|
||||
boolean completed = latch.await(timeoutMinutes, TimeUnit.MINUTES);
|
||||
if (!completed) {
|
||||
// Its output would otherwise hold a streaming connection for as long as the command runs on.
|
||||
closePhaseOutput(phaseOutput);
|
||||
return PhaseResult.ofFailure("Phase timed out after " + timeoutMinutes + " minutes");
|
||||
}
|
||||
if (stopFlag.get()) {
|
||||
@@ -769,6 +777,7 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
closePhaseOutput(phaseOutput);
|
||||
return PhaseResult.ofStopped();
|
||||
} catch (Exception e) {
|
||||
if (stopFlag.get()) {
|
||||
@@ -778,6 +787,17 @@ public class CodeBuildRunner implements ContainerTeardown, VpcDependencyProvider
|
||||
}
|
||||
}
|
||||
|
||||
private static void closePhaseOutput(Closeable phaseOutput) {
|
||||
if (phaseOutput == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
phaseOutput.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Could not close a CodeBuild phase's output stream");
|
||||
}
|
||||
}
|
||||
|
||||
private void uploadArtifacts(String region, Build build, Project project,
|
||||
ParsedArtifacts artifacts, Path workspace) throws IOException {
|
||||
String type = artifacts.type();
|
||||
|
||||
@@ -2009,8 +2009,8 @@ public class Ec2ContainerManager {
|
||||
};
|
||||
|
||||
UserDataPipeline.executeUserData(
|
||||
dockerClient, containerId, "EC2 instance " + instanceId, userData,
|
||||
userDataExecutionTimeout, lineConsumer, activeUserDataCallbacks);
|
||||
dockerClient, lifecycleManager.getStreamingDockerClient(), containerId, "EC2 instance " + instanceId,
|
||||
userData, userDataExecutionTimeout, lineConsumer, activeUserDataCallbacks);
|
||||
}
|
||||
|
||||
private void closeActiveUserDataCallbacks() {
|
||||
|
||||
@@ -715,7 +715,8 @@ public class EcrRegistryManager {
|
||||
final String finalExecId = execId;
|
||||
|
||||
try {
|
||||
ResultCallback.Adapter<Frame> asyncCallback = dockerClient.execStartCmd(finalExecId)
|
||||
ResultCallback.Adapter<Frame> asyncCallback = lifecycleManager.getStreamingDockerClient()
|
||||
.execStartCmd(finalExecId)
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
|
||||
@@ -193,7 +193,7 @@ public class EcsExecChannelHandler {
|
||||
return;
|
||||
}
|
||||
containerInput = toContainer;
|
||||
vertx.<Closeables>executeBlocking(() -> new Closeables(lifecycleManager.getDockerClient()
|
||||
vertx.<Closeables>executeBlocking(() -> new Closeables(lifecycleManager.getStreamingDockerClient()
|
||||
.execStartCmd(id)
|
||||
.withStdIn(execStdin)
|
||||
.withTty(current.interactive())
|
||||
|
||||
@@ -1816,7 +1816,7 @@ public class EksClusterManager
|
||||
.withAttachStdout(true)
|
||||
.withAttachStderr(false)
|
||||
.exec();
|
||||
return dockerClient
|
||||
return lifecycleManager.getStreamingDockerClient()
|
||||
.execStartCmd(execCreate.getId())
|
||||
.exec(logStreamer.execLogCallbackForAccount(
|
||||
accountId, logGroup, logStream, region, "eks-audit:" + clusterName, false));
|
||||
@@ -3874,6 +3874,7 @@ public class EksClusterManager
|
||||
}
|
||||
return UserDataPipeline.executeUserData(
|
||||
dockerClient,
|
||||
lifecycleManager.getStreamingDockerClient(),
|
||||
node.containerId(),
|
||||
context,
|
||||
userData,
|
||||
|
||||
@@ -216,8 +216,9 @@ public class EmrBootstrapRunner implements BootstrapRunner, ContainerTeardown {
|
||||
ContainerExec.Result result;
|
||||
try (ActionOutput stdout = new ActionOutput(prefix, logged);
|
||||
ActionOutput stderr = new ActionOutput(prefix, logged)) {
|
||||
result = ContainerExec.run(lifecycleManager.getDockerClient(), containerId,
|
||||
command.toArray(String[]::new), env, NO_TIMEOUT, stdout, stderr);
|
||||
// A user's script with no timeout: its output streams on the streaming pool for as long as it runs.
|
||||
result = ContainerExec.run(lifecycleManager.getDockerClient(), lifecycleManager.getStreamingDockerClient(),
|
||||
containerId, command.toArray(String[]::new), env, NO_TIMEOUT, stdout, stderr);
|
||||
if (logged) {
|
||||
writeLogs(bootstrap, number, stdout, stderr);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmd;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.StreamType;
|
||||
import io.floci.aws.core.common.docker.StreamingDocker;
|
||||
import io.floci.aws.services.ec2.Ec2Service;
|
||||
import io.floci.aws.services.ec2.model.Instance;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
@@ -27,11 +28,15 @@ public class SsmDirectCommandExecutor {
|
||||
private static final Logger LOG = Logger.getLogger(SsmDirectCommandExecutor.class);
|
||||
|
||||
private final DockerClient dockerClient;
|
||||
/** Carries a command's output, a stream that stays open for as long as the command runs. */
|
||||
private final DockerClient streamingDockerClient;
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
public SsmDirectCommandExecutor(DockerClient dockerClient, Ec2Service ec2Service) {
|
||||
public SsmDirectCommandExecutor(DockerClient dockerClient, @StreamingDocker DockerClient streamingDockerClient,
|
||||
Ec2Service ec2Service) {
|
||||
this.dockerClient = dockerClient;
|
||||
this.streamingDockerClient = streamingDockerClient;
|
||||
this.ec2Service = ec2Service;
|
||||
}
|
||||
|
||||
@@ -125,7 +130,8 @@ public class SsmDirectCommandExecutor {
|
||||
BoundedOutputCollector stdout = new BoundedOutputCollector(SsmCommandService.MAX_STDOUT_CHARS);
|
||||
Instant start = Instant.now();
|
||||
|
||||
ResultCallback<Frame> callback = dockerClient.execStartCmd(execId).exec(new ResultCallback.Adapter<Frame>() {
|
||||
ResultCallback<Frame> callback = streamingDockerClient.execStartCmd(execId)
|
||||
.exec(new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onNext(Frame frame) {
|
||||
byte[] payload = frame.getPayload();
|
||||
|
||||
@@ -401,16 +401,16 @@ floci:
|
||||
log-max-size: "10m"
|
||||
log-max-file: "3"
|
||||
docker-host: unix:///var/run/docker.sock
|
||||
# FLOCI_DOCKER_MAX_CONNECTIONS: connection pool size for Floci's short Docker calls, plus
|
||||
# CodeBuild phase execs, EKS audit followers and ECS Exec sessions. Past the limit,
|
||||
# create/start/stop/remove wait for a free connection and the emulator stalls. Keep in step
|
||||
# FLOCI_DOCKER_MAX_CONNECTIONS: connection pool size for Floci's short Docker calls. Past the
|
||||
# limit, create/start/stop/remove wait for a free connection and the emulator stalls. Keep in step
|
||||
# with the @WithDefault on EmulatorConfig.DockerConfig.maxConnections: a value set here WINS
|
||||
# over the annotation.
|
||||
max-connections: 1024
|
||||
# FLOCI_DOCKER_STREAMING_MAX_CONNECTIONS: separate pool for streams that last a container's
|
||||
# lifetime, so they never starve create/start/stop/remove. Each live Lambda container holds 2
|
||||
# (log follow and exit watcher) plus one per extension; 2048 covers the 500 containers the
|
||||
# runtime API port range allows with two extensions each. Keep in step with the @WithDefault on
|
||||
# (log follow and exit watcher) plus one per extension, and each CodeBuild phase, SSM command, ECS
|
||||
# Exec session, EKS audit follower, user data script and EMR bootstrap action one; 2048 covers the
|
||||
# 500 Lambda containers the runtime API port range allows with two extensions each. Keep in step with the @WithDefault on
|
||||
# EmulatorConfig.DockerConfig.streamingMaxConnections: a value set here WINS over the annotation.
|
||||
streaming-max-connections: 2048
|
||||
# FLOCI_DOCKER_CONNECTION_REQUEST_TIMEOUT_SECONDS: how long a Docker call waits for a free pooled
|
||||
|
||||
@@ -36,7 +36,7 @@ class ContainerConcurrentRemovalTest {
|
||||
private final Closeable waitStream = mock(Closeable.class);
|
||||
private final ConflictException conflict = new ConflictException("removal already in progress");
|
||||
private final ContainerLifecycleManager manager = new ContainerLifecycleManager(
|
||||
docker, mock(ImageCacheService.class), mock(ContainerDetector.class), mock(EmulatorConfig.class));
|
||||
docker, docker, mock(ImageCacheService.class), mock(ContainerDetector.class), mock(EmulatorConfig.class));
|
||||
|
||||
private void removalConflict(boolean running) {
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class, RETURNS_SELF);
|
||||
|
||||
@@ -49,6 +49,23 @@ public final class ContainerExecStubs {
|
||||
public static List<List<String>> completeEveryExec(DockerClient dockerClient, String containerId,
|
||||
List<Long> exitCodes, String stdout, String stderr,
|
||||
List<List<String>> envs) {
|
||||
return completeEveryExec(dockerClient, dockerClient, containerId, exitCodes, stdout, stderr, envs);
|
||||
}
|
||||
|
||||
/**
|
||||
* As {@link #completeEveryExec(DockerClient, String, long, String, String)}, the execs created and inspected
|
||||
* on {@code dockerClient} and startable on either client, so a test can verify which one each start used.
|
||||
*/
|
||||
public static List<List<String>> completeEveryExec(DockerClient dockerClient, DockerClient streamingDockerClient,
|
||||
String containerId, long exitCode, String stdout,
|
||||
String stderr) {
|
||||
return completeEveryExec(dockerClient, streamingDockerClient, containerId, List.of(exitCode), stdout, stderr,
|
||||
new ArrayList<>());
|
||||
}
|
||||
|
||||
private static List<List<String>> completeEveryExec(DockerClient dockerClient, DockerClient streamingDockerClient,
|
||||
String containerId, List<Long> exitCodes, String stdout,
|
||||
String stderr, List<List<String>> envs) {
|
||||
String execId = "exec-" + containerId;
|
||||
List<List<String>> commands = new ArrayList<>();
|
||||
|
||||
@@ -79,6 +96,9 @@ public final class ContainerExecStubs {
|
||||
return callback;
|
||||
});
|
||||
when(dockerClient.execStartCmd(execId)).thenReturn(startCmd);
|
||||
if (streamingDockerClient != dockerClient) {
|
||||
when(streamingDockerClient.execStartCmd(execId)).thenReturn(startCmd);
|
||||
}
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
|
||||
+2
-2
@@ -137,7 +137,7 @@ class ContainerLifecycleManagerCpuLimitTest {
|
||||
ImageCacheService imageCacheService = mock(ImageCacheService.class);
|
||||
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
new ContainerLifecycleManager(dockerClient, imageCacheService, mock(ContainerDetector.class), config)
|
||||
new ContainerLifecycleManager(dockerClient, dockerClient, imageCacheService, mock(ContainerDetector.class), config)
|
||||
.create(spec);
|
||||
|
||||
verify(createCmd).withHostName("ip-10-1-0-1.ec2.internal");
|
||||
@@ -162,7 +162,7 @@ class ContainerLifecycleManagerCpuLimitTest {
|
||||
ImageCacheService imageCacheService = mock(ImageCacheService.class);
|
||||
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, mock(ContainerDetector.class), config);
|
||||
dockerClient, dockerClient, imageCacheService, mock(ContainerDetector.class), config);
|
||||
|
||||
manager.create(spec);
|
||||
|
||||
|
||||
+1
-1
@@ -468,6 +468,6 @@ class ContainerLifecycleManagerCreateConflictRecoveryTest {
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -114,6 +114,6 @@ class ContainerLifecycleManagerCreateRejectionTest {
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -106,7 +106,7 @@ class ContainerLifecycleManagerDeviceRequestTest {
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
private static ContainerSpec specWithDeviceRequests(List<DeviceRequest> deviceRequests) {
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ class ContainerLifecycleManagerEphemeralTest {
|
||||
images = mock(ImageCacheService.class);
|
||||
when(images.ensureImageExists(spec.image())).thenReturn("image-id");
|
||||
EmulatorConfig config = mock(EmulatorConfig.class, RETURNS_DEEP_STUBS);
|
||||
manager = spy(new ContainerLifecycleManager(docker, images, mock(ContainerDetector.class), config));
|
||||
manager = spy(new ContainerLifecycleManager(docker, docker, images, mock(ContainerDetector.class), config));
|
||||
create = mock(CreateContainerCmd.class, RETURNS_SELF);
|
||||
CreateContainerResponse response = new CreateContainerResponse();
|
||||
response.setId("owned-id");
|
||||
|
||||
+1
-1
@@ -43,7 +43,7 @@ class ContainerLifecycleManagerImageLabelsTest {
|
||||
EmulatorConfig config;
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
|
||||
return new ContainerLifecycleManager(dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
private void imageInspectReturns(Map<String, String> labels) {
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import static org.mockito.Mockito.when;
|
||||
class ContainerLifecycleManagerImagesTest {
|
||||
|
||||
private final DockerClient docker = mock(DockerClient.class);
|
||||
private final ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
|
||||
private final ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
|
||||
@Test
|
||||
void aCommitNamesTheImageAndSetsItsUserAndLabels() {
|
||||
|
||||
+1
-1
@@ -289,7 +289,7 @@ class ContainerLifecycleManagerLabelsTest {
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
private static ContainerSpec specWithLabels(Map<String, String> labels) {
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ class ContainerLifecycleManagerLastLogLinesTest {
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
|
||||
manager = new ContainerLifecycleManager(dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
when(dockerClient.logContainerCmd("c1")).thenReturn(logs);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -202,7 +202,7 @@ class ContainerLifecycleManagerLinuxOptionsTest {
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
private CreateContainerCmd stubCreateContainer() {
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ class ContainerLifecycleManagerLivenessTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
when(dockerClient.inspectContainerCmd("c1")).thenReturn(inspectCmd);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -605,7 +605,7 @@ class ContainerLifecycleManagerNetworkTest {
|
||||
}
|
||||
|
||||
private ContainerLifecycleManager manager() {
|
||||
return new ContainerLifecycleManager(dockerClient, imageCacheService, containerDetector, config);
|
||||
return new ContainerLifecycleManager(dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
private static ContainerSpec spec(String networkMode, Map<Integer, Integer> portBindings,
|
||||
|
||||
+1
-1
@@ -141,7 +141,7 @@ class ContainerLifecycleManagerPortBindingTest {
|
||||
ImageCacheService imageCacheService = mock(ImageCacheService.class);
|
||||
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, mock(ContainerDetector.class), config);
|
||||
dockerClient, dockerClient, imageCacheService, mock(ContainerDetector.class), config);
|
||||
|
||||
manager.create(spec);
|
||||
|
||||
|
||||
+8
-2
@@ -16,7 +16,10 @@ class ContainerLifecycleManagerReachabilityTest {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
when(docker.pingCmd()).thenReturn(mock(PingCmd.class));
|
||||
|
||||
assertTrue(new ContainerLifecycleManager(docker, null, null, null).isDockerReachable());
|
||||
DockerClient streaming = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, streaming, null, null, null);
|
||||
|
||||
assertTrue(manager.isDockerReachable());
|
||||
}
|
||||
|
||||
// Catches: a missing daemon surfacing as an exception from the probe, which callers use to tell a
|
||||
@@ -28,6 +31,9 @@ class ContainerLifecycleManagerReachabilityTest {
|
||||
when(ping.exec()).thenThrow(new RuntimeException("java.net.SocketException: No such file or directory"));
|
||||
when(docker.pingCmd()).thenReturn(ping);
|
||||
|
||||
assertFalse(new ContainerLifecycleManager(docker, null, null, null).isDockerReachable());
|
||||
DockerClient streaming = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, streaming, null, null, null);
|
||||
|
||||
assertFalse(manager.isDockerReachable());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -57,7 +57,7 @@ class ContainerLifecycleManagerStartFailureTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = spy(new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config));
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ class ContainerLifecycleManagerStartTest {
|
||||
|
||||
private ContainerLifecycleManager manager(DockerClient docker) {
|
||||
return new ContainerLifecycleManager(
|
||||
docker, imageCacheService, containerDetector, config);
|
||||
docker, docker, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+5
-5
@@ -38,7 +38,7 @@ class ContainerLifecycleManagerTeardownTest {
|
||||
void strictRemovalRetainsLogStreamForRetryWithOptionalAnonymousVolumeCleanup(boolean removeAnonymousVolumes)
|
||||
throws Exception {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class);
|
||||
when(docker.stopContainerCmd("retry")).thenReturn(stop);
|
||||
when(stop.withTimeout(5)).thenReturn(stop);
|
||||
@@ -65,7 +65,7 @@ class ContainerLifecycleManagerTeardownTest {
|
||||
@Test
|
||||
void confirmedRemovalAnswersWhetherTheContainerIsGoneAndKeepsTheLogStreamUntilItIs() throws Exception {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class);
|
||||
when(docker.stopContainerCmd("held")).thenReturn(stop);
|
||||
when(stop.withTimeout(5)).thenReturn(stop);
|
||||
@@ -87,7 +87,7 @@ class ContainerLifecycleManagerTeardownTest {
|
||||
@ValueSource(strings = {"strict", "strict-volumes", "best-effort", "stop-only"})
|
||||
void laterOwnedStopsReachDockerWhileEarlierRemovalsAreBlocked(String mode) throws Exception {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class);
|
||||
CountDownLatch ninthStop = new CountDownLatch(1);
|
||||
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
|
||||
@@ -160,7 +160,7 @@ class ContainerLifecycleManagerTeardownTest {
|
||||
@Test
|
||||
void aContainerThatHadAlreadyExitedCountsAsStopped() throws Exception {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class);
|
||||
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
|
||||
when(stop.withTimeout(anyInt())).thenReturn(stop);
|
||||
@@ -183,7 +183,7 @@ class ContainerLifecycleManagerTeardownTest {
|
||||
@Test
|
||||
void aStopLeavesTheContainerInPlaceAndCountsAnExitedOrMissingOneAsStopped() {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class);
|
||||
when(docker.stopContainerCmd(anyString())).thenReturn(stop);
|
||||
when(stop.withTimeout(anyInt())).thenReturn(stop);
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ class ContainerLifecycleManagerVolumeTest {
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
manager = new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, containerDetector, config);
|
||||
dockerClient, dockerClient, imageCacheService, containerDetector, config);
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+1
-1
@@ -75,7 +75,7 @@ class ContainerLifecycleManagerVolumesFromTest {
|
||||
ImageCacheService imageCacheService = mock(ImageCacheService.class);
|
||||
when(imageCacheService.ensureImageExists(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
ContainerLifecycleManager manager = new ContainerLifecycleManager(
|
||||
dockerClient, imageCacheService, mock(ContainerDetector.class), config);
|
||||
dockerClient, dockerClient, imageCacheService, mock(ContainerDetector.class), config);
|
||||
|
||||
manager.create(spec);
|
||||
|
||||
|
||||
@@ -73,11 +73,13 @@ class UserDataPipelineTest {
|
||||
}
|
||||
return null;
|
||||
});
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, "container-id", 0L,
|
||||
// The script's output stays open for as long as it runs, so it streams on the streaming client.
|
||||
DockerClient streaming = mock(DockerClient.class);
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, streaming, "container-id", 0L,
|
||||
"bootstrap complete\n", "");
|
||||
List<String> output = new ArrayList<>();
|
||||
|
||||
UserDataPipeline.ExecutionResult result = UserDataPipeline.executeUserData(docker, "container-id",
|
||||
UserDataPipeline.ExecutionResult result = UserDataPipeline.executeUserData(docker, streaming, "container-id",
|
||||
"test instance", script, Duration.ofSeconds(1), output::add, null, 0L);
|
||||
|
||||
assertTrue(result.isSuccess(), result.getFailureMessage());
|
||||
@@ -87,7 +89,8 @@ class UserDataPipelineTest {
|
||||
assertEquals(List.of(List.of(UserDataPipeline.USER_DATA_SCRIPT_PATH)), commands);
|
||||
assertEquals(List.of("bootstrap complete"), output);
|
||||
verify(copyCmd, times(2)).withRemotePath("/var/lib");
|
||||
verify(docker).execStartCmd("exec-container-id");
|
||||
verify(streaming).execStartCmd("exec-container-id");
|
||||
verify(docker, never()).execStartCmd(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -97,7 +100,7 @@ class UserDataPipelineTest {
|
||||
when(docker.copyArchiveToContainerCmd("container-id")).thenReturn(copyCmd);
|
||||
when(copyCmd.exec()).thenThrow(new NotFoundException("Could not find the file /var/lib in container"));
|
||||
|
||||
UserDataPipeline.ExecutionResult result = UserDataPipeline.executeUserData(docker, "container-id",
|
||||
UserDataPipeline.ExecutionResult result = UserDataPipeline.executeUserData(docker, docker, "container-id",
|
||||
"test instance", "#!/bin/sh\nexit 0\n", Duration.ofSeconds(1), null, null);
|
||||
|
||||
assertFalse(result.isSuccess());
|
||||
|
||||
@@ -176,7 +176,7 @@ class ReposiliteSidecarManagerTest {
|
||||
@Test
|
||||
void failedStopRetainsTheManagedEndpointForCleanupRetry() throws Exception {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ContainerLifecycleManager lifecycle = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager lifecycle = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
StopContainerCmd stop = mock(StopContainerCmd.class);
|
||||
when(docker.stopContainerCmd("retained-reposilite")).thenReturn(stop);
|
||||
when(stop.withTimeout(5)).thenReturn(stop);
|
||||
|
||||
@@ -141,7 +141,7 @@ class VerdaccioSidecarManagerTest {
|
||||
when(docker.removeContainerCmd("tracked-verdaccio-1")).thenReturn(remove);
|
||||
when(remove.withForce(true)).thenReturn(remove);
|
||||
doThrow(new IllegalStateException("Docker removal failed")).doNothing().when(remove).exec();
|
||||
ContainerLifecycleManager realLifecycle = new ContainerLifecycleManager(docker, null, null, null);
|
||||
ContainerLifecycleManager realLifecycle = new ContainerLifecycleManager(docker, docker, null, null, null);
|
||||
VerdaccioSidecarManager manager = new VerdaccioSidecarManager(containerBuilder, realLifecycle, config,
|
||||
new CodeArtifactContainerRuns(realLifecycle, config).containers());
|
||||
seedPooledContainer(manager, "npm-repo-1", "tracked-verdaccio-1", "http://127.0.0.1:1");
|
||||
|
||||
@@ -195,7 +195,7 @@ class CodeBuildRunnerServiceRoleTest {
|
||||
when(server.start()).thenReturn(CompletableFuture.completedFuture(null));
|
||||
EcsCredentialsProxy proxy = mock(EcsCredentialsProxy.class);
|
||||
|
||||
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, containerBuilder, lifecycle, logStreamer,
|
||||
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, docker, containerBuilder, lifecycle, logStreamer,
|
||||
null, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint,
|
||||
mock(Ec2Service.class),
|
||||
new CodeBuildRoleCredentials(credentials, server, proxy, new EcsTaskLinkLocalAddresses())));
|
||||
|
||||
@@ -177,7 +177,7 @@ class CodeBuildRunnerSourceFailureTest {
|
||||
CodeBuildRoleCredentials roleCredentials = mock(CodeBuildRoleCredentials.class);
|
||||
when(roleCredentials.provision(anyString(), anyString(), nullable(String.class), anyString(), any()))
|
||||
.thenReturn(new CodeBuildRoleCredentials.BuildCredentials(Map.of(), null));
|
||||
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, containerBuilder, lifecycle, logStreamer,
|
||||
CodeBuildRunner runner = spy(new CodeBuildRunner(docker, docker, containerBuilder, lifecycle, logStreamer,
|
||||
s3, null, null, config, mock(ContainerDetector.class), regionResolver, endpoint, ec2,
|
||||
roleCredentials));
|
||||
doReturn(CodeBuildRunner.PhaseResult.ofSuccess()).when(runner)
|
||||
|
||||
@@ -24,6 +24,7 @@ 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.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class CodeBuildRunnerTest {
|
||||
@@ -35,9 +36,11 @@ class CodeBuildRunnerTest {
|
||||
// 2.5 GiB in total: more than a single Java byte array can hold.
|
||||
int chunkCount = 320;
|
||||
String lastLine = "error: build step failed\n";
|
||||
DockerClient dockerClient = dockerClientStreaming(chunk, chunkCount, lastLine, 2L);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null,
|
||||
null, null);
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
DockerClient streamingDockerClient = mock(DockerClient.class);
|
||||
stubPhase(dockerClient, streamingDockerClient, chunk, chunkCount, lastLine, 2L);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, streamingDockerClient, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null);
|
||||
|
||||
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
|
||||
List.of("./build.sh"), 60, new AtomicBoolean(false));
|
||||
@@ -47,11 +50,39 @@ class CodeBuildRunnerTest {
|
||||
assertEquals("Exit code 2: " + expectedTail, result.errorMessage());
|
||||
}
|
||||
|
||||
// Catches: a timed-out phase leaving its exec's output stream open, so it held a streaming
|
||||
// connection for as long as the command ran on.
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void aPhaseThatTimesOutClosesItsOutputStream() throws Exception {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
DockerClient streamingDockerClient = mock(DockerClient.class);
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
when(createResponse.getId()).thenReturn("exec-1");
|
||||
when(createCmd.exec()).thenReturn(createResponse);
|
||||
when(dockerClient.execCreateCmd("container-1")).thenReturn(createCmd);
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class);
|
||||
ResultCallback.Adapter<Frame> neverCompletes = mock(ResultCallback.Adapter.class);
|
||||
when(startCmd.exec(any())).thenReturn(neverCompletes);
|
||||
when(streamingDockerClient.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, streamingDockerClient, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null);
|
||||
|
||||
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
|
||||
List.of("./build.sh"), 0, new AtomicBoolean(false));
|
||||
|
||||
assertEquals("Phase timed out after 0 minutes", result.errorMessage());
|
||||
verify(neverCompletes).close();
|
||||
}
|
||||
|
||||
@Test
|
||||
void failureMessageIgnoresLongTrailingWhitespace() {
|
||||
DockerClient dockerClient = dockerClientStreaming(new byte[0], 0, "tests failed" + "\n".repeat(10_000), 1L);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, null, null, null, null, null, null, null, null, null, null,
|
||||
null, null);
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
DockerClient streamingDockerClient = mock(DockerClient.class);
|
||||
stubPhase(dockerClient, streamingDockerClient, new byte[0], 0, "tests failed" + "\n".repeat(10_000), 1L);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(dockerClient, streamingDockerClient, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null);
|
||||
|
||||
CodeBuildRunner.PhaseResult result = runner.runPhase("container-1", "/src", List.of(),
|
||||
List.of("./test.sh"), 60, new AtomicBoolean(false));
|
||||
@@ -67,14 +98,18 @@ class CodeBuildRunnerTest {
|
||||
when(config.port()).thenReturn(4566);
|
||||
ContainerDetector containerDetector = mock(ContainerDetector.class);
|
||||
ContainerReachableEndpoint endpoint = new ContainerReachableEndpoint(config, null, null, null, 4811);
|
||||
CodeBuildRunner runner = new CodeBuildRunner(null, null, null, null, null, null, null,
|
||||
CodeBuildRunner runner = new CodeBuildRunner(null, null, null, null, null, null, null, null,
|
||||
config, containerDetector, null, endpoint, null, null);
|
||||
|
||||
assertEquals("http://host.docker.internal:4811", runner.resolveEndpointUrl());
|
||||
}
|
||||
|
||||
private static DockerClient dockerClientStreaming(byte[] chunk, int chunkCount, String lastLine, long exitCode) {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
/**
|
||||
* The exec is created and inspected on the control-plane client and its output streamed on the
|
||||
* streaming client, so a phase whose output took a control-plane lease would find no stub.
|
||||
*/
|
||||
private static void stubPhase(DockerClient dockerClient, DockerClient streamingDockerClient, byte[] chunk,
|
||||
int chunkCount, String lastLine, long exitCode) {
|
||||
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, RETURNS_SELF);
|
||||
ExecCreateCmdResponse createResponse = mock(ExecCreateCmdResponse.class);
|
||||
@@ -92,13 +127,12 @@ class CodeBuildRunnerTest {
|
||||
callback.onComplete();
|
||||
return callback;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
when(streamingDockerClient.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
|
||||
InspectExecCmd inspectCmd = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectResponse = mock(InspectExecResponse.class);
|
||||
when(inspectResponse.getExitCodeLong()).thenReturn(exitCode);
|
||||
when(inspectCmd.exec()).thenReturn(inspectResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectCmd);
|
||||
return dockerClient;
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ class CodeBuildSourceCopyTest {
|
||||
uploads.consumedBytes = 8;
|
||||
uploads.failure = new RuntimeException(new IOException("Broken pipe"));
|
||||
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, docker, null, null, null, null, null, null, null, null, null, null, null, null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0);
|
||||
|
||||
assertEquals(2, uploads.commands.size());
|
||||
@@ -58,7 +58,8 @@ class CodeBuildSourceCopyTest {
|
||||
uploads.failure = new RuntimeException(new IOException("Broken pipe"));
|
||||
|
||||
RuntimeException failure = assertThrows(RuntimeException.class, () ->
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, docker, null, null, null, null, null, null, null, null, null, null, null,
|
||||
null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0));
|
||||
|
||||
assertEquals(6, uploads.commands.size());
|
||||
@@ -74,7 +75,8 @@ class CodeBuildSourceCopyTest {
|
||||
uploads.failure = new IllegalStateException("No such container");
|
||||
|
||||
RuntimeException failure = assertThrows(RuntimeException.class, () ->
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, docker, null, null, null, null, null, null, null, null, null, null, null,
|
||||
null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src", 0));
|
||||
|
||||
assertTrue(failure.getMessage().contains("No such container"));
|
||||
@@ -85,7 +87,7 @@ class CodeBuildSourceCopyTest {
|
||||
void skipsEmptyWorkspace(@TempDir Path workspace) {
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
|
||||
new CodeBuildRunner(docker, null, null, null, null, null, null, null, null, null, null, null, null)
|
||||
new CodeBuildRunner(docker, docker, null, null, null, null, null, null, null, null, null, null, null, null)
|
||||
.copySourceToContainer("build-container", workspace, "/codebuild/output/src/src");
|
||||
|
||||
verifyNoInteractions(docker);
|
||||
|
||||
@@ -51,6 +51,7 @@ import org.junit.jupiter.api.io.TempDir;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.stubbing.Answer;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.Closeable;
|
||||
@@ -1662,6 +1663,9 @@ class Ec2ContainerManagerTest {
|
||||
verify(harness.logStreamer, timeout(2000)).streamToCloudWatchLogs(
|
||||
any(String.class), any(String.class), eq("us-west-2"), eq(TEST_USER_DATA_OUTPUT)
|
||||
);
|
||||
// The script's output holds its connection for as long as it runs, so it uses the streaming pool.
|
||||
verify(harness.streamingDockerClient).execStartCmd("userdata-exec");
|
||||
verify(harness.dockerClient, never()).execStartCmd("userdata-exec");
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -2602,6 +2606,8 @@ class Ec2ContainerManagerTest {
|
||||
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
stubDockerPing(dockerClient, true);
|
||||
DockerClient streamingDockerClient = mock(DockerClient.class);
|
||||
when(lifecycleManager.getStreamingDockerClient()).thenReturn(streamingDockerClient);
|
||||
Ec2MetadataServer metadataServer = mock(Ec2MetadataServer.class);
|
||||
ContainerLogStreamer logStreamer = mock(ContainerLogStreamer.class);
|
||||
Ec2PortForwardManager portForwardManager = mock(Ec2PortForwardManager.class);
|
||||
@@ -2641,8 +2647,9 @@ class Ec2ContainerManagerTest {
|
||||
reachableEndpoint,
|
||||
executor,
|
||||
userDataTimeout);
|
||||
return new LaunchHarness(manager, lifecycleManager, dockerClient, metadataServer, logStreamer, builder,
|
||||
portAllocator, portForwardManager, config, vpcNetworkManager, new CopyOnWriteArrayList<>());
|
||||
return new LaunchHarness(manager, lifecycleManager, dockerClient, streamingDockerClient, metadataServer,
|
||||
logStreamer, builder, portAllocator, portForwardManager, config, vpcNetworkManager,
|
||||
new CopyOnWriteArrayList<>());
|
||||
}
|
||||
|
||||
// ── startup reconciliation of EC2 containers orphaned by a previous run ──────
|
||||
@@ -2836,7 +2843,7 @@ class Ec2ContainerManagerTest {
|
||||
? userDataExec : metadataExec;
|
||||
});
|
||||
|
||||
when(harness.dockerClient().execStartCmd(anyString())).thenAnswer(invocation -> {
|
||||
Answer<ExecStartCmd> start = invocation -> {
|
||||
String execId = invocation.getArgument(0);
|
||||
ExecStartCmd execStart = mock(ExecStartCmd.class);
|
||||
when(execStart.exec(any())).thenAnswer(startInvocation -> {
|
||||
@@ -2851,7 +2858,9 @@ class Ec2ContainerManagerTest {
|
||||
return callback;
|
||||
});
|
||||
return execStart;
|
||||
});
|
||||
};
|
||||
when(harness.dockerClient().execStartCmd(anyString())).thenAnswer(start);
|
||||
when(harness.streamingDockerClient().execStartCmd(anyString())).thenAnswer(start);
|
||||
|
||||
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
|
||||
@@ -3180,6 +3189,7 @@ class Ec2ContainerManagerTest {
|
||||
private record LaunchHarness(Ec2ContainerManager manager,
|
||||
ContainerLifecycleManager lifecycleManager,
|
||||
DockerClient dockerClient,
|
||||
DockerClient streamingDockerClient,
|
||||
Ec2MetadataServer metadataServer,
|
||||
ContainerLogStreamer logStreamer,
|
||||
ContainerBuilder.Builder builder,
|
||||
@@ -3214,7 +3224,8 @@ class Ec2ContainerManagerTest {
|
||||
return metadataExec;
|
||||
});
|
||||
|
||||
when(dockerClient.execStartCmd(anyString())).thenAnswer(invocation -> {
|
||||
// Startable on either client, so a test can verify which pool each exec's output used.
|
||||
Answer<ExecStartCmd> start = invocation -> {
|
||||
String execId = invocation.getArgument(0);
|
||||
ExecStartCmd execStart = mock(ExecStartCmd.class);
|
||||
when(execStart.exec(any())).thenAnswer(startInvocation -> {
|
||||
@@ -3231,7 +3242,9 @@ class Ec2ContainerManagerTest {
|
||||
return callback;
|
||||
});
|
||||
return execStart;
|
||||
});
|
||||
};
|
||||
when(dockerClient.execStartCmd(anyString())).thenAnswer(start);
|
||||
when(streamingDockerClient.execStartCmd(anyString())).thenAnswer(start);
|
||||
|
||||
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
|
||||
|
||||
@@ -1040,7 +1040,10 @@ class EcrRegistryManagerTest {
|
||||
when(execCreateCmd.exec()).thenReturn(execResponse);
|
||||
when(execResponse.getId()).thenReturn("gc-exec-1");
|
||||
ExecStartCmd execStartCmd = Mockito.mock(ExecStartCmd.class, Mockito.RETURNS_SELF);
|
||||
when(dockerClient.execStartCmd("gc-exec-1")).thenReturn(execStartCmd);
|
||||
// The collection's output holds its connection for minutes, so it streams on the streaming client.
|
||||
DockerClient streamingDockerClient = Mockito.mock(DockerClient.class);
|
||||
when(lifecycleManager.getStreamingDockerClient()).thenReturn(streamingDockerClient);
|
||||
when(streamingDockerClient.execStartCmd("gc-exec-1")).thenReturn(execStartCmd);
|
||||
ResultCallback.Adapter<Frame> execCallback = Mockito.mock(ResultCallback.Adapter.class);
|
||||
when(execStartCmd.exec(any())).thenReturn(execCallback);
|
||||
when(execCallback.awaitCompletion(anyLong(), any())).thenReturn(false);
|
||||
|
||||
@@ -71,10 +71,13 @@ class EcsExecChannelHandlerTest {
|
||||
}
|
||||
return attach;
|
||||
});
|
||||
when(docker.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
// The session's stream holds its connection for as long as the session, so it uses the streaming client.
|
||||
DockerClient streamingDocker = mock(DockerClient.class);
|
||||
when(streamingDocker.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(docker);
|
||||
when(lifecycleManager.getStreamingDockerClient()).thenReturn(streamingDocker);
|
||||
|
||||
Router router = Router.router(vertx);
|
||||
new EcsExecChannelHandler(sessions, lifecycleManager, new ObjectMapper(), vertx).init(router);
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.core.common.RegionResolver;
|
||||
import io.floci.aws.core.common.docker.ContainerBuilder;
|
||||
import io.floci.aws.core.common.docker.ContainerDetector;
|
||||
import io.floci.aws.core.common.docker.ContainerExecStubs;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager;
|
||||
import io.floci.aws.core.common.docker.ContainerLifecycleManager.ContainerInfo;
|
||||
import io.floci.aws.core.common.docker.ContainerLogStreamer;
|
||||
@@ -232,6 +233,25 @@ class EksClusterGuestSetupTest {
|
||||
assertEquals(new EksClusterManager.SetUpNode(CONTAINER_ID, null), waiting.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
|
||||
// Catches: a node group's user data script, which may run for minutes, holding a control-plane
|
||||
// connection for as long as it runs instead of a streaming one.
|
||||
@Test
|
||||
void userDataOutputStreamsOnTheStreamingClient() {
|
||||
DockerClient streaming = Mockito.mock(DockerClient.class);
|
||||
when(lifecycleManager.getStreamingDockerClient()).thenReturn(streaming);
|
||||
ContainerExecStubs.completeEveryExec(dockerClient, streaming, CONTAINER_ID, 0, "joined\n", "");
|
||||
Cluster cluster = cluster();
|
||||
manager.startCluster(cluster);
|
||||
manager.setUpGuest(cluster);
|
||||
|
||||
UserDataPipeline.ExecutionResult result =
|
||||
manager.executeUserData(cluster, "workers", "#!/bin/bash\necho joined\n");
|
||||
|
||||
assertTrue(result.isSuccess(), result.getFailureMessage());
|
||||
verify(streaming).execStartCmd("exec-" + CONTAINER_ID);
|
||||
verify(dockerClient, never()).execStartCmd("exec-" + CONTAINER_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void userDataFollowsANodeReplacedWhileItWaits() throws Exception {
|
||||
Cluster cluster = cluster();
|
||||
@@ -323,7 +343,10 @@ class EksClusterGuestSetupTest {
|
||||
when(docker.execCreateCmd(anyString())).thenReturn(execCreateCmd);
|
||||
when(execCreateCmd.exec()).thenReturn(execCreate);
|
||||
ExecStartCmd execStartCmd = Mockito.mock(ExecStartCmd.class, Mockito.RETURNS_SELF);
|
||||
when(docker.execStartCmd("exec-123")).thenReturn(execStartCmd);
|
||||
// The audit follower runs tail -F for the cluster's lifetime, so it streams on the streaming client.
|
||||
DockerClient streamingDocker = Mockito.mock(DockerClient.class);
|
||||
when(lifecycleManager.getStreamingDockerClient()).thenReturn(streamingDocker);
|
||||
when(streamingDocker.execStartCmd("exec-123")).thenReturn(execStartCmd);
|
||||
ResultCallback.Adapter<?> auditFollower = Mockito.mock(ResultCallback.Adapter.class);
|
||||
Mockito.doReturn(auditFollower).when(execStartCmd).exec(any());
|
||||
RegionResolver regionResolver = Mockito.mock(RegionResolver.class);
|
||||
|
||||
@@ -4573,7 +4573,10 @@ class EksClusterManagerTest {
|
||||
when(execCreateCmd.exec()).thenReturn(execCreate);
|
||||
|
||||
ExecStartCmd execStartCmd = Mockito.mock(ExecStartCmd.class, Mockito.RETURNS_SELF);
|
||||
when(dockerClient.execStartCmd("exec-123")).thenReturn(execStartCmd);
|
||||
// The audit follower runs tail -F for the cluster's lifetime, so it streams on the streaming client.
|
||||
DockerClient streamingDockerClient = Mockito.mock(DockerClient.class);
|
||||
when(lifecycleManager.getStreamingDockerClient()).thenReturn(streamingDockerClient);
|
||||
when(streamingDockerClient.execStartCmd("exec-123")).thenReturn(execStartCmd);
|
||||
ResultCallback.Adapter<?> mockAuditHandle = Mockito.mock(ResultCallback.Adapter.class);
|
||||
Mockito.doReturn(mockAuditHandle).when(execStartCmd).exec(any());
|
||||
|
||||
|
||||
@@ -83,6 +83,7 @@ class EmrBootstrapRunnerTest {
|
||||
void setUp() {
|
||||
when(builder.newContainer(anyString())).thenReturn(spec);
|
||||
when(lifecycle.getDockerClient()).thenReturn(docker);
|
||||
when(lifecycle.getStreamingDockerClient()).thenReturn(docker);
|
||||
when(lifecycle.createAndStart(any()))
|
||||
.thenReturn(new ContainerLifecycleManager.ContainerInfo(CONTAINER, Map.of()));
|
||||
when(roleCredentials.forRole(any(), any(), any())).thenReturn(Optional.empty());
|
||||
@@ -104,6 +105,20 @@ class EmrBootstrapRunnerTest {
|
||||
});
|
||||
}
|
||||
|
||||
// Catches: a bootstrap action, a user's script with no timeout, holding a control-plane connection for
|
||||
// as long as it runs instead of a streaming one.
|
||||
@Test
|
||||
void eachActionsOutputStreamsOnTheStreamingClient() {
|
||||
DockerClient streaming = mock(DockerClient.class);
|
||||
when(lifecycle.getStreamingDockerClient()).thenReturn(streaming);
|
||||
ContainerExecStubs.completeEveryExec(docker, streaming, CONTAINER, 0, "installed\n", "");
|
||||
|
||||
runner.run(bootstrap(null, action("s3://bucket/bootstrap/install.sh"),
|
||||
action("s3n://bucket/bootstrap/jars.sh")), () -> false);
|
||||
|
||||
verify(streaming, times(2)).execStartCmd(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void eachActionRunsInTurnAsRootThenTheContainerIsKeptAsTheImageTheStepsRunIn() {
|
||||
List<List<String>> commands = ContainerExecStubs.completeEveryExec(docker, CONTAINER, 0, "installed\n", "");
|
||||
|
||||
+1
-1
@@ -99,7 +99,7 @@ class RdsBackendEndpointRefreshIntegrationTest {
|
||||
ContainerDetector detector = mock(ContainerDetector.class);
|
||||
when(detector.isRunningInContainer()).thenReturn(true);
|
||||
lifecycleManager = new ContainerLifecycleManager(
|
||||
dockerClient, mock(ImageCacheService.class), detector, mock(EmulatorConfig.class));
|
||||
dockerClient, dockerClient, mock(ImageCacheService.class), detector, mock(EmulatorConfig.class));
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
|
||||
@@ -39,6 +39,9 @@ class SsmDirectCommandExecutorTest {
|
||||
@Test
|
||||
void executesRunShellScriptInsideEc2Container() throws Exception {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
// The command's output holds its connection for as long as the command runs, so it streams on
|
||||
// the streaming client while the exec is created and inspected on the control-plane one.
|
||||
DockerClient streamingDockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
Instance instance = instance("i-container", "container-1");
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
@@ -61,7 +64,7 @@ class SsmDirectCommandExecutorTest {
|
||||
resultCallback.onComplete();
|
||||
return resultCallback;
|
||||
});
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
when(streamingDockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
|
||||
InspectExecCmd inspectExec = mock(InspectExecCmd.class);
|
||||
InspectExecResponse inspectExecResponse = mock(InspectExecResponse.class);
|
||||
@@ -69,7 +72,8 @@ class SsmDirectCommandExecutorTest {
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, streamingDockerClient,
|
||||
ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -125,7 +129,7 @@ class SsmDirectCommandExecutorTest {
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
when(ec2Service.findInstanceById("i-agent")).thenReturn(null);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-agent",
|
||||
"AWS-RunShellScript",
|
||||
@@ -151,7 +155,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(ec2Service.isInstanceContainerRunning("i-running")).thenReturn(true);
|
||||
when(ec2Service.isInstanceContainerRunning("i-stopped")).thenReturn(false);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
|
||||
assertTrue(executor.isContainerBacked("i-running"));
|
||||
assertFalse(executor.isContainerBacked("i-stopped"));
|
||||
@@ -163,7 +167,7 @@ class SsmDirectCommandExecutorTest {
|
||||
DockerClient dockerClient = mock(DockerClient.class);
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunPowerShellScript",
|
||||
@@ -181,7 +185,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(ec2Service.findInstanceById("i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("i-container")).thenReturn(true);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -225,7 +229,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -258,7 +262,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(execStart.exec(any())).thenReturn(callback);
|
||||
when(dockerClient.execStartCmd("exec-1")).thenReturn(execStart);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -302,7 +306,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -349,7 +353,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -395,7 +399,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(inspectExec.exec()).thenReturn(inspectExecResponse);
|
||||
when(dockerClient.inspectExecCmd("exec-1")).thenReturn(inspectExec);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
Optional<SsmDirectCommandExecutor.ExecutionResult> result = executor.executeIfSupported(
|
||||
"i-container",
|
||||
"AWS-RunShellScript",
|
||||
@@ -415,7 +419,7 @@ class SsmDirectCommandExecutorTest {
|
||||
when(ec2Service.findInstanceById("111122223333", "i-container")).thenReturn(instance);
|
||||
when(ec2Service.isInstanceContainerRunning("111122223333", "i-container")).thenReturn(true);
|
||||
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, ec2Service);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(dockerClient, dockerClient, ec2Service);
|
||||
assertTrue(executor.supports("111122223333", "i-container", "AWS-RunShellScript"));
|
||||
assertFalse(executor.supports("444455556666", "i-container", "AWS-RunShellScript"));
|
||||
}
|
||||
|
||||
@@ -140,7 +140,7 @@ class SsmTimeoutDockerIntegrationTest {
|
||||
instance.setDockerContainerId(container.containerId());
|
||||
when(ec2.findInstanceById("i-timeout")).thenReturn(instance);
|
||||
when(ec2.isInstanceContainerRunning("i-timeout")).thenReturn(true);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(docker, ec2);
|
||||
SsmDirectCommandExecutor executor = new SsmDirectCommandExecutor(docker, docker, ec2);
|
||||
if (!descendantsOnly) {
|
||||
for (int code : List.of(124, 137, 143)) {
|
||||
SsmDirectCommandExecutor.ExecutionResult result = executor.executeIfSupported("i-timeout",
|
||||
|
||||
@@ -49,7 +49,7 @@ class SsmTimeoutSdkIntegrationTest extends SsmCommandIntegrationFixture {
|
||||
instance.setDockerContainerId(container.containerId());
|
||||
when(ec2.findInstanceById(account, instanceId)).thenReturn(instance);
|
||||
when(ec2.isInstanceContainerRunning(account, instanceId)).thenReturn(true);
|
||||
SsmDirectCommandExecutor actual = new SsmDirectCommandExecutor(docker, ec2);
|
||||
SsmDirectCommandExecutor actual = new SsmDirectCommandExecutor(docker, docker, ec2);
|
||||
when(executor.supports(account, instanceId, "AWS-RunShellScript")).thenReturn(true);
|
||||
when(executor.executeIfSupported(eq(account), eq(instanceId), eq("AWS-RunShellScript"), any(), anyInt()))
|
||||
.thenAnswer(call -> actual.executeIfSupported(call.getArgument(0), call.getArgument(1),
|
||||
|
||||
Reference in new issue
Block a user