| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "runtime" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 13 | "github.com/sylvinus/agent-vm/internal/remotehost" |
| 14 | ) |
| 15 | |
| 16 | |
| 17 | |
| 18 | type DesktopLocalController interface { |
| 19 | Status(context.Context) (DesktopLocalStatus, error) |
| 20 | Connect(context.Context) (*remotehost.Session, error) |
| 21 | Release(context.Context, DesktopLocalStatus, bool) error |
| 22 | ReleaseOwnedIdle(context.Context, DesktopLocalStatus) (bool, error) |
| 23 | } |
| 24 | |
| 25 | type DesktopLocalStatus struct { |
| 26 | Available bool `json:"available"` |
| 27 | Known bool `json:"known"` |
| 28 | ServiceRunning bool `json:"service_running"` |
| 29 | Running bool `json:"running"` |
| 30 | Busy bool `json:"busy"` |
| 31 | LiveTerminals int `json:"live_terminals"` |
| 32 | ControllerID string `json:"controller_id,omitempty"` |
| 33 | Message string `json:"message,omitempty"` |
| 34 | } |
| 35 | |
| 36 | var ( |
| 37 | errDesktopLocalLocked = errors.New("请先切回本机解锁账户,再停止本机环境") |
| 38 | errViewChanged = errors.New("工作环境已切换,请刷新后重试") |
| 39 | errCandidateChanged = errors.New("候选连接已取消或发生变化,请重新选择") |
| 40 | ) |
| 41 | |
| 42 | type desktopCandidate struct { |
| 43 | ID string `json:"id"` |
| 44 | Mode string `json:"mode"` |
| 45 | Connection remotehost.ConnectionState `json:"connection"` |
| 46 | } |
| 47 | |
| 48 | |
| 49 | |
| 50 | type desktopTarget struct { |
| 51 | id, mode string |
| 52 | remote *remotehost.Manager |
| 53 | ctx context.Context |
| 54 | cancel context.CancelFunc |
| 55 | mu sync.Mutex |
| 56 | session *remotehost.Session |
| 57 | localErr error |
| 58 | localDone chan struct{} |
| 59 | } |
| 60 | |
| 61 | func (t *desktopTarget) state() remotehost.ConnectionState { |
| 62 | if t.remote != nil { |
| 63 | return t.remote.Snapshot() |
| 64 | } |
| 65 | t.mu.Lock() |
| 66 | defer t.mu.Unlock() |
| 67 | state := remotehost.ConnectionState{State: "connecting", ConnectionID: t.id, Phase: "local_connect", Message: "正在连接本机工作台"} |
| 68 | switch { |
| 69 | case t.localErr != nil: |
| 70 | state.State, state.Phase, state.ErrorCode, state.Message = "failed", "", "local_unavailable", t.localErr.Error() |
| 71 | case t.session != nil && t.session.Context.Err() == nil: |
| 72 | manifest := t.session.Manifest |
| 73 | state.State, state.Phase, state.Message = "connected", "", "已连接本机环境" |
| 74 | state.InstanceID, state.Manifest = manifest.InstanceID, &manifest |
| 75 | case t.session != nil || t.ctx.Err() != nil: |
| 76 | state.State, state.Phase, state.ErrorCode, state.Message = "failed", "", "connection_lost", "本机工作台连接已断开,请重新连接" |
| 77 | } |
| 78 | return state |
| 79 | } |
| 80 | |
| 81 | func (t *desktopTarget) acquire() (*remotehost.Session, error) { |
| 82 | if t.remote != nil { |
| 83 | return t.remote.Acquire(t.id) |
| 84 | } |
| 85 | t.mu.Lock() |
| 86 | defer t.mu.Unlock() |
| 87 | if t.session == nil || t.ctx.Err() != nil || t.session.Context.Err() != nil { |
| 88 | return nil, errors.New("本机工作台尚未连接") |
| 89 | } |
| 90 | return t.session, nil |
| 91 | } |
| 92 | |
| 93 | func (t *desktopTarget) close() { |
| 94 | if t == nil { |
| 95 | return |
| 96 | } |
| 97 | t.cancel() |
| 98 | if t.remote != nil { |
| 99 | _ = t.remote.Close() |
| 100 | return |
| 101 | } |
| 102 | if t.localDone != nil { |
| 103 | <-t.localDone |
| 104 | } |
| 105 | t.mu.Lock() |
| 106 | s := t.session |
| 107 | t.mu.Unlock() |
| 108 | if s != nil { |
| 109 | _ = s.Close() |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | func (t *desktopTarget) candidate() *desktopCandidate { |
| 114 | if t == nil { |
| 115 | return nil |
| 116 | } |
| 117 | return &desktopCandidate{ID: t.id, Mode: t.mode, Connection: t.state()} |
| 118 | } |
| 119 | |
| 120 | type desktopGateway struct { |
| 121 | |
| 122 | |
| 123 | change sync.Mutex |
| 124 | mu sync.RWMutex |
| 125 | store *remotehost.Store |
| 126 | local DesktopLocalController |
| 127 | generation string |
| 128 | active, pending *desktopTarget |
| 129 | closed bool |
| 130 | departing bool |
| 131 | } |
| 132 | |
| 133 | func newDesktopGateway(profile string, local DesktopLocalController) *remoteGateway { |
| 134 | g := newRemoteGateway(profile) |
| 135 | g.desktop = &desktopGateway{local: local, store: g.store, generation: randomToken()} |
| 136 | return g |
| 137 | } |
| 138 | |
| 139 | func (d *desktopGateway) context() ClientContext { |
| 140 | d.mu.RLock() |
| 141 | generation, active, pending := d.generation, d.active, d.pending |
| 142 | d.mu.RUnlock() |
| 143 | c := ClientContext{DesktopGateway: true, Mode: "none", ConnectionID: generation, ClientPlatform: runtime.GOOS, State: remotehost.ConnectionState{State: "disconnected"}, Candidate: pending.candidate()} |
| 144 | if active == nil { |
| 145 | return c |
| 146 | } |
| 147 | c.Mode, c.State = active.mode, active.state() |
| 148 | c.HostID, c.InstanceID = c.State.HostID, c.State.InstanceID |
| 149 | if active.mode == "local" { |
| 150 | c.Name, c.ServerPlatform = "本机环境", runtime.GOOS |
| 151 | } else { |
| 152 | c.ServerPlatform = "linux" |
| 153 | if p, err := d.store.Get(c.HostID); err == nil { |
| 154 | c.Name = p.Name |
| 155 | if p.HostKey != nil { |
| 156 | c.HostFingerprint = p.HostKey.Fingerprint |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | return c |
| 161 | } |
| 162 | |
| 163 | type switchRequest struct { |
| 164 | ConnectionID string `json:"connection_id"` |
| 165 | CandidateID string `json:"candidate_id,omitempty"` |
| 166 | Mode string `json:"mode,omitempty"` |
| 167 | HostID string `json:"host_id,omitempty"` |
| 168 | Deploy bool `json:"deploy,omitempty"` |
| 169 | Passphrase string `json:"passphrase,omitempty"` |
| 170 | LocalAction string `json:"local_action,omitempty"` |
| 171 | LocalControllerID string `json:"local_controller_id,omitempty"` |
| 172 | } |
| 173 | |
| 174 | func (d *desktopGateway) checkGeneration(id string) error { |
| 175 | d.mu.RLock() |
| 176 | defer d.mu.RUnlock() |
| 177 | if d.closed || id == "" || id != d.generation { |
| 178 | return errViewChanged |
| 179 | } |
| 180 | return nil |
| 181 | } |
| 182 | |
| 183 | |
| 184 | func (d *desktopGateway) prepare(in switchRequest) (*desktopCandidate, error) { |
| 185 | d.change.Lock() |
| 186 | defer d.change.Unlock() |
| 187 | if err := d.checkGeneration(in.ConnectionID); err != nil { |
| 188 | return nil, err |
| 189 | } |
| 190 | if d.pending != nil { |
| 191 | return nil, errors.New("请先取消当前候选连接") |
| 192 | } |
| 193 | ctx, cancel := context.WithCancel(context.Background()) |
| 194 | t := &desktopTarget{mode: in.Mode, ctx: ctx, cancel: cancel} |
| 195 | switch in.Mode { |
| 196 | case "remote": |
| 197 | t.remote = remotehost.NewManager(d.store) |
| 198 | secret := []byte(in.Passphrase) |
| 199 | st, err := t.remote.Connect(in.HostID, remotehost.ConnectSecrets{Passphrase: secret, Deploy: in.Deploy}) |
| 200 | clear(secret) |
| 201 | if err != nil { |
| 202 | t.close() |
| 203 | return nil, err |
| 204 | } |
| 205 | t.id = st.ConnectionID |
| 206 | case "local": |
| 207 | if d.active != nil && d.active.mode == "local" && d.active.state().State == "connected" { |
| 208 | t.close() |
| 209 | return nil, errors.New("已连接当前本机工作台") |
| 210 | } |
| 211 | t.id = randomToken() |
| 212 | if d.local == nil { |
| 213 | t.close() |
| 214 | return nil, errors.New("本机运行组件不可用") |
| 215 | } |
| 216 | t.localDone = make(chan struct{}) |
| 217 | go func() { |
| 218 | defer close(t.localDone) |
| 219 | session, err := d.local.Connect(ctx) |
| 220 | t.mu.Lock() |
| 221 | t.session, t.localErr = session, err |
| 222 | t.mu.Unlock() |
| 223 | }() |
| 224 | default: |
| 225 | t.close() |
| 226 | return nil, errors.New("请选择本机或远程主机") |
| 227 | } |
| 228 | d.mu.Lock() |
| 229 | d.pending = t |
| 230 | d.mu.Unlock() |
| 231 | return t.candidate(), nil |
| 232 | } |
| 233 | |
| 234 | func (d *desktopGateway) matchesCandidate(in switchRequest) (*desktopTarget, error) { |
| 235 | if err := d.checkGeneration(in.ConnectionID); err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | if d.pending == nil || in.CandidateID == "" || in.CandidateID != d.pending.id { |
| 239 | return nil, errCandidateChanged |
| 240 | } |
| 241 | return d.pending, nil |
| 242 | } |
| 243 | |
| 244 | func (d *desktopGateway) cancelCandidate(in switchRequest) error { |
| 245 | d.change.Lock() |
| 246 | defer d.change.Unlock() |
| 247 | t, err := d.matchesCandidate(in) |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | d.mu.Lock() |
| 252 | d.pending = nil |
| 253 | d.mu.Unlock() |
| 254 | d.discard(t) |
| 255 | return nil |
| 256 | } |
| 257 | |
| 258 | |
| 259 | |
| 260 | func (d *desktopGateway) discard(t *desktopTarget) { |
| 261 | t.close() |
| 262 | if t == nil || t.mode != "local" || t.session == nil { |
| 263 | return |
| 264 | } |
| 265 | if owner, ok := d.local.(interface { |
| 266 | ReleaseUnused(context.Context, *remotehost.Session) error |
| 267 | }); ok { |
| 268 | ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 269 | defer cancel() |
| 270 | if err := owner.ReleaseUnused(ctx, t.session); err != nil { |
| 271 | diagnostics.Log("warn", "controller", "取消本机候选后未能确认空闲服务已释放") |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | func (d *desktopGateway) stopLocal(ctx context.Context, expected string) error { |
| 277 | if d.local == nil || expected == "" { |
| 278 | return errors.New("无法确认本机后台身份,请刷新本机状态") |
| 279 | } |
| 280 | st, err := d.local.Status(ctx) |
| 281 | if err != nil { |
| 282 | return err |
| 283 | } |
| 284 | if !st.Known || st.ControllerID != expected { |
| 285 | return errors.New("本机后台已变化,请刷新状态后再停止") |
| 286 | } |
| 287 | return d.local.Release(ctx, st, true) |
| 288 | } |
| 289 | |
| 290 | func (d *desktopGateway) stopLocalCard(ctx context.Context, in switchRequest) error { |
| 291 | d.change.Lock() |
| 292 | defer d.change.Unlock() |
| 293 | if err := d.checkGeneration(in.ConnectionID); err != nil { |
| 294 | return err |
| 295 | } |
| 296 | selected := d.active != nil && d.active.mode == "local" |
| 297 | if selected { |
| 298 | resume := d.freezeView() |
| 299 | defer resume() |
| 300 | } |
| 301 | if err := d.stopLocal(ctx, in.LocalControllerID); err != nil { |
| 302 | return err |
| 303 | } |
| 304 | if selected { |
| 305 | d.clearSelection() |
| 306 | } |
| 307 | return nil |
| 308 | } |
| 309 | |
| 310 | func suspendLocalView(ctx context.Context, t *desktopTarget) error { |
| 311 | session, err := t.acquire() |
| 312 | if err != nil { |
| 313 | return err |
| 314 | } |
| 315 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, session.Origin+"/api/account/suspend", strings.NewReader("{}")) |
| 316 | if err != nil { |
| 317 | return err |
| 318 | } |
| 319 | req.Header.Set("Origin", session.Origin) |
| 320 | req.Header.Set("Content-Type", "application/json") |
| 321 | response, err := session.Client.Do(req) |
| 322 | if err != nil { |
| 323 | return errors.New("未能锁定本机会话,请重新连接本机工作台") |
| 324 | } |
| 325 | defer response.Body.Close() |
| 326 | if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusLocked { |
| 327 | return errors.New("本机工作台未确认账户锁定") |
| 328 | } |
| 329 | return nil |
| 330 | } |
| 331 | |
| 332 | func (d *desktopGateway) leaveLocal(ctx context.Context, in switchRequest, old *desktopTarget) error { |
| 333 | switch in.LocalAction { |
| 334 | case "stop": |
| 335 | return d.stopLocal(ctx, in.LocalControllerID) |
| 336 | case "keep": |
| 337 | if old != nil && old.mode == "local" { |
| 338 | return suspendLocalView(ctx, old) |
| 339 | } |
| 340 | return nil |
| 341 | case "", "auto": |
| 342 | if d.local == nil { |
| 343 | return nil |
| 344 | } |
| 345 | st, err := d.local.Status(ctx) |
| 346 | if err != nil || !st.Known || st.Running || st.Busy || st.LiveTerminals > 0 { |
| 347 | return errors.New("本机环境可能仍有任务,请选择保留运行或停止本机") |
| 348 | } |
| 349 | if !st.ServiceRunning { |
| 350 | return nil |
| 351 | } |
| 352 | released, err := d.local.ReleaseOwnedIdle(ctx, st) |
| 353 | if err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if !released && old != nil && old.mode == "local" && old.state().State == "connected" { |
| 357 | return suspendLocalView(ctx, old) |
| 358 | } |
| 359 | return nil |
| 360 | default: |
| 361 | return errors.New("本机处理方式无效") |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | func (d *desktopGateway) commit(ctx context.Context, in switchRequest) error { |
| 366 | d.change.Lock() |
| 367 | defer d.change.Unlock() |
| 368 | t, err := d.matchesCandidate(in) |
| 369 | if err != nil { |
| 370 | return err |
| 371 | } |
| 372 | if _, err = t.acquire(); err != nil { |
| 373 | return errors.New("候选工作台尚未连接,当前工作台已保留") |
| 374 | } |
| 375 | old := d.active |
| 376 | if old != nil && old.mode == "local" { |
| 377 | resume := d.freezeView() |
| 378 | defer resume() |
| 379 | } |
| 380 | if t.mode == "remote" { |
| 381 | if err = d.leaveLocal(ctx, in, old); err != nil { |
| 382 | return err |
| 383 | } |
| 384 | } |
| 385 | if _, err = t.acquire(); err != nil { |
| 386 | return errors.New("候选工作台连接已中断,请重新连接") |
| 387 | } |
| 388 | d.mu.Lock() |
| 389 | d.generation, d.active, d.pending = t.id, t, nil |
| 390 | d.mu.Unlock() |
| 391 | old.close() |
| 392 | return nil |
| 393 | } |
| 394 | |
| 395 | |
| 396 | |
| 397 | |
| 398 | func (d *desktopGateway) freezeView() func() { |
| 399 | d.mu.Lock() |
| 400 | d.departing = true |
| 401 | d.mu.Unlock() |
| 402 | return func() { |
| 403 | d.mu.Lock() |
| 404 | d.departing = false |
| 405 | d.mu.Unlock() |
| 406 | } |
| 407 | } |
| 408 | |
| 409 | func (d *desktopGateway) disconnect(ctx context.Context, in switchRequest) error { |
| 410 | d.change.Lock() |
| 411 | defer d.change.Unlock() |
| 412 | if err := d.checkGeneration(in.ConnectionID); err != nil { |
| 413 | return err |
| 414 | } |
| 415 | resume := d.freezeView() |
| 416 | defer resume() |
| 417 | if t := d.active; t != nil && t.mode == "local" && t.state().State == "connected" { |
| 418 | if err := suspendLocalView(ctx, t); err != nil { |
| 419 | return err |
| 420 | } |
| 421 | } |
| 422 | d.clearSelection() |
| 423 | return nil |
| 424 | } |
| 425 | |
| 426 | |
| 427 | |
| 428 | func (d *desktopGateway) clearSelection() { |
| 429 | d.mu.Lock() |
| 430 | old, pending := d.active, d.pending |
| 431 | d.active, d.pending, d.generation = nil, nil, randomToken() |
| 432 | d.mu.Unlock() |
| 433 | d.discard(old) |
| 434 | d.discard(pending) |
| 435 | } |
| 436 | |
| 437 | func (d *desktopGateway) acquire(id string) (*remotehost.Session, bool, error) { |
| 438 | d.mu.RLock() |
| 439 | defer d.mu.RUnlock() |
| 440 | if d.closed || d.active == nil { |
| 441 | return nil, false, errViewChanged |
| 442 | } |
| 443 | if d.departing || id == "" || id != d.generation { |
| 444 | return nil, d.active.mode == "remote", errViewChanged |
| 445 | } |
| 446 | session, err := d.active.acquire() |
| 447 | return session, d.active.mode == "remote", err |
| 448 | } |
| 449 | |
| 450 | func (d *desktopGateway) close() { |
| 451 | d.change.Lock() |
| 452 | defer d.change.Unlock() |
| 453 | if d.closed { |
| 454 | return |
| 455 | } |
| 456 | d.mu.Lock() |
| 457 | d.closed = true |
| 458 | d.mu.Unlock() |
| 459 | if t := d.active; t != nil && t.mode == "local" && t.state().State == "connected" { |
| 460 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 461 | _ = suspendLocalView(ctx, t) |
| 462 | cancel() |
| 463 | } |
| 464 | d.clearSelection() |
| 465 | } |
| 466 | |
| 467 | func (d *desktopGateway) handle(path string, w http.ResponseWriter, r *http.Request) bool { |
| 468 | if path == "trusted-login" { |
| 469 | d.trustedLogin(w, r) |
| 470 | return true |
| 471 | } |
| 472 | if path == "local-status" && r.Method == http.MethodGet { |
| 473 | if d.local == nil { |
| 474 | jsonReply(w, DesktopLocalStatus{Known: true}) |
| 475 | return true |
| 476 | } |
| 477 | st, err := d.local.Status(r.Context()) |
| 478 | if err != nil { |
| 479 | http.Error(w, err.Error(), http.StatusServiceUnavailable) |
| 480 | return true |
| 481 | } |
| 482 | jsonReply(w, st) |
| 483 | return true |
| 484 | } |
| 485 | switch path { |
| 486 | case "candidate", "commit", "cancel", "disconnect", "local-stop": |
| 487 | case "local", "connect": |
| 488 | http.Error(w, "请通过候选连接选择工作环境", http.StatusConflict) |
| 489 | return true |
| 490 | default: |
| 491 | return false |
| 492 | } |
| 493 | if r.Method != http.MethodPost { |
| 494 | http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) |
| 495 | return true |
| 496 | } |
| 497 | var in switchRequest |
| 498 | if !readJSON(w, r, &in) { |
| 499 | return true |
| 500 | } |
| 501 | var err error |
| 502 | switch path { |
| 503 | case "candidate": |
| 504 | var c *desktopCandidate |
| 505 | c, err = d.prepare(in) |
| 506 | if err == nil { |
| 507 | w.Header().Set("Content-Type", "application/json") |
| 508 | w.WriteHeader(http.StatusAccepted) |
| 509 | jsonReply(w, c) |
| 510 | return true |
| 511 | } |
| 512 | case "commit": |
| 513 | err = d.commit(r.Context(), in) |
| 514 | case "cancel": |
| 515 | err = d.cancelCandidate(in) |
| 516 | case "disconnect": |
| 517 | err = d.disconnect(r.Context(), in) |
| 518 | case "local-stop": |
| 519 | err = d.stopLocalCard(r.Context(), in) |
| 520 | } |
| 521 | if err != nil { |
| 522 | code := http.StatusConflict |
| 523 | if errors.Is(err, errDesktopLocalLocked) { |
| 524 | code = http.StatusLocked |
| 525 | } |
| 526 | http.Error(w, err.Error(), code) |
| 527 | return true |
| 528 | } |
| 529 | jsonReply(w, d.context()) |
| 530 | return true |
| 531 | } |