diagnostics.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. package cmd
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "runtime/pprof"
  8. "runtime/trace"
  9. "strings"
  10. "github.com/zricethezav/gitleaks/v8/logging"
  11. )
  12. // DiagnosticsManager manages various types of diagnostics
  13. type DiagnosticsManager struct {
  14. Enabled bool
  15. DiagTypes []string
  16. OutputDir string
  17. cpuProfile *os.File
  18. memProfile string
  19. traceProfile *os.File
  20. }
  21. // NewDiagnosticsManager creates a new DiagnosticsManager instance
  22. func NewDiagnosticsManager(diagnosticsFlag string, diagnosticsDir string) (*DiagnosticsManager, error) {
  23. if diagnosticsFlag == "" {
  24. return &DiagnosticsManager{Enabled: false}, nil
  25. }
  26. dm := &DiagnosticsManager{
  27. Enabled: true,
  28. DiagTypes: strings.Split(diagnosticsFlag, ","),
  29. OutputDir: diagnosticsDir,
  30. }
  31. // If no output directory is specified, use the current directory
  32. if dm.OutputDir == "" {
  33. var err error
  34. dm.OutputDir, err = os.Getwd()
  35. if err != nil {
  36. return nil, fmt.Errorf("failed to get current directory: %w", err)
  37. }
  38. logging.Debug().Msgf("No diagnostics directory specified, using current directory: %s", dm.OutputDir)
  39. }
  40. // Create the output directory if it doesn't exist
  41. if err := os.MkdirAll(dm.OutputDir, 0755); err != nil {
  42. return nil, fmt.Errorf("failed to create diagnostics directory: %w", err)
  43. }
  44. // Make sure the output directory is absolute
  45. if !filepath.IsAbs(dm.OutputDir) {
  46. absPath, err := filepath.Abs(dm.OutputDir)
  47. if err != nil {
  48. return nil, fmt.Errorf("failed to get absolute path for diagnostics directory: %w", err)
  49. }
  50. dm.OutputDir = absPath
  51. }
  52. logging.Debug().Msgf("Diagnostics enabled: %s", strings.Join(dm.DiagTypes, ","))
  53. logging.Debug().Msgf("Diagnostics output directory: %s", dm.OutputDir)
  54. return dm, nil
  55. }
  56. // StartDiagnostics starts all enabled diagnostics
  57. func (dm *DiagnosticsManager) StartDiagnostics() error {
  58. if !dm.Enabled {
  59. return nil
  60. }
  61. var err error
  62. for _, diagType := range dm.DiagTypes {
  63. diagType = strings.TrimSpace(diagType)
  64. switch diagType {
  65. case "cpu":
  66. if err = dm.StartCPUProfile(); err != nil {
  67. return err
  68. }
  69. case "mem":
  70. if err = dm.SetupMemoryProfile(); err != nil {
  71. return err
  72. }
  73. case "trace":
  74. if err = dm.StartTraceProfile(); err != nil {
  75. return err
  76. }
  77. default:
  78. logging.Warn().Msgf("Unknown diagnostics type: %s", diagType)
  79. }
  80. }
  81. return nil
  82. }
  83. // StopDiagnostics stops all started diagnostics
  84. func (dm *DiagnosticsManager) StopDiagnostics() {
  85. if !dm.Enabled {
  86. return
  87. }
  88. logging.Debug().Msg("Stopping diagnostics and writing profiling data...")
  89. for _, diagType := range dm.DiagTypes {
  90. diagType = strings.TrimSpace(diagType)
  91. switch diagType {
  92. case "cpu":
  93. dm.StopCPUProfile()
  94. case "mem":
  95. dm.WriteMemoryProfile()
  96. case "trace":
  97. dm.StopTraceProfile()
  98. }
  99. }
  100. }
  101. // StartCPUProfile starts CPU profiling
  102. func (dm *DiagnosticsManager) StartCPUProfile() error {
  103. cpuProfilePath := filepath.Join(dm.OutputDir, "cpu.pprof")
  104. f, err := os.Create(cpuProfilePath)
  105. if err != nil {
  106. return fmt.Errorf("could not create CPU profile at %s: %w", cpuProfilePath, err)
  107. }
  108. if err := pprof.StartCPUProfile(f); err != nil {
  109. f.Close()
  110. return fmt.Errorf("could not start CPU profile: %w", err)
  111. }
  112. dm.cpuProfile = f
  113. return nil
  114. }
  115. // StopCPUProfile stops CPU profiling
  116. func (dm *DiagnosticsManager) StopCPUProfile() {
  117. if dm.cpuProfile != nil {
  118. pprof.StopCPUProfile()
  119. if err := dm.cpuProfile.Close(); err != nil {
  120. logging.Error().Err(err).Msg("Error closing CPU profile file")
  121. }
  122. logging.Info().Msgf("CPU profile written to: %s", dm.cpuProfile.Name())
  123. dm.cpuProfile = nil
  124. }
  125. }
  126. // SetupMemoryProfile sets up memory profiling to be written when StopDiagnostics is called
  127. func (dm *DiagnosticsManager) SetupMemoryProfile() error {
  128. memProfilePath := filepath.Join(dm.OutputDir, "mem.pprof")
  129. dm.memProfile = memProfilePath
  130. return nil
  131. }
  132. // WriteMemoryProfile writes the memory profile to disk
  133. func (dm *DiagnosticsManager) WriteMemoryProfile() {
  134. if dm.memProfile == "" {
  135. return
  136. }
  137. f, err := os.Create(dm.memProfile)
  138. if err != nil {
  139. logging.Error().Err(err).Msgf("Could not create memory profile at %s", dm.memProfile)
  140. return
  141. }
  142. // Get memory profile
  143. runtime.GC() // Run GC before taking the memory profile
  144. if err := pprof.WriteHeapProfile(f); err != nil {
  145. logging.Error().Err(err).Msg("Could not write memory profile")
  146. } else {
  147. logging.Info().Msgf("Memory profile written to: %s", dm.memProfile)
  148. }
  149. if err := f.Close(); err != nil {
  150. logging.Error().Err(err).Msg("Error closing memory profile file")
  151. }
  152. dm.memProfile = ""
  153. }
  154. // StartTraceProfile starts execution tracing
  155. func (dm *DiagnosticsManager) StartTraceProfile() error {
  156. traceProfilePath := filepath.Join(dm.OutputDir, "trace.out")
  157. f, err := os.Create(traceProfilePath)
  158. if err != nil {
  159. return fmt.Errorf("could not create trace profile at %s: %w", traceProfilePath, err)
  160. }
  161. if err := trace.Start(f); err != nil {
  162. f.Close()
  163. return fmt.Errorf("could not start trace profile: %w", err)
  164. }
  165. dm.traceProfile = f
  166. return nil
  167. }
  168. // StopTraceProfile stops execution tracing
  169. func (dm *DiagnosticsManager) StopTraceProfile() {
  170. if dm.traceProfile != nil {
  171. trace.Stop()
  172. if err := dm.traceProfile.Close(); err != nil {
  173. logging.Error().Err(err).Msg("Error closing trace profile file")
  174. }
  175. logging.Info().Msgf("Trace profile written to: %s", dm.traceProfile.Name())
  176. dm.traceProfile = nil
  177. }
  178. }