Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid port clashes where it may already be reserved via the build-helper-maven-plugin #2769

Merged
merged 1 commit into from
Jun 11, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 {} is already reserved for {}", port, property);
return true;
}
}
}
return false;
}
}