| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "regexp" |
| 9 | "runtime" |
| 10 | "slices" |
| 11 | "sort" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "al.essio.dev/pkg/shellescape" |
| 16 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| 17 | "golang.org/x/net/http/httpguts" |
| 18 | ) |
| 19 | |
| 20 | |
| 21 | |
| 22 | const clientMountRoot = "/run/cage-client-projects" |
| 23 | |
| 24 | var clientMountID = regexp.MustCompile(`^[0-9a-f]{32}$`) |
| 25 | var errClientMountGone = errors.New("本机项目共享已断开,请在本机重新选择文件夹") |
| 26 | |
| 27 | type guestClientMount struct { |
| 28 | ctx context.Context |
| 29 | cancel context.CancelFunc |
| 30 | done chan struct{} |
| 31 | ready bool |
| 32 | } |
| 33 | |
| 34 | |
| 35 | func (m *guestClientMount) live() bool { return m.ready && m.ctx.Err() == nil } |
| 36 | |
| 37 | func isClientMountPath(path string) bool { |
| 38 | return path == clientMountRoot || strings.HasPrefix(path, clientMountRoot+"/") |
| 39 | } |
| 40 | |
| 41 | func (s *Server) clientMountWorkspace(path string) (string, error) { |
| 42 | s.mu.Lock() |
| 43 | defer s.mu.Unlock() |
| 44 | if mount := s.clientMounts[path]; mount != nil && mount.live() { |
| 45 | return path, nil |
| 46 | } |
| 47 | return "", errClientMountGone |
| 48 | } |
| 49 | |
| 50 | func (s *Server) appendClientMounts(paths []string) []string { |
| 51 | s.mu.Lock() |
| 52 | defer s.mu.Unlock() |
| 53 | var live []string |
| 54 | for path, mount := range s.clientMounts { |
| 55 | if mount.live() && !slices.Contains(paths, path) { |
| 56 | live = append(live, path) |
| 57 | } |
| 58 | } |
| 59 | sort.Strings(live) |
| 60 | return append(paths, live...) |
| 61 | } |
| 62 | |
| 63 | func (s *Server) closeClientMounts() { |
| 64 | s.mu.Lock() |
| 65 | var mounts []*guestClientMount |
| 66 | for _, m := range s.clientMounts { |
| 67 | m.cancel() |
| 68 | mounts = append(mounts, m) |
| 69 | } |
| 70 | s.mu.Unlock() |
| 71 | for _, m := range mounts { |
| 72 | <-m.done |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | func (s *Server) recoverClientMounts(ctx context.Context) error { |
| 80 | s.mu.Lock() |
| 81 | initialized := s.clientMounts != nil |
| 82 | s.mu.Unlock() |
| 83 | if initialized { |
| 84 | return nil |
| 85 | } |
| 86 | const recoverScript = `set -eu |
| 87 | root=` + clientMountRoot + ` |
| 88 | [ ! -L "$root" ] || exit 1 |
| 89 | [ -d "$root" ] || exit 0 |
| 90 | for p in "$root"/*; do |
| 91 | [[ ${p##*/} =~ ^[a-f0-9]{32}$ ]] || continue |
| 92 | [ ! -L "$p" ] || continue |
| 93 | kind=$(findmnt -rn --nocanonicalize -o FSTYPE --mountpoint "$p") || kind= |
| 94 | case "$kind" in |
| 95 | fuse.sshfs) sudo -n umount -l -- "$p";; |
| 96 | "") ;; |
| 97 | *) continue;; |
| 98 | esac |
| 99 | sudo -n rmdir -- "$p" || true |
| 100 | done` |
| 101 | if _, err := s.guest(ctx, recoverScript); err != nil { |
| 102 | return errors.New("无法清理上次连接遗留的本机项目挂载") |
| 103 | } |
| 104 | s.mu.Lock() |
| 105 | if s.clientMounts == nil { |
| 106 | s.clientMounts = make(map[string]*guestClientMount) |
| 107 | } |
| 108 | s.mu.Unlock() |
| 109 | return nil |
| 110 | } |
| 111 | |
| 112 | func (s *Server) guestClientShare(w http.ResponseWriter, r *http.Request) { |
| 113 | if runtime.GOOS != "linux" || !containerenv.Configured(s.profile) { |
| 114 | http.NotFound(w, r) |
| 115 | return |
| 116 | } |
| 117 | id := r.URL.Query().Get("id") |
| 118 | if !clientMountID.MatchString(id) { |
| 119 | http.Error(w, "本机项目标识无效", http.StatusBadRequest) |
| 120 | return |
| 121 | } |
| 122 | path := clientMountRoot + "/" + id |
| 123 | if r.Method == http.MethodGet { |
| 124 | if _, err := s.clientMountWorkspace(path); err != nil { |
| 125 | http.Error(w, "本机项目尚未连接", http.StatusConflict) |
| 126 | return |
| 127 | } |
| 128 | jsonReply(w, map[string]string{"workspace": path}) |
| 129 | return |
| 130 | } |
| 131 | if !httpguts.HeaderValuesContainsToken(r.Header.Values("Connection"), "upgrade") || !strings.EqualFold(r.Header.Get("Upgrade"), "cage-sftp-v1") || r.ContentLength != 0 { |
| 132 | http.Error(w, "需要项目共享连接", http.StatusBadRequest) |
| 133 | return |
| 134 | } |
| 135 | if !s.op.TryLock() { |
| 136 | http.Error(w, "环境正在处理其他操作", http.StatusConflict) |
| 137 | return |
| 138 | } |
| 139 | ctx, cancel := context.WithCancel(r.Context()) |
| 140 | defer cancel() |
| 141 | mount := &guestClientMount{ctx: ctx, cancel: cancel, done: make(chan struct{})} |
| 142 | s.mu.Lock() |
| 143 | available := s.ready && !s.closing && len(s.clientMounts) < 16 && s.clientMounts[path] == nil && !s.busy() |
| 144 | if available { |
| 145 | if s.clientMounts == nil { |
| 146 | s.clientMounts = make(map[string]*guestClientMount) |
| 147 | } |
| 148 | s.clientMounts[path] = mount |
| 149 | } |
| 150 | s.mu.Unlock() |
| 151 | s.op.Unlock() |
| 152 | if !available { |
| 153 | http.Error(w, "环境未就绪、共享已存在或已达共享上限", http.StatusConflict) |
| 154 | return |
| 155 | } |
| 156 | defer func() { |
| 157 | s.mu.Lock() |
| 158 | delete(s.clientMounts, path) |
| 159 | |
| 160 | |
| 161 | s.mu.Unlock() |
| 162 | close(mount.done) |
| 163 | }() |
| 164 | |
| 165 | |
| 166 | |
| 167 | target := shellescape.Quote(path) |
| 168 | setup, finishSetup := context.WithTimeout(ctx, 10*time.Second) |
| 169 | _, err := s.guest(setup, "sudo -n install -d -m 0755 "+clientMountRoot+" && sudo -n mkdir -m 000 -- "+target) |
| 170 | finishSetup() |
| 171 | if err != nil { |
| 172 | http.Error(w, "无法准备云端容器挂载位置", http.StatusConflict) |
| 173 | return |
| 174 | } |
| 175 | defer func() { |
| 176 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 177 | defer cancel() |
| 178 | _, _ = s.guest(ctx, "if findmnt -rn --nocanonicalize --mountpoint "+target+" >/dev/null; then sudo -n umount -l -- "+target+"; fi; sudo -n rmdir -- "+target) |
| 179 | }() |
| 180 | conn, buffer, err := http.NewResponseController(w).Hijack() |
| 181 | if err != nil { |
| 182 | http.Error(w, "无法建立项目共享数据流", http.StatusServiceUnavailable) |
| 183 | return |
| 184 | } |
| 185 | defer conn.Close() |
| 186 | stopClose := context.AfterFunc(ctx, func() { _ = conn.Close() }) |
| 187 | defer stopClose() |
| 188 | if _, err = buffer.WriteString("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: cage-sftp-v1\r\n\r\n"); err != nil || buffer.Flush() != nil { |
| 189 | return |
| 190 | } |
| 191 | |
| 192 | |
| 193 | |
| 194 | |
| 195 | script := "exec sudo -n sshfs -f :/ " + target + ` -o "slave,allow_other,cache=no,nodev,nosuid,uid=$(id -u),gid=$(id -g)"` |
| 196 | cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script) |
| 197 | cmd.Stdout = conn |
| 198 | input, err := cmd.StdinPipe() |
| 199 | if err != nil { |
| 200 | return |
| 201 | } |
| 202 | defer input.Close() |
| 203 | if err = cmd.Start(); err != nil { |
| 204 | return |
| 205 | } |
| 206 | ingressDone := make(chan struct{}) |
| 207 | go func() { |
| 208 | defer close(ingressDone) |
| 209 | _, _ = io.Copy(input, buffer.Reader) |
| 210 | cancel() |
| 211 | }() |
| 212 | |
| 213 | |
| 214 | probed := make(chan struct{}) |
| 215 | go func() { |
| 216 | defer close(probed) |
| 217 | probe, end := context.WithTimeout(ctx, 15*time.Second) |
| 218 | defer end() |
| 219 | verify := "until [ \"$(findmnt -n -o FSTYPE --mountpoint " + target + ")\" = fuse.sshfs ] && stat -- " + target + "/. >/dev/null 2>&1; do sleep 0.1; done" |
| 220 | if _, err := s.guest(probe, verify); err != nil { |
| 221 | cancel() |
| 222 | return |
| 223 | } |
| 224 | s.mu.Lock() |
| 225 | mount.ready = ctx.Err() == nil |
| 226 | s.mu.Unlock() |
| 227 | }() |
| 228 | _ = cmd.Wait() |
| 229 | cancel() |
| 230 | <-ingressDone |
| 231 | <-probed |
| 232 | } |