Skip to content

Commit

Permalink
Add SocketAllocationSpec
Browse files Browse the repository at this point in the history
  • Loading branch information
bell-db committed Sep 13, 2024
1 parent 84d64f9 commit 7a1d089
Showing 1 changed file with 50 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package protocbridge.frontend
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.must.Matchers

import java.lang.management.ManagementFactory
import java.net.ServerSocket
import scala.collection.mutable
import scala.sys.process._
import scala.util.{Failure, Success, Try}

class SocketAllocationSpec extends AnyFlatSpec with Matchers {
it must "allocate an unused port" in {
val repeatCount = 100000
val portConflictCount = mutable.Map[Int, Int]()

val currentPid = getCurrentPid

for (i <- 1 to repeatCount) {
if (i % 100 == 1) println(s"Running iteration $i of $repeatCount")

val serverSocket = new ServerSocket(0) // Bind to any available port.
try {
val port = serverSocket.getLocalPort
Try {
s"lsof -i :$port -t".!!.trim
} match {
case Success(output) =>
if (output.nonEmpty) {
val pids = output.split("\n").filterNot(_.contains(currentPid.toString))
if (pids.nonEmpty) {
System.err.println("Port conflict detected on port " + port + " with PIDs: " + pids.mkString(", "))
portConflictCount(port) = portConflictCount.getOrElse(port, 0) + 1
}
}
case Failure(_) => // Ignore failure and continue
}
} finally {
serverSocket.close()
}
}

assert(portConflictCount.isEmpty, s"Found the following ports in use out of $repeatCount: $portConflictCount")
}

private def getCurrentPid: Int = {
val jvmName = ManagementFactory.getRuntimeMXBean.getName
val pid = jvmName.split("@")(0)
pid.toInt
}
}

0 comments on commit 7a1d089

Please sign in to comment.