(memoryThreshold uint64)
| 53 | } |
| 54 | |
| 55 | func (mm *MemoryMonitor) checkMemory(memoryThreshold uint64) { |
| 56 | // memoryThreshold == 0 means no need to monitor |
| 57 | if memoryThreshold == 0 { |
| 58 | return |
| 59 | } |
| 60 | var m runtime.MemStats |
| 61 | runtime.ReadMemStats(&m) |
| 62 | |
| 63 | if m.Sys >= memoryThreshold { |
| 64 | now := time.Now().Unix() |
| 65 | |
| 66 | // Dump heap profile |
| 67 | heapFileName := filepath.Join(mm.profile.DataDir, fmt.Sprintf("memory_dump_%d.prof", now)) |
| 68 | slog.Info("memory monitor: memory allocated exceeds memory threshold. will dump pprof memory and goroutine profile", "memoryUsage", m.Sys, "memoryThreshold", memoryThreshold) |
| 69 | slog.Info("memory monitor: dumping pprof memory profile", "fileName", heapFileName) |
| 70 | |
| 71 | if err := dumpHeapProfile(heapFileName); err != nil { |
| 72 | slog.Info("memory monitor: could not dump memory profile", "fileName", heapFileName, log.BBError(err)) |
| 73 | // Continue to attempt goroutine dump even if heap dump fails |
| 74 | } else { |
| 75 | if err := retainMostRecentFiles(mm.profile.DataDir, profileRetention); err != nil { |
| 76 | slog.Info("memory monitor: failed to cleanup old dump files after heap dump", log.BBError(err)) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | // Dump goroutine profile |
| 81 | goroutineFileName := filepath.Join(mm.profile.DataDir, fmt.Sprintf("goroutine_dump_%d.prof", now)) |
| 82 | slog.Info("memory monitor: dumping pprof goroutine profile", "fileName", goroutineFileName) |
| 83 | |
| 84 | if err := dumpGoroutineProfile(goroutineFileName); err != nil { |
| 85 | slog.Info("memory monitor: could not dump goroutine profile", "fileName", goroutineFileName, log.BBError(err)) |
| 86 | } else { |
| 87 | if err := retainMostRecentFiles(mm.profile.DataDir, profileRetention); err != nil { |
| 88 | slog.Info("memory monitor: failed to cleanup old dump files after goroutine dump", log.BBError(err)) |
| 89 | } |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | func retainMostRecentFiles(dir string, retainCount int) error { |
| 95 | // Handle memory dumps |
no test coverage detected