跳到主要内容

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

浏览文件

start.go

568 行 · 17.4 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package instance
5
6import (
7 "bufio"
8 "bytes"
9 "context"
10 "errors"
11 "fmt"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "text/template"
16 "time"
17
18 "github.com/docker/go-units"
19 "github.com/lima-vm/go-qcow2reader"
20 "github.com/lima-vm/go-qcow2reader/image/vhdx"
21 "github.com/sirupsen/logrus"
22
23 "github.com/lima-vm/lima/v2/pkg/autostart"
24 "github.com/lima-vm/lima/v2/pkg/cacheutil"
25 "github.com/lima-vm/lima/v2/pkg/driver"
26 "github.com/lima-vm/lima/v2/pkg/driverutil"
27 "github.com/lima-vm/lima/v2/pkg/executil"
28 "github.com/lima-vm/lima/v2/pkg/fileutils"
29 hostagentevents "github.com/lima-vm/lima/v2/pkg/hostagent/events"
30 "github.com/lima-vm/lima/v2/pkg/imgutil/proxyimgutil"
31 "github.com/lima-vm/lima/v2/pkg/limatype"
32 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
33 "github.com/lima-vm/lima/v2/pkg/limayaml"
34 "github.com/lima-vm/lima/v2/pkg/osutil"
35 "github.com/lima-vm/lima/v2/pkg/registry"
36 "github.com/lima-vm/lima/v2/pkg/store"
37 "github.com/lima-vm/lima/v2/pkg/usrlocal"
38)
39
40// DefaultWatchHostAgentEventsTimeout is the duration to wait for the instance
41// to be running before timing out.
42const DefaultWatchHostAgentEventsTimeout = 10 * time.Minute
43
44// Since the initial boot of Windows usually takes longer than DefaultWatchHostAgentEventsTimeout,
45// use a windows-specific default timeout duration.
46const WinDefaultWatchHostAgentEventsTimeout = 30 * time.Minute
47
48type Prepared struct {
49 Driver driver.Driver
50 GuestAgent string
51 NerdctlArchiveCache string
52}
53
54// Prepare ensures the disk, the nerdctl archive, etc.
55func Prepare(ctx context.Context, inst *limatype.Instance, guestAgent string) (*Prepared, error) {
56 var needsGuestAgent bool
57 switch *inst.Config.OS {
58 case limatype.DARWIN:
59 // macOS guests always need the guest agent for running fake-cloud-init
60 needsGuestAgent = true
61 case limatype.FREEBSD, limatype.WINDOWS:
62 // guest agent is not implemented for FreeBSD and Windows yet
63 needsGuestAgent = false
64 default:
65 needsGuestAgent = !*inst.Config.Plain
66 }
67 if needsGuestAgent && guestAgent == "" {
68 var err error
69 guestAgent, err = usrlocal.GuestAgentBinary(*inst.Config.OS, *inst.Config.Arch)
70 if err != nil {
71 return nil, err
72 }
73 }
74 limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0)
75 if err != nil {
76 return nil, fmt.Errorf("failed to create driver instance: %w", err)
77 }
78 if err := limayaml.Validate(inst.Config, true); err != nil {
79 return nil, fmt.Errorf("failed to validate the instance YAML after filling defaults: %w", err)
80 }
81
82 if err := limaDriver.Validate(ctx); err != nil {
83 return nil, err
84 }
85
86 if err := limaDriver.Create(ctx); err != nil {
87 return nil, err
88 }
89
90 // Migrate legacy disk layout (diffdisk → disk, ISO basedisk → iso)
91 if err := driverutil.MigrateDiskLayout(inst.Dir); err != nil {
92 return nil, err
93 }
94
95 supportedImageFormats := limaDriver.Info(ctx).Features.SupportedImageFormats
96
97 created := limayaml.IsExistingInstanceDir(inst.Dir)
98
99 imagePath := filepath.Join(inst.Dir, filenames.Image)
100 disk := filepath.Join(inst.Dir, filenames.Disk)
101 kernel := filepath.Join(inst.Dir, filenames.Kernel)
102 kernelCmdline := filepath.Join(inst.Dir, filenames.KernelCmdline)
103 initrd := filepath.Join(inst.Dir, filenames.Initrd)
104 if !osutil.FileExists(imagePath) && !osutil.FileExists(disk) {
105 var ensuredImage bool
106 var targetVariant, targetArchVariant string
107 var targetVariantSet bool
108 for _, img := range inst.Config.Images {
109 if img.Arch == *inst.Config.Arch {
110 targetVariant = img.Variant
111 targetArchVariant = img.ArchVariant
112 targetVariantSet = true
113 break
114 }
115 }
116
117 if len(inst.Config.Images) == 0 {
118 return nil, errors.New("no images are configured (did you set --image-variant or --arch-variant to a value not present in the template?)")
119 }
120 errs := make([]error, len(inst.Config.Images))
121 for i, f := range inst.Config.Images {
122 if targetVariantSet && f.Variant != targetVariant {
123 errs[i] = fmt.Errorf("%w: variant mismatch (expected %q, got %q)", fileutils.ErrSkipped, targetVariant, f.Variant)
124 continue
125 }
126 if targetVariantSet && f.ArchVariant != targetArchVariant {
127 errs[i] = fmt.Errorf("%w: archVariant mismatch (expected %q, got %q)", fileutils.ErrSkipped, targetArchVariant, f.ArchVariant)
128 continue
129 }
130 if _, err := fileutils.DownloadFile(ctx, imagePath, f.File, true, "the image", *inst.Config.Arch, supportedImageFormats); err != nil {
131 errs[i] = err
132 continue
133 }
134 if f.Kernel != nil {
135 // ensure decompress kernel because vz expects it to be decompressed
136 if _, err := fileutils.DownloadFile(ctx, kernel, f.Kernel.File, true, "the kernel", *inst.Config.Arch, nil); err != nil {
137 errs[i] = err
138 continue
139 }
140 if f.Kernel.Cmdline != "" {
141 if err := os.WriteFile(kernelCmdline, []byte(f.Kernel.Cmdline), 0o644); err != nil {
142 errs[i] = err
143 continue
144 }
145 }
146 }
147 if f.Initrd != nil {
148 // vz does not need initrd to be decompressed
149 if _, err := fileutils.DownloadFile(ctx, initrd, *f.Initrd, false, "the initrd", *inst.Config.Arch, nil); err != nil {
150 errs[i] = err
151 continue
152 }
153 }
154 ensuredImage = true
155 break
156 }
157 if !ensuredImage {
158 return nil, fileutils.Errors(errs)
159 }
160 }
161
162 if *inst.Config.OS == limatype.WINDOWS {
163 var winOpts limatype.WindowsOpts
164 if err := limayaml.Convert(inst.Config.OsOpts[limatype.WINDOWS], &winOpts, "osOpts.Windows"); err != nil {
165 return nil, err
166 }
167
168 if len(winOpts.VirtioWin) > 0 {
169 ensuredImage := false
170 errs := make([]error, len(winOpts.VirtioWin))
171 virtioWin := filepath.Join(inst.Dir, filenames.VirtioWin)
172 for i, f := range winOpts.VirtioWin {
173 if _, err := fileutils.DownloadFile(ctx, virtioWin, f, true, "virtio-win", *inst.Config.Arch, nil); err != nil {
174 errs[i] = err
175 continue
176 }
177 ensuredImage = true
178 break
179 }
180 if !ensuredImage {
181 return nil, fileutils.Errors(errs)
182 }
183 }
184 }
185
186 if os.Getenv("CAGE_SETUP_PROGRESS") == "1" {
187 fmt.Fprintln(os.Stderr, "CAGE_IMAGE_READY")
188 }
189 if err := limaDriver.CreateDisk(ctx); err != nil {
190 return nil, err
191 }
192
193 // Ensure disk size matches the configured value
194 if err := prepareDisk(ctx, inst); err != nil {
195 return nil, err
196 }
197
198 nerdctlArchiveCache, err := cacheutil.EnsureNerdctlArchiveCache(ctx, inst.Config, created)
199 if err != nil {
200 return nil, err
201 }
202
203 return &Prepared{
204 Driver: limaDriver,
205 GuestAgent: guestAgent,
206 NerdctlArchiveCache: nerdctlArchiveCache,
207 }, nil
208}
209
210// StartWithPaths starts the hostagent in the background, which in turn will start the instance.
211// StartWithPaths will listen to hostagent events and log them to STDOUT until either the instance
212// is running, or has failed to start.
213//
214// The launchHostAgentForeground argument makes the hostagent run in the foreground.
215// The function will continue to listen and log hostagent events until the instance is
216// shut down again.
217//
218// The showProgress argument tells the hostagent to show provision script progress by tailing cloud-init logs.
219//
220// The limactl argument allows the caller to specify the full path of the limactl executable.
221// The guestAgent argument allows the caller to specify the full path of the guest agent executable.
222// Inside limactl this function is only called by Start, which passes empty strings for both
223// limactl and guestAgent, in which case the location of the current executable is used for
224// limactl and the guest agent is located from the corresponding <prefix>/share/lima directory.
225//
226// StartWithPaths calls Prepare by itself, so you do not need to call Prepare manually before calling Start.
227func StartWithPaths(ctx context.Context, inst *limatype.Instance, launchHostAgentForeground, showProgress bool, limactl, guestAgent string) error {
228 haPIDPath := filepath.Join(inst.Dir, filenames.HostAgentPID)
229 // ReadPIDFile removes the PID file when it was left behind by a process that is not
230 // running anymore, or by a previous boot of the host.
231 if haPID, err := store.ReadPIDFile(haPIDPath); err != nil {
232 return err
233 } else if haPID != 0 {
234 return fmt.Errorf("instance %#q seems running (hint: remove %#q if the instance is not actually running)", inst.Name, haPIDPath)
235 }
236 logrus.Infof("Starting the instance %#q with %s VM driver %#q", inst.Name, registry.CheckInternalOrExternal(inst.VMType), inst.VMType)
237
238 haSockPath := filepath.Join(inst.Dir, filenames.HostAgentSock)
239
240 prepared, err := Prepare(ctx, inst, guestAgent)
241 if err != nil {
242 return err
243 }
244
245 if limactl == "" {
246 limactl, err = os.Executable()
247 if err != nil {
248 return err
249 }
250 }
251 haStdoutPath := filepath.Join(inst.Dir, filenames.HostAgentStdoutLog)
252 haStderrPath := filepath.Join(inst.Dir, filenames.HostAgentStderrLog)
253
254 begin := time.Now() // used for logrus propagation
255 var haCmd *exec.Cmd
256 if isRegisteredToAutoStart, err := autostart.IsRegistered(ctx, inst); err != nil && !errors.Is(err, autostart.ErrNotSupported) {
257 return fmt.Errorf("failed to check autostart registration: %w", err)
258 } else if !isRegisteredToAutoStart || launchHostAgentForeground {
259 if err := os.RemoveAll(haStdoutPath); err != nil {
260 return err
261 }
262 if err := os.RemoveAll(haStderrPath); err != nil {
263 return err
264 }
265 haStdoutW, err := os.Create(haStdoutPath)
266 if err != nil {
267 return err
268 }
269 // no defer haStdoutW.Close()
270 haStderrW, err := os.Create(haStderrPath)
271 if err != nil {
272 return err
273 }
274 // no defer haStderrW.Close()
275
276 var args []string
277 if logrus.GetLevel() >= logrus.DebugLevel {
278 args = append(args, "--debug")
279 }
280 args = append(args,
281 "hostagent",
282 "--pidfile", haPIDPath,
283 "--socket", haSockPath)
284 if prepared.Driver.Info(ctx).Features.CanRunGUI {
285 args = append(args, "--run-gui")
286 }
287 if prepared.GuestAgent != "" {
288 args = append(args, "--guestagent", prepared.GuestAgent)
289 }
290 if prepared.NerdctlArchiveCache != "" {
291 args = append(args, "--nerdctl-archive", prepared.NerdctlArchiveCache)
292 }
293 if showProgress {
294 args = append(args, "--progress")
295 }
296 args = append(args, inst.Name)
297 // Not exec.CommandContext: the hostagent outlives this call, and os/exec
298 // would kill it whenever ctx ends, even after Start returned.
299 haCmd = exec.Command(limactl, args...)
300
301 haCmd.SysProcAttr = executil.BackgroundSysProcAttr
302
303 haCmd.Stdout = haStdoutW
304 haCmd.Stderr = haStderrW
305
306 if launchHostAgentForeground {
307 if isRegisteredToAutoStart {
308 logrus.Warn("The instance is registered to start at login, but the --foreground option was given, so starting the instance directly")
309 }
310 haCmd.SysProcAttr = executil.ForegroundSysProcAttr
311 if err := execHostAgentForeground(limactl, haCmd); err != nil {
312 return err
313 }
314 } else if err := haCmd.Start(); err != nil {
315 return err
316 }
317 } else if err = autostart.RequestStart(ctx, inst); err != nil {
318 return fmt.Errorf("failed to request start via autostart manager: %w", err)
319 }
320
321 if err := waitHostAgentStart(ctx, haPIDPath, haStderrPath); err != nil {
322 return err
323 }
324
325 // Buffered: the goroutine that loses the race below must not block on its
326 // send for as long as the program lives (it would, once StartWithPaths
327 // has returned).
328 watchErrCh := make(chan error, 1)
329 go func() {
330 watchErrCh <- watchHostAgentEvents(ctx, inst, haStdoutPath, haStderrPath, begin, showProgress)
331 close(watchErrCh)
332 }()
333 waitErrCh := make(chan error, 1)
334 if haCmd != nil {
335 go func() {
336 waitErrCh <- haCmd.Wait()
337 close(waitErrCh)
338 }()
339 } else {
340 defer close(waitErrCh)
341 }
342
343 select {
344 case watchErr := <-watchErrCh:
345 // watchErr can be nil
346 return watchErr
347 // leave the hostagent process running
348 case waitErr := <-waitErrCh:
349 // waitErr should not be nil
350 return fmt.Errorf("host agent process has exited: %w", waitErr)
351 }
352}
353
354func Start(ctx context.Context, inst *limatype.Instance, launchHostAgentForeground, showProgress bool) error {
355 return StartWithPaths(ctx, inst, launchHostAgentForeground, showProgress, "", "")
356}
357
358func waitHostAgentStart(_ context.Context, haPIDPath, haStderrPath string) error {
359 begin := time.Now()
360 deadlineDuration := 5 * time.Second
361 deadline := begin.Add(deadlineDuration)
362 for {
363 if _, err := os.Stat(haPIDPath); !errors.Is(err, os.ErrNotExist) {
364 return nil
365 }
366 if time.Now().After(deadline) {
367 return fmt.Errorf("hostagent (%#q) did not start up in %v (hint: see %#q)", haPIDPath, deadlineDuration, haStderrPath)
368 }
369 }
370}
371
372func watchHostAgentEvents(ctx context.Context, inst *limatype.Instance, haStdoutPath, haStderrPath string, begin time.Time, showProgress bool) error {
373 ctx, cancel := context.WithTimeout(ctx, watchHostAgentTimeout(ctx))
374 defer cancel()
375
376 var (
377 printedSSHLocalPort bool
378 receivedRunningEvent bool
379 cloudInitCompleted bool
380 err error
381 )
382
383 onEvent := func(ev hostagentevents.Event) bool {
384 if !printedSSHLocalPort && ev.Status.SSHLocalPort != 0 {
385 logrus.Infof("SSH Local Port: %d", ev.Status.SSHLocalPort)
386 printedSSHLocalPort = true
387
388 // Update the instance's SSH port
389 inst.SSHLocalPort = ev.Status.SSHLocalPort
390 }
391
392 if showProgress && ev.Status.CloudInitProgress != nil {
393 progress := ev.Status.CloudInitProgress
394 if progress.Active && progress.LogLine == "" {
395 logrus.Infof("Cloud-init provisioning started...")
396 }
397
398 if progress.LogLine != "" {
399 logrus.Infof("[cloud-init] %s", progress.LogLine)
400 }
401
402 if progress.Completed {
403 cloudInitCompleted = true
404 logrus.Infof("Cloud-init progress monitoring done.")
405 }
406 }
407 if len(ev.Status.Errors) > 0 {
408 logrus.Errorf("%+v", ev.Status.Errors)
409 }
410 if ev.Status.Exiting {
411 err = fmt.Errorf("exiting, status=%+v (hint: see %#q)", ev.Status, haStderrPath)
412 return true
413 } else if ev.Status.Running {
414 receivedRunningEvent = true
415 if ev.Status.Degraded {
416 logrus.Warnf("DEGRADED. The VM seems running, but file sharing and port forwarding may not work. (hint: see %#q)", haStderrPath)
417 err = fmt.Errorf("degraded, status=%+v", ev.Status)
418 return true
419 }
420
421 if xerr := runAnsibleProvision(ctx, inst); xerr != nil {
422 err = xerr
423 return true
424 }
425
426 if showProgress && !cloudInitCompleted {
427 return false
428 }
429
430 if !isLaunchingShell(ctx) {
431 if *inst.Config.Plain {
432 logrus.Infof("READY. Run `ssh -F %#q %s` to open the shell.", inst.SSHConfigFile, inst.Hostname)
433 } else {
434 logrus.Infof("READY. Run `%s` to open the shell.", LimactlShellCmd(inst.Name))
435 }
436 }
437 _ = ShowMessage(inst)
438 err = nil
439 return true
440 }
441 return false
442 }
443
444 if xerr := hostagentevents.Watch(ctx, haStdoutPath, haStderrPath, begin, true, onEvent); xerr != nil {
445 return xerr
446 }
447
448 if err != nil {
449 return err
450 }
451
452 if !receivedRunningEvent {
453 return errors.New("did not receive an event with the `running` status")
454 }
455
456 return nil
457}
458
459type watchHostAgentEventsTimeoutKey = struct{}
460
461// WithWatchHostAgentTimeout sets the value of the timeout to use for
462// watchHostAgentEvents in the given Context.
463func WithWatchHostAgentTimeout(ctx context.Context, timeout time.Duration) context.Context {
464 return context.WithValue(ctx, watchHostAgentEventsTimeoutKey{}, timeout)
465}
466
467type launchingShellKey = struct{}
468
469// WithLaunchingShell marks the context as launching a shell after start,
470// suppressing the "READY. Run ... to open the shell" message.
471func WithLaunchingShell(ctx context.Context) context.Context {
472 return context.WithValue(ctx, launchingShellKey{}, true)
473}
474
475// IsLaunchingShell returns whether the launching shell flag is set in the context.
476func isLaunchingShell(ctx context.Context) bool {
477 v, _ := ctx.Value(launchingShellKey{}).(bool)
478 return v
479}
480
481// watchHostAgentTimeout returns the value of the timeout to use for
482// watchHostAgentEvents contained in the given Context, or its default value.
483func watchHostAgentTimeout(ctx context.Context) time.Duration {
484 if timeout, ok := ctx.Value(watchHostAgentEventsTimeoutKey{}).(time.Duration); ok {
485 return timeout
486 }
487 return DefaultWatchHostAgentEventsTimeout
488}
489
490func LimactlShellCmd(instName string) string {
491 shellCmd := fmt.Sprintf("limactl shell %s", instName)
492 if instName == "default" {
493 shellCmd = "lima"
494 }
495 return shellCmd
496}
497
498func ShowMessage(inst *limatype.Instance) error {
499 if inst.Message == "" {
500 return nil
501 }
502 t, err := template.New("message").Parse(inst.Message)
503 if err != nil {
504 return err
505 }
506 data, err := store.AddGlobalFields(inst)
507 if err != nil {
508 return err
509 }
510 var b bytes.Buffer
511 if err := t.Execute(&b, data); err != nil {
512 return err
513 }
514 scanner := bufio.NewScanner(&b)
515 logrus.Infof("Message from the instance %#q:", inst.Name)
516 for scanner.Scan() {
517 // Avoid prepending logrus "INFO" header, for ease of copy pasting
518 fmt.Fprintln(logrus.StandardLogger().Out, scanner.Text())
519 }
520 return scanner.Err()
521}
522
523// prepareDisk resizes the VM disk if its size differs from the configured size.
524// Returns nil if the disk does not yet exist (instance not yet initialized).
525func prepareDisk(ctx context.Context, inst *limatype.Instance) error {
526 disk := filepath.Join(inst.Dir, filenames.Disk)
527
528 _, err := os.Stat(disk)
529 if err != nil {
530 if os.IsNotExist(err) {
531 return nil
532 }
533 return err
534 }
535
536 f, err := os.Open(disk)
537 if err != nil {
538 return err
539 }
540 defer f.Close()
541
542 img, err := qcow2reader.Open(f)
543 if err != nil {
544 return err
545 }
546
547 diskSize := img.Size()
548
549 if img.Type() == vhdx.Type {
550 logrus.Warn("Skip resizing the instance because go-qcow2reader cannot read vhdx type image")
551 return nil
552 }
553
554 if inst.Disk == diskSize {
555 return nil
556 }
557
558 logrus.Infof("Resize instance %s's disk from %s to %s", inst.Name, units.BytesSize(float64(diskSize)), units.BytesSize(float64(inst.Disk)))
559
560 if inst.Disk < diskSize {
561 inst.Disk = diskSize
562 return errors.New("disk shrinking is not supported")
563 }
564
565 diskUtil := proxyimgutil.NewDiskUtil(ctx)
566
567 return diskUtil.ResizeDisk(ctx, disk, inst.Disk)
568}