Skip to content

Fix Port Binding Issue During Testing #382

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

Merged
merged 10 commits into from
Dec 6, 2023
22 changes: 21 additions & 1 deletion src/test/java/com/oltpbenchmark/api/AbstractTestCase.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.net.ServerSocket;
import java.net.BindException;

public abstract class AbstractTestCase<T extends BenchmarkModule> {

Expand Down Expand Up @@ -69,6 +71,7 @@ public abstract class AbstractTestCase<T extends BenchmarkModule> {
protected final String ddlOverridePath;

private static final AtomicInteger portCounter = new AtomicInteger(9001);
private static final int MAX_PORT_NUMBER = 65535;


public AbstractTestCase(boolean createDatabase, boolean loadDatabase) {
Expand Down Expand Up @@ -99,7 +102,7 @@ public final void setUp() throws Exception {
HsqlProperties props = new HsqlProperties();
//props.setProperty("server.remote_open", true);

int port = portCounter.incrementAndGet();
int port = findAvailablePort();

LOG.info("starting HSQLDB server for test [{}] on port [{}]", name.getMethodName(), port);

Expand Down Expand Up @@ -163,6 +166,23 @@ public final void setUp() throws Exception {
}
}

private int findAvailablePort() throws IOException {
while (true) {
int port = portCounter.incrementAndGet();

if (port > MAX_PORT_NUMBER) {
throw new IOException("No available port found up to " + MAX_PORT_NUMBER);
}

try (ServerSocket testSocket = new ServerSocket(port)) {
return port;
} catch (BindException e) {
// This port is already in use. Continue to next port.
LOG.warn("Port {} is already in use. Trying next port.", port);
}
}
}

protected TransactionTypes proceduresToTransactionTypes(List<Class<? extends Procedure>> procedures) {
TransactionTypes txnTypes = new TransactionTypes(new ArrayList<>());

Expand Down