Skip to content

Commit

Permalink
Avoid port clashes where it may already be reserved via the build-hel…
Browse files Browse the repository at this point in the history
…per-maven-plugin
  • Loading branch information
jamesnetherton committed Jun 11, 2021
1 parent 78f0372 commit d36e72f
Showing 1 changed file with 33 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,11 @@
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.ConfigProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -32,6 +35,10 @@
*/
public final class AvailablePortFinder {
private static final Logger LOGGER = LoggerFactory.getLogger(AvailablePortFinder.class);
private static final String[] QUARKUS_PORT_PROPERTIES = new String[] {
"quarkus.http.test-port",
"quarkus.http.test-ssl-port",
};

/**
* Creates a new instance.
Expand All @@ -47,17 +54,19 @@ private AvailablePortFinder() {
* @return the available port
*/
public static int getNextAvailable() {
try (ServerSocket ss = new ServerSocket()) {
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress((InetAddress) null, 0), 1);
while (true) {
try (ServerSocket ss = new ServerSocket()) {
ss.setReuseAddress(true);
ss.bind(new InetSocketAddress((InetAddress) null, 0), 1);

int port = ss.getLocalPort();

LOGGER.info("getNextAvailable() -> {}", port);

return port;
} catch (IOException e) {
throw new IllegalStateException("Cannot find free port", e);
int port = ss.getLocalPort();
if (!isQuarkusReservedPort(port)) {
LOGGER.info("getNextAvailable() -> {}", port);
return port;
}
} catch (IOException e) {
throw new IllegalStateException("Cannot find free port", e);
}
}
}

Expand All @@ -80,4 +89,18 @@ public static <T> Map<String, T> reserveNetworkPorts(Function<Integer, T> conver

return reservedPorts;
}

private static boolean isQuarkusReservedPort(int port) {
Config config = ConfigProvider.getConfig();
for (String property : QUARKUS_PORT_PROPERTIES) {
Optional<Integer> portProperty = config.getOptionalValue(property, Integer.class);
if (portProperty.isPresent()) {
if (port == portProperty.get()) {
LOGGER.info("Port %d is already reserved for %s", port, property);
return true;
}
}
}
return false;
}
}

0 comments on commit d36e72f

Please sign in to comment.