| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bufio" |
| 6 | "bytes" |
| 7 | "context" |
| 8 | "errors" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/url" |
| 13 | "os" |
| 14 | "path/filepath" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 18 | "github.com/sylvinus/agent-vm/internal/host" |
| 19 | "github.com/sylvinus/agent-vm/internal/version" |
| 20 | ) |
| 21 | |
| 22 | func (s *Server) diagnosticStatus(w http.ResponseWriter, r *http.Request) { |
| 23 | info, err := diagnostics.New(s.profile).Info() |
| 24 | if err != nil { |
| 25 | requestError(w, errors.New("无法读取诊断日志,请检查本机存储权限和剩余空间")) |
| 26 | return |
| 27 | } |
| 28 | jsonReply(w, info) |
| 29 | } |
| 30 | func (s *Server) diagnosticEvent(w http.ResponseWriter, r *http.Request) { |
| 31 | s.diagnosticRateMu.Lock() |
| 32 | if time.Since(s.diagnosticWindow) > time.Minute { |
| 33 | s.diagnosticWindow = time.Now() |
| 34 | s.diagnosticCount = 0 |
| 35 | } |
| 36 | s.diagnosticCount++ |
| 37 | permitted := s.diagnosticCount <= 60 |
| 38 | s.diagnosticRateMu.Unlock() |
| 39 | if !permitted { |
| 40 | http.Error(w, "诊断上报过于频繁", http.StatusTooManyRequests) |
| 41 | return |
| 42 | } |
| 43 | |
| 44 | var event struct { |
| 45 | Source string `json:"source"` |
| 46 | Level string `json:"level"` |
| 47 | Message string `json:"message"` |
| 48 | } |
| 49 | if !readJSON(w, r, &event, 32<<10) { |
| 50 | return |
| 51 | } |
| 52 | if event.Source != "frontend" && event.Source != "react" { |
| 53 | http.Error(w, "日志来源无效", 400) |
| 54 | return |
| 55 | } |
| 56 | if err := diagnostics.New(s.profile).Record(event.Level, event.Source, event.Message); err != nil { |
| 57 | http.Error(w, "诊断日志写入失败", 503) |
| 58 | return |
| 59 | } |
| 60 | jsonReply(w, map[string]bool{"ok": true}) |
| 61 | } |
| 62 | func (s *Server) diagnosticExport(w http.ResponseWriter, r *http.Request) { |
| 63 | if !s.diagnosticMu.TryLock() { |
| 64 | http.Error(w, "正在导出另一份诊断包,请稍候", 409) |
| 65 | return |
| 66 | } |
| 67 | defer s.diagnosticMu.Unlock() |
| 68 | guestState := "environment unavailable" |
| 69 | var guest []byte |
| 70 | if s.storageRecoveryStatus().Required { |
| 71 | guestState = "environment storage recovery pending" |
| 72 | } else if s.vmRunning() { |
| 73 | ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) |
| 74 | defer cancel() |
| 75 | var err error |
| 76 | if s.macosGuest != nil || s.windowsGuest != nil { |
| 77 | guest, err = s.nativeGuestDiagnostics(ctx) |
| 78 | } else { |
| 79 | guest, err = s.guest(ctx, `sudo python3 - <<'CAGE_DIAGNOSTIC_JOURNAL' |
| 80 | import subprocess, sys |
| 81 | result = subprocess.run(['journalctl','--namespace=cage','--no-pager','-o','short-iso','-n','150','--since','14 days ago'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=5, check=True) |
| 82 | data = result.stdout |
| 83 | if len(data) > 49152: |
| 84 | data = data[-49152:] |
| 85 | data = data.partition(b'\n')[2] |
| 86 | sys.stdout.buffer.write(data) |
| 87 | CAGE_DIAGNOSTIC_JOURNAL`) |
| 88 | } |
| 89 | if err != nil { |
| 90 | guest = nil |
| 91 | guestState = "guest collection failed" |
| 92 | } else { |
| 93 | guestState = "collected last 150 service lines (max 48 KiB)" |
| 94 | } |
| 95 | } |
| 96 | var bundle bytes.Buffer |
| 97 | if err := diagnostics.New(s.profile).Export(&bundle, version.Version, guest, guestState); err != nil { |
| 98 | requestError(w, errors.New("诊断包生成失败,请检查存储权限和剩余空间")) |
| 99 | return |
| 100 | } |
| 101 | w.Header().Set("Content-Type", "application/zip") |
| 102 | w.Header().Set("Content-Disposition", `attachment; filename="cage-diagnostics.zip"`) |
| 103 | _, _ = w.Write(bundle.Bytes()) |
| 104 | } |
| 105 | |
| 106 | |
| 107 | |
| 108 | |
| 109 | func ExportDiagnostics(configPath, destination string) error { |
| 110 | return ExportDiagnosticsForConnection(configPath, "", destination) |
| 111 | } |
| 112 | |
| 113 | func ExportDiagnosticsForConnection(configPath, connectionID, destination string) error { |
| 114 | return exportDiagnostics(configPath, connectionID, destination, false) |
| 115 | } |
| 116 | |
| 117 | |
| 118 | |
| 119 | func ExportAgentDiagnostics(configPath, destination string) error { |
| 120 | return exportDiagnostics(configPath, "local", destination, true) |
| 121 | } |
| 122 | |
| 123 | func exportDiagnostics(configPath, connectionID, destination string, agentLocal bool) error { |
| 124 | if !filepath.IsAbs(destination) { |
| 125 | return errors.New("请选择本机绝对保存路径") |
| 126 | } |
| 127 | profile := filepath.Dir(configPath) |
| 128 | store := diagnostics.New(profile) |
| 129 | dir := filepath.Dir(destination) |
| 130 | f, err := os.CreateTemp(dir, ".cage-diagnostics-*.zip") |
| 131 | if err != nil { |
| 132 | return err |
| 133 | } |
| 134 | temp := f.Name() |
| 135 | defer os.Remove(temp) |
| 136 | if err = host.ProtectFile(temp); err != nil { |
| 137 | f.Close() |
| 138 | return err |
| 139 | } |
| 140 | export := func() error { |
| 141 | var c *controllerClient |
| 142 | var e error |
| 143 | if agentLocal { |
| 144 | c, e = agentConnect(context.Background(), configPath) |
| 145 | } else { |
| 146 | c, e = connectController(profile) |
| 147 | } |
| 148 | if e != nil { |
| 149 | if connectionID != "" && connectionID != "local" { |
| 150 | return errors.New("远程连接不可用,无法导出云端诊断包") |
| 151 | } |
| 152 | if e := store.ImportLegacy(profile); e != nil { |
| 153 | return e |
| 154 | } |
| 155 | return store.Export(f, version.Version, nil, "controller unavailable or invalid; host logs only") |
| 156 | } |
| 157 | defer c.close() |
| 158 | if !agentLocal { |
| 159 | parsed, e := url.Parse(c.launch.URL) |
| 160 | if e != nil { |
| 161 | return e |
| 162 | } |
| 163 | ticket := parsed.Fragment |
| 164 | code, e := c.call("POST", "/api/session", map[string]string{"token": ticket}, nil) |
| 165 | if e != nil || code != 200 { |
| 166 | return errors.New("无法创建诊断导出会话,请重新打开 Cage") |
| 167 | } |
| 168 | if _, err := c.bindConnection(connectionID); err != nil { |
| 169 | return err |
| 170 | } |
| 171 | } |
| 172 | c.client.Timeout = 30 * time.Second |
| 173 | req, _ := http.NewRequest("GET", c.origin+"/api/diagnostics/export", nil) |
| 174 | if agentLocal { |
| 175 | req.Header.Set(connectionHeader, "local") |
| 176 | } |
| 177 | response, e := c.client.Do(req) |
| 178 | if e != nil { |
| 179 | return e |
| 180 | } |
| 181 | defer response.Body.Close() |
| 182 | if response.StatusCode != 200 { |
| 183 | return errors.New("诊断包导出未完成,请重新打开 Cage 后重试") |
| 184 | } |
| 185 | if response.Header.Get("Content-Type") != "application/zip" { |
| 186 | return errors.New("当前后台尚不支持诊断导出,请重启应用") |
| 187 | } |
| 188 | n, e := io.Copy(f, io.LimitReader(response.Body, (MaxDiagnosticBundle+1))) |
| 189 | if n > MaxDiagnosticBundle { |
| 190 | return errors.New("诊断包超过允许大小") |
| 191 | } |
| 192 | return e |
| 193 | } |
| 194 | err = export() |
| 195 | if err == nil { |
| 196 | err = addDesktopDiagnosticFile(f, profile) |
| 197 | } |
| 198 | if err == nil { |
| 199 | err = f.Sync() |
| 200 | } |
| 201 | err = errors.Join(err, f.Close()) |
| 202 | if err != nil { |
| 203 | return err |
| 204 | } |
| 205 | archive, err := zip.OpenReader(temp) |
| 206 | if err != nil { |
| 207 | return errors.New("诊断包未完整生成,请重新导出") |
| 208 | } |
| 209 | _ = archive.Close() |
| 210 | if agentLocal { |
| 211 | return os.Link(temp, destination) |
| 212 | } |
| 213 | |
| 214 | if st, e := os.Lstat(destination); e == nil && !st.Mode().IsRegular() { |
| 215 | return errors.New("请选择普通文件作为保存位置") |
| 216 | } |
| 217 | return os.Rename(temp, destination) |
| 218 | } |
| 219 | |
| 220 | |
| 221 | const MaxDiagnosticBundle int64 = 96 << 20 |
| 222 | |
| 223 | |
| 224 | type diagnosticResponse struct { |
| 225 | http.ResponseWriter |
| 226 | status int |
| 227 | } |
| 228 | |
| 229 | func (w *diagnosticResponse) Unwrap() http.ResponseWriter { return w.ResponseWriter } |
| 230 | func (w *diagnosticResponse) WriteHeader(status int) { |
| 231 | if w.status == 0 { |
| 232 | w.status = status |
| 233 | } |
| 234 | w.ResponseWriter.WriteHeader(status) |
| 235 | } |
| 236 | func (w *diagnosticResponse) Write(b []byte) (int, error) { |
| 237 | if w.status == 0 { |
| 238 | w.status = 200 |
| 239 | } |
| 240 | return w.ResponseWriter.Write(b) |
| 241 | } |
| 242 | func (w *diagnosticResponse) Flush() { _ = http.NewResponseController(w.ResponseWriter).Flush() } |
| 243 | func (w *diagnosticResponse) Hijack() (net.Conn, *bufio.ReadWriter, error) { |
| 244 | return http.NewResponseController(w.ResponseWriter).Hijack() |
| 245 | } |