Skip to content

Commit

Permalink
refactor (jkube-kit/common) : Refactor IoUtil.getFreeRandomPort to …
Browse files Browse the repository at this point in the history
…always generate a valid free random port (eclipse-jkube#2501)

+ Use ServerSocket to establish a connection instead of Socket which might
  also throw ConnectException for a socket already in use.
+ Modify IoUtilTes.findOpenPortWithSmallAttemptsCount to use
  `@RepeatedTest` annotation to run it 500 times

Signed-off-by: Rohan Kumar <[email protected]>
  • Loading branch information
rohanKanojia committed Feb 8, 2024
1 parent d828cd2 commit 18f8e6a
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.nio.file.Files;
Expand Down Expand Up @@ -128,12 +129,10 @@ public static int getFreeRandomPort() {
public static int getFreeRandomPort(int min, int max, int attempts) {
for (int i=0; i < attempts; i++) {
int port = min + RANDOM.nextInt(max - min + 1);
try (Socket ignored = new Socket("localhost", port)) { // NOSONAR
// Port is open for communication, meaning it's used up, try again
} catch (ConnectException e) {
try (ServerSocket ignored = new ServerSocket(port)) {
return port;
} catch (IOException e) {
throw new IllegalStateException("Error while trying to check open ports", e);
} catch (Exception e) {
// NOOP
}
}
throw new IllegalStateException("Cannot find a free random port in the range [" + min + ", " + max + "] after " + attempts + " attempts");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.eclipse.jkube.kit.common.TestHttpStaticServer;
import org.eclipse.jkube.kit.common.assertj.FileAssertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

Expand Down Expand Up @@ -64,7 +65,7 @@ void findOpenPortWhenPortsAreBusy() throws IOException {
assertThat(port2).isGreaterThan(port);
}

@Test
@RepeatedTest(500)
void findOpenPortWithSmallAttemptsCount() throws IOException {
int port = IoUtil.getFreeRandomPort(30000, 60000, 30);
try (ServerSocket ss = new ServerSocket(port)) {
Expand Down

0 comments on commit 18f8e6a

Please sign in to comment.