跳到主要内容

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

浏览文件

hostagent.go

219 行 · 5.8 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copied from third_party/lima/cmd/limactl/hostagent.go, which is in package
5// main and cannot be imported. Changed by agent-vm: the package name, and
6// WrapArgsError (in limactl's main.go) is cobra's own error here. Cage also
7// receives stop requests through its buffered channel and Windows event.
8// TestHostagentCopy fails when the two drift apart.
9
10package limaembed
11
12import (
13 "errors"
14 "fmt"
15 "io"
16 "net"
17 "net/http"
18 "os"
19 "os/signal"
20 "runtime"
21 "sync"
22 "syscall"
23 "time"
24
25 "github.com/sirupsen/logrus"
26 "github.com/spf13/cobra"
27
28 "github.com/lima-vm/lima/v2/pkg/hostagent"
29 "github.com/lima-vm/lima/v2/pkg/hostagent/api/server"
30 "github.com/lima-vm/lima/v2/pkg/store"
31)
32
33func newHostagentCommand() *cobra.Command {
34 hostagentCommand := &cobra.Command{
35 Use: "hostagent INSTANCE",
36 Short: "Run hostagent",
37 Args: cobra.ExactArgs(1),
38 RunE: hostagentAction,
39 Hidden: true,
40 }
41 hostagentCommand.Flags().StringP("pidfile", "p", "", "Write PID to file")
42 hostagentCommand.Flags().String("socket", "", "Path of hostagent socket")
43 hostagentCommand.Flags().Bool("run-gui", false, "Run GUI synchronously within hostagent")
44 hostagentCommand.Flags().String("guestagent", "", "Local file path (not URL) of lima-guestagent.OS-ARCH[.gz]")
45 hostagentCommand.Flags().String("nerdctl-archive", "", "Local file path (not URL) of nerdctl-full-VERSION-GOOS-GOARCH.tar.gz")
46 hostagentCommand.Flags().Bool("progress", false, "Show provision script progress by monitoring cloud-init logs")
47 return hostagentCommand
48}
49
50func hostagentAction(cmd *cobra.Command, args []string) error {
51 ctx := cmd.Context()
52 pidfile, err := cmd.Flags().GetString("pidfile")
53 if err != nil {
54 return err
55 }
56 if pidfile != "" {
57 if existingPID, err := store.ReadPIDFile(pidfile); existingPID != 0 {
58 return fmt.Errorf("another hostagent may already be running with pid %d (pidfile %#q)", existingPID, pidfile)
59 } else if err != nil {
60 return fmt.Errorf("failed to determine if another hostagent is running: %w", err)
61 }
62 if err := store.WritePIDFile(pidfile, os.Getpid()); err != nil {
63 return err
64 }
65 defer os.RemoveAll(pidfile)
66 }
67 socket, err := cmd.Flags().GetString("socket")
68 if err != nil {
69 return err
70 }
71 if socket == "" {
72 return errors.New("socket must be specified (limactl version mismatch?)")
73 }
74
75 instName := args[0]
76
77 runGUI, err := cmd.Flags().GetBool("run-gui")
78 if err != nil {
79 return err
80 }
81 if runGUI {
82 // Without this the call to vz.RunGUI fails. Adding it here, as this has to be called before the vz cgo loads.
83 runtime.LockOSThread()
84 defer runtime.UnlockOSThread()
85 }
86
87 signalCh := hostagentSignals
88 signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM)
89 stopNotification, err := watchHostagentStop(socket)
90 if err != nil {
91 return err
92 }
93 defer stopNotification()
94
95 stdout := &syncWriter{w: cmd.OutOrStdout()}
96 stderr := &syncWriter{w: cmd.ErrOrStderr()}
97 defer stdout.flush()
98 defer stderr.flush()
99
100 initLogrus(stderr)
101 var opts []hostagent.Opt
102 guestagentBinary, err := cmd.Flags().GetString("guestagent")
103 if err != nil {
104 return err
105 }
106 if guestagentBinary != "" {
107 opts = append(opts, hostagent.WithGuestAgentBinary(guestagentBinary))
108 }
109 nerdctlArchive, err := cmd.Flags().GetString("nerdctl-archive")
110 if err != nil {
111 return err
112 }
113 if nerdctlArchive != "" {
114 opts = append(opts, hostagent.WithNerdctlArchive(nerdctlArchive))
115 }
116 showProgress, err := cmd.Flags().GetBool("progress")
117 if err != nil {
118 return err
119 }
120 if showProgress {
121 opts = append(opts, hostagent.WithCloudInitProgress(showProgress))
122 }
123 ha, err := hostagent.New(ctx, instName, stdout, signalCh, opts...)
124 if err != nil {
125 return err
126 }
127
128 backend := &server.Backend{
129 Agent: ha,
130 }
131 r := http.NewServeMux()
132 server.AddRoutes(r, backend)
133 srv := &http.Server{Handler: r}
134 err = os.RemoveAll(socket)
135 if err != nil {
136 return err
137 }
138 var lc net.ListenConfig
139 l, err := lc.Listen(ctx, "unix", socket)
140 logrus.Infof("hostagent socket created at %s", socket)
141 if err != nil {
142 return err
143 }
144 go func() {
145 if serveErr := srv.Serve(l); serveErr != http.ErrServerClosed {
146 logrus.WithError(serveErr).Warn("hostagent API server exited with an error")
147 }
148 }()
149 defer srv.Close()
150 return ha.Run(ctx)
151}
152
153// syncer is implemented by *os.File.
154type syncer interface {
155 Sync() error
156}
157
158// syncInterval is how long syncWriter batches writes before flushing them.
159//
160// Flushing on every write serialised the whole hostagent behind one fsync per
161// record: logrus holds its output mutex across Out.Write, and the port
162// forwarder logs once per tunnel teardown, so a burst of closing connections
163// throttled all logging in the process.
164//
165// The flush cannot be dropped entirely. limactl start follows these files with
166// fsnotify, and on Windows the tailer stops seeing new lines without it.
167const syncInterval = 100 * time.Millisecond
168
169type syncWriter struct {
170 w io.Writer
171
172 mu sync.Mutex
173 dirty bool
174 timer *time.Timer
175}
176
177func (w *syncWriter) Write(p []byte) (int, error) {
178 w.mu.Lock()
179 defer w.mu.Unlock()
180
181 written, err := w.w.Write(p)
182 if err == nil {
183 w.dirty = true
184 if w.timer == nil {
185 w.timer = time.AfterFunc(syncInterval, w.flush)
186 }
187 }
188 return written, err
189}
190
191// flush stops the pending timer and syncs any writes in the current batch.
192func (w *syncWriter) flush() {
193 w.mu.Lock()
194 defer w.mu.Unlock()
195
196 if w.timer != nil {
197 w.timer.Stop()
198 w.timer = nil
199 }
200 if !w.dirty {
201 return
202 }
203 if s, ok := w.w.(syncer); ok {
204 _ = s.Sync()
205 }
206 w.dirty = false
207}
208
209func initLogrus(stderr io.Writer) {
210 logrus.SetOutput(stderr)
211 // JSON logs are parsed in pkg/hostagent/events.Watcher()
212 logrus.SetFormatter(new(logrus.JSONFormatter))
213 // HostAgent logging is one level more verbose than the start command itself
214 if logrus.GetLevel() == logrus.DebugLevel {
215 logrus.SetLevel(logrus.TraceLevel)
216 } else {
217 logrus.SetLevel(logrus.DebugLevel)
218 }
219}