mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(ecs): close an ECS Exec stream that attaches after the client has left (#7530)
This commit is contained in:
1 parent
0f242e9ee0
commit
e0b8da1b6c
4 files changed
+210
-97
No files matched your search
+9
-1
@@ -105,6 +105,7 @@ public class EcsExecChannelHandler {
|
||||
private volatile String execId;
|
||||
private volatile PipedOutputStream containerInput;
|
||||
private volatile Closeables exec;
|
||||
private volatile boolean closed;
|
||||
|
||||
Channel(String sessionId, ServerWebSocket webSocket) {
|
||||
this.sessionId = sessionId;
|
||||
@@ -197,7 +198,13 @@ public class EcsExecChannelHandler {
|
||||
.withStdIn(execStdin)
|
||||
.withTty(current.interactive())
|
||||
.exec(new ExecFrameCallback(this)), execStdin), false)
|
||||
.onSuccess(started -> exec = started)
|
||||
.onSuccess(started -> {
|
||||
exec = started;
|
||||
// The channel may have shut down while the attach was in flight.
|
||||
if (closed) {
|
||||
shutdown();
|
||||
}
|
||||
})
|
||||
.onFailure(cause -> failChannel(cause, current.containerName()));
|
||||
}
|
||||
|
||||
@@ -363,6 +370,7 @@ public class EcsExecChannelHandler {
|
||||
|
||||
/** Closing the exec streams talks to the daemon, so it too stays off the event loop. */
|
||||
private void shutdown() {
|
||||
closed = true;
|
||||
Closeables open = exec;
|
||||
PipedOutputStream stream = containerInput;
|
||||
exec = null;
|
||||
|
||||
-96
@@ -11,9 +11,6 @@ import io.github.hectorvent.floci.testing.TestImages;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.RestAssured;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
@@ -21,18 +18,13 @@ import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
@@ -199,94 +191,6 @@ class EcsExecChannelDockerIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** The half of the Session Manager protocol that {@code session-manager-plugin} implements. */
|
||||
private static final class PluginClient {
|
||||
|
||||
private final Vertx vertx;
|
||||
private final ExecSession session;
|
||||
private final URI streamUrl;
|
||||
private final BlockingQueue<AgentMessage> received = new LinkedBlockingQueue<>();
|
||||
|
||||
private HttpClient httpClient;
|
||||
private WebSocket webSocket;
|
||||
private long sequence;
|
||||
|
||||
PluginClient(Vertx vertx, ExecSession session, URI streamUrl) {
|
||||
this.vertx = vertx;
|
||||
this.session = session;
|
||||
this.streamUrl = streamUrl;
|
||||
}
|
||||
|
||||
void open() throws Exception {
|
||||
httpClient = vertx.createHttpClient();
|
||||
webSocket = httpClient.webSocket(streamUrl.getPort(), streamUrl.getHost(), streamUrl.getRawPath())
|
||||
.toCompletionStage().toCompletableFuture().get(20, TimeUnit.SECONDS);
|
||||
webSocket.binaryMessageHandler(buffer -> received.add(AgentMessage.decode(buffer.getBytes())));
|
||||
webSocket.writeTextMessage("{\"MessageSchemaVersion\":\"1.0\",\"RequestId\":\""
|
||||
+ UUID.randomUUID() + "\",\"TokenValue\":\"" + session.tokenValue()
|
||||
+ "\",\"ClientId\":\"" + UUID.randomUUID() + "\"}");
|
||||
}
|
||||
|
||||
void sendHandshakeResponse() {
|
||||
String payload = "{\"ClientVersion\":\"1.2.0.0\",\"ProcessedClientActions\":"
|
||||
+ "[{\"ActionType\":\"SessionType\",\"ActionStatus\":1}],\"Errors\":\"\"}";
|
||||
AgentMessage response = AgentMessage.outbound(AgentMessage.INPUT_STREAM_DATA, sequence++,
|
||||
AgentMessage.PAYLOAD_HANDSHAKE_RESPONSE, payload.getBytes(StandardCharsets.UTF_8));
|
||||
webSocket.writeBinaryMessage(Buffer.buffer(response.encode()));
|
||||
}
|
||||
|
||||
AgentMessage next() throws InterruptedException {
|
||||
AgentMessage message = received.poll(30, TimeUnit.SECONDS);
|
||||
assertNotNull(message, "the agent must send a frame");
|
||||
return message;
|
||||
}
|
||||
|
||||
byte[] readOutput() throws InterruptedException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (System.nanoTime() < deadline) {
|
||||
AgentMessage message = received.poll(1, TimeUnit.SECONDS);
|
||||
if (message == null) {
|
||||
continue;
|
||||
}
|
||||
if (AgentMessage.CHANNEL_CLOSED.equals(message.messageType())) {
|
||||
return output.toByteArray();
|
||||
}
|
||||
if (AgentMessage.OUTPUT_STREAM_DATA.equals(message.messageType())
|
||||
&& message.payloadType() == AgentMessage.PAYLOAD_OUTPUT) {
|
||||
output.writeBytes(message.payload());
|
||||
}
|
||||
}
|
||||
throw new AssertionError("the command must finish and close its channel");
|
||||
}
|
||||
|
||||
/** Collects output frames until the expected text shows up or the channel goes quiet. */
|
||||
String readUntil(String expected) throws InterruptedException {
|
||||
StringBuilder output = new StringBuilder();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (System.nanoTime() < deadline && !output.toString().contains(expected)) {
|
||||
AgentMessage message = received.poll(1, TimeUnit.SECONDS);
|
||||
if (message == null) {
|
||||
continue;
|
||||
}
|
||||
if (AgentMessage.OUTPUT_STREAM_DATA.equals(message.messageType())
|
||||
&& message.payloadType() == AgentMessage.PAYLOAD_OUTPUT) {
|
||||
output.append(message.payloadAsString());
|
||||
}
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
void close() {
|
||||
if (webSocket != null) {
|
||||
webSocket.close();
|
||||
}
|
||||
if (httpClient != null) {
|
||||
httpClient.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isDockerAvailable() {
|
||||
try {
|
||||
dockerClient.pingCmd().exec();
|
||||
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package io.github.hectorvent.floci.services.ecs.exec;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.github.dockerjava.api.DockerClient;
|
||||
import com.github.dockerjava.api.async.ResultCallback;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmd;
|
||||
import com.github.dockerjava.api.command.ExecCreateCmdResponse;
|
||||
import com.github.dockerjava.api.command.ExecStartCmd;
|
||||
import com.github.dockerjava.api.model.Frame;
|
||||
import io.github.hectorvent.floci.core.common.docker.ContainerLifecycleManager;
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.http.HttpServer;
|
||||
import io.vertx.ext.web.Router;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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.timeout;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class EcsExecChannelHandlerTest {
|
||||
|
||||
private static final String RUNTIME_ID = "container-1";
|
||||
|
||||
private final Vertx vertx = Vertx.vertx();
|
||||
|
||||
@AfterEach
|
||||
void closeVertx() throws Exception {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExecStreamThatAttachesAfterTheClientLeftIsClosed() throws Exception {
|
||||
EcsExecSessionRegistry sessions = new EcsExecSessionRegistry();
|
||||
ExecSession session = sessions.create("task", "cluster", "app", "container", RUNTIME_ID,
|
||||
List.of("/bin/sh"), false);
|
||||
|
||||
DockerClient docker = mock(DockerClient.class);
|
||||
ExecCreateCmd createCmd = mock(ExecCreateCmd.class, RETURNS_SELF);
|
||||
ExecCreateCmdResponse created = mock(ExecCreateCmdResponse.class);
|
||||
when(created.getId()).thenReturn("exec-1");
|
||||
when(createCmd.exec()).thenReturn(created);
|
||||
when(docker.execCreateCmd(RUNTIME_ID)).thenReturn(createCmd);
|
||||
|
||||
ExecStartCmd startCmd = mock(ExecStartCmd.class, RETURNS_SELF);
|
||||
AtomicReference<InputStream> execStdin = new AtomicReference<>();
|
||||
when(startCmd.withStdIn(any())).thenAnswer(invocation -> {
|
||||
execStdin.set(invocation.getArgument(0));
|
||||
return startCmd;
|
||||
});
|
||||
CountDownLatch attaching = new CountDownLatch(1);
|
||||
@SuppressWarnings("unchecked")
|
||||
ResultCallback<Frame> attach = mock(ResultCallback.class);
|
||||
when(startCmd.exec(any())).thenAnswer(invocation -> {
|
||||
attaching.countDown();
|
||||
// The attach returns only once the channel has shut down, which closes the exec's stdin.
|
||||
while (execStdin.get().read() != -1) {
|
||||
// drain
|
||||
}
|
||||
return attach;
|
||||
});
|
||||
when(docker.execStartCmd("exec-1")).thenReturn(startCmd);
|
||||
|
||||
ContainerLifecycleManager lifecycleManager = mock(ContainerLifecycleManager.class);
|
||||
when(lifecycleManager.getDockerClient()).thenReturn(docker);
|
||||
|
||||
Router router = Router.router(vertx);
|
||||
new EcsExecChannelHandler(sessions, lifecycleManager, new ObjectMapper(), vertx).init(router);
|
||||
HttpServer server = vertx.createHttpServer().requestHandler(router).listen(0)
|
||||
.toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
|
||||
PluginClient client = new PluginClient(vertx, session, URI.create("http://localhost:" + server.actualPort()
|
||||
+ EcsExecChannelHandler.CHANNEL_PATH_PREFIX + session.sessionId()));
|
||||
try {
|
||||
client.open();
|
||||
assertEquals(AgentMessage.PAYLOAD_HANDSHAKE_REQUEST, client.next().payloadType());
|
||||
client.sendHandshakeResponse();
|
||||
assertTrue(attaching.await(10, TimeUnit.SECONDS), "the agent must attach to the exec");
|
||||
} finally {
|
||||
client.close();
|
||||
}
|
||||
|
||||
verify(attach, timeout(10_000)).close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package io.github.hectorvent.floci.services.ecs.exec;
|
||||
|
||||
import io.vertx.core.Vertx;
|
||||
import io.vertx.core.buffer.Buffer;
|
||||
import io.vertx.core.http.HttpClient;
|
||||
import io.vertx.core.http.WebSocket;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.BlockingQueue;
|
||||
import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
|
||||
/** The half of the Session Manager protocol that {@code session-manager-plugin} implements. */
|
||||
final class PluginClient {
|
||||
|
||||
private final Vertx vertx;
|
||||
private final ExecSession session;
|
||||
private final URI streamUrl;
|
||||
private final BlockingQueue<AgentMessage> received = new LinkedBlockingQueue<>();
|
||||
|
||||
private HttpClient httpClient;
|
||||
private WebSocket webSocket;
|
||||
private long sequence;
|
||||
|
||||
PluginClient(Vertx vertx, ExecSession session, URI streamUrl) {
|
||||
this.vertx = vertx;
|
||||
this.session = session;
|
||||
this.streamUrl = streamUrl;
|
||||
}
|
||||
|
||||
void open() throws Exception {
|
||||
httpClient = vertx.createHttpClient();
|
||||
webSocket = httpClient.webSocket(streamUrl.getPort(), streamUrl.getHost(), streamUrl.getRawPath())
|
||||
.toCompletionStage().toCompletableFuture().get(20, TimeUnit.SECONDS);
|
||||
webSocket.binaryMessageHandler(buffer -> received.add(AgentMessage.decode(buffer.getBytes())));
|
||||
webSocket.writeTextMessage("{\"MessageSchemaVersion\":\"1.0\",\"RequestId\":\""
|
||||
+ UUID.randomUUID() + "\",\"TokenValue\":\"" + session.tokenValue()
|
||||
+ "\",\"ClientId\":\"" + UUID.randomUUID() + "\"}");
|
||||
}
|
||||
|
||||
void sendHandshakeResponse() {
|
||||
String payload = "{\"ClientVersion\":\"1.2.0.0\",\"ProcessedClientActions\":"
|
||||
+ "[{\"ActionType\":\"SessionType\",\"ActionStatus\":1}],\"Errors\":\"\"}";
|
||||
AgentMessage response = AgentMessage.outbound(AgentMessage.INPUT_STREAM_DATA, sequence++,
|
||||
AgentMessage.PAYLOAD_HANDSHAKE_RESPONSE, payload.getBytes(StandardCharsets.UTF_8));
|
||||
webSocket.writeBinaryMessage(Buffer.buffer(response.encode()));
|
||||
}
|
||||
|
||||
AgentMessage next() throws InterruptedException {
|
||||
AgentMessage message = received.poll(30, TimeUnit.SECONDS);
|
||||
assertNotNull(message, "the agent must send a frame");
|
||||
return message;
|
||||
}
|
||||
|
||||
byte[] readOutput() throws InterruptedException {
|
||||
ByteArrayOutputStream output = new ByteArrayOutputStream();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (System.nanoTime() < deadline) {
|
||||
AgentMessage message = received.poll(1, TimeUnit.SECONDS);
|
||||
if (message == null) {
|
||||
continue;
|
||||
}
|
||||
if (AgentMessage.CHANNEL_CLOSED.equals(message.messageType())) {
|
||||
return output.toByteArray();
|
||||
}
|
||||
if (AgentMessage.OUTPUT_STREAM_DATA.equals(message.messageType())
|
||||
&& message.payloadType() == AgentMessage.PAYLOAD_OUTPUT) {
|
||||
output.writeBytes(message.payload());
|
||||
}
|
||||
}
|
||||
throw new AssertionError("the command must finish and close its channel");
|
||||
}
|
||||
|
||||
/** Collects output frames until the expected text shows up or the channel goes quiet. */
|
||||
String readUntil(String expected) throws InterruptedException {
|
||||
StringBuilder output = new StringBuilder();
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(30);
|
||||
while (System.nanoTime() < deadline && !output.toString().contains(expected)) {
|
||||
AgentMessage message = received.poll(1, TimeUnit.SECONDS);
|
||||
if (message == null) {
|
||||
continue;
|
||||
}
|
||||
if (AgentMessage.OUTPUT_STREAM_DATA.equals(message.messageType())
|
||||
&& message.payloadType() == AgentMessage.PAYLOAD_OUTPUT) {
|
||||
output.append(message.payloadAsString());
|
||||
}
|
||||
}
|
||||
return output.toString();
|
||||
}
|
||||
|
||||
void close() {
|
||||
if (webSocket != null) {
|
||||
webSocket.close();
|
||||
}
|
||||
if (httpClient != null) {
|
||||
httpClient.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user