ModernUO/Projects/Server/Serialization/GenericPersistence.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
4 KiB
C#

/*************************************************************************
* ModernUO *
* Copyright 2019-2026 - ModernUO Development Team *
* Email: hi@modernuo.com *
* File: GenericPersistence.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.IO;
using System.IO.MemoryMappedFiles;
namespace Server;
public abstract class GenericPersistence : Persistence, IGenericSerializable
{
public string Name { get; }
public string SaveFilePath { get; protected set; } // "<Folder>/<System>.bin"
public byte SerializedThread { get; set; }
public int SerializedPosition { get; set; }
public int SerializedLength { get; set; }
public GenericPersistence(string name, int priority) : base(priority)
{
Name = name;
SaveFilePath = Path.Combine(Name, $"{Name}.bin");
}
public override void Serialize()
{
World.PushToCache(this);
}
public override void WriteSnapshot(string savePath, HashSet<Type> typeSet)
{
if (SerializedLength == 0)
{
return;
}
var file = Path.Combine(savePath, SaveFilePath);
var dir = Path.GetDirectoryName(file);
PathUtility.EnsureDirectory(dir);
var threads = World._threadWorkers;
using var binFs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None);
var thread = SerializedThread;
var heapStart = SerializedPosition;
var heapLength = SerializedLength;
binFs.Write(threads[thread].GetHeap(heapStart, heapLength));
}
public override unsafe void Deserialize(string savePath, Dictionary<ulong, string> typesDb)
{
// Assume savePath has the Core.BaseDirectory already prepended
var dataPath = Path.GetFullPath(SaveFilePath, savePath);
var file = new FileInfo(dataPath);
if (!file.Exists || file.Length <= 0)
{
return;
}
var fileLength = file.Length;
string error;
try
{
using var mmf = MemoryMappedFile.CreateFromFile(dataPath, FileMode.Open);
using var accessor = mmf.CreateViewStream();
byte* ptr = null;
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
var dataReader = new UnmanagedDataReader(ptr, accessor.Length, typesDb);
Deserialize(dataReader);
error = dataReader.Position != fileLength
? $"Serialized {fileLength} bytes, but {dataReader.Position} bytes deserialized"
: null;
accessor.SafeMemoryMappedViewHandle.ReleasePointer();
}
catch (Exception e)
{
error = e.ToString();
}
if (error != null)
{
Console.WriteLine($"***** Bad deserialize of {file.FullName} *****");
Console.WriteLine(error);
Console.Write("Skip this file and continue? (y/n): ");
var y = ConsoleInputHandler.ReadLine();
if (!y.InsensitiveEquals("y"))
{
throw new Exception("Deserialization failed.");
}
}
}
public abstract void Serialize(IGenericWriter writer);
public abstract void Deserialize(IGenericReader reader);
}