Merged in mike-so-reuseaddr (pull request #321)

Testing: Make PortAllocation set SO_REUSEADDR to avoid CI conflicts
This commit is contained in:
Andras Slemmer 2016-09-05 12:24:52 +01:00
commit ea3c63e023

View File

@ -20,10 +20,7 @@ import com.typesafe.config.ConfigRenderOptions
import org.slf4j.Logger import org.slf4j.Logger
import org.slf4j.LoggerFactory import org.slf4j.LoggerFactory
import java.io.File import java.io.File
import java.net.ServerSocket import java.net.*
import java.net.Socket
import java.net.SocketException
import java.net.URLClassLoader
import java.nio.file.Paths import java.nio.file.Paths
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.* import java.util.*
@ -95,7 +92,13 @@ sealed class PortAllocation {
override fun nextPort() = portCounter++ override fun nextPort() = portCounter++
} }
class RandomFree(): PortAllocation() { class RandomFree(): PortAllocation() {
override fun nextPort() = ServerSocket(0).use { it.localPort } override fun nextPort(): Int {
return ServerSocket().use {
it.reuseAddress = true
it.bind(InetSocketAddress("localhost", 0))
it.localPort
}
}
} }
} }
@ -179,10 +182,13 @@ private fun getTimestampAsDirectoryName(): String {
fun addressMustBeBound(hostAndPort: HostAndPort) { fun addressMustBeBound(hostAndPort: HostAndPort) {
poll("address $hostAndPort to bind") { poll("address $hostAndPort to bind") {
try { try {
Socket(hostAndPort.hostText, hostAndPort.port).close() ServerSocket().use {
Unit it.reuseAddress = true
} catch (_exception: SocketException) { it.bind(InetSocketAddress(hostAndPort.hostText, hostAndPort.port))
}
null null
} catch (_exception: SocketException) {
Unit
} }
} }
} }
@ -190,10 +196,13 @@ fun addressMustBeBound(hostAndPort: HostAndPort) {
fun addressMustNotBeBound(hostAndPort: HostAndPort) { fun addressMustNotBeBound(hostAndPort: HostAndPort) {
poll("address $hostAndPort to unbind") { poll("address $hostAndPort to unbind") {
try { try {
Socket(hostAndPort.hostText, hostAndPort.port).close() ServerSocket().use {
null it.reuseAddress = true
} catch (_exception: SocketException) { it.bind(InetSocketAddress(hostAndPort.hostText, hostAndPort.port))
}
Unit Unit
} catch (_exception: SocketException) {
null
} }
} }
} }