| | | 1 | | using System.Management.Automation; |
| | | 2 | | using System.Management.Automation.Runspaces; |
| | | 3 | | using Kestrun.Runner; |
| | | 4 | | using Microsoft.PowerShell; |
| | | 5 | | using System.Runtime.Versioning; |
| | | 6 | | using System.ServiceProcess; |
| | | 7 | | using System.Text; |
| | | 8 | | |
| | | 9 | | namespace Kestrun.ServiceHost; |
| | | 10 | | |
| | | 11 | | internal static class Program |
| | | 12 | | { |
| | 9 | 13 | | private sealed record ParsedOptions( |
| | 9 | 14 | | string ServiceName, |
| | 3 | 15 | | string RunnerExecutablePath, |
| | 6 | 16 | | string ScriptPath, |
| | 5 | 17 | | string ModuleManifestPath, |
| | 3 | 18 | | string[] ScriptArguments, |
| | 0 | 19 | | string? ServiceLogPath, |
| | 9 | 20 | | bool DirectRunMode, |
| | 10 | 21 | | bool DiscoverPowerShellHome); |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Mutable state used while parsing service-host command-line options. |
| | | 25 | | /// </summary> |
| | | 26 | | private sealed class ArgumentParseState |
| | | 27 | | { |
| | 17 | 28 | | public string ServiceName { get; set; } = string.Empty; |
| | | 29 | | |
| | 15 | 30 | | public string RunnerExecutablePath { get; set; } = string.Empty; |
| | | 31 | | |
| | 28 | 32 | | public string ScriptPath { get; set; } = string.Empty; |
| | | 33 | | |
| | 21 | 34 | | public string ModuleManifestPath { get; set; } = string.Empty; |
| | | 35 | | |
| | 12 | 36 | | public string[] ScriptArguments { get; set; } = []; |
| | | 37 | | |
| | 3 | 38 | | public string? ServiceLogPath { get; set; } |
| | | 39 | | |
| | 9 | 40 | | public bool DirectRunMode { get; set; } |
| | | 41 | | |
| | 4 | 42 | | public bool DiscoverPowerShellHome { get; set; } |
| | | 43 | | |
| | 7 | 44 | | public bool ScriptOptionSeen { get; set; } |
| | | 45 | | |
| | 7 | 46 | | public bool RunOptionSeen { get; set; } |
| | | 47 | | } |
| | | 48 | | |
| | | 49 | | private static int Main(string[] args) |
| | | 50 | | { |
| | 0 | 51 | | if (!TryParseArguments(args, out var options, out var error)) |
| | | 52 | | { |
| | 0 | 53 | | Console.Error.WriteLine(error); |
| | 0 | 54 | | PrintUsage(); |
| | 0 | 55 | | return 2; |
| | | 56 | | } |
| | | 57 | | // If running on Windows and not in an interactive session, run as a Windows Service. |
| | 0 | 58 | | if (OperatingSystem.IsWindows() && !Environment.UserInteractive) |
| | | 59 | | { |
| | 0 | 60 | | return RunWindowsService(options!); |
| | | 61 | | } |
| | | 62 | | // For non-Windows or interactive sessions, run as a foreground daemon. |
| | 0 | 63 | | return RunForegroundDaemon(options!); |
| | | 64 | | } |
| | | 65 | | |
| | | 66 | | [SupportedOSPlatform("windows")] |
| | | 67 | | private static int RunWindowsService(ParsedOptions options) |
| | | 68 | | { |
| | 0 | 69 | | ServiceBase.Run(new KestrunWindowsService(options)); |
| | 0 | 70 | | return 0; |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | /// <summary> |
| | | 74 | | /// Parses command-line arguments into strongly typed service-host options. |
| | | 75 | | /// </summary> |
| | | 76 | | /// <param name="args">The command-line arguments passed to the application.</param> |
| | | 77 | | /// <param name="options">Parsed options when successful; otherwise null.</param> |
| | | 78 | | /// <param name="error">An error message if argument parsing fails.</param> |
| | | 79 | | /// <returns>True when arguments were successfully parsed; otherwise false.</returns> |
| | | 80 | | private static bool TryParseArguments(string[] args, out ParsedOptions? options, out string error) |
| | | 81 | | { |
| | 8 | 82 | | options = null; |
| | | 83 | | |
| | 8 | 84 | | var parseState = new ArgumentParseState(); |
| | 8 | 85 | | return TryParseOptionTokens(args, parseState, out error) |
| | 8 | 86 | | && TryBuildParsedOptions(parseState, out options, out error); |
| | | 87 | | } |
| | | 88 | | |
| | | 89 | | /// <summary> |
| | | 90 | | /// Parses raw argument tokens into intermediate state. |
| | | 91 | | /// </summary> |
| | | 92 | | /// <param name="args">Raw argument list.</param> |
| | | 93 | | /// <param name="parseState">Mutable parse state.</param> |
| | | 94 | | /// <param name="error">Error message when parsing fails.</param> |
| | | 95 | | /// <returns>True when all tokens were parsed successfully; otherwise false.</returns> |
| | | 96 | | private static bool TryParseOptionTokens(string[] args, ArgumentParseState parseState, out string error) |
| | | 97 | | { |
| | 8 | 98 | | error = string.Empty; |
| | 8 | 99 | | var index = 0; |
| | 26 | 100 | | while (index < args.Length) |
| | | 101 | | { |
| | 22 | 102 | | if (!TryHandleArgumentToken(args, ref index, parseState, out var stopParsing, out error)) |
| | | 103 | | { |
| | 3 | 104 | | return false; |
| | | 105 | | } |
| | | 106 | | |
| | 19 | 107 | | if (stopParsing) |
| | | 108 | | { |
| | | 109 | | break; |
| | | 110 | | } |
| | | 111 | | } |
| | | 112 | | |
| | 5 | 113 | | return true; |
| | | 114 | | } |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// Parses one argument token and updates parsing state. |
| | | 118 | | /// </summary> |
| | | 119 | | /// <param name="args">Raw argument list.</param> |
| | | 120 | | /// <param name="index">Current argument index.</param> |
| | | 121 | | /// <param name="parseState">Mutable parse state.</param> |
| | | 122 | | /// <param name="stopParsing">True when token consumes remaining arguments and parsing should stop.</param> |
| | | 123 | | /// <param name="error">Error message when parsing fails.</param> |
| | | 124 | | /// <returns>True when the token was parsed successfully; otherwise false.</returns> |
| | | 125 | | private static bool TryHandleArgumentToken( |
| | | 126 | | string[] args, |
| | | 127 | | ref int index, |
| | | 128 | | ArgumentParseState parseState, |
| | | 129 | | out bool stopParsing, |
| | | 130 | | out string error) |
| | | 131 | | { |
| | 22 | 132 | | stopParsing = false; |
| | 22 | 133 | | error = string.Empty; |
| | | 134 | | |
| | 22 | 135 | | var current = args[index]; |
| | | 136 | | switch (current) |
| | | 137 | | { |
| | | 138 | | case "--name": |
| | 4 | 139 | | if (!TryReadOptionValue(args, ref index, current, out var serviceName, out error)) |
| | | 140 | | { |
| | 0 | 141 | | return false; |
| | | 142 | | } |
| | | 143 | | |
| | 4 | 144 | | parseState.ServiceName = serviceName; |
| | 4 | 145 | | return true; |
| | | 146 | | |
| | | 147 | | case "--runner-exe": |
| | 1 | 148 | | if (!TryReadOptionValue(args, ref index, current, out var runnerExecutablePath, out error)) |
| | | 149 | | { |
| | 0 | 150 | | return false; |
| | | 151 | | } |
| | | 152 | | |
| | 1 | 153 | | parseState.RunnerExecutablePath = runnerExecutablePath; |
| | 1 | 154 | | return true; |
| | | 155 | | |
| | | 156 | | case "--script": |
| | 4 | 157 | | return TryReadScriptPathOption(args, ref index, current, parseState, directRunMode: false, out error); |
| | | 158 | | |
| | | 159 | | case "--run": |
| | 4 | 160 | | return TryReadScriptPathOption(args, ref index, current, parseState, directRunMode: true, out error); |
| | | 161 | | |
| | | 162 | | case "--kestrun-manifest": |
| | 6 | 163 | | if (!TryReadOptionValue(args, ref index, current, out var moduleManifestPath, out error)) |
| | | 164 | | { |
| | 0 | 165 | | return false; |
| | | 166 | | } |
| | | 167 | | |
| | 6 | 168 | | parseState.ModuleManifestPath = moduleManifestPath; |
| | 6 | 169 | | return true; |
| | | 170 | | |
| | | 171 | | case "--service-log-path": |
| | 0 | 172 | | if (!TryReadOptionValue(args, ref index, current, out var parsedLogPath, out error)) |
| | | 173 | | { |
| | 0 | 174 | | return false; |
| | | 175 | | } |
| | | 176 | | |
| | 0 | 177 | | parseState.ServiceLogPath = parsedLogPath; |
| | 0 | 178 | | return true; |
| | | 179 | | |
| | | 180 | | case "--discover-pshome": |
| | 1 | 181 | | parseState.DiscoverPowerShellHome = true; |
| | 1 | 182 | | index += 1; |
| | 1 | 183 | | return true; |
| | | 184 | | |
| | | 185 | | case "--arguments": |
| | | 186 | | case "--": |
| | 1 | 187 | | parseState.ScriptArguments = [.. args.Skip(index + 1)]; |
| | 1 | 188 | | stopParsing = true; |
| | 1 | 189 | | return true; |
| | | 190 | | |
| | | 191 | | default: |
| | 1 | 192 | | error = $"Unknown option: {current}"; |
| | 1 | 193 | | return false; |
| | | 194 | | } |
| | | 195 | | } |
| | | 196 | | |
| | | 197 | | /// <summary> |
| | | 198 | | /// Reads the script path option value and enforces mutual exclusivity between <c>--script</c> and <c>--run</c>. |
| | | 199 | | /// </summary> |
| | | 200 | | /// <param name="args">Raw argument list.</param> |
| | | 201 | | /// <param name="index">Current argument index.</param> |
| | | 202 | | /// <param name="optionName">Option name being parsed.</param> |
| | | 203 | | /// <param name="parseState">Mutable parse state.</param> |
| | | 204 | | /// <param name="directRunMode">True when parsing <c>--run</c>; false for <c>--script</c>.</param> |
| | | 205 | | /// <param name="error">Error message when parsing fails.</param> |
| | | 206 | | /// <returns>True when parsing succeeds; otherwise false.</returns> |
| | | 207 | | private static bool TryReadScriptPathOption( |
| | | 208 | | string[] args, |
| | | 209 | | ref int index, |
| | | 210 | | string optionName, |
| | | 211 | | ArgumentParseState parseState, |
| | | 212 | | bool directRunMode, |
| | | 213 | | out string error) |
| | | 214 | | { |
| | 8 | 215 | | var conflictingOptionSeen = directRunMode |
| | 8 | 216 | | ? parseState.ScriptOptionSeen |
| | 8 | 217 | | : parseState.RunOptionSeen; |
| | 8 | 218 | | if (conflictingOptionSeen) |
| | | 219 | | { |
| | 2 | 220 | | error = "Options --script and --run are mutually exclusive."; |
| | 2 | 221 | | return false; |
| | | 222 | | } |
| | | 223 | | |
| | 6 | 224 | | if (!TryReadOptionValue(args, ref index, optionName, out var scriptPath, out error)) |
| | | 225 | | { |
| | 0 | 226 | | return false; |
| | | 227 | | } |
| | | 228 | | |
| | 6 | 229 | | parseState.ScriptPath = scriptPath; |
| | 6 | 230 | | if (directRunMode) |
| | | 231 | | { |
| | 3 | 232 | | parseState.RunOptionSeen = true; |
| | 3 | 233 | | parseState.DirectRunMode = true; |
| | | 234 | | } |
| | | 235 | | else |
| | | 236 | | { |
| | 3 | 237 | | parseState.ScriptOptionSeen = true; |
| | | 238 | | } |
| | | 239 | | |
| | 6 | 240 | | return true; |
| | | 241 | | } |
| | | 242 | | |
| | | 243 | | /// <summary> |
| | | 244 | | /// Validates parsed state, applies defaults, and constructs final parsed options. |
| | | 245 | | /// </summary> |
| | | 246 | | /// <param name="parseState">Parsed intermediate state.</param> |
| | | 247 | | /// <param name="options">Final parsed options when successful; otherwise null.</param> |
| | | 248 | | /// <param name="error">Error message when validation fails.</param> |
| | | 249 | | /// <returns>True when final options can be built; otherwise false.</returns> |
| | | 250 | | private static bool TryBuildParsedOptions(ArgumentParseState parseState, out ParsedOptions? options, out string erro |
| | | 251 | | { |
| | 5 | 252 | | options = null; |
| | 5 | 253 | | error = string.Empty; |
| | | 254 | | |
| | 5 | 255 | | var serviceName = parseState.ServiceName; |
| | 5 | 256 | | if (string.IsNullOrWhiteSpace(serviceName) && !string.IsNullOrWhiteSpace(parseState.ScriptPath)) |
| | | 257 | | { |
| | 3 | 258 | | serviceName = BuildDefaultServiceNameFromScriptPath(parseState.ScriptPath, parseState.DirectRunMode); |
| | | 259 | | } |
| | | 260 | | |
| | 5 | 261 | | if (string.IsNullOrWhiteSpace(serviceName)) |
| | | 262 | | { |
| | 0 | 263 | | error = "Missing --name."; |
| | 0 | 264 | | return false; |
| | | 265 | | } |
| | | 266 | | |
| | 5 | 267 | | var runnerExecutablePath = string.IsNullOrWhiteSpace(parseState.RunnerExecutablePath) |
| | 5 | 268 | | ? ResolveCurrentExecutablePath() |
| | 5 | 269 | | : parseState.RunnerExecutablePath; |
| | | 270 | | |
| | 5 | 271 | | if (string.IsNullOrWhiteSpace(parseState.ScriptPath)) |
| | | 272 | | { |
| | 1 | 273 | | error = "Missing --script or --run."; |
| | 1 | 274 | | return false; |
| | | 275 | | } |
| | | 276 | | |
| | 4 | 277 | | if (string.IsNullOrWhiteSpace(parseState.ModuleManifestPath)) |
| | | 278 | | { |
| | 1 | 279 | | error = "Missing --kestrun-manifest."; |
| | 1 | 280 | | return false; |
| | | 281 | | } |
| | | 282 | | |
| | 3 | 283 | | options = new ParsedOptions( |
| | 3 | 284 | | serviceName, |
| | 3 | 285 | | Path.GetFullPath(runnerExecutablePath), |
| | 3 | 286 | | Path.GetFullPath(parseState.ScriptPath), |
| | 3 | 287 | | Path.GetFullPath(parseState.ModuleManifestPath), |
| | 3 | 288 | | parseState.ScriptArguments, |
| | 3 | 289 | | parseState.ServiceLogPath, |
| | 3 | 290 | | parseState.DirectRunMode, |
| | 3 | 291 | | parseState.DiscoverPowerShellHome); |
| | 3 | 292 | | return true; |
| | | 293 | | } |
| | | 294 | | |
| | | 295 | | /// <summary> |
| | | 296 | | /// Reads a required value for the current option and advances the parse index. |
| | | 297 | | /// </summary> |
| | | 298 | | /// <param name="args">Raw argument list.</param> |
| | | 299 | | /// <param name="index">Current option index; advanced when a value is consumed.</param> |
| | | 300 | | /// <param name="optionName">Option name used in diagnostics.</param> |
| | | 301 | | /// <param name="value">Parsed option value.</param> |
| | | 302 | | /// <param name="error">Error message when value is missing.</param> |
| | | 303 | | /// <returns>True when a value exists; otherwise false.</returns> |
| | | 304 | | private static bool TryReadOptionValue(string[] args, ref int index, string optionName, out string value, out string |
| | | 305 | | { |
| | 17 | 306 | | value = string.Empty; |
| | 17 | 307 | | error = string.Empty; |
| | 17 | 308 | | if (index + 1 >= args.Length) |
| | | 309 | | { |
| | 0 | 310 | | error = $"Missing value for {optionName}."; |
| | 0 | 311 | | return false; |
| | | 312 | | } |
| | | 313 | | |
| | 17 | 314 | | value = args[index + 1]; |
| | 17 | 315 | | index += 2; |
| | 17 | 316 | | return true; |
| | | 317 | | } |
| | | 318 | | |
| | 0 | 319 | | private static void PrintUsage() => Console.WriteLine("Usage: kestrun-service-host [--name <service>] [--runner-exe |
| | | 320 | | |
| | | 321 | | /// <summary> |
| | | 322 | | /// Resolves the path of the current executable for diagnostic and compatibility metadata. |
| | | 323 | | /// </summary> |
| | | 324 | | /// <returns>Absolute executable path when available; otherwise a fallback token.</returns> |
| | | 325 | | private static string ResolveCurrentExecutablePath() |
| | | 326 | | { |
| | 4 | 327 | | if (!string.IsNullOrWhiteSpace(Environment.ProcessPath)) |
| | | 328 | | { |
| | 4 | 329 | | return Path.GetFullPath(Environment.ProcessPath); |
| | | 330 | | } |
| | | 331 | | // Fall back to a best-guess based on the current executable name and platform conventions. |
| | 0 | 332 | | return OperatingSystem.IsWindows() |
| | 0 | 333 | | ? Path.Combine(AppContext.BaseDirectory, "kestrun-service-host.exe") |
| | 0 | 334 | | : Path.Combine(AppContext.BaseDirectory, "kestrun-service-host"); |
| | | 335 | | } |
| | | 336 | | |
| | | 337 | | /// <summary> |
| | | 338 | | /// Builds the default service name when callers omit <c>--name</c>. |
| | | 339 | | /// </summary> |
| | | 340 | | /// <param name="scriptPath">Script path provided by the caller.</param> |
| | | 341 | | /// <param name="directRunMode">True when running in direct script mode.</param> |
| | | 342 | | /// <returns>Service name default derived from script path.</returns> |
| | | 343 | | private static string BuildDefaultServiceNameFromScriptPath(string scriptPath, bool directRunMode) |
| | | 344 | | { |
| | 5 | 345 | | var stem = Path.GetFileNameWithoutExtension(scriptPath); |
| | 5 | 346 | | if (string.IsNullOrWhiteSpace(stem)) |
| | | 347 | | { |
| | 3 | 348 | | return directRunMode ? "kestrun-direct" : "kestrun-service"; |
| | | 349 | | } |
| | | 350 | | // Sanitize the stem to ensure it's a valid filename segment, since it will be used in the default log file name |
| | 2 | 351 | | return directRunMode |
| | 2 | 352 | | ? $"kestrun-direct-{stem}" |
| | 2 | 353 | | : stem; |
| | | 354 | | } |
| | | 355 | | |
| | | 356 | | private static int RunForegroundDaemon(ParsedOptions options) |
| | | 357 | | { |
| | 0 | 358 | | var logPath = ResolveBootstrapLogPath(options.ServiceLogPath, options.ServiceName); |
| | 0 | 359 | | using var host = new ScriptExecutionHost(options, logPath); |
| | | 360 | | |
| | 0 | 361 | | using var shutdown = new CancellationTokenSource(); |
| | 0 | 362 | | var processExitStopRequested = 0; |
| | 0 | 363 | | Console.CancelKeyPress += (_, eventArgs) => |
| | 0 | 364 | | { |
| | 0 | 365 | | eventArgs.Cancel = true; |
| | 0 | 366 | | shutdown.Cancel(); |
| | 0 | 367 | | }; |
| | | 368 | | |
| | 0 | 369 | | AppDomain.CurrentDomain.ProcessExit += (_, _) => |
| | 0 | 370 | | { |
| | 0 | 371 | | if (Interlocked.Exchange(ref processExitStopRequested, 1) == 0) |
| | 0 | 372 | | { |
| | 0 | 373 | | host.WriteBootstrapLog("ProcessExit received. Triggering fast daemon shutdown."); |
| | 0 | 374 | | host.StopForProcessExit(); |
| | 0 | 375 | | } |
| | 0 | 376 | | |
| | 0 | 377 | | try |
| | 0 | 378 | | { |
| | 0 | 379 | | if (!shutdown.IsCancellationRequested) |
| | 0 | 380 | | { |
| | 0 | 381 | | shutdown.Cancel(); |
| | 0 | 382 | | } |
| | 0 | 383 | | } |
| | 0 | 384 | | catch (ObjectDisposedException) |
| | 0 | 385 | | { |
| | 0 | 386 | | // Process-exit can race with using-scope disposal; cancellation is best-effort. |
| | 0 | 387 | | } |
| | 0 | 388 | | }; |
| | | 389 | | |
| | 0 | 390 | | host.WriteBootstrapLog($"Daemon '{options.ServiceName}' starting."); |
| | | 391 | | |
| | 0 | 392 | | var startCode = host.Start(); |
| | 0 | 393 | | if (startCode != 0) |
| | | 394 | | { |
| | 0 | 395 | | return startCode; |
| | | 396 | | } |
| | | 397 | | |
| | 0 | 398 | | while (!shutdown.IsCancellationRequested) |
| | | 399 | | { |
| | 0 | 400 | | if (host.HasExited) |
| | | 401 | | { |
| | 0 | 402 | | var exitCode = host.ExitCode; |
| | 0 | 403 | | host.WriteBootstrapLog($"Runner process exited with code {exitCode}."); |
| | 0 | 404 | | return exitCode; |
| | | 405 | | } |
| | | 406 | | |
| | 0 | 407 | | Thread.Sleep(250); |
| | | 408 | | } |
| | | 409 | | |
| | 0 | 410 | | host.WriteBootstrapLog($"Daemon '{options.ServiceName}' stopping."); |
| | 0 | 411 | | if (Volatile.Read(ref processExitStopRequested) == 0) |
| | | 412 | | { |
| | 0 | 413 | | host.Stop(); |
| | | 414 | | } |
| | | 415 | | else |
| | | 416 | | { |
| | 0 | 417 | | host.WriteBootstrapLog("Daemon stop already requested from ProcessExit."); |
| | | 418 | | } |
| | | 419 | | |
| | 0 | 420 | | host.WriteBootstrapLog($"Daemon '{options.ServiceName}' stopped."); |
| | 0 | 421 | | return 0; |
| | 0 | 422 | | } |
| | | 423 | | |
| | | 424 | | [SupportedOSPlatform("windows")] |
| | | 425 | | private sealed class KestrunWindowsService : ServiceBase |
| | | 426 | | { |
| | | 427 | | private readonly ScriptExecutionHost _host; |
| | | 428 | | private int _hostDisposed; |
| | | 429 | | |
| | 0 | 430 | | public KestrunWindowsService(ParsedOptions options) |
| | | 431 | | { |
| | 0 | 432 | | ServiceName = options.ServiceName; |
| | 0 | 433 | | CanStop = true; |
| | 0 | 434 | | AutoLog = true; |
| | 0 | 435 | | _host = new ScriptExecutionHost(options, ResolveBootstrapLogPath(options.ServiceLogPath, options.ServiceName |
| | 0 | 436 | | } |
| | | 437 | | |
| | | 438 | | protected override void OnStart(string[] args) |
| | | 439 | | { |
| | 0 | 440 | | _host.WriteBootstrapLog($"Service '{ServiceName}' starting."); |
| | 0 | 441 | | var exitCode = _host.Start(); |
| | 0 | 442 | | if (exitCode != 0) |
| | | 443 | | { |
| | 0 | 444 | | ExitCode = exitCode; |
| | 0 | 445 | | Stop(); |
| | 0 | 446 | | return; |
| | | 447 | | } |
| | | 448 | | |
| | 0 | 449 | | _host.RegisterOnExit(code => |
| | 0 | 450 | | { |
| | 0 | 451 | | _host.WriteBootstrapLog($"Runner process exited with code {code}."); |
| | 0 | 452 | | ExitCode = code; |
| | 0 | 453 | | Stop(); |
| | 0 | 454 | | }); |
| | 0 | 455 | | } |
| | | 456 | | |
| | | 457 | | /// <summary> |
| | | 458 | | /// Requests the script host to stop and waits for it to complete before allowing the service to stop. Also ensu |
| | | 459 | | /// </summary> <remarks> |
| | | 460 | | /// Windows Services have a complex lifecycle and can be stopped by the runtime in various ways, such as when th |
| | | 461 | | /// </remarks> |
| | | 462 | | protected override void OnStop() |
| | | 463 | | { |
| | 0 | 464 | | _host.WriteBootstrapLog($"Service '{ServiceName}' stopping."); |
| | 0 | 465 | | _host.Stop(); |
| | 0 | 466 | | _host.WriteBootstrapLog($"Service '{ServiceName}' stopped."); |
| | 0 | 467 | | DisposeHostOnce(); |
| | 0 | 468 | | } |
| | | 469 | | |
| | | 470 | | /// <summary> |
| | | 471 | | /// Ensures the script host is disposed when the service is stopped or when the service object is disposed by th |
| | | 472 | | /// </summary> |
| | | 473 | | /// <param name="disposing">True when called from <see cref="IDisposable.Dispose"/>; false when called from the |
| | | 474 | | protected override void Dispose(bool disposing) |
| | | 475 | | { |
| | 0 | 476 | | if (disposing) |
| | | 477 | | { |
| | 0 | 478 | | DisposeHostOnce(); |
| | | 479 | | } |
| | | 480 | | |
| | 0 | 481 | | base.Dispose(disposing); |
| | 0 | 482 | | } |
| | | 483 | | |
| | | 484 | | /// <summary> |
| | | 485 | | /// Disposes the script host exactly once across <see cref="OnStop"/> and <see cref="Dispose(bool)"/>. |
| | | 486 | | /// </summary> |
| | | 487 | | private void DisposeHostOnce() |
| | | 488 | | { |
| | 0 | 489 | | if (Interlocked.Exchange(ref _hostDisposed, 1) == 0) |
| | | 490 | | { |
| | 0 | 491 | | _host.Dispose(); |
| | | 492 | | } |
| | 0 | 493 | | } |
| | | 494 | | } |
| | | 495 | | |
| | | 496 | | private sealed class ScriptExecutionHost : IDisposable |
| | | 497 | | { |
| | | 498 | | private readonly ParsedOptions _options; |
| | | 499 | | private readonly string _bootstrapLogDirectory; |
| | | 500 | | private readonly string _bootstrapLogPath; |
| | 6 | 501 | | private readonly Lock _sync = new(); |
| | 6 | 502 | | private readonly CancellationTokenSource _shutdown = new(); |
| | | 503 | | private Action<int>? _onExit; |
| | | 504 | | private Task<int>? _executionTask; |
| | | 505 | | private int? _exitCode; |
| | | 506 | | private int _stopRequested; |
| | | 507 | | private int _disposed; |
| | | 508 | | |
| | 6 | 509 | | public ScriptExecutionHost(ParsedOptions options, string bootstrapLogPath) |
| | | 510 | | { |
| | 6 | 511 | | _options = options; |
| | 6 | 512 | | _bootstrapLogPath = bootstrapLogPath; |
| | 6 | 513 | | _bootstrapLogDirectory = Path.GetDirectoryName(_bootstrapLogPath) ?? Path.GetTempPath(); |
| | 6 | 514 | | WriteBootstrapLog($"Initialized script host for service '{_options.ServiceName}' (directRun={_options.Direct |
| | 6 | 515 | | } |
| | | 516 | | |
| | 0 | 517 | | public bool HasExited => _executionTask?.IsCompleted == true; |
| | | 518 | | |
| | 0 | 519 | | public int ExitCode => _exitCode ?? 0; |
| | | 520 | | |
| | | 521 | | public int Start() |
| | | 522 | | { |
| | 3 | 523 | | if (_executionTask is not null) |
| | | 524 | | { |
| | 1 | 525 | | WriteBootstrapLog("Start requested while execution task is already running."); |
| | 1 | 526 | | return 0; |
| | | 527 | | } |
| | | 528 | | |
| | 2 | 529 | | WriteBootstrapLog( |
| | 2 | 530 | | $"Validating startup inputs. script='{_options.ScriptPath}', manifest='{_options.ModuleManifestPath}', r |
| | | 531 | | |
| | 2 | 532 | | if (!File.Exists(_options.ScriptPath)) |
| | | 533 | | { |
| | 1 | 534 | | WriteBootstrapLog($"Script file not found: {_options.ScriptPath}"); |
| | 1 | 535 | | return 2; |
| | | 536 | | } |
| | | 537 | | |
| | 1 | 538 | | if (!File.Exists(_options.ModuleManifestPath)) |
| | | 539 | | { |
| | 1 | 540 | | WriteBootstrapLog($"Kestrun manifest file not found: {_options.ModuleManifestPath}"); |
| | 1 | 541 | | return 2; |
| | | 542 | | } |
| | | 543 | | |
| | | 544 | | try |
| | | 545 | | { |
| | 0 | 546 | | WriteBootstrapLog("Starting script execution task."); |
| | 0 | 547 | | _executionTask = Task.Run(() => ExecuteScript( |
| | 0 | 548 | | _options.ScriptPath, |
| | 0 | 549 | | _options.ScriptArguments, |
| | 0 | 550 | | _options.ModuleManifestPath, |
| | 0 | 551 | | _options.DiscoverPowerShellHome, |
| | 0 | 552 | | WriteBootstrapLog, |
| | 0 | 553 | | _shutdown.Token)); |
| | | 554 | | |
| | 0 | 555 | | _ = _executionTask.ContinueWith(task => |
| | 0 | 556 | | { |
| | 0 | 557 | | var code = task.IsFaulted ? 1 : task.Result; |
| | 0 | 558 | | if (task.IsFaulted) |
| | 0 | 559 | | { |
| | 0 | 560 | | WriteBootstrapLog($"Script execution failed: {task.Exception?.GetBaseException()}"); |
| | 0 | 561 | | } |
| | 0 | 562 | | else |
| | 0 | 563 | | { |
| | 0 | 564 | | WriteBootstrapLog($"Script execution task completed with exit code {code}."); |
| | 0 | 565 | | } |
| | 0 | 566 | | |
| | 0 | 567 | | Action<int>? callback; |
| | 0 | 568 | | lock (_sync) |
| | 0 | 569 | | { |
| | 0 | 570 | | _exitCode = code; |
| | 0 | 571 | | callback = _onExit; |
| | 0 | 572 | | } |
| | 0 | 573 | | |
| | 0 | 574 | | callback?.Invoke(code); |
| | 0 | 575 | | }, TaskScheduler.Default); |
| | | 576 | | |
| | 0 | 577 | | return 0; |
| | | 578 | | } |
| | 0 | 579 | | catch (Exception ex) |
| | | 580 | | { |
| | 0 | 581 | | WriteBootstrapLog($"Failed to start script execution: {ex}"); |
| | 0 | 582 | | return 1; |
| | | 583 | | } |
| | 0 | 584 | | } |
| | | 585 | | |
| | | 586 | | public void RegisterOnExit(Action<int> onExit) |
| | 1 | 587 | | { |
| | | 588 | | lock (_sync) |
| | | 589 | | { |
| | 1 | 590 | | _onExit = onExit; |
| | 1 | 591 | | if (_exitCode.HasValue) |
| | | 592 | | { |
| | 1 | 593 | | onExit(_exitCode.Value); |
| | | 594 | | } |
| | 1 | 595 | | } |
| | 1 | 596 | | } |
| | | 597 | | |
| | | 598 | | public void Stop() |
| | 3 | 599 | | => StopCore(managedStopTimeoutMilliseconds: 5000, executionWaitTimeoutMilliseconds: 15000, reason: "Stop req |
| | | 600 | | |
| | | 601 | | /// <summary> |
| | | 602 | | /// Requests a fast stop used during process-exit where shutdown time budgets are constrained by the host OS. |
| | | 603 | | /// </summary> |
| | | 604 | | public void StopForProcessExit() |
| | 0 | 605 | | => StopCore(managedStopTimeoutMilliseconds: 500, executionWaitTimeoutMilliseconds: 1500, reason: "Process-ex |
| | | 606 | | |
| | | 607 | | /// <summary> |
| | | 608 | | /// Stops script execution, first requesting managed host shutdown, then waiting briefly for the execution task. |
| | | 609 | | /// </summary> |
| | | 610 | | /// <param name="managedStopTimeoutMilliseconds">Timeout for managed host stop coordination.</param> |
| | | 611 | | /// <param name="executionWaitTimeoutMilliseconds">Timeout waiting for execution task completion.</param> |
| | | 612 | | /// <param name="reason">Diagnostic reason written to bootstrap logs.</param> |
| | | 613 | | private void StopCore(int managedStopTimeoutMilliseconds, int executionWaitTimeoutMilliseconds, string reason) |
| | | 614 | | { |
| | | 615 | | try |
| | | 616 | | { |
| | 3 | 617 | | if (Interlocked.Exchange(ref _stopRequested, 1) != 0) |
| | | 618 | | { |
| | 1 | 619 | | WriteBootstrapLog("Stop already requested; skipping duplicate stop operation."); |
| | 1 | 620 | | return; |
| | | 621 | | } |
| | | 622 | | |
| | 2 | 623 | | if (Volatile.Read(ref _disposed) != 0) |
| | | 624 | | { |
| | 1 | 625 | | WriteBootstrapLog("Stop requested after host disposal; skipping shutdown cancellation."); |
| | 1 | 626 | | return; |
| | | 627 | | } |
| | | 628 | | |
| | 1 | 629 | | WriteBootstrapLog(reason); |
| | 1 | 630 | | _shutdown.Cancel(); |
| | | 631 | | |
| | 1 | 632 | | if (!RequestManagedStopAsync().Wait(managedStopTimeoutMilliseconds)) |
| | | 633 | | { |
| | 0 | 634 | | WriteBootstrapLog($"Managed host stop timed out after {managedStopTimeoutMilliseconds}ms."); |
| | | 635 | | } |
| | | 636 | | else |
| | | 637 | | { |
| | 1 | 638 | | WriteBootstrapLog("Managed host stop completed."); |
| | | 639 | | } |
| | | 640 | | |
| | 1 | 641 | | if (_executionTask is not null) |
| | | 642 | | { |
| | 0 | 643 | | if (!_executionTask.Wait(executionWaitTimeoutMilliseconds)) |
| | | 644 | | { |
| | 0 | 645 | | WriteBootstrapLog($"Execution task did not complete within {executionWaitTimeoutMilliseconds}ms |
| | | 646 | | } |
| | | 647 | | else |
| | | 648 | | { |
| | 0 | 649 | | WriteBootstrapLog("Execution task completed after stop request."); |
| | | 650 | | } |
| | | 651 | | } |
| | 1 | 652 | | } |
| | 0 | 653 | | catch (ObjectDisposedException ex) |
| | | 654 | | { |
| | 0 | 655 | | WriteBootstrapLog($"Failed to stop script execution: {ex.Message}"); |
| | 0 | 656 | | } |
| | 0 | 657 | | catch (InvalidOperationException ex) |
| | | 658 | | { |
| | 0 | 659 | | WriteBootstrapLog($"Failed to stop script execution: {ex.Message}"); |
| | 0 | 660 | | } |
| | 0 | 661 | | catch (AggregateException ex) |
| | | 662 | | { |
| | 0 | 663 | | WriteBootstrapLog($"Failed to stop script execution: {ex.GetBaseException().Message}"); |
| | 0 | 664 | | } |
| | 3 | 665 | | } |
| | | 666 | | |
| | | 667 | | public void WriteBootstrapLog(string message) |
| | | 668 | | { |
| | | 669 | | try |
| | | 670 | | { |
| | 15 | 671 | | _ = Directory.CreateDirectory(_bootstrapLogDirectory); |
| | 15 | 672 | | var line = $"{DateTime.UtcNow:O} {message}{Environment.NewLine}"; |
| | 15 | 673 | | File.AppendAllText(_bootstrapLogPath, line, Encoding.UTF8); |
| | 15 | 674 | | } |
| | 0 | 675 | | catch |
| | | 676 | | { |
| | | 677 | | // Best-effort logging only. |
| | 0 | 678 | | } |
| | 15 | 679 | | } |
| | | 680 | | |
| | | 681 | | public void Dispose() |
| | | 682 | | { |
| | 1 | 683 | | if (Interlocked.Exchange(ref _disposed, 1) == 0) |
| | | 684 | | { |
| | 1 | 685 | | _shutdown.Dispose(); |
| | | 686 | | } |
| | 1 | 687 | | } |
| | | 688 | | } |
| | | 689 | | |
| | | 690 | | /// <summary> |
| | | 691 | | /// Executes the target script in a runspace that has Kestrun imported by manifest path. |
| | | 692 | | /// </summary> |
| | | 693 | | /// <param name="scriptPath">Absolute path to the script to execute.</param> |
| | | 694 | | /// <param name="scriptArguments">Command-line arguments passed to the target script.</param> |
| | | 695 | | /// <param name="moduleManifestPath">Absolute path to Kestrun.psd1.</param> |
| | | 696 | | /// <param name="log">Best-effort service-host logger.</param> |
| | | 697 | | /// <param name="stopToken">Cancellation token signaled during service shutdown.</param> |
| | | 698 | | /// <returns>Process exit code.</returns> |
| | | 699 | | private static int ExecuteScript( |
| | | 700 | | string scriptPath, |
| | | 701 | | IReadOnlyList<string> scriptArguments, |
| | | 702 | | string moduleManifestPath, |
| | | 703 | | bool discoverPowerShellHome, |
| | | 704 | | Action<string> log, |
| | | 705 | | CancellationToken stopToken) |
| | | 706 | | { |
| | 0 | 707 | | log($"Preparing script execution. script='{scriptPath}', manifest='{moduleManifestPath}', args=[{FormatScriptArg |
| | 0 | 708 | | EnsureNet10Runtime(); |
| | 0 | 709 | | log("Verified .NET 10 runtime."); |
| | 0 | 710 | | ConfigurePowerShellHome(discoverPowerShellHome, moduleManifestPath, log); |
| | 0 | 711 | | EnsurePowerShellRuntimeHome(); |
| | 0 | 712 | | var psHome = Environment.GetEnvironmentVariable("PSHOME"); |
| | 0 | 713 | | var psModulePath = Environment.GetEnvironmentVariable("PSModulePath"); |
| | 0 | 714 | | log($"PowerShell runtime home prepared. PSHOME='{(string.IsNullOrWhiteSpace(psHome) ? "<null>" : psHome)}', PSMo |
| | 0 | 715 | | EnsureKestrunAssemblyPreloaded(moduleManifestPath, log); |
| | 0 | 716 | | log("Kestrun assembly preload completed."); |
| | | 717 | | |
| | 0 | 718 | | var sessionState = InitialSessionState.CreateDefault2(); |
| | 0 | 719 | | if (OperatingSystem.IsWindows()) |
| | | 720 | | { |
| | 0 | 721 | | sessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted; |
| | | 722 | | } |
| | | 723 | | |
| | 0 | 724 | | sessionState.ImportPSModule([moduleManifestPath]); |
| | 0 | 725 | | log($"Imported module manifest '{moduleManifestPath}'."); |
| | | 726 | | |
| | 0 | 727 | | using var runspace = RunspaceFactory.CreateRunspace(sessionState); |
| | 0 | 728 | | runspace.Open(); |
| | 0 | 729 | | log("Runspace opened."); |
| | | 730 | | |
| | 0 | 731 | | if (!HasKestrunHostManagerType()) |
| | | 732 | | { |
| | 0 | 733 | | throw new RuntimeException("Failed to import Kestrun module: type Kestrun.KestrunHostManager was not loaded. |
| | | 734 | | } |
| | | 735 | | |
| | 0 | 736 | | runspace.SessionStateProxy.SetVariable("__krRunnerScriptPath", scriptPath); |
| | 0 | 737 | | runspace.SessionStateProxy.SetVariable("__krRunnerScriptArgs", scriptArguments.ToArray()); |
| | 0 | 738 | | runspace.SessionStateProxy.SetVariable("__krRunnerQuiet", true); |
| | 0 | 739 | | runspace.SessionStateProxy.SetVariable("__krRunnerManagedConsole", true); |
| | | 740 | | |
| | 0 | 741 | | using var powershell = PowerShell.Create(); |
| | 0 | 742 | | powershell.Runspace = runspace; |
| | | 743 | | // Dot-source the script into the current scope so function metadata used by OpenAPI discovery remains visible. |
| | 0 | 744 | | _ = powershell.AddScript(". $__krRunnerScriptPath @__krRunnerScriptArgs", useLocalScope: false); |
| | 0 | 745 | | log("PowerShell invocation configured. Starting asynchronous execution."); |
| | | 746 | | |
| | | 747 | | IEnumerable<PSObject> output; |
| | 0 | 748 | | var asyncResult = powershell.BeginInvoke(); |
| | 0 | 749 | | var stopRequested = false; |
| | | 750 | | |
| | 0 | 751 | | while (!asyncResult.IsCompleted) |
| | | 752 | | { |
| | 0 | 753 | | _ = asyncResult.AsyncWaitHandle.WaitOne(200); |
| | 0 | 754 | | if (stopToken.IsCancellationRequested && !stopRequested) |
| | | 755 | | { |
| | 0 | 756 | | stopRequested = true; |
| | 0 | 757 | | log("Stop requested. Stopping Kestrun server..."); |
| | 0 | 758 | | _ = Task.Run(RequestManagedStopAsync); |
| | | 759 | | } |
| | | 760 | | } |
| | | 761 | | |
| | 0 | 762 | | output = powershell.EndInvoke(asyncResult); |
| | 0 | 763 | | log($"Script invocation completed. HadErrors={powershell.HadErrors}."); |
| | | 764 | | |
| | 0 | 765 | | WriteOutput(output, log); |
| | 0 | 766 | | WriteStreams(powershell.Streams, log); |
| | | 767 | | |
| | 0 | 768 | | return powershell.HadErrors ? 1 : 0; |
| | 0 | 769 | | } |
| | | 770 | | |
| | | 771 | | /// <summary> |
| | | 772 | | /// Ensures the runner is executing on .NET 10. |
| | | 773 | | /// </summary> |
| | | 774 | | private static void EnsureNet10Runtime() |
| | 0 | 775 | | => RunnerRuntime.EnsureNet10Runtime("kestrun-service-host"); |
| | | 776 | | |
| | | 777 | | /// <summary> |
| | | 778 | | /// Configures <c>PSHOME</c> for service-host script execution. |
| | | 779 | | /// </summary> |
| | | 780 | | /// <param name="discoverPowerShellHome">When true, does not set <c>PSHOME</c> and lets runtime discovery resolve it |
| | | 781 | | /// <param name="moduleManifestPath">Absolute path to Kestrun.psd1.</param> |
| | | 782 | | /// <param name="log">Best-effort service-host logger.</param> |
| | | 783 | | private static void ConfigurePowerShellHome(bool discoverPowerShellHome, string moduleManifestPath, Action<string> l |
| | | 784 | | { |
| | 1 | 785 | | if (discoverPowerShellHome) |
| | | 786 | | { |
| | 1 | 787 | | log("PSHOME discovery mode enabled; skipping PSHOME override."); |
| | 1 | 788 | | return; |
| | | 789 | | } |
| | | 790 | | |
| | 0 | 791 | | var serviceRoot = ResolveServiceRootFromManifestPath(moduleManifestPath); |
| | 0 | 792 | | Environment.SetEnvironmentVariable("PSHOME", serviceRoot); |
| | 0 | 793 | | log($"PSHOME set to service root '{serviceRoot}'."); |
| | 0 | 794 | | } |
| | | 795 | | |
| | | 796 | | /// <summary> |
| | | 797 | | /// Resolves the service root path from the staged Kestrun module manifest. |
| | | 798 | | /// </summary> |
| | | 799 | | /// <param name="moduleManifestPath">Absolute path to Kestrun.psd1 under <c>Modules/Kestrun</c>.</param> |
| | | 800 | | /// <returns>Absolute service root path.</returns> |
| | | 801 | | private static string ResolveServiceRootFromManifestPath(string moduleManifestPath) |
| | | 802 | | { |
| | 1 | 803 | | var manifestDirectory = Path.GetDirectoryName(moduleManifestPath); |
| | 1 | 804 | | if (string.IsNullOrWhiteSpace(manifestDirectory)) |
| | | 805 | | { |
| | 0 | 806 | | return AppContext.BaseDirectory; |
| | | 807 | | } |
| | | 808 | | |
| | 1 | 809 | | var moduleRoot = Directory.GetParent(manifestDirectory); |
| | 1 | 810 | | var serviceRoot = moduleRoot?.Parent; |
| | 1 | 811 | | return serviceRoot?.FullName ?? AppContext.BaseDirectory; |
| | | 812 | | } |
| | | 813 | | |
| | | 814 | | /// <summary> |
| | | 815 | | /// Ensures Kestrun.dll from the selected module root is loaded into the default context. |
| | | 816 | | /// </summary> |
| | | 817 | | /// <param name="moduleManifestPath">Absolute path to Kestrun.psd1.</param> |
| | | 818 | | /// <param name="log">Best-effort service-host logger.</param> |
| | | 819 | | private static void EnsureKestrunAssemblyPreloaded(string moduleManifestPath, Action<string> log) |
| | 0 | 820 | | => RunnerRuntime.EnsureKestrunAssemblyPreloaded(moduleManifestPath, message => log($"warning: {message}")); |
| | | 821 | | |
| | | 822 | | /// <summary> |
| | | 823 | | /// Ensures PowerShell built-in modules are discoverable for embedded runspace execution. |
| | | 824 | | /// </summary> |
| | | 825 | | private static void EnsurePowerShellRuntimeHome() |
| | 0 | 826 | | => RunnerRuntime.EnsurePowerShellRuntimeHome(createFallbackDirectories: false); |
| | | 827 | | |
| | | 828 | | /// <summary> |
| | | 829 | | /// Verifies that the loaded Kestrun assembly contains the expected host manager type. |
| | | 830 | | /// </summary> |
| | | 831 | | /// <returns>True when the expected Kestrun host manager type is available.</returns> |
| | | 832 | | private static bool HasKestrunHostManagerType() |
| | 0 | 833 | | => RunnerRuntime.HasKestrunHostManagerType(); |
| | | 834 | | |
| | | 835 | | /// <summary> |
| | | 836 | | /// Requests a graceful stop for all running Kestrun hosts managed in the current process. |
| | | 837 | | /// </summary> |
| | | 838 | | /// <returns>A task representing the stop attempt.</returns> |
| | | 839 | | private static Task RequestManagedStopAsync() |
| | 1 | 840 | | => RunnerRuntime.RequestManagedStopAsync(); |
| | | 841 | | |
| | | 842 | | /// <summary> |
| | | 843 | | /// Writes PowerShell pipeline output to stdout and service log. |
| | | 844 | | /// </summary> |
| | | 845 | | /// <param name="output">Pipeline output collection.</param> |
| | | 846 | | /// <param name="log">Best-effort service-host logger.</param> |
| | | 847 | | private static void WriteOutput(IEnumerable<PSObject> output, Action<string> log) |
| | 0 | 848 | | => RunnerRuntime.DispatchPowerShellOutput( |
| | 0 | 849 | | output, |
| | 0 | 850 | | value => |
| | 0 | 851 | | { |
| | 0 | 852 | | Console.WriteLine(value); |
| | 0 | 853 | | log($"output: {value}"); |
| | 0 | 854 | | }, |
| | 0 | 855 | | skipWhitespace: true); |
| | | 856 | | |
| | | 857 | | /// <summary> |
| | | 858 | | /// Writes non-output streams in a console-friendly format. |
| | | 859 | | /// </summary> |
| | | 860 | | /// <param name="streams">PowerShell data streams.</param> |
| | | 861 | | /// <param name="log">Best-effort service-host logger.</param> |
| | | 862 | | private static void WriteStreams(PSDataStreams streams, Action<string> log) |
| | | 863 | | { |
| | 0 | 864 | | RunnerRuntime.DispatchPowerShellStreams( |
| | 0 | 865 | | streams, |
| | 0 | 866 | | onWarning: message => |
| | 0 | 867 | | { |
| | 0 | 868 | | Console.Error.WriteLine(message); |
| | 0 | 869 | | log($"warning: {message}"); |
| | 0 | 870 | | }, |
| | 0 | 871 | | onVerbose: message => |
| | 0 | 872 | | { |
| | 0 | 873 | | Console.WriteLine(message); |
| | 0 | 874 | | log($"verbose: {message}"); |
| | 0 | 875 | | }, |
| | 0 | 876 | | onDebug: message => |
| | 0 | 877 | | { |
| | 0 | 878 | | Console.WriteLine(message); |
| | 0 | 879 | | log($"debug: {message}"); |
| | 0 | 880 | | }, |
| | 0 | 881 | | onInformation: message => |
| | 0 | 882 | | { |
| | 0 | 883 | | Console.WriteLine(message); |
| | 0 | 884 | | log($"info: {message}"); |
| | 0 | 885 | | }, |
| | 0 | 886 | | onError: message => |
| | 0 | 887 | | { |
| | 0 | 888 | | Console.Error.WriteLine(message); |
| | 0 | 889 | | log($"error: {message}"); |
| | 0 | 890 | | }, |
| | 0 | 891 | | skipWhitespace: true); |
| | 0 | 892 | | } |
| | | 893 | | |
| | | 894 | | private static string ResolveBootstrapLogPath(string? configuredPath, string serviceName) |
| | 0 | 895 | | => RunnerRuntime.ResolveBootstrapLogPath(configuredPath, BuildDefaultServiceLogFileName(serviceName)); |
| | | 896 | | |
| | | 897 | | /// <summary> |
| | | 898 | | /// Builds a default service log file name using the configured service name. |
| | | 899 | | /// </summary> |
| | | 900 | | /// <param name="serviceName">Configured service name.</param> |
| | | 901 | | /// <returns>Service-specific log file name.</returns> |
| | | 902 | | private static string BuildDefaultServiceLogFileName(string serviceName) |
| | 0 | 903 | | => $"kestrun-tool-service-{SanitizeFileNameSegment(serviceName)}.log"; |
| | | 904 | | |
| | | 905 | | /// <summary> |
| | | 906 | | /// Converts arbitrary service names to a filesystem-safe filename segment. |
| | | 907 | | /// </summary> |
| | | 908 | | /// <param name="value">Raw value to sanitize.</param> |
| | | 909 | | /// <returns>Safe filename segment.</returns> |
| | | 910 | | private static string SanitizeFileNameSegment(string value) |
| | | 911 | | { |
| | 1 | 912 | | if (string.IsNullOrWhiteSpace(value)) |
| | | 913 | | { |
| | 0 | 914 | | return "default"; |
| | | 915 | | } |
| | | 916 | | |
| | 1 | 917 | | var invalidChars = Path.GetInvalidFileNameChars(); |
| | 1 | 918 | | var sanitized = new string([.. |
| | 1 | 919 | | value.Select(c => |
| | 12 | 920 | | c < 32 |
| | 12 | 921 | | || invalidChars.Contains(c) |
| | 12 | 922 | | || c is '<' or '>' or ':' or '"' or '/' or '\\' or '|' or '?' or '*' |
| | 12 | 923 | | ? '-' |
| | 12 | 924 | | : c)]) |
| | 1 | 925 | | .Trim(); |
| | 1 | 926 | | return string.IsNullOrWhiteSpace(sanitized) ? "default" : sanitized; |
| | | 927 | | } |
| | | 928 | | |
| | | 929 | | /// <summary> |
| | | 930 | | /// Formats script arguments for diagnostic logging. |
| | | 931 | | /// </summary> |
| | | 932 | | /// <param name="scriptArguments">Script argument values.</param> |
| | | 933 | | /// <returns>Comma-separated argument list with shell-safe quoting.</returns> |
| | | 934 | | private static string FormatScriptArguments(IReadOnlyList<string> scriptArguments) |
| | 3 | 935 | | => scriptArguments.Count == 0 |
| | 3 | 936 | | ? "" |
| | 3 | 937 | | : string.Join(", ", |
| | 3 | 938 | | scriptArguments.Select(static arg => |
| | 7 | 939 | | string.IsNullOrEmpty(arg) |
| | 7 | 940 | | ? "\"\"" |
| | 7 | 941 | | : arg.Contains(' ') ? $"\"{arg}\"" : arg)); |
| | | 942 | | } |