diff --git a/.github/skills/smoke-tests/SKILL.md b/.github/skills/smoke-tests/SKILL.md index a847f6c5495049..dd029dc16f6f2b 100644 --- a/.github/skills/smoke-tests/SKILL.md +++ b/.github/skills/smoke-tests/SKILL.md @@ -49,6 +49,7 @@ Some placement is coupled to the workflows, and `test/smoke/src/shard.ts` encode - **WSL:** The WSL Dev Container suite is pinned to shard 1, and `pr-win32-test.yml` provisions WSL only in shard 1. The provisioning runs in the background while the shard installs and builds, and a step before the smoke tests waits for it. The suite's estimate in `shard.ts` also counts the WSL Kerberos proxy run after the shard, so that the balancer gives shard 1 fewer other suites. Keep `VSCODE_SMOKE_TEST_WSL_REQUIRED` set in every shard, so that all shards register the same suites and compute the same split. On Windows, shard 1 runs on the 1ES pool instead of the `vscode-large-runners-windows-8-core` larger runners: GitHub-hosted Windows runners intermittently freeze while WSL2 provisions a distribution ([actions/runner-images#14938](https://github.com/actions/runner-images/issues/14938)), which leaves the check pending for about 45 minutes until GitHub reports that it lost communication with the runner. - **WSL version:** the agents' Windows Server 2022 image only has the inbox WSL, so provisioning installs the WSL release pinned in `build/checksums/wsl.txt` (see `build/azure-pipelines/common/wsl.psm1`). To update it, put the SHA256 and file name of a newer `wsl..x64.msi` from the [microsoft/WSL releases](https://github.com/microsoft/WSL/releases) there. The installer caches key on that file; `pr-node-modules.yml` fills the GitHub cache on `main`. +- **Prepared WSL distribution:** the `wsl-distro` job of `pr-workspace-images.yml` (1ES pool, daily schedule and manual runs only) runs `wslDevContainer.ps1 -Operation Prepare` and saves the exported VHD in a cache keyed on the hash of `wslDevContainer.ps1` and `build/checksums/wsl.txt`. Shard 1 restores the newest entry for its hash and imports it with `wsl --import-in-place` instead of building the distribution. It builds the distribution when there is no entry for its hash (for example after a change to either file, until the next daily run or a manual run of the workflow on `main`), or when the import fails. - **macOS proxy runs:** On macOS, the PAC proxy Agents Window runs happen only in the last shard, so the balancer reserves their time there. Every shard must register the same suites; otherwise suites can be skipped or run twice. Don't make suite registration depend on anything that differs between shards. diff --git a/.github/workflows/pr-win32-test.yml b/.github/workflows/pr-win32-test.yml index f787e4c34a132c..38a92ab09ffbc2 100644 --- a/.github/workflows/pr-win32-test.yml +++ b/.github/workflows/pr-win32-test.yml @@ -126,6 +126,18 @@ jobs: if: ${{ env.ELECTRON_TESTS == 'true' && env.SMOKE_TESTS == 'true' && env.SMOKE_SHARD_INDEX == '1' }} uses: ./.github/actions/restore-wsl-installer + # The wsl-distro job of pr-workspace-images.yml prepares the WSL distribution on main every day, so that the + # setup imports it instead of building it. Its key hashes the files that define it, and the restore key finds the + # newest one. Without one, or when it cannot be used, wslDevContainer.ps1 builds the distribution. + - name: Restore prepared WSL distribution + if: ${{ env.ELECTRON_TESTS == 'true' && env.SMOKE_TESTS == 'true' && env.SMOKE_SHARD_INDEX == '1' }} + continue-on-error: true + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .build/wsl-distro + key: "wsl-distro-v1-${{ runner.os }}-${{ hashFiles('test/smoke/wslDevContainer.ps1', 'build/checksums/wsl.txt') }}" + restore-keys: "wsl-distro-v1-${{ runner.os }}-${{ hashFiles('test/smoke/wslDevContainer.ps1', 'build/checksums/wsl.txt') }}-" + # The WSL setup takes 2 to 4 minutes, mostly downloads and package installs, so it runs in the background # while the steps below install and build, and "Wait for the WSL Dev Container smoke test setup" waits for # it before the smoke tests. The setup writes its step outputs, log and exit code to files. Start-Process @@ -160,6 +172,7 @@ jobs: Set-Content -LiteralPath (Join-Path $state 'deadline.txt') -Value ([DateTime]::UtcNow.AddMinutes(15).ToString('o')) env: WSL_INSTALLER_CACHE_DIR: ${{ github.workspace }}\.build\wsl-installer + WSL_PREPARED_DISTRO_VHD: ${{ github.workspace }}\.build\wsl-distro\vscode-wsl-smoke.vhdx - name: Setup Node.js uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 diff --git a/.github/workflows/pr-workspace-images.yml b/.github/workflows/pr-workspace-images.yml index ed647c4942a499..4874a5626be69c 100644 --- a/.github/workflows/pr-workspace-images.yml +++ b/.github/workflows/pr-workspace-images.yml @@ -6,6 +6,8 @@ name: Code OSS (workspace images) # jobs, and with a .git that their checkouts reuse. A job that mounts an image installs only what # changed since. The test workflows adopt the images one platform at a time in follow-up pull # requests, and until then nothing uses them. See .github/workflows/workspace_image/README.md. +# The daily and manual runs also prepare the WSL distribution of the Windows smoke tests (the +# wsl-distro job). on: # Every day, so that there is always a recent image of main: the images are kept for 2 days schedule: @@ -384,3 +386,45 @@ jobs: archive: false retention-days: 2 if-no-files-found: error + + # The WSL distribution that the Windows smoke test shard with the WSL suite imports instead of building it (see + # test/smoke/wslDevContainer.ps1 and electron-smoke-1 in pr-win32-test.yml). It only needs to be recent, so it is + # rebuilt with the daily images and on manual runs, but not on pushes. It runs on the 1ES pool like that shard, as + # GitHub-hosted Windows runners intermittently freeze while WSL2 provisions a distribution. JobId must be unique per + # job. The cache key hashes the files that define the distribution, so that the shard of a commit that changes them + # builds the distribution instead; the shard restores the newest entry of its key. + wsl-distro: + name: Windows (WSL distribution) + if: ${{ github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' }} + runs-on: [ self-hosted, 1ES.Pool=1es-vscode-oss-windows-2022-x64, "JobId=wsl-distro-${{ github.run_id }}-${{ github.run_number }}-${{ github.run_attempt }}" ] + timeout-minutes: 30 + steps: + - name: Checkout microsoft/vscode + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Restore WSL installer + uses: ./.github/actions/restore-wsl-installer + + - name: Prepare the WSL distribution + timeout-minutes: 20 + shell: pwsh + run: .\test\smoke\wslDevContainer.ps1 -Operation Prepare -Destination "$env:GITHUB_WORKSPACE\.build\wsl-distro\vscode-wsl-smoke.vhdx" + env: + WSL_INSTALLER_CACHE_DIR: ${{ github.workspace }}\.build\wsl-installer + + - name: Save the WSL distribution + uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5.1.0 + with: + path: .build/wsl-distro + key: "wsl-distro-v1-${{ runner.os }}-${{ hashFiles('test/smoke/wslDevContainer.ps1', 'build/checksums/wsl.txt') }}-${{ github.run_id }}-${{ github.run_attempt }}" + + - name: Publish Log Files + if: failure() + continue-on-error: true + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: logs-windows-x64-wsl-distro-${{ github.run_attempt }} + path: .build/logs + if-no-files-found: ignore diff --git a/test/smoke/README.md b/test/smoke/README.md index 17f248dc078485..06f18b86aa4772 100644 --- a/test/smoke/README.md +++ b/test/smoke/README.md @@ -144,6 +144,8 @@ The source Agent Host uses a fixture-owned loopback TCP proxy to reach the Windo The GitHub and Azure Pipelines Windows x64 Electron smoke jobs use [wslDevContainer.ps1](wslDevContainer.ps1) to provision a job-owned WSL 2 distribution with Linux Docker Engine and a non-root test user. Azure Pipelines passes `-CI AzureDevOps` to use its source directory, build ID, job attempt, and pipeline variables; GitHub uses its workspace, run identifiers, and step outputs. Azure enables this coverage for Windows x64 builds with Electron tests enabled, and uses the freshly built Windows product. The test suite retains its existing Exploration exclusion; build scripts do not gate on quality. Both cache the Microsoft-signed WSL kernel installer under a daily key, restore the most recent earlier cache if needed, and refresh it in the background for the next build. A cold cache still requires a synchronous download. The installer signature is checked before use and before updating the cache; the pinned Ubuntu rootfs and Linux server are checked against their SHA256 hashes. The unchanged source-host backend uses the pinned published server recorded in the script. Setup verifies a real container and bind mount before running the UI suite. Cleanup runs even after failure or cancellation, removes the owned distribution and its temporary mock-server firewall rule, and retains Docker diagnostics with the smoke logs. The runner must already have the WSL and VirtualMachinePlatform Windows features enabled; setup does not enable features or reboot Windows. +On GitHub, the `wsl-distro` job of [pr-workspace-images.yml](../../.github/workflows/pr-workspace-images.yml) runs `wslDevContainer.ps1 -Operation Prepare` on `main` every day and on manual runs, on the 1ES pool. Prepare builds the same distribution, up to the pulled dev container image, and exports its VHD, which the job saves in a cache whose key hashes this script and `build/checksums/wsl.txt`. The Windows smoke shard restores the newest entry for its own versions of those files and passes the VHD in `WSL_PREPARED_DISTRO_VHD`. Setup then registers it under the run's distribution name with `wsl --import-in-place`, starts Docker Engine and checks the container and bind mount, instead of downloading and installing everything. Without a prepared distribution (for example until the next daily run after a change to this script), or when importing or starting it fails, Setup builds the distribution as before. Azure Pipelines always builds it. + All remote suites drive host connection, remote folder selection, **Use Dev Container**, prompt submission, the rendered response, and reopening the session through the UI. Model requests use the local mock LLM server, not paid models. They also verify that container startup uses the selected SSH/Tunnel/WSL connection and that the turn travels over the nested Dev Container transport. Source runs launch the compiled standalone Agent Host with the checkout's matching Electron runtime. Packaged runs launch the shipped `bootstrap-fork.js` / `agentHostMain` entrypoint with IPC, the build's NLS messages, and authenticated WebSocket configuration; they do not require the development-only standalone entrypoint. Since Code OSS does not configure tunnel authentication scopes, the Tunnel fixture creates a private source-app snapshot with only the required test product metadata; it never changes the checkout's product files. Packaged Tunnel runs require the supplied build's tunnel authentication configuration. diff --git a/test/smoke/wslDevContainer.ps1 b/test/smoke/wslDevContainer.ps1 index 7203dbb1fa51c0..98c5c0f437a71f 100644 --- a/test/smoke/wslDevContainer.ps1 +++ b/test/smoke/wslDevContainer.ps1 @@ -1,15 +1,25 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. +# Operations: +# - Setup: provisions a job-owned WSL 2 distribution with Linux Docker Engine, the pinned Linux server and a non-root +# test user, and sets the root, distro and serverPath outputs. When WSL_PREPARED_DISTRO_VHD names a distribution that +# Prepare exported, Setup imports it instead of building one, and falls back to building one when that fails. +# - Prepare: builds the same distribution and exports its VHD to the .vhdx file -Destination (see the wsl-distro job of +# .github/workflows/pr-workspace-images.yml). +# - AddServer: adds the Linux server of a compilation artifact to the distribution. +# - Cleanup: removes the distribution, its files and its firewall rule. param( - [ValidateSet('Setup', 'Cleanup', 'AddServer')] + [ValidateSet('Setup', 'Prepare', 'Cleanup', 'AddServer')] [string] $Operation = 'Setup', [ValidateSet('GitHub', 'AzureDevOps')] [string] $CI = 'GitHub', [string] $Distribution, [string] $Root, # AddServer: a compilation artifact's builds.tar.gz with the Linux server to add to the distribution. - [string] $Archive + [string] $Archive, + # Prepare: the .vhdx file to export the distribution to. + [string] $Destination ) $ErrorActionPreference = 'Stop' @@ -23,6 +33,16 @@ if (-not $workspace -or $runId -notmatch '^\d+$' -or $runAttempt -notmatch '^\d+ throw "Missing workspace, run ID, or attempt for $CI WSL smoke setup." } +# The pinned inputs of the distribution. +$rootfsUrl = 'https://cloud-images.ubuntu.com/wsl/jammy/20250318/ubuntu-jammy-wsl-amd64-ubuntu22.04lts.rootfs.tar.gz' +$rootfsSha256 = '1483cc5c1dce13064f774834cbffdff226559fd522a67a381a8ea77d63fb4109' +# The frontend is built from this PR; the unchanged backend uses a pinned published server. The WSL Kerberos proxy smoke +# tests need a server with the agent host's client proxy, Kerberos and certificate support. +$serverCommit = '67710841ad061a9e253214f87bf5415a185ab2ff' +$aptPackages = 'ca-certificates curl git iproute2 procps docker.io libatomic1 libkrb5-3 krb5-kdc krb5-admin-server squid-openssl openssl' +$devContainerImage = 'mcr.microsoft.com/devcontainers/base:ubuntu-24.04' +$serverPath = '/opt/vscode-smoke-server' + function Write-SmokeOutput([string] $Name, [string] $Value) { if ($CI -eq 'AzureDevOps') { $variable = switch ($Name) { @@ -152,14 +172,11 @@ function Write-WslDiagnostics([datetime] $ImportStartTime, [string] $InstallPath } } -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.' - } +<# +.SYNOPSIS +Unregisters the distribution and removes its files and firewall rule. +#> +function Remove-SmokeDistribution { try { Get-NetFirewallRule -Name $Distribution -ErrorAction SilentlyContinue | Remove-NetFirewallRule $registered = Invoke-WslExe -ArgumentList '--list', '--quiet' -TimeoutSeconds 60 @@ -182,106 +199,87 @@ if ($Operation -eq 'Cleanup') { } catch { throw "WSL smoke cleanup failed: $_" } - exit 0 } -if ($Operation -eq 'AddServer') { - if ($Distribution -notmatch '^vscode-wsl-smoke-\d+-\d+-[0-9a-f]{32}$') { - throw 'Refusing to change an unexpected WSL distribution.' - } - $wslPath = Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--exec', 'wslpath', '-u', ([IO.Path]::GetFullPath($Archive)) - $linuxArchive = $wslPath.Output.Trim() - if ($wslPath.ExitCode -ne 0 -or $linuxArchive -notmatch '^/mnt/[a-z]/[a-zA-Z0-9/_.-]+$') { - throw 'Cannot safely resolve the compilation archive path.' - } - # The server of the same build accepts the packaged client, unlike the pinned server. - Invoke-Wsl @" -mkdir /opt/vscode-smoke-build-server -tar -xzf '$linuxArchive' --strip-components=1 -C /opt/vscode-smoke-build-server vscode-server-linux-x64 -/opt/vscode-smoke-build-server/node --version -test -f /opt/vscode-smoke-build-server/out/server-main.js -"@ 600 - Write-SmokeOutput 'buildServerPath' '/opt/vscode-smoke-build-server' - 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. +<# +.SYNOPSIS +Drops any registration of the distribution, stops the utility VM and empties the install directory, to start again. +#> +function Reset-SmokeDistribution([string] $Install) { 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) + if (Test-Path -LiteralPath $Install) { + Remove-Item -LiteralPath $Install -Recurse -Force + } + New-Item -ItemType Directory -Path $Install | Out-Null } -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. The WSL Kerberos proxy smoke -# tests need a server with the agent host's client proxy, Kerberos and certificate support. -$serverCommit = '67710841ad061a9e253214f87bf5415a185ab2ff' -$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.' +<# +.SYNOPSIS +Imports the distribution from the pinned Ubuntu rootfs. +#> +function Import-RootfsDistribution([string] $Install) { + $archive = Join-Path $Root 'ubuntu-rootfs.tar.gz' + Save-Download $rootfsUrl $archive + if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne $rootfsSha256) { + throw 'Ubuntu WSL rootfs SHA256 mismatch.' + } + # 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." + Reset-SmokeDistribution $Install + Start-Sleep -Seconds (10 * $importAttempt) + } + Write-Host $import.Output + Invoke-Wsl 'uname -a; cat /etc/os-release' 120 } -# From the Azure-hosted agents, archive.ubuntu.com and security.ubuntu.com are at times so slow that apt runs past this -# command's timeout, so apt uses the Azure Ubuntu mirror. apt only warns about index files it could not fetch, so the -# index update fails on any fetch error and is retried. The WSL Kerberos proxy smoke tests run their own KDC and Squid, -# so policy-rc.d keeps the packages from starting theirs. -$aptPackages = 'ca-certificates curl git iproute2 procps docker.io libatomic1 libkrb5-3 krb5-kdc krb5-admin-server squid-openssl openssl' -$linuxRoot = $linuxArchive.Substring(0, $linuxArchive.LastIndexOf('/')) -$debDirectory = Join-Path $Root 'debs' -New-Item -ItemType Directory -Force -Path $debDirectory | Out-Null -Invoke-Wsl @" + +<# +.SYNOPSIS +Installs the pinned Linux server, the apt packages and the non-root test user into the distribution. +#> +function Install-DistributionContent { + $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.' + } + # From the Azure-hosted agents, archive.ubuntu.com and security.ubuntu.com are at times so slow that apt runs past this + # command's timeout, so apt uses the Azure Ubuntu mirror. apt only warns about index files it could not fetch, so the + # index update fails on any fetch error and is retried. The WSL Kerberos proxy smoke tests run their own KDC and Squid, + # so policy-rc.d keeps the packages from starting theirs. + $linuxRoot = $linuxArchive.Substring(0, $linuxArchive.LastIndexOf('/')) + $debDirectory = Join-Path $Root 'debs' + New-Item -ItemType Directory -Force -Path $debDirectory | Out-Null + Invoke-Wsl @" export DEBIAN_FRONTEND=noninteractive sed -i -e 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' -e 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list printf 'Acquire::Retries "5";\nAcquire::http::Timeout "30";\n' > /etc/apt/apt.conf.d/80-retries @@ -297,66 +295,75 @@ done apt-get install -y -qq --print-uris --no-install-recommends $aptPackages > '$linuxRoot/apt-uris.txt' "@ 180 -# The packages are downloaded by the host rather than by apt in the distribution. The Azure mirror at times serves -# package files to the distribution at about 120 KB/s for minutes while its index files stay fast, and apt keeps such -# a connection rather than giving up on it. Here a transfer that stays below 1 MB/s for 15 seconds is abandoned and -# retried on a fresh connection, then on the main Ubuntu archive. apt checks each file against the index when it installs. -# The host gives up after 4 minutes in total, leaving the packages it did not get to apt, within the step's timeout. -$debCount = 0 -$hostDownloadDeadline = [DateTime]::UtcNow.AddMinutes(4) -foreach ($line in Get-Content -LiteralPath (Join-Path $Root 'apt-uris.txt')) { - if ($line -notmatch "^'(https?://[^']+)' ([A-Za-z0-9_.+~%-]+\.deb) (\d+) (SHA512|SHA256|SHA1|MD5Sum):([0-9a-f]+)") { - continue - } - $url, $name, $size, $hash = $Matches[1], $Matches[2], [long]$Matches[3], $Matches[5] - $algorithm = @{ SHA512 = 'SHA512'; SHA256 = 'SHA256'; SHA1 = 'SHA1'; MD5Sum = 'MD5' }[$Matches[4]] - $destination = Join-Path $debDirectory $name - $downloaded = $false - # Each attempt opens a fresh connection: the Azure mirror twice, then the main Ubuntu archive. - $fallback = $url -replace '^http://azure\.archive\.ubuntu\.com/', 'http://archive.ubuntu.com/' - foreach ($candidate in @($url, $url, $fallback)) { - $remainingSeconds = [int]($hostDownloadDeadline - [DateTime]::UtcNow).TotalSeconds - if ($remainingSeconds -lt 10) { - break + # The packages are downloaded by the host rather than by apt in the distribution. The Azure mirror at times serves + # package files to the distribution at about 120 KB/s for minutes while its index files stay fast, and apt keeps such + # a connection rather than giving up on it. Here a transfer that stays below 1 MB/s for 15 seconds is abandoned and + # retried on a fresh connection, then on the main Ubuntu archive. apt checks each file against the index when it installs. + # The host gives up after 4 minutes in total, leaving the packages it did not get to apt, within the step's timeout. + $debCount = 0 + $hostDownloadDeadline = [DateTime]::UtcNow.AddMinutes(4) + foreach ($line in Get-Content -LiteralPath (Join-Path $Root 'apt-uris.txt')) { + if ($line -notmatch "^'(https?://[^']+)' ([A-Za-z0-9_.+~%-]+\.deb) (\d+) (SHA512|SHA256|SHA1|MD5Sum):([0-9a-f]+)") { + continue } - curl.exe --fail --location --silent --show-error --connect-timeout 10 --max-time ([Math]::Min(120, $remainingSeconds)) --speed-limit 1048576 --speed-time 15 --output $destination $candidate - if ($LASTEXITCODE -eq 0 -and (Get-Item -LiteralPath $destination).Length -eq $size -and (Get-FileHash -LiteralPath $destination -Algorithm $algorithm).Hash -eq $hash.ToUpperInvariant()) { - $downloaded = $true - break + $url, $name, $size, $hash = $Matches[1], $Matches[2], [long]$Matches[3], $Matches[5] + $algorithm = @{ SHA512 = 'SHA512'; SHA256 = 'SHA256'; SHA1 = 'SHA1'; MD5Sum = 'MD5' }[$Matches[4]] + $destination = Join-Path $debDirectory $name + $downloaded = $false + # Each attempt opens a fresh connection: the Azure mirror twice, then the main Ubuntu archive. + $fallback = $url -replace '^http://azure\.archive\.ubuntu\.com/', 'http://archive.ubuntu.com/' + foreach ($candidate in @($url, $url, $fallback)) { + $remainingSeconds = [int]($hostDownloadDeadline - [DateTime]::UtcNow).TotalSeconds + if ($remainingSeconds -lt 10) { + break + } + curl.exe --fail --location --silent --show-error --connect-timeout 10 --max-time ([Math]::Min(120, $remainingSeconds)) --speed-limit 1048576 --speed-time 15 --output $destination $candidate + if ($LASTEXITCODE -eq 0 -and (Get-Item -LiteralPath $destination).Length -eq $size -and (Get-FileHash -LiteralPath $destination -Algorithm $algorithm).Hash -eq $hash.ToUpperInvariant()) { + $downloaded = $true + break + } + Write-Host "Download of $name from $candidate failed (curl exit code $LASTEXITCODE)." } - Write-Host "Download of $name from $candidate failed (curl exit code $LASTEXITCODE)." - } - if (-not $downloaded) { - Remove-Item -LiteralPath $destination -ErrorAction SilentlyContinue - Write-Host "Leaving $name for apt to download." - continue + if (-not $downloaded) { + Remove-Item -LiteralPath $destination -ErrorAction SilentlyContinue + Write-Host "Leaving $name for apt to download." + continue + } + $debCount++ } - $debCount++ -} -Write-Host "Downloaded $debCount packages on the host." -# A failed curl above must not become the exit code of this script. -$global:LASTEXITCODE = 0 + Write-Host "Downloaded $debCount packages on the host." + # A failed curl above must not become the exit code of this script. + $global:LASTEXITCODE = 0 -Invoke-Wsl @" + Invoke-Wsl @" export DEBIAN_FRONTEND=noninteractive cp '$linuxRoot'/debs/*.deb /var/cache/apt/archives/ 2>/dev/null || true printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d chmod +x /usr/sbin/policy-rc.d apt-get install -y --no-install-recommends $aptPackages rm /usr/sbin/policy-rc.d -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 +mkdir -p $serverPath +tar -xzf '$linuxArchive' --strip-components=1 -C $serverPath +$serverPath/node --version +test -f $serverPath/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 "@ 720 -if ((Invoke-WslExe -ArgumentList '--terminate', $Distribution).ExitCode -ne 0) { - throw 'Failed to restart the owned distribution to apply its non-root default user.' + 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 @" + +<# +.SYNOPSIS +Starts Docker Engine in the distribution and checks that the default user can run the dev container image with a +bind mount. With -Pull, pulls the image first; otherwise the distribution must already have it. +#> +function Start-SmokeDocker([switch] $Pull) { + $image = if ($Pull) { "docker pull $devContainerImage" } else { "docker image inspect --format '{{index .RepoDigests 0}}' $devContainerImage" } + # 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' @@ -369,16 +376,176 @@ if ! docker info; then exit 1 fi test "`$(docker info --format '{{.OSType}}')" = linux -docker pull mcr.microsoft.com/devcontainers/base:ubuntu-24.04 +$image 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' +docker run --rm --mount type=bind,source=/tmp/vscode-smoke-bind-check,target=/check $devContainerImage 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.' + 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.' + } +} + +<# +.SYNOPSIS +Shrinks a dynamically expanding VHD by dropping the blocks that fstrim released. Failures only leave it larger. +#> +function Optimize-PreparedVhd([string] $Path) { + $commands = Join-Path ([IO.Path]::GetTempPath()) "compact-$([guid]::NewGuid().ToString('N')).txt" + try { + @("select vdisk file=`"$Path`"", 'attach vdisk readonly', 'compact vdisk', 'detach vdisk') | Set-Content -LiteralPath $commands + diskpart /s $commands | Out-Host + if ($LASTEXITCODE -ne 0) { + Write-Warning "Compacting $Path failed with exit code $LASTEXITCODE; exporting it as is." + @("select vdisk file=`"$Path`"", 'detach vdisk noerr') | Set-Content -LiteralPath $commands + diskpart /s $commands | Out-Host + } + } finally { + Remove-Item -LiteralPath $commands -ErrorAction SilentlyContinue + $global:LASTEXITCODE = 0 + } +} + +<# +.SYNOPSIS +Stops the distribution and exports its VHD to the .vhdx file $Path. +#> +function Export-PreparedDistribution([string] $Path) { + $digest = Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--user', 'root', '--exec', 'docker', 'image', 'inspect', '--format', '{{index .RepoDigests 0}}', $devContainerImage + if ($digest.ExitCode -ne 0) { + throw "Cannot determine the digest of ${devContainerImage}: $($digest.Output)" + } + # Every run starts its own dockerd and only needs its own log. Without the apt lists, apt needs an update first. + Invoke-Wsl @' +start-stop-daemon --stop --oknodo --pidfile /run/vscode-smoke-docker.pid --remove-pidfile --retry TERM/30/KILL/5 +: > /var/log/docker.log +apt-get clean +rm -rf /var/lib/apt/lists/* +sync +fstrim --verbose / || echo 'fstrim failed, so the export keeps the blocks of deleted files.' +'@ + $terminate = Invoke-WslExe -ArgumentList '--terminate', $Distribution -TimeoutSeconds 60 + if ($terminate.ExitCode -ne 0) { + throw "Failed to stop $Distribution before exporting it ($(Format-WslResult $terminate))." + } + New-Item -ItemType Directory -Force -Path (Split-Path $Path -Parent) | Out-Null + Remove-Item -LiteralPath $Path -ErrorAction SilentlyContinue + # A VHD export copies the distribution's ext4.vhdx as it is, which needs the same file extension. + $export = Invoke-WslExe -ArgumentList '--export', $Distribution, $Path, '--format', 'vhd' -TimeoutSeconds 600 + if ($export.ExitCode -ne 0) { + throw "Exporting $Distribution failed ($(Format-WslResult $export)): $($export.Output)" + } + $exportedSize = (Get-Item -LiteralPath $Path).Length + Optimize-PreparedVhd $Path + $compactedSize = (Get-Item -LiteralPath $Path).Length + Write-Host ('Exported {0} with {1} to {2}: {3:N2} GB, {4:N2} GB after compacting.' -f $Distribution, $digest.Output.Trim(), $Path, ($exportedSize / 1GB), ($compactedSize / 1GB)) +} + +<# +.SYNOPSIS +Registers the distribution that Prepare exported to the .vhdx file $Vhd in the install directory, without copying it. +#> +function Import-PreparedDistribution([string] $Vhd, [string] $Install) { + $installedVhd = Join-Path $Install 'ext4.vhdx' + # On the same volume, this is a rename rather than a copy of several GB. + Move-Item -LiteralPath $Vhd -Destination $installedVhd + $import = Invoke-WslExe -ArgumentList '--import-in-place', $Distribution, $installedVhd -TimeoutSeconds 120 + if ($import.ExitCode -ne 0) { + throw "wsl --import-in-place failed ($(Format-WslResult $import)): $($import.Output)" + } + Write-Host $import.Output + Invoke-Wsl 'uname -a; cat /etc/os-release' 120 } + +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.' + } + Remove-SmokeDistribution + exit 0 +} + +if ($Operation -eq 'AddServer') { + if ($Distribution -notmatch '^vscode-wsl-smoke-\d+-\d+-[0-9a-f]{32}$') { + throw 'Refusing to change an unexpected WSL distribution.' + } + $wslPath = Invoke-WslExe -ArgumentList '--distribution', $Distribution, '--exec', 'wslpath', '-u', ([IO.Path]::GetFullPath($Archive)) + $linuxArchive = $wslPath.Output.Trim() + if ($wslPath.ExitCode -ne 0 -or $linuxArchive -notmatch '^/mnt/[a-z]/[a-zA-Z0-9/_.-]+$') { + throw 'Cannot safely resolve the compilation archive path.' + } + # The server of the same build accepts the packaged client, unlike the pinned server. + Invoke-Wsl @" +mkdir /opt/vscode-smoke-build-server +tar -xzf '$linuxArchive' --strip-components=1 -C /opt/vscode-smoke-build-server vscode-server-linux-x64 +/opt/vscode-smoke-build-server/node --version +test -f /opt/vscode-smoke-build-server/out/server-main.js +"@ 600 + Write-SmokeOutput 'buildServerPath' '/opt/vscode-smoke-build-server' + exit 0 +} + +if ($Operation -eq 'Prepare' -and $Destination -notmatch '\.vhdx$') { + throw 'Prepare needs a .vhdx file -Destination to export the distribution to.' +} +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 +$stopwatch = [Diagnostics.Stopwatch]::StartNew() + +$Distribution = "vscode-wsl-smoke-$runId-$runAttempt-$([guid]::NewGuid().ToString('N'))" +$Root = Join-Path $workspace ".build\$Distribution" +New-Item -ItemType Directory -Path $Root | Out-Null +$install = Join-Path $Root 'distro' +New-Item -ItemType Directory -Path $install | Out-Null + +if ($Operation -eq 'Prepare') { + try { + Import-RootfsDistribution $install + Install-DistributionContent + Start-SmokeDocker -Pull + Export-PreparedDistribution $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Destination) + } finally { + try { + Remove-SmokeDistribution + } catch { + Write-Warning $_ + } + } + Write-Host "Prepared the WSL distribution with Linux server $serverCommit in $([int]$stopwatch.Elapsed.TotalSeconds)s." + exit 0 +} + +Write-SmokeOutput 'root' $Root +Write-SmokeOutput 'distro' $Distribution + +$imported = $false +if ($env:WSL_PREPARED_DISTRO_VHD -and (Test-Path -LiteralPath $env:WSL_PREPARED_DISTRO_VHD -PathType Leaf)) { + try { + Import-PreparedDistribution $env:WSL_PREPARED_DISTRO_VHD $install + Start-SmokeDocker + $imported = $true + } catch { + Write-Warning "Cannot use the prepared WSL distribution, building it instead: $_" + Reset-SmokeDistribution $install + } +} else { + Write-Host 'No prepared WSL distribution, building it.' +} +if (-not $imported) { + Import-RootfsDistribution $install + Install-DistributionContent + Start-SmokeDocker -Pull +} + $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.' @@ -388,5 +555,6 @@ 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." +Write-SmokeOutput 'serverPath' $serverPath +$source = if ($imported) { 'imported the prepared distribution' } else { 'built the distribution' } +Write-Host "WSL Docker is ready in $Distribution with Linux server $serverCommit ($source in $([int]$stopwatch.Elapsed.TotalSeconds)s)."