跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

vm_windows.go

291 行 · 8.9 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package wsl2
5
6import (
7 "context"
8 _ "embed"
9 "fmt"
10 "net"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "regexp"
15 "strconv"
16 "strings"
17
18 "github.com/sirupsen/logrus"
19
20 "github.com/lima-vm/lima/v2/pkg/executil"
21 "github.com/lima-vm/lima/v2/pkg/limatype"
22 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
23 "github.com/lima-vm/lima/v2/pkg/textutil"
24)
25
26// startVM calls WSL to start a VM.
27func startVM(ctx context.Context, distroName string) error {
28 out, err := executil.RunUTF16leCommand([]string{
29 "wsl.exe",
30 "--distribution",
31 distroName,
32 }, executil.WithContext(ctx))
33 if err != nil {
34 return fmt.Errorf("failed to run `wsl.exe --distribution %s`: %w (out=%#q)",
35 distroName, err, out)
36 }
37 return nil
38}
39
40// initVM calls WSL to import a new VM specifically for Lima.
41func initVM(ctx context.Context, instanceDir, distroName string) error {
42 baseDisk := filepath.Join(instanceDir, filenames.BaseDiskLegacy)
43 logrus.Infof("Importing distro from %#q to %#q", baseDisk, instanceDir)
44 out, err := executil.RunUTF16leCommand([]string{
45 "wsl.exe",
46 "--import",
47 distroName,
48 instanceDir,
49 baseDisk,
50 }, executil.WithContext(ctx))
51 if err != nil {
52 return fmt.Errorf("failed to run `wsl.exe --import %s %s %s`: %w (out=%#q)",
53 distroName, instanceDir, baseDisk, err, out)
54 }
55 return nil
56}
57
58// stopVM calls WSL to stop a running VM.
59func stopVM(ctx context.Context, distroName string) error {
60 out, err := executil.RunUTF16leCommand([]string{
61 "wsl.exe",
62 "--terminate",
63 distroName,
64 }, executil.WithContext(ctx))
65 if err != nil {
66 return fmt.Errorf("failed to run `wsl.exe --terminate %s`: %w (out=%#q)",
67 distroName, err, out)
68 }
69 return nil
70}
71
72//go:embed lima-init.TEMPLATE
73var limaBoot string
74
75// provisionVM starts Lima's boot process inside an already imported VM.
76func provisionVM(ctx context.Context, instanceDir, instanceName, distroName string, errCh chan<- error) error {
77 ciDataPath := filepath.Join(instanceDir, filenames.CIDataISODir)
78 m := map[string]string{
79 "CIDataPath": ciDataPath,
80 }
81 limaBootB, err := textutil.ExecuteTemplate(limaBoot, m)
82 if err != nil {
83 return fmt.Errorf("failed to construct wsl boot.sh script: %w", err)
84 }
85 limaBootFile, err := os.CreateTemp("", "lima-wsl2-boot-*.sh")
86 if err != nil {
87 return err
88 }
89 if _, err = limaBootFile.Write(limaBootB); err != nil {
90 limaBootFile.Close()
91 return err
92 }
93 limaBootFileWinPath := limaBootFile.Name()
94 if err = limaBootFile.Close(); err != nil {
95 return err
96 }
97 // path should be quoted and use \\ as separator
98 bootFileWSLPath := strconv.Quote(limaBootFileWinPath)
99 limaBootFilePathOnLinuxB, err := exec.CommandContext(
100 ctx,
101 "wsl.exe",
102 "-d",
103 distroName,
104 "bash",
105 "-c",
106 fmt.Sprintf("wslpath -u %s", bootFileWSLPath),
107 bootFileWSLPath,
108 ).Output()
109 if err != nil {
110 os.RemoveAll(limaBootFileWinPath)
111 // this can return an error with an exit code, which causes it not to be logged
112 // because main.handleExitCoder() traps it, so wrap the error
113 return fmt.Errorf("failed to run wslpath command: %w", err)
114 }
115 limaBootFileLinuxPath := strings.TrimSpace(string(limaBootFilePathOnLinuxB))
116 go func() {
117 cmd := exec.CommandContext(
118 ctx,
119 "wsl.exe",
120 "-d",
121 distroName,
122 "bash",
123 "-c",
124 limaBootFileLinuxPath,
125 )
126 out, err := cmd.CombinedOutput()
127 os.RemoveAll(limaBootFileWinPath)
128 logrus.Debugf("%v: %#q", cmd.Args, string(out))
129 if err != nil {
130 errCh <- fmt.Errorf(
131 "error running wslCommand that executes boot.sh (%v): %w, "+
132 "check /var/log/lima-init.log for more details (out=%#q)", cmd.Args, err, string(out))
133 }
134
135 <-ctx.Done()
136 logrus.Info("Context closed, stopping vm")
137 if status, err := getWslStatus(ctx, instanceName); err == nil &&
138 status == limatype.StatusRunning {
139 _ = stopVM(ctx, distroName)
140 }
141 }()
142
143 return err
144}
145
146// keepAlive runs a background process which in order to keep the WSL2 VM running in the background after launch.
147func keepAlive(ctx context.Context, distroName string, errCh chan<- error) {
148 keepAliveCmd := exec.CommandContext(
149 ctx,
150 "wsl.exe",
151 "-d",
152 distroName,
153 "bash",
154 "-c",
155 "nohup sleep 2147483647d >/dev/null 2>&1",
156 )
157
158 go func() {
159 if err := keepAliveCmd.Run(); err != nil {
160 errCh <- fmt.Errorf(
161 "error running wsl keepAlive command: %w", err)
162 }
163 }()
164}
165
166// unregisterVM calls WSL to unregister a VM.
167func unregisterVM(ctx context.Context, distroName string) error {
168 logrus.Info("Unregistering WSL2 VM")
169 out, err := executil.RunUTF16leCommand([]string{
170 "wsl.exe",
171 "--unregister",
172 distroName,
173 }, executil.WithContext(ctx))
174 if err != nil {
175 return fmt.Errorf("failed to run `wsl.exe --unregister %s`: %w (out=%#q)",
176 distroName, err, out)
177 }
178 return nil
179}
180
181// GetWslStatus runs `wsl --list --verbose` and parses its output.
182// There are several possible outputs, all listed with their whitespace preserved output below.
183//
184// (1) Expected output if at least one distro is installed:
185// PS > wsl --list --verbose
186//
187// NAME STATE VERSION
188//
189// * Ubuntu Stopped 2
190//
191// (2) Expected output when no distros are installed, but WSL is configured properly:
192// PS > wsl --list --verbose
193// Windows Subsystem for Linux has no installed distributions.
194//
195// Use 'wsl.exe --list --online' to list available distributions
196// and 'wsl.exe --install <Distro>' to install.
197//
198// Distributions can also be installed by visiting the Microsoft Store:
199// https://aka.ms/wslstore
200// Error code: Wsl/WSL_E_DEFAULT_DISTRO_NOT_FOUND
201//
202// (3) Expected output when no distros are installed, and WSL2 has no kernel installed:
203//
204// PS > wsl --list --verbose
205// Windows Subsystem for Linux has no installed distributions.
206// Distributions can be installed by visiting the Microsoft Store:
207// https://aka.ms/wslstore
208func getWslStatus(ctx context.Context, instName string) (string, error) {
209 distroName := "lima-" + instName
210 out, err := executil.RunUTF16leCommand([]string{
211 "wsl.exe",
212 "--list",
213 "--verbose",
214 }, executil.WithContext(ctx))
215 if err != nil {
216 return "", fmt.Errorf("failed to run `wsl --list --verbose`, err: %w (out=%#q)", err, out)
217 }
218
219 if out == "" {
220 return limatype.StatusBroken, fmt.Errorf("failed to read instance state for instance %#q, try running `wsl --list --verbose` to debug, err: %w", instName, err)
221 }
222
223 // Check for edge cases first
224 if strings.Contains(out, "Windows Subsystem for Linux has no installed distributions.") {
225 if strings.Contains(out, "Wsl/WSL_E_DEFAULT_DISTRO_NOT_FOUND") {
226 return limatype.StatusBroken, fmt.Errorf(
227 "failed to read instance state for instance %#q because no distro is installed,"+
228 "try running `wsl --install -d Ubuntu` and then re-running Lima", instName)
229 }
230 return limatype.StatusBroken, fmt.Errorf(
231 "failed to read instance state for instance %#q because there is no WSL kernel installed,"+
232 "this usually happens when WSL was installed for another user, but never for your user."+
233 "Try running `wsl --install -d Ubuntu` and `wsl --update`, and then re-running Lima", instName)
234 }
235
236 var instState string
237 wslListColsRegex := regexp.MustCompile(`\s+`)
238 // wsl --list --verbose may have different headers depending on localization, just split by line
239 for rows := range strings.SplitSeq(strings.ReplaceAll(out, "\r\n", "\n"), "\n") {
240 cols := wslListColsRegex.Split(strings.TrimSpace(rows), -1)
241 nameIdx := 0
242 // '*' indicates default instance
243 if cols[0] == "*" {
244 nameIdx = 1
245 }
246 if cols[nameIdx] == distroName {
247 instState = cols[nameIdx+1]
248 break
249 }
250 }
251
252 if instState == "" {
253 return limatype.StatusUninitialized, nil
254 }
255
256 return instState, nil
257}
258
259// GetSSHAddress runs a hostname command to get the IP from inside of a wsl2 VM.
260//
261// Expected output (whitespace preserved, [] for optional):
262// PS > wsl -d <distroName> bash -c hostname -I | cut -d' ' -f1
263// 168.1.1.1 [10.0.0.1]
264// But busybox hostname does not implement --all-ip-addresses:
265// hostname: unrecognized option: I
266func getSSHAddress(ctx context.Context, instName string) (string, error) {
267 distroName := "lima-" + instName
268 // Ubuntu
269 cmd := exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "bash", "-c", `hostname -I | cut -d ' ' -f1`)
270 out, err := cmd.CombinedOutput()
271 if err == nil {
272 return strings.TrimSpace(string(out)), nil
273 }
274 // Alpine
275 cmd = exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "sh", "-c", `ip route get 1 | awk '{gsub("^.*src ",""); print $1; exit}'`)
276 out, err = cmd.CombinedOutput()
277 if err == nil {
278 return strings.TrimSpace(string(out)), nil
279 }
280 // fallback
281 cmd = exec.CommandContext(ctx, "wsl.exe", "-d", distroName, "hostname", "-i")
282 out, err = cmd.CombinedOutput()
283 if err == nil {
284 ip := net.ParseIP(strings.TrimSpace(string(out)))
285 // some distributions use "127.0.1.1" as the host IP, but we want something that we can route to here
286 if ip != nil && !ip.IsLoopback() {
287 return strings.TrimSpace(string(out)), nil
288 }
289 }
290 return "", fmt.Errorf("failed to get hostname for instance %#q, err: %w (out=%#q)", instName, err, string(out))
291}