@@ -1778,7 +1778,10 @@ private async Task TryEnsureLocalGatewayKeepAliveAsync()
17781778
17791779 var activeRecord = _gatewayRegistry ? . GetActive ( ) ;
17801780 if ( ! WslKeepAlivePolicy . ShouldStart ( activeRecord , _settings . GetEffectiveGatewayUrl ( ) ) )
1781+ {
1782+ await StopStaleLocalGatewayKeepAliveAsync ( ) ;
17811783 return ;
1784+ }
17821785
17831786 var distroName = await ResolveLocalGatewayDistroNameAsync ( activeRecord ) ;
17841787 if ( string . IsNullOrWhiteSpace ( distroName ) ) return ;
@@ -1795,7 +1798,7 @@ private async Task TryEnsureLocalGatewayKeepAliveAsync()
17951798 // Spawn a detached wsl sleep process to keep the VM alive
17961799 var psi = new System . Diagnostics . ProcessStartInfo
17971800 {
1798- FileName = "wsl.exe" ,
1801+ FileName = ResolveWslExePath ( ) ,
17991802 UseShellExecute = false ,
18001803 CreateNoWindow = true ,
18011804 } ;
@@ -1817,6 +1820,138 @@ private async Task TryEnsureLocalGatewayKeepAliveAsync()
18171820 }
18181821 }
18191822
1823+ private async Task StopStaleLocalGatewayKeepAliveAsync ( )
1824+ {
1825+ try
1826+ {
1827+ var localDataDir = SetupExistingGatewayClassifier . ResolveLocalDataPath ( ) ;
1828+ var markerDir = Path . Combine ( localDataDir , "wsl-keepalive" ) ;
1829+ var markerDistroNames = ReadKeepAliveMarkerDistroNames ( markerDir ) ;
1830+ var setupStateDistroName = await ReadSetupStateDistroNameAsync ( localDataDir ) ;
1831+ var records = _gatewayRegistry ? . GetAll ( ) ?? [ ] ;
1832+
1833+ foreach ( var distroName in WslKeepAlivePolicy . FindStaleSetupManagedDistroNames (
1834+ records ,
1835+ markerDistroNames ,
1836+ setupStateDistroName ) )
1837+ {
1838+ StopKeepAliveProcessesForDistro ( distroName ) ;
1839+ DeleteKeepAliveMarker ( markerDir , distroName ) ;
1840+ }
1841+ }
1842+ catch ( Exception ex )
1843+ {
1844+ Logger . Warn ( $ "[WslKeepAlive] Stale keepalive cleanup failed (non-fatal): { ex . Message } ") ;
1845+ }
1846+ }
1847+
1848+ private static IReadOnlyList < string > ReadKeepAliveMarkerDistroNames ( string markerDir )
1849+ {
1850+ if ( ! Directory . Exists ( markerDir ) )
1851+ return [ ] ;
1852+
1853+ var distroNames = new List < string > ( ) ;
1854+ foreach ( var markerPath in Directory . EnumerateFiles ( markerDir , "*.json" ) )
1855+ {
1856+ if ( WslKeepAlivePolicy . TryGetMarkerDistroName ( File . ReadAllText ( markerPath ) , out var distroName ) )
1857+ distroNames . Add ( distroName ) ;
1858+ }
1859+
1860+ return distroNames ;
1861+ }
1862+
1863+ private static async Task < string ? > ReadSetupStateDistroNameAsync ( string localDataDir )
1864+ {
1865+ var stateFile = Path . Combine ( localDataDir , "setup-state.json" ) ;
1866+ if ( ! File . Exists ( stateFile ) )
1867+ return null ;
1868+
1869+ var json = await File . ReadAllTextAsync ( stateFile ) ;
1870+ using var doc = System . Text . Json . JsonDocument . Parse ( json ) ;
1871+ return doc . RootElement . TryGetProperty ( "DistroName" , out var distroElement )
1872+ ? distroElement . GetString ( )
1873+ : null ;
1874+ }
1875+
1876+ private static void StopKeepAliveProcessesForDistro ( string distroName )
1877+ {
1878+ var procs = System . Diagnostics . Process . GetProcessesByName ( "wsl" )
1879+ . Concat ( System . Diagnostics . Process . GetProcessesByName ( "wsl.exe" ) ) ;
1880+
1881+ foreach ( var proc in procs )
1882+ {
1883+ try
1884+ {
1885+ if ( WslKeepAlivePolicy . IsKeepaliveCommandLine ( GetProcessCommandLine ( proc . Id ) , distroName ) )
1886+ {
1887+ proc . Kill ( entireProcessTree : true ) ;
1888+ proc . WaitForExit ( 5000 ) ;
1889+ Logger . Info ( $ "[WslKeepAlive] Stopped stale keepalive for { distroName } (PID { proc . Id } ).") ;
1890+ }
1891+ }
1892+ catch
1893+ {
1894+ // Process may have exited while being inspected.
1895+ }
1896+ finally
1897+ {
1898+ proc . Dispose ( ) ;
1899+ }
1900+ }
1901+ }
1902+
1903+ private static void DeleteKeepAliveMarker ( string markerDir , string distroName )
1904+ {
1905+ if ( ! Directory . Exists ( markerDir ) )
1906+ return ;
1907+
1908+ foreach ( var markerPath in Directory . EnumerateFiles ( markerDir , "*.json" ) )
1909+ {
1910+ try
1911+ {
1912+ if ( WslKeepAlivePolicy . TryGetMarkerDistroName ( File . ReadAllText ( markerPath ) , out var markerDistro )
1913+ && string . Equals ( markerDistro , distroName , StringComparison . OrdinalIgnoreCase ) )
1914+ {
1915+ File . Delete ( markerPath ) ;
1916+ Logger . Info ( $ "[WslKeepAlive] Deleted stale keepalive marker for { distroName } .") ;
1917+ }
1918+ }
1919+ catch
1920+ {
1921+ // Best-effort cleanup; stale/corrupt markers are not fatal.
1922+ }
1923+ }
1924+ }
1925+
1926+ private static string ? GetProcessCommandLine ( int pid )
1927+ {
1928+ try
1929+ {
1930+ var psi = new System . Diagnostics . ProcessStartInfo ( "powershell.exe" ,
1931+ $ "-NoProfile -Command \" (Get-CimInstance Win32_Process -Filter 'ProcessId={ pid } ').CommandLine\" ")
1932+ {
1933+ RedirectStandardOutput = true ,
1934+ UseShellExecute = false ,
1935+ CreateNoWindow = true
1936+ } ;
1937+ using var p = System . Diagnostics . Process . Start ( psi ) ;
1938+ if ( p == null ) return null ;
1939+ var output = p . StandardOutput . ReadToEnd ( ) ;
1940+ p . WaitForExit ( 5000 ) ;
1941+ return output . Trim ( ) ;
1942+ }
1943+ catch { return null ; }
1944+ }
1945+
1946+ private static string ResolveWslExePath ( )
1947+ {
1948+ var windowsDir = Environment . GetFolderPath ( Environment . SpecialFolder . Windows ) ;
1949+ if ( string . IsNullOrWhiteSpace ( windowsDir ) )
1950+ windowsDir = Environment . GetEnvironmentVariable ( "SystemRoot" ) ?? @"C:\Windows" ;
1951+
1952+ return Path . Combine ( windowsDir , "System32" , "wsl.exe" ) ;
1953+ }
1954+
18201955 /// <summary>
18211956 /// Resolves the WSL distro name to keep alive. Prefers the value persisted by
18221957 /// onboarding in <c>setup-state.json</c> so the keepalive always targets the distro
0 commit comments