跳到主要内容

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

浏览文件

inotify.go

205 行 · 5.8 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package hostagent
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "os"
11 "path"
12 "path/filepath"
13 "strings"
14
15 "github.com/rjeczalik/notify"
16 "github.com/sirupsen/logrus"
17 "google.golang.org/protobuf/types/known/timestamppb"
18
19 guestagentapi "github.com/lima-vm/lima/v2/pkg/guestagent/api"
20)
21
22const CacheSize = 10000
23
24var (
25 inotifyCache = make(map[string]int64)
26 mountSymlinks = make(map[string]string)
27 mountLocations = make(map[string]string)
28)
29
30func (a *HostAgent) startInotify(ctx context.Context) error {
31 mountWatchCh := make(chan notify.EventInfo, 128)
32 if err := a.setupWatchers(mountWatchCh); err != nil {
33 return err
34 }
35 // notify.Watch allocates per-call kernel watchers and an internal reader
36 // goroutine; without notify.Stop they leak for the lifetime of the process.
37 defer notify.Stop(mountWatchCh)
38
39 // PostInotify returns a usable stream wrapper before the server-side
40 // handler is installed, so Sends issued during the gap fail with EOF.
41 select {
42 case <-a.guestAgentAliveCh:
43 case <-ctx.Done():
44 return nil
45 }
46
47 client, err := a.getOrCreateClient(ctx)
48 if err != nil {
49 return fmt.Errorf("inotify: failed to obtain guest agent client: %w", err)
50 }
51 inotifyClient, err := client.Inotify(ctx)
52 if err != nil {
53 return err
54 }
55 // Finalize the gRPC client-stream so the guest agent's PostInotify handler
56 // can return instead of staying parked on a half-open stream.
57 defer func() { _ = inotifyClient.CloseSend() }()
58
59 for {
60 select {
61 case <-ctx.Done():
62 return nil
63 case watchEvent := <-mountWatchCh:
64 watchPath := watchEvent.Path()
65 stat, err := os.Stat(watchPath)
66 if err != nil {
67 if !errors.Is(err, os.ErrNotExist) {
68 continue
69 }
70 if guestPath, ok := a.expectRemove(watchPath); ok {
71 event := &guestagentapi.Inotify{
72 MountPath: guestPath,
73 Time: timestamppb.Now(),
74 Removed: true,
75 }
76 if err := inotifyClient.Send(event); err != nil {
77 return fmt.Errorf("inotify stream closed: %w", err)
78 }
79 }
80 continue
81 }
82
83 if filterEvents(watchEvent, stat) {
84 continue
85 }
86
87 watchPath = translateToGuestPath(watchPath, mountSymlinks, mountLocations)
88
89 utcTimestamp := timestamppb.New(stat.ModTime().UTC())
90 event := &guestagentapi.Inotify{MountPath: watchPath, Time: utcTimestamp}
91 if err := inotifyClient.Send(event); err != nil {
92 // Stream is gone (typically a guest-agent reconnect). Return so
93 // the caller can re-spawn against the new client instead of
94 // looping silently with a dead stream.
95 return fmt.Errorf("inotify stream closed: %w", err)
96 }
97 }
98 }
99}
100
101func (a *HostAgent) setupWatchers(events chan notify.EventInfo) error {
102 for _, m := range a.instConfig.Mounts {
103 if !*m.Writable {
104 continue
105 }
106 symlink, err := filepath.EvalSymlinks(m.Location)
107 if err != nil {
108 return err
109 }
110 if m.Location != symlink {
111 mountSymlinks[symlink] = m.Location
112 }
113 if m.MountPoint != nil && m.Location != *m.MountPoint {
114 mountLocations[m.Location] = *m.MountPoint
115 }
116
117 logrus.Infof("enable inotify for writable mount: %s", m.Location)
118 err = notify.Watch(path.Join(m.Location, "..."), events, GetNotifyEvent())
119 if err != nil {
120 return err
121 }
122 }
123 return nil
124}
125
126// expectRemove prepares the relay of the removal of hostPath: the guest agent removes the path in the guest,
127// so that the guest emits an inotify event, and the mount must make that removal a no-op on the host,
128// as the path may have been created again on the host since.
129// It returns the path to remove in the guest, or false when the mount serving hostPath cannot
130// make the removal a no-op, e.g., for 9p and virtiofs.
131func (a *HostAgent) expectRemove(hostPath string) (string, bool) {
132 for symlink, original := range mountSymlinks {
133 if isUnder(hostPath, symlink, filepath.Separator) {
134 hostPath = original + strings.TrimPrefix(hostPath, symlink)
135 break
136 }
137 }
138 // The innermost mount serves the path.
139 var served *mount
140 for _, m := range a.mounts {
141 if isUnder(hostPath, filepath.Clean(m.location), filepath.Separator) &&
142 (served == nil || len(filepath.Clean(m.location)) > len(filepath.Clean(served.location))) {
143 served = m
144 }
145 }
146 if served == nil || served.expectRemove == nil {
147 return "", false
148 }
149 rel, err := filepath.Rel(filepath.Clean(served.location), hostPath)
150 if err != nil {
151 return "", false
152 }
153 guestPath := path.Join(served.mountPoint, filepath.ToSlash(rel))
154 // A mount nested in the guest at guestPath would receive the removal, without making it a no-op.
155 for _, m := range a.mounts {
156 if m != served && isUnder(m.mountPoint, served.mountPoint, '/') && (guestPath == m.mountPoint || isUnder(guestPath, m.mountPoint, '/')) {
157 return "", false
158 }
159 }
160 if !served.expectRemove(hostPath) {
161 return "", false
162 }
163 return guestPath, true
164}
165
166// isUnder reports whether p is strictly under dir.
167func isUnder(p, dir string, sep byte) bool {
168 return len(p) > len(dir) && strings.HasPrefix(p, dir) && (p[len(dir)] == sep || strings.HasSuffix(dir, string(sep)))
169}
170
171func translateToGuestPath(hostPath string, symlinks, locations map[string]string) string {
172 result := hostPath
173
174 for symlink, original := range symlinks {
175 if strings.HasPrefix(result, symlink) {
176 result = strings.ReplaceAll(result, symlink, original)
177 }
178 }
179
180 for location, mountPoint := range locations {
181 if suffix, ok := strings.CutPrefix(result, location); ok {
182 return mountPoint + suffix
183 }
184 }
185
186 return result
187}
188
189func filterEvents(event notify.EventInfo, stat os.FileInfo) bool {
190 currTime := stat.ModTime()
191 eventPath := event.Path()
192 cacheMilli, ok := inotifyCache[eventPath]
193 if ok {
194 // Ignore repeated events for 10ms to exclude recursive inotify events
195 if currTime.UnixMilli()-cacheMilli < 10 {
196 return true
197 }
198 }
199 inotifyCache[eventPath] = currTime.UnixMilli()
200
201 if len(inotifyCache) >= CacheSize {
202 inotifyCache = make(map[string]int64)
203 }
204 return false
205}