Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 151 additions & 14 deletions scripts/bootstrap-windows.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ function Test-WslRepairOutputReportsForbidden {
return $Output -match 'Forbidden\s*\(403\)'
}

function Test-WslRepairOutputRequiresReboot {
function Test-WslOutputRequiresReboot {
param([AllowNull()] [string]$Output)

if (-not $Output) {
Expand All @@ -760,6 +760,12 @@ function Test-WslRepairOutputRequiresReboot {
return $Output -match 'Changes will not be effective until the system is rebooted'
}

function Test-WslRepairOutputRequiresReboot {
param([AllowNull()] [string]$Output)

return Test-WslOutputRequiresReboot -Output $Output
}

function Write-WslRepairInstructions {
param(
[Parameter(Mandatory)] [int]$ExitCode,
Expand Down Expand Up @@ -1113,33 +1119,157 @@ function Wait-WslDistroRegistrationOrInstallExit {
}
}

function Write-WslInstallLog {
param([AllowNull()] [string]$LogPath)
function Get-WslInstallLog {
param(
[AllowNull()] [string]$LogPath,
[switch]$SuppressWarnings
)

if ([string]::IsNullOrWhiteSpace($LogPath)) {
return
return $null
}
if (-not (Test-Path -LiteralPath $LogPath)) {
return
return $null
}

try {
$log = Get-Content -LiteralPath $LogPath -Raw
return Get-Content -LiteralPath $LogPath -Raw
} catch {
Write-Status -Level WARN "Could not read WSL install log: $($_.Exception.Message)"
return
if (-not $SuppressWarnings) {
Write-Status -Level WARN "Could not read WSL install log: $($_.Exception.Message)"
}
return $null
}
}

function Convert-WslInstallLogForDisplay {
param(
[AllowNull()] [string]$Log,
[AllowNull()] [string[]]$SensitivePaths = @()
)

if ([string]::IsNullOrWhiteSpace($Log)) {
return $Log
}

$lines = (($Log -replace "`r`n", "`n") -replace "`r", "`n") -split "`n"
$separatorPattern = '^\*{6,}\s*$'
$firstSeparator = -1

for ($i = 0; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match $separatorPattern) {
$firstSeparator = $i
break
}
}

if ($firstSeparator -lt 0) {
return $Log
}

$headerEnd = -1
for ($i = $firstSeparator + 1; $i -lt $lines.Count; $i++) {
if ($lines[$i] -match $separatorPattern) {
$headerEnd = $i
break
}
}

if ($headerEnd -lt 0) {
return '[PowerShell transcript metadata redacted.]'
}

if (($headerEnd + 1) -lt $lines.Count) {
$bodyLines = @($lines[($headerEnd + 1)..($lines.Count - 1)])
} else {
$bodyLines = @()
}

$bodySeparators = @()
for ($i = 0; $i -lt $bodyLines.Count; $i++) {
if ($bodyLines[$i] -match $separatorPattern) {
$bodySeparators += $i
}
}

$footerStart = -1
if ($bodySeparators.Count -ge 2) {
$footerStart = $bodySeparators[$bodySeparators.Count - 2]
} elseif ($bodySeparators.Count -eq 1) {
$footerStart = $bodySeparators[0]
}

if ($footerStart -ge 0) {
if ($footerStart -eq 0) {
$bodyLines = @()
} else {
$bodyLines = @($bodyLines[0..($footerStart - 1)])
}
}

$filteredBodyLines = @()
foreach ($line in $bodyLines) {
$containsSensitivePath = $false
foreach ($path in $SensitivePaths) {
if (
-not [string]::IsNullOrWhiteSpace($path) -and
$line.IndexOf($path, [System.StringComparison]::OrdinalIgnoreCase) -ge 0
) {
$containsSensitivePath = $true
break
}
}
if (-not $containsSensitivePath) {
$filteredBodyLines += $line
}
}
$bodyLines = $filteredBodyLines

$bodyStart = 0
$bodyEnd = $bodyLines.Count - 1
while ($bodyStart -le $bodyEnd -and [string]::IsNullOrWhiteSpace($bodyLines[$bodyStart])) {
$bodyStart++
}
while ($bodyEnd -ge $bodyStart -and [string]::IsNullOrWhiteSpace($bodyLines[$bodyEnd])) {
$bodyEnd--
}
if ($bodyStart -le $bodyEnd) {
$bodyLines = @($bodyLines[($bodyStart)..($bodyEnd)])
} else {
$bodyLines = @()
}

return (@('[PowerShell transcript metadata redacted.]') + $bodyLines) -join "`n"
}

function Write-WslInstallLog {
param(
[AllowNull()] [string]$LogPath,
[AllowNull()] [string]$StatusPath
)

$log = Get-WslInstallLog -LogPath $LogPath
if ([string]::IsNullOrWhiteSpace($log)) {
return
}
$displayLog = Convert-WslInstallLogForDisplay -Log $log -SensitivePaths @($StatusPath, $LogPath)
if ([string]::IsNullOrWhiteSpace($displayLog)) {
return
}

Write-Host ''
Write-Host 'WSL install output:' -ForegroundColor Yellow
Write-NativeOutput -Value $log
Write-NativeOutput -Value $displayLog
Write-Host ''
}

function Test-WslInstallLogRequiresReboot {
param([AllowNull()] [string]$LogPath)

$log = Get-WslInstallLog -LogPath $LogPath -SuppressWarnings
return Test-WslOutputRequiresReboot -Output $log
}

function Remove-WslInstallArtifacts {
param(
[AllowNull()] [string]$StatusPath,
Expand Down Expand Up @@ -1228,7 +1358,7 @@ function Ensure-UbuntuWsl {
$registrationResult = Wait-WslDistroRegistrationOrInstallExit -Name $DistroName -StatusPath $installResult.StatusPath

if ($null -ne $registrationResult.ExitCode -and $registrationResult.ExitCode -ne 0) {
Write-WslInstallLog -LogPath $installResult.LogPath
Write-WslInstallLog -LogPath $installResult.LogPath -StatusPath $installResult.StatusPath
Remove-WslInstallArtifacts -StatusPath $installResult.StatusPath -LogPath $installResult.LogPath
$installArtifactsRemoved = $true
Write-WslUbuntuRequiredNotice -Name $DistroName
Expand All @@ -1237,13 +1367,20 @@ function Ensure-UbuntuWsl {

if (-not $registrationResult.Registered) {
if ($null -ne $registrationResult.ExitCode) {
Write-WslInstallLog -LogPath $installResult.LogPath
$installRequiresReboot = Test-WslInstallLogRequiresReboot -LogPath $installResult.LogPath
Write-WslInstallLog -LogPath $installResult.LogPath -StatusPath $installResult.StatusPath
Remove-WslInstallArtifacts -StatusPath $installResult.StatusPath -LogPath $installResult.LogPath
$installArtifactsRemoved = $true
Write-Status -Level WARN "$DistroName install command completed, but the distro is not registered yet."
Write-Status -Level WARN 'A reboot is required before WSL can finish registering the distro.'
Request-Reboot
return
if ($installRequiresReboot) {
Write-Status -Level WARN 'A reboot is required before WSL can finish registering the distro.'
Request-Reboot
return
}

Write-Status -Level WARN 'The install output did not report that a reboot is required.'
Write-WslUbuntuRequiredNotice -Name $DistroName
throw "WSL distro '$DistroName' is still not registered after install."
Comment thread
zyang-dev marked this conversation as resolved.
Resolved
}

Remove-WslInstallArtifacts -StatusPath $installResult.StatusPath -LogPath $installResult.LogPath
Expand Down
124 changes: 117 additions & 7 deletions test/bootstrap-windows.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -570,23 +570,34 @@
function Start-WslInstallInPowerShellWindow {
param([string]$Name)
Set-Content -LiteralPath $script:statusPath -Value '0'
Set-Content -LiteralPath $script:logPath -Value @'
$log = @'
**********************
Windows PowerShell transcript start
Username: NVIDIA.COM\\zyang
Username: EXAMPLE\\bootstrap-user
Benutzername: EXAMPLE\\bootstrap-user
Machine: TEST-HOST (Microsoft Windows NT 10.0.28000.0)
Computer: TEST-HOST (Microsoft Windows NT 10.0.28000.0)
Host Application: powershell.exe -Command $ErrorActionPreference = 'Continue'
$transcriptStarted = $false
try { Start-Transcript -Path $logPath -Force | Out-Null; $transcriptStarted = $true } catch { }
$statusPath = 'status-file'
& 'C:\\WINDOWS\\System32\\wsl.exe' --install -d 'Ubuntu-24.04'
try { [System.IO.File]::WriteAllText($statusPath, [string]$wslExitCode) } catch { }
Process ID: 1234
PSVersion: 5.1.28000.1830
**********************
'@
$log += ('Transcript started, output file is {0}{1}' -f $script:logPath, [Environment]::NewLine)
$log += ('Status file is {0}{1}' -f $script:statusPath, [Environment]::NewLine)
$log += @'
The requested operation is successful. Changes will not be effective until the system is rebooted.
Ubuntu installer command exited. This window will close automatically.
**********************
Windows PowerShell transcript end
End time: 20260628121936
**********************
'@
Set-Content -LiteralPath $script:logPath -Value $log
return [pscustomobject]@{ StatusPath = $script:statusPath; LogPath = $script:logPath; ProcessId = 1234 }
}
function Request-Reboot {
Expand All @@ -613,17 +624,30 @@
expect(result.stderr).toBe("");
const parsed = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1) ?? "{}");
expect(result.stdout).toContain("WSL install output:");
expect(result.stdout).toContain(

Check failure on line 627 in test/bootstrap-windows.test.ts

View workflow job for this annotation

GitHub Actions / cli-test-shards (1)

[integration] test/bootstrap-windows.test.ts > Windows bootstrap WSL distro preflight > requests reboot when Ubuntu install exits before distro registration

AssertionError: expected '\nUbuntu-24.04 is not registered yet.…' to contain 'The requested operation is successful…' - Expected + Received - The requested operation is successful. Changes will not be effective until the system is rebooted. + + Ubuntu-24.04 is not registered yet. Installing it in a separate PowerShell window... + Create the Unix user in that window if prompted. This script will continue after setup completes. + + + WSL install output: + [PowerShell transcript metadata redacted.] + Windows PowerShell transcript end + End time: 20260628121936 + + {"startProcessCalls":[],"statusMessages":["WARN:Ubuntu-24.04 install command completed, but the distro is not registered yet.","WARN:A reboot is required before WSL can finish registering the distro."],"requestReboot":true,"outcome":"REBOOT_REQUESTED"} + ❯ test/bootstrap-windows.test.ts:627:27
"The requested operation is successful. Changes will not be effective until the system is rebooted.",
);
expect(result.stdout).toContain(
"Ubuntu installer command exited. This window will close automatically.",
);
expect(result.stdout).toContain("Windows PowerShell transcript");
expect(result.stdout).toContain("Username:");
expect(result.stdout).toContain("Machine:");
expect(result.stdout).toContain("Host Application:");
expect(result.stdout).toContain("PSVersion:");
expect(result.stdout).toContain("[PowerShell transcript metadata redacted.]");
expect(result.stdout).not.toContain("Windows PowerShell transcript");
expect(result.stdout).not.toContain("Username:");
expect(result.stdout).not.toContain("Machine:");
expect(result.stdout).not.toContain("Host Application:");
expect(result.stdout).not.toContain("PSVersion:");
expect(result.stdout).not.toContain("Benutzername:");
expect(result.stdout).not.toContain("Computer:");
expect(result.stdout).not.toContain("EXAMPLE\\\\bootstrap-user");
expect(result.stdout).not.toContain("TEST-HOST");
expect(result.stdout).not.toContain("$statusPath = 'status-file'");
expect(result.stdout).not.toContain("$transcriptStarted = $false");
expect(result.stdout).not.toContain("Start-Transcript");
expect(result.stdout).not.toContain("WriteAllText");
expect(result.stdout).not.toContain("& 'C:\\\\WINDOWS\\\\System32\\\\wsl.exe' --install -d 'Ubuntu-24.04'");
expect(result.stdout).not.toContain("Transcript started, output file is");
expect(result.stdout).not.toContain("Status file is");
expect(result.stdout).not.toContain("End time:");
expect(parsed.statusMessages).toContain(
"WARN:Ubuntu-24.04 install command completed, but the distro is not registered yet.",
);
Expand All @@ -634,6 +658,92 @@
expect(parsed.outcome).toContain("REBOOT_REQUESTED");
});

itPowerShell("fails closed when a PowerShell transcript header is incomplete", () => {
const result = runPowerShellHarness(`
$ErrorActionPreference = 'Stop'
. ${JSON.stringify(BOOTSTRAP_WINDOWS)}

$log = @'
**********************
Windows PowerShell transcript start
Username: EXAMPLE\\bootstrap-user
Machine: TEST-HOST
'@

Convert-WslInstallLogForDisplay -Log $log
`);

expect(result.status).toBe(0);
expect(result.stderr).toBe("");
expect(result.stdout).toContain("[PowerShell transcript metadata redacted.]");
expect(result.stdout).not.toContain("EXAMPLE\\\\bootstrap-user");
expect(result.stdout).not.toContain("TEST-HOST");
});

itPowerShell("does not request reboot when Ubuntu install exits without registering the distro", () => {
const result = runPowerShellHarness(`
$ErrorActionPreference = 'Stop'
. ${JSON.stringify(BOOTSTRAP_WINDOWS)}

$script:statusMessages = @()
$script:requestReboot = $false
$script:outcome = 'success'
$script:statusPath = Join-Path $env:TEMP ('ubuntu-install-' + [guid]::NewGuid().ToString('N') + '.status')
$script:logPath = Join-Path $env:TEMP ('ubuntu-install-' + [guid]::NewGuid().ToString('N') + '.log')

function Resolve-WslExe { return 'wsl.exe' }
function Get-WslDistros { return @() }
function Start-WslInstallInPowerShellWindow {
param([string]$Name)
Set-Content -LiteralPath $script:statusPath -Value '0'
Set-Content -LiteralPath $script:logPath -Value @'
The operation completed successfully.
Ubuntu installer command exited. This window will close automatically.
'@
return [pscustomobject]@{ StatusPath = $script:statusPath; LogPath = $script:logPath; ProcessId = 1234 }
}
function Request-Reboot {
$script:requestReboot = $true
throw 'UNEXPECTED_REBOOT'
}
function Write-Status { param([string]$Message, [string]$Level = 'INFO') $script:statusMessages += ('{0}:{1}' -f $Level, $Message) }

try {
Ensure-UbuntuWsl
} catch {
$script:outcome = $_.Exception.Message
}

[pscustomobject]@{
statusMessages = $script:statusMessages
requestReboot = $script:requestReboot
outcome = $script:outcome
statusPathExists = Test-Path -LiteralPath $script:statusPath
logPathExists = Test-Path -LiteralPath $script:logPath
} | ConvertTo-Json -Compress
`);

expect(result.status).toBe(0);
expect(result.stderr).toBe("");
expect(result.stdout).toContain("WSL install output:");
expect(result.stdout).toContain("The operation completed successfully.");
expect(result.stdout).toContain("Please run: wsl --install -d Ubuntu-24.04");
const parsed = JSON.parse(result.stdout.trim().split(/\r?\n/).at(-1) ?? "{}");
expect(parsed.statusMessages).toContain(
"WARN:Ubuntu-24.04 install command completed, but the distro is not registered yet.",
);
expect(parsed.statusMessages).toContain(
"WARN:The install output did not report that a reboot is required.",
);
expect(parsed.statusMessages).not.toContain(
"WARN:A reboot is required before WSL can finish registering the distro.",
);
expect(parsed.requestReboot).toBe(false);
expect(parsed.outcome).toContain("WSL distro 'Ubuntu-24.04' is still not registered after install.");
expect(parsed.statusPathExists).toBe(false);
expect(parsed.logPathExists).toBe(false);
});

itPowerShell("reports failed Ubuntu install output in the main window", () => {
const result = runPowerShellHarness(`
$ErrorActionPreference = 'Stop'
Expand Down
Loading