Fix syslog server crashing whenever a client disconnects
When a client closed its connection, handleConnection threw on the null line, closed the socket, and then logged socket.description() - which reads the address of the now-closed socket and throws ClosedChannelException. That escaped the handler and crashed the whole server, dropping every other client's connection. With the Docker syslog log driver in non-blocking mode, the Factorio server's logs were then silently discarded, so most packets never arrived. Treat a null line as a normal client disconnect, capture the socket description while it's still open, and always close the socket in 'finally', so one connection can't take down the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
da9751c089
commit
2944d52843
1 changed files with 15 additions and 10 deletions
|
|
@ -17,6 +17,7 @@ import io.ktor.utils.io.readUTF8Line
|
|||
import java.util.EnumSet
|
||||
import kotlinx.coroutines.CancellationException
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.flow.MutableSharedFlow
|
||||
import kotlinx.coroutines.flow.SharedFlow
|
||||
import kotlinx.coroutines.flow.asSharedFlow
|
||||
|
|
@ -74,13 +75,15 @@ class SyslogSocketServer(
|
|||
private suspend fun handleConnection(
|
||||
socket: Socket
|
||||
): Unit = supervisorScope {
|
||||
// Capture this while the socket is open - reading the address of a closed socket throws,
|
||||
// which previously escaped this handler and crashed the whole server, dropping every client.
|
||||
val description = socket.description()
|
||||
try {
|
||||
val channel = socket.openReadChannel()
|
||||
while (socket.socketContext.isActive && !channel.isClosedForRead) {
|
||||
while (socket.socketContext.isActive) {
|
||||
|
||||
val line = channel.readUTF8Line()
|
||||
|
||||
requireNotNull(line) { "received 'null' line from ${socket.description()}" }
|
||||
// null means the client closed the connection
|
||||
val line = channel.readUTF8Line() ?: break
|
||||
|
||||
try {
|
||||
val messageContents = syslogParser.parseLine(line)
|
||||
|
|
@ -92,13 +95,15 @@ class SyslogSocketServer(
|
|||
|
||||
yield()
|
||||
}
|
||||
log("client closed socket $description")
|
||||
} catch (ex: CancellationException) {
|
||||
throw ex
|
||||
} catch (ex: Throwable) {
|
||||
withContext(Dispatchers.IO) { socket.close() }
|
||||
if (ex is CancellationException) {
|
||||
throw ex
|
||||
} else {
|
||||
log("closing socket ${socket.description()}, cause: ${ex::class.qualifiedName} ${ex.message}")
|
||||
ex.printStackTrace()
|
||||
log("closing socket $description, cause: ${ex::class.qualifiedName} ${ex.message}")
|
||||
ex.printStackTrace()
|
||||
} finally {
|
||||
withContext(NonCancellable + Dispatchers.IO) {
|
||||
runCatching { socket.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue