|
| 1 | +using System.Diagnostics; |
| 2 | +using System.Net; |
| 3 | +using System.Net.Http; |
| 4 | +using System.Net.Sockets; |
| 5 | +using System.Runtime.InteropServices; |
| 6 | +using System.Security.Cryptography; |
| 7 | +using System.Text.Json; |
| 8 | +using OpenClaw.Connection; |
| 9 | +using OpenClaw.Shared; |
| 10 | + |
| 11 | +namespace OpenClaw.SetupEngine; |
| 12 | + |
| 13 | +public sealed class CleanupStaleDistroStep : SetupStep |
| 14 | +{ |
| 15 | + public override string Id => "cleanup-distro"; |
| 16 | + public override string DisplayName => "Clean up stale WSL distro"; |
| 17 | + public override bool CanRetry => false; |
| 18 | + |
| 19 | + public override bool CanSkip(SetupContext ctx) => !ctx.Config.CleanBeforeRun; |
| 20 | + |
| 21 | + public override async Task<StepResult> ExecuteAsync(SetupContext ctx, CancellationToken ct) |
| 22 | + { |
| 23 | + var distro = ctx.DistroName!; |
| 24 | + if (!DistroInstallPathPolicy.TryGetManagedInstallPath(ctx.LocalDataDir, distro, out var wslDir, out var pathError)) |
| 25 | + return StepResult.Terminal(pathError); |
| 26 | + |
| 27 | + var list = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--list", "--quiet"], TimeSpan.FromSeconds(15), ct: ct); |
| 28 | + if (list.ExitCode != 0) |
| 29 | + return StepResult.Ok("WSL not available or no distros - nothing to clean"); |
| 30 | + |
| 31 | + var distros = WslInstallSupport.ParseQuietDistroList(list.Stdout); |
| 32 | + |
| 33 | + ctx.Logger.Debug($"Found WSL distros: [{string.Join(", ", distros)}]"); |
| 34 | + |
| 35 | + if (!distros.Any(d => d.Equals(distro, StringComparison.OrdinalIgnoreCase))) |
| 36 | + { |
| 37 | + // Distro not registered, but disk directory may still exist from prior crash |
| 38 | + if (Directory.Exists(wslDir)) |
| 39 | + { |
| 40 | + ctx.Logger.Info($"Removing orphaned WSL directory: {wslDir}"); |
| 41 | + var delete = await DeleteDistroDirectoryWithRetries(ctx, distro, wslDir, ct); |
| 42 | + if (!delete.IsSuccess) |
| 43 | + return delete; |
| 44 | + } |
| 45 | + ctx.Logger.Decision("No stale distro found", "skip cleanup"); |
| 46 | + return StepResult.Ok("No stale distro to clean"); |
| 47 | + } |
| 48 | + |
| 49 | + ctx.Logger.Decision($"Found existing distro '{distro}'", "terminating and unregistering"); |
| 50 | + |
| 51 | + // Stop only the app-owned distro. Global WSL shutdown would disrupt unrelated distros. |
| 52 | + await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--terminate", distro], TimeSpan.FromSeconds(30), ct: ct); |
| 53 | + await Task.Delay(2000, ct); // Let port release |
| 54 | + |
| 55 | + var unregister = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--unregister", distro], TimeSpan.FromSeconds(60), ct: ct); |
| 56 | + if (unregister.ExitCode != 0) |
| 57 | + { |
| 58 | + ctx.Logger.Warn($"First unregister attempt failed (exit {unregister.ExitCode}); retrying targeted termination"); |
| 59 | + await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--terminate", distro], TimeSpan.FromSeconds(30), ct: ct); |
| 60 | + await Task.Delay(3000, ct); |
| 61 | + unregister = await ctx.Commands.RunAsync(WslConstants.WslExePath, ["--unregister", distro], TimeSpan.FromSeconds(60), ct: ct); |
| 62 | + } |
| 63 | + |
| 64 | + if (unregister.ExitCode == 0) |
| 65 | + { |
| 66 | + // Also remove the on-disk WSL vhdx directory (--import fails if it exists) |
| 67 | + var delete = await DeleteDistroDirectoryWithRetries(ctx, distro, wslDir, ct); |
| 68 | + if (!delete.IsSuccess) |
| 69 | + return delete; |
| 70 | + |
| 71 | + // Wait for port to be released |
| 72 | + ctx.Logger.Info("Waiting for port release after distro termination..."); |
| 73 | + await PreflightPortStep.WaitForPortFreeAsync(ctx.Config.GatewayPort, ctx.Config.Gateway.Bind, ctx.Logger, ct); |
| 74 | + return StepResult.Ok($"Unregistered stale distro '{distro}'"); |
| 75 | + } |
| 76 | + |
| 77 | + return StepResult.Fail($"Failed to unregister distro: {unregister.Stderr}"); |
| 78 | + } |
| 79 | + |
| 80 | + internal static async Task<StepResult> DeleteDistroDirectoryWithRetries( |
| 81 | + SetupContext ctx, |
| 82 | + string distroName, |
| 83 | + string wslDir, |
| 84 | + CancellationToken ct) |
| 85 | + { |
| 86 | + var deletePath = wslDir; |
| 87 | + Exception? lastError = null; |
| 88 | + |
| 89 | + for (var attempt = 0; attempt < 4; attempt++) |
| 90 | + { |
| 91 | + if (!DistroInstallPathPolicy.TryValidateDeleteTarget( |
| 92 | + ctx.LocalDataDir, |
| 93 | + distroName, |
| 94 | + wslDir, |
| 95 | + out deletePath, |
| 96 | + out var pathError)) |
| 97 | + { |
| 98 | + return StepResult.Terminal(pathError); |
| 99 | + } |
| 100 | + |
| 101 | + try |
| 102 | + { |
| 103 | + if (File.Exists(deletePath)) |
| 104 | + { |
| 105 | + if (File.GetAttributes(deletePath).HasFlag(FileAttributes.ReparsePoint)) |
| 106 | + return StepResult.Fail($"App-owned WSL path '{deletePath}' is a reparse point; remove it manually and retry setup."); |
| 107 | + |
| 108 | + ctx.Logger.Info($"Removing app-owned WSL file at install path: {deletePath}"); |
| 109 | + File.Delete(deletePath); |
| 110 | + } |
| 111 | + else if (Directory.Exists(deletePath)) |
| 112 | + { |
| 113 | + if (new DirectoryInfo(deletePath).Attributes.HasFlag(FileAttributes.ReparsePoint)) |
| 114 | + return StepResult.Fail($"App-owned WSL directory '{deletePath}' is a reparse point; remove it manually and retry setup."); |
| 115 | + |
| 116 | + ctx.Logger.Info($"Removing app-owned WSL directory: {deletePath}"); |
| 117 | + Directory.Delete(deletePath, recursive: true); |
| 118 | + } |
| 119 | + |
| 120 | + var parent = Path.GetDirectoryName(deletePath); |
| 121 | + if (!string.IsNullOrWhiteSpace(parent) && |
| 122 | + Directory.Exists(parent) && |
| 123 | + !new DirectoryInfo(parent).Attributes.HasFlag(FileAttributes.ReparsePoint) && |
| 124 | + !Directory.EnumerateFileSystemEntries(parent).Any()) |
| 125 | + { |
| 126 | + Directory.Delete(parent); |
| 127 | + ctx.Logger.Info("Deleted empty wsl\\ parent directory"); |
| 128 | + } |
| 129 | + |
| 130 | + return StepResult.Ok("WSL directory removed"); |
| 131 | + } |
| 132 | + catch (DirectoryNotFoundException) |
| 133 | + { |
| 134 | + return StepResult.Ok("WSL directory already absent"); |
| 135 | + } |
| 136 | + catch (IOException ex) |
| 137 | + { |
| 138 | + lastError = ex; |
| 139 | + if (attempt >= 3) |
| 140 | + break; |
| 141 | + |
| 142 | + ctx.Logger.Warn($"VHD directory still locked, retrying in {(attempt + 1) * 2}s..."); |
| 143 | + await Task.Delay(TimeSpan.FromSeconds((attempt + 1) * 2), ct); |
| 144 | + } |
| 145 | + catch (UnauthorizedAccessException ex) |
| 146 | + { |
| 147 | + lastError = ex; |
| 148 | + if (attempt >= 3) |
| 149 | + break; |
| 150 | + |
| 151 | + ctx.Logger.Warn($"VHD directory access denied, retrying in {(attempt + 1) * 2}s..."); |
| 152 | + await Task.Delay(TimeSpan.FromSeconds((attempt + 1) * 2), ct); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + return StepResult.Fail( |
| 157 | + $"Failed to remove app-owned WSL directory '{deletePath}'. Close any process using the OpenClaw WSL distro and retry setup." |
| 158 | + + (lastError is null ? "" : $" Last error: {lastError.Message}")); |
| 159 | + } |
| 160 | +} |
0 commit comments