Added getFreeLocalPorts() for grabbing more than one port. Fixes bug in freeLocalHostAndPort() where the same port can be picked multiple times.

This commit is contained in:
RogerWillis 2016-08-26 13:46:11 +01:00
parent dc60db5f69
commit 6cf01f614f
2 changed files with 27 additions and 4 deletions

View File

@ -86,11 +86,32 @@ inline fun <R> rootCauseExceptions(body: () -> R): R {
}
}
/**
* Returns a free port.
*
* Unsafe for getting multiple ports!
* Use [getFreeLocalPorts] for getting multiple ports.
*/
fun freeLocalHostAndPort(): HostAndPort {
val freePort = ServerSocket(0).use { it.localPort }
return HostAndPort.fromParts("localhost", freePort)
}
/**
* Creates a specified number of ports for use by the Node.
*
* Unlikely, but in the time between running this function and handing the ports
* to the Node, some other process else could allocate the returned ports.
*/
fun getFreeLocalPorts(hostName: String, numberToAlloc: Int): List<HostAndPort> {
// Create a bunch of sockets up front.
val sockets = Array(numberToAlloc) { ServerSocket(0) }
val result = sockets.map { HostAndPort.fromParts(hostName, it.localPort) }
// Close sockets only once we've grabbed all the ports we need.
sockets.forEach(ServerSocket::close)
return result
}
/**
* Creates and tests a ledger built by the passed in dsl. The provided services can be customised, otherwise a default
* of a freshly built [MockServices] is used.

View File

@ -9,9 +9,11 @@ import java.nio.file.Paths
class IRSDemoTest {
@Test fun `runs IRS demo`() {
val nodeAddrA = freeLocalHostAndPort()
val apiAddrA = freeLocalHostAndPort()
val apiAddrB = freeLocalHostAndPort()
val hostAndPorts = getFreeLocalPorts("localhost", 4)
val nodeAddrA = hostAndPorts[0]
val apiAddrA = hostAndPorts[1]
val apiAddrB = hostAndPorts[2]
val baseDirectory = Paths.get("./build/integration-test/${TestTimestamp.timestamp}/irs-demo")
var procA: Process? = null
@ -29,7 +31,7 @@ class IRSDemoTest {
procB = startNode(
baseDirectory = baseDirectory,
nodeType = "NodeB",
nodeAddr = freeLocalHostAndPort(),
nodeAddr = hostAndPorts[3],
networkMapAddr = nodeAddrA,
apiAddr = apiAddrB
)