Skip to content

Commit 10a24c4

Browse files
committed
Fix CopyTest flakiness and WebSocketStreamHandler NPE on failed connection
1 parent 01f7f7f commit 10a24c4

3 files changed

Lines changed: 146 additions & 135 deletions

File tree

‎util/src/main/java/io/kubernetes/client/util/WebSocketStreamHandler.java‎

Lines changed: 30 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,11 @@ public synchronized boolean isClosed() {
128128

129129
@Override
130130
public synchronized void close() {
131-
if (state != State.CLOSED) {
131+
if (state == State.CLOSED) {
132+
notifyAll();
133+
return;
134+
}
135+
try {
132136
// Close all output streams. Caller of getInputStream(int) is responsible
133137
// for closing returned input streams
134138
for (PipedOutputStream out : pipedOutput.values()) {
@@ -155,15 +159,20 @@ public synchronized void close() {
155159
log.error("Error on close", ex);
156160
}
157161
}
158-
162+
} finally {
163+
// Always transition to CLOSED and wake up any writers blocked waiting for the socket
164+
// to open, even if closing one of the streams above failed unexpectedly.
159165
state = State.CLOSED;
160-
if (null != socket) {
161-
// code 1000 means "Normal Closure"
162-
socket.close(1000, "Triggered client-side terminate");
163-
log.debug("Successfully closed socket.");
166+
try {
167+
if (null != socket) {
168+
// code 1000 means "Normal Closure"
169+
socket.close(1000, "Triggered client-side terminate");
170+
log.debug("Successfully closed socket.");
171+
}
172+
} finally {
173+
notifyAll();
164174
}
165175
}
166-
notifyAll();
167176
}
168177

169178
/**
@@ -273,8 +282,13 @@ public void flush() throws IOException {
273282
if (state == State.CLOSED) {
274283
throw new IOException("Socket is closed!");
275284
}
285+
WebSocket ws = WebSocketStreamHandler.this.socket;
286+
if (ws == null) {
287+
// The socket was never opened, so there is nothing queued to flush.
288+
return;
289+
}
276290
int i = 0;
277-
while (WebSocketStreamHandler.this.socket.queueSize() > 0) {
291+
while (ws.queueSize() > 0) {
278292
try {
279293
Thread.sleep(FLUSH_WAIT_MILLIS);
280294
} catch (InterruptedException ex) {
@@ -298,16 +312,15 @@ public void write(byte[] b) throws IOException {
298312

299313
@Override
300314
public void write(byte[] b, int offset, int length) throws IOException {
301-
if (WebSocketStreamHandler.this.socket == null) {
302-
synchronized (WebSocketStreamHandler.this) {
315+
synchronized (WebSocketStreamHandler.this) {
316+
// wait for the websocket to be opened, failing fast if the handler is closed
317+
// (e.g. because the connection failed) before or while waiting.
318+
while (WebSocketStreamHandler.this.socket == null) {
303319
if (state == State.CLOSED) throw new IllegalStateException();
304-
if (WebSocketStreamHandler.this.socket == null) {
305-
// wait for the websocket to be opened
306-
try {
307-
WebSocketStreamHandler.this.wait();
308-
} catch (InterruptedException e) {
309-
throw new InterruptedIOException();
310-
}
320+
try {
321+
WebSocketStreamHandler.this.wait();
322+
} catch (InterruptedException e) {
323+
throw new InterruptedIOException();
311324
}
312325
}
313326
}

‎util/src/test/java/io/kubernetes/client/CopyTest.java‎

Lines changed: 66 additions & 118 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,11 @@
1818
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
1919
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
2020
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
21+
import static org.awaitility.Awaitility.await;
2122

22-
import com.github.tomakehurst.wiremock.core.Admin;
23-
import com.github.tomakehurst.wiremock.extension.Parameters;
24-
import com.github.tomakehurst.wiremock.extension.PostServeAction;
2523
import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
2624
import com.github.tomakehurst.wiremock.matching.AnythingPattern;
27-
import com.github.tomakehurst.wiremock.stubbing.ServeEvent;
25+
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder;
2826
import io.kubernetes.client.openapi.ApiClient;
2927
import io.kubernetes.client.openapi.ApiException;
3028
import io.kubernetes.client.openapi.models.V1ObjectMeta;
@@ -40,7 +38,6 @@
4038
import java.nio.file.Paths;
4139
import java.util.HashMap;
4240
import java.util.Map;
43-
import java.util.concurrent.CountDownLatch;
4441
import java.util.concurrent.TimeUnit;
4542
import org.junit.jupiter.api.BeforeEach;
4643
import org.junit.jupiter.api.Test;
@@ -125,25 +122,59 @@ public InputStream copyFileFromPod(String namespace, String pod, String srcPath)
125122
}
126123
}
127124

128-
public static class CountDownLatchAction extends PostServeAction {
129-
@Override
130-
public String getName() {
131-
return "countdown";
132-
}
133-
134-
@Override
135-
public void doAction(ServeEvent serveEvent, Admin admin, Parameters parameters) {
136-
CountDownLatch latch = (CountDownLatch) parameters.get("latch");
137-
latch.countDown();
138-
}
139-
}
140-
141125
@RegisterExtension
142126
static WireMockExtension apiServer =
143127
WireMockExtension.newInstance()
144-
.options(wireMockConfig().dynamicPort().extensions(new CountDownLatchAction()))
128+
.options(wireMockConfig().dynamicPort())
145129
.build();
146130

131+
private RequestPatternBuilder execRequest() {
132+
return getRequestedFor(
133+
urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"));
134+
}
135+
136+
private void stubExecNotFound() {
137+
apiServer.stubFor(
138+
get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
139+
.willReturn(
140+
aResponse()
141+
.withStatus(404)
142+
.withHeader("Content-Type", "application/json")
143+
.withBody("{}")));
144+
}
145+
146+
/**
147+
* Runs the given action on a background thread, waits until WireMock has recorded an exec
148+
* request, then stops the thread and waits for it to terminate so it cannot leak into later
149+
* tests.
150+
*/
151+
private void runUntilExecRequested(ThrowingRunnable action) throws InterruptedException {
152+
Thread t =
153+
new Thread(
154+
() -> {
155+
try {
156+
action.run();
157+
} catch (Exception ex) {
158+
// Expected: the mock server rejects the websocket upgrade.
159+
}
160+
});
161+
t.start();
162+
try {
163+
await()
164+
.atMost(30, TimeUnit.SECONDS)
165+
.until(() -> !apiServer.findAll(execRequest()).isEmpty());
166+
} finally {
167+
t.interrupt();
168+
t.join(TimeUnit.SECONDS.toMillis(30));
169+
}
170+
assertFalse(t.isAlive(), "background copy thread did not terminate");
171+
}
172+
173+
@FunctionalInterface
174+
private interface ThrowingRunnable {
175+
void run() throws Exception;
176+
}
177+
147178
@BeforeEach
148179
void setup() {
149180
client = new ClientBuilder().setBasePath("http://localhost:" + apiServer.getPort()).build();
@@ -187,46 +218,19 @@ void url() {
187218

188219
@Test
189220
void copyFileToPod(@TempDir Path tempDir) throws Exception {
190-
191221
Path testFile = Files.createTempFile(tempDir, "testfile", null);
192222

193223
Copy copy = new Copy(client);
194224

195-
CountDownLatch latch = new CountDownLatch(1);
196-
Parameters params = new Parameters();
197-
params.put("latch", latch);
225+
stubExecNotFound();
198226

199-
apiServer.stubFor(
200-
get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
201-
.withPostServeAction("countdown", params)
202-
.willReturn(
203-
aResponse()
204-
.withStatus(404)
205-
.withHeader("Content-Type", "application/json")
206-
.withBody("{}")));
207-
208-
// When attempting to write to the process outputstream in copyFileToPod, the
209-
// WebSocketStreamHandler is in a wait state because no websocket is created by mock, which
210-
// blocks the main thread. So here we execute the method in a thread.
211-
Thread t =
212-
new Thread(
213-
new Runnable() {
214-
public void run() {
215-
try {
216-
copy.copyFileToPod(
217-
namespace, podName, "", testFile, Paths.get("/copied-testfile"));
218-
} catch (IOException | ApiException ex) {
219-
ex.printStackTrace();
220-
}
221-
}
222-
});
223-
t.start();
224-
assertTrue(latch.await(30, TimeUnit.SECONDS));
225-
t.interrupt();
227+
// The mock server never upgrades to a websocket, so run the copy in the background and only
228+
// wait for the exec request to reach the server.
229+
runUntilExecRequested(
230+
() -> copy.copyFileToPod(namespace, podName, "", testFile, Paths.get("/copied-testfile")));
226231

227232
apiServer.verify(
228-
getRequestedFor(
229-
urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
233+
execRequest()
230234
.withQueryParam("stdin", equalTo("true"))
231235
.withQueryParam("stdout", equalTo("true"))
232236
.withQueryParam("stderr", equalTo("true"))
@@ -238,46 +242,17 @@ public void run() {
238242

239243
@Test
240244
void copyBinaryDataToPod() throws InterruptedException {
241-
242245
byte[] testSrc = new byte[0];
243246

244247
Copy copy = new Copy(client);
245248

246-
CountDownLatch latch = new CountDownLatch(1);
247-
Parameters params = new Parameters();
248-
params.put("latch", latch);
249-
250-
apiServer.stubFor(
251-
get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
252-
.withPostServeAction("countdown", params)
253-
.willReturn(
254-
aResponse()
255-
.withStatus(404)
256-
.withHeader("Content-Type", "application/json")
257-
.withBody("{}")));
249+
stubExecNotFound();
258250

259-
// When attempting to write to the process outputstream in copyFileToPod, the
260-
// WebSocketStreamHandler is in a wait state because no websocket is created by mock, which
261-
// blocks the main thread. So here we execute the method in a thread.
262-
Thread t =
263-
new Thread(
264-
new Runnable() {
265-
public void run() {
266-
try {
267-
copy.copyFileToPod(
268-
namespace, podName, "", testSrc, Paths.get("/copied-binarydata"));
269-
} catch (IOException | ApiException ex) {
270-
ex.printStackTrace();
271-
}
272-
}
273-
});
274-
t.start();
275-
assertTrue(latch.await(30, TimeUnit.SECONDS));
276-
t.interrupt();
251+
runUntilExecRequested(
252+
() -> copy.copyFileToPod(namespace, podName, "", testSrc, Paths.get("/copied-binarydata")));
277253

278254
apiServer.verify(
279-
getRequestedFor(
280-
urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
255+
execRequest()
281256
.withQueryParam("stdin", equalTo("true"))
282257
.withQueryParam("stdout", equalTo("true"))
283258
.withQueryParam("stderr", equalTo("true"))
@@ -291,42 +266,15 @@ public void run() {
291266
void testCopyDirectoryFromPod(@TempDir Path tempDir) throws Exception {
292267
Copy copy = new Copy(client);
293268

294-
CountDownLatch latch = new CountDownLatch(1);
295-
Parameters params = new Parameters();
296-
params.put("latch", latch);
297-
298-
apiServer.stubFor(
299-
get(urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
300-
.withPostServeAction("countdown", params)
301-
.willReturn(
302-
aResponse()
303-
.withStatus(404)
304-
.withHeader("Content-Type", "application/json")
305-
.withBody("{}")));
269+
stubExecNotFound();
306270

307-
Thread t =
308-
new Thread(
309-
new Runnable() {
310-
public void run() {
311-
try {
312-
copy.copyDirectoryFromPod(
313-
namespace,
314-
podName,
315-
"",
316-
tempDir.toString(),
317-
Paths.get("/copied-testDir"));
318-
} catch (IOException | ApiException | CopyNotSupportedException ex) {
319-
ex.printStackTrace();
320-
}
321-
}
322-
});
323-
t.start();
324-
assertTrue(latch.await(30, TimeUnit.SECONDS));
325-
t.interrupt();
271+
runUntilExecRequested(
272+
() ->
273+
copy.copyDirectoryFromPod(
274+
namespace, podName, "", tempDir.toString(), Paths.get("/copied-testDir")));
326275

327276
apiServer.verify(
328-
getRequestedFor(
329-
urlPathEqualTo("/api/v1/namespaces/" + namespace + "/pods/" + podName + "/exec"))
277+
execRequest()
330278
.withQueryParam("stdin", equalTo("false"))
331279
.withQueryParam("stdout", equalTo("true"))
332280
.withQueryParam("stderr", equalTo("true"))

0 commit comments

Comments
 (0)