From cfbe01fea639fc8256b10642e8619261170036f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Standa=20Nov=C3=A1k?= Date: Mon, 25 Nov 2024 17:17:21 +0100 Subject: [PATCH] chore: Check port availability before starting Tomcat (#2716) It gave just a cryptic error before, hard to determine what to do. Closes #2648. Co-authored-by: StaNov --- .../tolgee/configuration/PortAvailability.kt | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 backend/app/src/main/kotlin/io/tolgee/configuration/PortAvailability.kt diff --git a/backend/app/src/main/kotlin/io/tolgee/configuration/PortAvailability.kt b/backend/app/src/main/kotlin/io/tolgee/configuration/PortAvailability.kt new file mode 100644 index 0000000000..c2b3723ea6 --- /dev/null +++ b/backend/app/src/main/kotlin/io/tolgee/configuration/PortAvailability.kt @@ -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) + } + } +}