mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(docker): count open Docker streams per service and add a saturation harness (#8953)
* feat(docker): count open Docker streams per service and add a saturation harness * fix(docker): match container routes at the start of the path, and tidy the harness * test(docker): drop the saturation harness's quiet-stream sleep
This commit is contained in:
1 parent
43d6ea4961
commit
b9ebbe0a42
12 files changed
+629
-25
No files matched your search
@@ -71,7 +71,7 @@ starts ContainerHostNetworkDockerIntegrationTest ContainerBindDirectoryDockerInt
|
||||
EcsContainerManagerEfsIsolationDockerIntegrationTest EcsContainerManagerFirelensDockerIntegrationTest \
|
||||
EcsContainerManagerStatsDockerIntegrationTest EcsContainerManagerVolumesFromDockerIntegrationTest \
|
||||
EcsExecChannelDockerIntegrationTest EcsImagePullDockerIntegrationTest EcsLeftoverContainersDockerIntegrationTest \
|
||||
BatchDockerRunnerDockerIntegrationTest SageMakerDockerIntegrationTest \
|
||||
BatchDockerRunnerDockerIntegrationTest SageMakerDockerIntegrationTest DockerPoolSaturationNightlyIntegrationTest \
|
||||
&& [ -n "$BUSYBOX_IMAGE" ] && pull "$BUSYBOX_IMAGE"
|
||||
# Bind-directory ownership uses the default OpenSearch image, whose cold pull can outlast a test.
|
||||
OPENSEARCH_VERSIONS="$(find src/main/java -name OpenSearchVersions.java -print -quit)"
|
||||
|
||||
@@ -28,7 +28,7 @@ jobs:
|
||||
checks:
|
||||
name: Nightly checks (${{ matrix.group }})
|
||||
runs-on: ubuntu-latest
|
||||
# The existing checks keep their 336-minute total plus twenty minutes for setup. The shrink check runs
|
||||
# The existing checks keep their 339-minute total plus twenty minutes for setup. The shrink check runs
|
||||
# separately: its sixteen-minute method and two-minute setup plus twenty minutes for compilation/prefetch.
|
||||
# Combining them would exceed the hosted runner's 360-minute job limit.
|
||||
strategy:
|
||||
@@ -36,7 +36,7 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- group: standard
|
||||
timeout: 356
|
||||
timeout: 359
|
||||
- group: cluster-shrink
|
||||
timeout: 38
|
||||
timeout-minutes: ${{ matrix.timeout }}
|
||||
|
||||
@@ -104,12 +104,14 @@ floci:
|
||||
|
||||
Environment variable: `FLOCI_DOCKER_IMAGE_PULL_TIMEOUT_SECONDS`
|
||||
|
||||
To see how close Floci is to those limits, it logs a line every `pool-gauge-interval-seconds` (60 by default) while a pool is in use, and nothing while both are idle. Each pool reports its leased, available and pending connections against its limit and its open streams by kind, followed by the number of docker-java stream threads:
|
||||
To see how close Floci is to those limits, it logs a line every `pool-gauge-interval-seconds` (60 by default) while a pool is in use, and nothing while both are idle. Each pool reports its leased, available and pending connections against its limit and its open streams by kind and by the service whose container each one follows, followed by the number of docker-java stream threads:
|
||||
|
||||
```
|
||||
Docker pools: control-plane leased=2 available=6 pending=0 max=1024; streaming leased=40 available=0 pending=0 max=2048 streams[logs=20 wait=20]; stream threads=40
|
||||
Docker pools: control-plane leased=2 available=6 pending=0 max=1024; streaming leased=40 available=0 pending=0 max=2048 streams[logs=20 wait=20] services[lambda=36 unattributed=4]; stream threads=40
|
||||
```
|
||||
|
||||
A stream is `unattributed` when it follows no container (an exec, an image pull or build, daemon events), or a container this Floci process did not start with a service label: one started before a restart, by a tool other than Floci, or by a Floci helper that labels no service.
|
||||
|
||||
A `pending` above 0 means calls are waiting for a connection, and a call that waits longer than `connection-request-timeout-seconds` fails. To turn the lines off, set the interval to 0:
|
||||
|
||||
```yaml
|
||||
|
||||
@@ -400,6 +400,7 @@ public class ContainerLifecycleManager {
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
DockerContainerServices.record(containerId, spec.name(), labels);
|
||||
LOG.infov("Created container {0} (name={1}, not yet started)", containerId, spec.name());
|
||||
return containerId;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The Floci service each container was created for, read from its {@code io.floci.service} label, so
|
||||
* the Docker transport can count the streams it holds open per service. {@link ContainerLifecycleManager}
|
||||
* records a container when it creates one, under its id and its name; {@link FlociDockerHttpClient}
|
||||
* forgets it once a remove of it succeeds, whichever caller sent the remove. A stream that names no
|
||||
* container (an exec, a pull, a build, daemon events), and one following a container not recorded (one
|
||||
* created without the label, before a restart, or other than through {@link ContainerLifecycleManager}),
|
||||
* is {@link #UNATTRIBUTED}. A container removed outside Floci's transport keeps its entry, and so its
|
||||
* service, until the process ends.
|
||||
*/
|
||||
final class DockerContainerServices {
|
||||
|
||||
/** The service of a stream whose container is unknown, or that follows no container. */
|
||||
static final String UNATTRIBUTED = "unattributed";
|
||||
|
||||
private static final Map<String, Owner> OWNERS = new ConcurrentHashMap<>();
|
||||
|
||||
private DockerContainerServices() {
|
||||
}
|
||||
|
||||
/** Records the service a container's labels name; a container without the label is not recorded. */
|
||||
static void record(String containerId, String containerName, Map<String, String> labels) {
|
||||
String service = labels == null ? null
|
||||
: ContainerStorageHelper.labelValue(labels, ContainerStorageHelper.SERVICE_LABEL);
|
||||
if (containerId == null || service == null || service.isBlank()) {
|
||||
return;
|
||||
}
|
||||
boolean named = containerName != null && !containerName.isBlank();
|
||||
OWNERS.put(containerId, new Owner(service, named ? containerName : null));
|
||||
if (named) {
|
||||
Owner previous = OWNERS.put(containerName, new Owner(service, containerId));
|
||||
// An earlier container of this name (removed outside the transport) keeps its own id's
|
||||
// entry, but no longer as this name's other key, so forgetting it leaves the new name be.
|
||||
if (previous != null && previous.alias() != null && !previous.alias().equals(containerId)) {
|
||||
OWNERS.replace(previous.alias(), new Owner(previous.service(), containerName),
|
||||
new Owner(previous.service(), null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The service the container with this id or name was created for, or {@link #UNATTRIBUTED}. */
|
||||
static String serviceOf(String container) {
|
||||
Owner owner = container == null ? null : OWNERS.get(container);
|
||||
return owner == null ? UNATTRIBUTED : owner.service();
|
||||
}
|
||||
|
||||
/** Forgets a removed container, given by its id or its name. */
|
||||
static void forget(String container) {
|
||||
Owner owner = OWNERS.remove(container);
|
||||
if (owner != null && owner.alias() != null) {
|
||||
// Only while the other key still points back here: a newer container may hold the name now.
|
||||
OWNERS.remove(owner.alias(), new Owner(owner.service(), container));
|
||||
}
|
||||
}
|
||||
|
||||
/** @param alias the container's other key (its name for an id, its id for a name), or null */
|
||||
private record Owner(String service, String alias) {
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,8 @@ import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Logs how busy the Docker connection pools are, once per interval: for each pool its leased,
|
||||
* available and pending connections against its limit and its open long-lived streams by kind, then
|
||||
* available and pending connections against its limit and its open long-lived streams by kind and by
|
||||
* the service of the container they follow ({@link DockerContainerServices}), then
|
||||
* the number of docker-java stream threads. A line is written only while some pool has a lease, a
|
||||
* caller waiting for one, or an open stream, so an idle emulator logs nothing. It is the measurement
|
||||
* the Docker admission work is sized from (BL-215); there is no metrics endpoint.
|
||||
@@ -80,7 +81,7 @@ final class DockerPoolGaugeLogger {
|
||||
* The text of one reading, pools in name order, or null when every pool is idle, in which case the
|
||||
* stream threads are not counted. For example
|
||||
* {@code control-plane leased=2 available=6 pending=0 max=1024; streaming leased=40 available=0
|
||||
* pending=0 max=2048 streams[logs=20 wait=20]; stream threads=40}.
|
||||
* pending=0 max=2048 streams[logs=20 wait=20] services[lambda=36 unattributed=4]; stream threads=40}.
|
||||
*/
|
||||
static String line(Map<String, FlociDockerHttpClient.PoolGauges> readings, IntSupplier streamThreads) {
|
||||
if (readings.values().stream().allMatch(FlociDockerHttpClient.PoolGauges::idle)) {
|
||||
@@ -98,6 +99,11 @@ final class DockerPoolGaugeLogger {
|
||||
reading.openStreams().forEach((kind, open) -> streams.add(kind + "=" + open));
|
||||
part.append(" streams[").append(String.join(" ", streams)).append(']');
|
||||
}
|
||||
if (!reading.openStreamsByService().isEmpty()) {
|
||||
List<String> services = new ArrayList<>();
|
||||
reading.openStreamsByService().forEach((service, open) -> services.add(service + "=" + open));
|
||||
part.append(" services[").append(String.join(" ", services)).append(']');
|
||||
}
|
||||
parts.add(part.toString());
|
||||
});
|
||||
parts.add("stream threads=" + streamThreads.getAsInt());
|
||||
|
||||
@@ -61,6 +61,8 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@@ -91,10 +93,15 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
/** Idle pooled connections are closed in the background after this long. */
|
||||
static final TimeValue EVICT_IDLE_AFTER = TimeValue.ofSeconds(30);
|
||||
|
||||
/** A route under {@code /containers/}, with or without the API version in front: the rest is group 1. */
|
||||
private static final Pattern CONTAINER_ROUTE = Pattern.compile("(?:/v\\d+(?:\\.\\d+)*)?/containers/(.*)");
|
||||
|
||||
private final CloseableHttpClient httpClient;
|
||||
private final PoolingHttpClientConnectionManager connectionManager;
|
||||
/** Responses still open per {@link #streamKind} of the request that opened them. */
|
||||
private final Map<String, AtomicInteger> openStreams = new ConcurrentHashMap<>();
|
||||
/** The same responses per service of the container they follow, see {@link DockerContainerServices}. */
|
||||
private final Map<String, AtomicInteger> openStreamsByService = new ConcurrentHashMap<>();
|
||||
private final HttpHost host;
|
||||
private final String pathPrefix;
|
||||
/** The same settings with no response timeout, for requests that hold a stream open (see isLongLivedStream). */
|
||||
@@ -221,11 +228,18 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
boolean ttyExec = isTtyExec(request);
|
||||
ClassicHttpResponse response = httpClient.executeOpen(host, httpRequest, context);
|
||||
AtomicInteger openOfKind = null;
|
||||
AtomicInteger openOfService = null;
|
||||
if (streamKind != null) {
|
||||
openOfKind = openStreams.computeIfAbsent(streamKind, kind -> new AtomicInteger());
|
||||
openOfKind.incrementAndGet();
|
||||
openOfService = openStreamsByService.computeIfAbsent(
|
||||
DockerContainerServices.serviceOf(streamContainer(request)), service -> new AtomicInteger());
|
||||
openOfService.incrementAndGet();
|
||||
} else {
|
||||
forgetIfRemoved(request, response.getCode());
|
||||
}
|
||||
return new FlociResponse(httpRequest, response, ttyExec && response.getCode() == 200, openOfKind);
|
||||
return new FlociResponse(httpRequest, response, ttyExec && response.getCode() == 200,
|
||||
openOfKind, openOfService);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
} catch (LinkageError e) {
|
||||
@@ -246,22 +260,32 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
|
||||
/**
|
||||
* The pool's leased, available and pending connections and its limit, and the long-lived stream
|
||||
* responses still open by kind (only kinds with an open stream are listed), read at this moment.
|
||||
* responses still open by kind and by service (only those with an open stream are listed), read
|
||||
* at this moment.
|
||||
*/
|
||||
public PoolGauges gauges() {
|
||||
PoolStats stats = connectionManager.getTotalStats();
|
||||
Map<String, Integer> streams = new TreeMap<>();
|
||||
openStreams.forEach((kind, open) -> {
|
||||
int count = open.get();
|
||||
if (count > 0) {
|
||||
streams.put(kind, count);
|
||||
}
|
||||
});
|
||||
return new PoolGauges(stats.getLeased(), stats.getAvailable(), stats.getPending(), stats.getMax(), streams);
|
||||
return new PoolGauges(stats.getLeased(), stats.getAvailable(), stats.getPending(), stats.getMax(),
|
||||
nonZero(openStreams), nonZero(openStreamsByService));
|
||||
}
|
||||
|
||||
/** A point-in-time reading of one pool, see {@link #gauges()}. */
|
||||
public record PoolGauges(int leased, int available, int pending, int max, Map<String, Integer> openStreams) {
|
||||
private static Map<String, Integer> nonZero(Map<String, AtomicInteger> counts) {
|
||||
Map<String, Integer> open = new TreeMap<>();
|
||||
counts.forEach((key, count) -> {
|
||||
int value = count.get();
|
||||
if (value > 0) {
|
||||
open.put(key, value);
|
||||
}
|
||||
});
|
||||
return open;
|
||||
}
|
||||
|
||||
/**
|
||||
* A point-in-time reading of one pool, see {@link #gauges()}. {@code openStreamsByService} counts
|
||||
* the same streams as {@code openStreams}, by the service of the container each follows.
|
||||
*/
|
||||
public record PoolGauges(int leased, int available, int pending, int max, Map<String, Integer> openStreams,
|
||||
Map<String, Integer> openStreamsByService) {
|
||||
|
||||
/** Whether nothing is in use: no lease, no caller waiting for one and no stream open. */
|
||||
public boolean idle() {
|
||||
@@ -330,6 +354,48 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
return kind == null && request.hijackedInput() != null ? "hijacked" : kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* The container a stream follows, as the request names it (an id or a name), or null for a stream
|
||||
* that follows none: an exec start names its exec, and pulls, builds and events no container.
|
||||
*/
|
||||
static String streamContainer(Request request) {
|
||||
String[] segments = containerRoute(request.path());
|
||||
return segments != null && segments.length == 2 ? segments[0] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* After an ordinary call: a container removed (or already gone) is forgotten by
|
||||
* {@link DockerContainerServices}, so its entry does not outlive it.
|
||||
*/
|
||||
private static void forgetIfRemoved(Request request, int statusCode) {
|
||||
if (!"DELETE".equals(request.method()) || (statusCode >= 300 && statusCode != 404)) {
|
||||
return;
|
||||
}
|
||||
String[] segments = containerRoute(request.path());
|
||||
if (segments != null && segments.length == 1) {
|
||||
DockerContainerServices.forget(segments[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The route segments after {@code /containers/}, at most two (the container and its action), or
|
||||
* null when the route is not about one container.
|
||||
*/
|
||||
private static String[] containerRoute(String path) {
|
||||
int queryStart = path.indexOf('?');
|
||||
String route = queryStart < 0 ? path : path.substring(0, queryStart);
|
||||
// Only a route that is itself under /containers/, not an image name such as quay.io/containers/podman.
|
||||
Matcher matcher = CONTAINER_ROUTE.matcher(route);
|
||||
if (!matcher.matches()) {
|
||||
return null;
|
||||
}
|
||||
String[] segments = matcher.group(1).split("/");
|
||||
if (segments.length == 0 || segments.length > 2 || segments[0].isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
/** A boolean query parameter as Docker reads it ({@code 1} or {@code true}), or its default when absent. */
|
||||
private static boolean queryFlag(String query, String name, boolean defaultValue) {
|
||||
for (String param : query.split("&")) {
|
||||
@@ -399,17 +465,19 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
private final HttpUriRequestBase request;
|
||||
private final ClassicHttpResponse response;
|
||||
private final boolean ttyExec;
|
||||
/** The open-stream count this response is in, or null for an ordinary call. */
|
||||
/** The open-stream counts this response is in, by kind and by service, or null for an ordinary call. */
|
||||
private final AtomicInteger openOfKind;
|
||||
private final AtomicInteger openOfService;
|
||||
private final AtomicBoolean closed = new AtomicBoolean();
|
||||
private InputStream body;
|
||||
|
||||
FlociResponse(HttpUriRequestBase request, ClassicHttpResponse response, boolean ttyExec,
|
||||
AtomicInteger openOfKind) {
|
||||
AtomicInteger openOfKind, AtomicInteger openOfService) {
|
||||
this.request = request;
|
||||
this.response = response;
|
||||
this.ttyExec = ttyExec;
|
||||
this.openOfKind = openOfKind;
|
||||
this.openOfService = openOfService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -448,6 +516,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
public void close() {
|
||||
if (openOfKind != null && closed.compareAndSet(false, true)) {
|
||||
openOfKind.decrementAndGet();
|
||||
openOfService.decrementAndGet();
|
||||
}
|
||||
try {
|
||||
request.abort();
|
||||
|
||||
+16
@@ -101,6 +101,22 @@ class ContainerLifecycleManagerLabelsTest {
|
||||
capturedLabels(createCmd));
|
||||
}
|
||||
|
||||
// Catches: a container created without being recorded, so every stream that follows it is
|
||||
// reported as unattributed in the Docker pool line.
|
||||
@Test
|
||||
void createRecordsTheServiceTheContainerIsLabelledWith() {
|
||||
stubCreateContainer();
|
||||
|
||||
try {
|
||||
manager().create(specWithLabels(
|
||||
ContainerStorageHelper.resourceIdentityLabels("rds", "db-1", "000000000000", "us-east-1")));
|
||||
|
||||
assertEquals("rds", DockerContainerServices.serviceOf("container-id"));
|
||||
} finally {
|
||||
DockerContainerServices.forget("container-id");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void createWritesTheLegacyAliasOfEachNewKeyWithTheSameValue() {
|
||||
CreateContainerCmd createCmd = stubCreateContainer();
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class DockerContainerServicesTest {
|
||||
|
||||
@AfterEach
|
||||
void forgetTheTestContainers() {
|
||||
DockerContainerServices.forget("services-test-id");
|
||||
DockerContainerServices.forget("services-test-unlabelled");
|
||||
DockerContainerServices.forget("services-test-old");
|
||||
DockerContainerServices.forget("services-test-name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerWithoutTheServiceLabelIsUnattributed() {
|
||||
DockerContainerServices.record("services-test-unlabelled", null, Map.of("floci", "true"));
|
||||
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED,
|
||||
DockerContainerServices.serviceOf("services-test-unlabelled"));
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED, DockerContainerServices.serviceOf(null));
|
||||
}
|
||||
|
||||
// Catches: forgetting a container removed outside the transport also wiping a newer container's
|
||||
// entry under the same name, so that one's name-keyed streams read as unattributed.
|
||||
@Test
|
||||
void forgettingAnOldContainerLeavesANewerOneOfTheSameNameAttributed() {
|
||||
DockerContainerServices.record("services-test-old", "services-test-name",
|
||||
Map.of(ContainerStorageHelper.SERVICE_LABEL, "lambda"));
|
||||
DockerContainerServices.record("services-test-id", "services-test-name",
|
||||
Map.of(ContainerStorageHelper.SERVICE_LABEL, "ecs"));
|
||||
|
||||
DockerContainerServices.forget("services-test-old");
|
||||
|
||||
assertEquals("ecs", DockerContainerServices.serviceOf("services-test-name"));
|
||||
assertEquals("ecs", DockerContainerServices.serviceOf("services-test-id"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aContainerIsKnownByItsIdAndItsNameUntilEitherIsForgotten() {
|
||||
DockerContainerServices.record("services-test-id", "services-test-name",
|
||||
Map.of(ContainerStorageHelper.SERVICE_LABEL, "opensearch"));
|
||||
assertEquals("opensearch", DockerContainerServices.serviceOf("services-test-id"));
|
||||
assertEquals("opensearch", DockerContainerServices.serviceOf("services-test-name"));
|
||||
|
||||
DockerContainerServices.forget("services-test-name");
|
||||
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED, DockerContainerServices.serviceOf("services-test-id"));
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED, DockerContainerServices.serviceOf("services-test-name"));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
class DockerPoolGaugeLoggerTest {
|
||||
|
||||
private static final FlociDockerHttpClient.PoolGauges IDLE =
|
||||
new FlociDockerHttpClient.PoolGauges(0, 3, 0, 1024, Map.of());
|
||||
new FlociDockerHttpClient.PoolGauges(0, 3, 0, 1024, Map.of(), Map.of());
|
||||
|
||||
// Catches: an idle emulator writing a pool line every interval, or paying for a thread scan on a
|
||||
// reading that writes nothing.
|
||||
@@ -26,11 +26,13 @@ class DockerPoolGaugeLoggerTest {
|
||||
void aBusyPoolReportsEveryPoolInNameOrderWithItsStreamsAndTheStreamThreads() {
|
||||
Map<String, FlociDockerHttpClient.PoolGauges> readings = new TreeMap<>();
|
||||
readings.put("streaming", new FlociDockerHttpClient.PoolGauges(40, 0, 0, 2048,
|
||||
new TreeMap<>(Map.of("wait", 20, "logs", 20))));
|
||||
new TreeMap<>(Map.of("wait", 20, "logs", 20)),
|
||||
new TreeMap<>(Map.of("lambda", 36, "unattributed", 4))));
|
||||
readings.put("control-plane", IDLE);
|
||||
|
||||
assertEquals("control-plane leased=0 available=3 pending=0 max=1024; "
|
||||
+ "streaming leased=40 available=0 pending=0 max=2048 streams[logs=20 wait=20]; "
|
||||
+ "streaming leased=40 available=0 pending=0 max=2048 streams[logs=20 wait=20] "
|
||||
+ "services[lambda=36 unattributed=4]; "
|
||||
+ "stream threads=40",
|
||||
DockerPoolGaugeLogger.line(readings, () -> 40));
|
||||
}
|
||||
@@ -38,7 +40,8 @@ class DockerPoolGaugeLoggerTest {
|
||||
// Catches: callers waiting on a full pool reading as idle because no connection is leased yet.
|
||||
@Test
|
||||
void aCallerWaitingForAConnectionIsNotIdle() {
|
||||
FlociDockerHttpClient.PoolGauges waiting = new FlociDockerHttpClient.PoolGauges(0, 0, 2, 1, Map.of());
|
||||
FlociDockerHttpClient.PoolGauges waiting =
|
||||
new FlociDockerHttpClient.PoolGauges(0, 0, 2, 1, Map.of(), Map.of());
|
||||
|
||||
assertEquals("control-plane leased=0 available=0 pending=2 max=1; stream threads=0",
|
||||
DockerPoolGaugeLogger.line(Map.of("control-plane", waiting), () -> 0));
|
||||
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
package io.floci.aws.core.common.docker;
|
||||
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.PullImageResultCallback;
|
||||
import com.github.dockerjava.api.exception.NotFoundException;
|
||||
import com.github.dockerjava.api.model.Container;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import com.github.dockerjava.api.model.WaitResponse;
|
||||
import com.github.dockerjava.core.DefaultDockerClientConfig;
|
||||
import com.github.dockerjava.core.DockerClientImpl;
|
||||
import io.floci.aws.config.EmulatorConfig;
|
||||
import io.floci.aws.testing.DockerAvailability;
|
||||
import io.floci.aws.testing.TestImages;
|
||||
import io.smallrye.config.SmallRyeConfigBuilder;
|
||||
import org.apache.hc.core5.http.ConnectionRequestTimeoutException;
|
||||
import org.jboss.logging.Logger;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.condition.EnabledIfSystemProperty;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Saturation harness for the Docker transport (BL-706). It starts idle containers the way Lambda
|
||||
* does, each followed by a log stream and a container wait on the streaming pool, in steps, and at
|
||||
* each step logs what one more container costs: its start latency, the latency of a control-plane
|
||||
* ping, the streaming pool's leases and the docker-java stream threads. These are the numbers the
|
||||
* admission work (BL-212, BL-216, BL-217) is sized from.
|
||||
*
|
||||
* <p>It holds stream leases, which no response timeout releases, so it cannot drain itself (that
|
||||
* these streams carry no response timeout is covered by {@link FlociDockerHttpClientTest}). The
|
||||
* streaming pool is sized for exactly the containers the ramp starts, so the stream of one more waits for a
|
||||
* connection and fails with the lease timeout, the failure a saturated Floci reports.
|
||||
*
|
||||
* <p>Each container carries the {@code io.floci.service} label and is recorded the way
|
||||
* {@link ContainerLifecycleManager} records the containers it creates, so the streams it holds are
|
||||
* checked to be counted under that service, and its remove to forget it.
|
||||
*
|
||||
* <p>{@code -Ddocker.saturation.containers=N} raises the ramp (default 40) to measure a host; the
|
||||
* three-minute bound fits the default on a hosted runner, so a much larger ramp needs it raised too.
|
||||
*/
|
||||
@EnabledIfSystemProperty(named = "nightly.checks.enabled", matches = "true")
|
||||
class DockerPoolSaturationNightlyIntegrationTest {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(DockerPoolSaturationNightlyIntegrationTest.class);
|
||||
|
||||
private static final String LABEL = "floci.test";
|
||||
private static final String LABEL_VALUE = "docker-pool-saturation";
|
||||
/** The service the ramp's containers stand in for, as Lambda's log follow and exit wait. */
|
||||
private static final String SERVICE = "lambda";
|
||||
private static final int CONTAINERS = Integer.getInteger("docker.saturation.containers", 40);
|
||||
private static final int STEP = Math.max(1, CONTAINERS / 4);
|
||||
/** The streaming pool's response timeout, which its long-lived streams do not carry. */
|
||||
private static final Duration RESPONSE_TIMEOUT = Duration.ofSeconds(3);
|
||||
/** The control plane's, long enough for a create, start or remove on a loaded runner. */
|
||||
private static final Duration CONTROL_TIMEOUT = Duration.ofSeconds(60);
|
||||
private static final Duration LEASE_TIMEOUT = Duration.ofSeconds(2);
|
||||
|
||||
private FlociDockerHttpClient streamingTransport;
|
||||
private DockerClient control;
|
||||
private DockerClient streaming;
|
||||
private boolean dockerAvailable;
|
||||
private final List<String> containers = Collections.synchronizedList(new ArrayList<>());
|
||||
private final List<Closeable> streams = Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
@BeforeEach
|
||||
void connect() {
|
||||
EmulatorConfig config = new SmallRyeConfigBuilder().withMapping(EmulatorConfig.class)
|
||||
.build().getConfigMapping(EmulatorConfig.class);
|
||||
String host = DockerClientProducer.resolveDockerConnection(config.docker(), System::getenv).host();
|
||||
DefaultDockerClientConfig clientConfig = DefaultDockerClientConfig.createDefaultConfigBuilder()
|
||||
.withDockerHost(host).build();
|
||||
control = DockerClientImpl.getInstance(clientConfig, DockerClientProducer.wrapForRole(
|
||||
DockerClientProducer.newHttpClient(clientConfig, 16, CONTROL_TIMEOUT, LEASE_TIMEOUT), "control-plane",
|
||||
CONTROL_TIMEOUT));
|
||||
// Two streams per container, the log follow and the wait, and not one connection more.
|
||||
streamingTransport = DockerClientProducer.newHttpClient(clientConfig, 2 * CONTAINERS, RESPONSE_TIMEOUT,
|
||||
LEASE_TIMEOUT);
|
||||
streaming = DockerClientImpl.getInstance(clientConfig,
|
||||
DockerClientProducer.wrapForRole(streamingTransport, "streaming", RESPONSE_TIMEOUT));
|
||||
dockerAvailable = DockerAvailability.answers(control);
|
||||
Assumptions.assumeTrue(dockerAvailable, "Docker daemon is unavailable");
|
||||
removeLeftovers();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() throws IOException {
|
||||
try {
|
||||
synchronized (streams) {
|
||||
for (Closeable stream : streams) {
|
||||
closeQuietly(stream);
|
||||
}
|
||||
}
|
||||
if (control != null && dockerAvailable) {
|
||||
synchronized (containers) {
|
||||
for (String id : containers) {
|
||||
removeQuietly(id);
|
||||
}
|
||||
}
|
||||
removeLeftovers();
|
||||
}
|
||||
} finally {
|
||||
// A cleanup that throws still leaves no connection pool open for the rest of the run.
|
||||
try {
|
||||
if (control != null) {
|
||||
control.close();
|
||||
}
|
||||
} finally {
|
||||
if (streaming != null) {
|
||||
streaming.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Timeout(value = 3, unit = TimeUnit.MINUTES)
|
||||
void aFullStreamingPoolMakesTheNextStreamWaitThenFailOnTheLeaseTimeout() throws Exception {
|
||||
try (PullImageResultCallback pulled = new PullImageResultCallback()) {
|
||||
assertTrue(control.pullImageCmd(TestImages.BUSYBOX).exec(pulled).awaitCompletion(120, TimeUnit.SECONDS),
|
||||
"pulling " + TestImages.BUSYBOX);
|
||||
}
|
||||
|
||||
List<String> report = new ArrayList<>();
|
||||
report.add("containers start-ms(median) ping-ms(median) streaming-leased pending stream-threads");
|
||||
for (int started = 0; started < CONTAINERS; ) {
|
||||
int target = Math.min(CONTAINERS, started + STEP);
|
||||
List<Long> startMillis = new ArrayList<>();
|
||||
for (; started < target; started++) {
|
||||
String id = createIdleContainer();
|
||||
long begin = System.nanoTime();
|
||||
control.startContainerCmd(id).exec();
|
||||
startMillis.add(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin));
|
||||
followLikeLambda(id);
|
||||
}
|
||||
int expected = 2 * target;
|
||||
FlociDockerHttpClient.PoolGauges reading = awaitGauges(gauges -> gauges.leased() == expected,
|
||||
"the streaming pool to hold " + expected + " streams");
|
||||
report.add(String.format("%10d %16d %15d %16d %7d %14d", target, median(startMillis),
|
||||
median(pingMillis()), reading.leased(), reading.pending(),
|
||||
DockerPoolGaugeLogger.countStreamThreads()));
|
||||
}
|
||||
LOG.infov("Docker pool saturation, {0} containers in steps of {1}:\n{2}", CONTAINERS, STEP,
|
||||
String.join("\n", report));
|
||||
|
||||
FlociDockerHttpClient.PoolGauges quiet = streamingTransport.gauges();
|
||||
assertEquals(2 * CONTAINERS, quiet.leased(), "every container should hold both of its streams: " + quiet);
|
||||
assertEquals(Map.of("logs", CONTAINERS, "wait", CONTAINERS), quiet.openStreams());
|
||||
// docker-java reads each stream on a thread of its own, so the threads grow with the streams too.
|
||||
int streamThreads = DockerPoolGaugeLogger.countStreamThreads();
|
||||
assertTrue(streamThreads >= 2 * CONTAINERS, "one docker-java stream thread per open stream, counted "
|
||||
+ streamThreads);
|
||||
assertEquals(Map.of(SERVICE, 2 * CONTAINERS), quiet.openStreamsByService(),
|
||||
"every stream should be counted under the service of the container it follows");
|
||||
|
||||
// The pool is full: one more container's log stream waits for a connection, then fails.
|
||||
String extra = createIdleContainer();
|
||||
control.startContainerCmd(extra).exec();
|
||||
CompletableFuture<Throwable> failure = new CompletableFuture<>();
|
||||
long begin = System.nanoTime();
|
||||
streams.add(followLogs(extra, new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onError(Throwable throwable) {
|
||||
failure.complete(throwable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
failure.complete(null);
|
||||
}
|
||||
}));
|
||||
FlociDockerHttpClient.PoolGauges waiting = awaitGauges(gauges -> gauges.pending() >= 1,
|
||||
"the extra stream to wait for a connection");
|
||||
assertEquals(2 * CONTAINERS, waiting.leased(), waiting.toString());
|
||||
|
||||
Throwable error = failure.get(LEASE_TIMEOUT.multipliedBy(10).toMillis(), TimeUnit.MILLISECONDS);
|
||||
long waitedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin);
|
||||
assertTrue(error != null, "the extra stream should fail, not complete");
|
||||
assertInstanceOf(ConnectionRequestTimeoutException.class, rootCause(error), "got " + error);
|
||||
assertTrue(waitedMillis >= LEASE_TIMEOUT.toMillis() - 200,
|
||||
"should fail after the " + LEASE_TIMEOUT.toMillis() + " ms lease timeout, took " + waitedMillis + " ms");
|
||||
LOG.infov("With {0} streams open the next one waited {1} ms and failed with {2}", 2 * CONTAINERS,
|
||||
waitedMillis, rootCause(error).getClass().getSimpleName());
|
||||
|
||||
// A remove that succeeds forgets the container, whichever transport sent it.
|
||||
assertEquals(SERVICE, DockerContainerServices.serviceOf(extra));
|
||||
control.removeContainerCmd(extra).withForce(true).exec();
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED, DockerContainerServices.serviceOf(extra));
|
||||
}
|
||||
|
||||
private String createIdleContainer() {
|
||||
Map<String, String> labels = Map.of(LABEL, LABEL_VALUE, ContainerStorageHelper.SERVICE_LABEL, SERVICE);
|
||||
String id = control.createContainerCmd(TestImages.BUSYBOX)
|
||||
.withCmd("sleep", "600")
|
||||
.withLabels(labels)
|
||||
.exec().getId();
|
||||
DockerContainerServices.record(id, null, labels);
|
||||
containers.add(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
/** The two streams a Lambda container holds on the streaming pool: its log follow and its exit wait. */
|
||||
private void followLikeLambda(String id) {
|
||||
streams.add(followLogs(id, new ResultCallback.Adapter<Frame>() {
|
||||
@Override
|
||||
public void onError(Throwable ignored) {
|
||||
// Expected once the test closes the stream.
|
||||
}
|
||||
}));
|
||||
streams.add(streaming.waitContainerCmd(id).exec(new ResultCallback.Adapter<WaitResponse>() {
|
||||
@Override
|
||||
public void onError(Throwable ignored) {
|
||||
// Expected once the test closes the stream.
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
/** Follows a container's stdout and stderr on the streaming pool, as Lambda's log follow does. */
|
||||
private <T extends ResultCallback<Frame>> T followLogs(String id, T callback) {
|
||||
return streaming.logContainerCmd(id).withStdOut(true).withStdErr(true).withFollowStream(true).exec(callback);
|
||||
}
|
||||
|
||||
private List<Long> pingMillis() {
|
||||
List<Long> millis = new ArrayList<>();
|
||||
for (int i = 0; i < 5; i++) {
|
||||
long begin = System.nanoTime();
|
||||
control.pingCmd().exec();
|
||||
millis.add(TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - begin));
|
||||
}
|
||||
return millis;
|
||||
}
|
||||
|
||||
private FlociDockerHttpClient.PoolGauges awaitGauges(Predicate<FlociDockerHttpClient.PoolGauges> condition,
|
||||
String what) throws InterruptedException {
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
FlociDockerHttpClient.PoolGauges reading = streamingTransport.gauges();
|
||||
while (!condition.test(reading)) {
|
||||
if (System.nanoTime() > deadline) {
|
||||
fail("timed out waiting for " + what + ": " + reading);
|
||||
}
|
||||
Thread.sleep(50);
|
||||
reading = streamingTransport.gauges();
|
||||
}
|
||||
return reading;
|
||||
}
|
||||
|
||||
private static long median(List<Long> values) {
|
||||
List<Long> sorted = new ArrayList<>(values);
|
||||
Collections.sort(sorted);
|
||||
return sorted.get(sorted.size() / 2);
|
||||
}
|
||||
|
||||
private static Throwable rootCause(Throwable error) {
|
||||
Throwable cause = error;
|
||||
while (cause.getCause() != null && cause.getCause() != cause) {
|
||||
cause = cause.getCause();
|
||||
}
|
||||
return cause;
|
||||
}
|
||||
|
||||
private void removeLeftovers() {
|
||||
for (Container container : control.listContainersCmd().withShowAll(true)
|
||||
.withLabelFilter(Map.of(LABEL, LABEL_VALUE)).exec()) {
|
||||
removeQuietly(container.getId());
|
||||
}
|
||||
}
|
||||
|
||||
private void removeQuietly(String id) {
|
||||
try {
|
||||
control.removeContainerCmd(id).withForce(true).exec();
|
||||
} catch (NotFoundException expected) {
|
||||
LOG.debugv("Container {0} was already removed", id);
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "Container {0} could not be removed; it may be left running", id);
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeQuietly(Closeable stream) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException e) {
|
||||
LOG.debugv(e, "Closing a stream at teardown");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -395,6 +395,90 @@ class FlociDockerHttpClientTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamContainerNamesTheContainerAStreamFollows() {
|
||||
assertEquals("abc", FlociDockerHttpClient.streamContainer(request("POST /v1.43/containers/abc/wait")));
|
||||
assertEquals("abc", FlociDockerHttpClient.streamContainer(request("GET /containers/abc/logs?follow=1")));
|
||||
assertEquals("fn-1", FlociDockerHttpClient.streamContainer(request("POST /containers/fn-1/attach?stream=1")));
|
||||
assertEquals("abc", FlociDockerHttpClient.streamContainer(request("GET /containers/abc/stats")));
|
||||
// A container may be named like a collection route.
|
||||
assertEquals("create", FlociDockerHttpClient.streamContainer(request("GET /containers/create/logs?follow=1")));
|
||||
assertEquals("json", FlociDockerHttpClient.streamContainer(request("POST /v1.43/containers/json/wait")));
|
||||
for (String noContainer : List.of("POST /exec/abc/start", "POST /images/create?fromImage=alpine",
|
||||
"POST /build", "GET /events", "GET /containers/json", "GET /containers//", "DELETE /containers//",
|
||||
"GET /images/quay.io/containers/podman/json")) {
|
||||
assertNull(FlociDockerHttpClient.streamContainer(request(noContainer)), noContainer);
|
||||
}
|
||||
}
|
||||
|
||||
// Catches: streams reported under the wrong service, or a removed container whose id is still
|
||||
// attributed to its old service (and kept in memory) after the remove succeeded.
|
||||
@Test
|
||||
@Timeout(30)
|
||||
void gaugesCountOpenStreamsByTheServiceOfTheContainerTheyFollow() throws Exception {
|
||||
List<Socket> accepted = new CopyOnWriteArrayList<>();
|
||||
List<DockerHttpClient.Response> open = new CopyOnWriteArrayList<>();
|
||||
DockerContainerServices.record("fn-1", "floci-lambda-fn",
|
||||
ContainerStorageHelper.resourceIdentityLabels("lambda", "fn", "000000000000", "us-east-1"));
|
||||
DockerContainerServices.record("task-1", null,
|
||||
ContainerStorageHelper.resourceIdentityLabels("ecs", "task", "000000000000", "us-east-1"));
|
||||
try (ServerSocket server = new ServerSocket(0)) {
|
||||
Thread acceptor = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
while (true) {
|
||||
Socket socket = server.accept();
|
||||
accepted.add(socket);
|
||||
socket.getOutputStream().write(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
|
||||
+ "Transfer-Encoding: chunked\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
socket.getOutputStream().flush();
|
||||
}
|
||||
} catch (IOException expected) {
|
||||
// The server socket closed at the end of the test.
|
||||
}
|
||||
});
|
||||
try (FlociDockerHttpClient client = new FlociDockerHttpClient.Builder()
|
||||
.dockerHost(URI.create("tcp://127.0.0.1:" + server.getLocalPort()))
|
||||
.maxConnections(8)
|
||||
.responseTimeout(Duration.ofSeconds(30))
|
||||
.connectionRequestTimeout(Duration.ofSeconds(5))
|
||||
.build()) {
|
||||
for (String stream : List.of("POST /containers/fn-1/wait",
|
||||
"GET /containers/floci-lambda-fn/logs?follow=1",
|
||||
"POST /containers/task-1/wait", "POST /exec/e-1/start")) {
|
||||
open.add(client.execute(request(stream)));
|
||||
}
|
||||
|
||||
FlociDockerHttpClient.PoolGauges held = client.gauges();
|
||||
assertEquals(Map.of("lambda", 2, "ecs", 1, DockerContainerServices.UNATTRIBUTED, 1),
|
||||
held.openStreamsByService(), held.toString());
|
||||
assertEquals(Map.of("wait", 2, "logs", 1, "exec", 1), held.openStreams(), held.toString());
|
||||
|
||||
// An image whose name has containers/ in it is not a container remove.
|
||||
open.add(client.execute(request("DELETE /images/quay.io/containers/fn-1")));
|
||||
assertEquals("lambda", DockerContainerServices.serviceOf("fn-1"));
|
||||
|
||||
open.add(client.execute(request("DELETE /containers/fn-1")));
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED, DockerContainerServices.serviceOf("fn-1"));
|
||||
assertEquals(DockerContainerServices.UNATTRIBUTED, DockerContainerServices.serviceOf("floci-lambda-fn"),
|
||||
"removing a container by its id forgets its name too");
|
||||
assertEquals("ecs", DockerContainerServices.serviceOf("task-1"));
|
||||
|
||||
for (DockerHttpClient.Response response : open) {
|
||||
response.close();
|
||||
}
|
||||
assertEquals(Map.of(), client.gauges().openStreamsByService());
|
||||
} finally {
|
||||
for (Socket socket : accepted) {
|
||||
socket.close();
|
||||
}
|
||||
acceptor.interrupt();
|
||||
}
|
||||
} finally {
|
||||
DockerContainerServices.forget("fn-1");
|
||||
DockerContainerServices.forget("task-1");
|
||||
}
|
||||
}
|
||||
|
||||
private static DockerHttpClient.Request request(String methodAndPath) {
|
||||
String[] parts = methodAndPath.split(" ", 2);
|
||||
return DockerHttpClient.Request.builder().method(parts[0]).path(parts[1]).build();
|
||||
|
||||
Reference in new issue
Block a user