modernuo/Projects/Server/Configuration/ExpansionConfigurationPrompts.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

118 lines
3.8 KiB
C#

using Server.Maps;
using System;
using System.Globalization;
namespace Server;
public static class ExpansionConfigurationPrompts
{
internal static Expansion GetExpansion()
{
Console.WriteLine("Please choose an expansion by typing the number or short name:");
var expansions = ExpansionInfo.Table;
for (var i = 0; i < expansions.Length; i++)
{
var info = expansions[i];
Console.WriteLine(" - {0,2}: {1} ({2})", i, ((Expansion)info.Id).ToString(), info.Name);
}
var maxExpansion = (Expansion)expansions[^1].Id;
var maxExpansionName = maxExpansion.ToString();
do
{
Console.Write("[enter for {0}]> ", maxExpansionName);
var input = ConsoleInputHandler.ReadLine();
Expansion expansion;
if (string.IsNullOrWhiteSpace(input))
{
expansion = maxExpansion;
}
else if (int.TryParse(input, NumberStyles.Integer, null, out var number) &&
number >= 0 && number < expansions.Length)
{
expansion = (Expansion)number;
}
else if (!Enum.TryParse(input, out expansion))
{
Utility.PushColor(ConsoleColor.Red);
Console.Write(input);
Utility.PopColor();
Console.WriteLine(" is an invalid expansion option.");
continue;
}
Console.Write("Expansion set to ");
Utility.PushColor(ConsoleColor.Green);
Console.Write(ExpansionInfo.GetInfo(expansion).Name);
Utility.PopColor();
Console.WriteLine(".");
return expansion;
} while (true);
}
internal static void OutputSelectedMaps(Expansion expansion, MapSelectionFlags selectedMaps)
{
Console.WriteLine("Selected maps:");
var i = 0;
foreach (var flag in MapSelection.EnumFromExpansion(expansion))
{
Console.WriteLine($"{i + 1}. {flag} [{(selectedMaps.Includes(flag) ? "*" : "")}]");
i++;
}
Console.WriteLine();
Console.WriteLine($"[1-{i} and enter to toggle, or enter to finish]");
}
internal static MapSelectionFlags GetSelectedMaps(Expansion expansion)
{
var expansionMaps = ExpansionInfo.GetInfo(expansion).MapSelectionFlags;
var selectedMaps = expansionMaps;
string lastInput;
do
{
OutputSelectedMaps(expansion, selectedMaps);
lastInput = ConsoleInputHandler.ReadLine()?.TrimEnd();
if (string.IsNullOrWhiteSpace(lastInput))
{
break;
}
if (!int.TryParse(lastInput, out var selectedNumber))
{
Console.WriteLine("You need to choose a number, or press ENTER on its own to accept");
continue;
}
if (selectedNumber is < 1 or > 31)
{
Console.WriteLine("That number was not an option. Please try again...");
continue;
}
var selectedFlag = (MapSelectionFlags)(1 << (selectedNumber - 1));
if (!expansionMaps.Includes(selectedFlag))
{
Console.WriteLine("That number was not an option. Please try again...");
continue;
}
selectedMaps.Toggle(selectedFlag);
} while (lastInput != "");
Console.WriteLine("These maps will be populated and moongates will not lead to other maps: ");
Utility.PushColor(ConsoleColor.Green);
Console.WriteLine(selectedMaps.ToCommaDelimitedString());
Utility.PopColor();
Console.WriteLine($"To change the selected maps, modify {ExpansionInfo.ExpansionConfigurationPath}.");
return selectedMaps;
}
}