mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -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
+86
@@ -3,17 +3,31 @@ package io.github.hectorvent.floci.core.common.docker;
|
||||
import com.github.dockerjava.transport.DockerHttpClient;
|
||||
import org.apache.hc.core5.http.ConnectionRequestTimeoutException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.Timeout;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.StandardProtocolFamily;
|
||||
import java.net.UnixDomainSocketAddress;
|
||||
import java.net.Socket;
|
||||
import java.net.URI;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@@ -73,4 +87,76 @@ class FlociDockerHttpClientTest {
|
||||
private static DockerHttpClient.Request get(String path) {
|
||||
return DockerHttpClient.Request.builder().method(DockerHttpClient.Request.Method.GET).path(path).build();
|
||||
}
|
||||
|
||||
// Catches: on a unix:// host, a call to a silent daemon blocking forever because the socket ignored
|
||||
// the response timeout, and a long-lived stream (a container wait) cut off by that timeout once it
|
||||
// applies.
|
||||
@Test
|
||||
@Timeout(60)
|
||||
void overAUnixSocketOrdinaryCallsTimeOutWhileLongLivedStreamsStayOpen(@TempDir Path dir) throws Exception {
|
||||
Path socketPath = dir.resolve("docker.sock");
|
||||
List<SocketChannel> accepted = new CopyOnWriteArrayList<>();
|
||||
try (ServerSocketChannel server = ServerSocketChannel.open(StandardProtocolFamily.UNIX)) {
|
||||
server.bind(UnixDomainSocketAddress.of(socketPath));
|
||||
Thread acceptor = Thread.ofVirtual().start(() -> {
|
||||
try {
|
||||
while (true) {
|
||||
accepted.add(server.accept());
|
||||
}
|
||||
} catch (IOException expected) {
|
||||
// The server channel closed at the end of the test.
|
||||
}
|
||||
});
|
||||
try (FlociDockerHttpClient client = new FlociDockerHttpClient.Builder()
|
||||
.dockerHost(URI.create("unix://" + socketPath))
|
||||
.responseTimeout(Duration.ofSeconds(1))
|
||||
.build()) {
|
||||
long start = System.nanoTime();
|
||||
RuntimeException failure = assertThrows(RuntimeException.class,
|
||||
() -> client.execute(get("/containers/abc/json")));
|
||||
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
|
||||
assertTrue(failure.getCause() instanceof SocketTimeoutException,
|
||||
"an ordinary call should time out, got " + failure.getCause());
|
||||
assertTrue(elapsedMillis < 10_000, "timed out after " + elapsedMillis + " ms");
|
||||
|
||||
CompletableFuture<Integer> wait = CompletableFuture.supplyAsync(() -> {
|
||||
try (DockerHttpClient.Response response = client.execute(DockerHttpClient.Request.builder()
|
||||
.method(DockerHttpClient.Request.Method.POST).path("/containers/abc/wait").build())) {
|
||||
return response.getStatusCode();
|
||||
}
|
||||
});
|
||||
assertThrows(TimeoutException.class, () -> wait.get(2_500, TimeUnit.MILLISECONDS),
|
||||
"a container wait must outlive the response timeout");
|
||||
|
||||
SocketChannel waitConnection = accepted.get(accepted.size() - 1);
|
||||
waitConnection.write(ByteBuffer.wrap(("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
|
||||
+ "Content-Length: 15\r\n\r\n{\"StatusCode\":0}").getBytes(StandardCharsets.UTF_8)));
|
||||
assertEquals(200, wait.get(10, TimeUnit.SECONDS));
|
||||
} finally {
|
||||
for (SocketChannel channel : accepted) {
|
||||
channel.close();
|
||||
}
|
||||
acceptor.interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void streamingEndpointsAreRecognisedAndOrdinaryCallsAreNot() {
|
||||
for (String streaming : List.of("POST /v1.43/containers/abc/wait", "POST /exec/xyz/start",
|
||||
"POST /containers/abc/attach?stream=1", "GET /events?since=1", "GET /containers/abc/logs?follow=true",
|
||||
"GET /containers/abc/stats", "POST /images/create?fromImage=alpine", "POST /build")) {
|
||||
assertTrue(FlociDockerHttpClient.isLongLivedStream(request(streaming)), streaming);
|
||||
}
|
||||
for (String ordinary : List.of("GET /containers/abc/json", "GET /containers/abc/logs?tail=100",
|
||||
"GET /containers/abc/stats?stream=0", "POST /containers/abc/start", "POST /containers/create",
|
||||
"DELETE /containers/abc", "GET /_ping")) {
|
||||
assertFalse(FlociDockerHttpClient.isLongLivedStream(request(ordinary)), ordinary);
|
||||
}
|
||||
}
|
||||
|
||||
private static DockerHttpClient.Request request(String methodAndPath) {
|
||||
String[] parts = methodAndPath.split(" ", 2);
|
||||
return DockerHttpClient.Request.builder().method(parts[0]).path(parts[1]).build();
|
||||
}
|
||||
}
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
package io.github.hectorvent.floci.core.common.docker;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.StandardProtocolFamily;
|
||||
import java.net.UnixDomainSocketAddress;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.ClosedByInterruptException;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class UnixDomainSocketTest {
|
||||
|
||||
@TempDir
|
||||
Path dir;
|
||||
|
||||
private ServerSocketChannel server;
|
||||
private Path socketPath;
|
||||
|
||||
@BeforeEach
|
||||
void startServer() throws IOException {
|
||||
socketPath = dir.resolve("docker.sock");
|
||||
server = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
|
||||
server.bind(UnixDomainSocketAddress.of(socketPath));
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void stopServer() throws IOException {
|
||||
server.close();
|
||||
}
|
||||
|
||||
// Catches: a read that ignores SO_TIMEOUT and blocks forever on a silent peer, as docker-java's
|
||||
// UnixSocket does.
|
||||
@Test
|
||||
void aReadWithATimeoutFailsWhenThePeerStaysSilent() throws Exception {
|
||||
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
|
||||
SocketChannel ignored = server.accept()) {
|
||||
socket.setSoTimeout(200);
|
||||
long start = System.nanoTime();
|
||||
|
||||
assertThrows(SocketTimeoutException.class, () -> socket.getInputStream().read(new byte[16]));
|
||||
|
||||
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
|
||||
assertTrue(elapsedMillis >= 150 && elapsedMillis < 5_000, "timed out after " + elapsedMillis + " ms");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReadWithoutATimeoutWaitsForDataAndWritesReachThePeer() throws Exception {
|
||||
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
|
||||
SocketChannel peer = server.accept()) {
|
||||
socket.getOutputStream().write("ping".getBytes(StandardCharsets.UTF_8));
|
||||
ByteBuffer received = ByteBuffer.allocate(4);
|
||||
while (received.hasRemaining()) {
|
||||
peer.read(received);
|
||||
}
|
||||
assertEquals("ping", new String(received.array(), StandardCharsets.UTF_8));
|
||||
|
||||
InputStream input = socket.getInputStream();
|
||||
CompletableFuture<String> reply = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
byte[] bytes = new byte[4];
|
||||
int read = 0;
|
||||
while (read < bytes.length) {
|
||||
read += input.read(bytes, read, bytes.length - read);
|
||||
}
|
||||
return new String(bytes, StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
assertThrows(TimeoutException.class, () -> reply.get(300, TimeUnit.MILLISECONDS),
|
||||
"a read without a timeout should wait for the peer");
|
||||
|
||||
peer.write(ByteBuffer.wrap("pong".getBytes(StandardCharsets.UTF_8)));
|
||||
assertEquals("pong", reply.get(5, TimeUnit.SECONDS));
|
||||
}
|
||||
}
|
||||
|
||||
// Catches: a close from another thread surfacing as the selector's unchecked
|
||||
// ClosedSelectorException, which callers expecting an IOException do not handle.
|
||||
@Test
|
||||
void closingTheSocketEndsABlockedReadWithAnIOException() throws Exception {
|
||||
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
|
||||
SocketChannel ignored = server.accept()) {
|
||||
InputStream input = socket.getInputStream();
|
||||
CompletableFuture<Integer> read = CompletableFuture.supplyAsync(() -> {
|
||||
try {
|
||||
return input.read(new byte[16]);
|
||||
} catch (IOException e) {
|
||||
throw new UncheckedIOException(e);
|
||||
}
|
||||
});
|
||||
assertThrows(TimeoutException.class, () -> read.get(200, TimeUnit.MILLISECONDS));
|
||||
|
||||
socket.close();
|
||||
|
||||
ExecutionException failure = assertThrows(ExecutionException.class, () -> read.get(5, TimeUnit.SECONDS));
|
||||
assertInstanceOf(UncheckedIOException.class, failure.getCause(), "got " + failure.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
// Catches: an interrupted reader with no timeout spinning on a selector that returns at once
|
||||
// while the interrupt flag is set.
|
||||
@Test
|
||||
void anInterruptedReadClosesTheSocketInsteadOfSpinning() throws Exception {
|
||||
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString());
|
||||
SocketChannel ignored = server.accept()) {
|
||||
InputStream input = socket.getInputStream();
|
||||
AtomicReference<Throwable> failure = new AtomicReference<>();
|
||||
Thread reader = Thread.ofPlatform().start(() -> {
|
||||
try {
|
||||
input.read(new byte[16]);
|
||||
} catch (IOException e) {
|
||||
failure.set(e);
|
||||
}
|
||||
});
|
||||
reader.join(200);
|
||||
assertTrue(reader.isAlive(), "the read should be waiting for the peer");
|
||||
|
||||
reader.interrupt();
|
||||
reader.join(5_000);
|
||||
|
||||
assertFalse(reader.isAlive(), "the interrupted read should end");
|
||||
assertInstanceOf(ClosedByInterruptException.class, failure.get());
|
||||
assertTrue(socket.isClosed());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void readingAfterThePeerClosesReturnsEndOfStream() throws Exception {
|
||||
try (UnixDomainSocket socket = UnixDomainSocket.connect(socketPath.toString())) {
|
||||
server.accept().close();
|
||||
socket.setSoTimeout(2_000);
|
||||
|
||||
assertEquals(-1, socket.getInputStream().read());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user