| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/sylvinus/agent-vm/internal/cage" |
| 14 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| 15 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 16 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 17 | "github.com/sylvinus/agent-vm/internal/version" |
| 18 | ) |
| 19 | |
| 20 | const controlProtocol = 1 |
| 21 | |
| 22 | type ControllerIdentity struct { |
| 23 | Version string `json:"version"` |
| 24 | Build string `json:"build"` |
| 25 | Protocol int `json:"protocol"` |
| 26 | PID int `json:"pid"` |
| 27 | } |
| 28 | |
| 29 | func currentController() (ControllerIdentity, error) { |
| 30 | build, err := version.ExecutableIdentity() |
| 31 | return ControllerIdentity{Version: version.Version, Build: build, Protocol: controlProtocol, PID: os.Getpid()}, err |
| 32 | } |
| 33 | |
| 34 | func (identity ControllerIdentity) matches(other ControllerIdentity) bool { |
| 35 | return identity.Build != "" && identity.Build == other.Build && identity.Protocol == other.Protocol |
| 36 | } |
| 37 | |
| 38 | type launchResponse struct { |
| 39 | ConfigPath string `json:"config_path,omitempty"` |
| 40 | ClientOnly bool `json:"client_only,omitempty"` |
| 41 | DesktopGateway bool `json:"desktop_gateway,omitempty"` |
| 42 | URL string `json:"url"` |
| 43 | Controller ControllerIdentity `json:"controller"` |
| 44 | } |
| 45 | |
| 46 | func (s *Server) launcherAuthenticated(w http.ResponseWriter, r *http.Request) bool { |
| 47 | var input struct { |
| 48 | Token string `json:"token"` |
| 49 | } |
| 50 | if !readJSON(w, r, &input) { |
| 51 | return false |
| 52 | } |
| 53 | if !equalSecret(input.Token, s.token) { |
| 54 | http.Error(w, "Launcher refused", http.StatusUnauthorized) |
| 55 | return false |
| 56 | } |
| 57 | return true |
| 58 | } |
| 59 | |
| 60 | func (s *Server) handoff(w http.ResponseWriter, r *http.Request) { |
| 61 | if !s.launcherAuthenticated(w, r) { |
| 62 | return |
| 63 | } |
| 64 | if !s.op.TryLock() { |
| 65 | http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict) |
| 66 | return |
| 67 | } |
| 68 | s.handoffLocked(w) |
| 69 | } |
| 70 | |
| 71 | |
| 72 | func (s *Server) handoffLocked(w http.ResponseWriter) { |
| 73 | s.handoffWithVMOwnerLocked(w, "") |
| 74 | } |
| 75 | |
| 76 | |
| 77 | |
| 78 | func (s *Server) handoffWithVMOwnerLocked(w http.ResponseWriter, permittedOwner string) { |
| 79 | owners, probeError := controllerVMOwners(s.profile) |
| 80 | vmBusy := probeError != nil || len(owners) != 0 && (permittedOwner == "" || len(owners) != 1 || owners[0] != permittedOwner) |
| 81 | s.mu.Lock() |
| 82 | if s.closing { |
| 83 | s.mu.Unlock() |
| 84 | s.op.Unlock() |
| 85 | http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable) |
| 86 | return |
| 87 | } |
| 88 | busy := s.jobs.snapshot().Running || vmBusy |
| 89 | busy = busy || s.terminals.hasLive() |
| 90 | busy = busy || len(s.mobileCLI.activeAccounts()) != 0 |
| 91 | if busy || s.shutdown == nil { |
| 92 | s.mu.Unlock() |
| 93 | s.op.Unlock() |
| 94 | http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict) |
| 95 | return |
| 96 | } |
| 97 | s.closing = true |
| 98 | s.mu.Unlock() |
| 99 | if err := managedproxy.Stop(s.profile); err != nil { |
| 100 | s.mu.Lock() |
| 101 | s.closing = false |
| 102 | s.mu.Unlock() |
| 103 | s.op.Unlock() |
| 104 | http.Error(w, "代理尚未停止,未继续后台更新。", http.StatusConflict) |
| 105 | return |
| 106 | } |
| 107 | |
| 108 | |
| 109 | w.Header().Set("Content-Type", "application/json") |
| 110 | w.Header().Set("Content-Length", "18") |
| 111 | _, _ = w.Write([]byte("{\"stopping\":true}\n")) |
| 112 | |
| 113 | |
| 114 | _ = http.NewResponseController(w).Flush() |
| 115 | s.op.Unlock() |
| 116 | go s.shutdown() |
| 117 | } |
| 118 | |
| 119 | func controllerHasVM(profile string) bool { |
| 120 | running, err := controllerVMState(profile) |
| 121 | return err != nil || running |
| 122 | } |
| 123 | |
| 124 | |
| 125 | func controllerVMState(profile string) (bool, error) { |
| 126 | owners, err := controllerVMOwners(profile) |
| 127 | return len(owners) != 0, err |
| 128 | } |
| 129 | |
| 130 | func controllerVMOwners(profile string) ([]string, error) { |
| 131 | binding, err := guestos.LoadWindowsProfile(profile) |
| 132 | if err != nil { |
| 133 | return nil, err |
| 134 | } |
| 135 | if binding != nil { |
| 136 | ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) |
| 137 | defer cancel() |
| 138 | state, err := guestos.WindowsVMResources(ctx, profile, 0, 0) |
| 139 | if err != nil { |
| 140 | return nil, err |
| 141 | } |
| 142 | if state.State == "" { |
| 143 | return nil, errors.New("无法确认已绑定 Windows 客机的运行状态,现有环境保持不变") |
| 144 | } |
| 145 | if state.State == "Off" || state.State == "Saved" { |
| 146 | return nil, nil |
| 147 | } |
| 148 | return []string{fmt.Sprintf("windows/%s/%s", binding.VMID, state.State)}, nil |
| 149 | } |
| 150 | if containerenv.Configured(profile) { |
| 151 | environment, err := containerenv.Load(profile) |
| 152 | if err != nil { |
| 153 | return nil, err |
| 154 | } |
| 155 | ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| 156 | defer cancel() |
| 157 | state, err := environment.State(ctx) |
| 158 | if err != nil || !state.Running { |
| 159 | return nil, err |
| 160 | } |
| 161 | return []string{fmt.Sprintf("%s/%d", state.ContainerID, state.PID)}, nil |
| 162 | } |
| 163 | records, err := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-running.json")) |
| 164 | if err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | var owners []string |
| 168 | for _, path := range records { |
| 169 | b, err := os.ReadFile(path) |
| 170 | if err != nil { |
| 171 | return nil, err |
| 172 | } |
| 173 | var record struct { |
| 174 | PID int `json:"pid"` |
| 175 | Started string `json:"started"` |
| 176 | } |
| 177 | if json.Unmarshal(b, &record) != nil || record.PID <= 0 { |
| 178 | return nil, errors.New("环境进程记录无效") |
| 179 | } |
| 180 | if processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started) { |
| 181 | owners = append(owners, fmt.Sprintf("%s/%d", filepath.Base(filepath.Dir(path)), record.PID)) |
| 182 | } |
| 183 | } |
| 184 | return owners, nil |
| 185 | } |