gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2023 The Gitea Authors.
  2. // SPDX-License-Identifier: MIT
  3. package admin
  4. import (
  5. "archive/zip"
  6. "fmt"
  7. "runtime/pprof"
  8. "time"
  9. "code.gitea.io/gitea/modules/httplib"
  10. "code.gitea.io/gitea/modules/tailmsg"
  11. "code.gitea.io/gitea/modules/util"
  12. "code.gitea.io/gitea/services/context"
  13. )
  14. func MonitorDiagnosis(ctx *context.Context) {
  15. seconds := min(max(ctx.FormInt64("seconds"), 1), 300)
  16. httplib.ServeSetHeaders(ctx.Resp, &httplib.ServeHeaderOptions{
  17. ContentType: "application/zip",
  18. Disposition: "attachment",
  19. Filename: fmt.Sprintf("gitea-diagnosis-%s.zip", time.Now().Format("20060102-150405")),
  20. })
  21. zipWriter := zip.NewWriter(ctx.Resp)
  22. defer zipWriter.Close()
  23. f, err := zipWriter.CreateHeader(&zip.FileHeader{Name: "goroutine-before.txt", Method: zip.Deflate, Modified: time.Now()})
  24. if err != nil {
  25. ctx.ServerError("Failed to create zip file", err)
  26. return
  27. }
  28. _ = pprof.Lookup("goroutine").WriteTo(f, 1)
  29. f, err = zipWriter.CreateHeader(&zip.FileHeader{Name: "cpu-profile.dat", Method: zip.Deflate, Modified: time.Now()})
  30. if err != nil {
  31. ctx.ServerError("Failed to create zip file", err)
  32. return
  33. }
  34. err = pprof.StartCPUProfile(f)
  35. if err == nil {
  36. time.Sleep(time.Duration(seconds) * time.Second)
  37. pprof.StopCPUProfile()
  38. } else {
  39. _, _ = f.Write([]byte(err.Error()))
  40. }
  41. f, err = zipWriter.CreateHeader(&zip.FileHeader{Name: "goroutine-after.txt", Method: zip.Deflate, Modified: time.Now()})
  42. if err != nil {
  43. ctx.ServerError("Failed to create zip file", err)
  44. return
  45. }
  46. _ = pprof.Lookup("goroutine").WriteTo(f, 1)
  47. f, err = zipWriter.CreateHeader(&zip.FileHeader{Name: "heap.dat", Method: zip.Deflate, Modified: time.Now()})
  48. if err != nil {
  49. ctx.ServerError("Failed to create zip file", err)
  50. return
  51. }
  52. _ = pprof.Lookup("heap").WriteTo(f, 0)
  53. f, err = zipWriter.CreateHeader(&zip.FileHeader{Name: "perftrace.txt", Method: zip.Deflate, Modified: time.Now()})
  54. if err != nil {
  55. ctx.ServerError("Failed to create zip file", err)
  56. return
  57. }
  58. for _, record := range tailmsg.GetManager().GetTraceRecorder().GetRecords() {
  59. _, _ = f.Write(util.UnsafeStringToBytes(record.Time.Format(time.RFC3339)))
  60. _, _ = f.Write([]byte(" "))
  61. _, _ = f.Write(util.UnsafeStringToBytes((record.Content)))
  62. _, _ = f.Write([]byte("\n\n"))
  63. }
  64. }