Skip to content

Commit

Permalink
Find free hub port to support multiple local grids in common environm…
Browse files Browse the repository at this point in the history
…ent.
  • Loading branch information
squash-merge committed Apr 25, 2016
1 parent c5b20be commit cf88513
Showing 1 changed file with 47 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,15 @@

package com.paypal.selion.internal.platform.grid;

import java.io.IOException;
import java.net.BindException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.openqa.selenium.net.NetworkUtils;
import org.openqa.selenium.net.PortProber;

import com.paypal.selion.configuration.Config;
import com.paypal.selion.configuration.Config.ConfigProperty;
Expand All @@ -42,9 +50,13 @@ static synchronized LocalServerComponent getSingleton() {
synchronized LocalHub getLocalServerComponent() {
if (instance == null) {
instance = new LocalHub();
instance.setHost(new NetworkUtils().getNonLoopbackAddressOfThisMachine());

instance.setHost(new NetworkUtils().getIpOfLoopBackIp4());
instance.setPort(Integer.parseInt(Config.getConfigProperty(ConfigProperty.SELENIUM_PORT)));
int configHubPort = Integer.parseInt(Config.getConfigProperty(ConfigProperty.SELENIUM_PORT));
// Choose another free port when config port is not available.
int hubPort = LocalHub.pollPort(configHubPort) ? configHubPort : PortProber.findFreePort();
Config.setConfigProperty(ConfigProperty.SELENIUM_PORT, Integer.toString(hubPort));
instance.setPort(hubPort);

LauncherOptions launcherOptions = new LauncherOptionsImpl()
.setFileDownloadCheckTimeStampOnInvocation(false).setFileDownloadCleanupOnInvocation(false);
Expand Down Expand Up @@ -75,4 +87,37 @@ public void shutdown() {
super.shutdown();
LOGGER.exiting();
}


/**
* Polls port on localhost for its availability for 15 seconds.
*/
private static boolean pollPort(int port) {
long end = System.currentTimeMillis() + 15000;
while (System.currentTimeMillis() < end) {
Socket socket = new Socket();
try {
socket.setReuseAddress(false);
socket.bind(new InetSocketAddress("localhost", port));
socket.close();
return true;
} catch (ConnectException | BindException e) {
// Ignore this
} catch (UnknownHostException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if ((socket != null) && !socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
LOGGER.info("Error closing socket.");
}
}
}
}

return false;
}
}

0 comments on commit cf88513

Please sign in to comment.