fix(console): stop headless servers from pegging a CPU core (#2535)

## Problem

On headless Linux deployments (systemd service, Docker without a TTY, `nohup`), the ModernUO process pegs a full CPU core even when idle. It does not reproduce on Windows because that runs with an interactive console.

## Root cause

`ConsoleInputHandler` runs a background thread (named "Console Input Handler") that loops on `Console.ReadLine()`. When stdin is **not** an interactive terminal, `Console.ReadLine()` returns `null` at end-of-stream **immediately** on every call, so the loop `continue`s in a tight spin — one core at 100%.

Reproduced in a container running the actual distribution: the "Console Input Handler" thread sat at ~90% CPU on a headless boot; with a blocking stdin it dropped to idle.

## Fix

1. **Detect headless once at startup:** `Core.Headless = Console.IsInputRedirected`.
2. **Extract a testable `ConsoleInputPump`** that owns the input stream: per line read, it *atomically* (under one lock) either delivers the line to a waiting prompt or dispatches a console command, and it **ends on EOF instead of spinning**. Cleanup runs unconditionally in a `finally`, so a pending prompt is always released (never hangs). Replaces the old `async void` loop and the fragile `_expectUserInput` / two-`AutoResetEvent` / `_input` handshake.
3. **`ConsoleInputHandler` becomes a thin headless-aware facade** over the pump. Headless: the reader thread never starts (`Console input disabled (headless: stdin is not a TTY).`), and `ReadLine()` throws a fatal `HeadlessConsoleInputException`.
4. **Data-gating and first-boot prompts** (deserialization "delete bad types? y/n", save-conflict, config/expansion setup) now route through `ConsoleInputHandler.ReadLine()`, so a headless server crashes fatal with a clear message instead of reading `null` (previously an NRE or a silent wrong branch).

Design decision (model b): headless servers are expected to be supplied with configuration/save data (including the owner account); interactive prompts when headless are fatal by design.

## Testing

- New `ConsoleInputPumpTests` (5 tests): EOF ends the loop without spinning; command dispatch; a pending prompt receives the next line; EOF while a prompt is pending completes it with `null` (no hang); a throwing command lookup does not hang a pending prompt. The tests synchronize on real pump state (no `Thread.Sleep`), so they are deterministic on slow CI.
- Full `Server.Tests`: no new failures introduced.

## End-to-end verification (Docker, real distribution)

| | Console Input Handler thread | Container CPU |
|---|---|---|
| Before fix (headless boot) | ~90% | ~199% (2 cores) |
| After fix (headless boot) | **not started** | **~11%** |

After the fix, a headless boot logs `Console input disabled (headless: stdin is not a TTY).`, loads the world normally, and idles instead of spinning.
This commit is contained in:
Kamron Batman 2026-07-16 18:52:43 -07:00 committed by GitHub
parent f4a771c19d
commit 7434ed7ee1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
9 changed files with 354 additions and 74 deletions

View file

@ -24,13 +24,9 @@ namespace Server;
public static class ConsoleInputHandler
{
private static readonly AutoResetEvent _receivedUserInput = new(false);
private static readonly AutoResetEvent _endUserInput = new(false);
private static bool _initialized;
private static bool _expectUserInput;
private static ConsoleInputPump _pump;
private static readonly Dictionary<string, ConsoleCommand> _inputCommands = new();
private static string[] _commandDescriptions;
private static string _input;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RegisterCommand(string command, string description, Action<string> function) =>
@ -73,7 +69,6 @@ public static class ConsoleInputHandler
lock (_inputCommands)
{
var action = _inputCommands.GetValueOrDefault(command)?.Function;
_commandDescriptions = null;
return action;
}
}
@ -86,9 +81,15 @@ public static class ConsoleInputHandler
[CallPriority(0)]
public static void Initialize()
{
_initialized = true;
if (Core.Headless)
{
logger.Information("Console input disabled (headless: stdin is not a TTY).");
return;
}
new Thread(ProcessConsoleInput)
_pump = new ConsoleInputPump(Console.In, GetInputCommand, logger);
new Thread(_pump.Run)
{
IsBackground = true,
Name = "Console Input Handler"
@ -150,69 +151,21 @@ public static class ConsoleInputHandler
private static readonly ILogger logger = LogFactory.GetLogger(typeof(ConsoleInputHandler));
private static async void ProcessConsoleInput()
{
while (!Core.Closing)
{
string input;
try
{
input = Console.ReadLine()?.Trim();
}
catch
{
logger.Warning("Console commands have been disabled due to an error.");
_initialized = false;
return;
}
if (Volatile.Read(ref _expectUserInput))
{
_input = input;
_receivedUserInput.Set();
_endUserInput.WaitOne();
continue;
}
if (string.IsNullOrEmpty(input))
{
continue;
}
var splitInput = input.Split(' ', 2);
var command = splitInput[0].ToLower();
try
{
Action<string> action;
lock (_inputCommands)
{
action = _inputCommands.GetValueOrDefault(command)?.Function;
}
action?.Invoke(splitInput.Length > 1 ? splitInput[1] : string.Empty);
}
catch (Exception e)
{
logger.Error(e, "Failed to execute console command: {Command}", input);
}
}
}
public static string ReadLine()
{
if (!_initialized)
if (Core.Headless)
{
throw new HeadlessConsoleInputException("ConsoleInputHandler.ReadLine");
}
// Early startup (before Initialize) or after the loop ended: read directly.
var pump = _pump;
if (pump is not { Running: true })
{
return Console.ReadLine();
}
Volatile.Write(ref _expectUserInput, true);
_receivedUserInput.WaitOne();
var line = _input;
Volatile.Write(ref _expectUserInput, false);
_endUserInput.Set();
return line;
return pump.ReadLine();
}
private class ConsoleCommand(string[] commands, string description, Action<string> function)