modernuo/Projects/Server/Console/ConsoleInputHandler.cs
Kamron Batman 7434ed7ee1
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.
2026-07-16 18:52:43 -07:00

177 lines
5.9 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: ConsoleInputHandler.cs *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Server.Logging;
namespace Server;
public static class ConsoleInputHandler
{
private static ConsoleInputPump _pump;
private static readonly Dictionary<string, ConsoleCommand> _inputCommands = new();
private static string[] _commandDescriptions;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RegisterCommand(string command, string description, Action<string> function) =>
RegisterCommand([command], description, function);
// Note: Functions will be executed on a background thread!!
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void RegisterCommand(string[] commands, string description, Action<string> function)
{
if (commands is { Length: > 0 } && function != null)
{
var consoleCommand = new ConsoleCommand(commands, description, function);
lock (_inputCommands)
{
for (var i = 0; i < commands.Length; i++)
{
var command = commands[i].ToLower();
_inputCommands[command] = consoleCommand;
}
}
_commandDescriptions = null;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool UnregisterInputCommand(string command)
{
lock (_inputCommands)
{
var removed = _inputCommands.Remove(command);
_commandDescriptions = null;
return removed;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Action<string> GetInputCommand(string command)
{
lock (_inputCommands)
{
var action = _inputCommands.GetValueOrDefault(command)?.Function;
return action;
}
}
public static void Configure()
{
RegisterCommand(["help", "?"], "Displays this help screen.", DisplayHelp);
}
[CallPriority(0)]
public static void Initialize()
{
if (Core.Headless)
{
logger.Information("Console input disabled (headless: stdin is not a TTY).");
return;
}
_pump = new ConsoleInputPump(Console.In, GetInputCommand, logger);
new Thread(_pump.Run)
{
IsBackground = true,
Name = "Console Input Handler"
}.Start();
}
private static string[] GetHelpDescriptions()
{
if (_commandDescriptions != null)
{
return _commandDescriptions;
}
HashSet<ConsoleCommand> commands;
lock (_inputCommands)
{
commands = _inputCommands.Values.ToHashSet();
}
var longestCommand = 0;
var commandTuples = new (string Command, string Arguments)[commands.Count];
var index = 0;
foreach (var command in commands)
{
var commandAliases = string.Join("|", command.Commands);
longestCommand = Math.Max(longestCommand, commandAliases.Length);
commandTuples[index++] = (commandAliases, command.Description);
}
Array.Sort(commandTuples, (a, b) => a.Command.CompareOrdinal(b.Command));
_commandDescriptions = new string[commandTuples.Length];
for (var i = 0; i < commandTuples.Length; i++)
{
var (commandAliases, description) = commandTuples[i];
_commandDescriptions[i] = $"{commandAliases.PadRight(longestCommand + 1)} - {description}";
}
return _commandDescriptions;
}
private static void DisplayHelp(string arguments)
{
var commandDescriptions = GetHelpDescriptions();
if (commandDescriptions == null || commandDescriptions.Length == 0)
{
Console.WriteLine("No console commands registered.");
return;
}
Console.WriteLine("Available Commands:");
for (var i = 0; i < _commandDescriptions.Length; i++)
{
Console.WriteLine(_commandDescriptions[i]);
}
}
private static readonly ILogger logger = LogFactory.GetLogger(typeof(ConsoleInputHandler));
public static string ReadLine()
{
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();
}
return pump.ReadLine();
}
private class ConsoleCommand(string[] commands, string description, Action<string> function)
{
public readonly string[] Commands = commands;
public readonly string Description = description;
public readonly Action<string> Function = function;
}
}