跳到主要内容

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

浏览文件

hostagent.go

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