mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 16:35:29 -05:00
fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams (#5294)
* fix(core): make Docker read timeouts real on a Unix-socket host, except for long-lived streams docker-java's UnixSocket reads through a blocking channel stream that ignores SO_TIMEOUT, so on the default unix:// Docker host no call ever timed out: a 2-second response timeout let a container wait run 153 seconds, and a hung daemon blocked its caller forever. It is also why httpclient5's stale-connection check, a read with a 1 ms timeout, cannot be enabled there. FlociDockerHttpClient now connects to a unix:// host through UnixDomainSocket, which keeps the channel non-blocking and waits on a selector, so a read with a timeout fails with SocketTimeoutException. Making the timeout real would cut off streams that are silent while healthy, so requests that hold a stream open (container wait, exec and attach output, followed logs, streamed stats, events, image pulls and builds) get no response timeout on any host, which also keeps a TCP host's container wait from dying at five minutes. Every other call keeps the 5-minute timeout. * fix(core): keep the Unix socket's failures IOExceptions on close and interrupt Closing the socket while another thread waited in a read or write could end that wait with the selector's unchecked ClosedSelectorException, since close() may shut the selector between select() and selectedKeys(); callers expecting an IOException did not handle it. It is now a SocketException. A thread reading a silent stream with no timeout spun once interrupted, because select() returns at once while the interrupt flag is set; it now closes the socket and throws ClosedByInterruptException, as the blocking channel it replaced did. The tests wait with a timed get that expects a TimeoutException rather than a fixed sleep, so an early return fails at once, and cover a close during a blocked read and an interrupted read.
This commit is contained in:
1 parent
c09c7ae62b
commit
ddc47a465d
5 files changed
+596
-14
No files matched your search
+60
-14
@@ -10,7 +10,6 @@ package io.github.hectorvent.floci.core.common.docker;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import com.github.dockerjava.transport.NamedPipeSocket;
|
||||
import com.github.dockerjava.transport.SSLConfig;
|
||||
import com.github.dockerjava.transport.UnixSocket;
|
||||
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
|
||||
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
|
||||
import org.apache.hc.client5.http.config.ConnectionConfig;
|
||||
@@ -59,19 +58,23 @@ import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Floci's own Docker HTTP transport over httpclient5: the same transport docker-java's
|
||||
* Floci's own Docker HTTP transport over httpclient5: the transport docker-java's
|
||||
* {@code ApacheDockerHttpClient} builds, owned here so Floci can set what that builder does not
|
||||
* expose (idle-connection validation and eviction, the connection-lease timeout). It currently
|
||||
* applies exactly docker-java's settings: unix, npipe and tcp hosts, TLS from the SSL config, a pool
|
||||
* of {@code maxConnections} for one route, no socket read timeout on the pool ({@code SO_TIMEOUT} 0),
|
||||
* the request's response timeout, no stale-connection validation, and hijacked exec/attach upgrades
|
||||
* through {@link HijackingHttpRequestExecutor}.
|
||||
* expose (idle-connection validation and eviction, the connection-lease timeout). It applies
|
||||
* docker-java's settings (npipe and tcp hosts, TLS from the SSL config, a pool of
|
||||
* {@code maxConnections} for one route, no socket read timeout on the pool, no stale-connection
|
||||
* validation, hijacked exec/attach upgrades through {@link HijackingHttpRequestExecutor}) with two
|
||||
* differences: a {@code unix://} host connects through {@link UnixDomainSocket}, which honours read
|
||||
* timeouts where docker-java's socket ignored them, and requests that hold a stream open get no
|
||||
* response timeout ({@link #isLongLivedStream}), while every other call keeps it.
|
||||
*/
|
||||
public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
|
||||
private final CloseableHttpClient httpClient;
|
||||
private final HttpHost host;
|
||||
private final String pathPrefix;
|
||||
/** The same settings with no response timeout, for requests that hold a stream open (see isLongLivedStream). */
|
||||
private final RequestConfig streamRequestConfig;
|
||||
|
||||
private FlociDockerHttpClient(URI dockerHost, SSLConfig sslConfig, int maxConnections,
|
||||
Duration connectionTimeout, Duration responseTimeout,
|
||||
@@ -110,15 +113,17 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
? Timeout.of(connectionTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
|
||||
.build());
|
||||
|
||||
RequestConfig requestConfig = RequestConfig.custom()
|
||||
.setResponseTimeout(responseTimeout != null
|
||||
? Timeout.of(responseTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
|
||||
.setConnectionRequestTimeout(connectionRequestTimeout != null
|
||||
? Timeout.of(connectionRequestTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
|
||||
.build();
|
||||
streamRequestConfig = RequestConfig.copy(requestConfig).setResponseTimeout(Timeout.DISABLED).build();
|
||||
httpClient = HttpClients.custom()
|
||||
.setRequestExecutor(new HijackingHttpRequestExecutor(null))
|
||||
.setConnectionManager(connectionManager)
|
||||
.setDefaultRequestConfig(RequestConfig.custom()
|
||||
.setResponseTimeout(responseTimeout != null
|
||||
? Timeout.of(responseTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
|
||||
.setConnectionRequestTimeout(connectionRequestTimeout != null
|
||||
? Timeout.of(connectionRequestTimeout.toNanos(), TimeUnit.NANOSECONDS) : null)
|
||||
.build())
|
||||
.setDefaultRequestConfig(requestConfig)
|
||||
.disableConnectionState()
|
||||
.build();
|
||||
}
|
||||
@@ -140,7 +145,7 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
return new DefaultHttpClientConnectionOperator(
|
||||
socksProxy -> {
|
||||
if ("unix".equalsIgnoreCase(scheme)) {
|
||||
return UnixSocket.get(path);
|
||||
return UnixDomainSocket.connect(path);
|
||||
}
|
||||
if ("npipe".equalsIgnoreCase(scheme)) {
|
||||
return new NamedPipeSocket(path);
|
||||
@@ -169,6 +174,10 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
httpRequest.setEntity(new InputStreamEntity(request.body(), null));
|
||||
}
|
||||
|
||||
if (isLongLivedStream(request)) {
|
||||
httpRequest.setConfig(streamRequestConfig);
|
||||
}
|
||||
|
||||
if (request.hijackedInput() != null) {
|
||||
context.setAttribute(HijackingHttpRequestExecutor.HIJACKED_INPUT_ATTRIBUTE, request.hijackedInput());
|
||||
httpRequest.setHeader("Upgrade", "tcp");
|
||||
@@ -188,6 +197,43 @@ public final class FlociDockerHttpClient implements DockerHttpClient {
|
||||
httpClient.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests whose response is a stream that stays open, and may stay silent, for as long as what it
|
||||
* follows: a container wait, exec and attach output, followed logs, streamed stats, daemon events,
|
||||
* and the progress of an image pull or build. The response timeout bounds how long a silent
|
||||
* daemon is waited for, so applied to these it would cut off a quiet but healthy stream; they get
|
||||
* none. Every other call keeps the response timeout.
|
||||
*/
|
||||
static boolean isLongLivedStream(Request request) {
|
||||
if (request.hijackedInput() != null) {
|
||||
return true;
|
||||
}
|
||||
String path = request.path();
|
||||
int queryStart = path.indexOf('?');
|
||||
String route = queryStart < 0 ? path : path.substring(0, queryStart);
|
||||
String query = queryStart < 0 ? "" : path.substring(queryStart + 1);
|
||||
return switch (request.method()) {
|
||||
case "POST" -> route.endsWith("/wait") || route.endsWith("/attach") || route.endsWith("/build")
|
||||
|| route.endsWith("/images/create")
|
||||
|| (route.contains("/exec/") && route.endsWith("/start"));
|
||||
case "GET" -> route.endsWith("/events")
|
||||
|| (route.endsWith("/logs") && queryFlag(query, "follow", false))
|
||||
|| (route.endsWith("/stats") && queryFlag(query, "stream", true));
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
/** 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("&")) {
|
||||
if (param.startsWith(name + "=")) {
|
||||
String value = param.substring(name.length() + 1);
|
||||
return "1".equals(value) || "true".equalsIgnoreCase(value);
|
||||
}
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/** Builds a client; mirrors docker-java's {@code ApacheDockerHttpClient.Builder}. */
|
||||
public static final class Builder {
|
||||
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.SocketAddress;
|
||||
import java.net.SocketException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.UnixDomainSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ClosedByInterruptException;
|
||||
import java.nio.channels.ClosedSelectorException;
|
||||
import java.nio.channels.SelectionKey;
|
||||
import java.nio.channels.Selector;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* A {@link Socket} over a Unix domain socket that honours {@link #setSoTimeout(int)}.
|
||||
*
|
||||
* <p>docker-java's {@code UnixSocket} reads through a blocking channel stream, which ignores the read
|
||||
* timeout, so on a {@code unix://} Docker host no call ever timed out and httpclient5's stale-connection
|
||||
* check (a read with a 1 ms timeout) would block forever. This socket keeps the channel non-blocking and
|
||||
* waits on a {@link Selector}: a read with a timeout fails with {@link SocketTimeoutException} once the
|
||||
* timeout passes without data, and a timeout of zero waits indefinitely, as {@code SO_TIMEOUT} does.
|
||||
* Reads and writes have their own selector and lock, so a hijacked exec can write stdin on one thread
|
||||
* while another reads its output.
|
||||
*
|
||||
* <p>Failures keep the blocking channel's shape, so callers that expect an {@link IOException} still get
|
||||
* one: closing the socket while another thread waits in a read or write ends that wait with a
|
||||
* {@link SocketException} rather than the selector's unchecked {@link ClosedSelectorException}, and an
|
||||
* interrupted thread closes the socket and fails with {@link ClosedByInterruptException} instead of
|
||||
* spinning, since a selector returns at once while the interrupt flag is set.
|
||||
*/
|
||||
final class UnixDomainSocket extends Socket {
|
||||
|
||||
private final SocketChannel channel;
|
||||
private final SocketAddress address;
|
||||
private final Selector readSelector;
|
||||
private final Selector writeSelector;
|
||||
private final Object readLock = new Object();
|
||||
private final Object writeLock = new Object();
|
||||
private final InputStream input = new ChannelInputStream();
|
||||
private final OutputStream output = new ChannelOutputStream();
|
||||
private volatile int soTimeoutMillis;
|
||||
private volatile boolean closed;
|
||||
private volatile boolean inputShutdown;
|
||||
private volatile boolean outputShutdown;
|
||||
|
||||
private UnixDomainSocket(SocketChannel channel, SocketAddress address) throws IOException {
|
||||
this.channel = channel;
|
||||
this.address = address;
|
||||
this.readSelector = Selector.open();
|
||||
this.writeSelector = Selector.open();
|
||||
channel.register(readSelector, SelectionKey.OP_READ);
|
||||
channel.register(writeSelector, SelectionKey.OP_WRITE);
|
||||
}
|
||||
|
||||
/** Connects to the Unix domain socket at {@code path}. */
|
||||
static UnixDomainSocket connect(String path) throws IOException {
|
||||
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(path);
|
||||
SocketChannel channel = SocketChannel.open(address);
|
||||
try {
|
||||
channel.configureBlocking(false);
|
||||
return new UnixDomainSocket(channel, address);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
channel.close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect(SocketAddress endpoint) {
|
||||
// Already connected by connect(String): httpclient5 calls this on the socket its factory returned.
|
||||
}
|
||||
|
||||
@Override
|
||||
public void connect(SocketAddress endpoint, int timeout) {
|
||||
// Already connected by connect(String).
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream getInputStream() throws IOException {
|
||||
ensureOpen();
|
||||
if (inputShutdown) {
|
||||
throw new SocketException("Socket input is shutdown");
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OutputStream getOutputStream() throws IOException {
|
||||
ensureOpen();
|
||||
if (outputShutdown) {
|
||||
throw new SocketException("Socket output is shutdown");
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSoTimeout(int timeout) throws SocketException {
|
||||
if (timeout < 0) {
|
||||
throw new IllegalArgumentException("timeout can't be negative");
|
||||
}
|
||||
soTimeoutMillis = timeout;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getSoTimeout() {
|
||||
return soTimeoutMillis;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdownInput() throws IOException {
|
||||
ensureOpen();
|
||||
channel.shutdownInput();
|
||||
inputShutdown = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdownOutput() throws IOException {
|
||||
ensureOpen();
|
||||
channel.shutdownOutput();
|
||||
outputShutdown = true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
readSelector.wakeup();
|
||||
writeSelector.wakeup();
|
||||
try {
|
||||
channel.close();
|
||||
} finally {
|
||||
readSelector.close();
|
||||
writeSelector.close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isConnected() {
|
||||
return channel.isConnected();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBound() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isInputShutdown() {
|
||||
return inputShutdown;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isOutputShutdown() {
|
||||
return outputShutdown;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getLocalSocketAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public SocketAddress getRemoteSocketAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getInetAddress() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InetAddress getLocalAddress() {
|
||||
return null;
|
||||
}
|
||||
|
||||
private void ensureOpen() throws SocketException {
|
||||
if (closed) {
|
||||
throw new SocketException("Socket is closed");
|
||||
}
|
||||
}
|
||||
|
||||
private int read(ByteBuffer buffer) throws IOException {
|
||||
synchronized (readLock) {
|
||||
int timeout = soTimeoutMillis;
|
||||
long deadline = timeout > 0 ? System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(timeout) : 0L;
|
||||
try {
|
||||
while (true) {
|
||||
ensureOpen();
|
||||
int read = channel.read(buffer);
|
||||
if (read != 0) {
|
||||
return read;
|
||||
}
|
||||
if (timeout > 0) {
|
||||
long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime());
|
||||
if (remaining <= 0) {
|
||||
throw new SocketTimeoutException("Read timed out");
|
||||
}
|
||||
readSelector.select(remaining);
|
||||
} else {
|
||||
readSelector.select();
|
||||
}
|
||||
failIfInterrupted();
|
||||
readSelector.selectedKeys().clear();
|
||||
}
|
||||
} catch (ClosedSelectorException e) {
|
||||
throw new SocketException("Socket is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void write(ByteBuffer buffer) throws IOException {
|
||||
synchronized (writeLock) {
|
||||
try {
|
||||
while (buffer.hasRemaining()) {
|
||||
ensureOpen();
|
||||
if (channel.write(buffer) == 0) {
|
||||
writeSelector.select();
|
||||
failIfInterrupted();
|
||||
writeSelector.selectedKeys().clear();
|
||||
}
|
||||
}
|
||||
} catch (ClosedSelectorException e) {
|
||||
throw new SocketException("Socket is closed");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void failIfInterrupted() throws IOException {
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
close();
|
||||
throw new ClosedByInterruptException();
|
||||
}
|
||||
}
|
||||
|
||||
private final class ChannelInputStream extends InputStream {
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
byte[] one = new byte[1];
|
||||
int read = read(one, 0, 1);
|
||||
return read == -1 ? -1 : one[0] & 0xff;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] bytes, int offset, int length) throws IOException {
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
return UnixDomainSocket.this.read(ByteBuffer.wrap(bytes, offset, length));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
UnixDomainSocket.this.close();
|
||||
}
|
||||
}
|
||||
|
||||
private final class ChannelOutputStream extends OutputStream {
|
||||
|
||||
@Override
|
||||
public void write(int value) throws IOException {
|
||||
write(new byte[] {(byte) value}, 0, 1);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void write(byte[] bytes, int offset, int length) throws IOException {
|
||||
UnixDomainSocket.this.write(ByteBuffer.wrap(bytes, offset, length));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
UnixDomainSocket.this.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user