-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart-vm.ps1
More file actions
280 lines (243 loc) · 9.31 KB
/
start-vm.ps1
File metadata and controls
280 lines (243 loc) · 9.31 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
$ErrorActionPreference = 'Stop'
$repoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..\..')).Path
$qemuExe = Join-Path $repoRoot 'runtime\qemu\qemu-system-x86_64.exe'
$vmImage = Join-Path $repoRoot 'runtime\linux\images\ubuntu.qcow2'
$sshPrivateKey = Join-Path $repoRoot 'runtime\linux\ssh\id_ed25519'
$sshPublicKey = Join-Path $repoRoot 'runtime\linux\ssh\id_ed25519.pub'
$metaDataTemplate = Join-Path $repoRoot 'runtime\linux\cloud-init\meta-data'
$cloudInitServerScript = Join-Path $repoRoot 'scripts\runtime\windows\cloud-init-server.ps1'
$stateDir = Join-Path $repoRoot 'state\vm'
$vmLog = Join-Path $stateDir 'qemu.log'
$vmErrLog = Join-Path $stateDir 'qemu.err.log'
$vmPid = Join-Path $stateDir 'qemu.pid'
$vmMode = Join-Path $stateDir 'qemu-mode.txt'
$sshPortFile = Join-Path $stateDir 'ssh-port.txt'
$cloudInitStateDir = Join-Path $stateDir 'cloud-init'
$cloudInitUserDataPath = Join-Path $cloudInitStateDir 'user-data'
$cloudInitMetaDataPath = Join-Path $cloudInitStateDir 'meta-data'
$cloudInitPidFile = Join-Path $stateDir 'cloud-init-http.pid'
$cloudInitPortFile = Join-Path $stateDir 'cloud-init-port.txt'
function Ensure-Dir {
param([string]$PathToCreate)
if (-not (Test-Path $PathToCreate)) {
New-Item -ItemType Directory -Path $PathToCreate -Force | Out-Null
}
}
function Get-FreeTcpPort {
param(
[int]$StartPort,
[int]$EndPort
)
for ($port = $StartPort; $port -le $EndPort; $port++) {
$listener = $null
try {
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, $port)
$listener.Start()
$listener.Stop()
return $port
} catch {
if ($listener) {
try { $listener.Stop() } catch {}
}
}
}
throw "No free TCP port found in range $StartPort-$EndPort"
}
function Get-EphemeralTcpPort {
$listener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Loopback, 0)
try {
$listener.Start()
$endpoint = [System.Net.IPEndPoint]$listener.LocalEndpoint
return $endpoint.Port
} finally {
try { $listener.Stop() } catch {}
}
}
function Stop-CloudInitServer {
if (Test-Path $cloudInitPidFile) {
$raw = Get-Content $cloudInitPidFile -ErrorAction SilentlyContinue | Select-Object -First 1
if ($raw) {
$pidValue = "$raw".Trim()
if ($pidValue) {
Stop-Process -Id $pidValue -Force -ErrorAction SilentlyContinue
}
}
}
Remove-Item $cloudInitPidFile -ErrorAction SilentlyContinue
Remove-Item $cloudInitPortFile -ErrorAction SilentlyContinue
}
function Write-CloudInitSeed {
param(
[string]$PublicKey,
[string]$UserName
)
Ensure-Dir $cloudInitStateDir
$metaData = "instance-id: portable-coder-vm`nlocal-hostname: portable-coder`n"
if (Test-Path $metaDataTemplate) {
$metaData = Get-Content $metaDataTemplate -Raw
if (-not $metaData.Trim()) {
$metaData = "instance-id: portable-coder-vm`nlocal-hostname: portable-coder`n"
}
}
$metaData | Out-File -Encoding ascii -FilePath $cloudInitMetaDataPath
$userData = @"
#cloud-config
users:
- name: $UserName
shell: /bin/bash
sudo: ALL=(ALL) NOPASSWD:ALL
lock_passwd: true
groups:
- sudo
ssh_authorized_keys:
- $PublicKey
ssh_pwauth: false
packages:
- nodejs
- npm
runcmd:
- npm install -g @openai/codex @anthropic-ai/claude-code
"@
$userData | Out-File -Encoding utf8 -FilePath $cloudInitUserDataPath
}
function Start-CloudInitServer {
param(
[int]$Port
)
$args = @(
'-NoProfile',
'-ExecutionPolicy', 'Bypass',
'-File', $cloudInitServerScript,
'-Port', "$Port",
'-Directory', $cloudInitStateDir
)
$proc = Start-Process -FilePath 'powershell' -ArgumentList $args -PassThru -WindowStyle Hidden
Start-Sleep -Seconds 1
$proc.Refresh()
if ($proc.HasExited) {
throw "cloud-init HTTP server failed to start (exit code: $($proc.ExitCode))."
}
$proc.Id | Out-File -Encoding ascii -FilePath $cloudInitPidFile
$Port | Out-File -Encoding ascii -FilePath $cloudInitPortFile
}
function Start-QemuAttempt {
param(
[string]$Mode,
[string[]]$AccelerationArgs,
[string[]]$BaseArgs,
[string]$QemuBinary,
[string]$LogPath
)
"[$(Get-Date -Format o)] launch mode: $Mode" | Out-File -Encoding utf8 -FilePath $LogPath
$args = @() + $AccelerationArgs + $BaseArgs
$process = Start-Process -FilePath $QemuBinary -ArgumentList $args -PassThru -WindowStyle Hidden -RedirectStandardOutput $LogPath -RedirectStandardError $vmErrLog
Start-Sleep -Seconds 3
$process.Refresh()
if ($process.HasExited) {
return $null
}
return $process
}
Ensure-Dir $stateDir
if (-not (Test-Path $qemuExe)) {
throw "Missing QEMU binary: $qemuExe`nRun scripts\runtime\windows\bootstrap-runtime.cmd first."
}
if (-not (Test-Path $vmImage)) {
throw "Missing VM image: $vmImage`nRun scripts\runtime\windows\bootstrap-runtime.cmd first."
}
if (-not (Test-Path $sshPrivateKey) -or -not (Test-Path $sshPublicKey)) {
throw "Missing VM SSH key pair: $sshPrivateKey`nRun scripts\runtime\windows\bootstrap-runtime.cmd first."
}
if (-not (Test-Path $cloudInitServerScript)) {
throw "Missing cloud-init server script: $cloudInitServerScript"
}
if (Test-Path $vmPid) {
$existingPidRaw = Get-Content $vmPid -ErrorAction SilentlyContinue | Select-Object -First 1
$existingPid = "$existingPidRaw".Trim()
if ($existingPid) {
$existingProcess = Get-Process -Id $existingPid -ErrorAction SilentlyContinue
if ($existingProcess) {
if (-not (Test-Path $sshPortFile)) {
throw "VM appears running (pid: $existingPid) but missing SSH port file: $sshPortFile"
}
Write-Host "VM already running (pid: $existingPid)."
exit 0
}
}
Remove-Item $vmPid -ErrorAction SilentlyContinue
Remove-Item $vmMode -ErrorAction SilentlyContinue
Remove-Item $sshPortFile -ErrorAction SilentlyContinue
}
Stop-CloudInitServer
$requestedAccelMode = if ($env:PCODER_VM_ACCEL_MODE) { "$($env:PCODER_VM_ACCEL_MODE)".ToLowerInvariant() } else { 'auto' }
if ($requestedAccelMode -ne 'auto' -and $requestedAccelMode -ne 'whpx' -and $requestedAccelMode -ne 'tcg') {
throw "Invalid PCODER_VM_ACCEL_MODE '$requestedAccelMode'. Expected one of: auto, whpx, tcg."
}
$requestedPortRaw = $env:PCODER_VM_SSH_PORT
$sshPort = 0
if ($requestedPortRaw) {
$sshPort = [int]$requestedPortRaw
} else {
$sshPort = Get-FreeTcpPort -StartPort 2222 -EndPort 2299
}
$cloudInitPort = 0
try {
$cloudInitPort = Get-FreeTcpPort -StartPort 38080 -EndPort 38120
} catch {
$cloudInitPort = Get-EphemeralTcpPort
Write-Host "Preferred cloud-init port range 38080-38120 unavailable; using ephemeral port $cloudInitPort."
}
$guestUser = if ($env:PCODER_VM_USER) { $env:PCODER_VM_USER } else { 'portable' }
$pubKeyValue = (Get-Content $sshPublicKey -Raw).Trim()
Write-CloudInitSeed -PublicKey $pubKeyValue -UserName $guestUser
Start-CloudInitServer -Port $cloudInitPort
$baseArgs = @(
'-m', '4096',
'-smp', '2',
'-drive', "file=$vmImage,if=virtio,format=qcow2",
'-netdev', "user,id=net0,hostfwd=tcp::$sshPort-:22",
'-device', 'virtio-net-pci,netdev=net0',
'-smbios', "type=1,serial=ds=nocloud-net;s=http://10.0.2.2:$cloudInitPort/"
)
if ($requestedAccelMode -eq 'whpx') {
$forcedWhpx = Start-QemuAttempt -Mode 'accelerated-whpx' -AccelerationArgs @('-accel', 'whpx') -BaseArgs $baseArgs -QemuBinary $qemuExe -LogPath $vmLog
if ($forcedWhpx) {
$forcedWhpx.Id | Out-File -Encoding ascii -FilePath $vmPid
'accelerated-whpx' | Out-File -Encoding ascii -FilePath $vmMode
$sshPort | Out-File -Encoding ascii -FilePath $sshPortFile
Write-Host "VM started in forced accelerated mode (whpx). PID: $($forcedWhpx.Id). SSH port: $sshPort"
exit 0
}
Stop-CloudInitServer
throw "Failed to start VM in forced whpx mode. Check log: $vmLog"
}
if ($requestedAccelMode -eq 'tcg') {
$forcedTcg = Start-QemuAttempt -Mode 'portable-forced-tcg' -AccelerationArgs @('-accel', 'tcg') -BaseArgs $baseArgs -QemuBinary $qemuExe -LogPath $vmLog
if ($forcedTcg) {
$forcedTcg.Id | Out-File -Encoding ascii -FilePath $vmPid
'portable-fallback-tcg' | Out-File -Encoding ascii -FilePath $vmMode
$sshPort | Out-File -Encoding ascii -FilePath $sshPortFile
Write-Host "VM started in forced portable mode (tcg). PID: $($forcedTcg.Id). SSH port: $sshPort"
exit 0
}
Stop-CloudInitServer
throw "Failed to start VM in forced tcg mode. Check log: $vmLog"
}
$accelerated = Start-QemuAttempt -Mode 'accelerated-whpx' -AccelerationArgs @('-accel', 'whpx') -BaseArgs $baseArgs -QemuBinary $qemuExe -LogPath $vmLog
if ($accelerated) {
$accelerated.Id | Out-File -Encoding ascii -FilePath $vmPid
'accelerated-whpx' | Out-File -Encoding ascii -FilePath $vmMode
$sshPort | Out-File -Encoding ascii -FilePath $sshPortFile
Write-Host "VM started in accelerated mode (whpx). PID: $($accelerated.Id). SSH port: $sshPort"
exit 0
}
$fallback = Start-QemuAttempt -Mode 'portable-fallback-tcg' -AccelerationArgs @('-accel', 'tcg') -BaseArgs $baseArgs -QemuBinary $qemuExe -LogPath $vmLog
if ($fallback) {
$fallback.Id | Out-File -Encoding ascii -FilePath $vmPid
'portable-fallback-tcg' | Out-File -Encoding ascii -FilePath $vmMode
$sshPort | Out-File -Encoding ascii -FilePath $sshPortFile
Write-Host "VM started in portable fallback mode (tcg). PID: $($fallback.Id). SSH port: $sshPort"
exit 0
}
Stop-CloudInitServer
throw "Failed to start VM in both accelerated (whpx) and fallback (tcg) modes. Check log: $vmLog"