Files
Chronos/src/Titano.Server/Hosting/Windows/WindowsServiceHost.cs
T
Claude 1dc93932cc fix(server): report Windows service start and stop failures to the event log
A service has no console, and a refused data folder or server.json throws
before the server's log file exists, so the SCM recorded only error 1064
and the entry to check was lost. ServiceMain and the stop path now also
write the reason to the Application event log (source TitanoServer,
advapi32 ReportEventW, no message file registered). The Windows README
says where to look and that a data folder created by an unelevated
console run must be deleted or given to Administrators first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 15:51:22 +00:00

122 lines
4.5 KiB
C#

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static Titano.Server.Hosting.Windows.ServiceNative;
namespace Titano.Server.Hosting.Windows;
/// <summary>
/// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW,
/// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running
/// jobs keep their checkpoints and resume at the next start. A failure to start or stop goes to the Application event
/// log (<see cref="ServiceEventLog"/>), since a service has no console.
/// </summary>
[SupportedOSPlatform("windows")]
public static class WindowsServiceHost
{
public const string ServiceName = "TitanoServer";
private const uint StartWaitHint = 60_000;
private const uint StopWaitHint = 35_000;
private static readonly ServiceStatusTracker Status = new();
private static Func<WebApplication>? _build;
private static WebApplication? _app;
private static nint _statusHandle;
/// <summary>
/// Hands the process to the Service Control Manager and returns when the service has stopped. False when the
/// process was not started by the SCM (for example from a console).
/// </summary>
public static unsafe bool Run(Func<WebApplication> build)
{
_build = build;
fixed (char* name = ServiceName)
{
var table = stackalloc ServiceTableEntry[2];
table[0] = new ServiceTableEntry { ServiceName = name, ServiceProc = &ServiceMain };
table[1] = default;
if (StartServiceCtrlDispatcherW(table)) return true;
}
var error = Marshal.GetLastPInvokeError();
if (error == ErrorFailedServiceControllerConnect) return false;
throw new Win32Exception(error);
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe void ServiceMain(uint argc, char** argv)
{
_statusHandle = RegisterServiceCtrlHandlerExW(ServiceName, &Handler, 0);
if (_statusHandle == 0) return;
Report(Status.StartPending(StartWaitHint));
try
{
_app = _build!();
_app.StartAsync().GetAwaiter().GetResult();
Report(Status.Running());
}
catch (Exception ex)
{
// A refused data folder or server.json says which entry to check; the SCM itself records only error 1064.
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StartFailed, ServiceEventLog.Describe("Titano Server did not start:", ex));
Report(Status.Stopped(ErrorExceptionInService));
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe uint Handler(uint control, uint eventType, nint eventData, nint context)
{
switch (control)
{
case ControlStop or ControlShutdown:
if (Status.Current.State is ServiceState.Running or ServiceState.StartPending)
{
Report(Status.StopPending(StopWaitHint));
// The handler must return at once; the host stops on the thread pool.
_ = Task.Run(StopAsync);
}
return NoError;
case ControlInterrogate:
Report(Status.Current);
return NoError;
default:
return ErrorCallNotImplemented;
}
}
private static async Task StopAsync()
{
uint exitCode = 0;
try
{
if (_app is { } app)
{
await app.StopAsync();
await app.DisposeAsync();
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StopFailed, ServiceEventLog.Describe("Titano Server did not stop cleanly:", ex));
exitCode = ErrorExceptionInService;
}
Report(Status.Stopped(exitCode));
}
private static unsafe void Report(ServiceStatusReport report)
{
var status = new ServiceStatus
{
ServiceType = ServiceWin32OwnProcess,
CurrentState = (uint)report.State,
ControlsAccepted = report.ControlsAccepted,
Win32ExitCode = report.ExitCode,
CheckPoint = report.CheckPoint,
WaitHint = report.WaitHintMilliseconds,
};
SetServiceStatus(_statusHandle, &status);
}
}