| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Management.Automation; |
| | | 3 | | using System.Reflection; |
| | | 4 | | using System.Runtime.InteropServices; |
| | | 5 | | using System.Runtime.Loader; |
| | | 6 | | |
| | | 7 | | namespace Kestrun.Runner; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Provides shared runtime and process helpers for Kestrun script runner hosts. |
| | | 11 | | /// </summary> |
| | | 12 | | public static class RunnerRuntime |
| | | 13 | | { |
| | 1 | 14 | | private static readonly Lock AssemblyLoadSync = new(); |
| | | 15 | | private static string? s_kestrunModuleLibPath; |
| | | 16 | | private static bool s_dependencyResolverRegistered; |
| | 8 | 17 | | private sealed record KestrunAssemblyLoadInfo(string ModuleLibPath, string ExpectedAssemblyPath, Version? ExpectedVe |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Ensures the runner is executing on .NET 10. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="productName">Product name used in the exception message.</param> |
| | | 23 | | public static void EnsureNet10Runtime(string productName) |
| | | 24 | | { |
| | 1 | 25 | | var framework = RuntimeInformation.FrameworkDescription; |
| | 1 | 26 | | var runtimeVersion = Environment.Version; |
| | 1 | 27 | | if (runtimeVersion.Major < 10) |
| | | 28 | | { |
| | 0 | 29 | | throw new RuntimeException( |
| | 0 | 30 | | $"{productName} requires .NET 10 runtime (Environment.Version.Major >= 10). Current runtime: {framework} |
| | | 31 | | } |
| | 1 | 32 | | } |
| | | 33 | | |
| | | 34 | | /// <summary> |
| | | 35 | | /// Ensures Kestrun.dll from the selected module root is loaded into the default context. |
| | | 36 | | /// </summary> |
| | | 37 | | /// <param name="moduleManifestPath">Absolute path to Kestrun.psd1.</param> |
| | | 38 | | /// <param name="onWarning">Optional warning callback for non-fatal assembly preload conditions.</param> |
| | | 39 | | public static void EnsureKestrunAssemblyPreloaded(string moduleManifestPath, Action<string>? onWarning = null) |
| | | 40 | | { |
| | 2 | 41 | | var expected = ResolveExpectedKestrunAssemblyLoadInfo(moduleManifestPath); |
| | | 42 | | lock (AssemblyLoadSync) |
| | | 43 | | { |
| | 2 | 44 | | EnsureDependencyResolverRegistered(); |
| | | 45 | | |
| | 2 | 46 | | var alreadyLoaded = GetLoadedKestrunAssembly(); |
| | 2 | 47 | | if (alreadyLoaded is not null && TryHandleAlreadyLoadedKestrunAssembly(alreadyLoaded, expected, onWarning)) |
| | | 48 | | { |
| | 2 | 49 | | return; |
| | | 50 | | } |
| | | 51 | | |
| | 0 | 52 | | s_kestrunModuleLibPath = expected.ModuleLibPath; |
| | 0 | 53 | | _ = AssemblyLoadContext.Default.LoadFromAssemblyPath(expected.ExpectedAssemblyPath); |
| | 0 | 54 | | } |
| | 2 | 55 | | } |
| | | 56 | | |
| | | 57 | | /// <summary> |
| | | 58 | | /// Resolves and validates the expected Kestrun assembly load information from a module manifest path. |
| | | 59 | | /// </summary> |
| | | 60 | | /// <param name="moduleManifestPath">Absolute path to Kestrun.psd1.</param> |
| | | 61 | | /// <returns>Resolved Kestrun assembly load information.</returns> |
| | | 62 | | private static KestrunAssemblyLoadInfo ResolveExpectedKestrunAssemblyLoadInfo(string moduleManifestPath) |
| | | 63 | | { |
| | 2 | 64 | | var manifestDirectory = Path.GetDirectoryName(moduleManifestPath); |
| | 2 | 65 | | if (string.IsNullOrWhiteSpace(manifestDirectory)) |
| | | 66 | | { |
| | 0 | 67 | | throw new RuntimeException($"Unable to resolve manifest directory from: {moduleManifestPath}"); |
| | | 68 | | } |
| | | 69 | | |
| | 2 | 70 | | var moduleLibPath = Path.Combine(manifestDirectory, "lib", "net10.0"); |
| | 2 | 71 | | var expectedAssemblyPath = Path.Combine(moduleLibPath, "Kestrun.dll"); |
| | 2 | 72 | | if (!File.Exists(expectedAssemblyPath)) |
| | | 73 | | { |
| | 0 | 74 | | throw new RuntimeException($"Kestrun assembly not found at expected path: {expectedAssemblyPath}"); |
| | | 75 | | } |
| | | 76 | | |
| | 2 | 77 | | var expectedFullPath = Path.GetFullPath(expectedAssemblyPath); |
| | 2 | 78 | | var expectedAssemblyName = AssemblyName.GetAssemblyName(expectedFullPath); |
| | 2 | 79 | | return new KestrunAssemblyLoadInfo(moduleLibPath, expectedFullPath, expectedAssemblyName.Version); |
| | | 80 | | } |
| | | 81 | | |
| | | 82 | | /// <summary> |
| | | 83 | | /// Registers the dependency resolver for assemblies loaded from the selected Kestrun module folder. |
| | | 84 | | /// </summary> |
| | | 85 | | private static void EnsureDependencyResolverRegistered() |
| | | 86 | | { |
| | 2 | 87 | | if (s_dependencyResolverRegistered) |
| | | 88 | | { |
| | 1 | 89 | | return; |
| | | 90 | | } |
| | | 91 | | |
| | 1 | 92 | | AssemblyLoadContext.Default.Resolving += ResolveKestrunModuleDependency; |
| | 1 | 93 | | s_dependencyResolverRegistered = true; |
| | 1 | 94 | | } |
| | | 95 | | |
| | | 96 | | /// <summary> |
| | | 97 | | /// Returns the already-loaded Kestrun assembly from the current application domain when available. |
| | | 98 | | /// </summary> |
| | | 99 | | /// <returns>The loaded Kestrun assembly when present; otherwise null.</returns> |
| | | 100 | | private static Assembly? GetLoadedKestrunAssembly() |
| | 2 | 101 | | => AppDomain.CurrentDomain.GetAssemblies() |
| | 70 | 102 | | .FirstOrDefault(a => string.Equals(a.GetName().Name, "Kestrun", StringComparison.Ordinal)); |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Validates an already-loaded Kestrun assembly against the expected module assembly and handles compatibility warn |
| | | 106 | | /// </summary> |
| | | 107 | | /// <param name="loadedAssembly">Already-loaded Kestrun assembly.</param> |
| | | 108 | | /// <param name="expected">Expected Kestrun assembly load information.</param> |
| | | 109 | | /// <param name="onWarning">Optional warning callback for compatible preloaded assemblies from a different path.</pa |
| | | 110 | | /// <returns>True when startup should continue without loading another assembly; otherwise false.</returns> |
| | | 111 | | private static bool TryHandleAlreadyLoadedKestrunAssembly( |
| | | 112 | | Assembly loadedAssembly, |
| | | 113 | | KestrunAssemblyLoadInfo expected, |
| | | 114 | | Action<string>? onWarning) |
| | | 115 | | { |
| | 2 | 116 | | var loadedPath = GetNormalizedAssemblyLocation(loadedAssembly); |
| | 2 | 117 | | if (string.Equals(loadedPath, expected.ExpectedAssemblyPath, StringComparison.OrdinalIgnoreCase)) |
| | | 118 | | { |
| | 0 | 119 | | return true; |
| | | 120 | | } |
| | | 121 | | |
| | 2 | 122 | | var loadedVersion = loadedAssembly.GetName().Version; |
| | 2 | 123 | | if (!IsKestrunAssemblyVersionCompatible(loadedVersion, expected.ExpectedVersion)) |
| | | 124 | | { |
| | 0 | 125 | | throw new RuntimeException( |
| | 0 | 126 | | "Kestrun assembly was already loaded from a different location with an incompatible version. " |
| | 0 | 127 | | + $"Loaded version: {FormatVersionForDiagnostics(loadedVersion)}; " |
| | 0 | 128 | | + $"expected version: {FormatVersionForDiagnostics(expected.ExpectedVersion)}."); |
| | | 129 | | } |
| | | 130 | | |
| | 2 | 131 | | onWarning?.Invoke( |
| | 2 | 132 | | $"Kestrun assembly was already loaded from a different location; continuing with loaded assembly version " |
| | 2 | 133 | | + $"'{FormatVersionForDiagnostics(loadedVersion)}' " |
| | 2 | 134 | | + $"(expected '{FormatVersionForDiagnostics(expected.ExpectedVersion)}'). " |
| | 2 | 135 | | + $"Loaded path: '{loadedPath}'. Expected path: '{expected.ExpectedAssemblyPath}'."); |
| | 2 | 136 | | return true; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | /// <summary> |
| | | 140 | | /// Returns a normalized assembly location path suitable for diagnostics and comparisons. |
| | | 141 | | /// </summary> |
| | | 142 | | /// <param name="assembly">Assembly to inspect.</param> |
| | | 143 | | /// <returns>Full path when available; otherwise an empty string.</returns> |
| | | 144 | | private static string GetNormalizedAssemblyLocation(Assembly assembly) |
| | 2 | 145 | | => string.IsNullOrWhiteSpace(assembly.Location) |
| | 2 | 146 | | ? string.Empty |
| | 2 | 147 | | : Path.GetFullPath(assembly.Location); |
| | | 148 | | |
| | | 149 | | /// <summary> |
| | | 150 | | /// Formats assembly versions for diagnostics and warning messages. |
| | | 151 | | /// </summary> |
| | | 152 | | /// <param name="version">Version value to format.</param> |
| | | 153 | | /// <returns>Formatted version text, or <c>unknown</c> when version is unavailable.</returns> |
| | | 154 | | private static string FormatVersionForDiagnostics(Version? version) |
| | 3 | 155 | | => version is null ? "unknown" : version.ToString(); |
| | | 156 | | |
| | | 157 | | /// <summary> |
| | | 158 | | /// Determines whether an already-loaded Kestrun assembly version is compatible with the expected module version. |
| | | 159 | | /// </summary> |
| | | 160 | | /// <param name="loadedVersion">Version of the assembly already loaded in the process.</param> |
| | | 161 | | /// <param name="expectedVersion">Version of the assembly selected from the module path.</param> |
| | | 162 | | /// <returns>True when versions are considered compatible for startup continuation; otherwise false.</returns> |
| | | 163 | | private static bool IsKestrunAssemblyVersionCompatible(Version? loadedVersion, Version? expectedVersion) |
| | | 164 | | { |
| | 7 | 165 | | if (loadedVersion is null || expectedVersion is null) |
| | | 166 | | { |
| | 2 | 167 | | return false; |
| | | 168 | | } |
| | | 169 | | |
| | 5 | 170 | | if (loadedVersion.Major != expectedVersion.Major || loadedVersion.Minor != expectedVersion.Minor) |
| | | 171 | | { |
| | 1 | 172 | | return false; |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | static int NormalizeBuild(int value) |
| | | 176 | | { |
| | 8 | 177 | | return value < 0 ? 0 : value; |
| | | 178 | | } |
| | | 179 | | |
| | 4 | 180 | | var loadedBuild = NormalizeBuild(loadedVersion.Build); |
| | 4 | 181 | | var expectedBuild = NormalizeBuild(expectedVersion.Build); |
| | 4 | 182 | | return loadedBuild >= expectedBuild; |
| | | 183 | | } |
| | | 184 | | |
| | | 185 | | /// <summary> |
| | | 186 | | /// Ensures PowerShell built-in modules are discoverable for embedded runspace execution. |
| | | 187 | | /// </summary> |
| | | 188 | | /// <param name="createFallbackDirectories">When true, creates a writable fallback PSHOME and module folder if no in |
| | | 189 | | public static void EnsurePowerShellRuntimeHome(bool createFallbackDirectories) |
| | | 190 | | { |
| | 0 | 191 | | var currentPsHome = Environment.GetEnvironmentVariable("PSHOME"); |
| | 0 | 192 | | var existingPsHome = HasPowerShellManagementModule(currentPsHome) |
| | 0 | 193 | | ? currentPsHome |
| | 0 | 194 | | : null; |
| | 0 | 195 | | if (existingPsHome is not null) |
| | | 196 | | { |
| | 0 | 197 | | EnsurePsModulePathContains(Path.Combine(existingPsHome, "Modules")); |
| | 0 | 198 | | return; |
| | | 199 | | } |
| | | 200 | | |
| | 0 | 201 | | foreach (var candidate in EnumeratePowerShellHomeCandidates()) |
| | | 202 | | { |
| | 0 | 203 | | if (!HasPowerShellManagementModule(candidate)) |
| | | 204 | | { |
| | | 205 | | continue; |
| | | 206 | | } |
| | | 207 | | |
| | 0 | 208 | | Environment.SetEnvironmentVariable("PSHOME", candidate); |
| | 0 | 209 | | EnsurePsModulePathContains(Path.Combine(candidate, "Modules")); |
| | 0 | 210 | | return; |
| | | 211 | | } |
| | | 212 | | |
| | 0 | 213 | | if (!createFallbackDirectories) |
| | | 214 | | { |
| | 0 | 215 | | return; |
| | | 216 | | } |
| | | 217 | | |
| | 0 | 218 | | var fallbackPsHome = GetFallbackPowerShellHomePath(); |
| | 0 | 219 | | TryEnsureDirectory(fallbackPsHome); |
| | | 220 | | |
| | 0 | 221 | | var modulesPath = Path.Combine(fallbackPsHome, "Modules"); |
| | 0 | 222 | | TryEnsureDirectory(modulesPath); |
| | | 223 | | |
| | 0 | 224 | | Environment.SetEnvironmentVariable("PSHOME", fallbackPsHome); |
| | 0 | 225 | | EnsurePsModulePathContains(modulesPath); |
| | 0 | 226 | | } |
| | | 227 | | |
| | | 228 | | /// <summary> |
| | | 229 | | /// Verifies that the loaded Kestrun assembly contains the expected host manager type. |
| | | 230 | | /// </summary> |
| | | 231 | | /// <returns>True when the expected Kestrun host manager type is available.</returns> |
| | | 232 | | public static bool HasKestrunHostManagerType() |
| | | 233 | | { |
| | 0 | 234 | | var kestrunAssembly = AppDomain.CurrentDomain |
| | 0 | 235 | | .GetAssemblies() |
| | 0 | 236 | | .FirstOrDefault(a => string.Equals(a.GetName().Name, "Kestrun", StringComparison.Ordinal)); |
| | | 237 | | |
| | 0 | 238 | | return kestrunAssembly?.GetType("Kestrun.KestrunHostManager", throwOnError: false, ignoreCase: false) is not nul |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | /// <summary> |
| | | 242 | | /// Requests a graceful stop for all running Kestrun hosts managed in the current process. |
| | | 243 | | /// </summary> |
| | | 244 | | /// <returns>A task representing the stop attempt.</returns> |
| | | 245 | | public static async Task RequestManagedStopAsync() |
| | | 246 | | { |
| | 1 | 247 | | var hostManagerType = ResolveKestrunHostManagerType(); |
| | 1 | 248 | | if (hostManagerType is null) |
| | | 249 | | { |
| | 1 | 250 | | return; |
| | | 251 | | } |
| | | 252 | | |
| | | 253 | | try |
| | | 254 | | { |
| | 0 | 255 | | var stopAllAsyncMethod = hostManagerType.GetMethod( |
| | 0 | 256 | | "StopAllAsync", |
| | 0 | 257 | | BindingFlags.Public | BindingFlags.Static, |
| | 0 | 258 | | binder: null, |
| | 0 | 259 | | types: [typeof(CancellationToken)], |
| | 0 | 260 | | modifiers: null); |
| | 0 | 261 | | if (stopAllAsyncMethod is not null) |
| | | 262 | | { |
| | 0 | 263 | | if (stopAllAsyncMethod.Invoke(null, [CancellationToken.None]) is Task stopTask) |
| | | 264 | | { |
| | 0 | 265 | | await stopTask.ConfigureAwait(false); |
| | | 266 | | } |
| | | 267 | | } |
| | | 268 | | |
| | 0 | 269 | | var destroyAllMethod = hostManagerType.GetMethod("DestroyAll", BindingFlags.Public | BindingFlags.Static); |
| | 0 | 270 | | _ = destroyAllMethod?.Invoke(null, null); |
| | 0 | 271 | | } |
| | 0 | 272 | | catch |
| | | 273 | | { |
| | | 274 | | // Best-effort shutdown: ignore reflection/host state errors. |
| | 0 | 275 | | } |
| | 1 | 276 | | } |
| | | 277 | | |
| | | 278 | | /// <summary> |
| | | 279 | | /// Resolves the Kestrun host manager type from the current process. |
| | | 280 | | /// </summary> |
| | | 281 | | /// <returns>The host manager type when available; otherwise null.</returns> |
| | | 282 | | private static Type? ResolveKestrunHostManagerType() |
| | | 283 | | { |
| | 1 | 284 | | var hostManagerType = Type.GetType("Kestrun.KestrunHostManager, Kestrun", throwOnError: false, ignoreCase: false |
| | 1 | 285 | | if (hostManagerType is not null) |
| | | 286 | | { |
| | 0 | 287 | | return hostManagerType; |
| | | 288 | | } |
| | | 289 | | |
| | | 290 | | // Fallback: inspect loaded assemblies in case the simple assembly-qualified lookup misses. |
| | 1 | 291 | | return AppDomain.CurrentDomain |
| | 1 | 292 | | .GetAssemblies() |
| | 38 | 293 | | .Select(static assembly => assembly.GetType("Kestrun.KestrunHostManager", throwOnError: false, ignoreCase: f |
| | 39 | 294 | | .FirstOrDefault(static type => type is not null); |
| | | 295 | | } |
| | | 296 | | |
| | | 297 | | /// <summary> |
| | | 298 | | /// Resolves a bootstrap log path from an optional configured path and default file name. |
| | | 299 | | /// </summary> |
| | | 300 | | /// <param name="configuredPath">Configured file or directory path.</param> |
| | | 301 | | /// <param name="defaultFileName">Default log file name when no path is configured.</param> |
| | | 302 | | /// <returns>Resolved absolute log file path.</returns> |
| | | 303 | | public static string ResolveBootstrapLogPath(string? configuredPath, string defaultFileName) |
| | | 304 | | { |
| | 9 | 305 | | var defaultDirectory = GetDefaultBootstrapLogDirectory(); |
| | 9 | 306 | | var defaultPath = Path.Combine(defaultDirectory, defaultFileName); |
| | | 307 | | |
| | 9 | 308 | | if (string.IsNullOrWhiteSpace(configuredPath)) |
| | | 309 | | { |
| | 7 | 310 | | return defaultPath; |
| | | 311 | | } |
| | | 312 | | |
| | 2 | 313 | | var fullPath = Path.GetFullPath(configuredPath); |
| | 2 | 314 | | return Directory.Exists(fullPath) |
| | 2 | 315 | | ? Path.Combine(fullPath, defaultFileName) |
| | 2 | 316 | | : fullPath; |
| | | 317 | | } |
| | | 318 | | |
| | | 319 | | /// <summary> |
| | | 320 | | /// Returns the default bootstrap log directory for the current platform. |
| | | 321 | | /// </summary> |
| | | 322 | | /// <returns>Writable preferred log directory path.</returns> |
| | | 323 | | private static string GetDefaultBootstrapLogDirectory() |
| | | 324 | | { |
| | 9 | 325 | | if (OperatingSystem.IsWindows()) |
| | | 326 | | { |
| | 0 | 327 | | return Path.Combine( |
| | 0 | 328 | | Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), |
| | 0 | 329 | | "Kestrun", |
| | 0 | 330 | | "logs"); |
| | | 331 | | } |
| | | 332 | | |
| | 9 | 333 | | if (OperatingSystem.IsLinux()) |
| | | 334 | | { |
| | 9 | 335 | | var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| | 9 | 336 | | return Path.Combine(userProfile, ".local", "share", "kestrun", "logs"); |
| | | 337 | | } |
| | | 338 | | |
| | 0 | 339 | | if (OperatingSystem.IsMacOS()) |
| | | 340 | | { |
| | 0 | 341 | | var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| | 0 | 342 | | return Path.Combine(userProfile, "Library", "Application Support", "Kestrun", "logs"); |
| | | 343 | | } |
| | | 344 | | |
| | 0 | 345 | | return Path.Combine( |
| | 0 | 346 | | Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), |
| | 0 | 347 | | "Kestrun", |
| | 0 | 348 | | "logs"); |
| | | 349 | | } |
| | | 350 | | |
| | | 351 | | /// <summary> |
| | | 352 | | /// Dispatches non-empty PowerShell pipeline output text to a caller-provided sink. |
| | | 353 | | /// </summary> |
| | | 354 | | /// <param name="output">PowerShell pipeline output collection.</param> |
| | | 355 | | /// <param name="onOutput">Callback invoked for each selected output line.</param> |
| | | 356 | | /// <param name="skipWhitespace">When true, whitespace-only values are ignored.</param> |
| | | 357 | | public static void DispatchPowerShellOutput(IEnumerable<PSObject> output, Action<string> onOutput, bool skipWhitespa |
| | | 358 | | { |
| | 1 | 359 | | ArgumentNullException.ThrowIfNull(output); |
| | 1 | 360 | | ArgumentNullException.ThrowIfNull(onOutput); |
| | | 361 | | |
| | 8 | 362 | | foreach (var item in output) |
| | | 363 | | { |
| | 3 | 364 | | if (item is null) |
| | | 365 | | { |
| | | 366 | | continue; |
| | | 367 | | } |
| | | 368 | | |
| | 2 | 369 | | var value = item.BaseObject?.ToString() ?? item.ToString(); |
| | 2 | 370 | | if (skipWhitespace && string.IsNullOrWhiteSpace(value)) |
| | | 371 | | { |
| | | 372 | | continue; |
| | | 373 | | } |
| | | 374 | | |
| | 1 | 375 | | onOutput(value ?? string.Empty); |
| | | 376 | | } |
| | 1 | 377 | | } |
| | | 378 | | |
| | | 379 | | /// <summary> |
| | | 380 | | /// Dispatches PowerShell non-output streams to caller-provided handlers. |
| | | 381 | | /// </summary> |
| | | 382 | | /// <param name="streams">PowerShell data streams.</param> |
| | | 383 | | /// <param name="onWarning">Optional warning message handler.</param> |
| | | 384 | | /// <param name="onVerbose">Optional verbose message handler.</param> |
| | | 385 | | /// <param name="onDebug">Optional debug message handler.</param> |
| | | 386 | | /// <param name="onInformation">Optional information message handler.</param> |
| | | 387 | | /// <param name="onError">Optional error message handler.</param> |
| | | 388 | | /// <param name="skipWhitespace">When true, whitespace-only values are ignored.</param> |
| | | 389 | | public static void DispatchPowerShellStreams( |
| | | 390 | | PSDataStreams streams, |
| | | 391 | | Action<string>? onWarning, |
| | | 392 | | Action<string>? onVerbose, |
| | | 393 | | Action<string>? onDebug, |
| | | 394 | | Action<string>? onInformation, |
| | | 395 | | Action<string>? onError, |
| | | 396 | | bool skipWhitespace) |
| | | 397 | | { |
| | 1 | 398 | | ArgumentNullException.ThrowIfNull(streams); |
| | | 399 | | |
| | 2 | 400 | | DispatchMessages(streams.Warning, static record => record.Message, onWarning, skipWhitespace); |
| | 2 | 401 | | DispatchMessages(streams.Verbose, static record => record.Message, onVerbose, skipWhitespace); |
| | 2 | 402 | | DispatchMessages(streams.Debug, static record => record.Message, onDebug, skipWhitespace); |
| | 2 | 403 | | DispatchMessages(streams.Information, static record => record.MessageData?.ToString() ?? record.ToString(), onIn |
| | 2 | 404 | | DispatchMessages(streams.Error, static record => record.ToString(), onError, skipWhitespace); |
| | 1 | 405 | | } |
| | | 406 | | |
| | | 407 | | /// <summary> |
| | | 408 | | /// Resolves Kestrun module dependencies from the selected module lib folder. |
| | | 409 | | /// </summary> |
| | | 410 | | /// <param name="context">Assembly load context that requested the assembly.</param> |
| | | 411 | | /// <param name="assemblyName">Requested assembly identity.</param> |
| | | 412 | | /// <returns>Loaded assembly when available; otherwise null.</returns> |
| | | 413 | | private static Assembly? ResolveKestrunModuleDependency(AssemblyLoadContext context, AssemblyName assemblyName) |
| | | 414 | | { |
| | 0 | 415 | | if (string.IsNullOrWhiteSpace(assemblyName.Name)) |
| | | 416 | | { |
| | 0 | 417 | | return null; |
| | | 418 | | } |
| | | 419 | | |
| | 0 | 420 | | var moduleLibPath = s_kestrunModuleLibPath; |
| | 0 | 421 | | if (string.IsNullOrWhiteSpace(moduleLibPath)) |
| | | 422 | | { |
| | 0 | 423 | | return null; |
| | | 424 | | } |
| | | 425 | | |
| | 0 | 426 | | var candidatePath = Path.Combine(moduleLibPath, $"{assemblyName.Name}.dll"); |
| | 0 | 427 | | if (!File.Exists(candidatePath)) |
| | | 428 | | { |
| | 0 | 429 | | return null; |
| | | 430 | | } |
| | | 431 | | |
| | | 432 | | try |
| | | 433 | | { |
| | 0 | 434 | | return context.LoadFromAssemblyPath(Path.GetFullPath(candidatePath)); |
| | | 435 | | } |
| | 0 | 436 | | catch |
| | | 437 | | { |
| | 0 | 438 | | return null; |
| | | 439 | | } |
| | 0 | 440 | | } |
| | | 441 | | |
| | | 442 | | /// <summary> |
| | | 443 | | /// Dispatches formatted stream records through an optional callback. |
| | | 444 | | /// </summary> |
| | | 445 | | /// <typeparam name="TRecord">PowerShell stream record type.</typeparam> |
| | | 446 | | /// <param name="records">Record sequence.</param> |
| | | 447 | | /// <param name="formatter">Record-to-message formatter.</param> |
| | | 448 | | /// <param name="callback">Optional callback invoked for each message.</param> |
| | | 449 | | /// <param name="skipWhitespace">When true, whitespace-only values are ignored.</param> |
| | | 450 | | private static void DispatchMessages<TRecord>( |
| | | 451 | | IEnumerable<TRecord> records, |
| | | 452 | | Func<TRecord, string?> formatter, |
| | | 453 | | Action<string>? callback, |
| | | 454 | | bool skipWhitespace) |
| | | 455 | | { |
| | 5 | 456 | | if (callback is null) |
| | | 457 | | { |
| | 0 | 458 | | return; |
| | | 459 | | } |
| | | 460 | | |
| | 20 | 461 | | foreach (var record in records) |
| | | 462 | | { |
| | 5 | 463 | | var message = formatter(record); |
| | 5 | 464 | | if (skipWhitespace && string.IsNullOrWhiteSpace(message)) |
| | | 465 | | { |
| | | 466 | | continue; |
| | | 467 | | } |
| | | 468 | | |
| | 5 | 469 | | callback(message ?? string.Empty); |
| | | 470 | | } |
| | 5 | 471 | | } |
| | | 472 | | |
| | | 473 | | /// <summary> |
| | | 474 | | /// Ensures a module path exists in PSModulePath. |
| | | 475 | | /// </summary> |
| | | 476 | | /// <param name="path">Path to include.</param> |
| | | 477 | | private static void EnsurePsModulePathContains(string path) |
| | | 478 | | { |
| | 2 | 479 | | if (!Directory.Exists(path)) |
| | | 480 | | { |
| | 0 | 481 | | return; |
| | | 482 | | } |
| | | 483 | | |
| | 2 | 484 | | var modulePath = Environment.GetEnvironmentVariable("PSModulePath") ?? string.Empty; |
| | 2 | 485 | | var entries = modulePath.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.Tr |
| | 2 | 486 | | if (entries.Contains(path, StringComparer.OrdinalIgnoreCase)) |
| | | 487 | | { |
| | 1 | 488 | | return; |
| | | 489 | | } |
| | | 490 | | |
| | 1 | 491 | | var updated = string.IsNullOrWhiteSpace(modulePath) |
| | 1 | 492 | | ? path |
| | 1 | 493 | | : string.Join(Path.PathSeparator, new[] { path }.Concat(entries)); |
| | 1 | 494 | | Environment.SetEnvironmentVariable("PSModulePath", updated); |
| | 1 | 495 | | } |
| | | 496 | | |
| | | 497 | | /// <summary> |
| | | 498 | | /// Determines whether a path contains the built-in Microsoft.PowerShell.Management module. |
| | | 499 | | /// </summary> |
| | | 500 | | /// <param name="psHome">PowerShell home candidate.</param> |
| | | 501 | | /// <returns>True when the module path exists.</returns> |
| | | 502 | | private static bool HasPowerShellManagementModule(string? psHome) |
| | | 503 | | { |
| | 4 | 504 | | if (string.IsNullOrWhiteSpace(psHome)) |
| | | 505 | | { |
| | 0 | 506 | | return false; |
| | | 507 | | } |
| | | 508 | | |
| | 4 | 509 | | var moduleDirectory = Path.Combine(psHome, "Modules", "Microsoft.PowerShell.Management"); |
| | 4 | 510 | | if (!Directory.Exists(moduleDirectory)) |
| | | 511 | | { |
| | 1 | 512 | | return false; |
| | | 513 | | } |
| | | 514 | | |
| | 3 | 515 | | var manifestPath = Path.Combine(moduleDirectory, "Microsoft.PowerShell.Management.psd1"); |
| | 3 | 516 | | if (!File.Exists(manifestPath)) |
| | | 517 | | { |
| | 0 | 518 | | return false; |
| | | 519 | | } |
| | | 520 | | |
| | | 521 | | try |
| | | 522 | | { |
| | 3 | 523 | | var manifestText = File.ReadAllText(manifestPath); |
| | 3 | 524 | | return manifestText.Contains("CompatiblePSEditions", StringComparison.Ordinal) |
| | 3 | 525 | | && manifestText.Contains("Core", StringComparison.OrdinalIgnoreCase); |
| | | 526 | | } |
| | 0 | 527 | | catch |
| | | 528 | | { |
| | 0 | 529 | | return false; |
| | | 530 | | } |
| | 3 | 531 | | } |
| | | 532 | | |
| | | 533 | | /// <summary> |
| | | 534 | | /// Enumerates likely PowerShell installation roots. |
| | | 535 | | /// </summary> |
| | | 536 | | /// <returns>Distinct absolute PowerShell home candidates.</returns> |
| | | 537 | | private static IEnumerable<string> EnumeratePowerShellHomeCandidates() |
| | | 538 | | { |
| | 0 | 539 | | var candidates = new List<string>(); |
| | | 540 | | |
| | 0 | 541 | | var envPsHome = Environment.GetEnvironmentVariable("PSHOME"); |
| | 0 | 542 | | if (!string.IsNullOrWhiteSpace(envPsHome)) |
| | | 543 | | { |
| | 0 | 544 | | candidates.Add(Path.GetFullPath(envPsHome)); |
| | | 545 | | } |
| | | 546 | | |
| | 0 | 547 | | if (OperatingSystem.IsWindows()) |
| | | 548 | | { |
| | 0 | 549 | | var programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); |
| | 0 | 550 | | if (!string.IsNullOrWhiteSpace(programFiles)) |
| | | 551 | | { |
| | 0 | 552 | | candidates.Add(Path.Combine(programFiles, "PowerShell", "7")); |
| | 0 | 553 | | candidates.Add(Path.Combine(programFiles, "PowerShell", "7-preview")); |
| | | 554 | | } |
| | | 555 | | |
| | 0 | 556 | | var whereResult = RunProcessCapture("where.exe", ["pwsh"]); |
| | 0 | 557 | | if (whereResult.ExitCode == 0) |
| | | 558 | | { |
| | 0 | 559 | | var discovered = whereResult.Output |
| | 0 | 560 | | .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) |
| | 0 | 561 | | .Select(Path.GetDirectoryName) |
| | 0 | 562 | | .Where(static p => !string.IsNullOrWhiteSpace(p)) |
| | 0 | 563 | | .Select(static p => Path.GetFullPath(p!)); |
| | 0 | 564 | | candidates.AddRange(discovered); |
| | | 565 | | } |
| | | 566 | | } |
| | | 567 | | else |
| | | 568 | | { |
| | 0 | 569 | | candidates.Add("/opt/microsoft/powershell/7"); |
| | | 570 | | |
| | 0 | 571 | | var whichResult = RunProcessCapture("which", ["pwsh"]); |
| | 0 | 572 | | if (whichResult.ExitCode == 0) |
| | | 573 | | { |
| | 0 | 574 | | var discovered = whichResult.Output |
| | 0 | 575 | | .Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); |
| | 0 | 576 | | candidates.AddRange(discovered); |
| | | 577 | | } |
| | | 578 | | } |
| | | 579 | | |
| | 0 | 580 | | candidates = [ |
| | 0 | 581 | | .. candidates |
| | 0 | 582 | | .Select(NormalizePowerShellHomeCandidate) |
| | 0 | 583 | | .Where(static path => !string.IsNullOrWhiteSpace(path)) |
| | 0 | 584 | | ]; |
| | | 585 | | |
| | 0 | 586 | | return candidates |
| | 0 | 587 | | .Where(Directory.Exists) |
| | 0 | 588 | | .Distinct(StringComparer.OrdinalIgnoreCase); |
| | | 589 | | } |
| | | 590 | | |
| | | 591 | | /// <summary> |
| | | 592 | | /// Normalizes a PowerShell home candidate, resolving executable symlinks to their installation directory. |
| | | 593 | | /// </summary> |
| | | 594 | | /// <param name="path">Candidate path (directory or pwsh executable path).</param> |
| | | 595 | | /// <returns>Normalized directory path when possible; otherwise an empty string.</returns> |
| | | 596 | | private static string NormalizePowerShellHomeCandidate(string path) |
| | | 597 | | { |
| | 4 | 598 | | if (string.IsNullOrWhiteSpace(path)) |
| | | 599 | | { |
| | 1 | 600 | | return string.Empty; |
| | | 601 | | } |
| | | 602 | | |
| | 3 | 603 | | var trimmedPath = path.Trim(); |
| | 3 | 604 | | var fullPath = Path.GetFullPath(trimmedPath); |
| | | 605 | | |
| | 3 | 606 | | if (!IsPowerShellExecutablePath(fullPath)) |
| | | 607 | | { |
| | 1 | 608 | | return fullPath; |
| | | 609 | | } |
| | | 610 | | |
| | 2 | 611 | | if (!File.Exists(fullPath)) |
| | | 612 | | { |
| | 0 | 613 | | return string.Empty; |
| | | 614 | | } |
| | | 615 | | |
| | 2 | 616 | | var executableCandidates = new List<string> { fullPath }; |
| | 2 | 617 | | var resolvedPath = TryResolveFinalPath(fullPath); |
| | 2 | 618 | | if (!string.IsNullOrWhiteSpace(resolvedPath) |
| | 2 | 619 | | && !string.Equals(resolvedPath, fullPath, StringComparison.OrdinalIgnoreCase)) |
| | | 620 | | { |
| | 0 | 621 | | executableCandidates.Insert(0, resolvedPath); |
| | | 622 | | } |
| | | 623 | | |
| | 7 | 624 | | foreach (var executablePath in executableCandidates) |
| | | 625 | | { |
| | 2 | 626 | | var candidateHome = Path.GetDirectoryName(executablePath); |
| | 2 | 627 | | if (string.IsNullOrWhiteSpace(candidateHome)) |
| | | 628 | | { |
| | | 629 | | continue; |
| | | 630 | | } |
| | | 631 | | |
| | 2 | 632 | | var normalizedHome = Path.GetFullPath(candidateHome); |
| | 2 | 633 | | if (HasPowerShellManagementModule(normalizedHome)) |
| | | 634 | | { |
| | 1 | 635 | | return normalizedHome; |
| | | 636 | | } |
| | | 637 | | } |
| | | 638 | | |
| | 1 | 639 | | return string.Empty; |
| | 1 | 640 | | } |
| | | 641 | | |
| | | 642 | | /// <summary> |
| | | 643 | | /// Determines whether a path points to the pwsh executable. |
| | | 644 | | /// </summary> |
| | | 645 | | /// <param name="path">Path to evaluate.</param> |
| | | 646 | | /// <returns>True when the file name is pwsh or pwsh.exe.</returns> |
| | | 647 | | private static bool IsPowerShellExecutablePath(string path) |
| | | 648 | | { |
| | 6 | 649 | | if (string.IsNullOrWhiteSpace(path)) |
| | | 650 | | { |
| | 0 | 651 | | return false; |
| | | 652 | | } |
| | | 653 | | |
| | 6 | 654 | | var trimmedPath = path.TrimEnd('/', '\\'); |
| | 6 | 655 | | var separatorIndex = trimmedPath.LastIndexOfAny(['/', '\\']); |
| | 6 | 656 | | var fileName = separatorIndex >= 0 |
| | 6 | 657 | | ? trimmedPath[(separatorIndex + 1)..] |
| | 6 | 658 | | : trimmedPath; |
| | | 659 | | |
| | 6 | 660 | | return string.Equals(fileName, "pwsh", StringComparison.OrdinalIgnoreCase) |
| | 6 | 661 | | || string.Equals(fileName, "pwsh.exe", StringComparison.OrdinalIgnoreCase); |
| | | 662 | | } |
| | | 663 | | |
| | | 664 | | /// <summary> |
| | | 665 | | /// Resolves a symlink path to its final target when supported by the platform. |
| | | 666 | | /// </summary> |
| | | 667 | | /// <param name="path">Path that may be a symbolic link.</param> |
| | | 668 | | /// <returns>Resolved full target path when available; otherwise null.</returns> |
| | | 669 | | private static string? TryResolveFinalPath(string path) |
| | | 670 | | { |
| | | 671 | | try |
| | | 672 | | { |
| | 3 | 673 | | var resolved = File.ResolveLinkTarget(path, returnFinalTarget: true); |
| | 3 | 674 | | return resolved is null ? null : Path.GetFullPath(resolved.FullName); |
| | | 675 | | } |
| | 0 | 676 | | catch |
| | | 677 | | { |
| | 0 | 678 | | return null; |
| | | 679 | | } |
| | 3 | 680 | | } |
| | | 681 | | |
| | | 682 | | /// <summary> |
| | | 683 | | /// Returns a writable fallback PSHOME location based on operating system. |
| | | 684 | | /// </summary> |
| | | 685 | | /// <returns>Fallback PSHOME absolute path.</returns> |
| | | 686 | | private static string GetFallbackPowerShellHomePath() |
| | | 687 | | { |
| | 0 | 688 | | if (OperatingSystem.IsWindows()) |
| | | 689 | | { |
| | 0 | 690 | | var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); |
| | 0 | 691 | | return Path.Combine(localAppData, "PowerShell", "7"); |
| | | 692 | | } |
| | | 693 | | |
| | 0 | 694 | | if (OperatingSystem.IsLinux()) |
| | | 695 | | { |
| | 0 | 696 | | var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| | 0 | 697 | | return Path.Combine(userProfile, ".local", "share", "powershell", "7"); |
| | | 698 | | } |
| | | 699 | | |
| | 0 | 700 | | if (OperatingSystem.IsMacOS()) |
| | | 701 | | { |
| | 0 | 702 | | var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); |
| | 0 | 703 | | return Path.Combine(userProfile, "Library", "Application Support", "powershell", "7"); |
| | | 704 | | } |
| | | 705 | | |
| | 0 | 706 | | var localFallback = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); |
| | 0 | 707 | | return Path.Combine(localFallback, "powershell", "7"); |
| | | 708 | | } |
| | | 709 | | |
| | | 710 | | /// <summary> |
| | | 711 | | /// Ensures a directory exists without throwing. |
| | | 712 | | /// </summary> |
| | | 713 | | /// <param name="path">Directory path to create.</param> |
| | | 714 | | private static void TryEnsureDirectory(string path) |
| | | 715 | | { |
| | 2 | 716 | | if (string.IsNullOrWhiteSpace(path)) |
| | | 717 | | { |
| | 1 | 718 | | return; |
| | | 719 | | } |
| | | 720 | | |
| | | 721 | | try |
| | | 722 | | { |
| | 1 | 723 | | _ = Directory.CreateDirectory(path); |
| | 1 | 724 | | } |
| | 0 | 725 | | catch |
| | | 726 | | { |
| | | 727 | | // Best-effort bootstrap path creation. |
| | 0 | 728 | | } |
| | 1 | 729 | | } |
| | | 730 | | |
| | | 731 | | /// <summary> |
| | | 732 | | /// Runs a process and captures output for diagnostics. |
| | | 733 | | /// </summary> |
| | | 734 | | /// <param name="fileName">Executable to run.</param> |
| | | 735 | | /// <param name="arguments">Argument tokens.</param> |
| | | 736 | | /// <returns>Process result data.</returns> |
| | | 737 | | private static ProcessResult RunProcessCapture(string fileName, IReadOnlyList<string> arguments) |
| | | 738 | | { |
| | 2 | 739 | | var startInfo = new ProcessStartInfo |
| | 2 | 740 | | { |
| | 2 | 741 | | FileName = fileName, |
| | 2 | 742 | | UseShellExecute = false, |
| | 2 | 743 | | RedirectStandardOutput = true, |
| | 2 | 744 | | RedirectStandardError = true, |
| | 2 | 745 | | CreateNoWindow = true, |
| | 2 | 746 | | }; |
| | | 747 | | |
| | 12 | 748 | | foreach (var argument in arguments) |
| | | 749 | | { |
| | 4 | 750 | | startInfo.ArgumentList.Add(argument); |
| | | 751 | | } |
| | | 752 | | |
| | 2 | 753 | | using var process = Process.Start(startInfo); |
| | 2 | 754 | | if (process is null) |
| | | 755 | | { |
| | 0 | 756 | | return new ProcessResult(1, string.Empty, $"Failed to start process: {fileName}"); |
| | | 757 | | } |
| | | 758 | | |
| | 2 | 759 | | var outputTask = process.StandardOutput.ReadToEndAsync(); |
| | 2 | 760 | | var errorTask = process.StandardError.ReadToEndAsync(); |
| | | 761 | | |
| | 2 | 762 | | process.WaitForExit(); |
| | 2 | 763 | | Task.WaitAll(outputTask, errorTask); |
| | 2 | 764 | | return new ProcessResult(process.ExitCode, outputTask.Result, errorTask.Result); |
| | 2 | 765 | | } |
| | | 766 | | |
| | | 767 | | /// <summary> |
| | | 768 | | /// Captures child process execution results. |
| | | 769 | | /// </summary> |
| | | 770 | | /// <param name="ExitCode">Process exit code.</param> |
| | | 771 | | /// <param name="Output">Captured standard output.</param> |
| | | 772 | | /// <param name="Error">Captured standard error.</param> |
| | 7 | 773 | | private sealed record ProcessResult(int ExitCode, string Output, string Error); |
| | | 774 | | } |