Skip to content

Commit

Permalink
chore: Check port availability before starting Tomcat (#2716)
Browse files Browse the repository at this point in the history
It gave just a cryptic error before, hard to determine what to do.

Closes #2648.

Co-authored-by: StaNov <[email protected]>
  • Loading branch information
StaNov and StaNov authored Nov 25, 2024
1 parent 46c11be commit cfbe01f
Showing 1 changed file with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package io.tolgee.configuration

import okhttp3.internal.closeQuietly
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.servlet.ServletContextInitializer
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.io.IOException
import java.net.ServerSocket
import kotlin.system.exitProcess

@Configuration
class PortAvailability {
private val logger = LoggerFactory.getLogger(PortAvailability::class.java)

@Bean
fun portAvailabilityChecker(
@Value("\${server.port:8080}") port: Int,
@Value("\${management.server.port:#{null}}") managementPort: Int?,
): ServletContextInitializer {
return ServletContextInitializer {
checkPortAvailability(port, "server.port")
managementPort?.also { checkPortAvailability(it, "management.server.port") }
}
}

private fun checkPortAvailability(
port: Int,
propertyKey: String,
) {
try {
ServerSocket(port).closeQuietly()
} catch (e: IOException) {
logger.error(
"Port $port is already in use. " +
"Please free the port or specify a different port using the `$propertyKey` property.",
e,
)
exitProcess(1)
}
}
}

0 comments on commit cfbe01f

Please sign in to comment.