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
@@ -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();
|
||||
|
||||
Reference in new issue
Block a user