| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "github.com/sylvinus/agent-vm/internal/cage" |
| 10 | "github.com/sylvinus/agent-vm/internal/host" |
| 11 | "io" |
| 12 | "net/http" |
| 13 | "net/http/cookiejar" |
| 14 | "net/url" |
| 15 | "os" |
| 16 | "os/exec" |
| 17 | "path/filepath" |
| 18 | "time" |
| 19 | ) |
| 20 | |
| 21 | type DesktopOptions struct{ CompleteUpdate, UseExisting bool } |
| 22 | type DesktopResult struct { |
| 23 | Status string `json:"status"` |
| 24 | URL string `json:"url,omitempty"` |
| 25 | Message string `json:"message,omitempty"` |
| 26 | Legacy bool `json:"legacy,omitempty"` |
| 27 | Controller ControllerIdentity `json:"controller"` |
| 28 | } |
| 29 | type controllerClient struct { |
| 30 | profile, origin string |
| 31 | connectionID string |
| 32 | record controlFile |
| 33 | launch launchResponse |
| 34 | client *http.Client |
| 35 | } |
| 36 | |
| 37 | var errControllerUnavailable = errors.New("control service is unavailable") |
| 38 | |
| 39 | func openController(profile string) (*controllerClient, error) { |
| 40 | path := filepath.Join(profile, "control.json") |
| 41 | if err := host.CheckPrivateFile(path); err != nil { |
| 42 | if os.IsNotExist(err) { |
| 43 | return nil, errControllerUnavailable |
| 44 | } |
| 45 | return nil, err |
| 46 | } |
| 47 | b, err := os.ReadFile(path) |
| 48 | if os.IsNotExist(err) { |
| 49 | return nil, errControllerUnavailable |
| 50 | } |
| 51 | if err != nil { |
| 52 | return nil, err |
| 53 | } |
| 54 | var record controlFile |
| 55 | if json.Unmarshal(b, &record) != nil || record.Port < 1024 || record.Port > 65535 || len(record.Token) != 64 || record.PID < 1 { |
| 56 | return nil, errors.New("后台记录无效,请保留现有环境并检查私有配置。") |
| 57 | } |
| 58 | jar, _ := cookiejar.New(nil) |
| 59 | c := &controllerClient{profile: profile, record: record, origin: fmt.Sprintf("http://localhost:%d", record.Port), client: &http.Client{Timeout: 5 * time.Second, Jar: jar, Transport: &http.Transport{Proxy: nil}, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}} |
| 60 | return c, nil |
| 61 | } |
| 62 | |
| 63 | func connectController(profile string) (*controllerClient, error) { |
| 64 | if controllerLockFree(profile) { |
| 65 | return nil, errControllerUnavailable |
| 66 | } |
| 67 | c, err := openController(profile) |
| 68 | if err != nil { |
| 69 | if controllerLockFree(profile) { |
| 70 | return nil, errControllerUnavailable |
| 71 | } |
| 72 | return nil, err |
| 73 | } |
| 74 | record := c.record |
| 75 | status, err := c.call("POST", "/api/launch", map[string]string{"token": record.Token}, &c.launch) |
| 76 | if err != nil { |
| 77 | c.close() |
| 78 | var networkError *url.Error |
| 79 | if errors.As(err, &networkError) { |
| 80 | return nil, errControllerUnavailable |
| 81 | } |
| 82 | return nil, err |
| 83 | } |
| 84 | if status != http.StatusOK { |
| 85 | c.close() |
| 86 | if status == http.StatusServiceUnavailable { |
| 87 | return nil, errControllerUnavailable |
| 88 | } |
| 89 | |
| 90 | |
| 91 | |
| 92 | if controllerLockFree(profile) { |
| 93 | return nil, errControllerUnavailable |
| 94 | } |
| 95 | return nil, errors.New("无法认证已有后台,未尝试终止或替换它。") |
| 96 | } |
| 97 | u, err := url.Parse(c.launch.URL) |
| 98 | if err != nil || u.Scheme != "http" || u.Host != fmt.Sprintf("localhost:%d", record.Port) || u.User != nil || u.Fragment == "" { |
| 99 | c.close() |
| 100 | return nil, errors.New("后台返回了无效入口,未连接旧工作台。") |
| 101 | } |
| 102 | if c.launch.Controller.Protocol != 0 && c.launch.Controller.PID != record.PID { |
| 103 | c.close() |
| 104 | return nil, errors.New("后台身份已变化,请重试连接。") |
| 105 | } |
| 106 | return c, nil |
| 107 | } |
| 108 | func (c *controllerClient) close() { c.client.CloseIdleConnections() } |
| 109 | |
| 110 | |
| 111 | |
| 112 | |
| 113 | func waitControllerReady(ctx context.Context, profile string) (*controllerClient, error) { |
| 114 | for { |
| 115 | c, err := connectController(profile) |
| 116 | if !errors.Is(err, errControllerUnavailable) { |
| 117 | return c, err |
| 118 | } |
| 119 | free, lockErr := controllerLockStatus(profile) |
| 120 | if lockErr != nil { |
| 121 | return nil, lockErr |
| 122 | } |
| 123 | if free { |
| 124 | return nil, errControllerUnavailable |
| 125 | } |
| 126 | select { |
| 127 | case <-ctx.Done(): |
| 128 | return nil, errors.New("本机后台尚未退出或仍未响应,请稍后重试") |
| 129 | case <-time.After(100 * time.Millisecond): |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | func (c *controllerClient) call(method, path string, input, output any) (int, error) { |
| 134 | return c.callContext(context.Background(), method, path, input, output) |
| 135 | } |
| 136 | |
| 137 | func (c *controllerClient) callContext(ctx context.Context, method, path string, input, output any) (int, error) { |
| 138 | var body []byte |
| 139 | var err error |
| 140 | if input != nil { |
| 141 | body, err = json.Marshal(input) |
| 142 | if err != nil { |
| 143 | return 0, err |
| 144 | } |
| 145 | } |
| 146 | req, err := http.NewRequestWithContext(ctx, method, c.origin+path, bytes.NewReader(body)) |
| 147 | if err != nil { |
| 148 | return 0, err |
| 149 | } |
| 150 | req.Header.Set("Origin", c.origin) |
| 151 | req.Header.Set("Content-Type", "application/json") |
| 152 | if c.connectionID != "" { |
| 153 | req.Header.Set(connectionHeader, c.connectionID) |
| 154 | } |
| 155 | res, err := c.client.Do(req) |
| 156 | if err != nil { |
| 157 | return 0, err |
| 158 | } |
| 159 | defer res.Body.Close() |
| 160 | if res.StatusCode == http.StatusOK && output != nil { |
| 161 | if err = json.NewDecoder(io.LimitReader(res.Body, 256<<10)).Decode(output); err != nil { |
| 162 | return res.StatusCode, errors.New("后台响应无效,未继续更新。") |
| 163 | } |
| 164 | } |
| 165 | return res.StatusCode, nil |
| 166 | } |
| 167 | func pendingUpdate(c *controllerClient) DesktopResult { |
| 168 | return DesktopResult{Status: "upgrade_pending", Legacy: c.launch.Controller.Protocol == 0, Controller: c.launch.Controller, Message: "新版已准备好,当前后台仍在运行。请先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。终端任务会结束,项目和登录状态会保留。"} |
| 169 | } |
| 170 | |
| 171 | |
| 172 | |
| 173 | func Desktop(configPath string, options DesktopOptions) (DesktopResult, error) { |
| 174 | return desktopLaunch(filepath.Dir(configPath), false, options, func() error { return startController(configPath) }) |
| 175 | } |
| 176 | |
| 177 | func desktopLaunch(profile string, gateway bool, options DesktopOptions, start func() error) (DesktopResult, error) { |
| 178 | want, err := currentController() |
| 179 | if err != nil { |
| 180 | return DesktopResult{}, err |
| 181 | } |
| 182 | ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) |
| 183 | defer cancel() |
| 184 | current, err := waitControllerReady(ctx, profile) |
| 185 | if err == nil { |
| 186 | defer current.close() |
| 187 | if current.launch.DesktopGateway != gateway { |
| 188 | return DesktopResult{}, errors.New("此目录已被另一种 Cage 服务使用,请核对配置路径") |
| 189 | } |
| 190 | if options.CompleteUpdate { |
| 191 | if current.launch.DesktopGateway { |
| 192 | err = current.releaseDesktopEntry() |
| 193 | } else { |
| 194 | err = current.stopAndHandoff() |
| 195 | } |
| 196 | if err != nil { |
| 197 | return DesktopResult{}, err |
| 198 | } |
| 199 | } else if want.matches(current.launch.Controller) || options.UseExisting { |
| 200 | status := "ready" |
| 201 | if !want.matches(current.launch.Controller) { |
| 202 | status = "existing" |
| 203 | } |
| 204 | return DesktopResult{Status: status, URL: current.launch.URL, Controller: current.launch.Controller, Legacy: current.launch.Controller.Protocol == 0}, nil |
| 205 | } else { |
| 206 | if current.launch.Controller.Protocol != controlProtocol { |
| 207 | return pendingUpdate(current), nil |
| 208 | } |
| 209 | status, handoffErr := current.call("POST", "/api/handoff", map[string]string{"token": current.record.Token}, nil) |
| 210 | if handoffErr != nil { |
| 211 | return DesktopResult{}, handoffErr |
| 212 | } |
| 213 | if status != http.StatusOK { |
| 214 | return pendingUpdate(current), nil |
| 215 | } |
| 216 | if err = current.waitForExit(); err != nil { |
| 217 | return DesktopResult{}, err |
| 218 | } |
| 219 | } |
| 220 | } else if !errors.Is(err, errControllerUnavailable) { |
| 221 | return DesktopResult{}, err |
| 222 | } |
| 223 | if err = start(); err != nil { |
| 224 | return DesktopResult{}, err |
| 225 | } |
| 226 | for i := 0; i < 60; i++ { |
| 227 | c, readErr := connectController(profile) |
| 228 | if readErr == nil { |
| 229 | c.close() |
| 230 | if c.launch.DesktopGateway != gateway { |
| 231 | return DesktopResult{}, errors.New("打开期间控制服务身份发生变化,请重新选择") |
| 232 | } |
| 233 | if want.matches(c.launch.Controller) { |
| 234 | return DesktopResult{Status: "ready", URL: c.launch.URL, Controller: c.launch.Controller}, nil |
| 235 | } |
| 236 | return pendingUpdate(c), nil |
| 237 | } |
| 238 | time.Sleep(200 * time.Millisecond) |
| 239 | } |
| 240 | return DesktopResult{}, errors.New("工作台未能启动,请查看私有配置中的 control.log 后重试。") |
| 241 | } |
| 242 | |
| 243 | |
| 244 | |
| 245 | func PrepareUpdate(configPath string, stop bool) (DesktopResult, error) { |
| 246 | |
| 247 | |
| 248 | |
| 249 | ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) |
| 250 | defer cancel() |
| 251 | c, err := waitControllerReady(ctx, filepath.Dir(configPath)) |
| 252 | if errors.Is(err, errControllerUnavailable) { |
| 253 | lock, lockErr := openControllerLock(filepath.Dir(configPath), os.O_RDWR) |
| 254 | if lockErr == nil { |
| 255 | defer lock.Close() |
| 256 | if lockController(lock) != nil { |
| 257 | return DesktopResult{}, errors.New("后台暂时无法连接且尚未退出,请恢复连接后重试更新。") |
| 258 | } |
| 259 | defer unlockController(lock) |
| 260 | } else if !os.IsNotExist(lockErr) { |
| 261 | return DesktopResult{}, lockErr |
| 262 | } |
| 263 | if controllerHasVM(filepath.Dir(configPath)) { |
| 264 | return DesktopResult{}, errors.New("后台无法连接,但仍有环境进程。请恢复工作台连接并保存停止后再更新。") |
| 265 | } |
| 266 | return DesktopResult{Status: "prepared"}, nil |
| 267 | } |
| 268 | if err != nil { |
| 269 | return DesktopResult{}, err |
| 270 | } |
| 271 | defer c.close() |
| 272 | if stop { |
| 273 | if err = c.stopAndHandoff(); err != nil { |
| 274 | return DesktopResult{}, err |
| 275 | } |
| 276 | return DesktopResult{Status: "prepared"}, nil |
| 277 | } |
| 278 | if c.launch.Controller.Protocol == controlProtocol { |
| 279 | |
| 280 | |
| 281 | handoffCtx, cancelHandoff := context.WithTimeout(ctx, 3*time.Second) |
| 282 | defer cancelHandoff() |
| 283 | conflicted := false |
| 284 | handoff: |
| 285 | for { |
| 286 | status, err := c.callContext(handoffCtx, "POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) |
| 287 | if err != nil { |
| 288 | if conflicted && handoffCtx.Err() != nil { |
| 289 | break |
| 290 | } |
| 291 | return DesktopResult{}, err |
| 292 | } |
| 293 | if status == http.StatusOK { |
| 294 | if err = c.waitForExit(); err != nil { |
| 295 | return DesktopResult{}, err |
| 296 | } |
| 297 | return DesktopResult{Status: "prepared"}, nil |
| 298 | } |
| 299 | if status != http.StatusConflict { |
| 300 | break |
| 301 | } |
| 302 | conflicted = true |
| 303 | select { |
| 304 | case <-handoffCtx.Done(): |
| 305 | break handoff |
| 306 | case <-time.After(50 * time.Millisecond): |
| 307 | } |
| 308 | } |
| 309 | } |
| 310 | return DesktopResult{Status: "stop_required", Message: "请保存文件后确认停止环境并安装更新。终端任务会结束,项目和登录状态会保留。"}, nil |
| 311 | } |
| 312 | func (c *controllerClient) stopAndHandoff() error { |
| 313 | legacy := c.launch.Controller.Protocol == 0 |
| 314 | var owner legacyProcessIdentity |
| 315 | var err error |
| 316 | if legacy { |
| 317 | owner, err = identifyLegacyController(c.profile, c.record) |
| 318 | if err != nil { |
| 319 | return err |
| 320 | } |
| 321 | } else if c.launch.Controller.Protocol != controlProtocol { |
| 322 | return errors.New("当前后台协议不受此版本支持,已保留运行环境。请使用匹配的 Cage 版本停止环境。") |
| 323 | } |
| 324 | u, _ := url.Parse(c.launch.URL) |
| 325 | status, err := c.call("POST", "/api/session", map[string]string{"token": u.Fragment}, nil) |
| 326 | if err != nil { |
| 327 | return err |
| 328 | } |
| 329 | if status != http.StatusOK { |
| 330 | return errors.New("无法建立停止会话,请重试。") |
| 331 | } |
| 332 | var clientContext ClientContext |
| 333 | contextStatus, contextErr := c.call("GET", "/api/client/context", nil, &clientContext) |
| 334 | if contextErr == nil && contextStatus == http.StatusOK && (clientContext.Mode == "remote" || clientContext.ClientOnly) { |
| 335 | path := "/api/client/local" |
| 336 | if clientContext.ClientOnly { |
| 337 | path = "/api/client/disconnect" |
| 338 | } |
| 339 | status, err = c.call("POST", path, map[string]string{"connection_id": clientContext.ConnectionID}, nil) |
| 340 | if err != nil || status != http.StatusOK { |
| 341 | return errors.New("无法断开本地远程连接,未继续更新") |
| 342 | } |
| 343 | if clientContext.ClientOnly { |
| 344 | status, err = c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) |
| 345 | if err != nil || status != http.StatusOK { |
| 346 | return errors.New("本地连接服务尚未退出,请稍后重试") |
| 347 | } |
| 348 | return c.waitForExit() |
| 349 | } |
| 350 | } |
| 351 | var requested Job |
| 352 | status, err = c.call("POST", "/api/stop", map[string]any{}, &requested) |
| 353 | if err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if status != http.StatusOK || requested.ID == "" { |
| 357 | return errors.New("后台未接受停止请求,已取消本次更新。") |
| 358 | } |
| 359 | deadline := time.Now().Add(2 * time.Minute) |
| 360 | for { |
| 361 | var state struct { |
| 362 | VMRunning *bool `json:"vm_running"` |
| 363 | Job Job `json:"job"` |
| 364 | } |
| 365 | status, err = c.call("GET", "/api/status", nil, &state) |
| 366 | if err != nil { |
| 367 | return err |
| 368 | } |
| 369 | if status != http.StatusOK || state.VMRunning == nil || state.Job.ID != requested.ID { |
| 370 | return errors.New("停止状态发生变化,未终止后台;请确认现有任务后重试。") |
| 371 | } |
| 372 | if !state.Job.Running { |
| 373 | if state.Job.Error != "" || *state.VMRunning { |
| 374 | return errors.New("环境未能安全停止,未继续更新。请在原工作台查看停止结果。") |
| 375 | } |
| 376 | break |
| 377 | } |
| 378 | if time.Now().After(deadline) { |
| 379 | return errors.New("停止环境超时,后台保持运行,请稍后重试更新。") |
| 380 | } |
| 381 | time.Sleep(200 * time.Millisecond) |
| 382 | } |
| 383 | var terminals []struct { |
| 384 | Closed bool `json:"closed"` |
| 385 | } |
| 386 | status, err = c.call("GET", "/api/terminals", nil, &terminals) |
| 387 | if err != nil { |
| 388 | return err |
| 389 | } |
| 390 | if status != http.StatusOK { |
| 391 | return errors.New("无法确认终端已停止,未继续更新。") |
| 392 | } |
| 393 | for _, terminal := range terminals { |
| 394 | if !terminal.Closed { |
| 395 | return errors.New("仍有终端运行,未继续更新。") |
| 396 | } |
| 397 | } |
| 398 | if legacy { |
| 399 | verified, err := identifyLegacyController(c.profile, c.record) |
| 400 | if err != nil || verified != owner { |
| 401 | return errors.New("旧后台进程身份已变化,未发送退出信号;请重试更新。") |
| 402 | } |
| 403 | var final struct { |
| 404 | VMRunning *bool `json:"vm_running"` |
| 405 | Job Job `json:"job"` |
| 406 | } |
| 407 | status, err = c.call("GET", "/api/status", nil, &final) |
| 408 | if err != nil || status != http.StatusOK || final.VMRunning == nil || *final.VMRunning || final.Job.ID != requested.ID || final.Job.Running || final.Job.Error != "" || controllerHasVM(c.profile) { |
| 409 | return errors.New("停止后又有环境工作,未终止旧后台;请保存停止后重试。") |
| 410 | } |
| 411 | if err = terminateLegacy(owner.PID); err != nil { |
| 412 | return errors.New("旧后台未能退出,未替换应用。") |
| 413 | } |
| 414 | } else { |
| 415 | status, err = c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) |
| 416 | if err != nil { |
| 417 | return err |
| 418 | } |
| 419 | if status != http.StatusOK { |
| 420 | return errors.New("后台仍在执行工作,未继续更新。请保存并停止后重试。") |
| 421 | } |
| 422 | } |
| 423 | return c.waitForExit() |
| 424 | } |
| 425 | func (c *controllerClient) waitForExit() error { |
| 426 | f, err := openControllerLock(c.profile, os.O_RDWR) |
| 427 | if err != nil { |
| 428 | return errors.New("无法确认后台已退出,未继续更新。") |
| 429 | } |
| 430 | defer f.Close() |
| 431 | for i := 0; i < 100; i++ { |
| 432 | if lockController(f) == nil { |
| 433 | _ = unlockController(f) |
| 434 | return nil |
| 435 | } |
| 436 | time.Sleep(100 * time.Millisecond) |
| 437 | } |
| 438 | return errors.New("后台尚未退出,未强制结束进程。请稍后重试更新。") |
| 439 | } |
| 440 | func startController(configPath string) error { |
| 441 | exe, err := os.Executable() |
| 442 | if err != nil { |
| 443 | return err |
| 444 | } |
| 445 | return startControllerExecutable(configPath, exe) |
| 446 | } |
| 447 | |
| 448 | func startControllerExecutable(configPath, exe string, extraEnv ...string) error { |
| 449 | profile := filepath.Dir(configPath) |
| 450 | if err := host.EnsurePrivateDir(profile); err != nil { |
| 451 | return err |
| 452 | } |
| 453 | cmd := exec.Command(exe, "log-relay", "controller") |
| 454 | cmd.Dir = profile |
| 455 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) |
| 456 | cmd.Env = append(cmd.Env, extraEnv...) |
| 457 | detachController(cmd) |
| 458 | if err := cmd.Start(); err != nil { |
| 459 | return err |
| 460 | } |
| 461 | return cmd.Process.Release() |
| 462 | } |