跳到主要内容

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

浏览文件

requirements.go

376 行 · 13.1 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package hostagent
5
6import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "os/exec"
12 "runtime"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/lima-vm/sshocker/pkg/ssh"
18 "github.com/sirupsen/logrus"
19
20 "github.com/lima-vm/lima/v2/pkg/limatype"
21 "github.com/lima-vm/lima/v2/pkg/sshutil"
22)
23
24func (a *HostAgent) waitForRequirements(label string, requirements []requirement) error {
25 const (
26 retries = 200
27 sleepDuration = 3 * time.Second
28 )
29 var errs []error
30
31 fn := a.waitForRequirement
32 if *a.instConfig.OS == limatype.WINDOWS {
33 fn = a.waitForWinRequirement
34 }
35
36 for i, req := range requirements {
37 logrus.Infof("Waiting for the %s requirement %d of %d: %#q", label, i+1, len(requirements), req.description)
38 retryLoop:
39 for j := range retries {
40 err := fn(req)
41 if err == nil {
42 logrus.Infof("The %s requirement %d of %d is satisfied", label, i+1, len(requirements))
43 break retryLoop
44 }
45 if req.fatal {
46 logrus.Infof("No further %s requirements will be checked", label)
47 errs = append(errs, fmt.Errorf("failed to satisfy the %s requirement %d of %d %#q: %s; skipping further checks: %w", label, i+1, len(requirements), req.description, req.debugHint, err))
48 return errors.Join(errs...)
49 }
50 if j == retries-1 {
51 errs = append(errs, fmt.Errorf("failed to satisfy the %s requirement %d of %d %#q: %s: %w", label, i+1, len(requirements), req.description, req.debugHint, err))
52 break retryLoop
53 }
54 time.Sleep(sleepDuration)
55 }
56 }
57 return errors.Join(errs...)
58}
59
60// prefixExportParam will modify a script to be executed by ssh.ExecuteScript so that it exports
61// all the variables from /mnt/lima-cidata/param.env before invoking the actual interpreter.
62//
63// - The script is executed in user mode, so needs to read the file using `sudo`.
64//
65// - `sudo cat param.env | while …; do export …; done` does not work because the piping
66// creates a subshell, and the exported variables are not visible to the parent process.
67//
68// - The `<<<"$string"` redirection is not available on alpine-lima, where /bin/bash is
69// just a wrapper around busybox ash.
70//
71// A script that will start with `#!/usr/bin/env ruby` will be modified to look like this:
72//
73// while read -r line; do
74// [ -n "$line" ] && export "$line"
75// done<<EOF
76// $(sudo cat /mnt/lima-cidata/param.env)
77// EOF
78// /usr/bin/env ruby
79//
80// ssh.ExecuteScript will strip the `#!` prefix from the first line and invoke the
81// rest of the line as the command. The full script is then passed via STDIN. We use
82// "$(printf '…')" to be able to use \n as newline escapes, to fit everything on a
83// single line:
84//
85// #!/bin/bash -c "$(printf 'while … done<<EOF\n$(sudo …)\nEOF\n/usr/bin/env ruby')"
86// #!/usr/bin/env ruby
87// …
88//
89// An earlier implementation used $'…' for quoting, but that isn't supported if the
90// user switched the default shell to fish.
91func prefixExportParam(script string, guestOS *limatype.OS) (string, error) {
92 interpreter, err := ssh.ParseScriptInterpreter(script)
93 if err != nil {
94 return "", err
95 }
96
97 // TODO we should have a symbolic constant for `/mnt/lima-cidata`
98 cidata := "/mnt/lima-cidata"
99 sudo := "sudo"
100 if guestOS != nil && *guestOS == limatype.DARWIN {
101 cidata = "/Volumes/cidata"
102 // On macOS, /Volumes/cidata is not mounted as "root access only".
103 // FIXME: The cidata does not need to be root-only on Linux, either?
104 sudo = ""
105 }
106 exportParam := `param_env="$(` + sudo + ` cat ` + cidata + `/param.env)"; while read -r line; do [ -n "$line" ] && export "$line"; done<<EOF\n${param_env}\nEOF\n`
107
108 // double up all '%' characters so we can pass them through unchanged in the format string of printf
109 interpreter = strings.ReplaceAll(interpreter, "%", "%%")
110 exportParam = strings.ReplaceAll(exportParam, "%", "%%")
111 // strings will be interpolated into single-quoted strings, so protect any existing single quotes
112 interpreter = strings.ReplaceAll(interpreter, "'", `'"'"'`)
113 exportParam = strings.ReplaceAll(exportParam, "'", `'"'"'`)
114 return fmt.Sprintf("#!/bin/bash -c \"$(printf '%s%s')\"\n%s", exportParam, interpreter, script), nil
115}
116
117func (a *HostAgent) bashAvailable() bool {
118 return *a.instConfig.OS != limatype.FREEBSD && *a.instConfig.OS != limatype.WINDOWS
119}
120
121func (a *HostAgent) waitForRequirement(r requirement) error {
122 logrus.Debugf("executing script %#q", r.description)
123 script := r.script
124 if a.bashAvailable() {
125 var err error
126 // FIXME: prefixExportParam depends on bash
127 script, err = prefixExportParam(r.script, a.instConfig.OS)
128 if err != nil {
129 return err
130 }
131 }
132 sshConfig := a.sshConfig
133 if r.noMaster || runtime.GOOS == "windows" {
134 // Remove ControlMaster, ControlPath, and ControlPersist options,
135 // because Cygwin-based SSH clients do not support multiplexing when executing commands.
136 // References:
137 // https://inbox.sourceware.org/cygwin/[email protected]/T/
138 // https://stackoverflow.com/questions/20959792/is-ssh-controlmaster-with-cygwin-on-windows-actually-possible
139 // By removing these options:
140 // - Avoids execution failures when the control master is not yet available.
141 // - Prevents error messages such as:
142 // > mux_client_request_session: read from master failed: Connection reset by peer
143 // > ControlSocket ....sock already exists, disabling multiplexing
144 // > mm_send_fd: sendmsg(2): Connection reset by peer\\r\\nmux_client_request_session: send fds failed\\r\\n
145 sshConfig = &ssh.SSHConfig{
146 ConfigFile: sshConfig.ConfigFile,
147 Persist: false,
148 AdditionalArgs: sshutil.DisableControlMasterOptsFromSSHArgs(sshConfig.AdditionalArgs),
149 }
150 }
151 stdout, stderr, err := ssh.ExecuteScript(a.instSSHAddress, a.sshLocalPort, sshConfig, script, r.description)
152 logrus.Debugf("stdout=%#q, stderr=%#q, err=%v", stdout, stderr, err)
153 if err != nil {
154 return fmt.Errorf("stdout=%#q, stderr=%#q: %w", stdout, stderr, err)
155 }
156 return nil
157}
158
159// This function is copied from sshocker's ExecuteScript, because
160// the function doesn't support Windows commands.
161// TODO: Support Windows on sshocker, and replace this function.
162func (a *HostAgent) waitForWinRequirement(r requirement) error {
163 logrus.Debugf("executing script for windows %q", r.description)
164 script := r.script
165 sshConfig := a.sshConfig
166 if r.noMaster || runtime.GOOS == "windows" {
167 // Remove ControlMaster, ControlPath, and ControlPersist options,
168 // because Cygwin-based SSH clients do not support multiplexing when executing commands.
169 // References:
170 // https://inbox.sourceware.org/cygwin/[email protected]/T/
171 // https://stackoverflow.com/questions/20959792/is-ssh-controlmaster-with-cygwin-on-windows-actually-possible
172 // By removing these options:
173 // - Avoids execution failures when the control master is not yet available.
174 // - Prevents error messages such as:
175 // > mux_client_request_session: read from master failed: Connection reset by peer
176 // > ControlSocket ....sock already exists, disabling multiplexing
177 // > mm_send_fd: sendmsg(2): Connection reset by peer\\r\\nmux_client_request_session: send fds failed\\r\\n
178 sshConfig = &ssh.SSHConfig{
179 ConfigFile: sshConfig.ConfigFile,
180 Persist: false,
181 AdditionalArgs: sshutil.DisableControlMasterOptsFromSSHArgs(sshConfig.AdditionalArgs),
182 }
183 }
184 if sshConfig == nil {
185 return errors.New("got nil SSHConfig")
186 }
187 sshBinary := sshConfig.Binary()
188 sshArgs := sshConfig.Args()
189 if a.sshLocalPort != 0 {
190 sshArgs = append(sshArgs, "-p", strconv.Itoa(a.sshLocalPort))
191 }
192 sshArgs = append(sshArgs, a.instSSHAddress, "--", script)
193 sshCmd := exec.CommandContext(context.Background(), sshBinary, sshArgs...)
194 sshCmd.Stdin = strings.NewReader(script)
195 var stderr bytes.Buffer
196 sshCmd.Stderr = &stderr
197 logrus.Debugf("executing ssh for script :%s %v", sshCmd.Path, sshCmd.Args)
198 out, err := sshCmd.Output()
199 if err != nil {
200 return fmt.Errorf("failed to execute script: stdout=%q, stderr=%q: %w", string(out), stderr.String(), err)
201 }
202 return nil
203}
204
205type requirement struct {
206 description string
207 script string
208 debugHint string
209 fatal bool
210 noMaster bool
211}
212
213func (a *HostAgent) essentialRequirements() []requirement {
214 req := make([]requirement, 0)
215 req = append(req,
216 requirement{
217 description: "ssh",
218 script: `#!/bin/sh
219true
220`,
221 debugHint: `Failed to SSH into the guest.
222Make sure that the YAML field "ssh.localPort" is not used by other processes on the host.
223If any private key under ~/.ssh is protected with a passphrase, you need to have ssh-agent to be running.
224`,
225 noMaster: true,
226 })
227 startControlMasterReq := requirement{
228 description: "Explicitly start ssh ControlMaster",
229 script: `#!/bin/sh
230true
231`,
232 debugHint: `The persistent ssh ControlMaster should be started immediately.`,
233 }
234 if *a.instConfig.Plain || *a.instConfig.OS != limatype.LINUX {
235 req = append(req, startControlMasterReq)
236 return req
237 }
238 req = append(req,
239 requirement{
240 description: "user session is ready for ssh",
241 script: fmt.Sprintf(`#!/bin/sh
242set -eux
243[ "$(cat /run/lima-ssh-ready 2>/dev/null)" = "%s" ]
244`, a.iid),
245 debugHint: `The boot sequence will terminate any existing user session after updating
246/etc/environment to make sure the session includes the new values.
247Terminating the session will break the persistent SSH tunnel, so
248it must not be created until the session reset is done.
249`,
250 noMaster: true,
251 })
252
253 if *a.instConfig.MountType == limatype.REVSSHFS && len(a.instConfig.Mounts) > 0 {
254 req = append(req, requirement{
255 description: "sshfs binary to be installed",
256 script: `#!/bin/sh
257set -eux
258command -v sshfs
259`,
260 debugHint: `The sshfs binary was not installed in the guest.
261Make sure that you are using an officially supported image.
262Also see "/var/log/cloud-init-output.log" in the guest.
263A possible workaround is to run "apt-get install sshfs" in the guest.
264`,
265 })
266 req = append(req, requirement{
267 description: "fuse to allow_other as user",
268 script: fmt.Sprintf(`#!/bin/sh
269set -eux
270[ "$(cat /run/lima-fuse-ready 2>/dev/null)" = "%s" ]
271`, a.iid),
272 debugHint: `Waiting for /run/lima-fuse-ready to be created by the boot scripts.`,
273 })
274 } else {
275 req = append(req, startControlMasterReq)
276 }
277 return req
278}
279
280func (a *HostAgent) essentialWinRequirements() []requirement {
281 req := make([]requirement, 0)
282 req = append(req,
283 requirement{
284 description: "ssh",
285 script: `PowerShell.exe -NoProfile -NonInteractive -Command "if (Test-Path -Path 'C:\ProgramData\Lima\lima-boot-done.txt' -PathType Leaf) { exit 0 } else { exit 1 }"`,
286 debugHint: `Failed to SSH into the guest.
287Make sure that the YAML field "ssh.localPort" is not used by other processes on the host.
288If any private key under ~/.ssh is protected with a passphrase, you need to have ssh-agent to be running.
289`,
290 noMaster: true,
291 },
292 )
293
294 return req
295}
296
297func (a *HostAgent) optionalRequirements() []requirement {
298 req := make([]requirement, 0)
299 isLinuxGuest := a.instConfig.OS == nil || *a.instConfig.OS == limatype.LINUX
300 if isLinuxGuest && (*a.instConfig.Containerd.System || *a.instConfig.Containerd.User) && !*a.instConfig.Plain {
301 req = append(req,
302 requirement{
303 description: "systemd must be available",
304 fatal: true,
305 script: `#!/bin/bash
306set -eux -o pipefail
307if ! command -v systemctl 2>&1 >/dev/null; then
308 echo >&2 "systemd is not available on this OS"
309 exit 1
310fi
311`,
312 debugHint: `systemd is required to run containerd, but does not seem to be available.
313Make sure that you use an image that supports systemd. If you do not want to run
314containerd, please make sure that both 'container.system' and 'containerd.user'
315are set to 'false' in the config file.
316`,
317 },
318 requirement{
319 description: "containerd binaries to be installed",
320 script: `#!/bin/sh
321set -eux
322command -v nerdctl || test -x ` + *a.instConfig.GuestInstallPrefix + `/bin/nerdctl
323`,
324 debugHint: `The nerdctl binary was not installed in the guest.
325Make sure that you are using an officially supported image.
326Also see "/var/log/cloud-init-output.log" in the guest.
327`,
328 })
329 }
330 for _, probe := range a.instConfig.Probes {
331 if probe.Mode == limatype.ProbeModeReadiness {
332 req = append(req, requirement{
333 description: probe.Description,
334 script: *probe.Script,
335 debugHint: probe.Hint,
336 })
337 }
338 }
339 return req
340}
341
342func (a *HostAgent) optionalWinRequirements() []requirement {
343 req := make([]requirement, 0)
344 return req
345}
346
347func (a *HostAgent) finalRequirements() []requirement {
348 req := make([]requirement, 0)
349 logLocation := "/var/log/cloud-init-output.log in the guest"
350 if *a.instConfig.OS == limatype.DARWIN {
351 logLocation = "serialv.log in the host"
352 }
353 req = append(req,
354 requirement{
355 description: "boot scripts must have finished",
356 script: fmt.Sprintf(`#!/bin/sh
357set -eux
358BOOT_DONE=/run/lima-boot-done
359UNAME="$(uname)"
360if [ "$UNAME" = "Darwin" ] || [ "$UNAME" = "FreeBSD" ]; then
361 BOOT_DONE=/var/run/lima-boot-done
362fi
363[ "$(cat "$BOOT_DONE" 2>/dev/null)" = "%s" ]
364`, a.iid),
365 debugHint: `All boot scripts, provisioning scripts, and readiness probes must
366finish before the instance is considered "ready".
367Check "` + logLocation + `" to see where the process is blocked!
368`,
369 })
370 return req
371}
372
373func (a *HostAgent) finalWinRequirements() []requirement {
374 req := make([]requirement, 0)
375 return req
376}