Repository navigation
Expand file tree
/
Copy pathwslDevContainer.ps1
More file actions
298 lines (284 loc) · 14.4 KB
/
Copy pathwslDevContainer.ps1
File metadata and controls
298 lines (284 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
param(
[ValidateSet('Setup', 'Cleanup')]
[string] $Operation = 'Setup',
[ValidateSet('GitHub', 'AzureDevOps')]
[string] $CI = 'GitHub',
[string] $Distribution,
[string] $Root
)
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $false
Import-Module (Join-Path $PSScriptRoot '..\..\build\azure-pipelines\common\wsl.psm1') -Force
$wsl = Join-Path $env:SystemRoot 'System32\wsl.exe'
$workspace = if ($CI -eq 'AzureDevOps') { $env:BUILD_SOURCESDIRECTORY } else { $env:GITHUB_WORKSPACE }
$runId = if ($CI -eq 'AzureDevOps') { $env:BUILD_BUILDID } else { $env:GITHUB_RUN_ID }
$runAttempt = if ($CI -eq 'AzureDevOps') { $env:SYSTEM_JOBATTEMPT } else { $env:GITHUB_RUN_ATTEMPT }
if (-not $workspace -or $runId -notmatch '^\d+$' -or $runAttempt -notmatch '^\d+$') {
throw "Missing workspace, run ID, or attempt for $CI WSL smoke setup."
}
function Write-SmokeOutput([string] $Name, [string] $Value) {
if ($CI -eq 'AzureDevOps') {
$variable = switch ($Name) {
'root' { 'WSL_SMOKE_ROOT' }
'distro' { 'WSL_SMOKE_DISTRO' }
'serverPath' { 'WSL_SMOKE_SERVER_PATH' }
default { throw "Unknown WSL smoke output: $Name" }
}
$escaped = $Value.Replace('%', '%AZP25').Replace("`r", '%0D').Replace("`n", '%0A')
Write-Host "##vso[task.setvariable variable=$variable]$escaped"
} else {
"$Name=$Value" | Out-File -FilePath $env:GITHUB_OUTPUT -Encoding utf8 -Append
}
}
function Invoke-Wsl([string] $Command, [int] $TimeoutSeconds = 300) {
$Command = $Command -replace "`r`n", "`n"
$result = Invoke-WslExe -ArgumentList @('--distribution', $Distribution, '--user', 'root', '--exec', '/bin/bash', '-euc', $Command) -TimeoutSeconds $TimeoutSeconds -Stream
if ($result.TimedOut) {
throw "WSL smoke command timed out after $TimeoutSeconds seconds."
}
if ($result.ExitCode -ne 0) {
throw "WSL smoke command failed with exit code $($result.ExitCode)."
}
}
function Format-WslResult($Result) {
if ($Result.TimedOut) { 'timed out' } else { "exit code $($Result.ExitCode)" }
}
function Save-Download([string] $Url, [string] $Destination) {
curl.exe --fail --location --retry 5 --retry-all-errors --retry-max-time 120 --connect-timeout 30 --max-time 180 --output $Destination $Url
if ($LASTEXITCODE -ne 0) {
throw "Download failed with exit code ${LASTEXITCODE}: $Url"
}
}
function Write-DiagnosticSection([string] $Name, [scriptblock] $Action) {
"--- $Name ---"
try {
$output = & $Action 2>&1 | Out-String -Width 4096
$output.TrimEnd()
} catch {
"WARNING: Failed to collect ${Name}: $_"
}
}
function Write-WslDiagnostics([datetime] $ImportStartTime, [string] $InstallPath) {
'=== WSL diagnostics after failed import ==='
"Import started (UTC): $($ImportStartTime.ToUniversalTime().ToString('o'))"
# After a hang, wsl.exe may not respond at all, so every call here has a short timeout.
Write-DiagnosticSection 'Windows and WSL versions' {
Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber
"wsl.exe file version: $((Get-Item -LiteralPath $wsl).VersionInfo.FileVersion)"
$result = Invoke-WslExe -ArgumentList '--version' -TimeoutSeconds 30
$result.Output.TrimEnd()
"wsl --version: $(Format-WslResult $result)"
}
Write-DiagnosticSection 'wsl --status' {
$result = Invoke-WslExe -ArgumentList '--status' -TimeoutSeconds 30
$result.Output.TrimEnd()
"Result: $(Format-WslResult $result)"
}
Write-DiagnosticSection 'wsl --list --verbose' {
$result = Invoke-WslExe -ArgumentList '--list', '--verbose' -TimeoutSeconds 30
$result.Output.TrimEnd()
"Result: $(Format-WslResult $result)"
}
Write-DiagnosticSection 'Partial import files' {
$files = @(Get-ChildItem -LiteralPath $InstallPath -Force)
if ($files.Count) {
$files | Select-Object Name, Length, LastWriteTimeUtc | Format-List
} else {
'No files created.'
}
}
Write-DiagnosticSection 'Virtualization' {
Get-CimInstance -ClassName Win32_ComputerSystem |
Select-Object Manufacturer, Model, HypervisorPresent
}
Write-DiagnosticSection 'Windows optional features' {
foreach ($featureName in @('Microsoft-Windows-Subsystem-Linux', 'VirtualMachinePlatform')) {
Get-WindowsOptionalFeature -Online -FeatureName $featureName |
Select-Object FeatureName, State
}
}
Write-DiagnosticSection 'WSL services' {
foreach ($serviceName in @('LxssManager', 'WslService', 'vmcompute', 'hns')) {
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service) {
$service | Select-Object Name, Status, StartType
} else {
[pscustomobject]@{ Name = $serviceName; Status = 'NotFound'; StartType = $null }
}
}
}
Write-DiagnosticSection 'Pending reboot indicators' {
$pendingFileRenames = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager' -Name PendingFileRenameOperations -ErrorAction SilentlyContinue).PendingFileRenameOperations
[pscustomobject]@{
ComponentBasedServicing = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending'
WindowsUpdate = Test-Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired'
PendingFileRenames = $null -ne $pendingFileRenames
}
}
$eventStartTime = $ImportStartTime.AddMinutes(-1)
$eventEndTime = Get-Date
$wslEventLogs = @()
try {
$wslEventLogs = @(Get-WinEvent -ListLog '*Lxss*' -ErrorAction Stop | Select-Object -ExpandProperty LogName)
} catch {
"WARNING: Failed to discover WSL event logs: $_"
}
Write-DiagnosticSection 'Available WSL event logs' {
if ($wslEventLogs.Count) { $wslEventLogs } else { 'No Lxss event logs available.' }
}
foreach ($eventLogName in @($wslEventLogs + @('Microsoft-Windows-Host-Compute-Service-Admin', 'Microsoft-Windows-Hyper-V-Compute-Admin', 'Microsoft-Windows-Hyper-V-Worker-Admin', 'Microsoft-Windows-Hyper-V-VMMS-Admin') | Select-Object -Unique)) {
$action = {
Get-WinEvent -FilterHashtable @{ LogName = $eventLogName; StartTime = $eventStartTime; EndTime = $eventEndTime } -MaxEvents 20 -ErrorAction Stop |
Select-Object TimeCreated, Id, LevelDisplayName, Message | Format-List
}.GetNewClosure()
Write-DiagnosticSection "Recent events: $eventLogName" $action
}
}
if ($Operation -eq 'Cleanup') {
if ($Distribution -notmatch '^vscode-wsl-smoke-\d+-\d+-[0-9a-f]{32}$') {
throw 'Refusing cleanup of an unexpected WSL distribution.'
}
$Root = [IO.Path]::GetFullPath($Root)
if ([IO.Path]::GetDirectoryName($Root) -ne [IO.Path]::GetFullPath((Join-Path $workspace '.build')) -or [IO.Path]::GetFileName($Root) -ne $Distribution) {
throw 'Refusing cleanup of an unexpected WSL smoke directory.'
}
try {
Get-NetFirewallRule -Name $Distribution -ErrorAction SilentlyContinue | Remove-NetFirewallRule
$registered = Invoke-WslExe -ArgumentList '--list', '--quiet' -TimeoutSeconds 60
if ($registered.TimedOut) {
throw "WSL is not responding; leaving $Distribution and its files intact."
}
$names = @($registered.Output -split "`r?`n" | ForEach-Object { $_.Trim() })
if ($registered.ExitCode -ne 0 -or $names -contains $Distribution) {
$logDirectory = Join-Path $workspace '.build\logs\wsl-dev-container'
New-Item -ItemType Directory -Force -Path $logDirectory | Out-Null
(Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--user', 'root', '--exec', '/bin/sh', '-c', 'docker info; cat /var/log/docker.log 2>/dev/null' -TimeoutSeconds 60).Output |
Out-File -FilePath (Join-Path $logDirectory 'docker.log') -Encoding utf8
Invoke-WslExe -ArgumentList '--terminate', $Distribution -TimeoutSeconds 60 | Out-Null
$unregister = Invoke-WslExe -ArgumentList '--unregister', $Distribution -TimeoutSeconds 120
if ($unregister.ExitCode -ne 0) {
throw "Failed to unregister $Distribution ($(Format-WslResult $unregister)); leaving its files intact."
}
}
Remove-Item -LiteralPath $Root -Recurse -Force
} catch {
throw "WSL smoke cleanup failed: $_"
}
exit 0
}
if (-not (Test-Path -LiteralPath $wsl)) {
throw 'WSL is unavailable. This job requires WSL and VirtualMachinePlatform enabled without a pending reboot.'
}
$installerCache = if ($env:WSL_INSTALLER_CACHE_DIR) { $env:WSL_INSTALLER_CACHE_DIR } else { Join-Path $workspace '.build\wsl-installer' }
Install-Wsl -CacheDirectory $installerCache
$Distribution = "vscode-wsl-smoke-$runId-$runAttempt-$([guid]::NewGuid().ToString('N'))"
$Root = Join-Path $workspace ".build\$Distribution"
New-Item -ItemType Directory -Path $Root | Out-Null
Write-SmokeOutput 'root' $Root
Write-SmokeOutput 'distro' $Distribution
$archive = Join-Path $Root 'ubuntu-rootfs.tar.gz'
Save-Download 'https://cloud-images.ubuntu.com/wsl/jammy/20250318/ubuntu-jammy-wsl-amd64-ubuntu22.04lts.rootfs.tar.gz' $archive
if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne '1483cc5c1dce13064f774834cbffdff226559fd522a67a381a8ea77d63fb4109') {
throw 'Ubuntu WSL rootfs SHA256 mismatch.'
}
$install = Join-Path $Root 'distro'
New-Item -ItemType Directory -Path $install | Out-Null
# The WSL2 utility VM sometimes stops right after boot or hangs, failing or blocking the import, so the import has
# a timeout (a healthy one takes about 15 seconds) and is retried on a fresh utility VM.
$maxImportAttempts = 3
$importTimeoutSeconds = 120
for ($importAttempt = 1; ; $importAttempt++) {
$importStartTime = Get-Date
$import = Invoke-WslExe -ArgumentList '--import', $Distribution, $install, $archive, '--version', '2' -TimeoutSeconds $importTimeoutSeconds
if ($import.ExitCode -eq 0) {
break
}
$importResult = Format-WslResult $import
$logDirectory = Join-Path $workspace '.build\logs\wsl-dev-container'
New-Item -ItemType Directory -Force -Path $logDirectory | Out-Null
$diagnosticsPath = Join-Path $logDirectory "import-$Distribution-attempt-$importAttempt.log"
@("Import attempt: $importAttempt of $maxImportAttempts", "Import result: $importResult", 'Import output:', $import.Output) |
Tee-Object -FilePath $diagnosticsPath
Write-WslDiagnostics $importStartTime $install | Tee-Object -FilePath $diagnosticsPath -Append
if ($importAttempt -ge $maxImportAttempts) {
throw "Explicit WSL2 import failed ($importResult) after $importAttempt attempts. WSL1 is not supported by this test."
}
Write-Warning "Explicit WSL2 import attempt $importAttempt failed ($importResult). Resetting WSL before retrying."
# Drop any partial registration and stop the utility VM before starting again from an empty directory.
Write-Host (Invoke-WslExe -ArgumentList '--unregister', $Distribution -TimeoutSeconds 60).Output
$shutdown = Invoke-WslExe -ArgumentList '--shutdown', '--force' -TimeoutSeconds 60
Write-Host "$($shutdown.Output)wsl --shutdown --force: $(Format-WslResult $shutdown)"
Remove-Item -LiteralPath $install -Recurse -Force
New-Item -ItemType Directory -Path $install | Out-Null
Start-Sleep -Seconds (10 * $importAttempt)
}
Write-Host $import.Output
Invoke-Wsl 'uname -a; cat /etc/os-release' 120
# The frontend is built from this PR; the unchanged backend uses a pinned published server.
$serverCommit = '046944034292b5479b4e9a50ad1a508033ffb64f'
$metadata = Invoke-RestMethod "https://update.code.visualstudio.com/api/versions/commit:$serverCommit/server-linux-x64/insider"
if (-not $metadata.url -or $metadata.sha256hash -notmatch '^[0-9a-fA-F]{64}$') {
throw 'The pinned Linux server download metadata is incomplete.'
}
$serverArchive = Join-Path $Root 'server.tar.gz'
Save-Download $metadata.url $serverArchive
if ((Get-FileHash -LiteralPath $serverArchive -Algorithm SHA256).Hash -ne $metadata.sha256hash) {
throw 'Linux server SHA256 mismatch.'
}
$wslPath = Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--exec', 'wslpath', '-u', $serverArchive
$linuxArchive = $wslPath.Output.Trim()
if ($wslPath.ExitCode -ne 0 -or $linuxArchive -notmatch '^/mnt/[a-z]/[a-zA-Z0-9/_.-]+$') {
throw 'Cannot safely resolve the Linux server archive path.'
}
Invoke-Wsl @"
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y --no-install-recommends ca-certificates curl git iproute2 procps docker.io libatomic1 libkrb5-3
mkdir -p /opt/vscode-smoke-server
tar -xzf '$linuxArchive' --strip-components=1 -C /opt/vscode-smoke-server
/opt/vscode-smoke-server/node --version
test -f /opt/vscode-smoke-server/out/bootstrap-fork.js
useradd --create-home --shell /bin/bash vscode-smoke
usermod -aG docker vscode-smoke
printf '[user]\ndefault=vscode-smoke\n' > /etc/wsl.conf
"@
if ((Invoke-WslExe -ArgumentList '--terminate', $Distribution).ExitCode -ne 0) {
throw 'Failed to restart the owned distribution to apply its non-root default user.'
}
# Docker's default nftables backend needs matches that older WSL2 kernels lack; legacy iptables works with all of them.
Invoke-Wsl @"
update-alternatives --set iptables /usr/sbin/iptables-legacy
update-alternatives --set ip6tables /usr/sbin/ip6tables-legacy
start-stop-daemon --start --background --make-pidfile --pidfile /run/vscode-smoke-docker.pid --startas /bin/sh -- -c 'exec /usr/bin/dockerd > /var/log/docker.log 2>&1'
for attempt in `$(seq 1 60); do
if docker info > /dev/null 2>&1; then break; fi
sleep 1
done
if ! docker info; then
cat /var/log/docker.log
exit 1
fi
test "`$(docker info --format '{{.OSType}}')" = linux
docker pull mcr.microsoft.com/devcontainers/base:ubuntu-24.04
mkdir -p /tmp/vscode-smoke-bind-check
printf smoke > /tmp/vscode-smoke-bind-check/marker
docker run --rm --mount type=bind,source=/tmp/vscode-smoke-bind-check,target=/check mcr.microsoft.com/devcontainers/base:ubuntu-24.04 sh -c 'test "`$(cat /check/marker)" = smoke'
rm /tmp/vscode-smoke-bind-check/marker
rmdir /tmp/vscode-smoke-bind-check
"@
if ((Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--exec', '/bin/sh', '-ec', 'test "$(id -u)" -ne 0; docker info --format "{{.OSType}}"' -Stream).ExitCode -ne 0) {
throw 'The default WSL smoke user cannot access Docker.'
}
$addresses = Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--exec', 'hostname', '-I'
if ($addresses.ExitCode -ne 0) {
throw 'Cannot determine the WSL guest address for mock-server access.'
}
$guestAddress = ($addresses.Output.Trim() -split '\s+')[0]
if ($guestAddress -notmatch '^\d+\.\d+\.\d+\.\d+$') {
throw "Unexpected WSL guest address: $guestAddress"
}
New-NetFirewallRule -Name $Distribution -DisplayName $Distribution -Direction Inbound -Action Allow -Protocol TCP -RemoteAddress $guestAddress | Out-Null
Write-SmokeOutput 'serverPath' '/opt/vscode-smoke-server'
Write-Host "WSL Docker is ready in $Distribution with Linux server $serverCommit."